1use super::*;
2
3#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
4pub struct NotificationsConfig {
5 #[serde(default)]
6 pub on_task_complete: Vec<NotificationTarget>,
7 #[serde(default)]
8 pub on_error: Vec<NotificationTarget>,
9 #[serde(default)]
10 pub on_shutdown: Vec<NotificationTarget>,
11}
12
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
14#[serde(tag = "target", rename_all = "lowercase")]
15pub enum NotificationTarget {
16 Agent {
17 name: String,
18 },
19 Commander,
20 Email {
21 address: String,
22 #[serde(default)]
23 smtp_config_file: Option<String>,
24 },
25 Slack {
26 #[serde(default)]
27 channel: Option<String>,
28 #[serde(default)]
29 webhook_url_env: Option<String>,
30 },
31 Webpush {
32 url: String,
33 },
34 Webhook {
35 url: String,
36 #[serde(default = "default_post")]
37 method: String,
38 #[serde(default)]
39 auth: Option<String>,
40 },
41}
42fn default_post() -> String {
43 "POST".to_string()
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
47pub struct RetryConfig {
48 pub llm: RetryPolicy,
49 pub tool: RetryPolicy,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
53pub struct RetryPolicy {
54 pub max_retries: u32,
55 pub backoff: BackoffStrategy,
56 pub initial_delay_ms: u64,
57 #[serde(default)]
58 pub max_delay_ms: Option<u64>,
59 #[serde(default)]
60 pub retry_on: Vec<String>,
61}
62
63#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
64#[serde(rename_all = "lowercase")]
65pub enum BackoffStrategy {
66 Linear,
67 Exponential,
68 Fixed,
69}
70
71#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
72pub struct LifecycleConfig {
73 pub restart: RestartPolicy,
74 #[serde(default = "default_max_restarts")]
75 pub max_restarts: u32,
76 #[serde(default = "default_window")]
77 pub restart_window_secs: u64,
78 #[serde(default = "default_stop_timeout")]
79 pub stop_timeout_secs: u64,
80 #[serde(default = "default_mcp_required")]
81 pub mcp_required: bool,
82 #[serde(default)]
83 pub execution: ExecutionMode,
84 #[serde(default)]
85 pub schedule: Vec<ScheduleEntry>,
86 #[serde(default)]
87 pub idle_triggers: Vec<IdleTrigger>,
88}
89fn default_max_restarts() -> u32 {
90 3
91}
92fn default_window() -> u64 {
93 600
94}
95pub const DEFAULT_STOP_TIMEOUT_SECS: u64 = 15;
98
99fn default_stop_timeout() -> u64 {
100 DEFAULT_STOP_TIMEOUT_SECS
101}
102fn default_mcp_required() -> bool {
103 true
104}
105
106#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
107#[serde(rename_all = "snake_case")]
108pub enum RestartPolicy {
109 Never,
110 OnFailure,
111 Always,
112}
113
114#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
115#[serde(rename_all = "snake_case")]
116pub enum ExecutionMode {
117 #[default]
118 Daemon,
119 OnDemand,
120}
121
122pub const SCHEDULE_PROPOSAL_DIR: &str = "schedule-proposals";
137
138pub const SCHEDULE_CHANNEL_FILE: &str = "schedule-channel";
142
143pub const HITL_CHANNEL_FILE: &str = "hitl-channel";
148
149pub const START_CHANNEL_FILE: &str = "start-channel";
155
156pub const HITL_HEAD_DIR: &str = "hitl-heads";
160
161#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
163pub struct ScheduleProposal {
164 pub cron: String,
165 pub message: String,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub asked_for: Option<String>,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub not_after: Option<String>,
176 #[serde(default, skip_serializing_if = "Option::is_none")]
181 pub reply_to: Option<String>,
182 pub proposed_at: String,
183}
184
185#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
186pub struct ScheduleEntry {
187 pub cron: String,
188 pub message: String,
189 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub sends_to: Option<String>,
191 #[serde(default, skip_serializing_if = "Option::is_none")]
203 pub not_after: Option<String>,
204 #[serde(default, skip_serializing_if = "Option::is_none")]
209 pub reply_to: Option<String>,
210}
211
212#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
213pub struct IdleTrigger {
214 pub after_secs: u64,
216 pub message: String,
218 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub sends_to: Option<String>,
221 #[serde(default = "default_idle_cooldown")]
224 pub cooldown_secs: u64,
225 #[serde(default = "default_true")]
228 pub respect_quiet_hours: bool,
229}
230
231fn default_idle_cooldown() -> u64 {
232 600
233}
234pub fn name_enabled(denylist: &[String], name: &str) -> bool {
236 !denylist.iter().any(|n| n == name)
237}
238
239pub fn set_denylist(list: &mut Vec<String>, name: &str, enabled: bool) {
242 if enabled {
243 list.retain(|n| n != name);
244 } else if !list.iter().any(|n| n == name) {
245 list.push(name.to_string());
246 }
247}
248
249#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
250pub struct FileTransferConfig {
251 #[serde(default = "default_accept_max")]
252 pub accept_incoming_file_max_bytes: u64,
253 #[serde(default = "default_accept_total")]
254 pub accept_incoming_total_per_hour: u64,
255 #[serde(default = "default_approval_threshold")]
256 pub require_approval_above_bytes: u64,
257 #[serde(default = "default_reject_paths")]
258 pub reject_paths: Vec<String>,
259 #[serde(default = "default_allowed_mime")]
260 pub allowed_mime_types: Vec<String>,
261}
262
263impl Default for FileTransferConfig {
264 fn default() -> Self {
265 Self {
266 accept_incoming_file_max_bytes: default_accept_max(),
267 accept_incoming_total_per_hour: default_accept_total(),
268 require_approval_above_bytes: default_approval_threshold(),
269 reject_paths: default_reject_paths(),
270 allowed_mime_types: default_allowed_mime(),
271 }
272 }
273}
274
275fn default_accept_max() -> u64 {
276 10_485_760
277}
278fn default_accept_total() -> u64 {
279 104_857_600
280}
281fn default_approval_threshold() -> u64 {
282 10_485_760
283}
284fn default_reject_paths() -> Vec<String> {
285 vec!["~/.ssh".into(), "~/.aws".into(), "~/.gnupg".into()]
286}
287fn default_allowed_mime() -> Vec<String> {
288 vec!["*".into()]
289}
290
291#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
292#[serde(rename_all = "snake_case")]
293pub enum DeploymentType {
294 #[default]
295 Laptop,
296 Vm,
297 Docker,
298 K8s,
299 Lambda,
300}
301
302#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
303pub struct DeploymentConfig {
304 #[serde(rename = "type", default)]
305 pub deployment_type: DeploymentType,
306 #[serde(default, skip_serializing_if = "Option::is_none")]
307 pub region: Option<String>,
308 #[serde(default = "default_env")]
309 pub environment: Option<String>,
310}
311
312impl Default for DeploymentConfig {
313 fn default() -> Self {
314 Self {
315 deployment_type: DeploymentType::default(),
316 region: None,
317 environment: default_env(),
318 }
319 }
320}
321
322fn default_env() -> Option<String> {
323 Some("dev".into())
324}
325
326#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
332pub struct DroppedGrant {
333 pub path: String,
334 pub verb: String,
336 pub reason: String,
337}
338
339pub fn filesystem_grants_digest(fs: &FilesystemEntitlement) -> String {
346 use sha2::{Digest, Sha256};
347 let mut h = Sha256::new();
348 for (label, list) in [("r", &fs.read), ("w", &fs.write), ("d", &fs.deny)] {
349 let mut sorted = list.clone();
350 sorted.sort();
351 for p in sorted {
352 h.update(label.as_bytes());
353 h.update(b"\0");
354 h.update(p.as_bytes());
355 h.update(b"\0");
356 }
357 }
358 format!("sha256:{:x}", h.finalize())
359}
360
361pub fn spawn_dirs_digest(dirs: &[String]) -> String {
368 use sha2::{Digest, Sha256};
369 let mut sorted = dirs.to_vec();
370 sorted.sort();
371 let mut h = Sha256::new();
372 for p in sorted {
373 h.update(b"s\0");
374 h.update(p.as_bytes());
375 h.update(b"\0");
376 }
377 format!("sha256:{:x}", h.finalize())
378}
379
380#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
388pub struct SandboxRecord {
389 pub enforcing: bool,
393 pub mode: String,
395 pub granted_digest: String,
400 #[serde(default, skip_serializing_if = "Option::is_none")]
405 pub granted_spawn_dirs_digest: Option<String>,
406 #[serde(default)]
408 pub dropped: Vec<DroppedGrant>,
409}
410
411#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
412pub struct LockFile {
413 pub schema: u32,
414 pub uuid: String,
415 pub name: String,
416 pub pid: u32,
417 pub ppid: u32,
418 pub started_at: String,
419 pub binary_version: String,
420 pub transports: LockTransports,
421 pub card_digest: String,
422 pub capabilities: Vec<String>,
423 #[serde(default)]
426 pub build_sha: String,
427 #[serde(default)]
430 pub proto_version: u32,
431 #[serde(default, skip_serializing_if = "Option::is_none")]
434 pub sandbox: Option<SandboxRecord>,
435 #[serde(default, rename = "override", skip_serializing_if = "Option::is_none")]
438 pub startup_override: Option<OverrideRecord>,
439 #[serde(default, skip_serializing_if = "Option::is_none")]
441 pub override_rejected: Option<OverrideRejection>,
442}
443
444#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
445pub struct LockTransports {
446 pub stdio: bool,
447 #[serde(default)]
448 pub unix_socket: Option<String>,
449 #[serde(default)]
450 pub tcp: Option<String>,
451 #[serde(default)]
456 pub webhook: Option<String>,
457}
458
459#[cfg(test)]
460mod tests {
461 #[test]
465 fn grants_digest_ignores_order_but_not_content() {
466 let a = FilesystemEntitlement {
467 read: vec!["/a".into(), "/b".into()],
468 write: vec!["/w".into()],
469 deny: vec![],
470 };
471 let reordered = FilesystemEntitlement {
472 read: vec!["/b".into(), "/a".into()],
473 ..a.clone()
474 };
475 let changed = FilesystemEntitlement {
476 write: vec!["/w".into(), "/x".into()],
477 ..a.clone()
478 };
479 assert_eq!(
480 filesystem_grants_digest(&a),
481 filesystem_grants_digest(&reordered)
482 );
483 assert_ne!(
484 filesystem_grants_digest(&a),
485 filesystem_grants_digest(&changed)
486 );
487 }
488
489 #[test]
491 fn grants_digest_separates_the_verbs() {
492 let r = FilesystemEntitlement {
493 read: vec!["/p".into()],
494 write: vec![],
495 deny: vec![],
496 };
497 let w = FilesystemEntitlement {
498 read: vec![],
499 write: vec!["/p".into()],
500 deny: vec![],
501 };
502 assert_ne!(filesystem_grants_digest(&r), filesystem_grants_digest(&w));
503 }
504
505 #[test]
508 fn a_lock_without_the_sandbox_block_still_deserialises() {
509 let old = r#"{"schema":1,"uuid":"u","name":"n","pid":1,"ppid":0,
510 "started_at":"t","binary_version":"v",
511 "transports":{"stdio":true},"card_digest":"d","capabilities":[]}"#;
512 let lf: LockFile = serde_json::from_str(old).expect("old lock must load");
513 assert!(lf.sandbox.is_none());
514 }
515
516 #[test]
517 fn spawn_dirs_digest_ignores_order_and_tracks_membership() {
518 let a = vec!["/a".to_string(), "/b".to_string()];
519 let reordered = vec!["/b".to_string(), "/a".to_string()];
520 let grown = vec!["/a".to_string(), "/b".to_string(), "/c".to_string()];
521 assert_eq!(spawn_dirs_digest(&a), spawn_dirs_digest(&reordered));
522 assert_ne!(spawn_dirs_digest(&a), spawn_dirs_digest(&grown));
523 assert_ne!(spawn_dirs_digest(&[]), spawn_dirs_digest(&a));
525 }
526
527 #[test]
528 fn a_lock_sealed_before_the_spawn_digest_existed_loads_as_none() {
529 let old = r#"{"enforcing":true,"mode":"macos-sbpl","granted_digest":"sha256:x"}"#;
530 let rec: SandboxRecord = serde_json::from_str(old).expect("old record must load");
531 assert!(rec.granted_spawn_dirs_digest.is_none());
532 }
533
534 #[test]
535 fn the_sandbox_block_round_trips() {
536 let rec = SandboxRecord {
537 enforcing: false,
538 mode: "advisory-only".into(),
539 granted_digest: "sha256:x".into(),
540 granted_spawn_dirs_digest: Some("sha256:y".into()),
541 dropped: vec![DroppedGrant {
542 path: "/gone".into(),
543 verb: "write".into(),
544 reason: "path does not exist on disk".into(),
545 }],
546 };
547 let back: SandboxRecord =
548 serde_json::from_str(&serde_json::to_string(&rec).unwrap()).unwrap();
549 assert_eq!(back, rec);
550 }
551
552 use super::*;
553
554 #[test]
555 fn broad_audited_mcp_net_serde_roundtrip_and_defaults() {
556 let net = McpServerNetwork {
557 mode: McpNetMode::BroadAudited,
558 allow_hosts: vec![],
559 deny_hosts: vec!["evil.example".into()],
560 authorization: Some(EgressAuthorization {
561 authorized_by: "david".into(),
562 authorized_at_ms: 1_750_000_000_000,
563 }),
564 };
565 let y = serde_yaml::to_string(&net).unwrap();
566 assert!(y.contains("broad_audited"));
567 let back: McpServerNetwork = serde_yaml::from_str(&y).unwrap();
568 assert_eq!(back, net);
569 let legacy: McpServerNetwork =
571 serde_yaml::from_str("mode: restricted\nallow_hosts: []\n").unwrap();
572 assert_eq!(legacy.deny_hosts, Vec::<String>::new());
573 assert!(legacy.authorization.is_none());
574 }
575
576 #[test]
577 fn mcp_entry_network_is_optional_and_round_trips() {
578 let bare = "name: x\ncommand: npx\n";
580 let e: McpServerEntry = serde_yaml_ng::from_str(bare).unwrap();
581 assert!(e.network.is_none());
582
583 let with = "name: browser\ncommand: npx\nnetwork:\n mode: restricted\n allow_hosts: [\"example.com\", \"*.api.example.com\"]\n";
585 let e2: McpServerEntry = serde_yaml_ng::from_str(with).unwrap();
586 let net = e2.network.expect("network present");
587 assert_eq!(net.mode, McpNetMode::Restricted);
588 assert_eq!(net.allow_hosts, vec!["example.com", "*.api.example.com"]);
589
590 let out = serde_yaml_ng::to_string(&e).unwrap();
592 assert!(!out.contains("network"));
593 }
594
595 #[test]
596 fn profile_round_trip_yaml() {
597 let yaml = r#"
598schema: 1
599id: 01JQX4TM8Y9K7VQH6B2N3R5DPE
600name: agent_a
601display_name: "Price Hunter"
602version: "0.1.0"
603persona:
604 category: research
605 description: "Finds prices"
606 traits: { tone: concise, risk: cautious, verbosity: low }
607sys_prompt_file: "sys_prompt.md"
608model: { provider: ollama, name: "llama3.2:3b", params: { temperature: 0.2, max_tokens: 4096 } }
609mcp_servers: []
610skills: []
611transport:
612 stdio: true
613 socket: { enabled: true, bind: "unix:///tmp/a.sock" }
614communication: { accepts_from: ["*"], sends_to: [] }
615capabilities: ["a2a.message.send", "a2a.tasks"]
616entitlements:
617 network:
618 inbound: { ports: [] }
619 outbound: { mode: restricted, allow_hosts: [], protocols: ["tcp"], resolve_dns: { mode: system } }
620 filesystem: { read: [], write: [], deny: [] }
621 processes: { spawn: { mode: allowlist, allowed: [] } }
622 syscalls: { mode: default }
623 limits: { memory_mb: 512, file_descriptors: 1024, processes: 32 }
624notifications: { on_task_complete: [], on_error: [], on_shutdown: [] }
625retry:
626 llm: { max_retries: 3, backoff: exponential, initial_delay_ms: 1000, max_delay_ms: 30000, retry_on: [rate_limit, timeout, connection_error] }
627 tool: { max_retries: 1, backoff: fixed, initial_delay_ms: 500 }
628lifecycle: { restart: on_failure, max_restarts: 3, restart_window_secs: 600, stop_timeout_secs: 15, mcp_required: true }
629created_at: "2026-04-22T10:00:00+08:00"
630updated_at: "2026-04-22T10:00:00+08:00"
631"#;
632 let profile: AgentProfile = serde_yaml_ng::from_str(yaml).expect("parse");
633 assert_eq!(profile.name, "agent_a");
634 assert_eq!(profile.persona.category, PersonaCategory::Research);
635 assert_eq!(
636 profile.entitlements.network.outbound.mode,
637 NetworkOutboundMode::Restricted
638 );
639 let reserialized = serde_yaml_ng::to_string(&profile).expect("emit");
640 let round_tripped: AgentProfile = serde_yaml_ng::from_str(&reserialized).expect("re-parse");
641 assert_eq!(profile.id, round_tripped.id);
642 }
643
644 #[test]
645 fn requires_capabilities_defaults_empty_and_round_trips() {
646 let base = include_str!("../../tests/fixtures/profile_p0a_minimal.yaml");
647 let p: AgentProfile = serde_yaml_ng::from_str(base).unwrap();
648 assert!(p.requires_capabilities.is_empty());
649 let with = format!("{base}\nrequires_capabilities:\n - media\n");
650 let p2: AgentProfile = serde_yaml_ng::from_str(&with).unwrap();
651 assert_eq!(p2.requires_capabilities, vec!["media"]);
652 }
653}
654
655#[cfg(test)]
656mod idle_trigger_tests {
657 use super::*;
658
659 #[test]
660 fn idle_trigger_yaml_round_trip() {
661 let yaml = r#"
662restart: on_failure
663idle_triggers:
664 - after_secs: 3600
665 message: "still there?"
666 sends_to: other_agent
667 cooldown_secs: 1800
668 respect_quiet_hours: true
669"#;
670 let cfg: LifecycleConfig = serde_yaml_ng::from_str(yaml).unwrap();
671 assert_eq!(cfg.idle_triggers.len(), 1);
672 assert_eq!(cfg.idle_triggers[0].after_secs, 3600);
673 assert_eq!(cfg.idle_triggers[0].message, "still there?");
674 assert_eq!(
675 cfg.idle_triggers[0].sends_to.as_deref(),
676 Some("other_agent")
677 );
678 assert_eq!(cfg.idle_triggers[0].cooldown_secs, 1800);
679 assert!(cfg.idle_triggers[0].respect_quiet_hours);
680 }
681
682 #[test]
683 fn idle_trigger_defaults_when_omitted() {
684 let yaml = "restart: on_failure\n";
685 let cfg: LifecycleConfig = serde_yaml_ng::from_str(yaml).unwrap();
686 assert!(cfg.idle_triggers.is_empty());
687 }
688}
689
690#[cfg(test)]
691mod lockfile_compat_tests {
692 use super::*;
693
694 #[test]
695 fn lockfile_new_fields_default_for_old_locks() {
696 let old = r#"{"schema":1,"uuid":"u","name":"a","pid":1,"ppid":1,
699 "started_at":"t","binary_version":"mur-agent-runtime 2.26.9",
700 "transports":{"stdio":true},"card_digest":"d","capabilities":[]}"#;
701 let lock: LockFile = serde_json::from_str(old).unwrap();
702 assert_eq!(lock.build_sha, "");
703 assert_eq!(lock.proto_version, 0);
704 }
705
706 const OLD_LOCK: &str = r#"{"schema":1,"uuid":"u","name":"a","pid":1,"ppid":1,
707 "started_at":"t","binary_version":"mur-agent-runtime 2.26.9",
708 "transports":{"stdio":true},"card_digest":"d","capabilities":[]}"#;
709
710 #[test]
711 fn old_lock_without_override_fields_still_parses() {
712 let lock: LockFile = serde_json::from_str(OLD_LOCK).unwrap();
713 assert_eq!(lock.startup_override, None);
714 assert_eq!(lock.override_rejected, None);
715 let out = serde_json::to_value(&lock).unwrap();
717 assert!(out.get("override").is_none());
718 assert!(out.get("override_rejected").is_none());
719 }
720
721 #[test]
722 fn override_record_serializes_under_the_key_override() {
723 let mut lock: LockFile = serde_json::from_str(OLD_LOCK).unwrap();
724 lock.startup_override = Some(OverrideRecord {
725 nonce: "ovr-0123456789abcdef0123456789abcdef".into(),
726 flags: OverrideFlags {
727 no_hitl: true,
728 ..OverrideFlags::default()
729 },
730 confirmed_by: crate::startup_override::ConfirmedBy::Tty,
731 });
732 lock.override_rejected = Some(OverrideRejection {
733 nonce: None,
734 reason: "override rejected: unparseable".into(),
735 });
736 let out = serde_json::to_value(&lock).unwrap();
737 assert!(out.get("startup_override").is_none());
738 assert_eq!(out["override"]["flags"]["no_hitl"], true);
739 assert_eq!(out["override"]["confirmed_by"], "tty");
740 assert!(out["override_rejected"]["nonce"].is_null());
741 let back: LockFile = serde_json::from_value(out).unwrap();
742 assert_eq!(back, lock);
743 }
744}