forked from openai/codex
-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathagent_tool.rs
More file actions
2603 lines (2345 loc) · 86.6 KB
/
agent_tool.rs
File metadata and controls
2603 lines (2345 loc) · 86.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
use chrono::DateTime;
use chrono::Duration;
use chrono::Utc;
use serde::Deserialize;
use serde::Serialize;
use uuid::Uuid;
use std::fs::{self, OpenOptions};
use std::io::Write as IoWrite;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Stdio;
use tokio::process::Command;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWriteExt, BufReader};
use tokio::runtime::Builder as TokioRuntimeBuilder;
use tokio::sync::RwLock;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio::time::Duration as TokioDuration;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration as StdDuration, Instant};
use crate::spawn::spawn_tokio_command_with_retry;
use crate::protocol::AgentSourceKind;
use tracing::warn;
#[cfg(target_os = "windows")]
fn default_pathext_or_default() -> Vec<String> {
std::env::var("PATHEXT")
.ok()
.filter(|v| !v.is_empty())
.map(|v| {
v.split(';')
.filter(|s| !s.is_empty())
.map(|s| s.to_ascii_lowercase())
.collect()
})
// Keep a sane default set even if PATHEXT is missing or empty. Include
// .ps1 because PowerShell users can invoke scripts without specifying
// the extension; CreateProcess still resolves fine when we provide the
// full path with extension.
.unwrap_or_else(|| vec![
".com".into(),
".exe".into(),
".bat".into(),
".cmd".into(),
".ps1".into(),
])
}
#[cfg(target_os = "windows")]
fn resolve_in_path(command: &str) -> Option<std::path::PathBuf> {
use std::path::Path;
let cmd_path = Path::new(command);
// Absolute or contains separators: respect it directly if it points to a file.
if cmd_path.is_absolute() || command.contains(['\\', '/']) {
if cmd_path.is_file() {
return Some(cmd_path.to_path_buf());
}
}
// Search PATH with PATHEXT semantics and return the first hit.
let exts = default_pathext_or_default();
let Some(path_os) = std::env::var_os("PATH") else { return None; };
let has_ext = cmd_path.extension().is_some();
for dir in std::env::split_paths(&path_os) {
if dir.as_os_str().is_empty() {
continue;
}
if has_ext {
let candidate = dir.join(command);
if candidate.is_file() {
return Some(candidate);
}
} else {
for ext in &exts {
let candidate = dir.join(format!("{command}{ext}"));
if candidate.is_file() {
return Some(candidate);
}
}
}
}
None
}
use crate::agent_defaults::{agent_model_spec, default_params_for};
use shlex::split as shlex_split;
use crate::config_types::AgentConfig;
use crate::openai_tools::JsonSchema;
use crate::openai_tools::OpenAiTool;
use crate::openai_tools::ResponsesApiTool;
use crate::protocol::AgentInfo;
fn current_code_binary_path() -> Result<std::path::PathBuf, String> {
if let Ok(path) = std::env::var("CODE_BINARY_PATH") {
let p = std::path::PathBuf::from(path);
if !p.exists() {
return Err(format!(
"CODE_BINARY_PATH points to '{}' but that file is missing. Rebuild with ./build-fast.sh or update CODE_BINARY_PATH.",
p.display()
));
}
return Ok(p);
}
let exe = std::env::current_exe().map_err(|e| format!("Failed to resolve current executable: {}", e))?;
// If the kernel reports the path as "(deleted)", strip the suffix and prefer the live file
// at the same location (common when a rebuild replaces the inode under a long-running process).
let cleaned = strip_deleted_suffix(&exe);
if cleaned.exists() {
return Ok(cleaned);
}
if let Some(fallback) = fallback_code_binary_path() {
return Ok(fallback);
}
Err(format!(
"Current code binary is missing on disk ({}). It may have been deleted while running. Rebuild with ./build-fast.sh or reinstall 'code' to continue.",
exe.display()
))
}
fn strip_deleted_suffix(path: &std::path::Path) -> std::path::PathBuf {
const DELETED_SUFFIX: &str = " (deleted)";
let s = path.to_string_lossy();
if let Some(stripped) = s.strip_suffix(DELETED_SUFFIX) {
return std::path::PathBuf::from(stripped);
}
path.to_path_buf()
}
fn fallback_code_binary_path() -> Option<std::path::PathBuf> {
// If the running binary was pruned (e.g., shared target cache rotation), try to locate
// a fresh dev build in the repository, and if missing, trigger a quick rebuild.
let repo_root = find_repo_root(std::env::current_dir().ok()?)?;
let workspace = repo_root.join("code-rs");
// Probe likely build outputs in priority order.
let mut candidates = vec![
workspace.join("target/dev-fast/code"),
workspace.join("target/debug/code"),
workspace.join("target/release-prod/code"),
workspace.join("target/release/code"),
workspace.join("bin/code"),
];
if let Some(found) = candidates.iter().find(|p| p.exists()).cloned() {
return Some(found);
}
// Best-effort rebuild; swallow errors so caller can surface the original message.
let status = std::process::Command::new("bash")
.current_dir(&repo_root)
.args(["-lc", "./build-fast.sh >/dev/null 2>&1"])
.status()
.ok();
if status.map(|s| s.success()).unwrap_or(false) {
candidates.retain(|p| p.exists());
if let Some(found) = candidates.first().cloned() {
return Some(found);
}
}
None
}
fn find_repo_root(start: std::path::PathBuf) -> Option<std::path::PathBuf> {
let mut dir = Some(start.as_path());
while let Some(path) = dir {
if path.join(".git").exists() {
return Some(path.to_path_buf());
}
dir = path.parent();
}
None
}
/// Format a helpful error message when an agent command is not found.
/// Provides platform-specific guidance for resolving PATH issues.
fn format_agent_not_found_error(agent_name: &str, command: &str) -> String {
let mut msg = format!("Agent '{}' could not be found.", agent_name);
#[cfg(target_os = "windows")]
{
msg.push_str(&format!(
"\n\nTroubleshooting steps:\n\
1. Check if '{}' is installed and available in your PATH\n\
2. Try using an absolute path in your config.toml:\n\
[[agents]]\n\
name = \"{}\"\n\
command = \"C:\\\\Users\\\\YourUser\\\\AppData\\\\Roaming\\\\npm\\\\{}.cmd\"\n\
3. Verify your PATH includes the directory containing '{}'\n\
4. On Windows, ensure the file has a valid extension (.exe, .cmd, .bat, .com)\n\n\
For more information, see: https://github.com/just-every/code/blob/main/code-rs/config.md",
command, agent_name, command, command
));
}
#[cfg(not(target_os = "windows"))]
{
msg.push_str(&format!(
"\n\nTroubleshooting steps:\n\
1. Check if '{}' is installed: which {}\n\
2. Verify '{}' is in your PATH: echo $PATH\n\
3. Try using an absolute path in your config.toml:\n\
[[agents]]\n\
name = \"{}\"\n\
command = \"/absolute/path/to/{}\"\n\n\
For more information, see: https://github.com/just-every/code/blob/main/code-rs/config.md",
command, command, command, agent_name, command
));
}
msg
}
// Agent status enum
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum AgentStatus {
Pending,
Running,
Completed,
Failed,
Cancelled,
}
// Agent information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Agent {
pub id: String,
pub batch_id: Option<String>,
pub model: String,
#[serde(default)]
pub name: Option<String>,
pub prompt: String,
pub context: Option<String>,
pub output_goal: Option<String>,
pub files: Vec<String>,
pub read_only: bool,
pub status: AgentStatus,
pub result: Option<String>,
pub error: Option<String>,
pub created_at: DateTime<Utc>,
pub started_at: Option<DateTime<Utc>>,
pub completed_at: Option<DateTime<Utc>>,
pub progress: Vec<String>,
pub worktree_path: Option<String>,
pub branch_name: Option<String>,
#[serde(default)]
pub worktree_base: Option<String>,
#[serde(default)]
pub source_kind: Option<AgentSourceKind>,
#[serde(skip)]
pub log_tag: Option<String>,
#[serde(skip)]
#[allow(dead_code)]
pub config: Option<AgentConfig>,
pub reasoning_effort: code_protocol::config_types::ReasoningEffort,
#[serde(skip)]
pub last_activity: DateTime<Utc>,
}
// Global agent manager
lazy_static::lazy_static! {
pub static ref AGENT_MANAGER: Arc<RwLock<AgentManager>> = Arc::new(RwLock::new(AgentManager::new()));
}
pub struct AgentManager {
agents: HashMap<String, Agent>,
handles: HashMap<String, JoinHandle<()>>,
event_sender: Option<mpsc::UnboundedSender<AgentStatusUpdatePayload>>,
debug_log_root: Option<PathBuf>,
watchdog_handle: Option<JoinHandle<()>>,
inactivity_timeout: Duration,
}
#[derive(Debug, Clone)]
pub struct AgentStatusUpdatePayload {
pub agents: Vec<AgentInfo>,
pub context: Option<String>,
pub task: Option<String>,
}
impl AgentManager {
pub fn new() -> Self {
Self {
agents: HashMap::new(),
handles: HashMap::new(),
event_sender: None,
debug_log_root: None,
watchdog_handle: None,
inactivity_timeout: Duration::minutes(30),
}
}
pub fn set_event_sender(&mut self, sender: mpsc::UnboundedSender<AgentStatusUpdatePayload>) {
self.event_sender = Some(sender);
self.start_watchdog();
}
fn start_watchdog(&mut self) {
if self.watchdog_handle.is_some() {
return;
}
let timeout = self.inactivity_timeout;
let manager = Arc::downgrade(&AGENT_MANAGER);
self.watchdog_handle = Some(tokio::spawn(async move {
let mut ticker = tokio::time::interval(TokioDuration::from_secs(60));
loop {
ticker.tick().await;
let Some(manager_arc) = manager.upgrade() else { break; };
let mut mgr = manager_arc.write().await;
let now = Utc::now();
let timeout_ids: Vec<String> = mgr
.agents
.iter()
.filter(|(_, agent)| matches!(agent.status, AgentStatus::Pending | AgentStatus::Running))
.filter(|(_, agent)| now - agent.last_activity > timeout)
.map(|(id, _)| id.clone())
.collect();
if timeout_ids.is_empty() {
continue;
}
for agent_id in timeout_ids.iter() {
if let Some(handle) = mgr.handles.remove(agent_id) {
handle.abort();
}
if let Some(agent) = mgr.agents.get_mut(agent_id) {
agent.status = AgentStatus::Failed;
agent.error = Some(format!(
"Agent timed out after {} minutes of inactivity.",
timeout.num_minutes()
));
agent.completed_at = Some(now);
Self::record_activity(agent);
}
}
// Notify listeners once per sweep.
mgr.send_agent_status_update().await;
}
}));
}
pub fn set_debug_log_root(&mut self, root: Option<PathBuf>) {
self.debug_log_root = root;
}
async fn touch_agent(agent_id: &str) {
if let Some(manager) = Arc::downgrade(&AGENT_MANAGER).upgrade() {
let mut mgr = manager.write().await;
if let Some(agent) = mgr.agents.get_mut(agent_id) {
Self::record_activity(agent);
}
}
}
fn record_activity(agent: &mut Agent) {
agent.last_activity = Utc::now();
}
fn append_agent_log(&self, log_tag: &str, line: &str) {
let Some(root) = &self.debug_log_root else { return; };
let dir = root.join(log_tag);
if let Err(err) = fs::create_dir_all(&dir) {
warn!("failed to create agent log dir {:?}: {}", dir, err);
return;
}
let file = dir.join("progress.log");
match OpenOptions::new().create(true).append(true).open(&file) {
Ok(mut fh) => {
if let Err(err) = writeln!(fh, "{}", line) {
warn!("failed to write agent log {:?}: {}", file, err);
}
}
Err(err) => warn!("failed to open agent log {:?}: {}", file, err),
}
}
async fn send_agent_status_update(&self) {
if let Some(ref sender) = self.event_sender {
let now = Utc::now();
let agents: Vec<AgentInfo> = self
.agents
.values()
.map(|agent| {
// Just show the model name - status provides the useful info
let name = agent
.name
.as_ref()
.map(|value| value.clone())
.unwrap_or_else(|| agent.model.clone());
let start = agent.started_at.unwrap_or(agent.created_at);
let end = agent.completed_at.unwrap_or(now);
let elapsed_ms = match end.signed_duration_since(start).num_milliseconds() {
value if value >= 0 => Some(value as u64),
_ => None,
};
AgentInfo {
id: agent.id.clone(),
name,
status: format!("{:?}", agent.status).to_lowercase(),
batch_id: agent.batch_id.clone(),
model: Some(agent.model.clone()),
last_progress: agent.progress.last().cloned(),
result: agent.result.clone(),
error: agent.error.clone(),
elapsed_ms,
token_count: None,
last_activity_at: match agent.status {
AgentStatus::Pending | AgentStatus::Running => {
Some(agent.last_activity.to_rfc3339())
}
_ => None,
},
seconds_since_last_activity: match agent.status {
AgentStatus::Pending | AgentStatus::Running => Some(
Utc::now()
.signed_duration_since(agent.last_activity)
.num_seconds()
.max(0) as u64,
),
_ => None,
},
source_kind: agent.source_kind.clone(),
}
})
.collect();
// Get context and task from the first agent (they're all the same)
let (context, task) = self
.agents
.values()
.next()
.map(|agent| {
let context = agent
.context
.as_ref()
.and_then(|value| if value.trim().is_empty() {
None
} else {
Some(value.clone())
});
let task = if agent.prompt.trim().is_empty() {
None
} else {
Some(agent.prompt.clone())
};
(context, task)
})
.unwrap_or((None, None));
let payload = AgentStatusUpdatePayload { agents, context, task };
let _ = sender.send(payload);
}
}
pub async fn create_agent(
&mut self,
model: String,
name: Option<String>,
prompt: String,
context: Option<String>,
output_goal: Option<String>,
files: Vec<String>,
read_only: bool,
batch_id: Option<String>,
reasoning_effort: code_protocol::config_types::ReasoningEffort,
) -> String {
self.create_agent_internal(
model,
name,
prompt,
context,
output_goal,
files,
read_only,
batch_id,
None,
None,
None,
None,
reasoning_effort,
)
.await
}
pub async fn create_agent_with_config(
&mut self,
model: String,
name: Option<String>,
prompt: String,
context: Option<String>,
output_goal: Option<String>,
files: Vec<String>,
read_only: bool,
batch_id: Option<String>,
config: AgentConfig,
reasoning_effort: code_protocol::config_types::ReasoningEffort,
) -> String {
self.create_agent_internal(
model,
name,
prompt,
context,
output_goal,
files,
read_only,
batch_id,
Some(config),
None,
None,
None,
reasoning_effort,
)
.await
}
#[allow(dead_code)]
pub async fn create_agent_with_options(
&mut self,
model: String,
name: Option<String>,
prompt: String,
context: Option<String>,
output_goal: Option<String>,
files: Vec<String>,
read_only: bool,
batch_id: Option<String>,
config: Option<AgentConfig>,
worktree_branch: Option<String>,
worktree_base: Option<String>,
source_kind: Option<AgentSourceKind>,
reasoning_effort: code_protocol::config_types::ReasoningEffort,
) -> String {
self
.create_agent_internal(
model,
name,
prompt,
context,
output_goal,
files,
read_only,
batch_id,
config,
worktree_branch,
worktree_base,
source_kind,
reasoning_effort,
)
.await
}
async fn create_agent_internal(
&mut self,
model: String,
name: Option<String>,
prompt: String,
context: Option<String>,
output_goal: Option<String>,
files: Vec<String>,
read_only: bool,
batch_id: Option<String>,
config: Option<AgentConfig>,
worktree_branch: Option<String>,
worktree_base: Option<String>,
source_kind: Option<AgentSourceKind>,
reasoning_effort: code_protocol::config_types::ReasoningEffort,
) -> String {
let agent_id = Uuid::new_v4().to_string();
let log_tag = match source_kind {
Some(AgentSourceKind::AutoReview) => {
Some(format!("agents/auto-review/{}", agent_id))
}
_ => None,
};
let agent = Agent {
id: agent_id.clone(),
batch_id,
model,
name: normalize_agent_name(name),
prompt,
context,
output_goal,
files,
read_only,
status: AgentStatus::Pending,
result: None,
error: None,
created_at: Utc::now(),
started_at: None,
completed_at: None,
progress: Vec::new(),
worktree_path: None,
branch_name: worktree_branch,
worktree_base,
source_kind,
log_tag,
config: config.clone(),
reasoning_effort,
last_activity: Utc::now(),
};
self.agents.insert(agent_id.clone(), agent.clone());
// Send initial status update
self.send_agent_status_update().await;
// Spawn async agent
let agent_id_clone = agent_id.clone();
let handle = tokio::spawn(async move {
execute_agent(agent_id_clone, config).await;
});
self.handles.insert(agent_id.clone(), handle);
agent_id
}
pub fn get_agent(&self, agent_id: &str) -> Option<Agent> {
self.agents.get(agent_id).cloned()
}
pub fn get_all_agents(&self) -> impl Iterator<Item = &Agent> {
self.agents.values()
}
pub fn list_agents(
&self,
status_filter: Option<AgentStatus>,
batch_id: Option<String>,
recent_only: bool,
) -> Vec<Agent> {
let cutoff = if recent_only {
Some(Utc::now() - Duration::hours(2))
} else {
None
};
self.agents
.values()
.filter(|agent| {
if let Some(ref filter) = status_filter {
if agent.status != *filter {
return false;
}
}
if let Some(ref batch) = batch_id {
if agent.batch_id.as_ref() != Some(batch) {
return false;
}
}
if let Some(cutoff) = cutoff {
if agent.created_at < cutoff {
return false;
}
}
true
})
.cloned()
.collect()
}
pub fn has_active_agents(&self) -> bool {
self.agents
.values()
.any(|agent| matches!(agent.status, AgentStatus::Pending | AgentStatus::Running))
}
pub async fn cancel_agent(&mut self, agent_id: &str) -> bool {
if let Some(handle) = self.handles.remove(agent_id) {
handle.abort();
if let Some(agent) = self.agents.get_mut(agent_id) {
agent.status = AgentStatus::Cancelled;
agent.completed_at = Some(Utc::now());
}
true
} else {
false
}
}
pub async fn cancel_batch(&mut self, batch_id: &str) -> usize {
let agent_ids: Vec<String> = self
.agents
.values()
.filter(|agent| agent.batch_id.as_ref() == Some(&batch_id.to_string()))
.map(|agent| agent.id.clone())
.collect();
let mut count = 0;
for agent_id in agent_ids {
if self.cancel_agent(&agent_id).await {
count += 1;
}
}
count
}
pub async fn update_agent_status(&mut self, agent_id: &str, status: AgentStatus) {
if let Some(agent) = self.agents.get_mut(agent_id) {
agent.status = status;
if agent.status == AgentStatus::Running && agent.started_at.is_none() {
agent.started_at = Some(Utc::now());
}
if matches!(
agent.status,
AgentStatus::Completed | AgentStatus::Failed | AgentStatus::Cancelled
) {
agent.completed_at = Some(Utc::now());
}
Self::record_activity(agent);
// Send status update event
self.send_agent_status_update().await;
}
}
pub async fn update_agent_result(&mut self, agent_id: &str, result: Result<String, String>) {
let debug_enabled = self.debug_log_root.is_some();
if let Some((log_tag, log_lines)) = self.agents.get_mut(agent_id).map(|agent| {
let log_tag = if debug_enabled { agent.log_tag.clone() } else { None };
let mut log_lines: Vec<String> = Vec::new();
if debug_enabled {
let stamp = Utc::now().format("%H:%M:%S");
match &result {
Ok(output) => {
log_lines.push(format!("{stamp}: [result] completed"));
if !output.trim().is_empty() {
log_lines.push(output.trim_end().to_string());
}
}
Err(error) => {
log_lines.push(format!("{stamp}: [result] failed"));
log_lines.push(error.clone());
}
}
}
match result {
Ok(output) => {
agent.result = Some(output);
agent.status = AgentStatus::Completed;
}
Err(error) => {
agent.error = Some(error);
agent.status = AgentStatus::Failed;
}
}
agent.completed_at = Some(Utc::now());
Self::record_activity(agent);
(log_tag, log_lines)
}) {
if let Some(tag) = log_tag {
for line in log_lines {
self.append_agent_log(&tag, &line);
}
}
// Send status update event
self.send_agent_status_update().await;
}
}
pub async fn add_progress(&mut self, agent_id: &str, message: String) {
let debug_enabled = self.debug_log_root.is_some();
if let Some((log_tag, entry)) = self.agents.get_mut(agent_id).map(|agent| {
let entry = format!("{}: {}", Utc::now().format("%H:%M:%S"), message);
let log_tag = if debug_enabled { agent.log_tag.clone() } else { None };
agent.progress.push(entry.clone());
Self::record_activity(agent);
(log_tag, entry)
}) {
if let Some(tag) = log_tag {
self.append_agent_log(&tag, &entry);
}
// Send updated agent status with the latest progress
self.send_agent_status_update().await;
}
}
pub async fn update_worktree_info(
&mut self,
agent_id: &str,
worktree_path: String,
branch_name: String,
) {
if let Some(agent) = self.agents.get_mut(agent_id) {
agent.worktree_path = Some(worktree_path);
agent.branch_name = Some(branch_name);
}
}
}
async fn get_git_root() -> Result<PathBuf, String> {
let output = Command::new("git")
.args(&["rev-parse", "--show-toplevel"])
.output()
.await
.map_err(|e| format!("Git not installed or not in a git repository: {}", e))?;
if output.status.success() {
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(PathBuf::from(path))
} else {
Err("Not in a git repository".to_string())
}
}
use crate::git_worktree::sanitize_ref_component;
fn generate_branch_id(model: &str, agent: &str) -> String {
// Extract first few meaningful words from agent for the branch name
let stop = ["the", "and", "for", "with", "from", "into", "goal"]; // skip boilerplate
let words: Vec<&str> = agent
.split_whitespace()
.filter(|w| w.len() > 2 && !stop.contains(&w.to_ascii_lowercase().as_str()))
.take(3)
.collect();
let raw_suffix = if words.is_empty() {
Uuid::new_v4()
.to_string()
.split('-')
.next()
.unwrap_or("agent")
.to_string()
} else {
words.join("-")
};
// Sanitize both model and suffix for safety
let model_s = sanitize_ref_component(model);
let mut suffix_s = sanitize_ref_component(&raw_suffix);
// Constrain length to keep branch names readable
if suffix_s.len() > 40 {
suffix_s.truncate(40);
suffix_s = suffix_s.trim_matches('-').to_string();
if suffix_s.is_empty() {
suffix_s = "agent".to_string();
}
}
format!("code-{}-{}", model_s, suffix_s)
}
use crate::git_worktree::setup_worktree;
async fn execute_agent(agent_id: String, config: Option<AgentConfig>) {
let mut manager = AGENT_MANAGER.write().await;
// Get agent details
let agent = match manager.get_agent(&agent_id) {
Some(t) => t,
None => return,
};
// Update status to running
manager
.update_agent_status(&agent_id, AgentStatus::Running)
.await;
manager
.add_progress(
&agent_id,
format!("Starting agent with model: {}", agent.model),
)
.await;
let model = agent.model.clone();
let model_spec = agent_model_spec(&model);
let prompt = agent.prompt.clone();
let read_only = agent.read_only;
let context = agent.context.clone();
let output_goal = agent.output_goal.clone();
let files = agent.files.clone();
let reasoning_effort = agent.reasoning_effort;
let source_kind = agent.source_kind.clone();
let log_tag = agent.log_tag.clone();
drop(manager); // Release the lock before executing
// Build the full prompt with context
let mut full_prompt = prompt.clone();
// Prepend any per-agent instructions from config when available
if let Some(cfg) = config.as_ref() {
if let Some(instr) = cfg.instructions.as_ref() {
if !instr.trim().is_empty() {
full_prompt = format!("{}\n\n{}", instr.trim(), full_prompt);
}
}
}
if let Some(context) = &context {
let trimmed = full_prompt.trim_start();
if trimmed.starts_with('/') {
// Preserve leading slash commands so downstream executors can parse them.
full_prompt = format!("{full_prompt}\n\nContext: {context}");
} else {
full_prompt = format!("Context: {context}\n\nAgent: {full_prompt}");
}
}
if let Some(output_goal) = &output_goal {
full_prompt = format!("{}\n\nDesired output: {}", full_prompt, output_goal);
}
if !files.is_empty() {
full_prompt = format!("{}\n\nFiles to consider: {}", full_prompt, files.join(", "));
}
// Setup working directory and execute
let gating_error_message = |spec: &crate::agent_defaults::AgentModelSpec| {
if let Some(flag) = spec.gating_env {
format!(
"agent model '{}' is disabled; set {}=1 to enable it",
spec.slug, flag
)
} else {
format!("agent model '{}' is disabled", spec.slug)
}
};
// Track optional review output path for /review agents (AutoReview)
let mut review_output_json_path_capture: Option<PathBuf> = None;
let result = if !read_only {
// Check git and setup worktree for non-read-only mode
match get_git_root().await {
Ok(git_root) => {
let branch_id = agent
.branch_name
.clone()
.unwrap_or_else(|| generate_branch_id(&model, &prompt));
let mut manager = AGENT_MANAGER.write().await;
manager
.add_progress(&agent_id, format!("Creating git worktree: {}", branch_id))
.await;
drop(manager);
match setup_worktree(&git_root, &branch_id, agent.worktree_base.as_deref()).await {
Ok((worktree_path, used_branch)) => {
let mut manager = AGENT_MANAGER.write().await;
manager
.add_progress(
&agent_id,
format!("Executing in worktree: {}", worktree_path.display()),
)
.await;
manager
.update_worktree_info(
&agent_id,
worktree_path.display().to_string(),
used_branch.clone(),
)
.await;
drop(manager);
// Prepare optional review-output JSON path for /review agents
let review_output_json_path: Option<PathBuf> = agent
.source_kind
.as_ref()
.and_then(|kind| matches!(kind, AgentSourceKind::AutoReview).then(|| {
let filename = format!("{}.review-output.json", agent_id);
std::env::temp_dir().join(filename)
}));
review_output_json_path_capture = review_output_json_path.clone();
// Execute with full permissions in the worktree
let use_built_in_cloud = config.is_none()
&& model_spec
.map(|spec| spec.cli.eq_ignore_ascii_case("cloud"))
.unwrap_or_else(|| model.eq_ignore_ascii_case("cloud"));
if use_built_in_cloud {
if let Some(spec) = model_spec {
if !spec.is_enabled() {
Err(gating_error_message(spec))
} else {
execute_cloud_built_in_streaming(
&agent_id,
&full_prompt,
Some(worktree_path),