-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathagents.rs
More file actions
2142 lines (1885 loc) · 74 KB
/
agents.rs
File metadata and controls
2142 lines (1885 loc) · 74 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 anyhow::Result;
use chrono;
use dirs;
use log::{debug, error, info, warn};
use reqwest;
use rusqlite::{params, Connection, Result as SqliteResult};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use serde_yaml;
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::process::Stdio;
use std::sync::Mutex;
use tauri::{AppHandle, Emitter, Manager, State};
// Sidecar support removed; using system binary execution only
use tokio::io::{AsyncBufReadExt, BufReader as TokioBufReader};
use tokio::process::Command;
/// Finds the full path to the claude binary
/// This is necessary because macOS apps have a limited PATH environment
fn find_claude_binary(app_handle: &AppHandle) -> Result<String, String> {
crate::claude_binary::find_claude_binary(app_handle)
}
/// Represents a CC Agent stored in the database or loaded from filesystem
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Agent {
pub id: Option<i64>,
pub name: String,
pub icon: String,
pub system_prompt: String,
pub default_task: Option<String>,
pub model: String,
pub enable_file_read: bool,
pub enable_file_write: bool,
pub enable_network: bool,
pub hooks: Option<String>, // JSON string of hooks configuration
pub created_at: String,
pub updated_at: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<String>, // "database" or "filesystem"
#[serde(skip_serializing_if = "Option::is_none")]
pub file_path: Option<String>, // Path if loaded from filesystem
}
/// Represents an agent execution run
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AgentRun {
pub id: Option<i64>,
pub agent_id: i64,
pub agent_name: String,
pub agent_icon: String,
pub task: String,
pub model: String,
pub project_path: String,
pub session_id: String, // UUID session ID from Claude Code
pub status: String, // 'pending', 'running', 'completed', 'failed', 'cancelled'
pub pid: Option<u32>,
pub process_started_at: Option<String>,
pub created_at: String,
pub completed_at: Option<String>,
}
/// Represents runtime metrics calculated from JSONL
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AgentRunMetrics {
pub duration_ms: Option<i64>,
pub total_tokens: Option<i64>,
pub cost_usd: Option<f64>,
pub message_count: Option<i64>,
}
/// Combined agent run with real-time metrics
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AgentRunWithMetrics {
#[serde(flatten)]
pub run: AgentRun,
pub metrics: Option<AgentRunMetrics>,
pub output: Option<String>, // Real-time JSONL content
}
/// Agent export format
#[derive(Debug, Serialize, Deserialize)]
pub struct AgentExport {
pub version: u32,
pub exported_at: String,
pub agent: AgentData,
}
/// Agent data within export
#[derive(Debug, Serialize, Deserialize)]
pub struct AgentData {
pub name: String,
pub icon: String,
pub system_prompt: String,
pub default_task: Option<String>,
pub model: String,
pub hooks: Option<String>,
}
/// Frontmatter structure for agent markdown files
#[derive(Debug, Serialize, Deserialize)]
struct AgentFrontmatter {
name: String,
description: Option<String>,
tools: Option<String>,
model: Option<String>,
icon: Option<String>,
}
/// Database connection state
pub struct AgentDb(pub Mutex<Connection>);
/// Real-time JSONL reading and processing functions
impl AgentRunMetrics {
/// Calculate metrics from JSONL content
pub fn from_jsonl(jsonl_content: &str) -> Self {
let mut total_tokens = 0i64;
let mut cost_usd = 0.0f64;
let mut message_count = 0i64;
let mut start_time: Option<chrono::DateTime<chrono::Utc>> = None;
let mut end_time: Option<chrono::DateTime<chrono::Utc>> = None;
for line in jsonl_content.lines() {
if let Ok(json) = serde_json::from_str::<JsonValue>(line) {
message_count += 1;
// Track timestamps
if let Some(timestamp_str) = json.get("timestamp").and_then(|t| t.as_str()) {
if let Ok(timestamp) = chrono::DateTime::parse_from_rfc3339(timestamp_str) {
let utc_time = timestamp.with_timezone(&chrono::Utc);
if start_time.is_none() || utc_time < start_time.unwrap() {
start_time = Some(utc_time);
}
if end_time.is_none() || utc_time > end_time.unwrap() {
end_time = Some(utc_time);
}
}
}
// Extract token usage - check both top-level and nested message.usage
let usage = json
.get("usage")
.or_else(|| json.get("message").and_then(|m| m.get("usage")));
if let Some(usage) = usage {
if let Some(input_tokens) = usage.get("input_tokens").and_then(|t| t.as_i64()) {
total_tokens += input_tokens;
}
if let Some(output_tokens) = usage.get("output_tokens").and_then(|t| t.as_i64())
{
total_tokens += output_tokens;
}
}
// Extract cost information
if let Some(cost) = json.get("cost").and_then(|c| c.as_f64()) {
cost_usd += cost;
}
}
}
let duration_ms = match (start_time, end_time) {
(Some(start), Some(end)) => Some((end - start).num_milliseconds()),
_ => None,
};
Self {
duration_ms,
total_tokens: if total_tokens > 0 {
Some(total_tokens)
} else {
None
},
cost_usd: if cost_usd > 0.0 { Some(cost_usd) } else { None },
message_count: if message_count > 0 {
Some(message_count)
} else {
None
},
}
}
}
/// Read JSONL content from a session file
pub async fn read_session_jsonl(session_id: &str, project_path: &str) -> Result<String, String> {
let claude_dir = dirs::home_dir()
.ok_or("Failed to get home directory")?
.join(".claude")
.join("projects");
// Encode project path to match Claude Code's directory naming
let encoded_project = project_path.replace('/', "-");
let project_dir = claude_dir.join(&encoded_project);
let session_file = project_dir.join(format!("{}.jsonl", session_id));
if !session_file.exists() {
return Err(format!(
"Session file not found: {}",
session_file.display()
));
}
match tokio::fs::read_to_string(&session_file).await {
Ok(content) => Ok(content),
Err(e) => Err(format!("Failed to read session file: {}", e)),
}
}
/// Get agent run with real-time metrics
pub async fn get_agent_run_with_metrics(run: AgentRun) -> AgentRunWithMetrics {
match read_session_jsonl(&run.session_id, &run.project_path).await {
Ok(jsonl_content) => {
let metrics = AgentRunMetrics::from_jsonl(&jsonl_content);
AgentRunWithMetrics {
run,
metrics: Some(metrics),
output: Some(jsonl_content),
}
}
Err(e) => {
log::warn!("Failed to read JSONL for session {}: {}", run.session_id, e);
AgentRunWithMetrics {
run,
metrics: None,
output: None,
}
}
}
}
/// Initialize the agents database
pub fn init_database(app: &AppHandle) -> SqliteResult<Connection> {
let app_dir = app
.path()
.app_data_dir()
.expect("Failed to get app data dir");
std::fs::create_dir_all(&app_dir).expect("Failed to create app data dir");
let db_path = app_dir.join("agents.db");
let conn = Connection::open(db_path)?;
// Create agents table
conn.execute(
"CREATE TABLE IF NOT EXISTS agents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
icon TEXT NOT NULL,
system_prompt TEXT NOT NULL,
default_task TEXT,
model TEXT NOT NULL DEFAULT 'sonnet',
enable_file_read BOOLEAN NOT NULL DEFAULT 1,
enable_file_write BOOLEAN NOT NULL DEFAULT 1,
enable_network BOOLEAN NOT NULL DEFAULT 0,
hooks TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)",
[],
)?;
// Add columns to existing table if they don't exist
let _ = conn.execute("ALTER TABLE agents ADD COLUMN default_task TEXT", []);
let _ = conn.execute(
"ALTER TABLE agents ADD COLUMN model TEXT DEFAULT 'sonnet'",
[],
);
let _ = conn.execute("ALTER TABLE agents ADD COLUMN hooks TEXT", []);
let _ = conn.execute(
"ALTER TABLE agents ADD COLUMN enable_file_read BOOLEAN DEFAULT 1",
[],
);
let _ = conn.execute(
"ALTER TABLE agents ADD COLUMN enable_file_write BOOLEAN DEFAULT 1",
[],
);
let _ = conn.execute(
"ALTER TABLE agents ADD COLUMN enable_network BOOLEAN DEFAULT 0",
[],
);
// Create agent_runs table
conn.execute(
"CREATE TABLE IF NOT EXISTS agent_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id INTEGER NOT NULL,
agent_name TEXT NOT NULL,
agent_icon TEXT NOT NULL,
task TEXT NOT NULL,
model TEXT NOT NULL,
project_path TEXT NOT NULL,
session_id TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
pid INTEGER,
process_started_at TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
completed_at TEXT,
FOREIGN KEY (agent_id) REFERENCES agents(id) ON DELETE CASCADE
)",
[],
)?;
// Migrate existing agent_runs table if needed
let _ = conn.execute("ALTER TABLE agent_runs ADD COLUMN session_id TEXT", []);
let _ = conn.execute(
"ALTER TABLE agent_runs ADD COLUMN status TEXT DEFAULT 'pending'",
[],
);
let _ = conn.execute("ALTER TABLE agent_runs ADD COLUMN pid INTEGER", []);
let _ = conn.execute(
"ALTER TABLE agent_runs ADD COLUMN process_started_at TEXT",
[],
);
// Drop old columns that are no longer needed (data is now read from JSONL files)
// Note: SQLite doesn't support DROP COLUMN, so we'll ignore errors for existing columns
let _ = conn.execute(
"UPDATE agent_runs SET session_id = '' WHERE session_id IS NULL",
[],
);
let _ = conn.execute("UPDATE agent_runs SET status = 'completed' WHERE status IS NULL AND completed_at IS NOT NULL", []);
let _ = conn.execute("UPDATE agent_runs SET status = 'failed' WHERE status IS NULL AND completed_at IS NOT NULL AND session_id = ''", []);
let _ = conn.execute(
"UPDATE agent_runs SET status = 'pending' WHERE status IS NULL",
[],
);
// Create trigger to update the updated_at timestamp
conn.execute(
"CREATE TRIGGER IF NOT EXISTS update_agent_timestamp
AFTER UPDATE ON agents
FOR EACH ROW
BEGIN
UPDATE agents SET updated_at = CURRENT_TIMESTAMP WHERE id = NEW.id;
END",
[],
)?;
// Create settings table for app-wide settings
conn.execute(
"CREATE TABLE IF NOT EXISTS app_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)",
[],
)?;
// Create trigger to update the updated_at timestamp
conn.execute(
"CREATE TRIGGER IF NOT EXISTS update_app_settings_timestamp
AFTER UPDATE ON app_settings
FOR EACH ROW
BEGIN
UPDATE app_settings SET updated_at = CURRENT_TIMESTAMP WHERE key = NEW.key;
END",
[],
)?;
Ok(conn)
}
/// Parse a markdown file with YAML frontmatter
fn parse_agent_markdown(file_path: &Path) -> Result<Agent, String> {
let content = fs::read_to_string(file_path)
.map_err(|e| format!("Failed to read file {}: {}", file_path.display(), e))?;
// Split frontmatter and content
let parts: Vec<&str> = content.splitn(3, "---").collect();
if parts.len() < 3 {
return Err(format!("Invalid markdown format in {}", file_path.display()));
}
// Parse frontmatter
let frontmatter: AgentFrontmatter = serde_yaml::from_str(parts[1])
.map_err(|e| format!("Failed to parse frontmatter in {}: {}", file_path.display(), e))?;
// Extract system prompt from markdown content
let system_prompt = parts[2].trim().to_string();
// Determine icon based on name or use default
let icon = frontmatter.icon.unwrap_or_else(|| {
// Map common agent names to icons
match frontmatter.name.as_str() {
name if name.contains("ai") => "bot",
name if name.contains("api") => "globe",
name if name.contains("cloud") => "cloud",
name if name.contains("data") => "database",
name if name.contains("test") || name.contains("qa") => "shield",
name if name.contains("deploy") => "package",
name if name.contains("architect") => "layout",
name if name.contains("security") => "shield",
name if name.contains("debug") => "bug",
name if name.contains("doc") => "file-text",
name if name.contains("review") => "eye",
_ => "bot",
}.to_string()
});
let now = chrono::Local::now().to_rfc3339();
Ok(Agent {
id: None, // File-based agents don't have database IDs
name: frontmatter.name.clone(),
icon,
system_prompt,
default_task: frontmatter.description,
model: frontmatter.model.unwrap_or_else(|| "sonnet".to_string()),
enable_file_read: true,
enable_file_write: true,
enable_network: false,
hooks: None,
created_at: now.clone(),
updated_at: now,
source: Some("filesystem".to_string()),
file_path: Some(file_path.to_string_lossy().to_string()),
})
}
/// Load agents from the .claude/agents directory
fn load_filesystem_agents() -> Vec<Agent> {
let mut agents = Vec::new();
// Get the .claude/agents directory
let home = match dirs::home_dir() {
Some(h) => h,
None => {
warn!("Could not determine home directory");
return agents;
}
};
let agents_dir = home.join(".claude").join("agents");
if !agents_dir.exists() {
debug!("No .claude/agents directory found");
return agents;
}
// Recursively walk through the agents directory
fn scan_directory(dir: &Path, agents: &mut Vec<Agent>) {
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
// Skip hidden directories
if let Some(name) = path.file_name() {
if !name.to_string_lossy().starts_with('.') {
scan_directory(&path, agents);
}
}
} else if path.is_file() {
// Check if it's a markdown file
if let Some(ext) = path.extension() {
if ext == "md" || ext == "markdown" {
match parse_agent_markdown(&path) {
Ok(agent) => {
debug!("Loaded agent from file: {}", agent.name);
agents.push(agent);
}
Err(e) => {
warn!("Failed to parse agent file {}: {}", path.display(), e);
}
}
}
}
}
}
}
}
scan_directory(&agents_dir, &mut agents);
info!("Loaded {} agents from filesystem", agents.len());
agents
}
/// List all agents
#[tauri::command]
pub async fn list_agents(db: State<'_, AgentDb>) -> Result<Vec<Agent>, String> {
let conn = db.0.lock().map_err(|e| e.to_string())?;
let mut stmt = conn
.prepare("SELECT id, name, icon, system_prompt, default_task, model, enable_file_read, enable_file_write, enable_network, hooks, created_at, updated_at FROM agents ORDER BY created_at DESC")
.map_err(|e| e.to_string())?;
let mut agents = stmt
.query_map([], |row| {
Ok(Agent {
id: Some(row.get(0)?),
name: row.get(1)?,
icon: row.get(2)?,
system_prompt: row.get(3)?,
default_task: row.get(4)?,
model: row
.get::<_, String>(5)
.unwrap_or_else(|_| "sonnet".to_string()),
enable_file_read: row.get::<_, bool>(6).unwrap_or(true),
enable_file_write: row.get::<_, bool>(7).unwrap_or(true),
enable_network: row.get::<_, bool>(8).unwrap_or(false),
hooks: row.get(9)?,
created_at: row.get(10)?,
updated_at: row.get(11)?,
source: Some("database".to_string()),
file_path: None,
})
})
.map_err(|e| e.to_string())?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| e.to_string())?;
// Load agents from filesystem
let filesystem_agents = load_filesystem_agents();
// Combine agents from both sources
agents.extend(filesystem_agents);
Ok(agents)
}
/// Create a new agent
#[tauri::command]
pub async fn create_agent(
db: State<'_, AgentDb>,
name: String,
icon: String,
system_prompt: String,
default_task: Option<String>,
model: Option<String>,
enable_file_read: Option<bool>,
enable_file_write: Option<bool>,
enable_network: Option<bool>,
hooks: Option<String>,
) -> Result<Agent, String> {
let conn = db.0.lock().map_err(|e| e.to_string())?;
let model = model.unwrap_or_else(|| "sonnet".to_string());
let enable_file_read = enable_file_read.unwrap_or(true);
let enable_file_write = enable_file_write.unwrap_or(true);
let enable_network = enable_network.unwrap_or(false);
conn.execute(
"INSERT INTO agents (name, icon, system_prompt, default_task, model, enable_file_read, enable_file_write, enable_network, hooks) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
params![name, icon, system_prompt, default_task, model, enable_file_read, enable_file_write, enable_network, hooks],
)
.map_err(|e| e.to_string())?;
let id = conn.last_insert_rowid();
// Fetch the created agent
let agent = conn
.query_row(
"SELECT id, name, icon, system_prompt, default_task, model, enable_file_read, enable_file_write, enable_network, hooks, created_at, updated_at FROM agents WHERE id = ?1",
params![id],
|row| {
Ok(Agent {
id: Some(row.get(0)?),
name: row.get(1)?,
icon: row.get(2)?,
system_prompt: row.get(3)?,
default_task: row.get(4)?,
model: row.get(5)?,
enable_file_read: row.get(6)?,
enable_file_write: row.get(7)?,
enable_network: row.get(8)?,
hooks: row.get(9)?,
created_at: row.get(10)?,
updated_at: row.get(11)?,
source: Some("database".to_string()),
file_path: None,
})
},
)
.map_err(|e| e.to_string())?;
Ok(agent)
}
/// Update an existing agent
#[tauri::command]
pub async fn update_agent(
db: State<'_, AgentDb>,
id: i64,
name: String,
icon: String,
system_prompt: String,
default_task: Option<String>,
model: Option<String>,
enable_file_read: Option<bool>,
enable_file_write: Option<bool>,
enable_network: Option<bool>,
hooks: Option<String>,
) -> Result<Agent, String> {
let conn = db.0.lock().map_err(|e| e.to_string())?;
let model = model.unwrap_or_else(|| "sonnet".to_string());
// Build dynamic query based on provided parameters
let mut query =
"UPDATE agents SET name = ?1, icon = ?2, system_prompt = ?3, default_task = ?4, model = ?5, hooks = ?6"
.to_string();
let mut params_vec: Vec<Box<dyn rusqlite::ToSql>> = vec![
Box::new(name),
Box::new(icon),
Box::new(system_prompt),
Box::new(default_task),
Box::new(model),
Box::new(hooks),
];
let mut param_count = 6;
if let Some(efr) = enable_file_read {
param_count += 1;
query.push_str(&format!(", enable_file_read = ?{}", param_count));
params_vec.push(Box::new(efr));
}
if let Some(efw) = enable_file_write {
param_count += 1;
query.push_str(&format!(", enable_file_write = ?{}", param_count));
params_vec.push(Box::new(efw));
}
if let Some(en) = enable_network {
param_count += 1;
query.push_str(&format!(", enable_network = ?{}", param_count));
params_vec.push(Box::new(en));
}
param_count += 1;
query.push_str(&format!(" WHERE id = ?{}", param_count));
params_vec.push(Box::new(id));
conn.execute(
&query,
rusqlite::params_from_iter(params_vec.iter().map(|p| p.as_ref())),
)
.map_err(|e| e.to_string())?;
// Fetch the updated agent
let agent = conn
.query_row(
"SELECT id, name, icon, system_prompt, default_task, model, enable_file_read, enable_file_write, enable_network, hooks, created_at, updated_at FROM agents WHERE id = ?1",
params![id],
|row| {
Ok(Agent {
id: Some(row.get(0)?),
name: row.get(1)?,
icon: row.get(2)?,
system_prompt: row.get(3)?,
default_task: row.get(4)?,
model: row.get(5)?,
enable_file_read: row.get(6)?,
enable_file_write: row.get(7)?,
enable_network: row.get(8)?,
hooks: row.get(9)?,
created_at: row.get(10)?,
updated_at: row.get(11)?,
source: Some("database".to_string()),
file_path: None,
})
},
)
.map_err(|e| e.to_string())?;
Ok(agent)
}
/// Delete an agent
#[tauri::command]
pub async fn delete_agent(db: State<'_, AgentDb>, id: i64) -> Result<(), String> {
let conn = db.0.lock().map_err(|e| e.to_string())?;
conn.execute("DELETE FROM agents WHERE id = ?1", params![id])
.map_err(|e| e.to_string())?;
Ok(())
}
/// Get a single agent by ID
#[tauri::command]
pub async fn get_agent(db: State<'_, AgentDb>, id: i64) -> Result<Agent, String> {
let conn = db.0.lock().map_err(|e| e.to_string())?;
let agent = conn
.query_row(
"SELECT id, name, icon, system_prompt, default_task, model, enable_file_read, enable_file_write, enable_network, hooks, created_at, updated_at FROM agents WHERE id = ?1",
params![id],
|row| {
Ok(Agent {
id: Some(row.get(0)?),
name: row.get(1)?,
icon: row.get(2)?,
system_prompt: row.get(3)?,
default_task: row.get(4)?,
model: row.get::<_, String>(5).unwrap_or_else(|_| "sonnet".to_string()),
enable_file_read: row.get::<_, bool>(6).unwrap_or(true),
enable_file_write: row.get::<_, bool>(7).unwrap_or(true),
enable_network: row.get::<_, bool>(8).unwrap_or(false),
hooks: row.get(9)?,
created_at: row.get(10)?,
updated_at: row.get(11)?,
source: Some("database".to_string()),
file_path: None,
})
},
)
.map_err(|e| e.to_string())?;
Ok(agent)
}
/// List agent runs (optionally filtered by agent_id)
#[tauri::command]
pub async fn list_agent_runs(
db: State<'_, AgentDb>,
agent_id: Option<i64>,
) -> Result<Vec<AgentRun>, String> {
let conn = db.0.lock().map_err(|e| e.to_string())?;
let query = if agent_id.is_some() {
"SELECT id, agent_id, agent_name, agent_icon, task, model, project_path, session_id, status, pid, process_started_at, created_at, completed_at
FROM agent_runs WHERE agent_id = ?1 ORDER BY created_at DESC"
} else {
"SELECT id, agent_id, agent_name, agent_icon, task, model, project_path, session_id, status, pid, process_started_at, created_at, completed_at
FROM agent_runs ORDER BY created_at DESC"
};
let mut stmt = conn.prepare(query).map_err(|e| e.to_string())?;
let run_mapper = |row: &rusqlite::Row| -> rusqlite::Result<AgentRun> {
Ok(AgentRun {
id: Some(row.get(0)?),
agent_id: row.get(1)?,
agent_name: row.get(2)?,
agent_icon: row.get(3)?,
task: row.get(4)?,
model: row.get(5)?,
project_path: row.get(6)?,
session_id: row.get(7)?,
status: row
.get::<_, String>(8)
.unwrap_or_else(|_| "pending".to_string()),
pid: row
.get::<_, Option<i64>>(9)
.ok()
.flatten()
.map(|p| p as u32),
process_started_at: row.get(10)?,
created_at: row.get(11)?,
completed_at: row.get(12)?,
})
};
let runs = if let Some(aid) = agent_id {
stmt.query_map(params![aid], run_mapper)
} else {
stmt.query_map(params![], run_mapper)
}
.map_err(|e| e.to_string())?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| e.to_string())?;
Ok(runs)
}
/// Get a single agent run by ID
#[tauri::command]
pub async fn get_agent_run(db: State<'_, AgentDb>, id: i64) -> Result<AgentRun, String> {
let conn = db.0.lock().map_err(|e| e.to_string())?;
let run = conn
.query_row(
"SELECT id, agent_id, agent_name, agent_icon, task, model, project_path, session_id, status, pid, process_started_at, created_at, completed_at
FROM agent_runs WHERE id = ?1",
params![id],
|row| {
Ok(AgentRun {
id: Some(row.get(0)?),
agent_id: row.get(1)?,
agent_name: row.get(2)?,
agent_icon: row.get(3)?,
task: row.get(4)?,
model: row.get(5)?,
project_path: row.get(6)?,
session_id: row.get(7)?,
status: row.get::<_, String>(8).unwrap_or_else(|_| "pending".to_string()),
pid: row.get::<_, Option<i64>>(9).ok().flatten().map(|p| p as u32),
process_started_at: row.get(10)?,
created_at: row.get(11)?,
completed_at: row.get(12)?,
})
},
)
.map_err(|e| e.to_string())?;
Ok(run)
}
/// Get agent run with real-time metrics from JSONL
#[tauri::command]
pub async fn get_agent_run_with_real_time_metrics(
db: State<'_, AgentDb>,
id: i64,
) -> Result<AgentRunWithMetrics, String> {
let run = get_agent_run(db, id).await?;
Ok(get_agent_run_with_metrics(run).await)
}
/// List agent runs with real-time metrics from JSONL
#[tauri::command]
pub async fn list_agent_runs_with_metrics(
db: State<'_, AgentDb>,
agent_id: Option<i64>,
) -> Result<Vec<AgentRunWithMetrics>, String> {
let runs = list_agent_runs(db, agent_id).await?;
let mut runs_with_metrics = Vec::new();
for run in runs {
let run_with_metrics = get_agent_run_with_metrics(run).await;
runs_with_metrics.push(run_with_metrics);
}
Ok(runs_with_metrics)
}
/// Execute a CC agent with streaming output
#[tauri::command]
pub async fn execute_agent(
app: AppHandle,
agent_id: i64,
project_path: String,
task: String,
model: Option<String>,
db: State<'_, AgentDb>,
registry: State<'_, crate::process::ProcessRegistryState>,
) -> Result<i64, String> {
info!("Executing agent {} with task: {}", agent_id, task);
// Get the agent from database
let agent = get_agent(db.clone(), agent_id).await?;
let execution_model = model.unwrap_or(agent.model.clone());
// Create .claude/settings.json with agent hooks if it doesn't exist
if let Some(hooks_json) = &agent.hooks {
let claude_dir = std::path::Path::new(&project_path).join(".claude");
let settings_path = claude_dir.join("settings.json");
// Create .claude directory if it doesn't exist
if !claude_dir.exists() {
std::fs::create_dir_all(&claude_dir)
.map_err(|e| format!("Failed to create .claude directory: {}", e))?;
info!("Created .claude directory at: {:?}", claude_dir);
}
// Check if settings.json already exists
if !settings_path.exists() {
// Parse the hooks JSON
let hooks: serde_json::Value = serde_json::from_str(hooks_json)
.map_err(|e| format!("Failed to parse agent hooks: {}", e))?;
// Create a settings object with just the hooks
let settings = serde_json::json!({
"hooks": hooks
});
// Write the settings file
let settings_content = serde_json::to_string_pretty(&settings)
.map_err(|e| format!("Failed to serialize settings: {}", e))?;
std::fs::write(&settings_path, settings_content)
.map_err(|e| format!("Failed to write settings.json: {}", e))?;
info!(
"Created settings.json with agent hooks at: {:?}",
settings_path
);
} else {
info!("settings.json already exists at: {:?}", settings_path);
}
}
// Create a new run record
let run_id = {
let conn = db.0.lock().map_err(|e| e.to_string())?;
conn.execute(
"INSERT INTO agent_runs (agent_id, agent_name, agent_icon, task, model, project_path, session_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![agent_id, agent.name, agent.icon, task, execution_model, project_path, ""],
)
.map_err(|e| e.to_string())?;
conn.last_insert_rowid()
};
// Find Claude binary
info!("Running agent '{}'", agent.name);
let claude_path = match find_claude_binary(&app) {
Ok(path) => path,
Err(e) => {
error!("Failed to find claude binary: {}", e);
return Err(e);
}
};
// Build arguments
let args = vec![
"-p".to_string(),
task.clone(),
"--system-prompt".to_string(),
agent.system_prompt.clone(),
"--model".to_string(),
execution_model.clone(),
"--output-format".to_string(),
"stream-json".to_string(),
"--verbose".to_string(),
"--dangerously-skip-permissions".to_string(),
];
// Always use system binary execution (sidecar removed)
spawn_agent_system(
app,
run_id,
agent_id,
agent.name.clone(),
claude_path,
args,
project_path,
task,
execution_model,
db,
registry,
)
.await
}
/// Creates a system binary command for agent execution
fn create_agent_system_command(
claude_path: &str,
args: Vec<String>,
project_path: &str,
) -> Command {
let mut cmd = create_command_with_env(claude_path);
// Add all arguments
for arg in args {
cmd.arg(arg);
}
cmd.current_dir(project_path)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
cmd
}
/// Spawn agent using system binary command
async fn spawn_agent_system(
app: AppHandle,
run_id: i64,
agent_id: i64,
agent_name: String,
claude_path: String,
args: Vec<String>,
project_path: String,
task: String,
execution_model: String,
db: State<'_, AgentDb>,
registry: State<'_, crate::process::ProcessRegistryState>,
) -> Result<i64, String> {
// Build the command
let mut cmd = create_agent_system_command(&claude_path, args, &project_path);
// Spawn the process
info!("🚀 Spawning Claude system process...");
let mut child = cmd.spawn().map_err(|e| {
error!("❌ Failed to spawn Claude process: {}", e);
format!("Failed to spawn Claude: {}", e)
})?;
info!("🔌 Using Stdio::null() for stdin - no input expected");
// Get the PID and register the process
let pid = child.id().unwrap_or(0);
let now = chrono::Utc::now().to_rfc3339();
info!("✅ Claude process spawned successfully with PID: {}", pid);
// Update the database with PID and status
{
let conn = db.0.lock().map_err(|e| e.to_string())?;
conn.execute(
"UPDATE agent_runs SET status = 'running', pid = ?1, process_started_at = ?2 WHERE id = ?3",
params![pid as i64, now, run_id],
).map_err(|e| e.to_string())?;
info!("📝 Updated database with running status and PID");
}
// Get stdout and stderr
let stdout = child.stdout.take().ok_or("Failed to get stdout")?;
let stderr = child.stderr.take().ok_or("Failed to get stderr")?;
info!("📡 Set up stdout/stderr readers");
// Create readers
let stdout_reader = TokioBufReader::new(stdout);
let stderr_reader = TokioBufReader::new(stderr);