1use super::*;
2
3#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
10#[serde(rename_all = "snake_case")]
11pub enum VoiceId {
12 #[default]
14 AfHeart,
15 AfBella,
16 AfNicole,
17 AmAdam,
18 AmMichael,
19}
20
21impl VoiceId {
22 pub fn style_index(&self) -> usize {
24 match self {
25 VoiceId::AfHeart => 0,
26 VoiceId::AfBella => 1,
27 VoiceId::AfNicole => 2,
28 VoiceId::AmAdam => 3,
29 VoiceId::AmMichael => 4,
30 }
31 }
32
33 pub fn as_str(&self) -> &'static str {
35 match self {
36 VoiceId::AfHeart => "af_heart",
37 VoiceId::AfBella => "af_bella",
38 VoiceId::AfNicole => "af_nicole",
39 VoiceId::AmAdam => "am_adam",
40 VoiceId::AmMichael => "am_michael",
41 }
42 }
43}
44
45impl std::str::FromStr for VoiceId {
46 type Err = anyhow::Error;
47
48 fn from_str(s: &str) -> anyhow::Result<Self> {
49 match s {
50 "af_heart" => Ok(VoiceId::AfHeart),
51 "af_bella" => Ok(VoiceId::AfBella),
52 "af_nicole" => Ok(VoiceId::AfNicole),
53 "am_adam" => Ok(VoiceId::AmAdam),
54 "am_michael" => Ok(VoiceId::AmMichael),
55 other => anyhow::bail!(
56 "unknown voice ID '{other}' \
57 (valid: af_heart, af_bella, af_nicole, am_adam, am_michael)"
58 ),
59 }
60 }
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
66pub struct VoiceConfig {
67 #[serde(default)]
69 pub enabled: bool,
70 #[serde(default)]
72 pub voice_id: VoiceId,
73 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub input_device: Option<String>,
77}
78
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
84pub struct HitlConfig {
85 #[serde(default = "default_hitl_timeout_secs")]
86 pub timeout_secs: u32,
87 #[serde(default)]
90 pub max_iterations: Option<u32>,
91 #[serde(default)]
94 pub max_tokens: Option<u64>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub autonomy: Option<crate::hitl::Autonomy>,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
109 pub intent_check: Option<crate::hitl::intent::IntentCheckConfig>,
110}
111
112fn default_hitl_timeout_secs() -> u32 {
113 300
114}
115
116impl Default for HitlConfig {
117 fn default() -> Self {
118 Self {
119 timeout_secs: default_hitl_timeout_secs(),
120 max_iterations: None,
121 max_tokens: None,
122 autonomy: None,
123 intent_check: None,
124 }
125 }
126}
127
128#[cfg(test)]
129mod hitl_tests {
130 use super::*;
131
132 #[test]
135 fn hitl_config_autonomy_absent_means_inherit_not_continue() {
136 let cfg: HitlConfig = serde_yaml::from_str("timeout_secs: 60").unwrap();
137 assert_eq!(cfg.autonomy, None);
138 assert_eq!(cfg.autonomy.unwrap_or_default(), crate::hitl::Autonomy::Ask);
139 }
140
141 #[test]
142 fn hitl_config_autonomy_parses_all_three_modes() {
143 for (yaml, want) in [
144 ("continue", crate::hitl::Autonomy::Continue),
145 ("review", crate::hitl::Autonomy::Review),
146 ("ask", crate::hitl::Autonomy::Ask),
147 ] {
148 let cfg: HitlConfig =
149 serde_yaml::from_str(&format!("timeout_secs: 60\nautonomy: {yaml}")).unwrap();
150 assert_eq!(cfg.autonomy, Some(want), "yaml={yaml}");
151 }
152 }
153
154 #[test]
155 fn hitl_config_default_max_iterations_is_none() {
156 let cfg = HitlConfig::default();
157 assert!(cfg.max_iterations.is_none());
158 }
159
160 #[test]
161 fn hitl_config_max_iterations_explicit() {
162 let cfg: HitlConfig = serde_yaml::from_str("timeout_secs: 60\nmax_iterations: 5").unwrap();
163 assert_eq!(cfg.max_iterations, Some(5));
164 }
165
166 #[test]
167 fn hitl_config_default_max_tokens_is_none() {
168 let cfg = HitlConfig::default();
169 assert!(cfg.max_tokens.is_none());
170 }
171
172 #[test]
173 fn hitl_config_max_tokens_explicit() {
174 let cfg: HitlConfig = serde_yaml::from_str("timeout_secs: 60\nmax_tokens: 250000").unwrap();
175 assert_eq!(cfg.max_tokens, Some(250_000));
176 }
177}
178
179#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
185pub struct CompanionConfig {
186 #[serde(default)]
187 pub enabled: bool,
188 #[serde(default = "default_locale")]
189 pub locale: String,
190 #[serde(default)]
191 pub relationship: Relationship,
192 #[serde(default)]
193 pub voice_overrides: VoiceOverrides,
194 #[serde(default)]
195 pub onboarding: OnboardingState,
196 #[serde(default)]
197 pub rhythm: RhythmConfig,
198 #[serde(default)]
199 pub proactive: ProactiveConfig,
200}
201
202pub fn default_locale() -> String {
211 sys_locale::get_locale()
212 .filter(|l| !l.is_empty())
213 .or_else(|| std::env::var("LANG").ok().and_then(|v| normalize_lang(&v)))
214 .unwrap_or_else(|| "en-US".into())
215}
216
217fn normalize_lang(v: &str) -> Option<String> {
219 v.split('.')
220 .next()
221 .map(|s| s.replace('_', "-"))
222 .filter(|s| !s.is_empty())
223}
224
225#[cfg(test)]
226mod locale_tests {
227 use super::normalize_lang;
228
229 #[test]
230 fn lang_with_encoding_and_region_normalizes() {
231 assert_eq!(normalize_lang("zh_TW.UTF-8").as_deref(), Some("zh-TW"));
232 }
233
234 #[test]
235 fn lang_without_encoding_normalizes() {
236 assert_eq!(normalize_lang("en_US").as_deref(), Some("en-US"));
237 }
238
239 #[test]
240 fn lang_with_script_keeps_script() {
241 assert_eq!(
242 normalize_lang("zh_Hant_TW.UTF-8").as_deref(),
243 Some("zh-Hant-TW")
244 );
245 }
246
247 #[test]
248 fn empty_lang_yields_none() {
249 assert_eq!(normalize_lang(""), None);
250 }
251}
252
253#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
254pub struct VoiceOverrides {
255 #[serde(default, skip_serializing_if = "Option::is_none")]
256 pub name_for_user: Option<String>,
257 #[serde(default, skip_serializing_if = "Option::is_none")]
258 pub formality: Option<Formality>,
259 #[serde(default, skip_serializing_if = "Option::is_none")]
260 pub extra_instructions: Option<String>,
261}
262
263#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
264pub struct FirstMemory {
265 pub text: String,
266 pub established_at: chrono::DateTime<chrono::Utc>,
267}
268
269#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
270pub struct OnboardingState {
271 #[serde(default, skip_serializing_if = "Option::is_none")]
272 pub completed_at: Option<chrono::DateTime<chrono::Utc>>,
273 #[serde(default)]
274 pub version: u32,
275 #[serde(default, skip_serializing_if = "Option::is_none")]
276 pub agent_display_name: Option<String>,
277 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub first_memory: Option<FirstMemory>,
279}
280
281#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
284pub struct RhythmConfig {
285 #[serde(default)]
286 pub enabled: bool,
287}
288
289#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
290pub struct ProactiveConfig {
291 #[serde(default)]
292 pub enabled: bool,
293 #[serde(default, skip_serializing_if = "Option::is_none")]
295 pub learning_until: Option<chrono::DateTime<chrono::Utc>>,
296 #[serde(default, skip_serializing_if = "Option::is_none")]
297 pub quiet_hours: Option<QuietHours>,
298 #[serde(default, skip_serializing_if = "Option::is_none")]
299 pub active_hours: Option<ActiveHours>,
300 #[serde(default = "default_daily_cap")]
301 pub daily_cap: u8,
302 #[serde(default = "default_channels")]
303 pub channels: Vec<String>,
304 #[serde(default, skip_serializing_if = "Option::is_none")]
305 pub paused_until: Option<chrono::DateTime<chrono::Utc>>,
306}
307
308impl Default for ProactiveConfig {
309 fn default() -> Self {
310 Self {
311 enabled: false,
312 learning_until: None,
313 quiet_hours: None,
314 active_hours: None,
315 daily_cap: default_daily_cap(),
316 channels: default_channels(),
317 paused_until: None,
318 }
319 }
320}
321
322fn default_daily_cap() -> u8 {
323 3
324}
325fn default_channels() -> Vec<String> {
326 vec!["stdout".into()]
327}
328
329#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
330pub struct QuietHours {
331 pub start: String,
332 pub end: String,
333}
334
335#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
336pub struct ActiveHours {
337 pub start: String,
338 pub end: String,
339}
340
341#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
346pub struct AgentAppearance {
347 #[serde(default = "default_style_preset")]
349 pub style_preset: String,
350 #[serde(default)]
351 pub behavior_preset: BehaviorPreset,
352 #[serde(default, skip_serializing_if = "Option::is_none")]
354 pub source_image_path: Option<std::path::PathBuf>,
355 #[serde(default = "default_expressions_dir")]
357 pub expressions_dir: std::path::PathBuf,
358 #[serde(default, skip_serializing_if = "Option::is_none")]
359 pub last_rendered_at: Option<chrono::DateTime<chrono::Utc>>,
360 #[serde(default)]
361 pub render_status: RenderStatus,
362}
363
364fn default_style_preset() -> String {
365 "default-blob".into()
366}
367
368fn default_expressions_dir() -> std::path::PathBuf {
369 std::path::PathBuf::from("expressions")
370}
371
372impl Default for AgentAppearance {
373 fn default() -> Self {
374 Self {
375 style_preset: default_style_preset(),
376 behavior_preset: BehaviorPreset::Normal,
377 source_image_path: None,
378 expressions_dir: default_expressions_dir(),
379 last_rendered_at: None,
380 render_status: RenderStatus::Pending,
381 }
382 }
383}
384
385#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
386#[serde(rename_all = "snake_case")]
387pub enum BehaviorPreset {
388 Quiet,
389 #[default]
390 Normal,
391 Lively,
392}
393
394#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
395#[serde(tag = "status", rename_all = "snake_case")]
396pub enum RenderStatus {
397 #[default]
398 Pending,
399 Rendering {
400 done: u8,
401 total: u8,
402 },
403 Ready,
404 Failed {
405 reason: String,
406 },
407}
408
409#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
415#[serde(rename_all = "kebab-case")]
416pub enum SnapshotPolicy {
417 #[default]
418 PullOnStart,
419 PullPeriodic,
420 Manual,
421}
422
423#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
425pub struct PatternFilter {
426 #[serde(default, skip_serializing_if = "Vec::is_empty")]
427 pub applies_in: Vec<String>,
428 #[serde(default, skip_serializing_if = "Vec::is_empty")]
429 pub tier: Vec<String>,
430 #[serde(default, skip_serializing_if = "Vec::is_empty")]
431 pub maturity: Vec<String>,
432 #[serde(default)]
433 pub importance_min: f64,
434 #[serde(default = "default_max_snapshot_count")]
435 pub max_count: usize,
436 #[serde(default)]
437 pub snapshot_policy: SnapshotPolicy,
438}
439
440fn default_max_snapshot_count() -> usize {
441 200
442}
443
444impl Default for PatternFilter {
445 fn default() -> Self {
446 Self {
447 applies_in: vec![],
448 tier: vec![],
449 maturity: vec![],
450 importance_min: 0.0,
451 max_count: 200,
452 snapshot_policy: SnapshotPolicy::default(),
453 }
454 }
455}
456
457#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
459pub struct SnapshotRef {
460 pub knowledge_commit: String,
461 pub taken_at: String,
462 pub filter: PatternFilter,
463}
464
465#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
467pub struct FederationConfig {
468 #[serde(default)]
469 pub filter: PatternFilter,
470 #[serde(default, skip_serializing_if = "Option::is_none")]
471 pub snapshot_ref: Option<SnapshotRef>,
472 #[serde(default)]
473 pub evidence_flush_interval_minutes: u32,
474}
475
476#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
484#[serde(rename_all = "snake_case")]
485pub enum ProactiveTier {
486 Off,
487 WarmOnly,
488 WarmAndBehavior,
489 All,
490}
491
492impl ProactiveTier {
493 pub fn from_config(c: &CompanionConfig) -> Self {
494 match (c.enabled, c.rhythm.enabled, c.proactive.enabled) {
495 (false, _, _) => Self::Off,
496 (true, false, false) => Self::WarmOnly,
497 (true, true, false) => Self::WarmAndBehavior,
498 (true, _, true) => Self::All,
499 }
500 }
501
502 pub fn apply(&self, c: &mut CompanionConfig) {
503 match self {
504 Self::Off => {
505 c.enabled = false;
506 c.rhythm.enabled = false;
507 c.proactive.enabled = false;
508 }
509 Self::WarmOnly => {
510 c.enabled = true;
511 c.rhythm.enabled = false;
512 c.proactive.enabled = false;
513 }
514 Self::WarmAndBehavior => {
515 c.enabled = true;
516 c.rhythm.enabled = true;
517 c.proactive.enabled = false;
518 }
519 Self::All => {
520 c.enabled = true;
521 c.rhythm.enabled = true;
522 c.proactive.enabled = true;
523 }
524 }
525 }
526}
527
528#[cfg(test)]
529mod voice_tests {
530 use super::*;
531 use std::str::FromStr;
532
533 #[test]
534 fn voice_config_round_trips() {
535 let base = include_str!("../../tests/fixtures/profile_p0a_minimal.yaml");
537 let yaml = format!("{base}voice:\n enabled: true\n voice_id: af_bella\n");
538
539 let profile: AgentProfile = serde_yaml_ng::from_str(&yaml).expect("parse with voice");
540 assert!(profile.voice.enabled);
541 assert_eq!(profile.voice.voice_id, VoiceId::AfBella);
542
543 let legacy: AgentProfile = serde_yaml_ng::from_str(base).expect("parse without voice");
545 assert!(!legacy.voice.enabled);
546 assert_eq!(legacy.voice.voice_id, VoiceId::AfHeart);
547 }
548
549 #[test]
550 fn voice_id_from_str_roundtrips() {
551 let cases = [
552 ("af_heart", VoiceId::AfHeart),
553 ("af_bella", VoiceId::AfBella),
554 ("af_nicole", VoiceId::AfNicole),
555 ("am_adam", VoiceId::AmAdam),
556 ("am_michael", VoiceId::AmMichael),
557 ];
558 for (s, expected) in cases {
559 assert_eq!(VoiceId::from_str(s).unwrap(), expected);
560 assert_eq!(expected.as_str(), s);
561 }
562 }
563
564 #[test]
565 fn voice_id_from_str_rejects_unknown() {
566 assert!(VoiceId::from_str("bogus").is_err());
567 }
568}
569
570#[cfg(test)]
571mod appearance_tests {
572 use super::*;
573
574 #[test]
575 fn appearance_default_style_preset_is_default_blob() {
576 assert_eq!(AgentAppearance::default().style_preset, "default-blob");
577 }
578
579 #[test]
580 fn appearance_default_behavior_is_normal() {
581 assert_eq!(
582 AgentAppearance::default().behavior_preset,
583 BehaviorPreset::Normal
584 );
585 }
586
587 #[test]
588 fn appearance_default_render_status_is_pending() {
589 assert_eq!(
590 AgentAppearance::default().render_status,
591 RenderStatus::Pending
592 );
593 }
594
595 #[test]
596 fn render_status_serde_round_trip() {
597 let cases = [
598 RenderStatus::Pending,
599 RenderStatus::Rendering { done: 3, total: 12 },
600 RenderStatus::Ready,
601 RenderStatus::Failed {
602 reason: "out of quota".into(),
603 },
604 ];
605 for status in cases {
606 let yaml = serde_yaml_ng::to_string(&status).expect("serialize");
607 let back: RenderStatus = serde_yaml_ng::from_str(&yaml).expect("deserialize");
608 assert_eq!(status, back);
609 }
610 }
611
612 #[test]
613 fn agent_profile_with_appearance_round_trips() {
614 let base = include_str!("../../tests/fixtures/profile_p0a_minimal.yaml");
615 let yaml = format!(
616 "{base}appearance:\n style_preset: chiikawa\n render_status:\n status: ready\n"
617 );
618 let profile: AgentProfile = serde_yaml_ng::from_str(&yaml).expect("parse with appearance");
619 assert_eq!(profile.appearance.style_preset, "chiikawa");
620 assert_eq!(profile.appearance.render_status, RenderStatus::Ready);
621
622 let out = serde_yaml_ng::to_string(&profile).expect("serialize");
623 let back: AgentProfile = serde_yaml_ng::from_str(&out).expect("re-parse");
624 assert_eq!(profile.appearance, back.appearance);
625 }
626
627 #[test]
628 fn legacy_profile_without_appearance_uses_default() {
629 let yaml = include_str!("../../tests/fixtures/profile_p0a_minimal.yaml");
630 let profile: AgentProfile = serde_yaml_ng::from_str(yaml).expect("parse legacy");
631 assert_eq!(profile.appearance.style_preset, "default-blob");
632 assert_eq!(profile.appearance.behavior_preset, BehaviorPreset::Normal);
633 assert_eq!(profile.appearance.render_status, RenderStatus::Pending);
634 }
635
636 #[test]
637 fn legacy_profile_without_file_actions_or_action_pipeline_loads() {
638 let yaml = include_str!("../../tests/fixtures/profile_p0a_minimal.yaml");
639 let p: AgentProfile = serde_yaml_ng::from_str(yaml).unwrap();
640 assert!(p.file_actions.is_empty());
641 assert_eq!(p.action_pipeline.deletion.cancel_window_minutes, 10);
642 assert_eq!(p.action_pipeline.queue.max_concurrent, 3);
643 }
644}
645
646#[cfg(test)]
647mod federation_tests {
648 use super::*;
649
650 #[test]
651 fn test_pattern_filter_default() {
652 let f = PatternFilter::default();
653 assert_eq!(f.max_count, 200);
654 assert_eq!(f.importance_min, 0.0);
655 assert!(f.tier.is_empty());
656 }
657
658 #[test]
659 fn test_federation_config_roundtrip() {
660 let cfg = FederationConfig {
661 filter: PatternFilter {
662 tier: vec!["core".into()],
663 max_count: 50,
664 ..Default::default()
665 },
666 snapshot_ref: Some(SnapshotRef {
667 knowledge_commit: "abc123def456".into(),
668 taken_at: "2026-05-19T00:00:00Z".into(),
669 filter: PatternFilter::default(),
670 }),
671 evidence_flush_interval_minutes: 15,
672 };
673 let yaml = serde_yaml_ng::to_string(&cfg).unwrap();
674 let back: FederationConfig = serde_yaml_ng::from_str(&yaml).unwrap();
675 assert_eq!(cfg, back);
676 }
677
678 #[test]
679 fn test_agent_profile_federation_defaults() {
680 let cfg = FederationConfig::default();
684 assert_eq!(cfg.evidence_flush_interval_minutes, 0);
685 assert!(cfg.snapshot_ref.is_none());
686 }
687}