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
//! Profile configuration for per-environment settings.
use serde::{Deserialize, Serialize};
use stakpak_shared::models::integrations::anthropic::AnthropicConfig;
use stakpak_shared::models::integrations::gemini::GeminiConfig;
use stakpak_shared::models::integrations::openai::OpenAIConfig;
use stakpak_shared::models::llm::ProviderConfig;
use std::collections::HashMap;
use super::rulebook::RulebookConfig;
use super::types::{OldAppConfig, ProviderType};
use super::warden::WardenConfig;
/// Configuration for a specific profile (environment).
///
/// # New Config Format (v2)
/// ```toml
/// [profiles.myprofile.providers.openai]
/// type = "openai"
/// api_key = "sk-..."
///
/// [profiles.myprofile.providers.anthropic]
/// type = "anthropic"
/// api_key = "sk-ant-..."
///
/// [profiles.myprofile.providers.litellm]
/// type = "custom"
/// api_endpoint = "http://localhost:4000"
/// api_key = "sk-litellm"
/// ```
///
/// # Legacy Config Format (v1) - still supported for reading
/// ```toml
/// [profiles.myprofile]
/// openai.api_key = "sk-..."
/// anthropic.api_key = "sk-ant-..."
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct ProfileConfig {
/// API endpoint URL
pub api_endpoint: Option<String>,
/// API key for authentication
pub api_key: Option<String>,
/// Provider type (remote or local)
pub provider: Option<ProviderType>,
/// Allowed tools (empty = all tools allowed)
pub allowed_tools: Option<Vec<String>>,
/// Tools that auto-approve without asking
pub auto_approve: Option<Vec<String>>,
/// Rulebook filtering configuration
pub rulebooks: Option<RulebookConfig>,
/// Warden (runtime security) configuration
pub warden: Option<WardenConfig>,
/// Unified providers configuration (new format)
/// Key is provider name (e.g., "openai", "anthropic", "litellm")
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub providers: HashMap<String, ProviderConfig>,
// =========================================================================
// Legacy fields - kept for backward compatibility during config migration
// These are read but not written (skip_serializing)
// =========================================================================
/// OpenAI configuration (legacy - use providers instead)
#[serde(skip_serializing_if = "Option::is_none")]
pub openai: Option<OpenAIConfig>,
/// Gemini configuration (legacy - use providers instead)
#[serde(skip_serializing_if = "Option::is_none")]
pub gemini: Option<GeminiConfig>,
/// Anthropic configuration (legacy - use providers instead)
#[serde(skip_serializing_if = "Option::is_none")]
pub anthropic: Option<AnthropicConfig>,
/// User's preferred model (replaces smart_model/eco_model/recovery_model)
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
// =========================================================================
// Legacy model fields - kept for backward compatibility during migration
// These are read but deprecated (will migrate to 'model' field)
// =========================================================================
/// Eco (fast/cheap) model name (deprecated - use 'model')
#[serde(skip_serializing_if = "Option::is_none")]
pub eco_model: Option<String>,
/// Smart (capable) model name (deprecated - use 'model')
#[serde(skip_serializing_if = "Option::is_none")]
pub smart_model: Option<String>,
/// Recovery model name (deprecated - use 'model')
#[serde(skip_serializing_if = "Option::is_none")]
pub recovery_model: Option<String>,
}
impl ProfileConfig {
/// Create a profile with only the API endpoint set.
pub(crate) fn with_api_endpoint(api_endpoint: &str) -> Self {
ProfileConfig {
api_endpoint: Some(api_endpoint.into()),
..ProfileConfig::default()
}
}
/// Create a readonly profile based on the default profile.
/// This creates a replica of the default profile with warden enabled for sandboxed execution.
pub(crate) fn readonly_profile(default_profile: Option<&ProfileConfig>) -> Self {
match default_profile {
Some(default) => ProfileConfig {
// Copy all provider-related fields from default
api_endpoint: default.api_endpoint.clone(),
api_key: default.api_key.clone(),
provider: default.provider,
providers: default.providers.clone(),
// Copy model fields
model: default.model.clone(),
smart_model: default.smart_model.clone(),
eco_model: default.eco_model.clone(),
recovery_model: default.recovery_model.clone(),
// Enable warden for readonly sandboxed execution
warden: Some(WardenConfig::readonly_profile()),
// Don't copy allowed_tools/auto_approve - readonly has its own restrictions
..ProfileConfig::default()
},
None => ProfileConfig {
warden: Some(WardenConfig::readonly_profile()),
..ProfileConfig::default()
},
}
}
/// Create a profile migrated from the old config format.
pub(crate) fn migrated_from_old_config(old_config: OldAppConfig) -> Self {
ProfileConfig {
api_endpoint: Some(old_config.api_endpoint),
api_key: old_config.api_key,
..ProfileConfig::default()
}
}
/// Clean an API endpoint by removing `/chat/completions` suffix if present.
/// This suffix is appended at runtime by the provider, not stored in config.
fn clean_api_endpoint(endpoint: Option<String>) -> Option<String> {
endpoint.map(|ep| {
ep.trim_end_matches("/chat/completions")
.trim_end_matches("/chat/completions/")
.to_string()
})
}
/// Migrate legacy provider fields to the new unified `providers` HashMap.
///
/// This converts:
/// - `openai`, `anthropic`, `gemini` fields -> `providers["openai"]`, etc.
/// - Strips `/chat/completions` from endpoints (added at runtime)
///
/// Returns true if any migration was performed.
#[allow(clippy::collapsible_if)]
pub fn migrate_legacy_providers(&mut self) -> bool {
let mut migrated = false;
// Migrate openai
if let Some(openai) = self.openai.take() {
if let std::collections::hash_map::Entry::Vacant(e) =
self.providers.entry("openai".to_string())
{
e.insert(ProviderConfig::OpenAI {
api_key: openai.api_key,
api_endpoint: Self::clean_api_endpoint(openai.api_endpoint),
});
migrated = true;
}
}
// Migrate anthropic
if let Some(anthropic) = self.anthropic.take() {
if !self.providers.contains_key("anthropic") {
self.providers.insert(
"anthropic".to_string(),
ProviderConfig::Anthropic {
api_key: anthropic.api_key,
api_endpoint: Self::clean_api_endpoint(anthropic.api_endpoint),
access_token: anthropic.access_token,
},
);
migrated = true;
}
}
// Migrate gemini
if let Some(gemini) = self.gemini.take() {
if !self.providers.contains_key("gemini") {
self.providers.insert(
"gemini".to_string(),
ProviderConfig::Gemini {
api_key: gemini.api_key,
api_endpoint: Self::clean_api_endpoint(gemini.api_endpoint),
},
);
migrated = true;
}
}
// Also clean existing providers in HashMap
migrated = self.clean_provider_endpoints() || migrated;
migrated
}
/// Clean `/chat/completions` suffix from all provider endpoints.
/// Returns true if any endpoint was modified.
fn clean_provider_endpoints(&mut self) -> bool {
let mut cleaned = false;
for (_name, provider) in self.providers.iter_mut() {
match provider {
ProviderConfig::OpenAI { api_endpoint, .. } => {
if let Some(ep) = api_endpoint {
let clean = Self::clean_api_endpoint(Some(ep.clone()));
if clean.as_ref() != Some(ep) {
*api_endpoint = clean;
cleaned = true;
}
}
}
ProviderConfig::Anthropic { api_endpoint, .. } => {
if let Some(ep) = api_endpoint {
let clean = Self::clean_api_endpoint(Some(ep.clone()));
if clean.as_ref() != Some(ep) {
*api_endpoint = clean;
cleaned = true;
}
}
}
ProviderConfig::Gemini { api_endpoint, .. } => {
if let Some(ep) = api_endpoint {
let clean = Self::clean_api_endpoint(Some(ep.clone()));
if clean.as_ref() != Some(ep) {
*api_endpoint = clean;
cleaned = true;
}
}
}
ProviderConfig::Custom { api_endpoint, .. } => {
let clean = Self::clean_api_endpoint(Some(api_endpoint.clone()));
if let Some(clean_ep) = clean
&& &clean_ep != api_endpoint
{
*api_endpoint = clean_ep;
cleaned = true;
}
}
ProviderConfig::Stakpak { api_endpoint, .. } => {
if let Some(ep) = api_endpoint {
let clean = Self::clean_api_endpoint(Some(ep.clone()));
if clean.as_ref() != Some(ep) {
*api_endpoint = clean;
cleaned = true;
}
}
}
ProviderConfig::Bedrock { .. } => {
// Bedrock has no API endpoint to clean
}
}
}
cleaned
}
/// Check if this profile has legacy provider fields or endpoints that need migration/cleaning.
pub fn needs_provider_migration(&self) -> bool {
// Check for legacy provider fields
if self.openai.is_some() || self.anthropic.is_some() || self.gemini.is_some() {
return true;
}
// Check for endpoints with /chat/completions that need cleaning
for provider in self.providers.values() {
if let Some(ep) = provider.api_endpoint()
&& ep.contains("/chat/completions")
{
return true;
}
}
false
}
/// Merge this profile with another, using self's values if present.
pub(crate) fn merge(&self, other: Option<&ProfileConfig>) -> ProfileConfig {
// Merge providers: start with other's providers, then overlay self's
let mut merged_providers = other.map(|o| o.providers.clone()).unwrap_or_default();
for (name, config) in &self.providers {
merged_providers.insert(name.clone(), config.clone());
}
ProfileConfig {
api_endpoint: self
.api_endpoint
.clone()
.or_else(|| other.and_then(|config| config.api_endpoint.clone())),
api_key: self
.api_key
.clone()
.or_else(|| other.and_then(|config| config.api_key.clone())),
allowed_tools: self
.allowed_tools
.clone()
.or_else(|| other.and_then(|config| config.allowed_tools.clone())),
auto_approve: self
.auto_approve
.clone()
.or_else(|| other.and_then(|config| config.auto_approve.clone())),
rulebooks: self
.rulebooks
.clone()
.or_else(|| other.and_then(|config| config.rulebooks.clone())),
warden: self
.warden
.clone()
.or_else(|| other.and_then(|config| config.warden.clone())),
provider: self
.provider
.or_else(|| other.and_then(|config| config.provider)),
providers: merged_providers,
// Legacy fields - merge for backward compatibility during transition
openai: self
.openai
.clone()
.or_else(|| other.and_then(|config| config.openai.clone())),
anthropic: self
.anthropic
.clone()
.or_else(|| other.and_then(|config| config.anthropic.clone())),
gemini: self
.gemini
.clone()
.or_else(|| other.and_then(|config| config.gemini.clone())),
// New unified model field
model: self
.model
.clone()
.or_else(|| other.and_then(|config| config.model.clone())),
// Legacy fields - merge for backward compatibility during transition
eco_model: self
.eco_model
.clone()
.or_else(|| other.and_then(|config| config.eco_model.clone())),
smart_model: self
.smart_model
.clone()
.or_else(|| other.and_then(|config| config.smart_model.clone())),
recovery_model: self
.recovery_model
.clone()
.or_else(|| other.and_then(|config| config.recovery_model.clone())),
}
}
}
impl From<OldAppConfig> for ProfileConfig {
fn from(old_config: OldAppConfig) -> Self {
ProfileConfig {
api_endpoint: Some(old_config.api_endpoint),
api_key: old_config.api_key,
..ProfileConfig::default()
}
}
}