openheim 0.1.0

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
# openheim as a Rust library

Openheim can be embedded directly in your Rust application. The library exposes the full agent runtime — sessions, streaming, conversation history, RAG, skills, MCP servers, and tools — through a single `OpenheimClient` facade built on top of the [Agent Client Protocol (ACP)](https://github.com/block/agent-client-protocol).

---

## Add to your project

```toml
# Cargo.toml
[dependencies]
openheim = { path = "../openheim-core" }   # or version once published
tokio = { version = "1", features = ["full"] }
```

---

## Quick start

```rust
use openheim::{OpenheimClient, SessionUpdate};

#[tokio::main]
async fn main() -> openheim::Result<()> {
    // Loads ~/.openheim/config.toml
    let client = OpenheimClient::builder().build().await?;

    let session = client
        .new_session()
        .cwd("/my/project")
        .start()
        .await?;

    session
        .prompt("What files are in the current directory?", |update| {
            if let SessionUpdate::AgentMessageChunk(chunk) = update {
                for block in &chunk.content {
                    if let openheim::ContentBlock::Text(t) = block {
                        print!("{}", t.text);
                    }
                }
            }
        })
        .await?;

    Ok(())
}
```

---

## Client initialisation

### From `~/.openheim/config.toml` (default)

```rust
let client = OpenheimClient::builder().build().await?;
```

### From a custom config file

```rust
let client = OpenheimClient::from_config("/etc/myapp/openheim.toml")
    .build()
    .await?;
```

### Programmatic config (no file needed)

```rust
let client = OpenheimClient::builder()
    .provider("anthropic")
    .api_key("sk-ant-...")
    .model("claude-opus-4-7")
    .max_iterations(15)
    .build()
    .await?;
```

Supported `provider` values: `"openai"`, `"anthropic"`, `"gemini"`, or any string for OpenAI-compatible endpoints (Ollama, vLLM, LM Studio, etc.).

Default models when `.model()` is omitted:
- `"anthropic"``claude-sonnet-4-6`
- `"gemini"``gemini-2.0-flash`
- everything else → `gpt-4o`

### With MCP servers

MCP servers can be added in either mode. Their tools become available to the agent automatically as `{server_name}__{tool_name}`.

```rust
use openheim::{McpServerConfig, OpenheimClient};
use std::collections::HashMap;

let client = OpenheimClient::builder()
    .provider("openai")
    .api_key(std::env::var("OPENAI_API_KEY").unwrap())
    // stdio MCP server
    .mcp_server("filesystem", McpServerConfig {
        command: Some("npx".into()),
        args: vec![
            "-y".into(),
            "@modelcontextprotocol/server-filesystem".into(),
            "/workspace".into(),
        ],
        env: HashMap::new(),
        url: None,
    })
    // Streamable HTTP MCP server
    .mcp_server("my-tools", McpServerConfig {
        command: None,
        args: vec![],
        env: HashMap::new(),
        url: Some("http://localhost:8080/mcp".into()),
    })
    .build()
    .await?;
```

MCP servers defined in a config file are always loaded; builder `.mcp_server()` calls are merged in on top.

---

## Sessions

Sessions are the unit of conversation. Each session has its own message history, model, skills, and working directory.

### Create a session

```rust
let session = client
    .new_session()
    .model("gpt-4o")                          // optional — overrides the config default
    .skills(vec!["rust".into(), "tdd".into()]) // optional — names of ~/.openheim/skills/*.md
    .cwd("/my/workspace")                      // optional — used for history filtering
    .start()
    .await?;

println!("session id: {}", session.id);
```

### Send a prompt (streaming)

`prompt` calls your callback once per ACP `SessionUpdate` event as the agent runs.

```rust
use openheim::{AcpToolCall, ContentBlock, SessionUpdate};

session
    .prompt("Refactor the auth module to use JWTs", |update| {
        match update {
            SessionUpdate::AgentMessageChunk(chunk) => {
                for block in &chunk.content {
                    if let ContentBlock::Text(t) = block {
                        print!("{}", t.text);
                    }
                }
            }
            SessionUpdate::ToolCall(tc) => {
                println!("\n[tool] {} — running…", tc.name);
            }
            SessionUpdate::ToolCallUpdate(tcu) => {
                println!("[tool] {} — done", tcu.id);
            }
            _ => {}
        }
    })
    .await?;
```

### Multi-turn conversation

Call `prompt` multiple times on the same handle. The agent accumulates history on disk automatically.

```rust
session.prompt("My name is Alice", |_| {}).await?;
session.prompt("What's my name?", |update| { /* prints "Alice" */ }).await?;
```

---

## History & session management

### List sessions

```rust
use std::path::Path;

// All sessions, newest first
let all = client.list_sessions(None)?;

// Only sessions from a specific working directory
let workspace = client.list_sessions(Some(Path::new("/my/workspace")))?;

for info in &workspace {
    println!("{} — {}", info.id, info.title.as_deref().unwrap_or("untitled"));
}
```

### Get full conversation (messages + metadata)

```rust
let conv = client.get_session("550e8400-e29b-41d4-a716-446655440000")?;

println!("model: {:?}", conv.meta.model);
println!("messages: {}", conv.messages.len());

for msg in &conv.messages {
    println!("[{:?}] {}", msg.role, msg.content.as_deref().unwrap_or(""));
}
```

### Resume a session (load + continue prompting)

`load_session` registers the conversation in the live sessions map and replays the message history through your callback so you can populate a UI.

```rust
let session = client
    .load_session(
        "550e8400-e29b-41d4-a716-446655440000",
        "/my/workspace".into(),
        |update| {
            // replay previous messages into your UI
            match update {
                SessionUpdate::UserMessageChunk(chunk) => { /* render user bubble */ }
                SessionUpdate::AgentMessageChunk(chunk) => { /* render agent bubble */ }
                _ => {}
            }
        },
    )
    .await?;

// Continue where the conversation left off
session.prompt("Continue from where you left off", |update| { /* … */ }).await?;
```

### Delete a session

```rust
client.delete_session("550e8400-e29b-41d4-a716-446655440000")?;
```

---

## RAG — direct history and skills access

`client.rag()` returns a `&RagContext` with direct access to the underlying `HistoryManager` and `SkillsManager`. This is useful for advanced use cases like building custom UIs, searching conversations, or managing skills programmatically.

```rust
let rag = client.rag();

// List all conversation metadata
let metas = rag.history.list_conversations()?;

// Load a full conversation
let conv = rag.history.load_conversation(&uuid)?;

// Save a conversation (e.g. after external edits)
rag.history.save_conversation(&conv)?;

// List available skills
let skills = rag.skills.list_skills()?;
// → ["debugging", "rust", "tdd"]

// Load skill content
let content = rag.skills.load_skill("rust")?;
println!("{content}");
```

---

## Introspection

### Available tools

```rust
for tool in client.tools() {
    println!("{}: {}", tool.function.name, tool.function.description.as_deref().unwrap_or(""));
}
```

### MCP server statuses

```rust
for status in client.mcp_servers() {
    println!(
        "{} [{}] connected={} tools={}{}",
        status.name,
        status.transport,
        status.connected,
        status.tool_count,
        status.error.as_deref().map(|e| format!(" error={e}")).unwrap_or_default(),
    );
}
```

### Available models

```rust
let models = client.models();
println!("default provider: {}", models.default_provider);
for (provider, info) in &models.providers {
    println!("  {provider}: {} (default)", info.default_model);
    for model in &info.models {
        println!("    - {model}");
    }
}
```

---

## Full example — multi-provider app with MCP and history

```rust
use openheim::{ContentBlock, McpServerConfig, OpenheimClient, SessionUpdate};
use std::collections::HashMap;

#[tokio::main]
async fn main() -> openheim::Result<()> {
    let client = OpenheimClient::builder()
        .provider("anthropic")
        .api_key(std::env::var("ANTHROPIC_API_KEY").unwrap())
        .model("claude-opus-4-7")
        .max_iterations(20)
        .mcp_server("fs", McpServerConfig {
            command: Some("npx".into()),
            args: vec![
                "-y".into(),
                "@modelcontextprotocol/server-filesystem".into(),
                "/workspace".into(),
            ],
            env: HashMap::new(),
            url: None,
        })
        .build()
        .await?;

    // Print MCP connection status
    for s in client.mcp_servers() {
        println!("[mcp] {} — connected={} tools={}", s.name, s.connected, s.tool_count);
    }

    // Check for an existing session or start fresh
    let all_sessions = client.list_sessions(Some(std::path::Path::new("/workspace")))?;
    let session = if let Some(last) = all_sessions.first() {
        println!("Resuming session: {}", last.id);
        client
            .load_session(&last.id.to_string(), "/workspace".into(), |_| {})
            .await?
    } else {
        client
            .new_session()
            .skills(vec!["rust".into()])
            .cwd("/workspace")
            .start()
            .await?
    };

    session
        .prompt("Summarise the project structure", |update| {
            if let SessionUpdate::AgentMessageChunk(chunk) = update {
                for block in &chunk.content {
                    if let ContentBlock::Text(t) = block {
                        print!("{}", t.text);
                    }
                }
            }
        })
        .await?;

    println!("\nDone. Session id: {}", session.id);
    Ok(())
}
```

---

## ACP event reference

All events received by the `prompt` callback are `agent_client_protocol::schema::SessionUpdate` variants, re-exported from `openheim`:

| Variant | When |
|---|---|
| `AgentMessageChunk(ContentChunk)` | Streaming text from the LLM |
| `UserMessageChunk(ContentChunk)` | Echoed user message (during `load_session` history replay) |
| `ToolCall(AcpToolCall)` | Agent is about to invoke a tool |
| `ToolCallUpdate(ToolCallUpdate)` | Tool finished; contains status and raw output |

`ContentChunk.content` is a `Vec<ContentBlock>`. Match on `ContentBlock::Text(t)` to get the text string.

---

## Error handling

All fallible operations return `openheim::Result<T>` (`std::result::Result<T, openheim::Error>`).

```rust
use openheim::{Error, OpenheimClient};

match client.get_session("bad-id") {
    Ok(conv) => { /* … */ }
    Err(Error::ConfigError(msg)) => eprintln!("config: {msg}"),
    Err(Error::Other(msg)) => eprintln!("error: {msg}"),
    Err(e) => eprintln!("unexpected: {e}"),
}
```

Transient LLM errors (rate limits, 5xx, network timeouts) are retried automatically with exponential backoff before surfacing as `Error::HttpError` or `Error::ApiError`.