takobull 0.2.2

Ultra-lightweight personal AI Assistant for embedded systems - Rust port
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
//! TakoBull CLI entry point
//!
//! This is the main executable for TakoBull, providing command-line interface
//! and initialization of the system.

use clap::{Parser, Subcommand};
use std::path::PathBuf;
use tracing::info;

#[derive(Parser, Debug)]
#[command(name = "takobull")]
#[command(about = "Ultra-lightweight personal AI Assistant for embedded systems", long_about = None)]
#[command(version)]
#[command(author)]
struct Args {
    /// Path to configuration file
    #[arg(short, long, value_name = "FILE", global = true)]
    config: Option<PathBuf>,

    /// Log level (debug, info, warn, error)
    #[arg(short, long, default_value = "info", global = true)]
    log_level: String,

    /// Enable verbose output
    #[arg(short, long, global = true)]
    verbose: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Chat with the agent
    Agent {
        /// Message to send to the agent
        #[arg(short, long)]
        message: Option<String>,
    },
    /// Start the gateway for channel integrations
    Gateway,
    /// Show system status
    Status,
    /// Manage scheduled cron jobs
    Cron {
        #[command(subcommand)]
        action: CronAction,
    },
    /// Initialize configuration and workspace
    Onboard {
        /// Force overwrite existing config
        #[arg(long)]
        force: bool,
    },
}

#[derive(Subcommand, Debug)]
enum CronAction {
    /// List all scheduled jobs
    List,
    /// Add a new scheduled job
    Add {
        /// Cron expression
        #[arg(short, long)]
        expression: String,
        /// Job description
        #[arg(short, long)]
        description: String,
    },
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args = Args::parse();

    // Initialize logging
    takobull::logging::setup::init_logging(&args.log_level)?;

    info!("Starting TakoBull v{}", env!("CARGO_PKG_VERSION"));
    if let Some(config_path) = &args.config {
        info!("Configuration file: {:?}", config_path);
    }

    match args.command {
        Some(Commands::Agent { message }) => {
            handle_agent(message).await?;
        }
        Some(Commands::Gateway) => {
            handle_gateway().await?;
        }
        Some(Commands::Status) => {
            handle_status().await?;
        }
        Some(Commands::Cron { action }) => {
            handle_cron(action).await?;
        }
        Some(Commands::Onboard { force }) => {
            handle_onboard(force).await?;
        }
        None => {
            // Default: show help
            println!("TakoBull v{}", env!("CARGO_PKG_VERSION"));
            println!("Ultra-lightweight personal AI Assistant for embedded systems");
            println!("\nUsage: takobull [OPTIONS] <COMMAND>");
            println!("\nCommands:");
            println!("  agent    Chat with the agent");
            println!("  gateway  Start the gateway for channel integrations");
            println!("  status   Show system status");
            println!("  cron     Manage scheduled cron jobs");
            println!("  onboard  Initialize configuration and workspace");
            println!("\nOptions:");
            println!("  -c, --config <FILE>          Path to configuration file");
            println!("  -l, --log-level <LOG_LEVEL>  Log level (debug, info, warn, error)");
            println!("  -v, --verbose                Enable verbose output");
            println!("  -h, --help                   Print help");
            println!("  -V, --version                Print version");
        }
    }

    info!("TakoBull completed successfully");

    Ok(())
}

async fn handle_agent(message: Option<String>) -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting agent");

    // Load config
    let home = std::env::var("HOME")?;
    let config_path = format!("{}/.takobull/config.yaml", home);
    let workspace_path = format!("{}/.takobull/workspace", home);
    
    if !std::path::Path::new(&config_path).exists() {
        eprintln!("❌ Config not found: {}", config_path);
        eprintln!("Run 'takobull onboard' first to initialize");
        return Err("Config file not found".into());
    }

    let config_content = std::fs::read_to_string(&config_path)?;
    info!("Loaded config from: {}", config_path);

    if let Some(msg) = message {
        info!("Processing message: {}", msg);
        
        // Parse YAML config
        let config: serde_yaml::Value = serde_yaml::from_str(&config_content)?;
        
        let provider = config["agents"]["defaults"]["provider"]
            .as_str()
            .unwrap_or("openrouter")
            .to_string();
        
        let model = config["agents"]["defaults"]["model"]
            .as_str()
            .unwrap_or("meta-llama/llama-2-70b-chat")
            .to_string();
        
        // Get API key and base from provider config
        let provider_config = &config["providers"][&provider];
        let api_key = provider_config["api_key"]
            .as_str()
            .unwrap_or("")
            .to_string();
        
        // Provider-specific default API bases
        let default_api_base = match provider.as_str() {
            "openai" | "gpt" => "https://api.openai.com/v1",
            "anthropic" | "claude" => "https://api.anthropic.com/v1",
            "openrouter" => "https://openrouter.ai/api/v1",
            "groq" => "https://api.groq.com/openai/v1",
            "zhipu" | "glm" => "https://open.bigmodel.cn/api/paas/v4",
            "gemini" | "google" => "https://generativelanguage.googleapis.com/v1beta",
            "deepseek" => "https://api.deepseek.com/v1",
            "ollama" => "http://localhost:11434", // Local ollama (no /v1 suffix)
            "vllm" => "", // vLLM requires explicit api_base
            _ => "https://openrouter.ai/api/v1",
        };
        
        let api_base = provider_config["api_base"]
            .as_str()
            .unwrap_or(default_api_base)
            .to_string();
        
        info!("Using provider: {}, model: {}", provider, model);
        
        // Validate provider configuration
        if provider == "vllm" && api_base.is_empty() {
            eprintln!("❌ vLLM requires api_base to be configured");
            eprintln!("Set the api_base in ~/.takobull/config.yaml under providers.vllm.api_base");
            eprintln!("Example: providers.vllm.api_base: http://localhost:8000");
            return Err("vLLM api_base not configured".into());
        }
        
        // Local providers (ollama, vllm) don't require API keys
        let requires_api_key = !matches!(provider.as_str(), "ollama" | "vllm");
        
        if api_key.is_empty() && requires_api_key {
            eprintln!("❌ API key not configured for provider: {}", provider);
            eprintln!("Set the API key in ~/.takobull/config.yaml under providers.{}.api_key", provider);
            return Err("API key not configured".into());
        }
        
        // Create LLM client
        let llm_client = takobull::llm::LlmClient::new(&provider, &model, &api_key, &api_base);
        
        // Create tool registry and register tools
        let tool_registry = takobull::tools::ToolRegistry::new();
        let write_file_tool = std::sync::Arc::new(
            takobull::tools::WriteFileTool::new(workspace_path)
        );
        tool_registry.register(write_file_tool).await;
        
        // Create agent executor
        let executor = takobull::agent::AgentExecutor::new(llm_client, tool_registry);
        
        println!("🤖 Processing: {}", msg);
        
        match executor.execute(&msg).await {
            Ok(response) => {
                println!("{}", response);
                info!("Response: {}", response);
            }
            Err(e) => {
                eprintln!("❌ Error: {}", e);
                return Err(e);
            }
        }
    } else {
        info!("Starting interactive agent mode");
        println!("🤖 TakoBull Interactive Mode");
        println!("Type 'exit' to quit\n");
        
        // TODO: Start interactive REPL
        println!("(Interactive mode not yet implemented)");
    }

    Ok(())
}

async fn handle_gateway() -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting gateway");
    println!("Gateway mode (not yet implemented)");
    // TODO: Initialize channel connections
    // TODO: Start listening for messages
    Ok(())
}

async fn handle_status() -> Result<(), Box<dyn std::error::Error>> {
    info!("Showing status");
    
    let home = std::env::var("HOME")?;
    let config_path = format!("{}/.takobull/config.yaml", home);
    let workspace = format!("{}/.takobull/workspace", home);
    
    println!("🤖 takobull Status");
    println!("Version: v{}", env!("CARGO_PKG_VERSION"));
    
    // Config status
    let config_exists = std::path::Path::new(&config_path).exists();
    let config_status = if config_exists { "" } else { "" };
    println!("Config: {} {}", config_path, config_status);
    
    // Workspace status
    let workspace_exists = std::path::Path::new(&workspace).exists();
    let workspace_status = if workspace_exists { "" } else { "" };
    println!("Workspace: {} {}", workspace, workspace_status);
    
    // Load config if it exists
    if config_exists {
        let config_content = std::fs::read_to_string(&config_path)?;
        let config: serde_yaml::Value = serde_yaml::from_str(&config_content)?;
        
        // Model
        let model = config["agents"]["defaults"]["model"]
            .as_str()
            .unwrap_or("unknown");
        println!("Model: {}", model);
        
        // Get selected provider
        let selected_provider = config["agents"]["defaults"]["provider"]
            .as_str()
            .unwrap_or("openai");
        
        // API key status for selected provider only
        let api_key = config["providers"][selected_provider]["api_key"].as_str();
        let status = if api_key.is_some() { "" } else { "not set" };
        let provider_name = match selected_provider {
            "openrouter" => "OpenRouter API",
            "anthropic" => "Anthropic API",
            "openai" => "OpenAI API",
            "gemini" => "Gemini API",
            "zhipu" => "Zhipu API",
            "groq" => "Groq API",
            _ => selected_provider,
        };
        println!("Provider: {} ({})", provider_name, status);
    }
    
    println!("------");
    
    Ok(())
}

async fn handle_cron(action: CronAction) -> Result<(), Box<dyn std::error::Error>> {
    match action {
        CronAction::List => {
            info!("Listing cron jobs");
            println!("Cron jobs (not yet implemented)");
            // TODO: List scheduled jobs
        }
        CronAction::Add {
            expression,
            description,
        } => {
            info!("Adding cron job: {} - {}", expression, description);
            println!("Added cron job: {} - {}", expression, description);
            // TODO: Add scheduled job
        }
    }
    Ok(())
}

async fn handle_onboard(force: bool) -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting onboard process");
    
    let home = std::env::var("HOME")?;
    let workspace_dir = format!("{}/.takobull/workspace", home);
    let config_path = format!("{}/.takobull/config.yaml", home);
    
    // Create workspace directory
    std::fs::create_dir_all(&workspace_dir)?;
    println!("✓ Created workspace directory: {}", workspace_dir);
    
    // Create subdirectories
    let subdirs = vec!["sessions", "memory", "state", "cron", "skills"];
    for subdir in subdirs {
        std::fs::create_dir_all(format!("{}/{}", workspace_dir, subdir))?;
    }
    println!("✓ Created workspace subdirectories");
    
    // Create default config (overwrite if force flag is set)
    if !std::path::Path::new(&config_path).exists() || force {
        let default_config = r#"# TakoBull Configuration
# Ultra-lightweight personal AI Assistant for embedded systems

agents:
  defaults:
    workspace: "~/.takobull/workspace"
    restrict_to_workspace: true
    provider: "openrouter"
    model: "meta-llama/llama-2-70b-chat"
    max_tokens: 8192
    temperature: 0.7
    max_tool_iterations: 20

channels:
  telegram:
    enabled: false
    token: ""
    allow_from: []
  
  discord:
    enabled: false
    token: ""
    allow_from: []

providers:
  openrouter:
    api_key: ""
    api_base: "https://openrouter.ai/api/v1"
  
  anthropic:
    api_key: ""
    api_base: "https://api.anthropic.com"
  
  openai:
    api_key: ""
    api_base: "https://api.openai.com/v1"
  
  gemini:
    api_key: ""
    api_base: "https://generativelanguage.googleapis.com/v1beta/openai/"
  
  zhipu:
    api_key: ""
    api_base: "https://open.bigmodel.cn/api/paas/v4"
  
  groq:
    api_key: ""
    api_base: "https://api.groq.com/openai/v1"
  
  deepseek:
    api_key: ""
    api_base: "https://api.deepseek.com"
  
  vllm:
    api_key: ""
    api_base: ""

tools:
  web:
    brave:
      enabled: true
      api_key: ""
      max_results: 5
    
    duckduckgo:
      enabled: true
      max_results: 5

heartbeat:
  enabled: true
  interval: 30

logging:
  level: "info"
  format: "json"
"#;
        std::fs::write(&config_path, default_config)?;
        println!("✓ Created default config: {}", config_path);
    } else {
        println!("✓ Config already exists: {}", config_path);
    }
    
    // Create workspace files
    let workspace_files = vec![
        ("AGENTS.md", "# Agent Configuration\n\nConfigure agent behavior here.\n"),
        ("IDENTITY.md", "# Agent Identity\n\nDefine your agent's identity and personality.\n"),
        ("SOUL.md", "# Agent Soul\n\nDefine your agent's core values and principles.\n"),
        ("TOOLS.md", "# Available Tools\n\nList of tools available to the agent.\n"),
        ("USER.md", "# User Preferences\n\nDefine user preferences and settings.\n"),
        ("HEARTBEAT.md", "# Periodic Tasks\n\nDefine tasks to run periodically.\n"),
        ("MEMORY.md", "# Long-term Memory\n\nAgent's long-term memory storage.\n"),
    ];
    
    for (filename, content) in workspace_files {
        let filepath = format!("{}/{}", workspace_dir, filename);
        if !std::path::Path::new(&filepath).exists() {
            std::fs::write(&filepath, content)?;
        }
    }
    println!("✓ Created workspace files");
    
    println!("\n✅ Onboarding complete!");
    println!("\nNext steps:");
    println!("1. Edit config: {}", config_path);
    println!("2. Set your API keys (OPENROUTER_API_KEY, etc.)");
    println!("3. Run: takobull agent -m \"Hello\"");
    
    info!("Onboarding completed successfully");
    Ok(())
}