-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathconfigure.rs
More file actions
2136 lines (1885 loc) · 71.5 KB
/
configure.rs
File metadata and controls
2136 lines (1885 loc) · 71.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::recipes::github_recipe::GOOSE_RECIPE_GITHUB_REPO_CONFIG_KEY;
use cliclack::spinner;
use console::style;
use goose::agents::extension::{ToolInfo, PLATFORM_EXTENSIONS};
use goose::agents::extension_manager::get_parameter_names;
use goose::agents::Agent;
use goose::agents::{extension::Envs, ExtensionConfig};
use goose::config::declarative_providers::{
create_custom_provider, remove_custom_provider, CreateCustomProviderParams,
};
use goose::config::extensions::{
get_all_extension_names, get_all_extensions, get_enabled_extensions, get_extension_by_name,
name_to_key, remove_extension, set_extension, set_extension_enabled,
};
use goose::config::paths::Paths;
use goose::config::permission::PermissionLevel;
use goose::config::signup_tetrate::TetrateAuth;
use goose::config::{
configure_tetrate, Config, ConfigError, ExperimentManager, ExtensionEntry, GooseMode,
PermissionManager,
};
use goose::model::ModelConfig;
use goose::posthog::{get_telemetry_choice, TELEMETRY_ENABLED_KEY};
use goose::providers::base::ConfigKey;
use goose::providers::chatgpt_codex::reasoning_levels_for_model;
use goose::providers::formats::anthropic::supports_adaptive_thinking;
use goose::providers::provider_test::test_provider_configuration;
use goose::providers::{create, providers, retry_operation, RetryConfig};
use goose::session::SessionType;
use serde_json::Value;
use std::collections::HashMap;
// useful for light themes where there is no discernible colour contrast between
// cursor-selected and cursor-unselected items.
const MULTISELECT_VISIBILITY_HINT: &str = "<";
pub async fn handle_configure() -> anyhow::Result<()> {
let config = Config::global();
if !config.exists() {
handle_first_time_setup(config).await
} else {
handle_existing_config().await
}
}
pub fn configure_telemetry_consent_dialog() -> anyhow::Result<bool> {
let config = Config::global();
println!();
println!("{}", style("Help improve goose").bold());
println!();
println!(
"{}",
style("Would you like to help improve goose by sharing anonymous usage data?").dim()
);
println!(
"{}",
style("This helps us understand how goose is used and identify areas for improvement.")
.dim()
);
println!();
println!("{}", style("What we collect:").dim());
println!(
"{}",
style(" • Operating system, version, and architecture").dim()
);
println!("{}", style(" • goose version and install method").dim());
println!("{}", style(" • Provider and model used").dim());
println!(
"{}",
style(" • Extensions and tool usage counts (names only)").dim()
);
println!(
"{}",
style(" • Session metrics (duration, interaction count, token usage)").dim()
);
println!(
"{}",
style(" • Error types (e.g., \"rate_limit\", \"auth\" - no details)").dim()
);
println!();
println!(
"{}",
style("We never collect your conversations, code, tool arguments, error messages,").dim()
);
println!(
"{}",
style("or any personal data. You can change this anytime with 'goose configure'.").dim()
);
println!();
let enabled = cliclack::confirm("Share anonymous usage data to help improve goose?")
.initial_value(true)
.interact()?;
config.set_param(TELEMETRY_ENABLED_KEY, enabled)?;
if enabled {
let _ = cliclack::log::success("Thank you for helping improve goose!");
} else {
let _ = cliclack::log::info("Telemetry disabled. You can enable it anytime in settings.");
}
Ok(enabled)
}
async fn handle_first_time_setup(config: &Config) -> anyhow::Result<()> {
println!();
println!("{}", style("Welcome to goose! Let's get you set up.").dim());
println!(
"{}",
style(" you can rerun this command later to update your configuration").dim()
);
println!();
configure_telemetry_consent_dialog()?;
println!();
cliclack::intro(style(" goose-configure ").on_cyan().black())?;
let setup_method = cliclack::select("How would you like to set up your provider?")
.item(
"openrouter",
"OpenRouter Login (Recommended)",
"Sign in with OpenRouter to automatically configure models",
)
.item(
"tetrate",
"Tetrate Agent Router Service Login",
"Sign in with Tetrate Agent Router Service to automatically configure models",
)
.item(
"manual",
"Manual Configuration",
"Choose a provider and enter credentials manually",
)
.interact()?;
match setup_method {
"openrouter" => {
if let Err(e) = handle_openrouter_auth().await {
let _ = config.clear();
println!(
"\n {} OpenRouter authentication failed: {} \n Please try again or use manual configuration",
style("Error").red().italic(),
e,
);
}
}
"tetrate" => {
if let Err(e) = handle_tetrate_auth().await {
let _ = config.clear();
println!(
"\n {} Tetrate Agent Router Service authentication failed: {} \n Please try again or use manual configuration",
style("Error").red().italic(),
e,
);
}
}
"manual" => handle_manual_provider_setup(config).await,
_ => unreachable!(),
}
Ok(())
}
async fn handle_manual_provider_setup(config: &Config) {
match configure_provider_dialog().await {
Ok(true) => {
println!(
"\n {}: Run '{}' again to adjust your config or add extensions",
style("Tip").green().italic(),
style("goose configure").cyan()
);
set_extension(ExtensionEntry {
enabled: true,
config: ExtensionConfig::default(),
});
}
Ok(false) => {
let _ = config.clear();
println!(
"\n {}: We did not save your config, inspect your credentials\n and run '{}' again to ensure goose can connect",
style("Warning").yellow().italic(),
style("goose configure").cyan()
);
}
Err(e) => {
let _ = config.clear();
print_manual_config_error(&e);
}
}
}
fn print_manual_config_error(e: &anyhow::Error) {
match e.downcast_ref::<ConfigError>() {
Some(ConfigError::NotFound(key)) => {
println!(
"\n {} Required configuration key '{}' not found \n Please provide this value and run '{}' again",
style("Error").red().italic(),
key,
style("goose configure").cyan()
);
}
Some(ConfigError::KeyringError(msg)) => {
print_keyring_error(msg);
}
Some(ConfigError::DeserializeError(msg)) => {
println!(
"\n {} Invalid configuration value: {} \n Please check your input and run '{}' again",
style("Error").red().italic(),
msg,
style("goose configure").cyan()
);
}
Some(ConfigError::FileError(err)) => {
println!(
"\n {} Failed to access config file: {} \n Please check file permissions and run '{}' again",
style("Error").red().italic(),
err,
style("goose configure").cyan()
);
}
Some(ConfigError::DirectoryError(msg)) => {
println!(
"\n {} Failed to access config directory: {} \n Please check directory permissions and run '{}' again",
style("Error").red().italic(),
msg,
style("goose configure").cyan()
);
}
_ => {
println!(
"\n {} {} \n We did not save your config, inspect your credentials\n and run '{}' again to ensure goose can connect",
style("Error").red().italic(),
e,
style("goose configure").cyan()
);
}
}
}
#[cfg(target_os = "macos")]
fn print_keyring_error(msg: &str) {
println!(
"\n {} Failed to access secure storage (keyring): {} \n Please check your system keychain and run '{}' again. \n If your system is unable to use the keyring, please try setting secret key(s) via environment variables.",
style("Error").red().italic(),
msg,
style("goose configure").cyan()
);
}
#[cfg(target_os = "windows")]
fn print_keyring_error(msg: &str) {
println!(
"\n {} Failed to access Windows Credential Manager: {} \n Please check Windows Credential Manager and run '{}' again. \n If your system is unable to use the Credential Manager, please try setting secret key(s) via environment variables.",
style("Error").red().italic(),
msg,
style("goose configure").cyan()
);
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn print_keyring_error(msg: &str) {
println!(
"\n {} Failed to access secure storage: {} \n Please check your system's secure storage and run '{}' again. \n If your system is unable to use secure storage, please try setting secret key(s) via environment variables.",
style("Error").red().italic(),
msg,
style("goose configure").cyan()
);
}
async fn handle_existing_config() -> anyhow::Result<()> {
let config_dir = Paths::config_dir().display().to_string();
println!();
println!(
"{}",
style("This will update your existing config files").dim()
);
println!(
"{} {}",
style(" if you prefer, you can edit them directly at").dim(),
config_dir
);
println!();
cliclack::intro(style(" goose-configure ").on_cyan().black())?;
let action = cliclack::select("What would you like to configure?")
.item(
"providers",
"Configure Providers",
"Change provider or update credentials",
)
.item(
"custom_providers",
"Custom Providers",
"Add custom provider with compatible API",
)
.item("add", "Add Extension", "Connect to a new extension")
.item(
"toggle",
"Toggle Extensions",
"Enable or disable connected extensions",
)
.item("remove", "Remove Extension", "Remove an extension")
.item(
"settings",
"goose settings",
"Set the goose mode, Tool Output, Tool Permissions, Experiment, goose recipe github repo and more",
)
.interact()?;
match action {
"toggle" => toggle_extensions_dialog(),
"add" => configure_extensions_dialog(),
"remove" => remove_extension_dialog(),
"settings" => configure_settings_dialog().await,
"providers" => configure_provider_dialog().await.map(|_| ()),
"custom_providers" => configure_custom_provider_dialog().await,
_ => unreachable!(),
}
}
/// Helper function to handle OAuth configuration for a provider
async fn handle_oauth_configuration(provider_name: &str, key_name: &str) -> anyhow::Result<()> {
let _ = cliclack::log::info(format!(
"Configuring {} using OAuth device code flow...",
key_name
));
// Create a temporary provider instance to handle OAuth
let temp_model = ModelConfig::new("temp")?.with_canonical_limits(provider_name);
match create(provider_name, temp_model, Vec::new()).await {
Ok(provider) => match provider.configure_oauth().await {
Ok(_) => {
let _ = cliclack::log::success("OAuth authentication completed successfully!");
Ok(())
}
Err(e) => {
let _ = cliclack::log::error(format!("Failed to authenticate: {}", e));
Err(anyhow::anyhow!(
"OAuth authentication failed for {}: {}",
key_name,
e
))
}
},
Err(e) => {
let _ = cliclack::log::error(format!("Failed to create provider for OAuth: {}", e));
Err(anyhow::anyhow!(
"Failed to create provider for OAuth: {}",
e
))
}
}
}
fn interactive_model_search(models: &[String]) -> anyhow::Result<String> {
const MAX_VISIBLE: usize = 30;
let mut query = String::new();
loop {
let _ = cliclack::clear_screen();
let _ = cliclack::log::info(format!(
"🔍 {} models available. Type to filter.",
models.len()
));
let input: String = cliclack::input("Filtering models, press Enter to search")
.placeholder("e.g., gpt, sonnet, llama, qwen")
.default_input(&query)
.interact::<String>()?;
query = input.trim().to_string();
let filtered: Vec<String> = if query.is_empty() {
models.to_vec()
} else {
let q = query.to_lowercase();
models
.iter()
.filter(|m| m.to_lowercase().contains(&q))
.cloned()
.collect()
};
if filtered.is_empty() {
let _ = cliclack::log::warning("No matching models. Try a different search.");
continue;
}
let mut items: Vec<(String, String, &str)> = filtered
.iter()
.take(MAX_VISIBLE)
.map(|m| (m.clone(), m.clone(), ""))
.collect();
if filtered.len() > MAX_VISIBLE {
items.insert(
0,
(
"__refine__".to_string(),
format!(
"Refine search to see more (showing {} of {} results)",
MAX_VISIBLE,
filtered.len()
),
"Too many matches",
),
);
} else {
items.insert(
0,
(
"__new_search__".to_string(),
"Start a new search...".to_string(),
"Enter a different search term",
),
);
}
let selection = cliclack::select("Select a model:")
.items(&items)
.interact()?;
if selection == "__refine__" {
continue;
} else if selection == "__new_search__" {
query.clear();
continue;
} else {
return Ok(selection);
}
}
}
fn select_model_from_list(
models: &[String],
provider_meta: &goose::providers::base::ProviderMetadata,
) -> anyhow::Result<String> {
const MAX_MODELS: usize = 10;
const UNLISTED_MODEL_KEY: &str = "__unlisted__";
// Smart model selection:
// If we have more than MAX_MODELS models, show the recommended models with additional search option.
// Otherwise, show all models without search.
if models.len() > MAX_MODELS {
let recommended_models: Vec<String> = provider_meta
.known_models
.iter()
.map(|m| m.name.clone())
.filter(|name| models.contains(name))
.collect();
if !recommended_models.is_empty() {
let mut model_items: Vec<(String, String, &str)> = recommended_models
.iter()
.map(|m| (m.clone(), m.clone(), "Recommended"))
.collect();
model_items.insert(
0,
(
"search_all".to_string(),
"Search all models...".to_string(),
"Search complete model list",
),
);
model_items.push((
UNLISTED_MODEL_KEY.to_string(),
"Enter a model not listed...".to_string(),
"",
));
let selection = cliclack::select("Select a model:")
.items(&model_items)
.interact()?;
if selection == "search_all" {
Ok(interactive_model_search(models)?)
} else if selection == UNLISTED_MODEL_KEY {
prompt_unlisted_model(provider_meta)
} else {
Ok(selection)
}
} else {
Ok(interactive_model_search(models)?)
}
} else {
let mut model_items: Vec<(String, String, &str)> =
models.iter().map(|m| (m.clone(), m.clone(), "")).collect();
model_items.push((
UNLISTED_MODEL_KEY.to_string(),
"Enter a model not listed...".to_string(),
"",
));
let selection = cliclack::select("Select a model:")
.items(&model_items)
.interact()?;
if selection == UNLISTED_MODEL_KEY {
prompt_unlisted_model(provider_meta)
} else {
Ok(selection)
}
}
}
fn prompt_unlisted_model(
provider_meta: &goose::providers::base::ProviderMetadata,
) -> anyhow::Result<String> {
let model: String = cliclack::input("Enter the model name:")
.placeholder(&provider_meta.default_model)
.validate(|input: &String| {
if input.trim().is_empty() {
Err("Please enter a model name")
} else {
Ok(())
}
})
.interact()?;
Ok(model.trim().to_string())
}
fn try_store_secret(config: &Config, key_name: &str, value: String) -> anyhow::Result<bool> {
match config.set_secret(key_name, &value) {
Ok(_) => Ok(true),
Err(ConfigError::FallbackToFileStorage) => Ok(true),
Err(e) => {
cliclack::outro(style(format!(
"Failed to store {} securely: {}. Please ensure your system's secure storage is accessible. Alternatively you can run with GOOSE_DISABLE_KEYRING=true or set the key in your environment variables",
key_name, e
)).on_red().white())?;
Ok(false)
}
}
}
async fn configure_single_key(
config: &Config,
provider_name: &str,
display_name: &str,
key: &ConfigKey,
) -> anyhow::Result<bool> {
let from_env = std::env::var(&key.name).ok();
match from_env {
Some(env_value) => {
let _ = cliclack::log::info(format!("{} is set via environment variable", key.name));
if cliclack::confirm("Would you like to save this value to your keyring?")
.initial_value(true)
.interact()?
{
if key.secret {
if !try_store_secret(config, &key.name, env_value)? {
return Ok(false);
}
} else {
config.set_param(&key.name, &env_value)?;
}
let _ = cliclack::log::info(format!("Saved {} to {}", key.name, config.path()));
}
}
None => {
let existing: Result<String, _> = if key.secret {
config.get_secret(&key.name)
} else {
config.get_param(&key.name)
};
match existing {
Ok(_) => {
let _ = cliclack::log::info(format!("{} is already configured", key.name));
if cliclack::confirm("Would you like to update this value?").interact()? {
if key.oauth_flow {
handle_oauth_configuration(provider_name, &key.name).await?;
} else {
let value: String = if key.secret {
cliclack::password(format!("Enter new value for {}", key.name))
.mask('▪')
.interact()?
} else {
let mut input =
cliclack::input(format!("Enter new value for {}", key.name));
if key.default.is_some() {
input = input.default_input(&key.default.clone().unwrap());
}
input.interact()?
};
if key.secret {
if !try_store_secret(config, &key.name, value)? {
return Ok(false);
}
} else {
config.set_param(&key.name, &value)?;
}
}
}
}
Err(_) => {
if key.oauth_flow {
handle_oauth_configuration(provider_name, &key.name).await?;
} else if !key.required && key.secret {
if cliclack::confirm(format!(
"Would you like to set {}? (optional)",
key.name
))
.initial_value(true)
.interact()?
{
let value: String =
cliclack::password(format!("Enter value for {}", key.name))
.mask('▪')
.interact()?;
if !try_store_secret(config, &key.name, value)? {
return Ok(false);
}
}
} else {
let prompt = if key.required {
format!(
"Provider {} requires {}, please enter a value",
display_name, key.name
)
} else {
format!("Enter {} (optional, press Enter to skip)", key.name)
};
let value: String = if key.secret {
cliclack::password(&prompt).mask('▪').interact()?
} else {
let mut input = cliclack::input(&prompt);
if key.default.is_some() {
input = input.default_input(&key.default.clone().unwrap());
}
if !key.required {
input = input.required(false);
}
input.interact()?
};
if value.is_empty() {
return Ok(true);
}
if key.secret {
if !try_store_secret(config, &key.name, value)? {
return Ok(false);
}
} else {
config.set_param(&key.name, &value)?;
}
}
}
}
}
}
Ok(true)
}
pub async fn configure_provider_dialog() -> anyhow::Result<bool> {
// Get global config instance
let config = Config::global();
// Get all available providers and their metadata
let mut available_providers = providers().await;
// Sort providers alphabetically by display name
available_providers.sort_by(|a, b| a.0.display_name.cmp(&b.0.display_name));
// Create selection items from provider metadata
let provider_items: Vec<(&String, &str, &str)> = available_providers
.iter()
.map(|(p, _)| (&p.name, p.display_name.as_str(), p.description.as_str()))
.collect();
// Get current default provider if it exists
let current_provider: Option<String> = config.get_goose_provider().ok();
let default_provider = current_provider.unwrap_or_default();
// Select provider
let provider_name = cliclack::select("Which model provider should we use?")
.initial_value(&default_provider)
.items(&provider_items)
.filter_mode()
.interact()?;
// Get the selected provider's metadata
let (provider_meta, _) = available_providers
.iter()
.find(|(p, _)| &p.name == provider_name)
.expect("Selected provider must exist in metadata");
for key in provider_meta
.config_keys
.iter()
.filter(|k| k.primary || k.oauth_flow)
{
if !configure_single_key(config, provider_name, &provider_meta.display_name, key).await? {
return Ok(false);
}
}
let non_primary_keys: Vec<_> = provider_meta
.config_keys
.iter()
.filter(|k| !k.primary && !k.oauth_flow)
.collect();
if !non_primary_keys.is_empty()
&& cliclack::confirm("Would you like to configure advanced settings?")
.initial_value(false)
.interact()?
{
for key in non_primary_keys {
if !configure_single_key(config, provider_name, &provider_meta.display_name, key)
.await?
{
return Ok(false);
}
}
}
let spin = spinner();
spin.start("Attempting to fetch supported models...");
let models_res = {
let temp_model_config =
ModelConfig::new(&provider_meta.default_model)?.with_canonical_limits(provider_name);
let temp_provider = create(provider_name, temp_model_config, Vec::new()).await?;
retry_operation(&RetryConfig::default(), || async {
temp_provider.fetch_recommended_models().await
})
.await
};
spin.stop(style("Model fetch complete").green());
// Select a model: on fetch error show styled error and abort; if models available, show list; otherwise free-text input
let model: String = match models_res {
Err(e) => {
// Provider hook error
cliclack::outro(style(e.to_string()).on_red().white())?;
return Ok(false);
}
Ok(models) if !models.is_empty() => select_model_from_list(&models, provider_meta)?,
Ok(_) => {
let default_model =
std::env::var("GOOSE_MODEL").unwrap_or(provider_meta.default_model.clone());
cliclack::input("Enter a model from that provider:")
.default_input(&default_model)
.interact()?
}
};
if model.to_lowercase().starts_with("gemini-3") {
let thinking_level: &str = cliclack::select("Select thinking level for Gemini 3:")
.item("low", "Low - Better latency, lighter reasoning", "")
.item("high", "High - Deeper reasoning, higher latency", "")
.interact()?;
config.set_gemini3_thinking_level(thinking_level)?;
}
if model.to_lowercase().starts_with("claude-") {
let supports_adaptive = supports_adaptive_thinking(&model);
let mut thinking_select = cliclack::select("Select extended thinking mode for Claude:");
if supports_adaptive {
thinking_select = thinking_select.item(
"adaptive",
"Adaptive - Claude decides when and how much to think (recommended)",
"",
);
}
thinking_select = thinking_select
.item("enabled", "Enabled - Fixed token budget for thinking", "")
.item("disabled", "Disabled - No extended thinking", "");
if supports_adaptive {
thinking_select = thinking_select.initial_value("adaptive");
} else {
thinking_select = thinking_select.initial_value("disabled");
}
let thinking_type: &str = thinking_select.interact()?;
config.set_claude_thinking_type(thinking_type)?;
if thinking_type == "adaptive" {
let effort: &str = cliclack::select("Select adaptive thinking effort level:")
.item("low", "Low - Minimal thinking, fastest responses", "")
.item("medium", "Medium - Moderate thinking", "")
.item("high", "High - Deep reasoning (default)", "")
.item(
"max",
"Max - No constraints on thinking depth (Opus 4.6 only)",
"",
)
.initial_value("high")
.interact()?;
config.set_claude_thinking_effort(effort)?;
} else if thinking_type == "enabled" {
let budget: String = cliclack::input("Enter thinking budget (tokens):")
.default_input("16000")
.validate(|input: &String| match input.parse::<i32>() {
Ok(n) if n > 0 => Ok(()),
_ => Err("Please enter a valid positive number"),
})
.interact()?;
config.set_claude_thinking_budget(budget.parse::<i32>()?)?;
}
}
if provider_name == "chatgpt_codex" {
let valid_levels = reasoning_levels_for_model(&model);
if !valid_levels.is_empty() {
let mut select = cliclack::select("Select reasoning effort level:");
for &level in valid_levels {
let description = match level {
"low" => "Low - Fast responses with lighter reasoning",
"medium" => "Medium - Balances speed and reasoning depth for everyday tasks",
"high" => "High - Greater reasoning depth for complex problems",
"xhigh" => "Extra High - Extra high reasoning depth for complex problems",
_ => "",
};
select = select.item(level, description, "");
}
select = select.initial_value("medium");
let effort: &str = select.interact()?;
config.set_chatgpt_codex_reasoning_effort(effort.to_string())?;
}
}
// Test the configuration
let spin = spinner();
spin.start("Checking your configuration...");
let toolshim_enabled = std::env::var("GOOSE_TOOLSHIM")
.map(|val| val == "1" || val.to_lowercase() == "true")
.unwrap_or(false);
let toolshim_model = std::env::var("GOOSE_TOOLSHIM_OLLAMA_MODEL").ok();
match test_provider_configuration(provider_name, &model, toolshim_enabled, toolshim_model).await
{
Ok(()) => {
config.set_goose_provider(provider_name)?;
config.set_goose_model(&model)?;
print_config_file_saved()?;
Ok(true)
}
Err(e) => {
spin.stop(style(e.to_string()).red());
cliclack::outro(style("Failed to configure provider: init chat completion request with tool did not succeed.").on_red().white())?;
Ok(false)
}
}
}
/// Configure extensions that can be used with goose
/// Dialog for toggling which extensions are enabled/disabled
pub fn toggle_extensions_dialog() -> anyhow::Result<()> {
for warning in goose::config::get_warnings() {
eprintln!("{}", style(format!("Warning: {}", warning)).yellow());
}
let extensions = get_all_extensions();
if extensions.is_empty() {
cliclack::outro(
"No extensions configured yet. Run configure and add some extensions first.",
)?;
return Ok(());
}
// Create a list of extension names and their enabled status
let mut extension_status: Vec<(String, bool)> = extensions
.iter()
.map(|entry| (entry.config.name().to_string(), entry.enabled))
.collect();
// Sort extensions alphabetically by name
extension_status.sort_by(|a, b| a.0.cmp(&b.0));
// Get currently enabled extensions for the selection
let enabled_extensions: Vec<&String> = extension_status
.iter()
.filter(|(_, enabled)| *enabled)
.map(|(name, _)| name)
.collect();
// Let user toggle extensions
let selected = cliclack::multiselect(
"enable extensions: (use \"space\" to toggle and \"enter\" to submit)",
)
.required(false)
.items(
&extension_status
.iter()
.map(|(name, _)| (name, name.as_str(), MULTISELECT_VISIBILITY_HINT))
.collect::<Vec<_>>(),
)
.initial_values(enabled_extensions)
.filter_mode()
.interact()?;
// Update enabled status for each extension
for name in extension_status.iter().map(|(name, _)| name) {
set_extension_enabled(
&name_to_key(name),
selected.iter().any(|s| s.as_str() == name),
);
}
let config = Config::global();
cliclack::outro(format!(
"Extension settings saved successfully to {}",
config.path()
))?;
Ok(())
}
fn prompt_extension_timeout() -> anyhow::Result<u64> {
Ok(
cliclack::input("Please set the timeout for this tool (in secs):")
.placeholder(&goose::config::DEFAULT_EXTENSION_TIMEOUT.to_string())
.validate(|input: &String| match input.parse::<u64>() {
Ok(_) => Ok(()),
Err(_) => Err("Please enter a valid timeout"),
})
.interact()?,
)
}
fn prompt_extension_description() -> anyhow::Result<String> {
Ok(cliclack::input("Enter a description for this extension:")
.placeholder("Description")
.validate(|input: &String| {
if input.trim().is_empty() {
Err("Please enter a valid description")
} else {
Ok(())
}
})
.interact()?)
}
fn prompt_extension_name(placeholder: &str) -> anyhow::Result<String> {
let extensions = get_all_extension_names();
Ok(
cliclack::input("What would you like to call this extension?")
.placeholder(placeholder)
.validate(move |input: &String| {
if input.is_empty() {
Err("Please enter a name")
} else if extensions.contains(input) {
Err("An extension with this name already exists")
} else {
Ok(())
}
})
.interact()?,
)
}
fn collect_env_vars() -> anyhow::Result<(HashMap<String, String>, Vec<String>)> {
let envs = HashMap::new();
let mut env_keys = Vec::new();
let config = Config::global();
if !cliclack::confirm("Would you like to add environment variables?").interact()? {
return Ok((envs, env_keys));
}
loop {
let key: String = cliclack::input("Environment variable name:")
.placeholder("API_KEY")
.interact()?;
let value: String = cliclack::password("Environment variable value:")
.mask('▪')
.interact()?;
if !try_store_secret(config, &key, value)? {
return Err(anyhow::anyhow!("Failed to store secret"));
}
env_keys.push(key);
if !cliclack::confirm("Add another environment variable?").interact()? {
break;
}
}
Ok((envs, env_keys))
}
fn collect_headers() -> anyhow::Result<HashMap<String, String>> {
let mut headers = HashMap::new();
if !cliclack::confirm("Would you like to add custom headers?").interact()? {
return Ok(headers);
}