-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsession.rs
More file actions
1987 lines (1762 loc) · 71.9 KB
/
session.rs
File metadata and controls
1987 lines (1762 loc) · 71.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
//! Session runner - manages the lifecycle of a conversation session.
//!
//! This module provides the core session management that connects
//! the TUI/CLI to the agent loop.
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use async_channel::{Receiver, Sender, unbounded};
use chrono::Utc;
use tokio_stream::StreamExt;
use tracing::{info, warn};
use cortex_protocol::{
AgentMessageDeltaEvent, AgentMessageEvent, ConversationId, ErrorEvent, Event, EventMsg,
ExecApprovalRequestEvent, ExecCommandBeginEvent, ExecCommandEndEvent,
ExecCommandOutputDeltaEvent, ExecCommandSource, ExecOutputStream, Op, ParsedCommand,
SessionConfiguredEvent, Submission, TaskCompleteEvent, TaskStartedEvent, TokenCountEvent,
TokenUsage, TokenUsageInfo, UserMessageEvent,
};
use crate::client::types::MessageContent;
use crate::client::{
CompletionRequest, Message, MessageRole, ModelClient, ResponseEvent, ToolCall,
ToolDefinition as ClientToolDefinition, create_client,
};
use crate::config::Config;
use crate::error::{CortexError, Result};
use crate::rollout::reader::{RolloutItem, get_events, get_session_meta};
use crate::rollout::recorder::SessionMeta;
use crate::rollout::{RolloutRecorder, SESSIONS_SUBDIR, get_rollout_path, read_rollout};
use crate::skills::{render_skills_section, try_get_skills_manager};
use crate::summarization::SummarizationStrategy;
use crate::tools::context::ToolOutputChunk;
use crate::tools::{ToolContext, ToolRouter};
/// Simple token counter for session context tracking.
/// Uses approximation-based counting (4 chars per token).
pub struct TokenCounter;
impl Default for TokenCounter {
fn default() -> Self {
Self::new()
}
}
impl TokenCounter {
/// Create a new token counter.
pub fn new() -> Self {
Self
}
/// Count tokens in messages (approximate).
pub async fn count_messages(&self, _model: &str, messages: &[Message]) -> Result<usize> {
let mut total = 0usize;
for msg in messages {
// Base overhead per message (~4 tokens)
total += 4;
// Count content tokens
let text = match &msg.content {
MessageContent::Text(t) => t.len(),
MessageContent::Parts(parts) => parts
.iter()
.map(|p| match p {
crate::client::types::ContentPart::Text { text, .. } => text.len(),
_ => 85, // Image tokens approximation
})
.sum(),
MessageContent::ToolResult { content, .. } => content.len(),
MessageContent::ToolCalls(calls) => {
calls.iter().map(|c| c.name.len() + c.arguments.len()).sum()
}
};
// Approximate: 4 chars per token
total += (text as f64 / 4.0).ceil() as usize;
}
// Message separator overhead
total += messages.len() * 3;
Ok(total)
}
/// Count tokens in tool definitions (approximate).
pub async fn count_tools(&self, _model: &str, tools: &[ClientToolDefinition]) -> Result<usize> {
let mut total = 0usize;
for tool in tools {
let json = serde_json::to_string(tool).unwrap_or_default();
// Approximate: 4 chars per token + 10 overhead
total += (json.len() as f64 / 4.0).ceil() as usize + 10;
}
// Base overhead for having tools
if !tools.is_empty() {
total += 9;
}
Ok(total)
}
}
/// A running session that handles conversation with the model.
pub struct Session {
/// Session configuration.
config: Config,
/// Conversation ID.
conversation_id: ConversationId,
/// Model client.
client: Box<dyn ModelClient>,
/// Tool router.
tool_router: ToolRouter,
/// Conversation messages.
messages: Vec<Message>,
/// Submission receiver (from UI).
submission_rx: Receiver<Submission>,
/// Event sender (to UI).
event_tx: Sender<Event>,
/// Current turn ID.
turn_id: u64,
/// Token usage tracking.
total_usage: TokenUsage,
/// Token counter for precise context window tracking.
token_counter: Arc<TokenCounter>,
/// Whether session is running.
running: bool,
/// Current agent profile.
pub current_agent_profile: Option<crate::agent::AgentProfile>,
/// Rollout recorder for persistence.
recorder: Option<RolloutRecorder>,
/// Pending approval requests (call_id -> (tool_call, args)).
pending_approvals: std::collections::HashMap<String, PendingToolCall>,
/// Cancellation flag for interrupting current request.
cancelled: Arc<AtomicBool>,
/// Snapshot manager for undo/redo.
snapshot_manager: Arc<crate::tasks::snapshot::SnapshotManager>,
/// Undo history.
undo_history: crate::tasks::undo::UndoHistory,
/// Redo history.
redo_history: crate::tasks::undo::RedoHistory,
/// Current turn's undo actions.
current_undo_actions: Vec<crate::tasks::undo::UndoAction>,
/// Share service for generating public URLs.
share_service: crate::share_service::ShareService,
/// LSP integration.
lsp: Arc<crate::integrations::LspIntegration>,
}
/// A tool call waiting for approval.
#[derive(Debug, Clone)]
struct PendingToolCall {
tool_name: String,
arguments: serde_json::Value,
tool_call_id: String,
}
/// Handle for interacting with a session.
#[derive(Clone)]
pub struct SessionHandle {
/// Submission sender.
pub submission_tx: Sender<Submission>,
/// Event receiver.
pub event_rx: Receiver<Event>,
/// Conversation ID.
pub conversation_id: ConversationId,
/// Cancellation flag.
pub cancelled: Arc<AtomicBool>,
}
impl Session {
/// Create a new session with channels.
pub fn new(config: Config) -> Result<(Self, SessionHandle)> {
let (submission_tx, submission_rx) = unbounded();
let (event_tx, event_rx) = unbounded();
let conversation_id = ConversationId::new();
let cancelled = Arc::new(AtomicBool::new(false));
// Get API key from environment or config
let api_key = std::env::var("OPENAI_API_KEY")
.or_else(|_| std::env::var("ANTHROPIC_API_KEY"))
.or_else(|_| std::env::var("OPENROUTER_API_KEY"))
.unwrap_or_default();
let client = create_client(
&config.model_provider_id,
&config.model,
&api_key,
Some(config.model_provider.base_url.as_str()),
)?;
let mut tool_router = ToolRouter::new();
// Initialize rollout recorder
let mut recorder = RolloutRecorder::new(&config.cortex_home, conversation_id)?;
recorder.init()?;
// Record session metadata
let meta = SessionMeta {
id: conversation_id,
parent_id: None,
fork_point: None,
timestamp: Utc::now().to_rfc3339(),
cwd: config.cwd.clone(),
model: config.model.clone(),
cli_version: env!("CARGO_PKG_VERSION").to_string(),
instructions: config.user_instructions.clone(),
};
recorder.record_meta(&meta)?;
// Initialize with system prompt (including skills if available)
let skills_section = load_skills_section(&config.cwd);
let mut messages = Vec::new();
messages.push(Message::system(build_system_prompt_with_skills(
&config,
skills_section.as_deref(),
)));
// Load current agent profile if set
let current_agent_profile = if let Some(agent_name) = &config.current_agent {
let profiles = crate::agent::AgentProfile::load_all().unwrap_or_default();
profiles.get(agent_name).cloned()
} else {
None
};
// Initialize snapshot manager
let snapshot_dir = config
.cortex_home
.join("snapshots")
.join(conversation_id.to_string());
let snapshot_manager =
Arc::new(crate::tasks::snapshot::SnapshotManager::new(50).with_storage(snapshot_dir));
// Initialize LSP integration
let lsp = Arc::new(crate::integrations::LspIntegration::new(true));
let lsp_clone = lsp.clone();
let cwd_clone = config.cwd.clone();
tokio::spawn(async move {
if let Err(e) = lsp_clone.init(&cwd_clone).await {
warn!("Failed to initialize LSP in session: {}", e);
}
});
tool_router.set_lsp(lsp.clone());
let session = Self {
config,
conversation_id,
client,
tool_router,
messages,
submission_rx,
event_tx,
turn_id: 0,
total_usage: TokenUsage::default(),
token_counter: Arc::new(TokenCounter),
running: true,
current_agent_profile,
recorder: Some(recorder),
pending_approvals: std::collections::HashMap::new(),
cancelled: cancelled.clone(),
snapshot_manager,
undo_history: crate::tasks::undo::UndoHistory::new(50),
redo_history: crate::tasks::undo::RedoHistory::new(50),
current_undo_actions: Vec::new(),
share_service: crate::share_service::ShareService::new(),
lsp,
};
let handle = SessionHandle {
submission_tx,
event_rx,
conversation_id: session.conversation_id,
cancelled,
};
Ok((session, handle))
}
/// Run the session loop.
pub async fn run(&mut self) -> Result<()> {
// Emit session configured event
self.emit(EventMsg::SessionConfigured(Box::new(
SessionConfiguredEvent {
session_id: self.conversation_id,
parent_session_id: None,
model: self.config.model.clone(),
model_provider_id: self.config.model_provider_id.clone(),
approval_policy: self.config.approval_policy,
sandbox_policy: self.config.sandbox_policy.clone(),
cwd: self.config.cwd.clone(),
reasoning_effort: None,
history_log_id: 0,
history_entry_count: 0,
initial_messages: None,
rollout_path: PathBuf::new(),
},
)))
.await;
while self.running {
// Check cancellation flag periodically using a timeout
let submission = tokio::select! {
result = self.submission_rx.recv() => {
match result {
Ok(s) => s,
Err(_) => break,
}
}
_ = tokio::time::sleep(std::time::Duration::from_millis(100)) => {
// Check if we should exit due to cancellation
if self.cancelled.load(Ordering::SeqCst) {
tracing::info!("Session detected cancellation, exiting run loop");
self.running = false;
break;
}
continue;
}
};
if let Err(e) = self.handle_submission(submission).await {
self.emit(EventMsg::Error(ErrorEvent {
message: e.to_string(),
cortex_error_info: None,
}))
.await;
}
}
Ok(())
}
async fn handle_submission(&mut self, submission: Submission) -> Result<()> {
match submission.op {
Op::Shutdown => {
self.running = false;
self.emit(EventMsg::ShutdownComplete).await;
}
Op::Interrupt => {
// Set cancellation flag to stop current request
self.cancelled.store(true, Ordering::SeqCst);
self.emit(EventMsg::TurnAborted(cortex_protocol::TurnAbortedEvent {
reason: cortex_protocol::TurnAbortReason::Interrupted,
}))
.await;
}
Op::UserInput { items } => {
self.handle_user_input(&submission.id, items).await?;
}
Op::UserTurn { items, .. } => {
self.handle_user_input(&submission.id, items).await?;
}
Op::Compact => {
self.handle_compact().await?;
}
Op::Undo => {
self.handle_undo().await?;
}
Op::Redo => {
self.handle_redo().await?;
}
Op::ForkSession {
fork_point_message_id,
message_index,
} => {
self.handle_fork_session(fork_point_message_id, message_index)
.await?;
}
Op::ExecApproval { id, decision } => {
self.handle_exec_approval(&id, decision).await?;
}
Op::OverrideTurnContext {
cwd,
approval_policy,
sandbox_policy,
model,
effort,
summary,
} => {
if let Some(cwd) = cwd {
info!("Updating session CWD to: {:?}", cwd);
self.config.cwd = cwd;
}
if let Some(policy) = approval_policy {
self.config.approval_policy = policy;
}
if let Some(policy) = sandbox_policy {
self.config.sandbox_policy = policy;
}
if let Some(model) = model {
self.config.model = model;
}
if let Some(effort) = effort {
self.config.reasoning_effort = effort.map(|e| match e {
cortex_protocol::ReasoningEffort::Low => {
crate::config::ReasoningEffort::Low
}
cortex_protocol::ReasoningEffort::Medium => {
crate::config::ReasoningEffort::Medium
}
cortex_protocol::ReasoningEffort::High => {
crate::config::ReasoningEffort::High
}
});
}
if let Some(summary) = summary {
self.config.reasoning_summary = match summary {
cortex_protocol::ReasoningSummary::None => {
crate::config::ReasoningSummary::None
}
cortex_protocol::ReasoningSummary::Brief => {
crate::config::ReasoningSummary::Brief
}
cortex_protocol::ReasoningSummary::Detailed => {
crate::config::ReasoningSummary::Detailed
}
cortex_protocol::ReasoningSummary::Auto => {
crate::config::ReasoningSummary::Auto
}
};
}
}
Op::SwitchAgent { name } => {
info!("Switching agent to: {}", name);
self.config.current_agent = Some(name.clone());
// Load and set the agent profile
let profiles = crate::agent::AgentProfile::load_all().unwrap_or_default();
self.current_agent_profile = profiles.get(&name).cloned();
// Update system prompt in existing message history
if let Some(msg) = self.messages.first_mut()
&& matches!(msg.role, crate::client::MessageRole::System)
{
*msg = Message::system(build_system_prompt(&self.config));
}
}
Op::Share => {
let url = self
.share_service
.share(&self.conversation_id.to_string(), &self.messages)
.await?;
self.emit(EventMsg::SessionShared(
cortex_protocol::SessionSharedEvent { url },
))
.await;
}
Op::Unshare => {
self.share_service
.unshare(&self.conversation_id.to_string())
.await?;
self.emit(EventMsg::SessionUnshared(
cortex_protocol::SessionUnsharedEvent { success: true },
))
.await;
}
Op::ReloadMcpServers => {
info!("Reloading MCP servers...");
}
Op::EnableMcpServer { name } => {
info!("Enabling MCP server: {}...", name);
}
Op::DisableMcpServer { name } => {
info!("Disabling MCP server: {}...", name);
}
_ => {}
}
Ok(())
}
async fn handle_user_input(
&mut self,
_submission_id: &str,
items: Vec<cortex_protocol::UserInput>,
) -> Result<()> {
tracing::info!("Session handling user input: {} items", items.len());
// Reset cancellation flag at start of each turn
self.cancelled.store(false, Ordering::SeqCst);
self.turn_id += 1;
let turn_id = self.turn_id.to_string();
// Extract text from user input
let user_text: String = items
.iter()
.filter_map(|item| {
if let cortex_protocol::UserInput::Text { text } = item {
Some(text.clone())
} else {
None
}
})
.collect::<Vec<_>>()
.join("\n");
if user_text.is_empty() {
tracing::warn!("Session received empty user input");
return Ok(());
}
tracing::debug!("User message: {}", user_text);
// Track messages for redo
let _msg_start_idx = self.messages.len();
// Emit user message event
self.emit(EventMsg::UserMessage(UserMessageEvent {
id: None,
parent_id: None,
message: user_text.clone(),
images: None,
}))
.await;
// Add user message to history
self.messages.push(Message::user(&user_text));
// Emit task started
self.emit(EventMsg::TaskStarted(TaskStartedEvent {
model_context_window: self.config.model_context_window,
}))
.await;
// Fast git-based snapshot (uses git write-tree, instant)
// Only track if the cwd is a git repository (has .git directory)
let is_git_repo = self.config.cwd.join(".git").exists()
|| std::process::Command::new("git")
.args(["rev-parse", "--is-inside-work-tree"])
.current_dir(&self.config.cwd)
.output()
.map(|o| o.status.success())
.unwrap_or(false);
let pre_snapshot_hash = if is_git_repo {
match crate::git_snapshot::GitSnapshot::new(
&self.config.cortex_home,
&self.conversation_id.to_string(),
self.config.cwd.clone(),
) {
Ok(gs) => gs.track().ok(),
Err(e) => {
tracing::warn!("Failed to create git snapshot: {}", e);
None
}
}
} else {
tracing::debug!("Skipping snapshot - cwd is not a git repository");
None
};
// Run the agent loop until complete
tracing::info!("Starting agent loop for turn {}...", turn_id);
if let Err(e) = self.run_agent_loop(&turn_id).await {
tracing::error!("Agent loop failed: {}", e);
// Emit error event so TUI can display it
self.emit(EventMsg::Error(ErrorEvent {
message: e.to_string(),
cortex_error_info: None,
}))
.await;
// Emit TaskComplete to reset TUI state
self.emit(EventMsg::TaskComplete(TaskCompleteEvent {
last_agent_message: None,
}))
.await;
return Err(e);
}
tracing::info!("Agent loop completed for turn {}", turn_id);
// Fast git-based diff (if we have a pre-snapshot)
if let Some(hash) = pre_snapshot_hash
&& let Ok(gs) = crate::git_snapshot::GitSnapshot::new(
&self.config.cortex_home,
&self.conversation_id.to_string(),
self.config.cwd.clone(),
)
{
// Get diff for display
if let Ok(diff_text) = gs.diff(&hash)
&& !diff_text.is_empty()
{
use cortex_protocol::TurnDiffEvent;
self.emit(EventMsg::TurnDiff(TurnDiffEvent {
unified_diff: diff_text,
}))
.await;
}
}
// Create undo task
let undo_task = crate::tasks::undo::UndoTask::new(
format!("undo_{turn_id}"),
crate::tasks::undo::UndoTarget::Turn(turn_id.clone()),
);
self.undo_history.push(undo_task);
Ok(())
}
async fn handle_compact(&mut self) -> Result<()> {
let strategy = SummarizationStrategy::default();
let (to_summarize, to_keep) = strategy.split_messages(&self.messages);
if to_summarize.is_empty() {
return Ok(());
}
// Build summarization prompt
let prompt = strategy.build_summarization_prompt(&to_summarize);
// Call model to summarize
let request = CompletionRequest {
model: "gpt-4o-mini".to_string(), // Use a cheaper model for summarization
messages: prompt,
max_tokens: Some(strategy.target_summary_tokens as u32),
temperature: Some(0.3),
..Default::default()
};
let mut stream = self.client.complete(request).await?;
let mut summary = String::new();
while let Some(event) = stream.next().await {
if let ResponseEvent::Delta(delta) = event? {
summary.push_str(&delta);
}
}
// Replace messages
let mut new_messages = Vec::new();
if strategy.preserve_system
&& !self.messages.is_empty()
&& self.messages[0].role == MessageRole::System
{
new_messages.push(self.messages[0].clone());
}
new_messages.push(Message::system(format!(
"[Conversation Summary]\n\n{}",
summary
)));
new_messages.extend(to_keep);
self.messages = new_messages;
// Emit event or log
tracing::info!("Context compacted using summarization strategy");
Ok(())
}
/// Capture a snapshot of the current workspace.
async fn capture_snapshot(
&self,
description: &str,
) -> Result<crate::tasks::snapshot::Snapshot> {
let mut snapshot = self.snapshot_manager.create(description).await;
snapshot.turn_id = Some(self.turn_id.to_string());
// Walk workspace and capture files
// For performance, we only capture files that are likely to be changed
// or we could use a more sophisticated approach.
// For now, let's capture everything in CWD except ignored patterns.
let mut it = walkdir::WalkDir::new(&self.config.cwd).into_iter();
loop {
// Check for cancellation periodically
if self.cancelled.load(Ordering::SeqCst) {
tracing::info!("Snapshot capture cancelled by user");
return Err(CortexError::Cancelled);
}
let entry = match it.next() {
None => break,
Some(Err(_)) => continue,
Some(Ok(e)) => e,
};
let path = entry.path();
if path.is_dir() {
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if name == ".git"
|| name == "target"
|| name == "node_modules"
|| name == ".factory"
{
it.skip_current_dir();
}
continue;
}
// Skip large files or binary files if needed
// For now, just capture
if let Err(e) = snapshot.capture_file(path) {
tracing::warn!("Failed to capture file {}: {}", path.display(), e);
}
}
Ok(snapshot)
}
async fn run_agent_loop(&mut self, _turn_id: &str) -> Result<()> {
let max_iterations = 200;
let mut iteration = 0;
loop {
// Check for cancellation
if self.cancelled.load(Ordering::SeqCst) {
tracing::info!("Agent loop cancelled by user");
break;
}
iteration += 1;
if iteration > max_iterations {
self.emit(EventMsg::Error(ErrorEvent {
message: "Maximum iterations reached".to_string(),
cortex_error_info: None,
}))
.await;
break;
}
// Build completion request
let tool_defs = self.tool_router.get_tool_definitions();
// Calculate precise context tokens
let client_tools: Vec<ClientToolDefinition> = tool_defs
.iter()
.map(|t| {
ClientToolDefinition::function(&t.name, &t.description, t.parameters.clone())
})
.collect();
let context_tokens = self
.token_counter
.count_messages(&self.config.model, &self.messages)
.await
.unwrap_or(0);
let tools_tokens = self
.token_counter
.count_tools(&self.config.model, &client_tools)
.await
.unwrap_or(0);
let total_context_tokens = context_tokens + tools_tokens;
// Emit token count event before starting request
self.emit(EventMsg::TokenCount(TokenCountEvent {
info: Some(TokenUsageInfo {
total_token_usage: self.total_usage.clone(),
last_token_usage: TokenUsage::default(),
model_context_window: self.config.model_context_window,
context_tokens: total_context_tokens as i64,
}),
rate_limits: None,
}))
.await;
let tools = client_tools;
let request = CompletionRequest {
model: self.config.model.clone(),
messages: self.messages.clone(),
max_tokens: Some(4096),
temperature: Some(0.7),
tools,
stream: true,
};
// Get streaming response
let mut stream = self.client.complete(request).await?;
let mut full_content = String::new();
let mut tool_calls: Vec<ToolCall> = Vec::new();
// Process stream
while let Some(event) = stream.next().await {
// Check for cancellation during streaming
if self.cancelled.load(Ordering::SeqCst) {
tracing::info!("Stream processing cancelled by user");
return Ok(());
}
match event? {
ResponseEvent::Delta(delta) => {
full_content.push_str(&delta);
self.emit(EventMsg::AgentMessageDelta(AgentMessageDeltaEvent {
delta,
}))
.await;
}
ResponseEvent::ToolCall(tc) => {
tracing::info!("Session received tool call: {} (id: {})", tc.name, tc.id);
tool_calls.push(ToolCall {
id: tc.id,
call_type: "function".to_string(),
function: crate::client::FunctionCall {
name: tc.name,
arguments: tc.arguments,
},
});
}
ResponseEvent::Done(response) => {
// Update token usage
self.total_usage.input_tokens += response.usage.input_tokens;
self.total_usage.output_tokens += response.usage.output_tokens;
self.total_usage.total_tokens += response.usage.total_tokens;
self.emit(EventMsg::TokenCount(TokenCountEvent {
info: Some(TokenUsageInfo {
total_token_usage: self.total_usage.clone(),
last_token_usage: TokenUsage {
input_tokens: response.usage.input_tokens,
output_tokens: response.usage.output_tokens,
total_tokens: response.usage.total_tokens,
..Default::default()
},
model_context_window: self.config.model_context_window,
context_tokens: response.usage.input_tokens
+ response.usage.output_tokens,
}),
rate_limits: None,
}))
.await;
}
ResponseEvent::Error(e) => {
self.emit(EventMsg::Error(ErrorEvent {
message: e,
cortex_error_info: None,
}))
.await;
return Ok(());
}
_ => {}
}
}
// Emit full message if we have content
if !full_content.is_empty() {
self.emit(EventMsg::AgentMessage(AgentMessageEvent {
id: None,
parent_id: None,
message: full_content.clone(),
}))
.await;
}
// Add assistant message to history
let mut assistant_msg = Message::assistant(&full_content);
if !tool_calls.is_empty() {
assistant_msg.tool_calls = Some(tool_calls.clone());
}
self.messages.push(assistant_msg);
// If no tool calls, we're done
if tool_calls.is_empty() {
break;
}
// Execute tool calls
tracing::info!("Processing {} tool calls", tool_calls.len());
for tool_call in tool_calls {
// Check for cancellation before each tool
if self.cancelled.load(Ordering::SeqCst) {
tracing::info!("Tool execution cancelled by user");
return Ok(());
}
let tool_name = &tool_call.function.name;
tracing::info!("Processing tool call: {} (id: {})", tool_name, tool_call.id);
let args: serde_json::Value = serde_json::from_str(&tool_call.function.arguments)
.unwrap_or(serde_json::Value::Null);
// Check agent permissions first
// Use a local boolean to avoid borrowing self mutably later
let mut agent_denied = false;
if let Some(profile) = &self.current_agent_profile
&& let crate::agent::ToolPermission::Deny = profile.can_use_tool(tool_name)
{
agent_denied = true;
}
if agent_denied {
let profile_name = self
.current_agent_profile
.as_ref()
.map(|p| p.name.clone())
.unwrap_or_default();
tracing::warn!(
"Agent '{}' denied access to tool '{}'",
profile_name,
tool_name
);
self.emit(EventMsg::Error(ErrorEvent {
message: format!(
"Agent '{}' is not allowed to use tool '{}'.",
profile_name, tool_name
),
cortex_error_info: None,
}))
.await;
// Add rejection message as tool result
self.messages.push(Message::tool_result(
&tool_call.id,
format!(
"Permission denied: Agent '{}' is not allowed to use tool '{}'.",
profile_name, tool_name
),
));
continue;
}
// Check if approval is needed for shell commands
let needs_approval = if tool_name == "Execute" {
if let Some(cmd_array) = args.get("command").and_then(|c| c.as_array()) {
let cmd: Vec<String> = cmd_array
.iter()
.filter_map(|v| v.as_str().map(std::string::ToString::to_string))
.collect();
let analysis = crate::safety::analyze_command(&cmd, &self.config.cwd);
let requires = crate::safety::requires_approval(
&analysis,
&self.config.approval_policy,
);
if requires {
// Emit approval request
self.emit(EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent {
call_id: tool_call.id.clone(),
turn_id: self.turn_id.to_string(),
command: cmd.clone(),
cwd: self.config.cwd.clone(),
sandbox_assessment: None,
}))
.await;
true
} else {
false
}
} else {
false
}
} else {
false
};
// If approval needed, store pending and wait for user response
tracing::info!("needs_approval for {}: {}", tool_name, needs_approval);
if needs_approval {
tracing::info!("Tool {} requires approval, storing pending", tool_name);
self.pending_approvals.insert(
tool_call.id.clone(),
PendingToolCall {
tool_name: tool_name.clone(),
arguments: args,
tool_call_id: tool_call.id.clone(),
},
);
// Return early - we'll continue when approval comes
return Ok(());
}
tracing::info!("Tool {} does NOT require approval, executing", tool_name);
// Handle PatchApply events
if tool_name == "ApplyPatch"
&& let Some(patch) = args.get("patch").and_then(|p| p.as_str())
&& let Ok(file_changes) =
crate::tools::handlers::apply_patch::parse_unified_diff(patch)
{
let mut protocol_changes = std::collections::HashMap::new();
for change in file_changes {
if let Some(path) = change.new_path.or(change.old_path) {
let protocol_change = if change.is_new_file {
cortex_protocol::FileChange::Add {
content: String::new(),
}
} else if change.is_deleted {
cortex_protocol::FileChange::Delete {
content: String::new(),
}
} else {
cortex_protocol::FileChange::Update {
unified_diff: String::new(),
move_path: None,
}
};
protocol_changes.insert(path, protocol_change);
}
}
self.emit(EventMsg::PatchApplyBegin(
cortex_protocol::PatchApplyBeginEvent {
call_id: tool_call.id.clone(),
turn_id: self.turn_id.to_string(),
auto_approved: true,
changes: protocol_changes,
},
))
.await;
}