-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathexec.rs
More file actions
1537 lines (1361 loc) · 58.6 KB
/
exec.rs
File metadata and controls
1537 lines (1361 loc) · 58.6 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
//! Tool execution engine
//!
//! Executes tool pipelines with approval flow and streaming output.
#![allow(dead_code)]
use std::collections::{HashMap, HashSet, VecDeque};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use crate::effect::EffectResult;
use crate::llm::AgentId;
use crate::transcript::Status;
use crate::tools::pipeline::{Effect, Step, ToolPipeline};
use crate::tools::ToolRegistry;
// =============================================================================
// Polling helpers
// =============================================================================
/// Noop waker for manual polling
struct NoopWaker;
impl Wake for NoopWaker {
fn wake(self: Arc<Self>) {}
}
/// Poll a oneshot receiver without blocking
fn poll_receiver<T>(rx: &mut oneshot::Receiver<T>) -> Poll<Result<T, oneshot::error::RecvError>> {
let waker = Waker::from(Arc::new(NoopWaker));
let mut cx = Context::from_waker(&waker);
Pin::new(rx).poll(&mut cx)
}
// =============================================================================
// Types
// =============================================================================
/// What an active pipeline is waiting for (mutually exclusive states)
enum WaitingFor {
/// Not waiting - ready to execute next step
Nothing,
/// Waiting for a handler to complete (spawned in separate task).
/// The JoinHandle is kept so we can abort the task on cancellation.
Handler(oneshot::Receiver<Step>, JoinHandle<()>),
/// Waiting for delegated effect to complete
Effect(oneshot::Receiver<EffectResult>),
/// Waiting for user approval (Ok = approved, Err = denied)
Approval(oneshot::Receiver<EffectResult>),
}
/// A tool call pending execution
#[derive(Debug, Clone)]
pub struct ToolCall {
pub agent_id: AgentId,
pub call_id: String,
pub name: String,
pub params: serde_json::Value,
pub decision: ToolDecision,
/// If true, execute in background and return immediately
pub background: bool,
}
impl ToolCall {
pub fn with_agent_id(mut self, agent_id: AgentId) -> Self {
self.agent_id = agent_id;
self
}
}
/// Decision state for a pending tool
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ToolDecision {
#[default]
Pending,
Requested,
Approve,
Deny,
}
/// Events emitted by the tool executor
#[derive(Debug)]
pub enum ToolEvent {
/// Effect delegated to app (IDE, agents, approvals, etc)
Delegate {
agent_id: AgentId,
call_id: String,
effect: Effect,
/// Send result back to executor to continue/error the pipeline
responder: oneshot::Sender<EffectResult>,
},
/// Streaming output from execution
Delta {
agent_id: AgentId,
call_id: String,
content: String,
},
/// Tool execution completed successfully
Completed {
agent_id: AgentId,
call_id: String,
content: String,
},
/// Tool execution failed
Error {
agent_id: AgentId,
call_id: String,
content: String,
},
/// Background tool started - placeholder sent to agent
BackgroundStarted {
agent_id: AgentId,
call_id: String,
name: String,
},
/// Background tool completed - notification for agent
BackgroundCompleted {
agent_id: AgentId,
call_id: String,
name: String,
},
}
impl ToolEvent {
fn completed(active: ActivePipeline) -> Self {
Self::Completed {
agent_id: active.agent_id,
call_id: active.call_id,
content: active.output,
}
}
fn error(active: ActivePipeline, content: impl Into<String>) -> Self {
Self::Error {
agent_id: active.agent_id,
call_id: active.call_id,
content: content.into(),
}
}
fn delta(active: &ActivePipeline, content: String) -> Self {
Self::Delta {
agent_id: active.agent_id,
call_id: active.call_id.clone(),
content,
}
}
fn delegate(
active: &ActivePipeline,
effect: Effect,
) -> (Self, oneshot::Receiver<EffectResult>) {
let (tx, rx) = oneshot::channel();
(
Self::Delegate {
agent_id: active.agent_id,
call_id: active.call_id.clone(),
effect,
responder: tx,
},
rx,
)
}
}
/// Active pipeline execution state
struct ActivePipeline {
agent_id: AgentId,
call_id: String,
name: String,
params: serde_json::Value,
pipeline: ToolPipeline,
output: String,
/// What we're currently waiting for (if anything)
waiting: WaitingFor,
/// Original decision from tool call (for pre-approval)
original_decision: ToolDecision,
/// If true, this is a background task
background: bool,
/// Execution status
status: Status,
}
impl ActivePipeline {
fn new(tool_call: ToolCall, pipeline: ToolPipeline) -> Self {
Self {
agent_id: tool_call.agent_id,
call_id: tool_call.call_id,
name: tool_call.name,
original_decision: tool_call.decision,
params: tool_call.params,
background: tool_call.background,
pipeline,
output: String::new(),
waiting: WaitingFor::Nothing,
status: Status::Running,
}
}
/// Check if pipeline is waiting for something
fn is_waiting(&self) -> bool {
!matches!(self.waiting, WaitingFor::Nothing)
}
/// Check if pipeline is waiting for a handler (spawned task)
fn is_waiting_for_handler(&self) -> bool {
matches!(self.waiting, WaitingFor::Handler(..))
}
/// Check if pipeline is complete (no more steps)
fn is_complete(&self) -> bool {
self.pipeline.is_empty() && !self.is_waiting()
}
// -- State transitions --
/// Transition to error state
fn set_error(&mut self, msg: impl Into<String>) {
self.status = Status::Error;
self.output = msg.into();
self.waiting = WaitingFor::Nothing;
}
/// Transition to complete state
fn set_complete(&mut self) {
self.status = Status::Complete;
self.waiting = WaitingFor::Nothing;
}
/// Transition to denied state
fn set_denied(&mut self) {
self.status = Status::Denied;
self.waiting = WaitingFor::Nothing;
}
}
/// Executes tools with approval flow and streaming output.
///
/// Supports concurrent execution of multiple tools. Blocking tools emit
/// Completed/Error events and are removed from tracking. Background tools
/// emit BackgroundStarted immediately and BackgroundCompleted when done,
/// staying in active map until results are retrieved via take_result().
pub struct ToolExecutor {
tools: ToolRegistry,
pending: VecDeque<ToolCall>,
/// All active pipelines, keyed by call_id
active: HashMap<String, ActivePipeline>,
/// Flag to signal cancellation
cancelled: bool,
}
impl ToolExecutor {
pub fn new(tools: ToolRegistry) -> Self {
Self {
tools,
pending: VecDeque::new(),
active: HashMap::new(),
cancelled: false,
}
}
pub fn tools(&self) -> &ToolRegistry {
&self.tools
}
pub fn tools_mut(&mut self) -> &mut ToolRegistry {
&mut self.tools
}
/// Cancel any active or pending tool execution
/// Hard cancel: abort all foreground tasks and clear the pending queue.
/// Used when ending the entire turn.
pub fn cancel(&mut self) {
self.cancelled = true;
self.pending.clear();
// Abort running foreground tasks. Background tasks are independent
// and keep running across cancellations.
self.active.retain(|_, p| {
if p.background {
return true;
}
if let WaitingFor::Handler(_, ref handle) = p.waiting {
handle.abort();
}
false
});
}
/// Soft cancel: abort the currently running foreground task and return
/// error events for it. The pending queue and background tasks are untouched,
/// so the next tool can rise up.
pub fn cancel_foreground(&mut self) -> Vec<ToolEvent> {
let mut events = Vec::new();
let to_cancel: Vec<String> = self.active.iter()
.filter(|(_, p)| !p.background && p.status == Status::Running
&& p.is_waiting_for_handler())
.map(|(id, _)| id.clone())
.collect();
for call_id in to_cancel {
if let Some(mut p) = self.active.remove(&call_id) {
if let WaitingFor::Handler(_, ref handle) = p.waiting {
handle.abort();
}
p.waiting = WaitingFor::Nothing;
events.push(ToolEvent::Error {
agent_id: p.agent_id,
call_id: p.call_id.clone(),
content: "Cancelled by user".to_string(),
});
}
}
events
}
/// Returns true if any foreground tool is currently running (handler spawned).
pub fn has_running_foreground(&self) -> bool {
self.active.values().any(|p|
!p.background && p.status == Status::Running && p.is_waiting_for_handler()
)
}
pub fn enqueue(&mut self, tool_calls: Vec<ToolCall>) {
self.pending.extend(tool_calls);
}
/// List all background tasks: (call_id, tool_name, status)
pub fn list_tasks(&self) -> Vec<(&str, &str, Status)> {
self.active.values()
.filter(|p| p.background)
.map(|p| (p.call_id.as_str(), p.name.as_str(), p.status))
.collect()
}
/// Take a completed/failed background result by call_id (removes from tracking)
pub fn take_result(&mut self, call_id: &str) -> Option<(String, String, Status)> {
match self.active.get(call_id) {
Some(p) if p.background && p.status != Status::Running => {
let p = self.active.remove(call_id).unwrap();
Some((p.name, p.output, p.status))
}
_ => None,
}
}
/// Get output from a background task without removing it (for testing)
#[cfg(test)]
pub fn get_background_output(&self, call_id: &str) -> Option<String> {
self.active.get(call_id)
.filter(|p| p.background)
.map(|p| p.output.clone())
}
/// Check if a tool call is ready to start (not denied/requested)
fn is_ready(tool_call: &ToolCall) -> bool {
matches!(tool_call.decision, ToolDecision::Pending | ToolDecision::Approve)
}
/// Check if a foreground tool is currently running for a specific agent
fn has_running_foreground_for_agent(&self, agent_id: AgentId) -> bool {
self.active.values().any(|p|
p.agent_id == agent_id && !p.background && p.status == Status::Running
)
}
/// Count running background tasks
pub fn running_background_count(&self) -> usize {
self.active.values().filter(|p| p.background && p.status == Status::Running).count()
}
/// Start a tool by composing its pipeline and adding to active
fn start_tool(&mut self, tool_call: ToolCall) {
let call_id = tool_call.call_id.clone();
let tool = self.tools.get(&tool_call.name);
let pipeline = tool.compose(tool_call.params.clone());
self.active.insert(call_id, ActivePipeline::new(tool_call, pipeline));
}
pub async fn next(&mut self) -> Option<ToolEvent> {
// Check for cancellation
if self.cancelled {
self.cancelled = false;
return None;
}
// Start pending tools with these rules:
// - Foreground tools execute strictly in order (FIFO), one at a time per agent
// - Background tools can start anytime, order not guaranteed
// Start one foreground tool per agent that doesn't already have one running
let fg_agent_ids: HashSet<_> = self.pending.iter()
.filter(|t| !t.background && Self::is_ready(t))
.map(|t| t.agent_id)
.collect();
for agent_id in fg_agent_ids {
if !self.has_running_foreground_for_agent(agent_id) {
if let Some(idx) = self.pending.iter().position(|t|
t.agent_id == agent_id && !t.background && Self::is_ready(t)
) {
let tool_call = self.pending.remove(idx).unwrap();
self.start_tool(tool_call);
}
}
}
// Start all ready background tools
// (Collect indices first, then remove in reverse to preserve indices)
let bg_indices: Vec<_> = self.pending.iter()
.enumerate()
.filter(|(_, t)| t.background && Self::is_ready(t))
.map(|(i, _)| i)
.collect();
for idx in bg_indices.into_iter().rev() {
let tool_call = self.pending.remove(idx).unwrap();
self.start_tool(tool_call);
}
// Main execution loop - keeps going while there's work to do
loop {
// Poll all active pipelines for pending results (handlers, effects, approvals)
let call_ids: Vec<String> = self.active.keys().cloned().collect();
for call_id in &call_ids {
if let Some(event) = self.poll_waiting(call_id) {
return Some(event);
}
}
// Execute steps on non-waiting pipelines
let call_ids: Vec<String> = self.active.keys().cloned().collect();
let mut any_stepped = false;
let mut any_waiting_for_handler = false;
for call_id in &call_ids {
let (should_step, is_handler_wait) = {
match self.active.get(call_id) {
Some(active) => (
// Step if not waiting and either:
// - Running (including when empty, to trigger completion)
// - Denied/Error with finally handlers still remaining
!active.is_waiting() &&
(active.status == Status::Running || !active.pipeline.is_empty()),
active.is_waiting_for_handler(),
),
None => (false, false),
}
};
if is_handler_wait {
any_waiting_for_handler = true;
}
if should_step {
any_stepped = true;
if let Some(event) = self.execute_step(call_id) {
return Some(event);
}
}
}
// If we stepped something, continue the loop (execute_step may have spawned a handler)
if any_stepped {
continue;
}
// If any pipelines are waiting for spawned handlers, yield to let them run
if any_waiting_for_handler {
tokio::task::yield_now().await;
continue;
}
// Check if we're blocked waiting for user input (approvals) or effects
let any_waiting_for_external = self.active.values().any(|p| {
matches!(p.waiting, WaitingFor::Approval(_) | WaitingFor::Effect(_))
});
if any_waiting_for_external {
// Sleep briefly to avoid busy-polling while waiting for user input
// The main app loop handles keyboard events separately
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
continue;
}
// Nothing to step and nothing waiting - we're done for now
break;
}
None
}
/// Poll the waiting state for a specific pipeline
fn poll_waiting(&mut self, call_id: &str) -> Option<ToolEvent> {
let active = self.active.get_mut(call_id)?;
// Take ownership of waiting state to poll it
let waiting = std::mem::replace(&mut active.waiting, WaitingFor::Nothing);
match waiting {
WaitingFor::Nothing => None,
WaitingFor::Handler(mut rx, handle) => {
match poll_receiver(&mut rx) {
Poll::Ready(Ok(step)) => {
// Handler completed - process the step result
drop(handle);
self.process_step(call_id, step)
},
Poll::Ready(Err(_)) => {
// Channel dropped - handler panicked or was cancelled
drop(handle);
let active = self.active.get_mut(call_id)?;
if active.background {
active.set_error("Handler channel dropped");
Some(ToolEvent::BackgroundCompleted {
agent_id: active.agent_id,
call_id: active.call_id.clone(),
name: active.name.clone(),
})
} else {
let active = self.active.remove(call_id).unwrap();
Some(ToolEvent::error(active, "Handler channel dropped"))
}
},
Poll::Pending => {
// Still running - put it back
self.active.get_mut(call_id).unwrap().waiting = WaitingFor::Handler(rx, handle);
None
},
}
},
WaitingFor::Effect(mut rx) => {
match poll_receiver(&mut rx) {
Poll::Ready(Ok(Ok(None))) => {
// Effect completed, no output - continue pipeline
None
},
Poll::Ready(Ok(Ok(Some(output)))) => {
// Effect completed with output - inject into pipeline
active.output = output;
None
},
Poll::Ready(Ok(Err(msg))) => {
let mut active = self.active.remove(call_id).unwrap();
if active.background {
active.set_error(msg);
let event = ToolEvent::BackgroundCompleted {
agent_id: active.agent_id,
call_id: active.call_id.clone(),
name: active.name.clone(),
};
self.active.insert(active.call_id.clone(), active);
Some(event)
} else {
Some(ToolEvent::error(active, msg))
}
},
Poll::Ready(Err(_)) => {
let mut active = self.active.remove(call_id).unwrap();
if active.background {
active.set_error("Effect channel dropped");
let event = ToolEvent::BackgroundCompleted {
agent_id: active.agent_id,
call_id: active.call_id.clone(),
name: active.name.clone(),
};
self.active.insert(active.call_id.clone(), active);
Some(event)
} else {
Some(ToolEvent::error(active, "Effect channel dropped"))
}
},
Poll::Pending => {
// Put it back - still waiting
self.active.get_mut(call_id).unwrap().waiting = WaitingFor::Effect(rx);
None
},
}
},
WaitingFor::Approval(mut rx) => {
let poll_result = poll_receiver(&mut rx);
match poll_result {
Poll::Ready(Ok(Ok(_))) => {
// Approved - continue pipeline
// For background tools, emit BackgroundStarted now
if active.background {
Some(ToolEvent::BackgroundStarted {
agent_id: active.agent_id,
call_id: active.call_id.clone(),
name: active.name.clone(),
})
} else {
None
}
},
Poll::Ready(Ok(Err(reason))) => {
// Denied - skip to finally
active.pipeline.skip_to_finally();
active.set_denied();
Some(ToolEvent::Error {
agent_id: active.agent_id,
call_id: active.call_id.clone(),
content: reason,
})
},
Poll::Ready(Err(_)) => {
tracing::warn!("poll_waiting: approval channel dropped");
let active = self.active.remove(call_id).unwrap();
Some(ToolEvent::error(active, "Approval cancelled"))
},
Poll::Pending => {
tracing::trace!("poll_waiting: Pending (waiting for user approval)");
// Put it back - still waiting
self.active.get_mut(call_id).unwrap().waiting = WaitingFor::Approval(rx);
None
},
}
},
}
}
/// Execute next handler in a specific pipeline.
/// Spawns the handler in a separate task to avoid losing state if dropped.
fn execute_step(&mut self, call_id: &str) -> Option<ToolEvent> {
// Get the handler to execute
let handler = {
let active = self.active.get_mut(call_id)?;
match active.pipeline.pop() {
Some(h) => h,
None => {
// Pipeline complete - finally handlers have run
// For denied/errored pipelines, we already emitted the event, just cleanup
if active.status == Status::Denied || active.status == Status::Error {
self.active.remove(call_id);
return None;
}
if active.background {
active.set_complete();
return Some(ToolEvent::BackgroundCompleted {
agent_id: active.agent_id,
call_id: active.call_id.clone(),
name: active.name.clone(),
});
} else {
let active = self.active.remove(call_id).unwrap();
return Some(ToolEvent::completed(active));
}
},
}
};
// Spawn handler in separate task so it won't be lost if our future is dropped.
// The result will be polled via WaitingFor::Handler in poll_waiting().
let (tx, rx) = oneshot::channel();
let handle = tokio::spawn(async move {
let step = handler.call().await;
let _ = tx.send(step);
});
let active = self.active.get_mut(call_id)?;
active.waiting = WaitingFor::Handler(rx, handle);
None
}
/// Process a Step result from a completed handler.
/// Factored out since it's used by poll_waiting when Handler completes.
fn process_step(&mut self, call_id: &str, step: Step) -> Option<ToolEvent> {
let active = self.active.get_mut(call_id)?;
match step {
Step::Continue => None,
Step::Output(content) => {
active.output = content;
None
},
Step::Delta(content) => {
Some(ToolEvent::delta(active, content))
},
Step::Delegate(effect) => {
let (event, rx) = ToolEvent::delegate(active, effect);
active.waiting = WaitingFor::Effect(rx);
Some(event)
},
Step::AwaitApproval => {
// Skip approval if tool was pre-approved
if active.original_decision == ToolDecision::Approve {
// For background tools, emit BackgroundStarted now
if active.background {
Some(ToolEvent::BackgroundStarted {
agent_id: active.agent_id,
call_id: active.call_id.clone(),
name: active.name.clone(),
})
} else {
None // Continue to next step
}
} else {
// Delegate approval to app via Effect::AwaitApproval
let effect = Effect::AwaitApproval {
name: active.name.clone(),
params: active.params.clone(),
background: active.background,
};
let (event, rx) = ToolEvent::delegate(active, effect);
active.waiting = WaitingFor::Approval(rx);
Some(event)
}
},
Step::Error(msg) => {
if active.background {
active.set_error(&msg);
Some(ToolEvent::BackgroundCompleted {
agent_id: active.agent_id,
call_id: active.call_id.clone(),
name: active.name.clone(),
})
} else {
let active = self.active.remove(call_id).unwrap();
Some(ToolEvent::error(active, msg))
}
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tools::impls::ShellTool;
use std::collections::HashSet;
/// Helper to collect all events until no more are produced
async fn collect_events(executor: &mut ToolExecutor) -> Vec<ToolEvent> {
let mut events = vec![];
while let Some(event) = executor.next().await {
events.push(event);
}
events
}
#[tokio::test]
async fn test_single_tool_completes() {
let mut registry = ToolRegistry::empty();
registry.register(std::sync::Arc::new(ShellTool::new()));
let mut executor = ToolExecutor::new(registry);
executor.enqueue(vec![ToolCall {
agent_id: 0,
call_id: "test1".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "echo hello" }),
decision: ToolDecision::Approve,
background: false,
}]);
let events = collect_events(&mut executor).await;
assert_eq!(events.len(), 1);
match &events[0] {
ToolEvent::Completed { content, .. } => {
assert!(content.contains("hello"));
}
other => panic!("Expected Completed, got {:?}", other),
}
}
#[tokio::test]
async fn test_multiple_tools_sequential() {
let mut registry = ToolRegistry::empty();
registry.register(std::sync::Arc::new(ShellTool::new()));
let mut executor = ToolExecutor::new(registry);
// Enqueue two tools
executor.enqueue(vec![
ToolCall {
agent_id: 0,
call_id: "test1".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "echo first" }),
decision: ToolDecision::Approve,
background: false,
},
ToolCall {
agent_id: 0,
call_id: "test2".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "echo second" }),
decision: ToolDecision::Approve,
background: false,
},
]);
let events = collect_events(&mut executor).await;
// Both should complete
let completed: Vec<_> = events.iter().filter(|e| matches!(e, ToolEvent::Completed { .. })).collect();
assert_eq!(completed.len(), 2, "Expected 2 Completed events, got {}", completed.len());
// Verify both outputs are present
let outputs: Vec<_> = completed.iter().map(|e| {
if let ToolEvent::Completed { content, .. } = e { content.clone() } else { String::new() }
}).collect();
assert!(outputs.iter().any(|o| o.contains("first")), "Missing 'first' output");
assert!(outputs.iter().any(|o| o.contains("second")), "Missing 'second' output");
}
#[tokio::test]
async fn test_background_tools_concurrent() {
// This test verifies that concurrent background tools don't lose output
let mut registry = ToolRegistry::empty();
registry.register(std::sync::Arc::new(ShellTool::new()));
let mut executor = ToolExecutor::new(registry);
// Enqueue multiple background tools
executor.enqueue(vec![
ToolCall {
agent_id: 0,
call_id: "bg1".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "echo background_one" }),
decision: ToolDecision::Approve,
background: true,
},
ToolCall {
agent_id: 0,
call_id: "bg2".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "echo background_two" }),
decision: ToolDecision::Approve,
background: true,
},
ToolCall {
agent_id: 0,
call_id: "bg3".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "echo background_three" }),
decision: ToolDecision::Approve,
background: true,
},
]);
let events = collect_events(&mut executor).await;
// Should have BackgroundStarted and BackgroundCompleted for each
let started: HashSet<_> = events.iter().filter_map(|e| {
if let ToolEvent::BackgroundStarted { call_id, .. } = e { Some(call_id.clone()) } else { None }
}).collect();
let completed: HashSet<_> = events.iter().filter_map(|e| {
if let ToolEvent::BackgroundCompleted { call_id, .. } = e { Some(call_id.clone()) } else { None }
}).collect();
assert_eq!(started.len(), 3, "Expected 3 BackgroundStarted events");
assert_eq!(completed.len(), 3, "Expected 3 BackgroundCompleted events");
assert!(started.contains("bg1"));
assert!(started.contains("bg2"));
assert!(started.contains("bg3"));
assert!(completed.contains("bg1"));
assert!(completed.contains("bg2"));
assert!(completed.contains("bg3"));
// Verify outputs are stored (not lost!)
let output1 = executor.get_background_output("bg1");
let output2 = executor.get_background_output("bg2");
let output3 = executor.get_background_output("bg3");
assert!(output1.is_some(), "bg1 output was lost!");
assert!(output2.is_some(), "bg2 output was lost!");
assert!(output3.is_some(), "bg3 output was lost!");
assert!(output1.unwrap().contains("background_one"), "bg1 has wrong output");
assert!(output2.unwrap().contains("background_two"), "bg2 has wrong output");
assert!(output3.unwrap().contains("background_three"), "bg3 has wrong output");
}
#[tokio::test]
async fn test_mixed_foreground_background() {
let mut registry = ToolRegistry::empty();
registry.register(std::sync::Arc::new(ShellTool::new()));
let mut executor = ToolExecutor::new(registry);
// Mix of foreground and background tools
executor.enqueue(vec![
ToolCall {
agent_id: 0,
call_id: "fg1".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "echo foreground" }),
decision: ToolDecision::Approve,
background: false,
},
ToolCall {
agent_id: 0,
call_id: "bg1".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "echo background" }),
decision: ToolDecision::Approve,
background: true,
},
]);
let events = collect_events(&mut executor).await;
// Foreground should have Completed
let fg_completed = events.iter().any(|e| {
matches!(e, ToolEvent::Completed { call_id, .. } if call_id == "fg1")
});
assert!(fg_completed, "Foreground tool should complete normally");
// Background should have BackgroundCompleted
let bg_completed = events.iter().any(|e| {
matches!(e, ToolEvent::BackgroundCompleted { call_id, .. } if call_id == "bg1")
});
assert!(bg_completed, "Background tool should complete");
// Verify background output is stored
let bg_output = executor.get_background_output("bg1");
assert!(bg_output.is_some(), "Background output was lost");
assert!(bg_output.unwrap().contains("background"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_handler_spawn_doesnt_block() {
// This test verifies that spawning handlers doesn't block - multiple tools
// can have their handlers running concurrently.
// Uses multi_thread runtime because shell handlers use spawn_blocking,
// which needs worker threads to poll JoinHandle completion promptly.
let mut registry = ToolRegistry::empty();
registry.register(std::sync::Arc::new(ShellTool::new()));
let mut executor = ToolExecutor::new(registry);
// Use sleep to make tools take some time
executor.enqueue(vec![
ToolCall {
agent_id: 0,
call_id: "slow1".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "sleep 0.5 && echo slow1_done" }),
decision: ToolDecision::Approve,
background: true,
},
ToolCall {
agent_id: 0,
call_id: "slow2".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "sleep 0.5 && echo slow2_done" }),
decision: ToolDecision::Approve,
background: true,
},
]);
let start = std::time::Instant::now();
let events = collect_events(&mut executor).await;
let elapsed = start.elapsed();
// If running concurrently, should take ~0.5s. If sequential, ~1.0s+
assert!(elapsed.as_millis() < 800, "Tools should run concurrently, took {:?}", elapsed);
// Both should complete
let completed: HashSet<_> = events.iter().filter_map(|e| {
if let ToolEvent::BackgroundCompleted { call_id, .. } = e { Some(call_id.clone()) } else { None }
}).collect();
assert_eq!(completed.len(), 2);
// Both outputs should be present
assert!(executor.get_background_output("slow1").unwrap().contains("slow1_done"));
assert!(executor.get_background_output("slow2").unwrap().contains("slow2_done"));
}
#[tokio::test]
async fn test_foreground_fifo_order() {
// Foreground tools should execute in strict FIFO order,
// even if all are auto-approved
let mut registry = ToolRegistry::empty();
registry.register(std::sync::Arc::new(ShellTool::new()));
let mut executor = ToolExecutor::new(registry);
// Enqueue three foreground tools - second one sleeps to test ordering
executor.enqueue(vec![
ToolCall {
agent_id: 0,
call_id: "fg1".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "sleep 0.05 && echo first" }),
decision: ToolDecision::Approve,
background: false,
},
ToolCall {
agent_id: 0,
call_id: "fg2".to_string(),
name: "mcp_shell".to_string(),
params: serde_json::json!({ "command": "echo second" }),
decision: ToolDecision::Approve,
background: false,
},
]);