zeptoclaw 0.3.0

Ultra-lightweight personal AI assistant framework
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
//! Configuration type definitions for ZeptoClaw
//!
//! This module defines all configuration structs used throughout the framework.
//! All types implement serde traits for JSON serialization and have sensible defaults.

use serde::{Deserialize, Serialize};

/// Main configuration struct for ZeptoClaw
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
pub struct Config {
    /// Agent configuration (models, tokens, iterations)
    pub agents: AgentConfig,
    /// Channel configurations (Telegram, Discord, Slack, etc.)
    pub channels: ChannelsConfig,
    /// LLM provider configurations (Claude, OpenAI, OpenRouter, etc.)
    pub providers: ProvidersConfig,
    /// Gateway server configuration
    pub gateway: GatewayConfig,
    /// Tools configuration
    pub tools: ToolsConfig,
    /// Memory configuration
    pub memory: MemoryConfig,
    /// Heartbeat background task configuration
    pub heartbeat: HeartbeatConfig,
    /// Skills system configuration
    pub skills: SkillsConfig,
    /// Runtime configuration for container isolation
    pub runtime: RuntimeConfig,
    /// Containerized agent configuration
    pub container_agent: ContainerAgentConfig,
    /// Swarm / multi-agent delegation configuration
    pub swarm: SwarmConfig,
    /// Tool approval configuration
    pub approval: crate::tools::approval::ApprovalConfig,
    /// Plugin system configuration
    pub plugins: crate::plugins::types::PluginConfig,
    /// Telemetry export configuration
    pub telemetry: crate::utils::telemetry::TelemetryConfig,
    /// Cost tracking configuration
    pub cost: crate::utils::cost::CostConfig,
    /// Batch processing configuration
    pub batch: crate::batch::BatchConfig,
    /// Hook system configuration
    pub hooks: crate::hooks::HooksConfig,
    /// Safety layer configuration
    pub safety: crate::safety::SafetyConfig,
    /// Context compaction configuration
    pub compaction: CompactionConfig,
    /// MCP (Model Context Protocol) server configuration
    pub mcp: McpConfig,
    /// Routines (event/webhook/cron triggers) configuration
    pub routines: RoutinesConfig,
}

// ============================================================================
// Compaction Configuration
// ============================================================================

/// Context compaction configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CompactionConfig {
    /// Whether automatic context compaction is enabled.
    pub enabled: bool,
    /// Maximum context window size in tokens.
    pub context_limit: usize,
    /// Fraction (0.0-1.0) of context_limit that triggers compaction.
    pub threshold: f64,
}

impl Default for CompactionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            context_limit: 100_000,
            threshold: 0.80,
        }
    }
}

// ============================================================================
// MCP Configuration
// ============================================================================

/// MCP (Model Context Protocol) server configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct McpConfig {
    /// MCP server definitions.
    pub servers: Vec<McpServerConfig>,
}

/// Configuration for a single MCP server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
    /// Human-readable server name (used as tool name prefix).
    pub name: String,
    /// Server URL endpoint.
    pub url: String,
    /// Request timeout in seconds (default: 30).
    #[serde(default = "default_mcp_timeout")]
    pub timeout_secs: u64,
}

fn default_mcp_timeout() -> u64 {
    30
}

// ============================================================================
// Routines Configuration
// ============================================================================

/// Routines (event/webhook/cron triggers) configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RoutinesConfig {
    /// Whether the routines engine is enabled.
    pub enabled: bool,
    /// Cron tick interval in seconds.
    pub cron_interval_secs: u64,
    /// Maximum concurrent routine executions.
    pub max_concurrent: usize,
}

impl Default for RoutinesConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            cron_interval_secs: 60,
            max_concurrent: 3,
        }
    }
}

/// Agent configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
pub struct AgentConfig {
    /// Default agent settings
    pub defaults: AgentDefaults,
}

/// Default agent settings
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AgentDefaults {
    /// Workspace directory path
    pub workspace: String,
    /// Default model to use
    pub model: String,
    /// Maximum tokens for responses
    pub max_tokens: u32,
    /// Temperature for generation
    pub temperature: f32,
    /// Maximum tool iterations per turn
    pub max_tool_iterations: u32,
    /// Maximum wall-clock time (seconds) for a single agent run.
    pub agent_timeout_secs: u64,
    /// How to handle messages arriving during an active run.
    pub message_queue_mode: MessageQueueMode,
    /// Whether to stream the final LLM response token-by-token in CLI mode.
    pub streaming: bool,
    /// Per-session token budget (input + output). 0 = unlimited.
    pub token_budget: u64,
}

/// Default model compile-time configuration.
/// Set `ZEPTOCLAW_DEFAULT_MODEL` at compile time to override.
const COMPILE_TIME_DEFAULT_MODEL: &str = match option_env!("ZEPTOCLAW_DEFAULT_MODEL") {
    Some(v) => v,
    None => "claude-sonnet-4-5-20250929",
};

impl Default for AgentDefaults {
    fn default() -> Self {
        Self {
            workspace: "~/.zeptoclaw/workspace".to_string(),
            model: COMPILE_TIME_DEFAULT_MODEL.to_string(),
            max_tokens: 8192,
            temperature: 0.7,
            max_tool_iterations: 20,
            agent_timeout_secs: 300,
            message_queue_mode: MessageQueueMode::default(),
            streaming: false,
            token_budget: 0,
        }
    }
}

/// How to handle messages that arrive while an agent run is active.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum MessageQueueMode {
    /// Buffer messages, concatenate into one when current run finishes.
    #[default]
    Collect,
    /// Buffer messages, replay each as a separate run after current finishes.
    Followup,
}

// ============================================================================
// Channel Configurations
// ============================================================================

/// All channel configurations
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ChannelsConfig {
    /// Telegram bot configuration
    pub telegram: Option<TelegramConfig>,
    /// Discord bot configuration
    pub discord: Option<DiscordConfig>,
    /// Slack bot configuration
    pub slack: Option<SlackConfig>,
    /// WhatsApp bridge configuration
    pub whatsapp: Option<WhatsAppConfig>,
    /// Feishu (Lark) configuration
    pub feishu: Option<FeishuConfig>,
    /// MaixCam configuration
    pub maixcam: Option<MaixCamConfig>,
    /// QQ configuration
    pub qq: Option<QQConfig>,
    /// DingTalk configuration
    pub dingtalk: Option<DingTalkConfig>,
    /// Webhook inbound channel configuration
    pub webhook: Option<WebhookConfig>,
}

/// Webhook inbound channel configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Address to bind the HTTP server to
    #[serde(default = "default_webhook_bind_address")]
    pub bind_address: String,
    /// Port to listen on
    #[serde(default = "default_webhook_port")]
    pub port: u16,
    /// URL path to accept webhook requests on
    #[serde(default = "default_webhook_path")]
    pub path: String,
    /// Optional Bearer token for request authentication
    #[serde(default)]
    pub auth_token: Option<String>,
    /// Allowlist of sender IDs (empty = allow all)
    #[serde(default)]
    pub allow_from: Vec<String>,
}

fn default_webhook_bind_address() -> String {
    "127.0.0.1".to_string()
}

fn default_webhook_port() -> u16 {
    9876
}

fn default_webhook_path() -> String {
    "/webhook".to_string()
}

impl Default for WebhookConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            bind_address: default_webhook_bind_address(),
            port: default_webhook_port(),
            path: default_webhook_path(),
            auth_token: None,
            allow_from: Vec::new(),
        }
    }
}

/// Telegram channel configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TelegramConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Bot token from BotFather
    pub token: String,
    /// Allowlist of user IDs/usernames (empty = allow all)
    #[serde(default)]
    pub allow_from: Vec<String>,
}

/// Discord channel configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DiscordConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Bot token from Discord Developer Portal
    pub token: String,
    /// Allowlist of user IDs (empty = allow all)
    #[serde(default)]
    pub allow_from: Vec<String>,
}

/// Slack channel configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SlackConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Bot token (xoxb-...)
    pub bot_token: String,
    /// App-level token (xapp-...)
    pub app_token: String,
    /// Allowlist of user IDs (empty = allow all)
    #[serde(default)]
    pub allow_from: Vec<String>,
}

/// WhatsApp channel configuration (via bridge)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WhatsAppConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// WebSocket bridge URL
    #[serde(default = "default_whatsapp_bridge_url")]
    pub bridge_url: String,
    /// Allowlist of phone numbers (empty = allow all)
    #[serde(default)]
    pub allow_from: Vec<String>,
    /// Whether ZeptoClaw manages the bridge binary lifecycle.
    /// When true, `channel setup` and `gateway` will auto-install and start the bridge.
    /// When false, the user manages the bridge process externally.
    #[serde(default = "default_bridge_managed")]
    pub bridge_managed: bool,
}

fn default_whatsapp_bridge_url() -> String {
    "ws://localhost:3001".to_string()
}

fn default_bridge_managed() -> bool {
    true
}

impl Default for WhatsAppConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            bridge_url: default_whatsapp_bridge_url(),
            allow_from: Vec::new(),
            bridge_managed: default_bridge_managed(),
        }
    }
}

/// Feishu (Lark) channel configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FeishuConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// App ID
    pub app_id: String,
    /// App Secret
    pub app_secret: String,
    /// Encrypt Key for event subscription
    #[serde(default)]
    pub encrypt_key: String,
    /// Verification Token
    #[serde(default)]
    pub verification_token: String,
    /// Allowlist of user IDs (empty = allow all)
    #[serde(default)]
    pub allow_from: Vec<String>,
}

/// MaixCam channel configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaixCamConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Host to bind to
    #[serde(default = "default_maixcam_host")]
    pub host: String,
    /// Port to listen on
    #[serde(default = "default_maixcam_port")]
    pub port: u16,
    /// Allowlist of device IDs (empty = allow all)
    #[serde(default)]
    pub allow_from: Vec<String>,
}

fn default_maixcam_host() -> String {
    "0.0.0.0".to_string()
}

fn default_maixcam_port() -> u16 {
    18790
}

impl Default for MaixCamConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            host: default_maixcam_host(),
            port: default_maixcam_port(),
            allow_from: Vec::new(),
        }
    }
}

/// QQ channel configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct QQConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// App ID
    pub app_id: String,
    /// App Secret
    pub app_secret: String,
    /// Allowlist of QQ numbers (empty = allow all)
    #[serde(default)]
    pub allow_from: Vec<String>,
}

/// DingTalk channel configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DingTalkConfig {
    /// Whether the channel is enabled
    #[serde(default)]
    pub enabled: bool,
    /// Client ID
    pub client_id: String,
    /// Client Secret
    pub client_secret: String,
    /// Allowlist of user IDs (empty = allow all)
    #[serde(default)]
    pub allow_from: Vec<String>,
}

// ============================================================================
// Provider Configurations
// ============================================================================

/// All LLM provider configurations
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ProvidersConfig {
    /// Anthropic Claude configuration
    pub anthropic: Option<ProviderConfig>,
    /// OpenAI configuration
    pub openai: Option<ProviderConfig>,
    /// OpenRouter configuration
    pub openrouter: Option<ProviderConfig>,
    /// Groq configuration
    pub groq: Option<ProviderConfig>,
    /// Zhipu (GLM) configuration
    pub zhipu: Option<ProviderConfig>,
    /// VLLM configuration
    pub vllm: Option<ProviderConfig>,
    /// Google Gemini configuration
    pub gemini: Option<ProviderConfig>,
    /// Ollama (local models) configuration
    pub ollama: Option<ProviderConfig>,
    /// Retry behavior for runtime provider calls
    pub retry: RetryConfig,
    /// Fallback behavior across multiple configured runtime providers
    pub fallback: FallbackConfig,
}

/// Generic provider configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProviderConfig {
    /// API key for authentication
    #[serde(default)]
    pub api_key: Option<String>,
    /// Custom API base URL
    #[serde(default)]
    pub api_base: Option<String>,
    /// Authentication method (e.g., "oauth", "api_key")
    #[serde(default)]
    pub auth_method: Option<String>,
}

/// Retry behavior for runtime provider calls.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RetryConfig {
    /// Enable automatic retry for transient provider errors.
    pub enabled: bool,
    /// Maximum number of retry attempts.
    pub max_retries: u32,
    /// Base delay in milliseconds for exponential backoff.
    pub base_delay_ms: u64,
    /// Maximum delay cap in milliseconds for exponential backoff.
    pub max_delay_ms: u64,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_retries: 3,
            base_delay_ms: 1_000,
            max_delay_ms: 30_000,
        }
    }
}

/// Fallback behavior across multiple configured runtime providers.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct FallbackConfig {
    /// Enable provider fallback (primary -> secondary) when possible.
    pub enabled: bool,
    /// Optional preferred fallback provider id (e.g. "openai", "anthropic").
    pub provider: Option<String>,
}

impl Default for FallbackConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            provider: None,
        }
    }
}

// ============================================================================
// Gateway Configuration
// ============================================================================

/// Gateway server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GatewayConfig {
    /// Host to bind to
    pub host: String,
    /// Port to listen on
    pub port: u16,
}

impl Default for GatewayConfig {
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_string(),
            port: 8080,
        }
    }
}

// ============================================================================
// Tools Configuration
// ============================================================================

/// Tools configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ToolsConfig {
    /// Web tools configuration
    pub web: WebToolsConfig,
    /// WhatsApp Cloud API tool configuration
    pub whatsapp: WhatsAppToolConfig,
    /// Google Sheets tool configuration
    pub google_sheets: GoogleSheetsToolConfig,
}

/// Web tools configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct WebToolsConfig {
    /// Web search configuration
    pub search: WebSearchConfig,
}

/// Web search configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct WebSearchConfig {
    /// API key for search service
    #[serde(default)]
    pub api_key: Option<String>,
    /// Maximum search results to return
    pub max_results: u32,
}

impl Default for WebSearchConfig {
    fn default() -> Self {
        Self {
            api_key: None,
            max_results: 5,
        }
    }
}

/// WhatsApp Cloud API tool configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct WhatsAppToolConfig {
    /// WhatsApp Business account ID (optional, informational)
    #[serde(default)]
    pub business_account_id: Option<String>,
    /// Phone number ID used in Cloud API endpoint path
    #[serde(default)]
    pub phone_number_id: Option<String>,
    /// Permanent access token for Cloud API
    #[serde(default)]
    pub access_token: Option<String>,
    /// Optional webhook verify token
    #[serde(default)]
    pub webhook_verify_token: Option<String>,
    /// Default template language code
    pub default_language: String,
}

impl Default for WhatsAppToolConfig {
    fn default() -> Self {
        Self {
            business_account_id: None,
            phone_number_id: None,
            access_token: None,
            webhook_verify_token: None,
            default_language: "ms".to_string(),
        }
    }
}

/// Google Sheets tool configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct GoogleSheetsToolConfig {
    /// OAuth bearer access token (recommended for tool usage)
    #[serde(default)]
    pub access_token: Option<String>,
    /// Optional service account JSON encoded as base64
    #[serde(default)]
    pub service_account_base64: Option<String>,
}

// ============================================================================
// Memory Configuration
// ============================================================================

/// Memory backend selection.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum MemoryBackend {
    /// Disable memory tools.
    #[serde(rename = "none")]
    Disabled,
    /// Built-in workspace markdown memory.
    #[default]
    Builtin,
    /// QMD backend (falls back safely when unavailable).
    Qmd,
}

/// Memory citation mode.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum MemoryCitationsMode {
    /// Show citations depending on channel context.
    #[default]
    Auto,
    /// Always include citations in snippets.
    On,
    /// Never include citations in snippets.
    Off,
}

/// Memory configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MemoryConfig {
    /// Memory backend to use.
    pub backend: MemoryBackend,
    /// Citation mode for memory snippets.
    pub citations: MemoryCitationsMode,
    /// Whether to include MEMORY.md + memory/**/*.md by default.
    pub include_default_memory: bool,
    /// Default maximum memory search results.
    pub max_results: u32,
    /// Minimum score threshold for memory search results.
    pub min_score: f32,
    /// Maximum snippet length returned per result.
    pub max_snippet_chars: u32,
    /// Extra workspace-relative file/dir paths to include.
    #[serde(default)]
    pub extra_paths: Vec<String>,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            backend: MemoryBackend::Builtin,
            citations: MemoryCitationsMode::Auto,
            include_default_memory: true,
            max_results: 6,
            min_score: 0.2,
            max_snippet_chars: 700,
            extra_paths: Vec::new(),
        }
    }
}

// ============================================================================
// Heartbeat Configuration
// ============================================================================

/// Heartbeat background service configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct HeartbeatConfig {
    /// Enable or disable heartbeat service.
    pub enabled: bool,
    /// Heartbeat interval in seconds.
    pub interval_secs: u64,
    /// Optional heartbeat file path override.
    #[serde(default)]
    pub file_path: Option<String>,
}

impl Default for HeartbeatConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            interval_secs: 30 * 60,
            file_path: None,
        }
    }
}

// ============================================================================
// Skills Configuration
// ============================================================================

/// Skills system configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SkillsConfig {
    /// Enable or disable the skills system.
    pub enabled: bool,
    /// Optional workspace skills directory override.
    #[serde(default)]
    pub workspace_dir: Option<String>,
    /// Skills that should always be injected into context.
    #[serde(default)]
    pub always_load: Vec<String>,
    /// Built-in or workspace skills to disable by name.
    #[serde(default)]
    pub disabled: Vec<String>,
}

impl Default for SkillsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            workspace_dir: None,
            always_load: Vec::new(),
            disabled: Vec::new(),
        }
    }
}

// ============================================================================
// Swarm / Multi-Agent Delegation Configuration
// ============================================================================

/// Swarm / multi-agent delegation configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SwarmConfig {
    /// Whether delegation is enabled.
    pub enabled: bool,
    /// Maximum delegation depth (1 = no sub-sub-agents).
    pub max_depth: u32,
    /// Maximum concurrent sub-agents (for future parallel mode).
    pub max_concurrent: u32,
    /// Pre-defined role presets with tool whitelists.
    pub roles: std::collections::HashMap<String, SwarmRole>,
}

impl Default for SwarmConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_depth: 1,
            max_concurrent: 3,
            roles: std::collections::HashMap::new(),
        }
    }
}

/// A pre-defined sub-agent role with system prompt and tool whitelist.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct SwarmRole {
    /// System prompt for this role.
    pub system_prompt: String,
    /// Allowed tool names (empty = all minus delegate/spawn).
    pub tools: Vec<String>,
}

// ============================================================================
// Runtime Configuration
// ============================================================================

/// Container runtime type for shell command execution
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum RuntimeType {
    /// Native execution (no container isolation)
    #[default]
    Native,
    /// Docker container isolation
    Docker,
    /// Apple Container isolation (macOS only)
    #[serde(rename = "apple")]
    AppleContainer,
}

/// Runtime configuration for shell execution
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RuntimeConfig {
    /// Type of container runtime to use
    pub runtime_type: RuntimeType,
    /// Whether to fall back to native runtime if configured runtime is unavailable
    pub allow_fallback_to_native: bool,
    /// Path to JSON allowlist used to validate runtime extra mounts
    #[serde(default = "default_mount_allowlist_path")]
    pub mount_allowlist_path: String,
    /// Docker-specific configuration
    pub docker: DockerConfig,
    /// Apple Container-specific configuration (macOS)
    pub apple: AppleContainerConfig,
}

fn default_mount_allowlist_path() -> String {
    "~/.zeptoclaw/mount-allowlist.json".to_string()
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        Self {
            runtime_type: RuntimeType::Native,
            allow_fallback_to_native: false,
            mount_allowlist_path: default_mount_allowlist_path(),
            docker: DockerConfig::default(),
            apple: AppleContainerConfig::default(),
        }
    }
}

/// Docker runtime configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DockerConfig {
    /// Docker image to use for shell execution
    pub image: String,
    /// Additional volume mounts (host:container format)
    pub extra_mounts: Vec<String>,
    /// Memory limit (e.g., "512m")
    pub memory_limit: Option<String>,
    /// CPU limit (e.g., "1.0")
    pub cpu_limit: Option<String>,
    /// Network mode (default: none for security)
    pub network: String,
}

impl Default for DockerConfig {
    fn default() -> Self {
        Self {
            image: "alpine:latest".to_string(),
            extra_mounts: Vec::new(),
            memory_limit: Some("512m".to_string()),
            cpu_limit: Some("1.0".to_string()),
            network: "none".to_string(),
        }
    }
}

/// Apple Container runtime configuration (macOS only)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct AppleContainerConfig {
    /// Container image/bundle path
    pub image: String,
    /// Additional directory mounts
    pub extra_mounts: Vec<String>,
}

// ============================================================================
// Containerized Agent Configuration
// ============================================================================

/// Container backend for the containerized agent proxy.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ContainerAgentBackend {
    /// Auto-detect: on macOS try Apple Container first, then Docker.
    #[default]
    Auto,
    /// Always use Docker.
    Docker,
    /// Use Apple Container (macOS only).
    #[cfg(target_os = "macos")]
    #[serde(rename = "apple")]
    Apple,
}

/// Configuration for containerized agent mode.
///
/// When running with `--containerized`, the gateway spawns each agent
/// in an isolated container for multi-user safety.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ContainerAgentConfig {
    /// Container backend to use (auto, docker, apple).
    pub backend: ContainerAgentBackend,
    /// Container image for the agent.
    pub image: String,
    /// Docker binary path/name override (Docker backend only).
    pub docker_binary: Option<String>,
    /// Memory limit (e.g., "1g") — Docker only, ignored by Apple Container.
    pub memory_limit: Option<String>,
    /// CPU limit (e.g., "2.0") — Docker only, ignored by Apple Container.
    pub cpu_limit: Option<String>,
    /// Request timeout in seconds.
    pub timeout_secs: u64,
    /// Network mode (default: "none" for security) — Docker only.
    pub network: String,
    /// Extra volume mounts (host:container format).
    pub extra_mounts: Vec<String>,
    /// Maximum number of concurrent container invocations.
    pub max_concurrent: usize,
}

impl Default for ContainerAgentConfig {
    fn default() -> Self {
        Self {
            backend: ContainerAgentBackend::Auto,
            image: "zeptoclaw:latest".to_string(),
            docker_binary: None,
            memory_limit: Some("1g".to_string()),
            cpu_limit: Some("2.0".to_string()),
            timeout_secs: 300,
            network: "none".to_string(),
            extra_mounts: Vec::new(),
            max_concurrent: 5,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_swarm_config_defaults() {
        let config = SwarmConfig::default();
        assert!(config.enabled);
        assert_eq!(config.max_depth, 1);
        assert_eq!(config.max_concurrent, 3);
        assert!(config.roles.is_empty());
    }

    #[test]
    fn test_swarm_config_deserialize() {
        let json = r#"{
            "enabled": true,
            "roles": {
                "researcher": {
                    "system_prompt": "You are a researcher.",
                    "tools": ["web_search", "web_fetch"]
                }
            }
        }"#;
        let config: SwarmConfig = serde_json::from_str(json).unwrap();
        assert!(config.enabled);
        assert_eq!(config.roles.len(), 1);
        let role = config.roles.get("researcher").unwrap();
        assert_eq!(role.tools, vec!["web_search", "web_fetch"]);
    }

    #[test]
    fn test_swarm_role_defaults() {
        let role = SwarmRole::default();
        assert!(role.system_prompt.is_empty());
        assert!(role.tools.is_empty());
    }

    #[test]
    fn test_streaming_defaults_to_false() {
        let defaults = AgentDefaults::default();
        assert!(!defaults.streaming);
    }

    #[test]
    fn test_streaming_config_deserialize() {
        let json = r#"{"streaming": true}"#;
        let defaults: AgentDefaults = serde_json::from_str(json).unwrap();
        assert!(defaults.streaming);
    }

    #[test]
    fn test_config_with_swarm_deserialize() {
        let json = r#"{
            "swarm": {
                "enabled": false,
                "max_depth": 2
            }
        }"#;
        let config: Config = serde_json::from_str(json).unwrap();
        assert!(!config.swarm.enabled);
        assert_eq!(config.swarm.max_depth, 2);
    }
}