rho-coding-agent 2.26.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
use std::{
    path::{Path, PathBuf},
    sync::{Arc, Mutex, OnceLock},
};

use rho_providers::credentials::{
    open_credential_store, probe_credential_store, CredentialError, CredentialResult,
    CredentialStore, CredentialStoreBackend, CredentialStoreProbe, OsCredentialStore,
};

use crate::config::Config;

mod startup_notice;
pub(crate) use startup_notice::StartupKeyringNotice;

const LEGACY_POLICY_FILE: &str = "credential-store";
const ENV_BACKEND: &str = "RHO_CREDENTIAL_STORE";

/// Application credential adapter selected by the configured backend.
///
/// Backend resolution order:
/// 1. `RHO_CREDENTIAL_STORE` for the current process
/// 2. `behavior.credential_store` in config.toml
/// 3. OS store (default when unset)
///
/// File storage must be chosen explicitly through `/login`, the CLI, config, or env.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct AppCredentialStore;

#[derive(Clone, Debug)]
pub(crate) struct StoreChoiceRequest {
    pub os: CredentialStoreProbe,
    pub file: CredentialStoreProbe,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct StoreChoiceOption {
    pub backend: CredentialStoreBackend,
    pub available: bool,
}

impl StoreChoiceRequest {
    pub fn probe() -> Self {
        Self {
            os: probe(CredentialStoreBackend::Os),
            file: probe(CredentialStoreBackend::File),
        }
    }

    pub fn options(&self) -> [StoreChoiceOption; 2] {
        [
            StoreChoiceOption {
                backend: CredentialStoreBackend::Os,
                available: self.os.available,
            },
            StoreChoiceOption {
                backend: CredentialStoreBackend::File,
                available: self.file.available,
            },
        ]
    }

    pub fn available_backends(&self) -> Vec<CredentialStoreBackend> {
        self.options()
            .into_iter()
            .filter(|option| option.available)
            .map(|option| option.backend)
            .collect()
    }

    pub fn default_backend(&self) -> Option<CredentialStoreBackend> {
        self.available_backends().into_iter().next()
    }

    pub fn detail_for(&self, backend: CredentialStoreBackend) -> &str {
        match backend {
            CredentialStoreBackend::Os => self.os.detail.as_str(),
            CredentialStoreBackend::File => self.file.detail.as_str(),
        }
    }
}

impl AppCredentialStore {
    /// Makes the next reads see logins saved by another process, such as a
    /// terminal login an editor ran. The OS store caches reads, including
    /// misses, for the life of the process; the file store always rereads.
    pub(crate) fn reread_external_logins() {
        OsCredentialStore::forget_cached_secrets();
    }
}

impl CredentialStore for AppCredentialStore {
    fn get_secret(&self, account: &str) -> CredentialResult<Option<String>> {
        selected_store()?.get_secret(account)
    }

    fn set_secret(&self, account: &str, secret: &str) -> CredentialResult<()> {
        selected_store()?.set_secret(account, secret)
    }

    fn delete_secret(&self, account: &str) -> CredentialResult<bool> {
        selected_store()?.delete_secret(account)
    }
}

pub(crate) fn probe(backend: CredentialStoreBackend) -> CredentialStoreProbe {
    probe_credential_store(backend)
}

/// Backend saved in config, ignoring env overrides.
///
/// `None` means the setting is unset and the OS store is used by default.
/// Reads are non-destructive: legacy policy files are not removed here.
pub(crate) fn saved_policy_backend(
    config_path: Option<&Path>,
) -> anyhow::Result<Option<CredentialStoreBackend>> {
    let path = match config_path {
        Some(path) => path.to_path_buf(),
        None => Config::default_path()?,
    };
    if path.exists() {
        let config = Config::load_settings_only(path)?;
        if config.credential_store.is_some() {
            return Ok(config.credential_store);
        }
    }
    Ok(read_legacy_policy_file()?)
}

/// Persist the backend in config.toml and open it for this process.
pub(crate) fn set_backend(
    backend: CredentialStoreBackend,
    config_path: Option<PathBuf>,
) -> anyhow::Result<PathBuf> {
    let availability = probe(backend);
    if !availability.available {
        anyhow::bail!(availability.detail);
    }

    let path = match config_path {
        Some(path) => path,
        None => Config::default_path()?,
    };
    let mut config = if path.exists() {
        Config::load_settings_only(path.clone())?
    } else {
        Config::default()
    };
    config.credential_store = Some(backend);
    config.write_settings(path.clone())?;
    remember_config_path(&path);
    activate(backend)?;
    remove_legacy_policy_file()?;
    Ok(path)
}

/// Resolve and open the backend once for this process from config + env.
///
/// Also migrates legacy policy/web-search secrets when needed. Call at startup,
/// not on every settings read.
pub(crate) fn initialize_from_config(
    config: &mut Config,
    config_path: &Path,
) -> anyhow::Result<()> {
    remember_config_path(config_path);
    let mut dirty = absorb_legacy_policy(config)?;
    let backend = resolve_backend(config.credential_store)?;
    activate(backend)?;
    if matches!(
        config.migrate_legacy_web_search_credentials(&AppCredentialStore),
        Ok(true)
    ) {
        dirty = true;
    }
    if config.promote_stored_custom_auth(&AppCredentialStore) {
        dirty = true;
    }
    if dirty {
        config.write_settings(config_path.to_path_buf())?;
    }
    Ok(())
}

/// Whether config still needs an explicit credential-store choice before login.
pub(crate) fn needs_explicit_choice(config: &Config) -> bool {
    env_backend_override().is_none() && config.credential_store.is_none()
}

/// Build a choice request when login still needs an explicit backend selection.
pub(crate) fn choice_request(config: &Config) -> Option<StoreChoiceRequest> {
    needs_explicit_choice(config).then(StoreChoiceRequest::probe)
}

pub(crate) fn configured_backend() -> CredentialResult<CredentialStoreBackend> {
    resolve_backend(read_config_backend().ok().flatten())
}

pub(crate) fn build_provider_from_config(
    config: &Config,
    credential_store: Arc<dyn CredentialStore>,
) -> Result<Arc<dyn rho_sdk::provider::ModelProvider>, rho_providers::model::ModelError> {
    let _scope = config
        .providers
        .thread_scope()
        .map_err(|error| rho_providers::model::ModelError::InvalidResponse(error.to_string()))?;
    let options = crate::app::sdk_config::provider_options_from_config(config)?;
    let credentials = rho_providers::auth::provider_credentials::ApplicationCredentialSource::new(
        credential_store,
    );
    rho_providers::providers::build_sdk_provider_with_source(options, &credentials)
}

/// Live rebuilds await catalog hydrate so npm-following providers pick the
/// advertised adapter before the first request, not after a background fetch.
///
/// Options are resolved synchronously so the thread-local custom-provider
/// overlay is never held across the catalog await.
pub(crate) async fn build_provider_from_config_ensuring_catalog(
    config: &Config,
    credential_store: Arc<dyn CredentialStore>,
) -> Result<Arc<dyn rho_sdk::provider::ModelProvider>, rho_providers::model::ModelError> {
    let options = crate::app::sdk_config::provider_options_from_config(config)?;
    options.ensure_catalog_for_construction().await;
    build_provider_from_config(config, credential_store)
}

pub(crate) async fn build_provider(
    provider: &str,
    model: &str,
    reasoning: rho_providers::reasoning::ReasoningLevel,
    auth: &str,
) -> Result<Arc<dyn rho_sdk::provider::ModelProvider>, rho_providers::model::ModelError> {
    build_provider_on(&Config::default(), provider, model, reasoning, auth).await
}

/// [`build_provider`] on `base`'s `[providers]`, so a configured endpoint or
/// custom provider reaches the model. Nothing else carries over from `base`.
pub(crate) async fn build_provider_on(
    base: &Config,
    provider: &str,
    model: &str,
    reasoning: rho_providers::reasoning::ReasoningLevel,
    auth: &str,
) -> Result<Arc<dyn rho_sdk::provider::ModelProvider>, rho_providers::model::ModelError> {
    let config = Config {
        provider: provider.into(),
        model: model.into(),
        reasoning,
        auth: auth.into(),
        providers: base.providers.clone(),
        ..Config::default()
    };
    build_provider_from_config_ensuring_catalog(&config, Arc::new(AppCredentialStore)).await
}

fn env_backend_override() -> Option<String> {
    std::env::var(ENV_BACKEND)
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

fn resolve_backend(
    config_backend: Option<CredentialStoreBackend>,
) -> CredentialResult<CredentialStoreBackend> {
    if let Some(value) = env_backend_override() {
        return CredentialStoreBackend::parse(&value);
    }
    Ok(config_backend.unwrap_or(CredentialStoreBackend::Os))
}

fn activate(backend: CredentialStoreBackend) -> CredentialResult<()> {
    let store = Arc::new(startup_notice::NotifyingCredentialStore {
        inner: open_credential_store(backend)?,
        backend,
    });
    let mut guard = process_state()
        .lock()
        .unwrap_or_else(|error| error.into_inner());
    guard.store = Some(store);
    Ok(())
}

fn remember_config_path(path: &Path) {
    let mut guard = process_state()
        .lock()
        .unwrap_or_else(|error| error.into_inner());
    guard.config_path = Some(path.to_path_buf());
}

fn selected_store() -> CredentialResult<Arc<dyn CredentialStore>> {
    {
        let guard = process_state()
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        if let Some(store) = guard.store.as_ref() {
            return Ok(Arc::clone(store));
        }
    }
    let backend = configured_backend()?;
    activate(backend)?;
    let guard = process_state()
        .lock()
        .unwrap_or_else(|error| error.into_inner());
    guard.store.clone().ok_or_else(|| {
        CredentialError::StoreUnavailable("credential store failed to initialize".into())
    })
}

struct ProcessState {
    store: Option<Arc<dyn CredentialStore>>,
    config_path: Option<PathBuf>,
}

fn process_state() -> &'static Mutex<ProcessState> {
    static STATE: OnceLock<Mutex<ProcessState>> = OnceLock::new();
    STATE.get_or_init(|| {
        Mutex::new(ProcessState {
            store: None,
            config_path: None,
        })
    })
}

fn read_config_backend() -> anyhow::Result<Option<CredentialStoreBackend>> {
    let path = {
        let guard = process_state()
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        guard.config_path.clone()
    };
    let path = match path {
        Some(path) => path,
        None => Config::default_path()?,
    };
    if !path.exists() {
        return Ok(None);
    }
    Ok(Config::load_settings_only(path)?.credential_store)
}

fn absorb_legacy_policy(config: &mut Config) -> anyhow::Result<bool> {
    let Some(backend) = read_legacy_policy_file()? else {
        return Ok(false);
    };
    let changed = if config.credential_store.is_none() {
        config.credential_store = Some(backend);
        true
    } else {
        false
    };
    remove_legacy_policy_file()?;
    Ok(changed)
}

fn read_legacy_policy_file() -> CredentialResult<Option<CredentialStoreBackend>> {
    let path = match legacy_policy_path() {
        Ok(path) => path,
        Err(_) => return Ok(None),
    };
    if !path.exists() {
        return Ok(None);
    }
    let value = std::fs::read_to_string(&path).map_err(|error| {
        CredentialError::StoreUnavailable(format!(
            "could not read legacy credential-store policy {}: {error}",
            path.display()
        ))
    })?;
    Ok(Some(CredentialStoreBackend::parse(&value)?))
}

fn remove_legacy_policy_file() -> anyhow::Result<()> {
    let path = legacy_policy_path()?;
    if path.exists() {
        std::fs::remove_file(path)?;
    }
    Ok(())
}

fn legacy_policy_path() -> anyhow::Result<PathBuf> {
    Ok(crate::paths::rho_dir()?.join(LEGACY_POLICY_FILE))
}

#[cfg(test)]
fn resolve_backend_from(
    environment: Option<&str>,
    config_backend: Option<CredentialStoreBackend>,
) -> CredentialResult<CredentialStoreBackend> {
    if let Some(value) = environment.map(str::trim).filter(|value| !value.is_empty()) {
        return CredentialStoreBackend::parse(value);
    }
    Ok(config_backend.unwrap_or(CredentialStoreBackend::Os))
}

#[cfg(test)]
fn needs_explicit_choice_from(
    env_set: bool,
    config_backend: Option<CredentialStoreBackend>,
) -> bool {
    !env_set && config_backend.is_none()
}

#[cfg(test)]
#[path = "credential_store_tests.rs"]
mod tests;