-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathsettings_tool.py
More file actions
2493 lines (2163 loc) · 99.6 KB
/
settings_tool.py
File metadata and controls
2493 lines (2163 loc) · 99.6 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
"""
Advanced settings configuration tool for the LLM API Key Proxy.
Provides interactive configuration for custom providers, model definitions, and concurrency limits.
"""
import json
import os
from pathlib import Path
from typing import Dict, Any, Optional, List
from rich.console import Console
from rich.prompt import Prompt, IntPrompt, Confirm
from rich.panel import Panel
from dotenv import set_key, unset_key
from rotator_library.utils.paths import get_data_file
console = Console()
# Sentinel value for distinguishing "no pending change" from "pending change to None"
_NOT_FOUND = object()
# Import default OAuth port values from provider modules
# These serve as the source of truth for default port values
try:
from rotator_library.providers.gemini_auth_base import GeminiAuthBase
GEMINI_CLI_DEFAULT_OAUTH_PORT = GeminiAuthBase.CALLBACK_PORT
except ImportError:
GEMINI_CLI_DEFAULT_OAUTH_PORT = 8085
try:
from rotator_library.providers.antigravity_auth_base import AntigravityAuthBase
ANTIGRAVITY_DEFAULT_OAUTH_PORT = AntigravityAuthBase.CALLBACK_PORT
except ImportError:
ANTIGRAVITY_DEFAULT_OAUTH_PORT = 51121
try:
from rotator_library.providers.iflow_auth_base import (
CALLBACK_PORT as IFLOW_DEFAULT_OAUTH_PORT,
)
except ImportError:
IFLOW_DEFAULT_OAUTH_PORT = 11451
def clear_screen(subtitle: str = ""):
"""
Cross-platform terminal clear with optional header.
Uses native OS commands instead of ANSI escape sequences:
- Windows (conhost & Windows Terminal): cls
- Unix-like systems (Linux, Mac): clear
Args:
subtitle: If provided, displays a header panel with this subtitle.
If empty/None, just clears the screen.
"""
os.system("cls" if os.name == "nt" else "clear")
if subtitle:
console.print(
Panel(
f"[bold cyan]{subtitle}[/bold cyan]",
title="--- API Key Proxy ---",
)
)
class AdvancedSettings:
"""Manages pending changes to .env"""
def __init__(self):
self.env_file = get_data_file(".env")
self.pending_changes = {} # key -> value (None means delete)
self.load_current_settings()
def load_current_settings(self):
"""Load current .env values into env vars"""
from dotenv import load_dotenv
load_dotenv(self.env_file, override=True)
def set(self, key: str, value: str):
"""Stage a change"""
self.pending_changes[key] = value
def remove(self, key: str):
"""Stage a removal"""
self.pending_changes[key] = None
def save(self):
"""Write pending changes to .env"""
for key, value in self.pending_changes.items():
if value is None:
# Remove key
unset_key(str(self.env_file), key)
else:
# Set key
set_key(str(self.env_file), key, value)
self.pending_changes.clear()
self.load_current_settings()
def discard(self):
"""Discard pending changes"""
self.pending_changes.clear()
def has_pending(self) -> bool:
"""Check if there are pending changes"""
return bool(self.pending_changes)
def get_pending_value(self, key: str):
"""Get pending value for a key. Returns sentinel _NOT_FOUND if no pending change."""
return self.pending_changes.get(key, _NOT_FOUND)
def get_original_value(self, key: str) -> Optional[str]:
"""Get the current .env value (before pending changes)"""
return os.getenv(key)
def get_change_type(self, key: str) -> Optional[str]:
"""Returns 'add', 'edit', 'remove', or None if no pending change"""
if key not in self.pending_changes:
return None
if self.pending_changes[key] is None:
return "remove"
elif os.getenv(key) is not None:
return "edit"
else:
return "add"
def get_pending_keys_by_pattern(
self, prefix: str = "", suffix: str = ""
) -> List[str]:
"""Get all pending change keys that match prefix and/or suffix"""
return [
k
for k in self.pending_changes.keys()
if k.startswith(prefix) and k.endswith(suffix)
]
def get_changes_summary(self) -> Dict[str, List[tuple]]:
"""Get categorized summary of all pending changes.
Returns dict with 'add', 'edit', 'remove' keys,
each containing list of (key, old_val, new_val) tuples.
"""
summary: Dict[str, List[tuple]] = {"add": [], "edit": [], "remove": []}
for key, new_val in self.pending_changes.items():
old_val = os.getenv(key)
change_type = self.get_change_type(key)
if change_type:
summary[change_type].append((key, old_val, new_val))
# Sort each list alphabetically by key
for change_type in summary:
summary[change_type].sort(key=lambda x: x[0])
return summary
def get_pending_counts(self) -> Dict[str, int]:
"""Get counts of pending changes by type"""
adds = len(
[
k
for k, v in self.pending_changes.items()
if v is not None and os.getenv(k) is None
]
)
edits = len(
[
k
for k, v in self.pending_changes.items()
if v is not None and os.getenv(k) is not None
]
)
removes = len([k for k, v in self.pending_changes.items() if v is None])
return {"add": adds, "edit": edits, "remove": removes}
class CustomProviderManager:
"""Manages custom provider API bases"""
def __init__(self, settings: AdvancedSettings):
self.settings = settings
def get_current_providers(self) -> Dict[str, str]:
"""Get currently configured custom providers"""
from proxy_app.provider_urls import PROVIDER_URL_MAP
providers = {}
for key, value in os.environ.items():
if key.endswith("_API_BASE"):
provider = key.replace("_API_BASE", "").lower()
# Only include if NOT in hardcoded map
if provider not in PROVIDER_URL_MAP:
providers[provider] = value
return providers
def add_provider(self, name: str, api_base: str):
"""Add PROVIDER_API_BASE"""
key = f"{name.upper()}_API_BASE"
self.settings.set(key, api_base)
def edit_provider(self, name: str, api_base: str):
"""Edit PROVIDER_API_BASE"""
self.add_provider(name, api_base)
def remove_provider(self, name: str):
"""Remove PROVIDER_API_BASE"""
key = f"{name.upper()}_API_BASE"
self.settings.remove(key)
class ModelDefinitionManager:
"""Manages PROVIDER_MODELS"""
def __init__(self, settings: AdvancedSettings):
self.settings = settings
def get_current_provider_models(self, provider: str) -> Optional[Dict]:
"""Get currently configured models for a provider"""
key = f"{provider.upper()}_MODELS"
value = os.getenv(key)
if value:
try:
return json.loads(value)
except (json.JSONDecodeError, ValueError):
return None
return None
def get_all_providers_with_models(self) -> Dict[str, int]:
"""Get all providers with model definitions"""
providers = {}
for key, value in os.environ.items():
if key.endswith("_MODELS"):
provider = key.replace("_MODELS", "").lower()
try:
parsed = json.loads(value)
if isinstance(parsed, dict):
providers[provider] = len(parsed)
elif isinstance(parsed, list):
providers[provider] = len(parsed)
except (json.JSONDecodeError, ValueError):
pass
return providers
def set_models(self, provider: str, models: Dict[str, Dict[str, Any]]):
"""Set PROVIDER_MODELS"""
key = f"{provider.upper()}_MODELS"
value = json.dumps(models)
self.settings.set(key, value)
def remove_models(self, provider: str):
"""Remove PROVIDER_MODELS"""
key = f"{provider.upper()}_MODELS"
self.settings.remove(key)
class ConcurrencyManager:
"""Manages MAX_CONCURRENT_REQUESTS_PER_KEY_PROVIDER"""
def __init__(self, settings: AdvancedSettings):
self.settings = settings
def get_current_limits(self) -> Dict[str, int]:
"""Get currently configured concurrency limits"""
limits = {}
for key, value in os.environ.items():
if key.startswith("MAX_CONCURRENT_REQUESTS_PER_KEY_"):
provider = key.replace("MAX_CONCURRENT_REQUESTS_PER_KEY_", "").lower()
try:
limits[provider] = int(value)
except (json.JSONDecodeError, ValueError):
pass
return limits
def set_limit(self, provider: str, limit: int):
"""Set concurrency limit"""
key = f"MAX_CONCURRENT_REQUESTS_PER_KEY_{provider.upper()}"
self.settings.set(key, str(limit))
def remove_limit(self, provider: str):
"""Remove concurrency limit (reset to default)"""
key = f"MAX_CONCURRENT_REQUESTS_PER_KEY_{provider.upper()}"
self.settings.remove(key)
class RotationModeManager:
"""Manages ROTATION_MODE_PROVIDER settings for sequential/balanced credential rotation"""
VALID_MODES = ["balanced", "sequential"]
def __init__(self, settings: AdvancedSettings):
self.settings = settings
def get_current_modes(self) -> Dict[str, str]:
"""Get currently configured rotation modes"""
modes = {}
for key, value in os.environ.items():
if key.startswith("ROTATION_MODE_"):
provider = key.replace("ROTATION_MODE_", "").lower()
if value.lower() in self.VALID_MODES:
modes[provider] = value.lower()
return modes
def get_default_mode(self, provider: str) -> str:
"""Get the default rotation mode for a provider"""
try:
from rotator_library.providers import PROVIDER_PLUGINS
provider_class = PROVIDER_PLUGINS.get(provider.lower())
if provider_class and hasattr(provider_class, "default_rotation_mode"):
return provider_class.default_rotation_mode
return "balanced"
except ImportError:
# Fallback defaults if import fails
if provider.lower() == "antigravity":
return "sequential"
return "balanced"
def get_effective_mode(self, provider: str) -> str:
"""Get the effective rotation mode (configured or default)"""
configured = self.get_current_modes().get(provider.lower())
if configured:
return configured
return self.get_default_mode(provider)
def set_mode(self, provider: str, mode: str):
"""Set rotation mode for a provider"""
if mode.lower() not in self.VALID_MODES:
raise ValueError(
f"Invalid rotation mode: {mode}. Must be one of {self.VALID_MODES}"
)
key = f"ROTATION_MODE_{provider.upper()}"
self.settings.set(key, mode.lower())
def remove_mode(self, provider: str):
"""Remove rotation mode (reset to provider default)"""
key = f"ROTATION_MODE_{provider.upper()}"
self.settings.remove(key)
class PriorityMultiplierManager:
"""Manages CONCURRENCY_MULTIPLIER_<PROVIDER>_PRIORITY_<N> settings"""
def __init__(self, settings: AdvancedSettings):
self.settings = settings
def get_provider_defaults(self, provider: str) -> Dict[int, int]:
"""Get default priority multipliers from provider class"""
try:
from rotator_library.providers import PROVIDER_PLUGINS
provider_class = PROVIDER_PLUGINS.get(provider.lower())
if provider_class and hasattr(
provider_class, "default_priority_multipliers"
):
return dict(provider_class.default_priority_multipliers)
except ImportError:
pass
return {}
def get_sequential_fallback(self, provider: str) -> int:
"""Get sequential fallback multiplier from provider class"""
try:
from rotator_library.providers import PROVIDER_PLUGINS
provider_class = PROVIDER_PLUGINS.get(provider.lower())
if provider_class and hasattr(
provider_class, "default_sequential_fallback_multiplier"
):
return provider_class.default_sequential_fallback_multiplier
except ImportError:
pass
return 1
def get_current_multipliers(self) -> Dict[str, Dict[int, int]]:
"""Get currently configured priority multipliers from env vars"""
multipliers: Dict[str, Dict[int, int]] = {}
for key, value in os.environ.items():
if key.startswith("CONCURRENCY_MULTIPLIER_") and "_PRIORITY_" in key:
try:
# Parse: CONCURRENCY_MULTIPLIER_<PROVIDER>_PRIORITY_<N>
parts = key.split("_PRIORITY_")
provider = parts[0].replace("CONCURRENCY_MULTIPLIER_", "").lower()
remainder = parts[1]
# Check if mode-specific (has _SEQUENTIAL or _BALANCED suffix)
if "_" in remainder:
continue # Skip mode-specific for now (show in separate view)
priority = int(remainder)
multiplier = int(value)
if provider not in multipliers:
multipliers[provider] = {}
multipliers[provider][priority] = multiplier
except (ValueError, IndexError):
pass
return multipliers
def get_effective_multiplier(self, provider: str, priority: int) -> int:
"""Get effective multiplier (configured, provider default, or 1)"""
# Check env var override
current = self.get_current_multipliers()
if provider.lower() in current:
if priority in current[provider.lower()]:
return current[provider.lower()][priority]
# Check provider defaults
defaults = self.get_provider_defaults(provider)
if priority in defaults:
return defaults[priority]
# Return 1 (no multiplier)
return 1
def set_multiplier(self, provider: str, priority: int, multiplier: int):
"""Set priority multiplier for a provider"""
if multiplier < 1:
raise ValueError("Multiplier must be >= 1")
key = f"CONCURRENCY_MULTIPLIER_{provider.upper()}_PRIORITY_{priority}"
self.settings.set(key, str(multiplier))
def remove_multiplier(self, provider: str, priority: int):
"""Remove multiplier (reset to provider default)"""
key = f"CONCURRENCY_MULTIPLIER_{provider.upper()}_PRIORITY_{priority}"
self.settings.remove(key)
# =============================================================================
# PROVIDER-SPECIFIC SETTINGS DEFINITIONS
# =============================================================================
# Antigravity provider environment variables
ANTIGRAVITY_SETTINGS = {
"ANTIGRAVITY_SIGNATURE_CACHE_TTL": {
"type": "int",
"default": 3600,
"description": "Memory cache TTL for Gemini 3 thought signatures (seconds)",
},
"ANTIGRAVITY_SIGNATURE_DISK_TTL": {
"type": "int",
"default": 86400,
"description": "Disk cache TTL for Gemini 3 thought signatures (seconds)",
},
"ANTIGRAVITY_PRESERVE_THOUGHT_SIGNATURES": {
"type": "bool",
"default": True,
"description": "Preserve thought signatures in client responses",
},
"ANTIGRAVITY_ENABLE_SIGNATURE_CACHE": {
"type": "bool",
"default": True,
"description": "Enable signature caching for multi-turn conversations",
},
"ANTIGRAVITY_ENABLE_DYNAMIC_MODELS": {
"type": "bool",
"default": False,
"description": "Enable dynamic model discovery from API",
},
"ANTIGRAVITY_GEMINI3_TOOL_FIX": {
"type": "bool",
"default": True,
"description": "Enable Gemini 3 tool hallucination prevention",
},
"ANTIGRAVITY_CLAUDE_TOOL_FIX": {
"type": "bool",
"default": True,
"description": "Enable Claude tool hallucination prevention",
},
"ANTIGRAVITY_CLAUDE_THINKING_SANITIZATION": {
"type": "bool",
"default": True,
"description": "Sanitize thinking blocks for Claude multi-turn conversations",
},
"ANTIGRAVITY_GEMINI3_TOOL_PREFIX": {
"type": "str",
"default": "gemini3_",
"description": "Prefix added to tool names for Gemini 3 disambiguation",
},
"ANTIGRAVITY_GEMINI3_DESCRIPTION_PROMPT": {
"type": "str",
"default": "\n\nSTRICT PARAMETERS: {params}.",
"description": "Template for strict parameter hints in tool descriptions",
},
"ANTIGRAVITY_CLAUDE_DESCRIPTION_PROMPT": {
"type": "str",
"default": "\n\nSTRICT PARAMETERS: {params}.",
"description": "Template for Claude strict parameter hints in tool descriptions",
},
"ANTIGRAVITY_OAUTH_PORT": {
"type": "int",
"default": ANTIGRAVITY_DEFAULT_OAUTH_PORT,
"description": "Local port for OAuth callback server during authentication",
},
# Cross-provider fallback tuning (extend for additional providers if needed)
"FALLBACK_COOLDOWN_MULTIPLIER_ANTIGRAVITY": {
"type": "float",
"default": 1.5,
"description": "Multiplier applied to exhaustion cooldown when fallback triggers",
},
"FALLBACK_COOLDOWN_MIN_SECONDS_ANTIGRAVITY": {
"type": "int",
"default": 60,
"description": "Minimum fallback cooldown duration after switching providers",
},
}
# Gemini CLI provider environment variables
GEMINI_CLI_SETTINGS = {
"GEMINI_CLI_SIGNATURE_CACHE_TTL": {
"type": "int",
"default": 3600,
"description": "Memory cache TTL for thought signatures (seconds)",
},
"GEMINI_CLI_SIGNATURE_DISK_TTL": {
"type": "int",
"default": 86400,
"description": "Disk cache TTL for thought signatures (seconds)",
},
"GEMINI_CLI_PRESERVE_THOUGHT_SIGNATURES": {
"type": "bool",
"default": True,
"description": "Preserve thought signatures in client responses",
},
"GEMINI_CLI_ENABLE_SIGNATURE_CACHE": {
"type": "bool",
"default": True,
"description": "Enable signature caching for multi-turn conversations",
},
"GEMINI_CLI_GEMINI3_TOOL_FIX": {
"type": "bool",
"default": True,
"description": "Enable Gemini 3 tool hallucination prevention",
},
"GEMINI_CLI_GEMINI3_TOOL_PREFIX": {
"type": "str",
"default": "gemini3_",
"description": "Prefix added to tool names for Gemini 3 disambiguation",
},
"GEMINI_CLI_GEMINI3_DESCRIPTION_PROMPT": {
"type": "str",
"default": "\n\nSTRICT PARAMETERS: {params}.",
"description": "Template for strict parameter hints in tool descriptions",
},
"GEMINI_CLI_PROJECT_ID": {
"type": "str",
"default": "",
"description": "GCP Project ID for paid tier users (required for paid tiers)",
},
"GEMINI_CLI_OAUTH_PORT": {
"type": "int",
"default": GEMINI_CLI_DEFAULT_OAUTH_PORT,
"description": "Local port for OAuth callback server during authentication",
},
# Cross-provider fallback tuning (extend for additional providers if needed)
"FALLBACK_COOLDOWN_MULTIPLIER_GEMINI_CLI": {
"type": "float",
"default": 1.5,
"description": "Multiplier applied to exhaustion cooldown when fallback triggers",
},
"FALLBACK_COOLDOWN_MIN_SECONDS_GEMINI_CLI": {
"type": "int",
"default": 60,
"description": "Minimum fallback cooldown duration after switching providers",
},
}
# iFlow provider environment variables
IFLOW_SETTINGS = {
"IFLOW_OAUTH_PORT": {
"type": "int",
"default": IFLOW_DEFAULT_OAUTH_PORT,
"description": "Local port for OAuth callback server during authentication",
},
}
# Map provider names to their settings definitions
PROVIDER_SETTINGS_MAP = {
"antigravity": ANTIGRAVITY_SETTINGS,
"gemini_cli": GEMINI_CLI_SETTINGS,
"iflow": IFLOW_SETTINGS,
}
class ProviderSettingsManager:
"""Manages provider-specific configuration settings"""
def __init__(self, settings: AdvancedSettings):
self.settings = settings
def get_available_providers(self) -> List[str]:
"""Get list of providers with specific settings available"""
return list(PROVIDER_SETTINGS_MAP.keys())
def get_provider_settings_definitions(
self, provider: str
) -> Dict[str, Dict[str, Any]]:
"""Get settings definitions for a provider"""
return PROVIDER_SETTINGS_MAP.get(provider, {})
def get_current_value(self, key: str, definition: Dict[str, Any]) -> Any:
"""Get current value of a setting from environment"""
env_value = os.getenv(key)
if env_value is None:
return definition.get("default")
setting_type = definition.get("type", "str")
try:
if setting_type == "bool":
return env_value.lower() in ("true", "1", "yes")
elif setting_type == "int":
return int(env_value)
else:
return env_value
except (ValueError, AttributeError):
return definition.get("default")
def get_all_current_values(self, provider: str) -> Dict[str, Any]:
"""Get all current values for a provider"""
definitions = self.get_provider_settings_definitions(provider)
values = {}
for key, definition in definitions.items():
values[key] = self.get_current_value(key, definition)
return values
def set_value(self, key: str, value: Any, definition: Dict[str, Any]):
"""Set a setting value, converting to string for .env storage"""
setting_type = definition.get("type", "str")
if setting_type == "bool":
str_value = "true" if value else "false"
else:
str_value = str(value)
self.settings.set(key, str_value)
def reset_to_default(self, key: str):
"""Remove a setting to reset it to default"""
self.settings.remove(key)
def get_modified_settings(self, provider: str) -> Dict[str, Any]:
"""Get settings that differ from defaults"""
definitions = self.get_provider_settings_definitions(provider)
modified = {}
for key, definition in definitions.items():
current = self.get_current_value(key, definition)
default = definition.get("default")
if current != default:
modified[key] = current
return modified
class SettingsTool:
"""Main settings tool TUI"""
def __init__(self):
self.console = Console()
self.settings = AdvancedSettings()
self.provider_mgr = CustomProviderManager(self.settings)
self.model_mgr = ModelDefinitionManager(self.settings)
self.concurrency_mgr = ConcurrencyManager(self.settings)
self.rotation_mgr = RotationModeManager(self.settings)
self.priority_multiplier_mgr = PriorityMultiplierManager(self.settings)
self.provider_settings_mgr = ProviderSettingsManager(self.settings)
self.running = True
def _format_item(
self,
name: str,
value: str,
change_type: Optional[str],
old_value: Optional[str] = None,
width: int = 15,
) -> str:
"""Format a list item with change indicator.
change_type: None, 'add', 'edit', 'remove'
Returns formatted string like:
" + myapi https://api.example.com" (green)
" ~ openai 1 → 5 requests/key" (yellow)
" - oldapi https://old.api.com" (red)
" • groq 3 requests/key" (normal)
"""
if change_type == "add":
return f" [green]+ {name:{width}} {value}[/green]"
elif change_type == "edit":
if old_value is not None:
return f" [yellow]~ {name:{width}} {old_value} → {value}[/yellow]"
else:
return f" [yellow]~ {name:{width}} {value}[/yellow]"
elif change_type == "remove":
return f" [red]- {name:{width}} {value}[/red]"
else:
return f" • {name:{width}} {value}"
def _get_pending_status_text(self) -> str:
"""Get formatted pending changes status text for main menu."""
if not self.settings.has_pending():
return "[dim]ℹ️ No pending changes[/dim]"
counts = self.settings.get_pending_counts()
parts = []
if counts["add"]:
parts.append(
f"[green]{counts['add']} addition{'s' if counts['add'] > 1 else ''}[/green]"
)
if counts["edit"]:
parts.append(
f"[yellow]{counts['edit']} modification{'s' if counts['edit'] > 1 else ''}[/yellow]"
)
if counts["remove"]:
parts.append(
f"[red]{counts['remove']} removal{'s' if counts['remove'] > 1 else ''}[/red]"
)
return f"[bold]ℹ️ Pending changes: {', '.join(parts)}[/bold]"
self.running = True
def get_available_providers(self) -> List[str]:
"""Get list of providers that have credentials configured"""
env_file = get_data_file(".env")
providers = set()
# Scan for providers with API keys from local .env
if env_file.exists():
try:
with open(env_file, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
# Skip comments and empty lines
if not line or line.startswith("#"):
continue
if (
"_API_KEY" in line
and "PROXY_API_KEY" not in line
and "=" in line
):
provider = line.split("_API_KEY")[0].strip().lower()
providers.add(provider)
except (IOError, OSError):
pass
# Also check for OAuth providers from files
from rotator_library.utils.paths import get_oauth_dir
oauth_dir = get_oauth_dir()
if oauth_dir.exists():
for file in oauth_dir.glob("*_oauth_*.json"):
provider = file.name.split("_oauth_")[0]
providers.add(provider)
return sorted(list(providers))
def run(self):
"""Main loop"""
while self.running:
self.show_main_menu()
def show_main_menu(self):
"""Display settings categories"""
clear_screen()
self.console.print(
Panel.fit(
"[bold cyan]🔧 Advanced Settings Configuration[/bold cyan]",
border_style="cyan",
)
)
self.console.print()
self.console.print("[bold]⚙️ Configuration Categories[/bold]")
self.console.print()
self.console.print(" 1. 🌐 Custom Provider API Bases")
self.console.print(" 2. 📦 Provider Model Definitions")
self.console.print(" 3. ⚡ Concurrency Limits")
self.console.print(" 4. 🔄 Rotation Modes")
self.console.print(" 5. 🔬 Provider-Specific Settings")
self.console.print(" 6. 🎯 Model Filters (Ignore/Whitelist)")
self.console.print(" 7. 💾 Save & Exit")
self.console.print(" 8. 🚫 Exit Without Saving")
self.console.print()
self.console.print("━" * 70)
self.console.print(self._get_pending_status_text())
self.console.print()
choice = Prompt.ask(
"Select option",
choices=["1", "2", "3", "4", "5", "6", "7", "8"],
show_choices=False,
)
if choice == "1":
self.manage_custom_providers()
elif choice == "2":
self.manage_model_definitions()
elif choice == "3":
self.manage_concurrency_limits()
elif choice == "4":
self.manage_rotation_modes()
elif choice == "5":
self.manage_provider_settings()
elif choice == "6":
self.launch_model_filter_gui()
elif choice == "7":
self.save_and_exit()
elif choice == "8":
self.exit_without_saving()
def manage_custom_providers(self):
"""Manage custom provider API bases"""
while True:
clear_screen()
# Get current providers from env
providers = self.provider_mgr.get_current_providers()
self.console.print(
Panel.fit(
"[bold cyan]🌐 Custom Provider API Bases[/bold cyan]",
border_style="cyan",
)
)
self.console.print()
self.console.print("[bold]📋 Configured Custom Providers[/bold]")
self.console.print("━" * 70)
# Build combined view with pending changes
all_providers: Dict[str, Dict[str, Any]] = {}
# Add current providers (from env)
for name, base in providers.items():
key = f"{name.upper()}_API_BASE"
change_type = self.settings.get_change_type(key)
if change_type == "remove":
all_providers[name] = {"value": base, "type": "remove", "old": None}
elif change_type == "edit":
new_val = self.settings.pending_changes[key]
all_providers[name] = {
"value": new_val,
"type": "edit",
"old": base,
}
else:
all_providers[name] = {"value": base, "type": None, "old": None}
# Add pending new providers (additions)
for key in self.settings.get_pending_keys_by_pattern(suffix="_API_BASE"):
if self.settings.get_change_type(key) == "add":
name = key.replace("_API_BASE", "").lower()
if name not in all_providers:
all_providers[name] = {
"value": self.settings.pending_changes[key],
"type": "add",
"old": None,
}
if all_providers:
# Sort alphabetically
for name in sorted(all_providers.keys()):
info = all_providers[name]
self.console.print(
self._format_item(
name,
info["value"],
info["type"],
info["old"],
)
)
else:
self.console.print(" [dim]No custom providers configured[/dim]")
self.console.print()
self.console.print("━" * 70)
self.console.print()
self.console.print("[bold]⚙️ Actions[/bold]")
self.console.print()
self.console.print(" 1. ➕ Add New Custom Provider")
self.console.print(" 2. ✏️ Edit Existing Provider")
self.console.print(" 3. 🗑️ Remove Provider")
self.console.print(" 4. ↩️ Back to Settings Menu")
self.console.print()
self.console.print("━" * 70)
self.console.print()
choice = Prompt.ask(
"Select option", choices=["1", "2", "3", "4"], show_choices=False
)
if choice == "1":
name = Prompt.ask("Provider name (e.g., 'opencode')").strip().lower()
if name:
api_base = Prompt.ask("API Base URL").strip()
if api_base:
self.provider_mgr.add_provider(name, api_base)
self.console.print(
f"\n[green]✅ Custom provider '{name}' staged![/green]"
)
self.console.print(
f" To use: set {name.upper()}_API_KEY in credentials"
)
input("\nPress Enter to continue...")
elif choice == "2":
# Get editable providers (existing + pending additions, excluding pending removals)
editable = {
k: v for k, v in all_providers.items() if v["type"] != "remove"
}
if not editable:
self.console.print("\n[yellow]No providers to edit[/yellow]")
input("\nPress Enter to continue...")
continue
# Show numbered list
self.console.print("\n[bold]Select provider to edit:[/bold]")
providers_list = sorted(editable.keys())
for idx, prov in enumerate(providers_list, 1):
self.console.print(f" {idx}. {prov}")
choice_idx = IntPrompt.ask(
"Select option",
choices=[str(i) for i in range(1, len(providers_list) + 1)],
)
name = providers_list[choice_idx - 1]
info = editable[name]
# Get effective current value (could be pending or from env)
current_base = info["value"]
self.console.print(f"\nCurrent API Base: {current_base}")
new_base = Prompt.ask(
"New API Base [press Enter to keep current]", default=current_base
).strip()
if new_base and new_base != current_base:
self.provider_mgr.edit_provider(name, new_base)
self.console.print(
f"\n[green]✅ Custom provider '{name}' updated![/green]"
)
else:
self.console.print("\n[yellow]No changes made[/yellow]")
input("\nPress Enter to continue...")
elif choice == "3":
# Get removable providers (existing ones not already pending removal)
removable = {
k: v
for k, v in all_providers.items()
if v["type"] != "remove" and v["type"] != "add"
}
# For pending additions, we can "undo" by removing from pending
pending_adds = {
k: v for k, v in all_providers.items() if v["type"] == "add"
}
if not removable and not pending_adds:
self.console.print("\n[yellow]No providers to remove[/yellow]")
input("\nPress Enter to continue...")
continue
# Show numbered list
self.console.print("\n[bold]Select provider to remove:[/bold]")
# Show existing providers first, then pending additions
providers_list = sorted(removable.keys()) + sorted(pending_adds.keys())
for idx, prov in enumerate(providers_list, 1):
if prov in pending_adds:
self.console.print(
f" {idx}. {prov} [green](pending add)[/green]"
)
else:
self.console.print(f" {idx}. {prov}")
choice_idx = IntPrompt.ask(
"Select option",
choices=[str(i) for i in range(1, len(providers_list) + 1)],
)
name = providers_list[choice_idx - 1]
if Confirm.ask(f"Remove '{name}'?"):
if name in pending_adds:
# Undo pending addition - remove from pending_changes
key = f"{name.upper()}_API_BASE"
del self.settings.pending_changes[key]
self.console.print(
f"\n[green]✅ Pending addition of '{name}' cancelled![/green]"
)
else:
self.provider_mgr.remove_provider(name)
self.console.print(
f"\n[green]✅ Provider '{name}' marked for removal![/green]"
)
input("\nPress Enter to continue...")
elif choice == "4":
break
def manage_model_definitions(self):
"""Manage provider model definitions"""
while True:
clear_screen()