Skip to content

Commit bcaeaf8

Browse files
feat: Add config_manager.py - Configuration management and settings handling
1 parent 81ef7c6 commit bcaeaf8

1 file changed

Lines changed: 195 additions & 0 deletions

File tree

config_manager.py

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Configuration Manager for Linux Desktop AI Agent
4+
Handles configuration storage and management
5+
"""
6+
7+
import json
8+
import logging
9+
from pathlib import Path
10+
from typing import Dict, Any, Optional
11+
from dataclasses import dataclass, asdict
12+
13+
logger = logging.getLogger(__name__)
14+
15+
16+
@dataclass
17+
class AgentConfig:
18+
"""Agent configuration"""
19+
# Llama settings
20+
llama_model: str = "llama3.1:8b"
21+
llama_host: str = "localhost"
22+
llama_port: int = 11434
23+
24+
# Module settings
25+
enabled_modules: list = None
26+
27+
# Notification settings
28+
notifications_enabled: bool = True
29+
notification_type: str = "desktop" # desktop, email, both
30+
email_address: Optional[str] = None
31+
32+
# Automation settings
33+
auto_cleanup: bool = False
34+
auto_cleanup_interval: int = 86400 # 24 hours
35+
auto_update: bool = False
36+
auto_update_interval: int = 604800 # 7 days
37+
38+
# Alert thresholds
39+
cpu_threshold: float = 80.0
40+
memory_threshold: float = 80.0
41+
disk_threshold: float = 85.0
42+
43+
# Logging
44+
log_level: str = "INFO"
45+
log_file: str = "/tmp/linux_desktop_agent.log"
46+
47+
def __post_init__(self):
48+
if self.enabled_modules is None:
49+
self.enabled_modules = [
50+
"system_cleanup",
51+
"system_monitor",
52+
"network",
53+
"file_manager",
54+
"package_manager",
55+
"security",
56+
"developer_tools"
57+
]
58+
59+
def to_dict(self) -> Dict[str, Any]:
60+
"""Convert to dictionary"""
61+
return asdict(self)
62+
63+
@classmethod
64+
def from_dict(cls, data: Dict[str, Any]) -> "AgentConfig":
65+
"""Create from dictionary"""
66+
return cls(**data)
67+
68+
69+
class ConfigManager:
70+
"""Manages agent configuration"""
71+
72+
def __init__(self, config_dir: Optional[Path] = None):
73+
"""
74+
Initialize configuration manager
75+
76+
Args:
77+
config_dir: Configuration directory (default: ~/.config/linux-desktop-agent)
78+
"""
79+
if config_dir is None:
80+
config_dir = Path.home() / ".config" / "linux-desktop-agent"
81+
82+
self.config_dir = Path(config_dir)
83+
self.config_dir.mkdir(parents=True, exist_ok=True)
84+
85+
self.config_file = self.config_dir / "config.json"
86+
self.backup_dir = self.config_dir / "backups"
87+
self.backup_dir.mkdir(exist_ok=True)
88+
89+
self.config = self._load_config()
90+
91+
def _load_config(self) -> AgentConfig:
92+
"""Load configuration from file"""
93+
if self.config_file.exists():
94+
try:
95+
with open(self.config_file, 'r') as f:
96+
data = json.load(f)
97+
logger.info(f"Loaded configuration from {self.config_file}")
98+
return AgentConfig.from_dict(data)
99+
except Exception as e:
100+
logger.error(f"Error loading config: {e}")
101+
return AgentConfig()
102+
else:
103+
logger.info("Creating default configuration")
104+
return AgentConfig()
105+
106+
def save_config(self, config: Optional[AgentConfig] = None):
107+
"""Save configuration to file"""
108+
if config is None:
109+
config = self.config
110+
111+
try:
112+
# Create backup
113+
if self.config_file.exists():
114+
import shutil
115+
from datetime import datetime
116+
backup_file = self.backup_dir / f"config_{datetime.now().isoformat()}.json"
117+
shutil.copy(self.config_file, backup_file)
118+
119+
# Save new config
120+
with open(self.config_file, 'w') as f:
121+
json.dump(config.to_dict(), f, indent=2)
122+
123+
logger.info(f"Saved configuration to {self.config_file}")
124+
self.config = config
125+
except Exception as e:
126+
logger.error(f"Error saving config: {e}")
127+
128+
def get(self, key: str, default: Any = None) -> Any:
129+
"""Get configuration value"""
130+
return getattr(self.config, key, default)
131+
132+
def set(self, key: str, value: Any):
133+
"""Set configuration value"""
134+
if hasattr(self.config, key):
135+
setattr(self.config, key, value)
136+
self.save_config()
137+
else:
138+
logger.warning(f"Unknown configuration key: {key}")
139+
140+
def update(self, updates: Dict[str, Any]):
141+
"""Update multiple configuration values"""
142+
for key, value in updates.items():
143+
self.set(key, value)
144+
145+
def reset_to_defaults(self):
146+
"""Reset configuration to defaults"""
147+
self.config = AgentConfig()
148+
self.save_config()
149+
logger.info("Configuration reset to defaults")
150+
151+
def export_config(self, filepath: Path):
152+
"""Export configuration to file"""
153+
try:
154+
with open(filepath, 'w') as f:
155+
json.dump(self.config.to_dict(), f, indent=2)
156+
logger.info(f"Exported configuration to {filepath}")
157+
except Exception as e:
158+
logger.error(f"Error exporting config: {e}")
159+
160+
def import_config(self, filepath: Path):
161+
"""Import configuration from file"""
162+
try:
163+
with open(filepath, 'r') as f:
164+
data = json.load(f)
165+
self.config = AgentConfig.from_dict(data)
166+
self.save_config()
167+
logger.info(f"Imported configuration from {filepath}")
168+
except Exception as e:
169+
logger.error(f"Error importing config: {e}")
170+
171+
def get_all(self) -> Dict[str, Any]:
172+
"""Get all configuration"""
173+
return self.config.to_dict()
174+
175+
176+
# Global configuration manager instance
177+
_config_manager: Optional[ConfigManager] = None
178+
179+
180+
def get_config_manager() -> ConfigManager:
181+
"""Get global configuration manager"""
182+
global _config_manager
183+
if _config_manager is None:
184+
_config_manager = ConfigManager()
185+
return _config_manager
186+
187+
188+
def get_config(key: str, default: Any = None) -> Any:
189+
"""Get configuration value"""
190+
return get_config_manager().get(key, default)
191+
192+
193+
def set_config(key: str, value: Any):
194+
"""Set configuration value"""
195+
get_config_manager().set(key, value)

0 commit comments

Comments
 (0)