agent86-core 1.2.2

The agent behind agent86: a safe agent runtime you can embed
Documentation
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
//! The unified model interface.
//!
//! Every backend implements [`Provider::stream`]; [`Provider::complete`] is
//! derived from it, so one API round-trip yields both live text and the
//! authoritative result. Streamed and non-streamed calls therefore always agree
//! on the final text.

pub mod anthropic;
pub mod capabilities;
pub mod catalog;
pub mod google;
pub mod hints;
pub mod ollama;
pub mod openai;
pub mod reasoning;
pub mod remote_windows;
pub mod retry;

use crate::config::{Config, ProviderConfig};
use crate::pricing::PriceTable;
use crate::secrets::{resolve_api_key, OsKeyring, SecretStore};
use crate::types::{Completion, CompletionDelta, CompletionRequest, ModelRef};
use anthropic::{AnthropicConfig, AnthropicProvider};
use futures_util::future::BoxFuture;
use futures_util::stream::{BoxStream, StreamExt};
use ollama::{OllamaConfig, OllamaProvider};
use openai::{OpenAiConfig, OpenAiProvider};
use std::time::Duration;
use thiserror::Error;

/// llama.cpp's server (`llama-server --port`).
const LLAMACPP_DEFAULT_BASE_URL: &str = "http://localhost:8080/v1";

/// vLLM's own default port (`vllm serve --port`).
pub const VLLM_DEFAULT_BASE_URL: &str = "http://localhost:8000/v1";

/// The port LM Studio's docs assume throughout (`lms server start` reuses the last).
pub const LMSTUDIO_DEFAULT_BASE_URL: &str = "http://localhost:1234/v1";

/// A server agent86 knows beyond the OpenAI-compatible API it speaks (beyond
/// Python): chosen by a section's `adapter`, or by the built-in section's name.
/// The requests are the OpenAI adapter's; the kind decides the rest: whether a
/// key is optional, where the context window comes from, local pricing, and the
/// hints its errors get.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServerKind {
    Vllm,
    LmStudio,
}

impl ServerKind {
    /// The `adapter` value that selects this kind, and the built-in section's name.
    pub fn name(self) -> &'static str {
        match self {
            Self::Vllm => "vllm",
            Self::LmStudio => "lmstudio",
        }
    }

    /// The URL a section of this kind reaches when it sets none.
    pub fn default_base_url(self) -> &'static str {
        match self {
            Self::Vllm => VLLM_DEFAULT_BASE_URL,
            Self::LmStudio => LMSTUDIO_DEFAULT_BASE_URL,
        }
    }

    /// A key is sent when one resolves, and its absence is not an error: the
    /// server is open unless it was started with one (vLLM's `--api-key`, LM
    /// Studio's "Require Authentication").
    pub fn key_optional(self) -> bool {
        true
    }

    pub(crate) fn parse(adapter: &str) -> Option<Self> {
        match adapter.trim() {
            "vllm" => Some(Self::Vllm),
            "lmstudio" => Some(Self::LmStudio),
            _ => None,
        }
    }
}

/// The server kind behind section `name`: its `adapter` when it sets one, else
/// the built-in section's own. `None` for an unknown `adapter`, which
/// [`provider_for_ref`] refuses; callers that only label or price (the provider
/// list, the price table) treat it as no kind.
pub fn server_kind(name: &str, section: Option<&ProviderConfig>) -> Option<ServerKind> {
    match section.and_then(|section| section.adapter.as_deref()) {
        Some(adapter) => ServerKind::parse(adapter),
        None => ServerKind::parse(name),
    }
}

/// Is a key optional for section `name`? True for every [`ServerKind`]: the
/// third key state beside "required" (an `api_key_env`) and "none" (no
/// `api_key_env`), which the provider list, `keys set`, and the editor's model
/// lists all know.
pub fn key_optional(name: &str, section: Option<&ProviderConfig>) -> bool {
    server_kind(name, section).is_some_and(ServerKind::key_optional)
}

/// Construct the provider that serves `reference`, e.g. `openrouter:openai/gpt-4o-mini`.
///
/// Any provider section with a `base_url` is treated as OpenAI-compatible, so
/// OpenRouter, Groq, and Together work with only a config block; vLLM and LM
/// Studio have sections of their own, and `adapter` ([`ServerKind`]) for others.
/// A key is required for `openai` itself, and for other sections only when they
/// name an `api_key_env`; a `base_url` without one is a keyless local endpoint.
///
/// API keys come from the environment variable named by `api_key_env`, then
/// from the OS keyring (service `agent86`, account = the provider section name).
pub fn provider_for_ref(
    reference: &ModelRef,
    config: &Config,
) -> Result<Box<dyn Provider>, ProviderError> {
    provider_for_ref_with_store(reference, config, &OsKeyring)
}

/// [`provider_for_ref`] with an explicit secret store, so tests never touch the OS keyring.
pub fn provider_for_ref_with_store(
    reference: &ModelRef,
    config: &Config,
    store: &dyn SecretStore,
) -> Result<Box<dyn Provider>, ProviderError> {
    build_provider(reference, config, |name, section| {
        resolve_api_key(name, section.api_key_env.as_deref(), store)
    })
}

/// [`provider_for_ref`] with a key that was typed but not stored yet: the
/// connection test sends it as it is, skipping the environment and the keyring,
/// as Python's `provider_for_ref(..., api_key=key)` does.
pub fn provider_for_ref_with_key(
    reference: &ModelRef,
    config: &Config,
    api_key: &str,
) -> Result<Box<dyn Provider>, ProviderError> {
    build_provider(reference, config, |_, _| Some(api_key.to_owned()))
}

fn build_provider(
    reference: &ModelRef,
    config: &Config,
    api_key: impl FnOnce(&str, &ProviderConfig) -> Option<String>,
) -> Result<Box<dyn Provider>, ProviderError> {
    let name = reference.provider.as_str();
    let section = config.providers.get(name).cloned().unwrap_or_default();

    if let Some(adapter) = section.adapter.as_deref() {
        if ServerKind::parse(adapter).is_none() {
            return Err(ProviderError::InvalidSetting {
                provider: name.to_owned(),
                detail: format!(
                    "adapter must be \"vllm\" or \"lmstudio\", not {adapter:?}; remove it \
                     for a plain OpenAI-compatible endpoint"
                ),
            });
        }
    }

    if name == "anthropic" {
        // Python leaves the section's timeouts to the SDK's own (see anthropic.rs).
        let provider = AnthropicProvider::new(
            reference.model.clone(),
            AnthropicConfig {
                base_url: section.base_url.clone(),
                api_key_env: section
                    .api_key_env
                    .clone()
                    .unwrap_or_else(|| anthropic::DEFAULT_API_KEY_ENV.to_owned()),
                max_tokens: section.max_tokens,
                prompt_cache: section.prompt_cache,
                max_retries: section.max_retries,
                ..AnthropicConfig::default()
            },
            api_key(name, &section),
        )?
        .with_pricing(PriceTable::from_config(config), reference.to_string());
        return Ok(Box::new(provider));
    }

    // Gemini has its own adapter (beyond Python), for the thought signatures its
    // OpenAI-compatible endpoint loses.
    if name == "google" {
        let seconds = durations(name);
        let provider = google::GoogleProvider::new(
            reference.model.clone(),
            google::GoogleConfig {
                base_url: section.base_url.clone(),
                api_key_env: section
                    .api_key_env
                    .clone()
                    .unwrap_or_else(|| google::DEFAULT_API_KEY_ENV.to_owned()),
                config_name: name.to_owned(),
                max_tokens: section.max_tokens,
                connect_timeout: seconds("connect_timeout_s", section.connect_timeout_s)?,
                read_timeout: seconds("read_timeout_s", section.read_timeout_s)?,
                max_retries: section.max_retries,
                store: section.store,
            },
            api_key(name, &section),
        )?
        .with_pricing(PriceTable::from_config(config), reference.to_string());
        return Ok(Box::new(provider));
    }

    // Ollama has its own adapter (and no key), whatever its section says.
    if name == "ollama" {
        let seconds = durations(name);
        let provider = OllamaProvider::new(
            reference.model.clone(),
            OllamaConfig {
                base_url: section.base_url.clone(),
                num_ctx: section.num_ctx,
                max_tokens: section.max_tokens,
                connect_timeout: seconds("connect_timeout_s", section.connect_timeout_s)?,
                read_timeout: seconds("read_timeout_s", section.read_timeout_s)?,
                max_retries: section.max_retries,
            },
        )?;
        return Ok(Box::new(provider));
    }

    // llama.cpp serves the OpenAI-compatible API locally, so this is the OpenAI
    // adapter under its own name, with a local default and no key.
    if name == "llamacpp" {
        let mut section = section;
        section
            .base_url
            .get_or_insert_with(|| LLAMACPP_DEFAULT_BASE_URL.to_owned());
        let mut openai_config = openai_config(name, &section, false)?;
        openai_config.adapter = "llamacpp";
        let provider = OpenAiProvider::new(
            reference.model.clone(),
            openai_config,
            api_key(name, &section),
        )?
        .with_pricing(PriceTable::from_config(config), reference.to_string());
        return Ok(Box::new(provider));
    }

    // A known server (vLLM): the OpenAI adapter under the kind's name, its URL
    // defaulted, and a key sent only when one resolves.
    if let Some(kind) = server_kind(name, Some(&section)) {
        let mut section = section;
        section
            .base_url
            .get_or_insert_with(|| kind.default_base_url().to_owned());
        let mut openai_config = openai_config(name, &section, !kind.key_optional())?;
        openai_config.adapter = kind.name();
        // `[model.context_window]` wins over what the server reports.
        let overridden = [reference.to_string().as_str(), reference.model.as_str()]
            .iter()
            .any(|key| {
                config
                    .model
                    .context_window
                    .get(*key)
                    .is_some_and(|&w| w > 0)
            });
        openai_config.live_window = kind == ServerKind::LmStudio && !overridden;
        let provider = OpenAiProvider::new(
            reference.model.clone(),
            openai_config,
            api_key(name, &section),
        )?
        .with_pricing(PriceTable::from_config(config), reference.to_string());
        return Ok(Box::new(provider));
    }

    let require_key = match name {
        "openai" | "openai-compatible" => true,
        _ if section.base_url.is_some() => section.api_key_env.is_some(),
        _ => {
            return Err(ProviderError::UnknownProvider {
                provider: name.to_owned(),
            })
        }
    };

    let api_key = api_key(name, &section);
    let openai_config = openai_config(name, &section, require_key)?;
    let provider = OpenAiProvider::new(reference.model.clone(), openai_config, api_key)?
        .with_pricing(PriceTable::from_config(config), reference.to_string());
    Ok(Box::new(provider))
}

fn openai_config(
    name: &str,
    section: &ProviderConfig,
    require_key: bool,
) -> Result<OpenAiConfig, ProviderError> {
    let seconds = durations(name);
    Ok(OpenAiConfig {
        base_url: section.base_url.clone(),
        api_key_env: section.api_key_env.clone(),
        config_name: name.to_owned(),
        adapter: "openai",
        require_key,
        max_tokens: section.max_tokens,
        connect_timeout: seconds("connect_timeout_s", section.connect_timeout_s)?,
        read_timeout: seconds("read_timeout_s", section.read_timeout_s)?,
        max_retries: section.max_retries,
        routing: section.routing.clone(),
        live_window: false,
    })
}

/// A `[providers.<name>]` timeout as a duration, refusing negative or absurd values.
fn durations(name: &str) -> impl Fn(&str, f64) -> Result<Duration, ProviderError> + '_ {
    move |field, value| {
        Duration::try_from_secs_f64(value).map_err(|_| ProviderError::InvalidSetting {
            provider: name.to_owned(),
            detail: format!("{field} must be a non-negative number of seconds, not {value}"),
        })
    }
}

/// A stream of text deltas whose final item carries `done = true` and the full completion.
pub type DeltaStream<'a> = BoxStream<'a, Result<CompletionDelta, ProviderError>>;

/// Adapter behind one provider's API.
pub trait Provider: Send + Sync {
    /// Short adapter id, e.g. `openai` for every OpenAI-compatible endpoint.
    fn name(&self) -> &str;

    /// The concrete model this instance targets.
    fn model(&self) -> &str;

    /// Stream text deltas; the final delta carries `done = true` and the full completion.
    ///
    /// After any text delta has been yielded, a failure is surfaced as an error and
    /// never retried, because a retry would duplicate text the caller already saw.
    fn stream(&self, request: CompletionRequest) -> DeltaStream<'_>;

    /// A copy with the same settings and key and an HTTP client of its own, for a
    /// specialist sub-agent on a fan-out thread (beyond Python): a pooled
    /// connection only makes progress while the runtime that opened it is polled,
    /// so a thread must never reuse one another runtime opened. Never reads the
    /// keyring. Building the client can fail, which fails that delegation.
    fn fresh(&self) -> Result<std::sync::Arc<dyn Provider>, ProviderError>;

    /// The context window the server reports now, for a server that sets it at
    /// runtime (beyond Python): LM Studio's loaded context length, learned once a
    /// request has loaded the model and then kept for this provider's life. `None`
    /// leaves the window computed at startup or on `/model`.
    fn live_context_window(&self) -> Option<u64> {
        None
    }

    /// Consume [`Provider::stream`] and return the assembled completion.
    fn complete(
        &self,
        request: CompletionRequest,
    ) -> BoxFuture<'_, Result<Completion, ProviderError>> {
        Box::pin(collect_completion(self.model(), self.stream(request)))
    }
}

/// Assemble a completion from a delta stream, matching the Python `complete()`.
pub async fn collect_completion(
    model: &str,
    mut deltas: DeltaStream<'_>,
) -> Result<Completion, ProviderError> {
    let mut text = String::new();
    let mut thinking = String::new();
    let mut last = None;
    while let Some(delta) = deltas.next().await {
        let delta = delta?;
        text.push_str(&delta.text);
        thinking.push_str(&delta.thinking);
        if delta.done && delta.completion.is_some() {
            last = delta.completion;
        }
    }
    Ok(match last {
        None => Completion {
            text,
            thinking,
            model: Some(model.to_owned()),
            ..Completion::default()
        },
        Some(mut completion) => {
            if completion.text.is_empty() {
                completion.text = text;
            }
            if completion.thinking.is_empty() {
                completion.thinking = thinking;
            }
            completion
        }
    })
}

/// A provider could not be constructed or reached.
///
/// Every message is safe to show: response bodies and transport details are
/// redacted before they are stored here.
#[derive(Debug, Clone, PartialEq, Error)]
pub enum ProviderError {
    #[error(
        "Unknown provider '{provider}'. Built-in: anthropic, google, openai, ollama, llamacpp, vllm, lmstudio. \
         For an OpenAI-compatible endpoint, add a [providers.{provider}] block with a base_url \
         (e.g. OpenRouter, Groq, Together) to your config."
    )]
    UnknownProvider { provider: String },

    #[error("Invalid [providers.{provider}] setting: {detail}")]
    InvalidSetting { provider: String, detail: String },

    #[error(
        "No API key found. Set the {env} environment variable or store a key in the OS keyring (service \"agent86\", account \"{account}\")."
    )]
    MissingApiKey { env: String, account: String },

    #[error("Could not construct the HTTP client: {detail}")]
    Client { detail: String },

    #[error("HTTP {status}: {body}")]
    Http { status: u16, body: String },

    /// An HTTP failure from a known server whose body says what to fix (beyond
    /// Python; see [`hints`]): Python's text, then the hint.
    #[error("HTTP {status}: {body} -- {hint}")]
    HttpHint {
        status: u16,
        body: String,
        hint: String,
    },

    #[error("Cannot reach {endpoint}: {detail}")]
    Connect { endpoint: String, detail: String },

    #[error(
        "Timed out connecting to {endpoint} after {seconds}s (connect_timeout_s). \
         Raise connect_timeout_s in the [providers.*] block for this endpoint to allow more time."
    )]
    ConnectTimeout { endpoint: String, seconds: f64 },

    #[error(
        "Timed out waiting for {endpoint} after {seconds}s with no data received (read_timeout_s). \
         This is the maximum gap between streamed chunks, not the total generation time — \
         a long but still-progressing generation is not affected. \
         Raise read_timeout_s in the [providers.*] block for this endpoint if this endpoint is just slow to respond."
    )]
    ReadTimeout { endpoint: String, seconds: f64 },

    #[error(
        "{provider}: {endpoint} returned a malformed streaming chunk for model {model:?} — \
         could not parse the SSE 'data:' line as JSON ({detail}). \
         The stream was probably truncated, or the endpoint is not OpenAI-compatible."
    )]
    MalformedChunk {
        provider: String,
        endpoint: String,
        model: String,
        detail: String,
    },

    #[error(
        "{provider}: the connection to {endpoint} failed while streaming model {model:?} — {detail}. \
         The server closed the stream early; retry, or check the endpoint and network."
    )]
    StreamInterrupted {
        provider: String,
        endpoint: String,
        model: String,
        detail: String,
    },

    /// A message already worded as Python's adapter words it (Ollama's, Anthropic's).
    #[error("{0}")]
    Message(String),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{load_config, ConfigPaths, Overrides};
    use crate::secrets::NoSecretStore;

    fn builtin_config() -> Config {
        let paths = ConfigPaths {
            user: None,
            project: std::path::PathBuf::from("no-such-dir/config.toml"),
            project_trust: crate::config::ProjectTrust::Trusted,
        };
        load_config(&paths, &Overrides::default()).unwrap()
    }

    #[test]
    fn llamacpp_is_the_openai_adapter_under_its_own_name_without_a_key() {
        let mut config = builtin_config();
        let reference = ModelRef::parse("llamacpp:qwen3").unwrap();
        let provider = provider_for_ref_with_store(&reference, &config, &NoSecretStore).unwrap();
        assert_eq!((provider.name(), provider.model()), ("llamacpp", "qwen3"));

        // No base_url falls back to the local server, and a named key variable
        // with nothing behind it is still not required.
        let section = config.providers.get_mut("llamacpp").unwrap();
        section.base_url = None;
        section.api_key_env = Some("AGENT86_TEST_UNSET_LLAMACPP_KEY".to_owned());
        let provider = provider_for_ref_with_store(&reference, &config, &NoSecretStore).unwrap();
        assert_eq!(provider.name(), "llamacpp");
    }
}