openheim 0.2.1

A fast, multi-provider LLM agent runtime written in Rust
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
use std::{
    collections::BTreeMap,
    path::{Path, PathBuf},
    sync::Arc,
};

use agent_client_protocol::schema::{SessionInfo, SessionUpdate};
use uuid::Uuid;

use crate::{
    acp::AgentState,
    config::{
        AgentConfig, AppConfig, McpServerConfig, ProviderConfig, load_config, load_config_from,
    },
    error::Result,
    mcp::McpServerStatus,
    rag::{Conversation, ConversationMeta, RagContext},
};

/// The main entry point for embedding openheim in your application.
///
/// Wraps an `AgentState` and exposes all agent capabilities:
/// sessions, history, RAG, MCP servers, tools, and models.
pub struct OpenheimClient {
    state: Arc<AgentState>,
}

impl OpenheimClient {
    /// Start building a client with programmatic config or a config file.
    pub fn builder() -> OpenheimBuilder {
        OpenheimBuilder::default()
    }

    /// Shorthand to start from a specific config file path.
    pub fn from_config(path: impl AsRef<Path>) -> OpenheimBuilder {
        OpenheimBuilder {
            config_path: Some(path.as_ref().to_path_buf()),
            ..Default::default()
        }
    }

    // ── Sessions ──────────────────────────────────────────────────────────────

    /// Create a new session. Returns a builder to set model, skills, and cwd.
    pub fn new_session(&self) -> SessionBuilder<'_> {
        SessionBuilder {
            state: &self.state,
            model: None,
            skills: vec![],
            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")),
        }
    }

    /// List persisted sessions (all or filtered by cwd).
    pub async fn list_sessions(&self, cwd: Option<&Path>) -> Result<Vec<SessionInfo>> {
        self.state.acp_list_sessions(cwd).await
    }

    /// Load a persisted session into a live `SessionHandle`.
    ///
    /// `on_history` is called once for each message in the conversation history
    /// (as `SessionUpdate::UserMessageChunk` / `AgentMessageChunk`) so callers
    /// can replay the conversation in their UI.
    pub async fn load_session(
        &self,
        session_id: &str,
        cwd: PathBuf,
        on_history: impl FnMut(SessionUpdate) + Send,
    ) -> Result<SessionHandle> {
        self.state
            .acp_load_session(session_id, cwd, on_history)
            .await?;
        Ok(SessionHandle {
            id: session_id.to_string(),
            state: self.state.clone(),
        })
    }

    /// Fetch the full `Conversation` (messages + metadata) for a session id.
    pub fn get_session(&self, session_id: &str) -> Result<Conversation> {
        let uuid = Uuid::parse_str(session_id)
            .map_err(|_| crate::error::Error::Other("invalid session id".to_string()))?;
        self.state.rag.history.load_conversation(&uuid)
    }

    /// List all conversation metadata without loading messages.
    pub fn list_all_sessions(&self) -> Result<Vec<ConversationMeta>> {
        self.state.rag.history.list_conversations()
    }

    /// Permanently delete a persisted session.
    pub fn delete_session(&self, session_id: &str) -> Result<()> {
        let uuid = Uuid::parse_str(session_id)
            .map_err(|_| crate::error::Error::Other("invalid session id".to_string()))?;
        self.state.rag.history.delete_conversation(&uuid)
    }

    // ── RAG ───────────────────────────────────────────────────────────────────

    /// Direct access to the RAG context (history + skills managers).
    pub fn rag(&self) -> &RagContext {
        &self.state.rag
    }

    // ── Introspection ─────────────────────────────────────────────────────────

    /// All tool definitions available to the agent (built-in + MCP).
    pub fn tools(&self) -> Vec<crate::core::models::Tool> {
        self.state.executor.list_tools()
    }

    /// MCP server connection statuses.
    pub fn mcp_servers(&self) -> &[McpServerStatus] {
        &self.state.mcp_statuses
    }

    /// Available models per provider (no credentials).
    pub fn models(&self) -> crate::config::ModelsInfo {
        self.state.app_config.models_info()
    }
}

// ── SessionBuilder ────────────────────────────────────────────────────────────

/// Builder returned by `OpenheimClient::new_session()`.
pub struct SessionBuilder<'a> {
    state: &'a Arc<AgentState>,
    model: Option<String>,
    skills: Vec<String>,
    cwd: PathBuf,
}

impl<'a> SessionBuilder<'a> {
    /// Override the model for this session (must be listed in the config).
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Skills to inject into the system prompt (names of `~/.openheim/skills/*.md` files).
    pub fn skills(mut self, skills: Vec<String>) -> Self {
        self.skills = skills;
        self
    }

    /// Working directory for this session (used for history filtering).
    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
        self.cwd = cwd.into();
        self
    }

    /// Create the session and return a handle for prompting.
    pub async fn start(self) -> Result<SessionHandle> {
        let id = self
            .state
            .acp_new_session(self.model.as_deref(), self.skills, self.cwd)
            .await?;
        Ok(SessionHandle {
            id,
            state: self.state.clone(),
        })
    }
}

// ── SessionHandle ─────────────────────────────────────────────────────────────

/// A live session that can receive prompts.
pub struct SessionHandle {
    pub id: String,
    state: Arc<AgentState>,
}

impl SessionHandle {
    /// Send a prompt and stream ACP `SessionUpdate` events to `on_update`.
    ///
    /// The callback receives:
    /// - `SessionUpdate::AgentMessageChunk` — streaming text from the LLM
    /// - `SessionUpdate::ToolCall` — a tool the agent is about to invoke
    /// - `SessionUpdate::ToolCallUpdate` — result of the tool call
    pub async fn prompt(
        &self,
        text: &str,
        on_update: impl FnMut(SessionUpdate) + Send,
    ) -> Result<()> {
        self.state
            .acp_prompt(&self.id, text.to_string(), on_update)
            .await
    }

    /// Switch the model for this session mid-conversation.
    ///
    /// The model must be listed under a provider in the config. Returns
    /// `(provider_name, model_name)` on success; the next prompt will use
    /// the new model while preserving conversation history.
    pub async fn switch_model(&self, provider: &str, model: &str) -> Result<(String, String)> {
        self.state
            .acp_update_session_model(&self.id, provider, model)
            .await
    }

    /// Restore a persisted session as the active session for this handle.
    ///
    /// Registers the conversation in the agent state so subsequent `prompt`
    /// calls continue from its history. Pass a no-op callback — the TUI
    /// already replays history visually before calling this.
    pub async fn restore(
        &self,
        session_id: &str,
        cwd: std::path::PathBuf,
    ) -> Result<SessionHandle> {
        self.state.acp_load_session(session_id, cwd, |_| {}).await?;
        Ok(SessionHandle {
            id: session_id.to_string(),
            state: Arc::clone(&self.state),
        })
    }
}

// ── OpenheimBuilder ───────────────────────────────────────────────────────────

/// Builder for `OpenheimClient`.
///
/// Supports two modes:
/// 1. **Programmatic** — set `.provider()`, `.api_key()`, `.model()` directly.
/// 2. **File-based** — call `OpenheimClient::from_config(path)` or leave
///    everything unset to load from `~/.openheim/config.toml`.
///
/// MCP servers can be added in either mode with `.mcp_server()`.
#[derive(Default)]
pub struct OpenheimBuilder {
    // file-based path (None = ~/.openheim/config.toml)
    config_path: Option<PathBuf>,
    // programmatic fields — if any of these are set we skip the config file
    provider: Option<String>,
    api_key: Option<String>,
    model: Option<String>,
    api_base: Option<String>,
    max_iterations: Option<usize>,
    timeout_secs: Option<u64>,
    max_tokens: Option<u32>,
    mcp_servers: BTreeMap<String, McpServerConfig>,
}

impl OpenheimBuilder {
    /// Path to a config file (overrides `~/.openheim/config.toml`).
    pub fn config_path(mut self, path: impl AsRef<Path>) -> Self {
        self.config_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// Provider name: `"openai"`, `"anthropic"`, `"gemini"`, or any custom name
    /// for OpenAI-compatible endpoints.
    pub fn provider(mut self, provider: impl Into<String>) -> Self {
        self.provider = Some(provider.into());
        self
    }

    /// API key for the provider.
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    /// Model name (e.g. `"claude-opus-4-7"`, `"gpt-4o"`).
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Override the provider API base URL (useful for proxies or local models).
    pub fn api_base(mut self, base: impl Into<String>) -> Self {
        self.api_base = Some(base.into());
        self
    }

    /// Maximum number of agent iterations before stopping.
    pub fn max_iterations(mut self, n: usize) -> Self {
        self.max_iterations = Some(n);
        self
    }

    /// Request timeout in seconds.
    pub fn timeout_secs(mut self, secs: u64) -> Self {
        self.timeout_secs = Some(secs);
        self
    }

    /// Maximum output tokens for LLM responses.
    pub fn max_tokens(mut self, tokens: u32) -> Self {
        self.max_tokens = Some(tokens);
        self
    }

    /// Register an MCP server. Tools will be available as `{name}__{tool_name}`.
    pub fn mcp_server(mut self, name: impl Into<String>, config: McpServerConfig) -> Self {
        self.mcp_servers.insert(name.into(), config);
        self
    }

    /// Build the client, connecting to MCP servers and initialising the agent state.
    pub async fn build(self) -> Result<OpenheimClient> {
        let (agent_config, mut app_config) = if self.provider.is_some()
            || self.api_key.is_some()
            || self.model.is_some()
            || self.api_base.is_some()
        {
            build_programmatic(
                self.provider,
                self.api_key,
                self.model,
                self.api_base,
                self.max_iterations,
                self.timeout_secs,
                self.max_tokens,
            )
        } else {
            let app_config = match self.config_path {
                Some(ref path) => load_config_from(path)?,
                None => load_config()?,
            };
            let mut agent_config = app_config.resolve(None)?;
            if let Some(n) = self.max_iterations {
                agent_config.max_iterations = n;
            }
            if let Some(s) = self.timeout_secs {
                agent_config.timeout_secs = s;
            }
            if let Some(t) = self.max_tokens {
                agent_config.max_tokens = Some(t);
            }
            (agent_config, app_config)
        };

        // Merge any extra MCP servers from the builder
        for (name, cfg) in self.mcp_servers {
            app_config.mcp_servers.insert(name, cfg);
        }

        let rag = RagContext::new()?;
        let state = Arc::new(AgentState::new(agent_config, app_config, rag).await?);
        Ok(OpenheimClient { state })
    }
}

fn build_programmatic(
    provider: Option<String>,
    api_key: Option<String>,
    model: Option<String>,
    api_base: Option<String>,
    max_iterations: Option<usize>,
    timeout_secs: Option<u64>,
    max_tokens: Option<u32>,
) -> (AgentConfig, AppConfig) {
    let provider = provider.unwrap_or_else(|| "openai".to_string());
    let api_base = api_base.unwrap_or_else(|| default_api_base(&provider));
    let model = model.unwrap_or_else(|| default_model(&provider));
    let api_key = api_key.unwrap_or_default();
    let max_iter = max_iterations.unwrap_or(10);
    let timeout = timeout_secs.unwrap_or(120);

    let mut providers = BTreeMap::new();
    providers.insert(
        provider.clone(),
        ProviderConfig {
            api_base: api_base.clone(),
            default_model: model.clone(),
            models: vec![model.clone()],
            env_var: None,
            api_key: Some(api_key.clone()),
            timeout_secs: Some(timeout),
            max_tokens,
        },
    );

    let app_config = AppConfig {
        default_provider: provider.clone(),
        max_iterations: max_iter,
        theme_color: None,
        providers,
        mcp_servers: BTreeMap::new(),
    };

    let agent_config = AgentConfig {
        provider_name: provider,
        api_base,
        api_key,
        model,
        max_iterations: max_iter,
        timeout_secs: timeout,
        max_tokens,
    };

    (agent_config, app_config)
}

fn default_api_base(provider: &str) -> String {
    match provider {
        "anthropic" => "https://api.anthropic.com/v1".to_string(),
        "gemini" => "https://generativelanguage.googleapis.com/v1beta".to_string(),
        _ => "https://api.openai.com/v1".to_string(),
    }
}

fn default_model(provider: &str) -> String {
    match provider {
        "anthropic" => "claude-sonnet-4-6".to_string(),
        "gemini" => "gemini-2.0-flash".to_string(),
        _ => "gpt-4o".to_string(),
    }
}