opencrabs 0.3.25

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
use std::path::PathBuf;

use crate::config::Config;

use super::types::*;
use super::wizard::OnboardingWizard;
use crate::tui::provider_selector::CUSTOM_PROVIDER_IDX;

/// Try to write a config key, collecting errors into a Vec for later reporting.
macro_rules! try_write {
    ($errors:expr, $section:expr, $key:expr, $val:expr) => {
        if let Err(e) = Config::write_key($section, $key, $val) {
            tracing::warn!("Failed to write {}.{}: {}", $section, $key, e);
            $errors.push(format!("{}.{}", $section, $key));
        }
    };
}

/// Try to write a keys.toml key, collecting errors into a Vec for later reporting.
macro_rules! try_write_keys {
    ($errors:expr, $section:expr, $key:expr, $val:expr) => {
        if let Err(e) = Config::write_keys_key($section, $key, $val) {
            tracing::warn!("Failed to write keys.toml {}.{}: {}", $section, $key, e);
            $errors.push(format!("{}.{}", $section, $key));
        }
    };
}

/// Try to write a config array, collecting errors into a Vec for later reporting.
macro_rules! try_write_array {
    ($errors:expr, $section:expr, $key:expr, $val:expr) => {
        if let Err(e) = Config::write_array($section, $key, $val) {
            tracing::warn!("Failed to write {}.{}: {}", $section, $key, e);
            $errors.push(format!("{}.{}", $section, $key));
        }
    };
}

impl OnboardingWizard {
    /// Ensure config.toml and keys.toml exist in the workspace directory
    pub(super) fn ensure_config_files(&mut self) -> Result<(), String> {
        let workspace_path = std::path::PathBuf::from(&self.workspace_path);

        // Create workspace directory if it doesn't exist
        if !workspace_path.exists() {
            std::fs::create_dir_all(&workspace_path)
                .map_err(|e| format!("Failed to create workspace directory: {}", e))?;
        }

        let config_path = workspace_path.join("config.toml");
        let keys_path = workspace_path.join("keys.toml");

        // Create config.toml if it doesn't exist (copy from embedded example)
        if !config_path.exists() {
            let config_content = include_str!("../../../config.toml.example");
            std::fs::write(&config_path, config_content)
                .map_err(|e| format!("Failed to write config.toml: {}", e))?;
            tracing::info!("Created config.toml at {:?}", config_path);
        }

        // Create keys.toml if it doesn't exist (copy from embedded example)
        if !keys_path.exists() {
            let keys_content = include_str!("../../../keys.toml.example");
            std::fs::write(&keys_path, keys_content)
                .map_err(|e| format!("Failed to write keys.toml: {}", e))?;
            tracing::info!("Created keys.toml at {:?}", keys_path);
        }

        // Ensure usage_pricing.toml exists and is up to date
        // (also called on startup, but onboarding may run before that path)
        crate::usage::pricing::PricingConfig::seed_from_example();

        // Reload models for the selected provider from the newly created config
        self.ps.reload_config_models();

        Ok(())
    }

    /// Initialize health check results
    pub fn start_health_check(&mut self) {
        // Reload config from disk so re-check picks up external changes
        if self.quick_jump
            && let Ok(config) = crate::config::Config::load()
        {
            let fresh = Self::from_config(&config);
            self.ps.api_key_input = fresh.ps.api_key_input;
            self.ps.selected_provider = fresh.ps.selected_provider;
            self.workspace_path = fresh.workspace_path;
            self.channel_toggles = fresh.channel_toggles;
            self.telegram_token_input = fresh.telegram_token_input;
            self.telegram_user_id_input = fresh.telegram_user_id_input;
            self.discord_token_input = fresh.discord_token_input;
            self.discord_channel_id_input = fresh.discord_channel_id_input;
            self.slack_bot_token_input = fresh.slack_bot_token_input;
            self.slack_app_token_input = fresh.slack_app_token_input;
            self.slack_channel_id_input = fresh.slack_channel_id_input;
            self.trello_api_key_input = fresh.trello_api_key_input;
            self.trello_api_token_input = fresh.trello_api_token_input;
            self.trello_board_id_input = fresh.trello_board_id_input;
            self.whatsapp_connected = fresh.whatsapp_connected;
            self.image_vision_enabled = fresh.image_vision_enabled;
            self.image_generation_enabled = fresh.image_generation_enabled;
            self.image_api_key_input = fresh.image_api_key_input;
        }

        let auth_label = if self.ps.is_cli() {
            "CLI Binary Found"
        } else {
            "API Key Present"
        };
        let mut checks = vec![
            (auth_label.to_string(), HealthStatus::Pending),
            ("Config File".to_string(), HealthStatus::Pending),
            ("Workspace Directory".to_string(), HealthStatus::Pending),
            ("Template Files".to_string(), HealthStatus::Pending),
        ];

        // Add channel-specific checks for enabled channels
        if self.is_telegram_enabled() {
            checks.push(("Telegram Token".to_string(), HealthStatus::Pending));
            checks.push(("Telegram User ID".to_string(), HealthStatus::Pending));
        }
        if self.is_discord_enabled() {
            checks.push(("Discord Token".to_string(), HealthStatus::Pending));
            checks.push(("Discord Channel ID".to_string(), HealthStatus::Pending));
        }
        if self.is_slack_enabled() {
            checks.push(("Slack Bot Token".to_string(), HealthStatus::Pending));
            checks.push(("Slack Channel ID".to_string(), HealthStatus::Pending));
        }
        if self.is_whatsapp_enabled() {
            checks.push(("WhatsApp Connected".to_string(), HealthStatus::Pending));
        }
        if self.is_trello_enabled() {
            checks.push(("Trello API Key".to_string(), HealthStatus::Pending));
            checks.push(("Trello API Token".to_string(), HealthStatus::Pending));
            checks.push(("Trello Board ID".to_string(), HealthStatus::Pending));
        }
        if self.image_vision_enabled || self.image_generation_enabled {
            checks.push(("Google Image API Key".to_string(), HealthStatus::Pending));
        }

        self.health_results = checks;
        self.health_running = true;
        self.health_complete = false;
    }

    /// Resolve pending health checks (call from tick to show Pending state for one frame).
    pub fn tick_health_check(&mut self) {
        if self.health_running && !self.health_complete {
            self.run_health_checks();
        }
    }

    /// Execute all health checks
    fn run_health_checks(&mut self) {
        // Check 1: API key / CLI binary present
        self.health_results[0].1 = if self.ps.is_cli() {
            // CLI providers: check if the binary is installed
            let binary = match self.ps.provider_id() {
                "claude-cli" => "claude",
                "codex-cli" => "codex",
                _ => "opencode",
            };
            if which::which(binary).is_ok() {
                HealthStatus::Pass
            } else {
                HealthStatus::Fail(format!("'{}' CLI not found in PATH", binary))
            }
        } else if !self.ps.api_key_input.is_empty()
            || (self.ps.is_custom() && !self.ps.base_url.is_empty())
        {
            HealthStatus::Pass
        } else {
            HealthStatus::Fail("No API key provided".to_string())
        };

        // Check 2: Config path writable
        let config_path = crate::config::opencrabs_home().join("config.toml");
        self.health_results[1].1 = if let Some(parent) = config_path.parent() {
            if parent.exists() || std::fs::create_dir_all(parent).is_ok() {
                HealthStatus::Pass
            } else {
                HealthStatus::Fail(format!("Cannot create {}", parent.display()))
            }
        } else {
            HealthStatus::Fail("Invalid config path".to_string())
        };

        // Check 3: Workspace directory
        let workspace = PathBuf::from(&self.workspace_path);
        self.health_results[2].1 =
            if workspace.exists() || std::fs::create_dir_all(&workspace).is_ok() {
                HealthStatus::Pass
            } else {
                HealthStatus::Fail(format!("Cannot create {}", workspace.display()))
            };

        // Check 4: Template files available (they're compiled in, always present)
        self.health_results[3].1 = HealthStatus::Pass;

        // Channel checks (by name, since indices depend on which channels are enabled)
        for i in 0..self.health_results.len() {
            let name = self.health_results[i].0.clone();
            self.health_results[i].1 = match name.as_str() {
                "Telegram Token" => {
                    if !self.telegram_token_input.is_empty() {
                        HealthStatus::Pass
                    } else {
                        HealthStatus::Fail("No token provided".to_string())
                    }
                }
                "Telegram User ID" => {
                    if !self.telegram_user_id_input.is_empty() {
                        HealthStatus::Pass
                    } else {
                        HealthStatus::Fail("No user ID — bot won't know who to talk to".to_string())
                    }
                }
                "Discord Token" => {
                    if !self.discord_token_input.is_empty() {
                        HealthStatus::Pass
                    } else {
                        HealthStatus::Fail("No token provided".to_string())
                    }
                }
                "Discord Channel ID" => {
                    if !self.discord_channel_id_input.is_empty() {
                        HealthStatus::Pass
                    } else {
                        HealthStatus::Fail(
                            "No channel ID — bot won't know where to post".to_string(),
                        )
                    }
                }
                "Slack Bot Token" => {
                    if !self.slack_bot_token_input.is_empty() {
                        HealthStatus::Pass
                    } else {
                        HealthStatus::Fail("No bot token provided".to_string())
                    }
                }
                "Slack Channel ID" => {
                    if !self.slack_channel_id_input.is_empty() {
                        HealthStatus::Pass
                    } else {
                        HealthStatus::Fail(
                            "No channel ID — bot won't know where to post".to_string(),
                        )
                    }
                }
                "WhatsApp Connected" => {
                    if self.whatsapp_connected {
                        HealthStatus::Pass
                    } else {
                        HealthStatus::Fail("Not paired — scan QR code to connect".to_string())
                    }
                }
                "Trello API Key" => {
                    if !self.trello_api_key_input.is_empty() {
                        HealthStatus::Pass
                    } else {
                        HealthStatus::Fail("No API Key provided".to_string())
                    }
                }
                "Trello API Token" => {
                    if !self.trello_api_token_input.is_empty() {
                        HealthStatus::Pass
                    } else {
                        HealthStatus::Fail("No API Token provided".to_string())
                    }
                }
                "Trello Board ID" => {
                    if !self.trello_board_id_input.is_empty() {
                        HealthStatus::Pass
                    } else {
                        HealthStatus::Fail(
                            "No Board ID — agent won't know which board to poll".to_string(),
                        )
                    }
                }
                "Google Image API Key" => {
                    if !self.image_api_key_input.is_empty() {
                        HealthStatus::Pass
                    } else {
                        HealthStatus::Fail(
                            "No API key — vision and image generation need a Google AI key"
                                .to_string(),
                        )
                    }
                }
                _ => continue, // Already set above
            };
        }

        self.health_running = false;
        self.health_complete = true;
    }

    /// Check if all health checks passed
    pub fn all_health_passed(&self) -> bool {
        self.health_complete
            && self
                .health_results
                .iter()
                .all(|(_, s)| matches!(s, HealthStatus::Pass))
    }

    /// Apply wizard configuration — creates config.toml, stores API key, seeds workspace
    /// Merges with existing config to preserve settings not modified in wizard.
    ///
    /// In quick_jump mode, only writes settings relevant to the current step to avoid
    /// overwriting unrelated channel/provider settings loaded with defaults.
    pub fn apply_config(&self) -> Result<(), String> {
        // Determine which sections to write based on quick_jump + current step
        let write_provider = !self.quick_jump
            || matches!(
                self.step,
                OnboardingStep::ProviderAuth | OnboardingStep::Complete
            );
        let write_channels = !self.quick_jump
            || matches!(
                self.step,
                OnboardingStep::Channels
                    | OnboardingStep::TelegramSetup
                    | OnboardingStep::DiscordSetup
                    | OnboardingStep::WhatsAppSetup
                    | OnboardingStep::SlackSetup
                    | OnboardingStep::TrelloSetup
                    | OnboardingStep::Complete
            );
        let write_voice = !self.quick_jump
            || matches!(
                self.step,
                OnboardingStep::VoiceSetup | OnboardingStep::Complete
            );
        let write_image = !self.quick_jump
            || matches!(
                self.step,
                OnboardingStep::ImageSetup | OnboardingStep::Complete
            );

        // Groq key for STT/TTS
        let groq_key = if !self.groq_api_key_input.is_empty() && !self.has_existing_groq_key() {
            Some(self.groq_api_key_input.clone())
        } else {
            None
        };

        // Write config.toml via merge (write_key) — never overwrite entire file
        let mut write_errors: Vec<String> = Vec::new();

        // Provider settings — only when relevant step is active
        let custom_section;
        let section = if self.ps.selected_provider < CUSTOM_PROVIDER_IDX {
            let id = PROVIDERS[self.ps.selected_provider].id;
            crate::utils::providers::find_provider_meta(id)
                .map(|m| m.config_section)
                .unwrap_or("providers.anthropic")
        } else {
            custom_section = format!("providers.custom.{}", self.ps.custom_name);
            &custom_section
        };

        if write_provider {
            // Disable all providers first, then enable selected one
            {
                let all_sections = if let Ok(cfg) = Config::load() {
                    crate::utils::providers::all_config_sections(&cfg.providers)
                } else {
                    crate::utils::providers::KNOWN_PROVIDERS
                        .iter()
                        .map(|p| p.config_section.to_string())
                        .collect()
                };
                for s in &all_sections {
                    if let Err(e) = Config::write_key(s, "enabled", "false") {
                        tracing::warn!("Failed to write {}.enabled: {}", s, e);
                        write_errors.push(format!("{}.enabled", s));
                    }
                }
            }

            // Enable + configure the selected provider
            let custom_section;
            let section = if self.ps.selected_provider < CUSTOM_PROVIDER_IDX {
                let id = PROVIDERS[self.ps.selected_provider].id;
                crate::utils::providers::find_provider_meta(id)
                    .map(|m| m.config_section)
                    .unwrap_or("providers.anthropic")
            } else {
                custom_section = format!("providers.custom.{}", self.ps.custom_name);
                &custom_section
            };
            try_write!(write_errors, section, "enabled", "true");
            let model = self.ps.selected_model_name().to_string();
            if !model.is_empty() {
                try_write!(write_errors, section, "default_model", &model);
            }

            // Write base_url / extra config for providers that need it
            match self.ps.provider_id() {
                "github" => {
                    try_write!(
                        write_errors,
                        section,
                        "base_url",
                        "https://api.githubcopilot.com/chat/completions"
                    );
                }
                "openrouter" => {
                    try_write!(
                        write_errors,
                        section,
                        "base_url",
                        "https://openrouter.ai/api/v1/chat/completions"
                    );
                }
                "minimax" => {
                    try_write!(
                        write_errors,
                        section,
                        "base_url",
                        "https://api.minimax.io/v1"
                    );
                }
                "zhipu" => {
                    let endpoint_type = if self.ps.zhipu_endpoint_type == 1 {
                        "coding"
                    } else {
                        "api"
                    };
                    try_write!(write_errors, section, "endpoint_type", endpoint_type);
                }
                "" => {
                    if !self.ps.base_url.is_empty() {
                        try_write!(write_errors, section, "base_url", &self.ps.base_url);
                    }
                    if !self.ps.custom_model.is_empty() {
                        try_write!(
                            write_errors,
                            section,
                            "default_model",
                            &self.ps.custom_model
                        );
                    }
                    if !self.ps.context_window.is_empty() {
                        try_write!(
                            write_errors,
                            section,
                            "context_window",
                            &self.ps.context_window
                        );
                    }
                }
                _ => {}
            }

            // Write models array for providers that have static model lists
            if !self.ps.config_models.is_empty()
                && (matches!(self.ps.provider_id(), "github" | "minimax" | "zhipu" | "")
                    || self.ps.selected_provider >= CUSTOM_PROVIDER_IDX)
            {
                try_write_array!(write_errors, section, "models", &self.ps.config_models);
            }
            // Write enable_thinking for Qwen (thinking mode on by default)
            if self.ps.provider_id() == "qwen" {
                try_write!(write_errors, section, "enable_thinking", "true");
            }
            // Clean up ghost custom provider entries (empty name/url/model)
            Config::cleanup_empty_custom_providers();
        } // end if write_provider

        // Agent defaults — ensure these are persisted on fresh install
        // (serde defaults handle runtime, but we persist so they're visible in config.toml)
        try_write!(write_errors, "agent", "approval_policy", "auto-always");

        if write_channels {
            // Channel enabled flags (from channel_toggles: 0=Telegram, 1=Discord, 2=WhatsApp, 3=Slack)
            try_write!(
                write_errors,
                "channels.telegram",
                "enabled",
                &self.is_telegram_enabled().to_string()
            );
            try_write!(
                write_errors,
                "channels.discord",
                "enabled",
                &self.is_discord_enabled().to_string()
            );
            try_write!(
                write_errors,
                "channels.whatsapp",
                "enabled",
                &self.channel_toggles.get(2).is_some_and(|t| t.1).to_string()
            );
            try_write!(
                write_errors,
                "channels.slack",
                "enabled",
                &self.is_slack_enabled().to_string()
            );
            try_write!(
                write_errors,
                "channels.trello",
                "enabled",
                &self.is_trello_enabled().to_string()
            );

            // respond_to per channel
            let respond_to_values = ["all", "dm_only", "mention"];
            try_write!(
                write_errors,
                "channels.telegram",
                "respond_to",
                respond_to_values[self.telegram_respond_to.min(2)]
            );
            try_write!(
                write_errors,
                "channels.discord",
                "respond_to",
                respond_to_values[self.discord_respond_to.min(2)]
            );
            try_write!(
                write_errors,
                "channels.slack",
                "respond_to",
                respond_to_values[self.slack_respond_to.min(2)]
            );
        } // end if write_channels

        if write_voice {
            // Voice config — uses named SttProvider/TtsProvider variants

            // ── STT providers ──
            let groq_key_exists =
                !self.groq_api_key_input.is_empty() || self.has_existing_groq_key();

            // STT: Groq
            try_write!(
                write_errors,
                "providers.stt.groq",
                "enabled",
                &(self.stt_provider == SttProvider::Groq && groq_key_exists).to_string()
            );
            if self.stt_provider == SttProvider::Groq && groq_key_exists {
                try_write!(
                    write_errors,
                    "providers.stt.groq",
                    "default_model",
                    "whisper-large-v3-turbo"
                );
                // Write Groq API key to keys.toml (only if newly entered)
                if !self.groq_api_key_input.is_empty() && !self.has_existing_groq_key() {
                    try_write_keys!(
                        write_errors,
                        "providers.stt.groq",
                        "api_key",
                        &self.groq_api_key_input
                    );
                }
            }

            // STT: Local
            try_write!(
                write_errors,
                "providers.stt.local",
                "enabled",
                &(self.stt_provider == SttProvider::Local).to_string()
            );
            if self.stt_provider == SttProvider::Local {
                #[cfg(feature = "local-stt")]
                {
                    use crate::channels::voice::local_whisper::LOCAL_MODEL_PRESETS;
                    if self.selected_local_stt_model < LOCAL_MODEL_PRESETS.len() {
                        try_write!(
                            write_errors,
                            "providers.stt.local",
                            "model",
                            LOCAL_MODEL_PRESETS[self.selected_local_stt_model].id
                        );
                    }
                }
            }

            // STT: OpenAI-compatible
            try_write!(
                write_errors,
                "providers.stt.openai_compatible",
                "enabled",
                &(self.stt_provider == SttProvider::OpenAiCompatible).to_string()
            );
            if self.stt_provider == SttProvider::OpenAiCompatible {
                if !self.stt_openai_compat_base_url.is_empty() {
                    try_write!(
                        write_errors,
                        "providers.stt.openai_compatible",
                        "base_url",
                        &self.stt_openai_compat_base_url
                    );
                }
                if !self.stt_openai_compat_model.is_empty() {
                    try_write!(
                        write_errors,
                        "providers.stt.openai_compatible",
                        "model",
                        &self.stt_openai_compat_model
                    );
                }
                // Write API key to keys.toml (only if newly entered)
                if !self.stt_openai_compat_key_input.is_empty() {
                    try_write_keys!(
                        write_errors,
                        "providers.stt.openai_compatible",
                        "api_key",
                        &self.stt_openai_compat_key_input
                    );
                }
            }

            // STT: Voicebox
            try_write!(
                write_errors,
                "providers.stt.voicebox",
                "enabled",
                &(self.stt_provider == SttProvider::Voicebox).to_string()
            );
            if self.stt_provider == SttProvider::Voicebox && !self.stt_voicebox_base_url.is_empty()
            {
                try_write!(
                    write_errors,
                    "providers.stt.voicebox",
                    "base_url",
                    &self.stt_voicebox_base_url
                );
            }

            // ── TTS providers ──

            // TTS: OpenAI
            try_write!(
                write_errors,
                "providers.tts.openai",
                "enabled",
                &(self.tts_provider == TtsProvider::OpenAi).to_string()
            );
            if self.tts_provider == TtsProvider::OpenAi {
                try_write!(
                    write_errors,
                    "providers.tts.openai",
                    "default_model",
                    "gpt-4o-mini-tts"
                );
            }

            // TTS: Local Piper
            try_write!(
                write_errors,
                "providers.tts.local",
                "enabled",
                &(self.tts_provider == TtsProvider::Local).to_string()
            );
            if self.tts_provider == TtsProvider::Local {
                #[cfg(feature = "local-tts")]
                {
                    use crate::channels::voice::local_tts::PIPER_VOICES;
                    if self.selected_tts_voice < PIPER_VOICES.len() {
                        try_write!(
                            write_errors,
                            "providers.tts.local",
                            "voice",
                            PIPER_VOICES[self.selected_tts_voice].id
                        );
                    }
                }
            }

            // TTS: OpenAI-compatible
            try_write!(
                write_errors,
                "providers.tts.openai_compatible",
                "enabled",
                &(self.tts_provider == TtsProvider::OpenAiCompatible).to_string()
            );
            if self.tts_provider == TtsProvider::OpenAiCompatible {
                if !self.tts_openai_compat_base_url.is_empty() {
                    try_write!(
                        write_errors,
                        "providers.tts.openai_compatible",
                        "base_url",
                        &self.tts_openai_compat_base_url
                    );
                }
                if !self.tts_openai_compat_model.is_empty() {
                    try_write!(
                        write_errors,
                        "providers.tts.openai_compatible",
                        "model",
                        &self.tts_openai_compat_model
                    );
                }
                if !self.tts_openai_compat_voice.is_empty() {
                    try_write!(
                        write_errors,
                        "providers.tts.openai_compatible",
                        "voice",
                        &self.tts_openai_compat_voice
                    );
                }
                // Write API key to keys.toml (only if newly entered)
                if !self.tts_openai_compat_key_input.is_empty() {
                    try_write_keys!(
                        write_errors,
                        "providers.tts.openai_compatible",
                        "api_key",
                        &self.tts_openai_compat_key_input
                    );
                }
            }

            // TTS: Voicebox
            try_write!(
                write_errors,
                "providers.tts.voicebox",
                "enabled",
                &(self.tts_provider == TtsProvider::Voicebox).to_string()
            );
            if self.tts_provider == TtsProvider::Voicebox {
                if !self.tts_voicebox_base_url.is_empty() {
                    try_write!(
                        write_errors,
                        "providers.tts.voicebox",
                        "base_url",
                        &self.tts_voicebox_base_url
                    );
                }
                if !self.tts_voicebox_profile_id.is_empty() {
                    try_write!(
                        write_errors,
                        "providers.tts.voicebox",
                        "profile_id",
                        &self.tts_voicebox_profile_id
                    );
                }
                if !self.tts_voicebox_engine.is_empty() {
                    try_write!(
                        write_errors,
                        "providers.tts.voicebox",
                        "engine",
                        &self.tts_voicebox_engine
                    );
                }
            }
        } // end if write_voice

        if write_image {
            // Image config
            let default_model = "gemini-3.1-flash-image-preview";
            // Wizard input wins; empty stays on the seeded default.
            let trimmed = self.image_generation_model_input.trim();
            let generation_model = if trimmed.is_empty() {
                default_model
            } else {
                trimmed
            };
            if self.image_generation_enabled {
                try_write!(write_errors, "image.generation", "enabled", "true");
                try_write!(write_errors, "image.generation", "model", generation_model);
            }
            if self.image_vision_enabled {
                try_write!(write_errors, "image.vision", "enabled", "true");
                try_write!(write_errors, "image.vision", "model", default_model);
            }
            // Save image API key to keys.toml (only if newly entered)
            if !self.image_api_key_input.is_empty()
                && !self.has_existing_image_key()
                && let Err(e) = crate::config::write_secret_key(
                    "providers.image.gemini",
                    "api_key",
                    &self.image_api_key_input,
                )
            {
                tracing::warn!("Failed to save image API key to keys.toml: {}", e);
            }
        } // end if write_image

        // Save API key to keys.toml via merge — never overwrite
        if write_provider
            && !self.ps.has_existing_key_sentinel()
            && !self.ps.api_key_input.is_empty()
            && let Err(e) =
                crate::config::write_secret_key(section, "api_key", &self.ps.api_key_input)
        {
            tracing::warn!("Failed to save API key to keys.toml: {}", e);
        }

        // (GitHub Copilot OAuth token is saved directly via the device flow handler)

        // Save STT/TTS keys to keys.toml
        if write_voice {
            if let Some(ref groq_key) = groq_key
                && let Err(e) =
                    crate::config::write_secret_key("providers.stt.groq", "api_key", groq_key)
            {
                tracing::warn!("Failed to save Groq key to keys.toml: {}", e);
            }
            if self.tts_enabled
                && let Some(ref groq_key) = groq_key
                && let Err(e) =
                    crate::config::write_secret_key("providers.tts.openai", "api_key", groq_key)
            {
                tracing::warn!("Failed to save TTS key to keys.toml: {}", e);
            }
            // OpenAI-compatible STT key
            if !self.stt_openai_compat_key_input.is_empty()
                && let Err(e) = crate::config::write_secret_key(
                    "providers.stt.openai_compatible",
                    "api_key",
                    &self.stt_openai_compat_key_input,
                )
            {
                tracing::warn!("Failed to save OpenAI-compatible STT key: {}", e);
            }
            // OpenAI-compatible TTS key
            if !self.tts_openai_compat_key_input.is_empty()
                && let Err(e) = crate::config::write_secret_key(
                    "providers.tts.openai_compatible",
                    "api_key",
                    &self.tts_openai_compat_key_input,
                )
            {
                tracing::warn!("Failed to save OpenAI-compatible TTS key: {}", e);
            }
        } // end voice keys

        if write_channels {
            // Persist channel tokens to keys.toml (if new)
            if !self.telegram_token_input.is_empty()
                && !self.has_existing_telegram_token()
                && let Err(e) = crate::config::write_secret_key(
                    "channels.telegram",
                    "token",
                    &self.telegram_token_input,
                )
            {
                tracing::warn!("Failed to save Telegram token to keys.toml: {}", e);
            }
            if !self.discord_token_input.is_empty()
                && !self.has_existing_discord_token()
                && let Err(e) = crate::config::write_secret_key(
                    "channels.discord",
                    "token",
                    &self.discord_token_input,
                )
            {
                tracing::warn!("Failed to save Discord token to keys.toml: {}", e);
            }
            if !self.slack_bot_token_input.is_empty()
                && !self.has_existing_slack_bot_token()
                && let Err(e) = crate::config::write_secret_key(
                    "channels.slack",
                    "token",
                    &self.slack_bot_token_input,
                )
            {
                tracing::warn!("Failed to save Slack bot token to keys.toml: {}", e);
            }
            if !self.slack_app_token_input.is_empty()
                && !self.has_existing_slack_app_token()
                && let Err(e) = crate::config::write_secret_key(
                    "channels.slack",
                    "app_token",
                    &self.slack_app_token_input,
                )
            {
                tracing::warn!("Failed to save Slack app token to keys.toml: {}", e);
            }
            // Trello API Key (saved as app_token) + API Token
            if !self.trello_api_key_input.is_empty()
                && !self.has_existing_trello_api_key()
                && let Err(e) = crate::config::write_secret_key(
                    "channels.trello",
                    "app_token",
                    &self.trello_api_key_input,
                )
            {
                tracing::warn!("Failed to save Trello API Key to keys.toml: {}", e);
            }
            if !self.trello_api_token_input.is_empty()
                && !self.has_existing_trello_api_token()
                && let Err(e) = crate::config::write_secret_key(
                    "channels.trello",
                    "token",
                    &self.trello_api_token_input,
                )
            {
                tracing::warn!("Failed to save Trello API Token to keys.toml: {}", e);
            }

            // Persist channel IDs/user IDs to config.toml (if new)
            // telegram_user_id_input is never a sentinel — write whatever
            // the user left in the field (empty = "allow any user").
            if !self.telegram_user_id_input.is_empty() {
                try_write_array!(
                    write_errors,
                    "channels.telegram",
                    "allowed_users",
                    std::slice::from_ref(&self.telegram_user_id_input)
                );
            }
            if !self.discord_channel_id_input.is_empty() && !self.has_existing_discord_channel_id()
            {
                try_write_array!(
                    write_errors,
                    "channels.discord",
                    "allowed_channels",
                    std::slice::from_ref(&self.discord_channel_id_input)
                );
            }
            if !self.slack_channel_id_input.is_empty() && !self.has_existing_slack_channel_id() {
                try_write_array!(
                    write_errors,
                    "channels.slack",
                    "allowed_channels",
                    std::slice::from_ref(&self.slack_channel_id_input)
                );
            }
            if !self.discord_allowed_list_input.is_empty()
                && !self.has_existing_discord_allowed_list()
            {
                try_write_array!(
                    write_errors,
                    "channels.discord",
                    "allowed_users",
                    std::slice::from_ref(&self.discord_allowed_list_input)
                );
            }
            if !self.slack_allowed_list_input.is_empty() && !self.has_existing_slack_allowed_list()
            {
                try_write_array!(
                    write_errors,
                    "channels.slack",
                    "allowed_users",
                    std::slice::from_ref(&self.slack_allowed_list_input)
                );
            }
            if !self.whatsapp_phone_input.is_empty() && !self.has_existing_whatsapp_phone() {
                try_write_array!(
                    write_errors,
                    "channels.whatsapp",
                    "allowed_phones",
                    std::slice::from_ref(&self.whatsapp_phone_input)
                );
            }
            if !self.trello_board_id_input.is_empty() && !self.has_existing_trello_board_id() {
                let boards: Vec<String> = self
                    .trello_board_id_input
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                if !boards.is_empty() {
                    try_write_array!(write_errors, "channels.trello", "board_ids", &boards);
                }
            }
            if !self.trello_allowed_users_input.is_empty()
                && !self.has_existing_trello_allowed_users()
            {
                let users: Vec<String> = self
                    .trello_allowed_users_input
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                if !users.is_empty() {
                    try_write_array!(write_errors, "channels.trello", "allowed_users", &users);
                }
            }
        } // end if write_channels

        // Seed workspace templates (use AI-generated content when available)
        if self.seed_templates {
            let workspace = PathBuf::from(&self.workspace_path);
            std::fs::create_dir_all(&workspace)
                .map_err(|e| format!("Failed to create workspace: {}", e))?;

            for (filename, content) in TEMPLATE_FILES {
                let file_path = workspace.join(filename);
                // Use AI-generated content when available, static template as fallback
                let generated = match *filename {
                    "SOUL.md" => self.generated_soul.as_deref(),
                    "IDENTITY.md" => self.generated_identity.as_deref(),
                    "USER.md" => self.generated_user.as_deref(),
                    "AGENTS.md" => self.generated_agents.as_deref(),
                    "TOOLS.md" => self.generated_tools.as_deref(),
                    "MEMORY.md" => self.generated_memory.as_deref(),
                    _ => None,
                };
                // Write if: AI-generated (always overwrite) or file doesn't exist (seed template)
                if generated.is_some() || !file_path.exists() {
                    let final_content = generated.unwrap_or(content);
                    std::fs::write(&file_path, final_content)
                        .map_err(|e| format!("Failed to write {}: {}", filename, e))?;
                }
            }
        }

        // Install daemon if requested
        if self.install_daemon
            && let Err(e) = install_daemon_service()
        {
            tracing::warn!("Failed to install daemon: {}", e);
            // Non-fatal — don't block onboarding completion
        }

        if !write_errors.is_empty() {
            tracing::error!(
                "Onboarding: failed to write {} config keys: {}",
                write_errors.len(),
                write_errors.join(", ")
            );
            return Err(format!(
                "Some settings could not be saved ({}). Check file permissions on config.toml.",
                write_errors.join(", ")
            ));
        }

        Ok(())
    }
}

/// Install the appropriate daemon service for the current platform
fn install_daemon_service() -> Result<(), String> {
    #[cfg(target_os = "linux")]
    {
        install_systemd_service()
    }

    #[cfg(target_os = "macos")]
    {
        install_launchagent()
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        Err("Daemon installation not supported on this platform".to_string())
    }
}

#[cfg(target_os = "linux")]
fn install_systemd_service() -> Result<(), String> {
    let service_dir = dirs::config_dir()
        .ok_or("Cannot determine config dir")?
        .parent()
        .ok_or("Cannot determine parent of config dir")?
        .join(".config")
        .join("systemd")
        .join("user");

    // Try the standard XDG path first
    let service_dir = if service_dir.exists() {
        service_dir
    } else {
        dirs::home_dir()
            .ok_or("Cannot determine home dir")?
            .join(".config")
            .join("systemd")
            .join("user")
    };

    std::fs::create_dir_all(&service_dir)
        .map_err(|e| format!("Failed to create systemd dir: {}", e))?;

    let exe_path = std::env::current_exe().map_err(|e| format!("Failed to get exe path: {}", e))?;

    let service_content = format!(
        r#"[Unit]
Description=OpenCrabs AI Orchestration Agent
After=network.target

[Service]
Type=simple
ExecStart={} daemon
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
"#,
        exe_path.display()
    );

    let service_path = service_dir.join("opencrabs.service");
    std::fs::write(&service_path, service_content)
        .map_err(|e| format!("Failed to write service file: {}", e))?;

    // Enable and start the service
    std::process::Command::new("systemctl")
        .args(["--user", "enable", "opencrabs"])
        .output()
        .map_err(|e| format!("Failed to enable service: {}", e))?;

    std::process::Command::new("systemctl")
        .args(["--user", "start", "opencrabs"])
        .output()
        .map_err(|e| format!("Failed to start service: {}", e))?;

    Ok(())
}

#[cfg(target_os = "macos")]
fn install_launchagent() -> Result<(), String> {
    let agents_dir = dirs::home_dir()
        .ok_or("Cannot determine home dir")?
        .join("Library")
        .join("LaunchAgents");

    std::fs::create_dir_all(&agents_dir)
        .map_err(|e| format!("Failed to create LaunchAgents dir: {}", e))?;

    let exe_path = std::env::current_exe().map_err(|e| format!("Failed to get exe path: {}", e))?;

    let plist_content = format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.opencrabs.agent</string>
    <key>ProgramArguments</key>
    <array>
        <string>{}</string>
        <string>daemon</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
</dict>
</plist>
"#,
        exe_path.display()
    );

    let plist_path = agents_dir.join("com.opencrabs.agent.plist");
    std::fs::write(&plist_path, plist_content)
        .map_err(|e| format!("Failed to write plist: {}", e))?;

    std::process::Command::new("launchctl")
        .args(["load", &plist_path.to_string_lossy()])
        .output()
        .map_err(|e| format!("Failed to load launch agent: {}", e))?;

    Ok(())
}