rsclaw 2026.4.5

High-performance AI gateway with native OpenClaw A2A orchestration
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
use anyhow::Result;

use super::style::{banner, dim, green, kv, red, yellow};
use crate::{cli::GatewayCommand, config, gateway, sys::detect_memory_tier};

const VERSION: &str = env!("RSCLAW_BUILD_VERSION");

/// Spawn `rsclaw gateway run` as a detached background process, propagating
/// instance-isolation env vars set by `--dev` / `--profile`.
fn spawn_gateway_bg() -> Result<std::process::Child> {
    spawn_gateway_bg_pub()
}

/// Public version for use by configure restart.
pub fn spawn_gateway_bg_pub() -> Result<std::process::Child> {
    let exe = std::env::current_exe()?;
    let mut cmd = std::process::Command::new(&exe);
    if let Ok(v) = std::env::var("RSCLAW_BASE_DIR") {
        cmd.env("RSCLAW_BASE_DIR", v);
    }
    if let Ok(v) = std::env::var("RSCLAW_PORT") {
        cmd.env("RSCLAW_PORT", v);
    }

    // Redirect stdout/stderr to log file for background mode
    let log_path = crate::config::loader::log_file();
    if let Some(parent) = log_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let null_path = if cfg!(windows) { "NUL" } else { "/dev/null" };
    let log_file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&log_path)
        .unwrap_or_else(|_| std::fs::File::open(null_path).expect("failed to open null device"));
    let log_file2 = log_file
        .try_clone()
        .unwrap_or_else(|_| std::fs::File::open(null_path).expect("failed to open null device"));

    // Set default log level for background mode (user can override via RUST_LOG
    // env)
    if std::env::var("RUST_LOG").is_err() {
        cmd.env("RUST_LOG", "rsclaw=info");
    }
    cmd.arg("gateway")
        .arg("run")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::from(log_file))
        .stderr(std::process::Stdio::from(log_file2));

    // On Windows, detach the child process so it survives the parent exit.
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
        const DETACHED_PROCESS: u32 = 0x00000008;
        cmd.creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS);
    }

    Ok(cmd.spawn()?)
}

pub async fn cmd_gateway(sub: GatewayCommand) -> Result<()> {
    match sub {
        GatewayCommand::Run(_args) => {
            // Check if setup is needed before loading config.
            if crate::migrate::check_needs_setup() {
                return Ok(());
            }

            let config = std::sync::Arc::new(config::load_quiet()?);
            let port = config.gateway.port;
            let bind = match config.gateway.bind {
                crate::config::schema::BindMode::Auto
                | crate::config::schema::BindMode::Lan
                | crate::config::schema::BindMode::All => "0.0.0.0",
                crate::config::schema::BindMode::Loopback => "loopback",
                crate::config::schema::BindMode::Custom => "custom",
                crate::config::schema::BindMode::Tailnet => "tailnet",
            };
            let pid = std::process::id();
            banner(&format!("rsclaw gateway v{VERSION}"));
            kv("Port:", &format!("{port} | Bind: {bind}"));
            kv("PID:", &format!("{pid}"));
            println!();

            let tier = detect_memory_tier();
            gateway::startup::start_gateway(config, tier).await
        }
        GatewayCommand::Start => {
            // Check if setup is needed.
            if crate::migrate::check_needs_setup() {
                return Ok(());
            }

            banner(&format!("rsclaw gateway v{VERSION}"));
            // Check if already running
            if let Some(pid) = gateway_read_pid()
                && process_alive(pid)
            {
                println!("  {} Gateway already running (pid {pid})", yellow("[!]"));
                return Ok(());
            }
            let child = spawn_gateway_bg()?;
            let pid = child.id();
            let port = detect_port();
            println!("  {} Gateway started", green("[ok]"));
            kv("PID:", &format!("{pid}"));
            kv("URL:", &format!("http://127.0.0.1:{port}"));
            println!();
            Ok(())
        }
        GatewayCommand::Stop => {
            let pid_display = gateway_read_pid()
                .map(|p| format!(" (pid {p})"))
                .unwrap_or_default();
            match gateway_signal_stop() {
                Ok(()) => println!("  {} Gateway stopped{pid_display}", green("[ok]")),
                Err(e) => println!("  {} {e}", yellow("[!]")),
            }
            Ok(())
        }
        GatewayCommand::Restart => {
            banner(&format!("rsclaw gateway v{VERSION}"));
            match gateway_signal_stop() {
                Ok(()) => {
                    println!("  {} Stopping...", dim("[..]"));
                    // gateway_signal_stop already waits for exit; small extra
                    // delay to let the port be released by the OS.
                    std::thread::sleep(std::time::Duration::from_millis(200));
                }
                Err(_) => {
                    println!("  {} No running gateway found, starting fresh", dim("[..]"));
                }
            }
            let child = spawn_gateway_bg()?;
            let pid = child.id();
            let port = detect_port();
            println!("  {} Gateway restarted", green("[ok]"));
            kv("PID:", &format!("{pid}"));
            kv("URL:", &format!("http://127.0.0.1:{port}"));
            println!();
            Ok(())
        }
        GatewayCommand::Status => gateway_print_status(),
        GatewayCommand::Health => {
            let config = config::load_quiet().ok();
            let port = config.map(|c| c.gateway.port).unwrap_or(18888);
            let url = format!("http://127.0.0.1:{port}/api/v1/health");
            match reqwest::Client::new().get(&url).send().await {
                Ok(resp) if resp.status().is_success() => {
                    println!("  [ok] Healthy -- {url}");
                }
                Ok(resp) => {
                    println!("  [!!] Unhealthy -- {} {url}", resp.status());
                }
                Err(_) => {
                    println!("  [!!] Unreachable -- {url}");
                }
            }
            Ok(())
        }
        GatewayCommand::Install => cmd_gateway_install().await,
        GatewayCommand::Uninstall => cmd_gateway_uninstall().await,
        GatewayCommand::Probe => {
            let config = std::sync::Arc::new(config::load_quiet()?);
            let port = config.gateway.port;
            let url = format!("http://127.0.0.1:{port}/api/v1/health");
            let resp = reqwest::Client::new()
                .get(&url)
                .send()
                .await
                .map_err(|e| anyhow::anyhow!("gateway unreachable at {url}: {e}"))?;
            println!("  {} -- {url}", resp.status());
            Ok(())
        }
        GatewayCommand::Discover => {
            println!("Scanning local network for rsclaw/openclaw gateways...");
            println!("(discovery uses mDNS/broadcast -- not yet implemented)");
            println!("Try: http://127.0.0.1:{}", detect_port());
            Ok(())
        }
        GatewayCommand::UsageCost => {
            let config = config::load_quiet().ok();
            let port = config.map(|c| c.gateway.port).unwrap_or(18888);
            let url = format!("http://127.0.0.1:{port}/api/v1/usage");
            match reqwest::Client::new().get(&url).send().await {
                Ok(resp) if resp.status().is_success() => {
                    let body: serde_json::Value = resp.json().await.unwrap_or_default();
                    println!("{}", serde_json::to_string_pretty(&body)?);
                }
                Ok(resp) => {
                    println!("usage endpoint returned: {}", resp.status());
                }
                Err(_) => {
                    println!("gateway not reachable at port {port}");
                }
            }
            Ok(())
        }
        GatewayCommand::Call { method, args } => {
            let config = std::sync::Arc::new(config::load_quiet()?);
            let port = config.gateway.port;
            let url = format!("http://127.0.0.1:{port}/api/v1/{method}");
            let body: serde_json::Value = if args.is_empty() {
                serde_json::Value::Object(Default::default())
            } else {
                serde_json::from_str(&args.join(" "))
                    .unwrap_or(serde_json::Value::String(args.join(" ")))
            };
            let resp = reqwest::Client::new()
                .post(&url)
                .json(&body)
                .send()
                .await
                .map_err(|e| anyhow::anyhow!("gateway unreachable at {url}: {e}"))?;
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            println!("{status} {text}");
            Ok(())
        }
    }
}

// ---------------------------------------------------------------------------
// PID helpers
// ---------------------------------------------------------------------------

pub fn gateway_pid_file() -> std::path::PathBuf {
    config::loader::pid_file()
}

fn gateway_read_pid() -> Option<u32> {
    std::fs::read_to_string(gateway_pid_file())
        .ok()?
        .trim()
        .parse::<u32>()
        .ok()
}

fn process_alive(pid: u32) -> bool {
    crate::sys::process_alive(pid)
}

fn detect_port() -> u16 {
    config::load_quiet()
        .ok()
        .map(|c| c.gateway.port)
        .unwrap_or(18888)
}

pub fn gateway_signal_stop() -> Result<()> {
    let pid = gateway_read_pid()
        .ok_or_else(|| anyhow::anyhow!("gateway is not running (no PID file)"))?;
    if !process_alive(pid) {
        let _ = std::fs::remove_file(gateway_pid_file());
        anyhow::bail!("gateway process {pid} is not running");
    }
    crate::sys::process_terminate(pid)?;
    // Wait for process to exit (up to 5 seconds).
    for _ in 0..50 {
        if !process_alive(pid) {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    // Clean up PID file.
    let _ = std::fs::remove_file(gateway_pid_file());
    Ok(())
}

pub fn gateway_print_status() -> Result<()> {
    let port = detect_port();
    let base = config::loader::base_dir();
    banner(&format!("rsclaw gateway v{VERSION}"));

    kv("Base dir:", &format!("{}", base.display()));
    kv("Port:", &format!("{port}"));

    match gateway_read_pid() {
        Some(pid) if process_alive(pid) => {
            kv("Status:", &green(&format!("running (pid {pid})")));
            kv("URL:", &format!("http://127.0.0.1:{port}"));

            // Try to get version from health endpoint
            let url = format!("http://127.0.0.1:{port}/api/v1/status");
            if let Ok(resp) = reqwest::blocking::get(&url)
                && let Ok(body) = resp.json::<serde_json::Value>()
            {
                if let Some(v) = body.get("version").and_then(|v| v.as_str()) {
                    kv("Version:", v);
                }
                if let Some(a) = body.get("agents").and_then(|v| v.as_u64()) {
                    kv("Agents:", &format!("{a}"));
                }
            }
        }
        Some(pid) => {
            let _ = std::fs::remove_file(gateway_pid_file());
            kv("Status:", &red(&format!("stopped (stale pid {pid})")));
        }
        None => {
            kv("Status:", &red("stopped"));
        }
    }
    println!();
    Ok(())
}

// ---------------------------------------------------------------------------
// gateway install / uninstall
// ---------------------------------------------------------------------------

#[cfg(target_os = "macos")]
async fn cmd_gateway_install() -> Result<()> {
    let home = dirs_next::home_dir().ok_or_else(|| anyhow::anyhow!("cannot determine home dir"))?;
    let binary = std::env::current_exe()?;
    let plist_dir = home.join("Library/LaunchAgents");
    std::fs::create_dir_all(&plist_dir)?;
    let plist_path = plist_dir.join("ai.rsclaw.gateway.plist");

    let plist = format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>ai.rsclaw.gateway</string>
  <key>ProgramArguments</key>
  <array>
    <string>{binary}</string>
    <string>gateway</string>
    <string>run</string>
  </array>
  <key>KeepAlive</key>
  <true/>
  <key>RunAtLoad</key>
  <true/>
  <key>StandardOutPath</key>
  <string>{home}/.rsclaw/var/logs/gateway.log</string>
  <key>StandardErrorPath</key>
  <string>{home}/.rsclaw/var/logs/gateway.log</string>
</dict>
</plist>
"#,
        binary = binary.display(),
        home = home.display(),
    );

    std::fs::write(&plist_path, &plist)?;
    println!("  [+] {}", plist_path.display());

    let status = std::process::Command::new("launchctl")
        .args(["load", "-w"])
        .arg(&plist_path)
        .status()?;

    if status.success() {
        println!("  [ok] Service installed -- starts on login, restarts on crash");
    } else {
        eprintln!("  [!!] launchctl load failed (exit {})", status);
    }
    Ok(())
}

#[cfg(target_os = "macos")]
async fn cmd_gateway_uninstall() -> Result<()> {
    let home = dirs_next::home_dir().ok_or_else(|| anyhow::anyhow!("cannot determine home dir"))?;
    let plist_path = home.join("Library/LaunchAgents/ai.rsclaw.gateway.plist");

    let status = std::process::Command::new("launchctl")
        .args(["unload", "-w"])
        .arg(&plist_path)
        .status()?;

    if !status.success() {
        eprintln!("  [!] launchctl unload failed (may not have been loaded)");
    }

    if plist_path.exists() {
        std::fs::remove_file(&plist_path)?;
    }
    println!("  [ok] Service uninstalled");
    Ok(())
}

#[cfg(target_os = "linux")]
async fn cmd_gateway_install() -> Result<()> {
    let binary = std::env::current_exe()?;
    let user = std::env::var("USER").unwrap_or_else(|_| "root".to_owned());
    let home = dirs_next::home_dir().ok_or_else(|| anyhow::anyhow!("cannot determine home dir"))?;

    let unit = format!(
        "[Unit]\n\
         Description=rsclaw AI gateway\n\
         After=network.target\n\
         \n\
         [Service]\n\
         Type=simple\n\
         User={user}\n\
         ExecStart={binary} gateway run\n\
         Restart=on-failure\n\
         RestartSec=5\n\
         StandardOutput=append:{home}/.rsclaw/var/logs/gateway.log\n\
         StandardError=append:{home}/.rsclaw/var/logs/gateway.log\n\
         \n\
         [Install]\n\
         WantedBy=default.target\n",
        binary = binary.display(),
        home = home.display(),
    );

    let unit_dir = home.join(".config/systemd/user");
    std::fs::create_dir_all(&unit_dir)?;
    let unit_path = unit_dir.join("rsclaw-gateway.service");
    std::fs::write(&unit_path, &unit)?;
    println!("  [+] {}", unit_path.display());

    for cmd in [
        vec!["systemctl", "--user", "daemon-reload"],
        vec!["systemctl", "--user", "enable", "--now", "rsclaw-gateway"],
    ] {
        let status = std::process::Command::new(cmd[0])
            .args(&cmd[1..])
            .status()?;
        if !status.success() {
            eprintln!("  [!!] systemctl {} failed", cmd[1..].join(" "));
        }
    }
    println!("  [ok] Service installed and started");
    Ok(())
}

#[cfg(target_os = "linux")]
async fn cmd_gateway_uninstall() -> Result<()> {
    let home = dirs_next::home_dir().ok_or_else(|| anyhow::anyhow!("cannot determine home dir"))?;
    let unit_path = home.join(".config/systemd/user/rsclaw-gateway.service");

    for cmd in [
        vec!["systemctl", "--user", "disable", "--now", "rsclaw-gateway"],
        vec!["systemctl", "--user", "daemon-reload"],
    ] {
        let _ = std::process::Command::new(cmd[0]).args(&cmd[1..]).status();
    }

    if unit_path.exists() {
        std::fs::remove_file(&unit_path)?;
    }
    println!("  [ok] Service uninstalled");
    Ok(())
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
async fn cmd_gateway_install() -> Result<()> {
    println!("  [!] Gateway install is only supported on macOS and Linux");
    Ok(())
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
async fn cmd_gateway_uninstall() -> Result<()> {
    println!("  [!] Gateway uninstall is only supported on macOS and Linux");
    Ok(())
}