aonyx-agent 0.10.0

The agent with a real memory palace — Knowledge Graph + Hybrid Search + Time-machine. Agent loop + the `aonyx` CLI.
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
//! `aonyx setup` — the interactive configuration wizard.
//!
//! Walks the user through choosing an LLM provider, entering credentials
//! (stored in the OS keyring when one is available), picking a model, and
//! verifying everything with a live connection test — then writes
//! `~/.aonyx/config.toml`. Secrets go to the keyring, never the file,
//! unless the user explicitly opts into a plaintext fallback.

use std::sync::Arc;

use aonyx_core::{ChatRequest, LlmProvider, Message, Role};
use dialoguer::{theme::ColorfulTheme, Confirm, Input, Password, Select};
use futures::StreamExt;

use crate::config::Config;
use crate::secrets;

/// Provider menu: `(id, human label, needs an API key)`.
const PROVIDERS: &[(&str, &str, bool)] = &[
    ("anthropic", "Anthropic (Claude)", true),
    ("openai", "OpenAI", true),
    ("openrouter", "OpenRouter", true),
    ("ollama", "Ollama (local)", false),
    ("lm-studio", "LM Studio (local)", false),
    (
        "claude-code",
        "Claude Code (no key — uses the `claude` CLI)",
        false,
    ),
];

/// Entry point for `aonyx setup` / `aonyx setup provider`.
pub async fn run_provider_wizard() -> anyhow::Result<()> {
    let theme = ColorfulTheme::default();
    println!("aonyx setup — configure your LLM provider\n");

    // Operate on the on-disk config (no env merge) so we never round-trip
    // an env-sourced key back into the file.
    let mut config = Config::load_raw()?;

    let labels: Vec<&str> = PROVIDERS.iter().map(|p| p.1).collect();
    let default_idx = PROVIDERS
        .iter()
        .position(|p| p.0 == config.provider)
        .unwrap_or(0);
    let idx = Select::with_theme(&theme)
        .with_prompt("Provider")
        .items(&labels)
        .default(default_idx)
        .interact()?;
    let (provider, _label, needs_key) = PROVIDERS[idx];
    config.provider = provider.to_string();

    // Credentials (key-based providers only).
    if needs_key {
        if let Some((field, env_var)) = key_slots(provider) {
            let key: String = Password::with_theme(&theme)
                .with_prompt(format!(
                    "{env_var} (input hidden — leave empty to use $env)"
                ))
                .allow_empty_password(true)
                .interact()?;
            if key.trim().is_empty() {
                println!("  · no key entered — will read ${env_var} at runtime");
                clear_key_field(&mut config, field);
            } else {
                store_key(&mut config, field, key.trim(), &theme)?;
            }
        }
    }

    // Endpoint / binary for the remaining providers.
    match provider {
        "ollama" => {
            config.ollama_base_url = Some(prompt_default(
                &theme,
                "Ollama base URL",
                config
                    .ollama_base_url
                    .clone()
                    .unwrap_or_else(|| aonyx_llm::OLLAMA_DEFAULT_BASE_URL.to_string()),
            )?);
        }
        "lm-studio" => {
            config.lm_studio_base_url = Some(prompt_default(
                &theme,
                "LM Studio base URL",
                config.lm_studio_base_url.clone().unwrap_or_else(|| {
                    aonyx_llm::lm_studio::LM_STUDIO_DEFAULT_BASE_URL.to_string()
                }),
            )?);
        }
        "claude-code" => {
            config.claude_code_binary = Some(prompt_default(
                &theme,
                "Path to the `claude` binary",
                config
                    .claude_code_binary
                    .clone()
                    .unwrap_or_else(|| aonyx_llm::CLAUDE_DEFAULT_BIN.to_string()),
            )?);
        }
        _ => {}
    }

    // Model.
    config.model = prompt_default(&theme, "Model", default_model(provider, &config.model))?;

    // RAG — backend + embeddings (ADR-008 / ADR-009).
    let backends = [
        "local — built-in palace (offline)",
        "external — MCP rag_search",
    ];
    let b_idx = Select::with_theme(&theme)
        .with_prompt("RAG backend")
        .items(&backends)
        .default(if config.rag.backend == "external" {
            1
        } else {
            0
        })
        .interact()?;
    config.rag.backend = if b_idx == 1 { "external" } else { "local" }.to_string();

    let embeds = [
        "local — fastembed (offline; needs the `rag` build feature)",
        "provider — OpenAI / Ollama embeddings",
    ];
    let e_idx = Select::with_theme(&theme)
        .with_prompt("Embeddings")
        .items(&embeds)
        .default(if config.rag.embeddings == "provider" {
            1
        } else {
            0
        })
        .interact()?;
    config.rag.embeddings = if e_idx == 1 { "provider" } else { "local" }.to_string();

    // Live connection test (skip for claude-code — that shells out to the
    // `claude` CLI, which we don't want to spawn just to ping).
    if provider != "claude-code"
        && Confirm::with_theme(&theme)
            .with_prompt("Test the connection now?")
            .default(true)
            .interact()?
    {
        match crate::build_provider(&config) {
            Ok(p) => match test_connection(&p, &config.model).await {
                Ok(()) => println!("  ✓ connection OK"),
                Err(e) => {
                    println!("  ✗ connection failed: {e}");
                    if !Confirm::with_theme(&theme)
                        .with_prompt("Save the config anyway?")
                        .default(true)
                        .interact()?
                    {
                        println!("aborted — nothing written.");
                        return Ok(());
                    }
                }
            },
            Err(e) => println!("  ✗ could not build provider: {e} (will retry at runtime)"),
        }
    }

    config.save()?;
    println!("\n✓ wrote {}", Config::config_path()?.display());
    println!("  run `aonyx` to start a session.");
    Ok(())
}

/// Suggested default model per provider, falling back to whatever is
/// already configured for an unknown id.
fn default_model(provider: &str, current: &str) -> String {
    match provider {
        "anthropic" => "claude-sonnet-4-5-20250929".to_string(),
        "openai" => "gpt-4o".to_string(),
        "openrouter" => "anthropic/claude-3.5-sonnet".to_string(),
        "ollama" => "llama3.1:8b".to_string(),
        "lm-studio" => "local-model".to_string(),
        _ => current.to_string(),
    }
}

/// `(keyring key / config field, environment variable)` for a key-based
/// provider. The keyring key intentionally matches the `config.toml`
/// field name so the two storages share one identifier.
fn key_slots(provider: &str) -> Option<(&'static str, &'static str)> {
    match provider {
        "anthropic" => Some(("anthropic_api_key", "ANTHROPIC_API_KEY")),
        "openai" => Some(("openai_api_key", "OPENAI_API_KEY")),
        "openrouter" => Some(("openrouter_api_key", "OPENROUTER_API_KEY")),
        _ => None,
    }
}

/// Prompt for a free-text value with a pre-filled default.
fn prompt_default(theme: &ColorfulTheme, prompt: &str, default: String) -> anyhow::Result<String> {
    Ok(Input::<String>::with_theme(theme)
        .with_prompt(prompt)
        .default(default)
        .interact_text()?)
}

/// Store an API key in the keyring; on failure, offer a plaintext
/// fallback in `config.toml` or skip (leaving the env var as the source).
fn store_key(
    config: &mut Config,
    field: &str,
    key: &str,
    theme: &ColorfulTheme,
) -> anyhow::Result<()> {
    match secrets::set(field, key) {
        Ok(()) => {
            println!("  ✓ stored in the OS keyring");
            // Make sure no stale plaintext copy survives in the file.
            clear_key_field(config, field);
        }
        Err(e) => {
            println!("  ⚠ keyring unavailable ({e})");
            let plain = Confirm::with_theme(theme)
                .with_prompt("Store the key in ~/.aonyx/config.toml as plaintext instead?")
                .default(false)
                .interact()?;
            if plain {
                set_key_field(config, field, key);
                println!("  ✓ stored in config.toml (plaintext)");
            } else {
                clear_key_field(config, field);
                println!(
                    "  · skipped — export ${} to use this provider",
                    key_slots_env(field)
                );
            }
        }
    }
    Ok(())
}

fn set_key_field(c: &mut Config, field: &str, key: &str) {
    match field {
        "anthropic_api_key" => c.anthropic_api_key = Some(key.to_string()),
        "openai_api_key" => c.openai_api_key = Some(key.to_string()),
        "openrouter_api_key" => c.openrouter_api_key = Some(key.to_string()),
        _ => {}
    }
}

fn clear_key_field(c: &mut Config, field: &str) {
    match field {
        "anthropic_api_key" => c.anthropic_api_key = None,
        "openai_api_key" => c.openai_api_key = None,
        "openrouter_api_key" => c.openrouter_api_key = None,
        _ => {}
    }
}

fn key_slots_env(field: &str) -> &'static str {
    match field {
        "anthropic_api_key" => "ANTHROPIC_API_KEY",
        "openai_api_key" => "OPENAI_API_KEY",
        "openrouter_api_key" => "OPENROUTER_API_KEY",
        _ => "",
    }
}

/// Fire a one-shot, tiny completion and pull the first stream frame to
/// confirm the endpoint and credentials actually work.
async fn test_connection(provider: &Arc<dyn LlmProvider>, model: &str) -> anyhow::Result<()> {
    let req = ChatRequest {
        model: model.to_string(),
        messages: vec![Message::new(Role::User, "ping")],
        tools: Vec::new(),
        temperature: None,
        max_tokens: Some(16),
    };
    let mut stream = provider
        .chat_stream(req)
        .await
        .map_err(|e| anyhow::anyhow!("{e}"))?;
    match stream.next().await {
        Some(Ok(_)) => Ok(()),
        Some(Err(e)) => Err(anyhow::anyhow!("{e}")),
        // An empty-but-clean stream still proves the endpoint answered.
        None => Ok(()),
    }
}

/// Entry point for `aonyx setup telegram` — store the bot token in the
/// keyring and the allowed-chat list in `config.toml`. Always available
/// (writing config is light); actually running the bot needs the
/// `telegram` build feature.
pub async fn run_telegram_wizard() -> anyhow::Result<()> {
    let theme = ColorfulTheme::default();
    println!("aonyx setup telegram — configure the Telegram bot\n");
    let mut config = Config::load_raw()?;

    let token: String = Password::with_theme(&theme)
        .with_prompt("Bot token from @BotFather (hidden — empty to keep current / use $env)")
        .allow_empty_password(true)
        .interact()?;
    if token.trim().is_empty() {
        println!("  · no token entered — will read $TELEGRAM_BOT_TOKEN at runtime");
    } else {
        match secrets::set("telegram_bot_token", token.trim()) {
            Ok(()) => println!("  ✓ token stored in the OS keyring"),
            Err(e) => println!("  ⚠ keyring unavailable ({e}) — export TELEGRAM_BOT_TOKEN instead"),
        }
    }

    let current = config
        .telegram_allowed_chats
        .iter()
        .map(|i| i.to_string())
        .collect::<Vec<_>>()
        .join(",");
    let chats: String = Input::<String>::with_theme(&theme)
        .with_prompt("Allowed chat ids, comma-separated (empty = allow everyone)")
        .allow_empty(true)
        .default(current)
        .interact_text()?;
    config.telegram_allowed_chats = parse_chat_ids(&chats);

    config.save()?;
    println!("\n✓ wrote {}", Config::config_path()?.display());
    if config.telegram_allowed_chats.is_empty() {
        println!("  ⚠ no allow-list — the bot will answer ANY chat. Add ids to lock it down.");
    }
    if cfg!(feature = "telegram") {
        println!("  run `aonyx serve telegram` to start the bot.");
    } else {
        println!(
            "  this build lacks Telegram support — reinstall with \
             `--features telegram` to run the bot."
        );
    }
    Ok(())
}

/// Entry point for `aonyx setup discord` — store the bot token in the
/// keyring and the allowed-channel list in `config.toml`.
pub async fn run_discord_wizard() -> anyhow::Result<()> {
    let theme = ColorfulTheme::default();
    println!("aonyx setup discord — configure the Discord bot\n");
    println!(
        "  note: enable the MESSAGE CONTENT intent for your bot at\n  \
         https://discord.com/developers/applications → Bot → Privileged Gateway Intents\n"
    );
    let mut config = Config::load_raw()?;

    let token: String = Password::with_theme(&theme)
        .with_prompt("Bot token (hidden — empty to keep current / use $env)")
        .allow_empty_password(true)
        .interact()?;
    if token.trim().is_empty() {
        println!("  · no token entered — will read $DISCORD_BOT_TOKEN at runtime");
    } else {
        match secrets::set("discord_bot_token", token.trim()) {
            Ok(()) => println!("  ✓ token stored in the OS keyring"),
            Err(e) => println!("  ⚠ keyring unavailable ({e}) — export DISCORD_BOT_TOKEN instead"),
        }
    }

    let current = config
        .discord_allowed_channels
        .iter()
        .map(|i| i.to_string())
        .collect::<Vec<_>>()
        .join(",");
    let chans: String = Input::<String>::with_theme(&theme)
        .with_prompt("Allowed channel ids, comma-separated (empty = allow everywhere)")
        .allow_empty(true)
        .default(current)
        .interact_text()?;
    config.discord_allowed_channels = parse_chat_ids(&chans);

    config.save()?;
    println!("\n✓ wrote {}", Config::config_path()?.display());
    if config.discord_allowed_channels.is_empty() {
        println!("  ⚠ no allow-list — the bot will answer ANY channel it can see.");
    }
    if cfg!(feature = "discord") {
        println!("  run `aonyx serve discord` to start the bot.");
    } else {
        println!(
            "  this build lacks Discord support — reinstall with \
             `--features discord` to run the bot."
        );
    }
    Ok(())
}

/// Parse a comma-separated list of chat ids, dropping blanks / non-numbers.
fn parse_chat_ids(s: &str) -> Vec<i64> {
    s.split(',')
        .filter_map(|p| p.trim().parse::<i64>().ok())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::parse_chat_ids;

    #[test]
    fn parses_and_skips_junk() {
        assert_eq!(parse_chat_ids("123, -456 ,abc,, 789"), vec![123, -456, 789]);
        assert!(parse_chat_ids("").is_empty());
    }
}