-
Notifications
You must be signed in to change notification settings - Fork 336
Expand file tree
/
Copy pathagents.rs
More file actions
2173 lines (1940 loc) · 71.3 KB
/
agents.rs
File metadata and controls
2173 lines (1940 loc) · 71.3 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 super::state::{AgentInfo, ApiState};
use crate::agent::cortex::CortexLogger;
use crate::conversation::channels::ChannelStore;
use axum::Json;
use axum::extract::{Query, State};
use axum::http::StatusCode;
use serde::{Deserialize, Serialize};
use sqlx::Row as _;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
fn hosted_agent_limit() -> Option<usize> {
let deployment = std::env::var("SPACEBOT_DEPLOYMENT").ok()?;
if !deployment.eq_ignore_ascii_case("hosted") {
return None;
}
std::env::var("SPACEBOT_MAX_AGENTS")
.ok()
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| *value > 0)
}
#[derive(Serialize, utoipa::ToSchema)]
pub(super) struct AgentsResponse {
agents: Vec<AgentInfo>,
}
#[derive(Serialize, utoipa::ToSchema)]
pub(super) struct AgentOverviewResponse {
memory_counts: HashMap<String, i64>,
memory_total: i64,
channel_count: usize,
cron_jobs: Vec<CronJobInfo>,
last_bulletin_at: Option<String>,
recent_cortex_events: Vec<crate::agent::cortex::CortexEvent>,
memory_daily: Vec<DayCount>,
activity_daily: Vec<ActivityDayCount>,
activity_heatmap: Vec<HeatmapCell>,
latest_bulletin: Option<String>,
}
#[derive(Serialize, utoipa::ToSchema)]
struct DayCount {
date: String,
count: i64,
}
#[derive(Serialize, utoipa::ToSchema)]
struct ActivityDayCount {
date: String,
branches: i64,
workers: i64,
}
#[derive(Serialize, utoipa::ToSchema)]
struct HeatmapCell {
day: i64,
hour: i64,
count: i64,
}
#[derive(Serialize, utoipa::ToSchema)]
struct CronJobInfo {
id: String,
prompt: String,
cron_expr: Option<String>,
interval_secs: u64,
delivery_target: String,
enabled: bool,
run_once: bool,
active_hours: Option<(u8, u8)>,
timeout_secs: Option<u64>,
}
#[derive(Serialize, utoipa::ToSchema)]
pub(super) struct InstanceOverviewResponse {
version: &'static str,
uptime_seconds: u64,
pid: u32,
agents: Vec<AgentSummary>,
}
#[derive(Serialize, utoipa::ToSchema)]
struct AgentSummary {
id: String,
channel_count: usize,
memory_total: i64,
cron_job_count: usize,
activity_sparkline: Vec<i64>,
last_activity_at: Option<String>,
last_bulletin_at: Option<String>,
profile: Option<crate::agent::cortex::AgentProfile>,
}
#[derive(Serialize, utoipa::ToSchema)]
pub(super) struct AgentProfileResponse {
profile: Option<crate::agent::cortex::AgentProfile>,
}
#[derive(Serialize, utoipa::ToSchema)]
pub(super) struct IdentityResponse {
soul: Option<String>,
identity: Option<String>,
role: Option<String>,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub(super) struct IdentityQuery {
agent_id: String,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub(super) struct IdentityUpdateRequest {
agent_id: String,
soul: Option<String>,
identity: Option<String>,
role: Option<String>,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub(super) struct AgentOverviewQuery {
agent_id: String,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub struct CreateAgentRequest {
pub agent_id: String,
pub display_name: Option<String>,
pub role: Option<String>,
}
/// Result from internal agent creation logic.
pub struct CreateAgentResult {
pub success: bool,
pub agent_id: String,
pub message: String,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub(super) struct UpdateAgentRequest {
agent_id: String,
display_name: Option<String>,
role: Option<String>,
gradient_start: Option<String>,
gradient_end: Option<String>,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub(super) struct DeleteAgentQuery {
agent_id: String,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub(super) struct AgentMcpQuery {
agent_id: String,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub(super) struct ReconnectMcpRequest {
agent_id: String,
server_name: String,
}
#[derive(Serialize, utoipa::ToSchema)]
pub(super) struct AgentMcpResponse {
servers: Vec<crate::mcp::McpServerStatus>,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub(super) struct WarmupQuery {
agent_id: Option<String>,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub(super) struct WarmupTriggerRequest {
agent_id: Option<String>,
#[serde(default)]
force: bool,
}
#[derive(Serialize, utoipa::ToSchema)]
pub(super) struct WarmupStatusEntry {
agent_id: String,
status: crate::config::WarmupStatus,
}
#[derive(Serialize, utoipa::ToSchema)]
pub(super) struct WarmupStatusResponse {
statuses: Vec<WarmupStatusEntry>,
}
#[derive(Serialize, utoipa::ToSchema)]
pub(super) struct WarmupTriggerResponse {
status: &'static str,
forced: bool,
accepted_agents: Vec<String>,
}
fn hydrate_warmup_status(
runtime_config: &crate::config::RuntimeConfig,
) -> crate::config::WarmupStatus {
let mut status = runtime_config.warmup_status.load().as_ref().clone();
let now_ms = chrono::Utc::now().timestamp_millis();
status.bulletin_age_secs = compute_bulletin_age_secs(status.last_refresh_unix_ms, now_ms);
status
}
fn compute_bulletin_age_secs(last_refresh_unix_ms: Option<i64>, now_unix_ms: i64) -> Option<u64> {
last_refresh_unix_ms.map(|refresh_ms| {
if now_unix_ms > refresh_ms {
((now_unix_ms - refresh_ms) / 1000) as u64
} else {
0
}
})
}
fn resolve_warmup_agent_ids(
requested_agent_id: Option<&str>,
runtime_config_ids: &HashSet<String>,
memory_search_ids: &HashSet<String>,
mcp_manager_ids: &HashSet<String>,
sqlite_pool_ids: &HashSet<String>,
) -> Result<Vec<String>, StatusCode> {
let target_agent_ids = if let Some(agent_id) = requested_agent_id {
vec![agent_id.to_string()]
} else {
runtime_config_ids.iter().cloned().collect::<Vec<_>>()
};
let single_target = requested_agent_id.is_some();
let mut accepted_agents = Vec::new();
for agent_id in target_agent_ids {
if !runtime_config_ids.contains(&agent_id) {
if single_target {
return Err(StatusCode::NOT_FOUND);
}
continue;
}
if !memory_search_ids.contains(&agent_id) {
tracing::warn!(agent_id = %agent_id, "missing memory search for warmup trigger");
if single_target {
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
continue;
}
if !mcp_manager_ids.contains(&agent_id) {
tracing::warn!(agent_id = %agent_id, "missing mcp manager for warmup trigger");
if single_target {
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
continue;
}
if !sqlite_pool_ids.contains(&agent_id) {
tracing::warn!(agent_id = %agent_id, "missing sqlite pool for warmup trigger");
if single_target {
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
continue;
}
accepted_agents.push(agent_id);
}
Ok(accepted_agents)
}
/// List all configured agents with their config summaries.
#[utoipa::path(
get,
path = "/agents",
responses(
(status = 200, body = AgentsResponse),
),
tag = "agents",
)]
pub(super) async fn list_agents(State(state): State<Arc<ApiState>>) -> Json<AgentsResponse> {
let agents = state.agent_configs.load();
Json(AgentsResponse {
agents: agents.as_ref().clone(),
})
}
/// List MCP connection status for an agent.
#[utoipa::path(
get,
path = "/agents/mcp",
params(
("agent_id" = String, Query, description = "Agent ID"),
),
responses(
(status = 200, body = AgentMcpResponse),
(status = 404, description = "Agent not found"),
),
tag = "agents",
)]
pub(super) async fn list_agent_mcp(
State(state): State<Arc<ApiState>>,
Query(query): Query<AgentMcpQuery>,
) -> Result<Json<AgentMcpResponse>, StatusCode> {
let managers = state.mcp_managers.load();
let manager = managers
.get(&query.agent_id)
.cloned()
.ok_or(StatusCode::NOT_FOUND)?;
let servers = manager.statuses().await;
Ok(Json(AgentMcpResponse { servers }))
}
/// Force reconnect for a single MCP server on an agent.
#[utoipa::path(
post,
path = "/agents/mcp/reconnect",
request_body = ReconnectMcpRequest,
responses(
(status = 200, body = serde_json::Value),
(status = 404, description = "Agent not found"),
(status = 400, description = "Failed to reconnect"),
),
tag = "agents",
)]
pub(super) async fn reconnect_agent_mcp(
State(state): State<Arc<ApiState>>,
Json(request): Json<ReconnectMcpRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let managers = state.mcp_managers.load();
let manager = managers
.get(&request.agent_id)
.cloned()
.ok_or(StatusCode::NOT_FOUND)?;
manager
.reconnect(&request.server_name)
.await
.map_err(|error| {
tracing::warn!(
%error,
agent_id = %request.agent_id,
server_name = %request.server_name,
"failed to reconnect mcp server"
);
StatusCode::BAD_REQUEST
})?;
Ok(Json(serde_json::json!({
"success": true,
"agent_id": request.agent_id,
"server_name": request.server_name
})))
}
/// Get warmup status for one agent or all agents.
#[utoipa::path(
get,
path = "/agents/warmup",
params(
("agent_id" = Option<String>, Query, description = "Optional agent ID to get status for a specific agent"),
),
responses(
(status = 200, body = WarmupStatusResponse),
(status = 404, description = "Agent not found"),
),
tag = "agents",
)]
pub(super) async fn get_warmup_status(
State(state): State<Arc<ApiState>>,
Query(query): Query<WarmupQuery>,
) -> Result<Json<WarmupStatusResponse>, StatusCode> {
let runtime_configs = state.runtime_configs.load();
let mut statuses = if let Some(agent_id) = query.agent_id {
let runtime_config = runtime_configs
.get(&agent_id)
.ok_or(StatusCode::NOT_FOUND)?;
vec![WarmupStatusEntry {
agent_id,
status: hydrate_warmup_status(runtime_config),
}]
} else {
runtime_configs
.iter()
.map(|(agent_id, runtime_config)| WarmupStatusEntry {
agent_id: agent_id.clone(),
status: hydrate_warmup_status(runtime_config),
})
.collect::<Vec<_>>()
};
statuses.sort_by(|left, right| left.agent_id.cmp(&right.agent_id));
Ok(Json(WarmupStatusResponse { statuses }))
}
/// Trigger warmup for one agent or all agents.
#[utoipa::path(
post,
path = "/agents/warmup/trigger",
request_body = WarmupTriggerRequest,
responses(
(status = 200, body = WarmupTriggerResponse),
(status = 503, description = "LLM manager not available"),
(status = 404, description = "Agent not found"),
),
tag = "agents",
)]
pub(super) async fn trigger_warmup(
State(state): State<Arc<ApiState>>,
Json(request): Json<WarmupTriggerRequest>,
) -> Result<Json<WarmupTriggerResponse>, StatusCode> {
let llm_manager = {
let guard = state.llm_manager.read().await;
guard.as_ref().cloned().ok_or_else(|| {
tracing::error!("LLM manager not available for warmup trigger");
StatusCode::SERVICE_UNAVAILABLE
})?
};
let runtime_configs = state.runtime_configs.load();
let memory_searches = state.memory_searches.load();
let mcp_managers = state.mcp_managers.load();
let pools = state.agent_pools.load();
let sandboxes = state.sandboxes.load();
let runtime_config_ids = runtime_configs.keys().cloned().collect::<HashSet<_>>();
let memory_search_ids = memory_searches.keys().cloned().collect::<HashSet<_>>();
let mcp_manager_ids = mcp_managers.keys().cloned().collect::<HashSet<_>>();
let sqlite_pool_ids = pools.keys().cloned().collect::<HashSet<_>>();
let accepted_agents = resolve_warmup_agent_ids(
request.agent_id.as_deref(),
&runtime_config_ids,
&memory_search_ids,
&mcp_manager_ids,
&sqlite_pool_ids,
)?;
for agent_id in accepted_agents.iter() {
let Some(runtime_config) = runtime_configs.get(agent_id).cloned() else {
continue;
};
let Some(memory_search) = memory_searches.get(agent_id).cloned() else {
continue;
};
let Some(mcp_manager) = mcp_managers.get(agent_id).cloned() else {
continue;
};
let Some(sqlite_pool) = pools.get(agent_id).cloned() else {
continue;
};
let Some(sandbox) = sandboxes.get(agent_id).cloned() else {
continue;
};
let Some(task_store) = state.task_store.load().as_ref().clone() else {
tracing::warn!(
agent_id,
"global task store not initialized, skipping warmup"
);
continue;
};
let llm_manager = llm_manager.clone();
let force = request.force;
let agent_id = agent_id.clone();
let injection_tx = state.injection_tx.clone();
let humans = (**state.agent_humans.load()).clone();
tokio::spawn(async move {
let (event_tx, memory_event_tx) = crate::create_process_event_buses();
let project_store =
std::sync::Arc::new(crate::projects::ProjectStore::new(sqlite_pool.clone()));
let working_memory_tz = runtime_config
.user_timezone
.load()
.as_deref()
.or(runtime_config.cron_timezone.load().as_deref())
.and_then(|tz| tz.parse::<chrono_tz::Tz>().ok())
.unwrap_or(chrono_tz::Tz::UTC);
let working_memory =
crate::memory::WorkingMemoryStore::new(sqlite_pool.clone(), working_memory_tz);
let deps = crate::AgentDeps {
agent_id: Arc::from(agent_id.as_str()),
memory_search,
llm_manager,
mcp_manager,
cron_tool: None,
runtime_config,
event_tx,
memory_event_tx,
sqlite_pool: sqlite_pool.clone(),
messaging_manager: None,
sandbox,
task_store,
project_store,
links: Arc::new(arc_swap::ArcSwap::from_pointee(Vec::new())),
agent_names: Arc::new(std::collections::HashMap::new()),
humans: Arc::new(arc_swap::ArcSwap::from_pointee(humans)),
process_control_registry: Arc::new(
crate::agent::process_control::ProcessControlRegistry::new(),
),
injection_tx,
working_memory,
};
let logger = CortexLogger::new(sqlite_pool);
crate::agent::cortex::run_warmup_once(&deps, &logger, "api_trigger", force).await;
});
}
Ok(Json(WarmupTriggerResponse {
status: "warming",
forced: request.force,
accepted_agents,
}))
}
/// Create a new agent and initialize it live (directories, databases, memory, identity, cron, cortex).
#[utoipa::path(
post,
path = "/agents",
request_body = CreateAgentRequest,
responses(
(status = 201, body = serde_json::Value, description = "Agent created successfully"),
(status = 400, description = "Invalid request or agent limit reached"),
(status = 409, description = "Agent already exists"),
(status = 500, description = "Internal server error"),
),
tag = "agents",
)]
pub(super) async fn create_agent(
State(state): State<Arc<ApiState>>,
Json(request): Json<CreateAgentRequest>,
) -> (StatusCode, Json<serde_json::Value>) {
match create_agent_internal(&state, request).await {
Ok(result) => (
StatusCode::CREATED,
Json(serde_json::json!({
"success": result.success,
"agent_id": result.agent_id,
"message": result.message
})),
),
Err(message) => {
let status = if message.contains("already exists") {
StatusCode::CONFLICT
} else if message.contains("cannot be empty") || message.contains("agent limit") {
StatusCode::BAD_REQUEST
} else {
StatusCode::INTERNAL_SERVER_ERROR
};
(
status,
Json(serde_json::json!({
"success": false,
"message": message
})),
)
}
}
}
/// Internal agent creation logic shared between the API handler and factory tools.
pub async fn create_agent_internal(
state: &Arc<ApiState>,
request: CreateAgentRequest,
) -> Result<CreateAgentResult, String> {
if let Some(limit) = hosted_agent_limit() {
let existing = state.agent_configs.load();
if existing.len() >= limit {
return Err(format!(
"agent limit reached for this instance: up to {limit} agent{}",
if limit == 1 { "" } else { "s" }
));
}
}
let agent_id = request.agent_id.trim().to_string();
if agent_id.is_empty() {
return Err("Agent ID cannot be empty".into());
}
{
let existing = state.agent_configs.load();
if existing.iter().any(|a| a.id == agent_id) {
return Err(format!("Agent '{agent_id}' already exists"));
}
}
let config_path = state.config_path.read().await.clone();
let instance_dir = (**state.instance_dir.load()).clone();
// Acquire the config write mutex to prevent concurrent read-modify-write races.
let _config_guard = state.config_write_mutex.lock().await;
// Fail early if messaging manager is unavailable — before any config write,
// directory creation, or database init that would leave a half-created agent.
let messaging_manager = {
let guard = state.messaging_manager.read().await;
guard
.as_ref()
.cloned()
.ok_or_else(|| {
"Messaging manager not initialized. Please ensure messaging adapters are configured before creating agents.".to_string()
})?
};
let content = if config_path.exists() {
tokio::fs::read_to_string(&config_path)
.await
.map_err(|error| {
tracing::warn!(%error, "failed to read config.toml");
format!("failed to read config.toml: {error}")
})?
} else {
String::new()
};
let mut doc: toml_edit::DocumentMut = content.parse().map_err(|error| {
tracing::warn!(%error, "failed to parse config.toml");
format!("failed to parse config.toml: {error}")
})?;
if doc.get("agents").is_none() {
doc["agents"] = toml_edit::Item::ArrayOfTables(toml_edit::ArrayOfTables::new());
}
let agents_array = doc["agents"]
.as_array_of_tables_mut()
.ok_or_else(|| "agents is not an array of tables in config.toml".to_string())?;
// Revalidate uniqueness under the lock — another request may have written the
// same agent_id to config.toml between our first check and mutex acquisition.
// Check against the parsed TOML document (agents_array) rather than the stale
// in-memory cache to ensure we catch concurrent writes.
if agents_array.iter().any(|t| {
t.get("id")
.and_then(|v| v.as_str())
.map(|id| id == agent_id)
.unwrap_or(false)
}) {
return Err(format!("Agent '{agent_id}' already exists"));
}
let mut new_table = toml_edit::Table::new();
new_table["id"] = toml_edit::value(&agent_id);
if let Some(display_name) = &request.display_name
&& !display_name.is_empty()
{
new_table["display_name"] = toml_edit::value(display_name.as_str());
}
if let Some(role) = &request.role
&& !role.is_empty()
{
new_table["role"] = toml_edit::value(role.as_str());
}
agents_array.push(new_table);
tokio::fs::write(&config_path, doc.to_string())
.await
.map_err(|error| {
tracing::warn!(%error, "failed to write config.toml");
format!("failed to write config.toml: {error}")
})?;
// Release the config write mutex — remaining work doesn't touch config.toml.
drop(_config_guard);
// Read defaults directly from the config we just wrote to disk rather than
// relying on the cached `defaults_config` which may be stale (e.g. if a
// provider was configured but the in-memory cache wasn't refreshed yet).
let disk_defaults = match crate::config::Config::load_from_path(&config_path) {
Ok(fresh_config) => {
// Also update the in-memory cache so subsequent operations
// (e.g. creating another agent) don't hit stale defaults.
state
.set_defaults_config(fresh_config.defaults.clone())
.await;
Some(fresh_config.defaults)
}
Err(error) => {
tracing::warn!(
%error,
"failed to reload config.toml for defaults; falling back to cached defaults"
);
None
}
};
let cached_defaults;
let defaults = if let Some(ref d) = disk_defaults {
d
} else {
cached_defaults = state.defaults_config.read().await;
cached_defaults.as_ref().ok_or_else(|| {
tracing::error!("defaults config not available");
"defaults config not available".to_string()
})?
};
let raw_config = crate::config::AgentConfig {
id: agent_id.clone(),
default: false,
display_name: request.display_name.clone().filter(|s| !s.is_empty()),
role: request.role.clone().filter(|s| !s.is_empty()),
gradient_start: None,
gradient_end: None,
workspace: None,
routing: None,
max_concurrent_branches: None,
max_concurrent_workers: None,
max_turns: None,
branch_max_turns: None,
context_window: None,
tool_use_enforcement: None,
compaction: None,
memory_persistence: None,
coalesce: None,
ingestion: None,
cortex: None,
warmup: None,
browser: None,
channel: None,
mcp: None,
brave_search_key: None,
cron_timezone: None,
user_timezone: None,
sandbox: None,
projects: None,
cron: Vec::new(),
};
let agent_config = raw_config.resolve(&instance_dir, defaults);
for dir in [
&agent_config.workspace,
&agent_config.data_dir,
&agent_config.archives_dir,
&agent_config.ingest_dir(),
&agent_config.logs_dir(),
] {
std::fs::create_dir_all(dir).map_err(|error| {
tracing::error!(%error, dir = %dir.display(), "failed to create agent directory");
format!("failed to create directory {}: {error}", dir.display())
})?;
}
let db = crate::db::Db::connect(&agent_config.data_dir)
.await
.map_err(|error| {
tracing::error!(%error, agent_id = %agent_id, "failed to connect agent databases");
format!("failed to connect databases: {error}")
})?;
let settings_path = agent_config.data_dir.join("settings.redb");
let settings_store = std::sync::Arc::new(
crate::settings::SettingsStore::new(&settings_path).map_err(|error| {
tracing::error!(%error, agent_id = %agent_id, "failed to init settings store");
format!("failed to init settings store: {error}")
})?,
);
let embedding_model = {
let guard = state.embedding_model.read().await;
guard
.as_ref()
.ok_or_else(|| {
tracing::error!("embedding model not available");
"embedding model not available".to_string()
})?
.clone()
};
let memory_store = crate::memory::MemoryStore::new(db.sqlite.clone());
let embedding_table = crate::memory::EmbeddingTable::open_or_create(&db.lance)
.await
.map_err(|error| {
tracing::error!(%error, agent_id = %agent_id, "failed to init embeddings");
format!("failed to init embeddings: {error}")
})?;
if let Err(error) = embedding_table.ensure_fts_index().await {
tracing::warn!(%error, agent_id = %agent_id, "failed to create FTS index");
}
let memory_search = std::sync::Arc::new(crate::memory::MemorySearch::new(
memory_store,
embedding_table,
embedding_model,
));
let task_store = state
.task_store
.load()
.as_ref()
.clone()
.ok_or_else(|| "global task store not initialized".to_string())?;
let (event_tx, memory_event_tx) = crate::create_process_event_buses();
let arc_agent_id: crate::AgentId = std::sync::Arc::from(agent_id.as_str());
crate::identity::scaffold_identity_files(&agent_config.identity_dir)
.await
.map_err(|error| {
tracing::error!(%error, agent_id = %agent_id, "failed to scaffold identity files");
format!("failed to scaffold identity files: {error}")
})?;
let identity = crate::identity::Identity::load(&agent_config.identity_dir).await;
let skills =
crate::skills::SkillSet::load(&instance_dir.join("skills"), &agent_config.skills_dir())
.await;
let prompt_engine = {
let guard = state.prompt_engine.read().await;
guard
.as_ref()
.ok_or_else(|| {
tracing::error!("prompt engine not available");
"prompt engine not available".to_string()
})?
.clone()
};
let defaults_for_runtime = if let Some(d) = disk_defaults {
d
} else {
let guard = state.defaults_config.read().await;
guard
.as_ref()
.ok_or_else(|| {
tracing::error!("defaults config not available");
"defaults config not available".to_string()
})?
.clone()
};
let runtime_config = std::sync::Arc::new(crate::config::RuntimeConfig::new(
&instance_dir,
&agent_config,
&defaults_for_runtime,
prompt_engine,
identity,
skills,
));
runtime_config.set_settings(settings_store.clone());
let llm_manager = {
let guard = state.llm_manager.read().await;
guard
.as_ref()
.ok_or_else(|| {
tracing::error!("LLM manager not available");
"LLM manager not available".to_string()
})?
.clone()
};
let mcp_manager = std::sync::Arc::new(crate::mcp::McpManager::new(agent_config.mcp.clone()));
mcp_manager.connect_all().await;
let sandbox = std::sync::Arc::new(
crate::sandbox::Sandbox::new(
runtime_config.sandbox.clone(),
agent_config.workspace.clone(),
&instance_dir,
agent_config.data_dir.clone(),
)
.await,
);
let project_store = std::sync::Arc::new(crate::projects::ProjectStore::new(db.sqlite.clone()));
// Inject active project root paths into the sandbox allowlist.
crate::projects::refresh_sandbox_project_paths(&project_store, &arc_agent_id, &sandbox).await;
let deps = crate::AgentDeps {
agent_id: arc_agent_id.clone(),
memory_search: memory_search.clone(),
llm_manager,
mcp_manager: mcp_manager.clone(),
task_store: task_store.clone(),
project_store: project_store.clone(),
cron_tool: None,
runtime_config: runtime_config.clone(),
event_tx: event_tx.clone(),
memory_event_tx: memory_event_tx.clone(),
sqlite_pool: db.sqlite.clone(),
messaging_manager: Some(messaging_manager.clone()),
sandbox: sandbox.clone(),
links: Arc::new(arc_swap::ArcSwap::from_pointee(
(**state.agent_links.load()).clone(),
)),
process_control_registry: Arc::new(
crate::agent::process_control::ProcessControlRegistry::new(),
),
injection_tx: state.injection_tx.clone(),
agent_names: {
let configs = state.agent_configs.load();
let mut names: std::collections::HashMap<String, String> = configs
.iter()
.map(|c| {
(
c.id.clone(),
c.display_name.clone().unwrap_or_else(|| c.id.clone()),
)
})
.collect();
names.entry(agent_id.clone()).or_insert_with(|| {
request
.display_name
.clone()
.filter(|s| !s.is_empty())
.unwrap_or_else(|| agent_id.clone())
});
Arc::new(names)
},
humans: Arc::new(arc_swap::ArcSwap::from_pointee(
(**state.agent_humans.load()).clone(),
)),
working_memory: {
let tz = agent_config
.user_timezone
.as_deref()
.or(agent_config.cron_timezone.as_deref())
.and_then(|tz| tz.parse::<chrono_tz::Tz>().ok())
.unwrap_or(chrono_tz::Tz::UTC);
crate::memory::WorkingMemoryStore::new(db.sqlite.clone(), tz)
},
};
let event_rx = event_tx.subscribe();
state.register_agent_events(agent_id.clone(), event_rx);
let cron_store = std::sync::Arc::new(crate::cron::CronStore::new(db.sqlite.clone()));
let cron_context = crate::cron::CronContext {
deps: deps.clone(),
screenshot_dir: agent_config.screenshot_dir(),
logs_dir: agent_config.logs_dir(),
messaging_manager: messaging_manager.clone(),
store: cron_store.clone(),
};
let scheduler = std::sync::Arc::new(crate::cron::Scheduler::new(cron_context));
runtime_config.set_cron(cron_store.clone(), scheduler.clone());
let cron_tool =
crate::tools::CronTool::new(cron_store.clone(), scheduler.clone(), messaging_manager);
let browser_config = (**runtime_config.browser_config.load()).clone();
let brave_search_key = (**runtime_config.brave_search_key.load()).clone();
let conversation_logger =
crate::conversation::history::ConversationLogger::new(db.sqlite.clone());
let channel_store = crate::conversation::ChannelStore::new(db.sqlite.clone());
let run_logger = crate::conversation::ProcessRunLogger::new(db.sqlite.clone());
let cortex_ctx = crate::agent::cortex_chat::CortexChatSession::create_context();
let cortex_tool_server = crate::tools::create_cortex_chat_tool_server(
deps.agent_id.clone(),
deps.clone(),
deps.task_store.clone(),
memory_search.clone(),
deps.memory_event_tx.clone(),
conversation_logger,
channel_store,
run_logger,
browser_config,
agent_config.screenshot_dir(),
brave_search_key,
runtime_config.workspace_dir.clone(),
sandbox.clone(),
runtime_config.clone(),
state.clone(),
Some(cortex_ctx.clone()),
);
// Add factory tools to the cortex chat tool server
if let Err(error) =
crate::tools::add_factory_tools(&cortex_tool_server, state.clone(), memory_search.clone())
.await
{
tracing::warn!(%error, agent_id = %agent_id, "failed to add factory tools to cortex chat");
}
let cortex_store = crate::agent::cortex_chat::CortexChatStore::new(db.sqlite.clone());
let cortex_session = crate::agent::cortex_chat::CortexChatSession::new(
deps.clone(),
cortex_tool_server,
cortex_store,
cortex_ctx,
)
.with_factory(true);
let cortex_logger = crate::agent::cortex::CortexLogger::new(db.sqlite.clone());
let _warmup_loop = crate::agent::cortex::spawn_warmup_loop(deps.clone(), cortex_logger.clone());
let _cortex_loop = crate::agent::cortex::spawn_cortex_loop(deps.clone(), cortex_logger.clone());
let _association_loop =
crate::agent::cortex::spawn_association_loop(deps.clone(), cortex_logger);
crate::agent::cortex::spawn_ready_task_loop(
deps.clone(),
crate::agent::cortex::CortexLogger::new(db.sqlite.clone()),
);
let ingestion_config = **runtime_config.ingestion.load();
if ingestion_config.enabled {
crate::agent::ingestion::spawn_ingestion_loop(agent_config.ingest_dir(), deps.clone());
}