rsclaw 0.0.1-alpha.1

rsclaw: High-performance AI agent (BETA). Optimized for M4 Max and 2GB VPS. 100% compatible with openclaw
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
#![allow(dead_code)]

mod config;
mod provider;
mod skill;
mod plugin;
mod agent;
mod channel;
mod gateway;
mod server;
mod store;
mod cron;
mod hooks;
mod utils;

use anyhow::Result;
use clap::{Parser, Subcommand};
use tracing_subscriber::{fmt, EnvFilter};

#[derive(Parser)]
#[command(name = "rsclaw", version, about = "Rust multi-agent collaboration framework")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Start the gateway server
    Run {
        /// Custom config file path
        #[arg(long)]
        config: Option<String>,
    },
    /// Validate and fix configuration
    Doctor {
        /// Attempt to fix configuration issues
        #[arg(long, default_value_t = false)]
        fix: bool,
    },
    /// Initialize rsclaw configuration
    Init {
        /// Force overwrite existing configuration
        #[arg(long, default_value_t = false)]
        force: bool,
    },
    /// Show current configuration
    Config,
    /// Agent management commands
    Agent {
        #[command(subcommand)]
        action: AgentAction,
    },
    /// Skill management commands
    Skill {
        #[command(subcommand)]
        action: SkillAction,
    },
    /// Plugin management commands
    Plugin {
        #[command(subcommand)]
        action: PluginAction,
    },
    /// Cron job management commands
    Cron {
        #[command(subcommand)]
        action: CronAction,
    },
    /// Hook event management commands
    Hook {
        #[command(subcommand)]
        action: HookAction,
    },
}

#[derive(Subcommand)]
enum AgentAction {
    /// List running agents
    List,
    /// Create a new agent
    Create {
        /// Agent name
        name: String,
    },
    /// Chat with an agent
    Chat {
        /// Agent name
        name: String,
        /// Message to send
        message: String,
    },
    /// Destroy an agent
    Destroy {
        /// Agent name
        name: String,
    },
}

#[derive(Subcommand)]
enum SkillAction {
    /// List installed skills
    List,
    /// Pull a skill from ClawHub
    Pull {
        /// Skill name to pull
        name: String,
    },
    /// Run a skill
    Run {
        /// Skill name to run
        name: String,
        /// Arguments to pass to the skill
        args: Vec<String>,
    },
}

#[derive(Subcommand)]
enum PluginAction {
    /// List installed plugins
    List,
    /// Load a plugin
    Load {
        /// Plugin name to load
        name: String,
    },
    /// Run a plugin method
    Run {
        /// Plugin name
        plugin: String,
        /// Method to call
        method: String,
        /// JSON parameters
        params: Option<String>,
    },
}

#[derive(Subcommand)]
enum CronAction {
    /// List all cron jobs
    List,
    /// Add a new cron job
    Add {
        /// Cron expression (e.g., "*/5 * * * *")
        expression: String,
        /// Target agent or skill name
        target: String,
        /// Job description
        description: String,
    },
    /// Run a cron job immediately
    Run {
        /// Job ID
        id: String,
    },
    /// Delete a cron job
    Delete {
        /// Job ID
        id: String,
    },
}

#[derive(Subcommand)]
enum HookAction {
    /// List all registered hooks
    List,
    /// Trigger an event manually
    Trigger {
        /// Event name (e.g., system_start, gateway_start)
        event: String,
    },
}

static AGENT_MANAGER: std::sync::OnceLock<agent::AgentManager> = std::sync::OnceLock::new();

fn get_manager() -> &'static agent::AgentManager {
    AGENT_MANAGER.get_or_init(|| {
        let config = config::loader::ConfigLoader::load().unwrap_or_default();
        agent::AgentManager::new(config.memory.max_concurrent_agents)
    })
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
    fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .with_target(false)
        .init();

    let cli = Cli::parse();

    match cli.command {
        Commands::Run { config } => cmd_run(config).await,
        Commands::Doctor { fix } => cmd_doctor(fix).await,
        Commands::Init { force } => cmd_init(force).await,
        Commands::Config => cmd_config().await,
        Commands::Agent { action } => match action {
            AgentAction::List => cmd_agent_list().await,
            AgentAction::Create { name } => cmd_agent_create(name).await,
            AgentAction::Chat { name, message } => cmd_agent_chat(name, message).await,
            AgentAction::Destroy { name } => cmd_agent_destroy(name).await,
        },
        Commands::Skill { action } => match action {
            SkillAction::List => cmd_skill_list().await,
            SkillAction::Pull { name } => cmd_skill_pull(name).await,
            SkillAction::Run { name, args } => cmd_skill_run(name, args).await,
        },
        Commands::Plugin { action } => match action {
            PluginAction::List => cmd_plugin_list().await,
            PluginAction::Load { name } => cmd_plugin_load(name).await,
            PluginAction::Run { plugin, method, params } => cmd_plugin_run(plugin, method, params).await,
        },
        Commands::Cron { action } => match action {
            CronAction::List => cmd_cron_list().await,
            CronAction::Add { expression, target, description } => cmd_cron_add(expression, target, description).await,
            CronAction::Run { id } => cmd_cron_run(id).await,
            CronAction::Delete { id } => cmd_cron_delete(id).await,
        },
        Commands::Hook { action } => match action {
            HookAction::List => cmd_hook_list().await,
            HookAction::Trigger { event } => cmd_hook_trigger(event).await,
        },
    }
}

async fn cmd_run(config_path: Option<String>) -> Result<()> {
    use config::loader::ConfigLoader;
    use gateway::Gateway;
    use server::Server;

    let config = if let Some(path) = config_path {
        let path = std::path::Path::new(&path);
        if path.ends_with(".toml") {
            ConfigLoader::load_toml(path)?
        } else {
            ConfigLoader::load_json5(path)?
        }
    } else {
        ConfigLoader::load()?
    };

    let host = config.gateway.host.to_string();
    let port = config.gateway.port;
    let max_concurrent = config.memory.max_concurrent_agents;

    let gateway = Gateway::new(max_concurrent);
    let server = Server::new(gateway, &host, port);

    server.start().await
}

async fn cmd_doctor(fix: bool) -> Result<()> {
    use config::loader::ConfigLoader;
    use config::validator::ConfigValidator;

    let config = ConfigLoader::load()?;
    let issues = ConfigValidator::validate(&config)?;

    if issues.is_empty() {
        println!("Configuration is valid.");
        return Ok(());
    }

    println!("Found {} configuration issues:", issues.len());
    for (i, issue) in issues.iter().enumerate() {
        println!("  {}. {}", i + 1, issue);
    }

    if fix {
        println!("Configuration issues would be fixed.");
    }

    Ok(())
}

async fn cmd_init(force: bool) -> Result<()> {
    use config::loader::ConfigLoader;

    let config_path = dirs::home_dir()
        .ok_or_else(|| anyhow::anyhow!("Cannot determine home directory"))?
        .join(".rsclaw")
        .join("rsclaw.toml");

    if config_path.exists() && !force {
        anyhow::bail!(
            "Configuration already exists at {:?}. Use --force to overwrite.",
            config_path
        );
    }

    ConfigLoader::init_default_config(&config_path)?;
    println!("Configuration initialized at {:?}", config_path);
    Ok(())
}

async fn cmd_config() -> Result<()> {
    use config::loader::ConfigLoader;

    let config = ConfigLoader::load()?;
    let output = toml::to_string_pretty(&config)?;
    println!("{}", output);
    Ok(())
}

async fn cmd_agent_list() -> Result<()> {
    let manager = get_manager();
    let agents = manager.list().await;

    if agents.is_empty() {
        println!("No running agents.");
        return Ok(());
    }

    println!("Running agents ({}/{}):", manager.current_concurrency(), manager.max_concurrency());
    for agent in agents {
        let state = agent.state().await;
        println!("  - {} [{:?}]", agent.name(), state);
    }

    Ok(())
}

async fn cmd_agent_create(name: String) -> Result<()> {
    use std::sync::Arc;

    let manager = get_manager();

    if manager.is_at_capacity() {
        anyhow::bail!(
            "Cannot create agent: concurrency limit reached ({}/{})",
            manager.current_concurrency(),
            manager.max_concurrency()
        );
    }

    let config = config::loader::ConfigLoader::load()?;
    let agent_config = agent::AgentConfig {
        name: Arc::from(name.as_str()),
        model: Arc::from("gpt-4"),
        system_prompt: Arc::from("You are a helpful assistant."),
        max_tokens: 4096,
        memory_limit_mb: config.memory.max_agent_memory_mb,
    };

    let created_name = manager.create(agent_config).await?;
    println!("Agent '{}' created successfully.", created_name);

    Ok(())
}

async fn cmd_agent_chat(name: String, message: String) -> Result<()> {
    println!("Agent '{}' processing message...", name);
    println!("Note: No LLM provider configured, simulating response.");
    println!("User: {}", message);
    println!("Assistant: This is a simulated response. Configure an LLM provider for real responses.");

    Ok(())
}

async fn cmd_agent_destroy(name: String) -> Result<()> {
    let manager = get_manager();

    if manager.destroy(&name).await? {
        println!("Agent '{}' destroyed, memory released.", name);
    } else {
        println!("Agent '{}' not found.", name);
    }

    Ok(())
}

async fn cmd_skill_list() -> Result<()> {
    use skill::SkillLoader;

    let skills_dir = utils::ensure_skills_dir()?;
    let mut loader = SkillLoader::new(skills_dir);
    let count = loader.load_all()?;

    if count == 0 {
        println!("No skills installed.");
        return Ok(());
    }

    println!("Installed skills ({}):", count);
    for skill in loader.list() {
        if let Some(manifest) = &skill.manifest {
            println!("  - {} (v{}): {}", skill.name, manifest.version, manifest.description);
        } else {
            println!("  - {}", skill.name);
        }
    }

    Ok(())
}

async fn cmd_skill_pull(name: String) -> Result<()> {
    use skill::ClawHubClient;

    let skills_dir = utils::ensure_skills_dir()?;
    let client = ClawHubClient::default();

    println!("Pulling skill '{}' from ClawHub...", name);
    client.install_skill(&name, &skills_dir).await?;
    println!("Skill '{}' installed successfully.", name);

    Ok(())
}

async fn cmd_skill_run(name: String, args: Vec<String>) -> Result<()> {
    use skill::{SkillLoader, ShellRunner};

    let skills_dir = utils::ensure_skills_dir()?;
    let mut loader = SkillLoader::new(skills_dir);
    loader.load_all()?;

    let skill = loader.get(&name)
        .ok_or_else(|| anyhow::anyhow!("Skill '{}' not found", name))?;

    let timeout = skill.manifest
        .as_ref()
        .and_then(|m| m.timeout)
        .unwrap_or(30) as u64;

    let runner = ShellRunner::new(timeout);
    let result = runner.run(&skill.path, &args).await?;

    if result.success {
        print!("{}", result.stdout);
    } else {
        print!("{}", result.stderr);
        anyhow::bail!("Skill execution failed with exit code: {:?}", result.exit_code);
    }

    Ok(())
}

async fn cmd_plugin_list() -> Result<()> {
    let plugins_dir = utils::plugins_dir()?;
    let manager = plugin::PluginManager::new(plugins_dir);

    let plugins = manager.list();
    if plugins.is_empty() {
        println!("No plugins installed.");
        return Ok(());
    }

    println!("Installed plugins ({}):", plugins.len());
    for plugin in plugins {
        println!("  - {} (v{}): {}", plugin.name, plugin.manifest.version, plugin.manifest.description);
    }

    Ok(())
}

async fn cmd_plugin_load(name: String) -> Result<()> {
    let plugins_dir = utils::plugins_dir()?;
    let mut manager = plugin::PluginManager::new(plugins_dir);

    manager.load(&name)?;
    println!("Plugin '{}' loaded successfully.", name);

    let slots = manager.list_slots();
    if !slots.is_empty() {
        println!("Registered slots:");
        for slot in slots {
            println!("  - {} ({})", slot.name, slot.slot_type);
        }
    }

    Ok(())
}

async fn cmd_plugin_run(plugin: String, method: String, params: Option<String>) -> Result<()> {
    let plugins_dir = utils::plugins_dir()?;
    let mut manager = plugin::PluginManager::new(plugins_dir);

    manager.load(&plugin)?;

    let params_value = if let Some(p) = params {
        Some(serde_json::from_str(&p)?)
    } else {
        None
    };

    println!("Running {}.{}...", plugin, method);
    let result = manager.execute(&plugin, &method, params_value).await?;
    println!("{}", serde_json::to_string_pretty(&result)?);

    Ok(())
}

async fn cmd_cron_list() -> Result<()> {
    use std::sync::Arc;
    use cron::CronStore;

    let store = Arc::new(store::default_store()?);
    let cron_store = Arc::new(CronStore::new(store));
    let tasks = cron_store.list_all()?;

    if tasks.is_empty() {
        println!("No cron jobs configured.");
        return Ok(());
    }

    println!("Cron jobs ({}):", tasks.len());
    for task in tasks {
        let status = match task.status {
            cron::TaskStatus::Pending => "pending",
            cron::TaskStatus::Running => "running",
            cron::TaskStatus::Completed => "completed",
            cron::TaskStatus::Failed => "failed",
        };
        println!("  - {} [{}] {}: {} -> {}", task.id, status, task.expression, task.target, task.description);
    }

    Ok(())
}

async fn cmd_cron_add(expression: String, target: String, description: String) -> Result<()> {
    use std::sync::Arc;
    use cron::{CronStore, CronTask, TaskType};

    let store = Arc::new(store::default_store()?);
    let cron_store = Arc::new(CronStore::new(store));

    let task = CronTask::new(
        Arc::from(expression.as_str()),
        TaskType::Agent,
        Arc::from(target.as_str()),
        Arc::from(description.as_str()),
    );

    cron_store.save(&task)?;

    println!("Cron job added with ID: {}", task.id);
    println!("  Expression: {}", expression);
    println!("  Target: {}", target);
    println!("  Description: {}", description);

    Ok(())
}

async fn cmd_cron_run(id: String) -> Result<()> {
    use std::sync::Arc;
    use cron::CronStore;

    let store = Arc::new(store::default_store()?);
    let cron_store = Arc::new(CronStore::new(store));

    let task = cron_store.load(&id)?
        .ok_or_else(|| anyhow::anyhow!("Cron job '{}' not found", id))?;

    println!("Running cron job '{}'...", id);
    println!("Target: {}", task.target);
    println!("Description: {}", task.description);
    println!("Note: Task execution simulation (no LLM provider configured)");

    Ok(())
}

async fn cmd_cron_delete(id: String) -> Result<()> {
    use std::sync::Arc;
    use cron::CronStore;

    let store = Arc::new(store::default_store()?);
    let cron_store = Arc::new(CronStore::new(store));

    if cron_store.delete(&id)? {
        println!("Cron job '{}' deleted.", id);
    } else {
        println!("Cron job '{}' not found.", id);
    }

    Ok(())
}

async fn cmd_hook_list() -> Result<()> {
    use std::sync::Arc;
    use hooks::{HookRegistry, SystemHooks};

    let registry = Arc::new(HookRegistry::new());
    SystemHooks::register(&registry).await?;

    let hooks = registry.list().await;

    if hooks.is_empty() {
        println!("No hooks registered.");
        return Ok(());
    }

    println!("Registered hooks ({}):", hooks.len());
    for hook in hooks {
        let status = if hook.enabled { "enabled" } else { "disabled" };
        println!("  - {} [{}] {} (priority: {})", hook.id, status, hook.name, hook.priority);
        println!("    Event: {}", hook.event);
    }

    Ok(())
}

async fn cmd_hook_trigger(event: String) -> Result<()> {
    use std::sync::Arc;
    use hooks::{HookEvent, HookRegistry, HookEngine, HookTrigger, SystemHooks};

    let store = Arc::new(store::default_store()?);
    let skills_dir = utils::ensure_skills_dir()?;

    let registry = Arc::new(HookRegistry::with_store(store));
    SystemHooks::register(&registry).await?;

    let engine = Arc::new(HookEngine::new(registry, skills_dir));
    let trigger = HookTrigger::new(engine);

    let hook_event = HookEvent::from_str(&event)
        .ok_or_else(|| anyhow::anyhow!("Invalid event: {}", event))?;

    println!("Triggering event '{}'...", event);
    let results = trigger.trigger(hook_event, serde_json::json!({})).await;

    println!("Execution results:");
    for result in results {
        let status = if result.success { "ok" } else { "failed" };
        println!("  - Hook '{}' [{}] in {}ms", result.hook_id, status, result.duration_ms);
        if let Some(error) = &result.error {
            println!("    Error: {}", error);
        }
    }

    Ok(())
}