rsclaw 2026.5.1

AI Agent Engine 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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
use anyhow::{bail, Result};
use std::path::PathBuf;
use std::time::Duration;

use super::style::*;
use crate::cli::ToolsCommand;

// ---------------------------------------------------------------------------
// Mirror URL (Chinese users) / upstream fallback
// ---------------------------------------------------------------------------

const MIRROR_BASE: &str = "https://gitfast.org/tools";

/// Manifest endpoint — returns JSON with versions and download URLs.
const MANIFEST_URL: &str = "https://gitfast.org/tools/manifest.json";

// ---------------------------------------------------------------------------
// Tool definitions
// ---------------------------------------------------------------------------

struct ToolDef {
    name: &'static str,
    display: &'static str,
    detect_cmd: &'static [&'static str],
    local_bin: &'static str, // relative to tools_dir(), e.g. "chrome/chrome"
    /// Optional tools are still listed by `tools status` but excluded from
    /// the missing/required tally (no warn from `rsclaw doctor`).
    optional: bool,
}

const TOOLS: &[ToolDef] = &[
    ToolDef {
        name: "chrome",
        display: "Chrome for Testing (browser automation)",
        detect_cmd: &["google-chrome", "chromium", "chromium-browser", "chrome"],
        local_bin: "chrome",
        optional: false,
    },
    ToolDef {
        name: "ffmpeg",
        display: "ffmpeg (audio/video processing)",
        detect_cmd: &["ffmpeg"],
        local_bin: "ffmpeg",
        optional: false,
    },
    ToolDef {
        name: "node",
        display: "Node.js (plugin runtime)",
        detect_cmd: &["node"],
        local_bin: "node",
        optional: false,
    },
    ToolDef {
        name: "python",
        display: "Python 3 (skill/plugin runtime)",
        detect_cmd: &["python3", "python"],
        local_bin: "python",
        optional: false,
    },
    ToolDef {
        name: "sherpa-onnx",
        display: "sherpa-onnx (STT + TTS engine)",
        detect_cmd: &["sherpa-onnx-offline-tts", "sherpa-onnx-offline", "sherpa-onnx"],
        local_bin: "sherpa-onnx",
        optional: false,
    },
    ToolDef {
        name: "opencode",
        display: "OpenCode (AI coding agent)",
        detect_cmd: &["opencode"],
        local_bin: "opencode",
        optional: false,
    },
    ToolDef {
        name: "claude-code",
        display: "Claude Code (AI coding agent, optional)",
        detect_cmd: &["claude"],
        local_bin: "claude-code",
        optional: true,
    },
];

// ---------------------------------------------------------------------------
// Paths
// ---------------------------------------------------------------------------

fn tools_dir() -> PathBuf {
    crate::config::loader::base_dir().join("tools")
}

// ---------------------------------------------------------------------------
// Detection
// ---------------------------------------------------------------------------

fn is_tool_in_path(def: &ToolDef) -> bool {
    for cmd in def.detect_cmd {
        if which::which(cmd).is_ok() {
            return true;
        }
    }
    false
}

fn is_tool_installed_locally(def: &ToolDef) -> bool {
    let dir = tools_dir().join(def.local_bin);
    dir.exists()
}

fn tool_status(def: &ToolDef) -> &'static str {
    if is_tool_installed_locally(def) {
        "installed"
    } else if is_tool_in_path(def) {
        "system"
    } else {
        "missing"
    }
}

// ---------------------------------------------------------------------------
// Public: tools summary for `rsclaw status`
// ---------------------------------------------------------------------------

/// Returns a one-line tools summary, e.g. "chrome ✓  ffmpeg ✓  node ✓  python ✓  sherpa-onnx ✗"
/// Optional tools that are missing render as "·" so they don't look like a failure.
pub fn tools_summary_line() -> String {
    TOOLS
        .iter()
        .map(|def| {
            let status = tool_status(def);
            let icon = match (status, def.optional) {
                ("missing", true) => "·",
                ("missing", false) => "",
                _ => "",
            };
            format!("{} {}", def.name, icon)
        })
        .collect::<Vec<_>>()
        .join("  ")
}

/// Returns count of (available, required-total) tools — optional tools are
/// excluded from the denominator so a missing optional never trips a warn.
pub fn tools_count() -> (usize, usize) {
    let required = TOOLS.iter().filter(|d| !d.optional);
    let total = required.clone().count();
    let available = required.filter(|d| tool_status(d) != "missing").count();
    (available, total)
}

/// Returns names of missing required tools (optional tools never reported missing).
pub fn tools_missing() -> Vec<&'static str> {
    TOOLS.iter()
        .filter(|d| !d.optional && tool_status(d) == "missing")
        .map(|d| d.name)
        .collect()
}

// ---------------------------------------------------------------------------
// Commands
// ---------------------------------------------------------------------------

pub async fn cmd_tools(sub: ToolsCommand) -> Result<()> {
    match sub {
        ToolsCommand::List => { cmd_list(); Ok(()) }
        ToolsCommand::Status => { cmd_status(); Ok(()) }
        ToolsCommand::Install { name, force } => cmd_install(&name, force).await,
    }
}

fn cmd_list() {
    banner(&format!(
        "rsclaw tools v{}",
        option_env!("RSCLAW_BUILD_VERSION").unwrap_or("dev")
    ));
    println!();

    let dir = tools_dir();
    let mut found = false;

    for def in TOOLS {
        let local_dir = dir.join(def.local_bin);
        if local_dir.exists() {
            println!("  {}  {}", green(""), bold(def.name));
            println!("    {}", dim(&local_dir.display().to_string()));
            found = true;
        }
    }

    if !found {
        warn_msg("no tools installed locally");
        println!();
        println!("  Run: rsclaw tools install <name>");
        println!("  Available: chrome, ffmpeg, node, python, opencode, claude-code, all");
    }
}

fn cmd_status() {
    banner(&format!(
        "rsclaw tools v{}",
        option_env!("RSCLAW_BUILD_VERSION").unwrap_or("dev")
    ));
    println!();

    for def in TOOLS {
        let status = tool_status(def);
        let (icon, label) = match (status, def.optional) {
            ("system", _) => (green(""), green("system PATH")),
            ("installed", _) => (green(""), cyan("~/.rsclaw/tools")),
            ("missing", true) => (dim("·"), dim("not installed (optional)")),
            _ => (red(""), red("not found")),
        };
        println!("  {} {:<14} {}  {}", icon, bold(def.name), label, dim(def.display));
    }

    // Hint only when REQUIRED tools are missing (optional ones never warn).
    let missing: Vec<&str> = tools_missing();
    if !missing.is_empty() {
        println!();
        println!(
            "  Install missing tools: {} or download from {}",
            bold("rsclaw tools install <name>"),
            cyan("https://gitfast.io"),
        );
    }
}

/// Resolve tool name aliases (e.g. "chromium" → "chrome").
/// Find node binary: prefer locally installed, fallback to system PATH.
fn find_node_binary(tools_dir: &std::path::Path) -> Option<String> {
    // Check local tools dir first.
    let local = tools_dir.join("node").join("bin").join("node");
    if local.exists() { return Some(local.to_string_lossy().to_string()); }
    // Windows variant.
    let local_win = tools_dir.join("node").join("node.exe");
    if local_win.exists() { return Some(local_win.to_string_lossy().to_string()); }
    // System PATH.
    which::which("node").ok().map(|p| p.to_string_lossy().to_string())
}

fn resolve_tool_name(name: &str) -> &str {
    match name {
        "chromium" | "chromium-browser" | "google-chrome" => "chrome",
        "python3" => "python",
        "nodejs" | "node.js" => "node",
        "open-code" | "opencode-cli" => "opencode",
        "claude" | "claude-agent" | "claudecode" => "claude-code",
        _ => name,
    }
}

pub async fn cmd_install(name: &str, force: bool) -> Result<()> {
    let name = resolve_tool_name(name);
    let names: Vec<&str> = if name == "all" {
        TOOLS.iter().map(|d| d.name).collect()
    } else {
        // Validate name
        if !TOOLS.iter().any(|d| d.name == name) {
            bail!(
                "Unknown tool: {name}. Available: {}",
                TOOLS
                    .iter()
                    .map(|d| d.name)
                    .collect::<Vec<_>>()
                    .join(", ")
            );
        }
        vec![name]
    };

    // Fetch manifest from mirror
    println!("Fetching tool manifest from {} ...", dim(MANIFEST_URL));
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(30))
        .build()?;

    let manifest: serde_json::Value = match client.get(MANIFEST_URL).send().await {
        Ok(resp) if resp.status().is_success() => resp.json().await?,
        Ok(resp) => bail!("manifest fetch failed: HTTP {}", resp.status()),
        Err(e) => {
            err_msg(&format!("Cannot reach mirror: {e}"));
            println!();
            println!("  Please download manually from: {}", bold("https://gitfast.io"));
            println!("  Then extract to: {}", bold(&tools_dir().display().to_string()));
            return Ok(());
        }
    };

    let dir = tools_dir();
    std::fs::create_dir_all(&dir)?;

    let platform = detect_platform();
    println!("Platform: {}", bold(platform));
    println!();

    for tool_name in &names {
        let def = TOOLS.iter().find(|d| d.name == *tool_name).unwrap();

        // Skip if already available (unless --force)
        if !force && is_tool_in_path(def) {
            println!("  {} {} {}", green(""), bold(def.name), dim("(already in system PATH, skipping)"));
            continue;
        }
        if !force && is_tool_installed_locally(def) {
            println!("  {} {} {}", green(""), bold(def.name), dim("(already installed, skipping)"));
            continue;
        }

        // npm-based tools: install via npm --prefix instead of downloading binary.
        let npm_package = match *tool_name {
            "claude-code" => Some("@anthropic-ai/claude-code"),
            _ => None,
        };
        if let Some(pkg) = npm_package {
            let dest_dir = dir.join(def.local_bin);
            std::fs::create_dir_all(&dest_dir)?;
            println!("  Installing {} via npm ...", bold(def.name));
            let node_bin = find_node_binary(&dir);
            // Windows ships npm as both `npm` (shell wrapper) and `npm.cmd`
            // (Windows batch). The shell wrapper goes through bash and
            // breaks when spawned from a Windows-native subprocess (it
            // emits Unix-style paths like /d/Program Files/...). Use the
            // .cmd form on Windows; other platforms keep the bare name.
            let npm_basename = if cfg!(target_os = "windows") { "npm.cmd" } else { "npm" };
            let npm_bin = node_bin.as_deref().map(|n| {
                let p = std::path::Path::new(n).parent().unwrap_or(std::path::Path::new(""));
                p.join(npm_basename).to_string_lossy().to_string()
            }).unwrap_or_else(|| npm_basename.to_owned());
            let status = std::process::Command::new(&npm_bin)
                .args(["install", "--prefix", &dest_dir.to_string_lossy(), pkg])
                .status();
            match status {
                Ok(s) if s.success() => ok(&format!("{} installed to {}", def.name, dest_dir.display())),
                Ok(s) => err_msg(&format!("{}: npm install exited with {s}", def.name)),
                Err(e) => {
                    err_msg(&format!("{}: npm not found ({e}). Install node first: rsclaw tools install node", def.name));
                }
            }
            continue;
        }

        let download_url = resolve_download_url(&manifest, tool_name, platform);
        let Some(url) = download_url else {
            warn_msg(&format!(
                "{}: no download available for platform {platform}. Download from https://gitfast.io",
                def.name
            ));
            continue;
        };

        println!("  Installing {} ...", bold(def.name));
        println!("    {}", dim(&url));

        let dest_dir = dir.join(def.local_bin);
        std::fs::create_dir_all(&dest_dir)?;

        match download_and_extract(&client, &url, &dest_dir).await {
            Ok(()) => {
                ok(&format!("{} installed to {}", def.name, dest_dir.display()));
            }
            Err(e) => {
                err_msg(&format!("{}: {e}", def.name));
                println!("    Download manually from: {}", bold("https://gitfast.io"));
            }
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Platform detection
// ---------------------------------------------------------------------------

fn detect_platform() -> &'static str {
    let os = std::env::consts::OS;
    let arch = std::env::consts::ARCH;
    match (os, arch) {
        ("linux", "x86_64") => "linux-x64",
        ("linux", "aarch64") => "linux-arm64",
        ("macos", "x86_64") => "mac-x64",
        ("macos", "aarch64") => "mac-arm64",
        ("windows", "x86_64") => "win-x64",
        _ => "unknown",
    }
}

// ---------------------------------------------------------------------------
// Resolve download URL from manifest
// ---------------------------------------------------------------------------

fn resolve_download_url(
    manifest: &serde_json::Value,
    tool: &str,
    platform: &str,
) -> Option<String> {
    // Try manifest.{tool}.downloads.{platform}
    if let Some(url) = manifest
        .get(tool)
        .and_then(|t| t.get("downloads"))
        .and_then(|d| d.get(platform))
        .and_then(|v| v.as_str())
    {
        return Some(url.to_owned());
    }

    // Fallback: construct URL from mirror base + tool conventions
    // manifest keys use underscores (sherpa_onnx), tool names use hyphens (sherpa-onnx)
    let manifest_key = tool.replace('-', "_");
    let section = manifest.get(&manifest_key).or_else(|| manifest.get(tool))?;

    match tool {
        "chrome" => {
            let ver = section.get("version")?.as_str()?;
            let filename = match platform {
                "linux-x64" => "chrome-linux64.zip",
                "mac-x64" => "chrome-mac-x64.zip",
                "mac-arm64" => "chrome-mac-arm64.zip",
                "win-x64" => "chrome-win64.zip",
                _ => return None,
            };
            Some(format!("{MIRROR_BASE}/chrome/{ver}/{filename}"))
        }
        "ffmpeg" => {
            let filename = match platform {
                "linux-x64" => "ffmpeg-linux-x64.tar.xz",
                "linux-arm64" => "ffmpeg-linux-arm64.tar.xz",
                "win-x64" => "ffmpeg-win-x64.zip",
                "mac-x64" | "mac-arm64" => "ffmpeg-mac-x64.zip",
                _ => return None,
            };
            Some(format!("{MIRROR_BASE}/ffmpeg/{filename}"))
        }
        "node" => {
            let ver = section.get("version")?.as_str()?;
            let filename = match platform {
                "linux-x64" => format!("node-linux-x64.tar.xz"),
                "linux-arm64" => format!("node-linux-arm64.tar.xz"),
                "mac-x64" => format!("node-mac-x64.tar.gz"),
                "mac-arm64" => format!("node-mac-arm64.tar.gz"),
                "win-x64" => format!("node-win-x64.zip"),
                _ => return None,
            };
            Some(format!("{MIRROR_BASE}/node/{ver}/{filename}"))
        }
        "python" => {
            let ver = section.get("version")?.as_str()?;
            let filename = match platform {
                "linux-x64" => "python-linux-x64.tar.gz",
                "linux-arm64" => "python-linux-arm64.tar.gz",
                "mac-x64" => "python-mac-x64.tar.gz",
                "mac-arm64" => "python-mac-arm64.tar.gz",
                "win-x64" => "python-win-x64.tar.gz",
                _ => return None,
            };
            Some(format!("{MIRROR_BASE}/python/{ver}/{filename}"))
        }
        "sherpa-onnx" => {
            // Use the `-shared` variants (NOT `-shared-lib`). The `-lib`
            // suffix is library-only (just .dylib/.so) and lacks the
            // sherpa-onnx-offline / sherpa-onnx-offline-tts CLI binaries
            // that TTS / STT actually invoke. The `-shared` archives ship
            // bin/ alongside lib/ — that's the one we want.
            //
            // linux-aarch64 names the CPU build `-shared-cpu` (there are
            // also `-shared-gpu-*` GPU variants we skip). Windows packages
            // the runtime config in the suffix; `-shared-MT-Release` is
            // the standard release build.
            let ver = section.get("version")?.as_str()?;
            let filename = match platform {
                "linux-x64" => format!("sherpa-onnx-v{ver}-linux-x64-shared.tar.bz2"),
                "linux-arm64" => format!("sherpa-onnx-v{ver}-linux-aarch64-shared-cpu.tar.bz2"),
                "mac-x64" => format!("sherpa-onnx-v{ver}-osx-x64-shared.tar.bz2"),
                "mac-arm64" => format!("sherpa-onnx-v{ver}-osx-arm64-shared.tar.bz2"),
                "win-x64" => format!("sherpa-onnx-v{ver}-win-x64-shared-MT-Release.tar.bz2"),
                _ => return None,
            };
            Some(format!("{MIRROR_BASE}/sherpa-onnx/{ver}/{filename}"))
        }
        "opencode" => {
            let ver = section.get("version")?.as_str()?;
            let filename = match platform {
                "linux-x64" => "opencode-linux-x64.tar.gz",
                "linux-arm64" => "opencode-linux-arm64.tar.gz",
                "mac-x64" => "opencode-mac-x64.tar.gz",
                "mac-arm64" => "opencode-mac-arm64.tar.gz",
                _ => return None, // no Windows binary available
            };
            Some(format!("{MIRROR_BASE}/opencode/{ver}/{filename}"))
        }
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Download and extract archive
// ---------------------------------------------------------------------------

/// Download an archive and extract to dest. Public so `cmd/models.rs` can reuse.
pub async fn download_and_extract_public(
    client: &reqwest::Client,
    url: &str,
    dest: &std::path::Path,
) -> Result<()> {
    download_and_extract(client, url, dest).await
}

async fn download_and_extract(
    client: &reqwest::Client,
    url: &str,
    dest: &std::path::Path,
) -> Result<()> {
    let tmp_dir = tempfile::tempdir()?;
    let filename = url.rsplit('/').next().unwrap_or("download");
    let tmp_path = tmp_dir.path().join(filename);
    download_resumable(client, url, &tmp_path, filename).await?;

    if url.ends_with(".zip") {
        extract_zip(&tmp_path, dest)?;
    } else if url.ends_with(".tar.xz") {
        extract_tar_xz(&tmp_path, dest)?;
    } else if url.ends_with(".tar.gz") || url.ends_with(".tgz") {
        extract_tar_gz(&tmp_path, dest)?;
    } else if url.ends_with(".tar.bz2") {
        extract_tar_bz2(&tmp_path, dest)?;
    } else {
        // Unknown format — move the raw file
        std::fs::rename(&tmp_path, dest.join(filename))?;
    }

    Ok(())
}

/// Resumable streaming HTTP download with a TTY progress bar. The file lives
/// at `out_path` across runs — interrupted transfers continue via the HTTP
/// `Range` header on the next attempt.
///
/// Resume safety: a sidecar `<out_path>.meta` stashes the upstream
/// `(content_length, last_modified || date)` of the version we started
/// downloading. On resume we send `If-Range` plus a manual size check so a
/// CDN that quietly swapped the file mid-transfer can't produce a Frankenstein
/// archive. Mismatch → wipe the partial and restart from byte 0.
///
/// `label` shows in the progress bar prefix (e.g. "BGE model").
///
/// Returns the total bytes resident at `out_path` after the call.
pub async fn download_resumable(
    client: &reqwest::Client,
    url: &str,
    out_path: &std::path::Path,
    label: &str,
) -> Result<u64> {
    use indicatif::{ProgressBar, ProgressStyle};
    use tokio::io::AsyncWriteExt;
    use futures::StreamExt;

    if let Some(parent) = out_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let meta_path = out_path.with_extension(format!(
        "{}meta",
        out_path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| format!("{e}."))
            .unwrap_or_default()
    ));

    let mut already = std::fs::metadata(out_path).map(|m| m.len()).unwrap_or(0);
    // Stashed (content_length, version_token) from the previous start. We
    // only attempt a resume when the partial bytes AND the meta both exist;
    // a partial without meta is a leftover from a pre-meta version of this
    // function and gets wiped to be safe.
    let stashed: Option<(u64, String)> = if already > 0 {
        std::fs::read_to_string(&meta_path)
            .ok()
            .and_then(|s| s.split_once('\t').map(|(a, b)| (a.to_owned(), b.to_owned())))
            .and_then(|(len_s, tok)| len_s.parse::<u64>().ok().map(|n| (n, tok)))
    } else {
        None
    };
    if already > 0 && stashed.is_none() {
        let _ = std::fs::remove_file(out_path);
        let _ = std::fs::remove_file(&meta_path);
        already = 0;
    }

    // Issue a single GET with conditional Range + If-Range. If-Range tells the
    // server "only partial-content me if the version still matches"; mismatch
    // makes it return the full body (200) which we handle as a clean restart.
    let mut req = client.get(url).timeout(Duration::from_secs(600));
    if let Some((_stashed_len, ref token)) = stashed {
        req = req
            .header(reqwest::header::RANGE, format!("bytes={already}-"))
            .header(reqwest::header::IF_RANGE, token.as_str());
    }
    let resp = req.send().await?;
    let status = resp.status();

    let resume = match status.as_u16() {
        206 => true,
        200 => false, // server ignored Range or If-Range mismatch — restart
        416 => {
            // Already have the full file (or local is larger than remote).
            // Treat as success at current size and drop the meta sidecar.
            let _ = std::fs::remove_file(&meta_path);
            return Ok(already);
        }
        _ => {
            anyhow::bail!(
                "download {url} failed: HTTP {status} {}",
                status.canonical_reason().unwrap_or("")
            );
        }
    };

    // Capture upstream version token + total size BEFORE consuming the body.
    let total_size = if resume {
        resp.headers()
            .get(reqwest::header::CONTENT_RANGE)
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.rsplit('/').next())
            .and_then(|s| s.parse::<u64>().ok())
            .or_else(|| resp.content_length().map(|n| already + n))
    } else {
        resp.content_length()
    };
    // Prefer Last-Modified over Date for If-Range — Date is the response
    // generation timestamp (changes on every request), Last-Modified is
    // the file mtime (stable). ETag would be ideal but many CDNs don't set
    // it. Date is the last-resort fallback so we still catch obvious
    // size-shifts even when the server is barebones.
    let version_token: Option<String> = resp
        .headers()
        .get(reqwest::header::ETAG)
        .or_else(|| resp.headers().get(reqwest::header::LAST_MODIFIED))
        .or_else(|| resp.headers().get(reqwest::header::DATE))
        .and_then(|v| v.to_str().ok())
        .map(str::to_owned);

    // Restart conditions, all of which mean the partial we have on disk is
    // unsafe to append to:
    //   1. server's total differs from the size we stashed last time (file
    //      changed upstream)
    //   2. local partial is somehow larger than the upstream total (truncate
    //      / dd / FS quota glitch extended it past the real size)
    let restart_due_to_size_mismatch = resume
        && match (stashed.as_ref().map(|(n, _)| *n), total_size) {
            (Some(stash_total), Some(now_total)) => stash_total != now_total,
            _ => false,
        };
    let restart_due_to_local_overshoot = resume
        && match total_size {
            Some(now_total) => already > now_total,
            None => false,
        };
    let resume = resume && !restart_due_to_size_mismatch && !restart_due_to_local_overshoot;
    if restart_due_to_size_mismatch {
        tracing::warn!(
            url,
            "download_resumable: server total size changed since previous start; restarting from byte 0"
        );
    }
    if restart_due_to_local_overshoot {
        tracing::warn!(
            url,
            already,
            ?total_size,
            "download_resumable: local partial larger than upstream total; restarting from byte 0"
        );
    }

    // Hide the progress bar in non-TTY contexts (daemon, CI, log file
    // redirect) — otherwise indicatif's `\r`-painted updates pollute logs
    // and look like garbled output. Mirrors the QR popup TTY check from
    // commit 839120a.
    let draw_target = if std::io::IsTerminal::is_terminal(&std::io::stderr()) {
        indicatif::ProgressDrawTarget::stderr()
    } else {
        indicatif::ProgressDrawTarget::hidden()
    };
    let bar = if let Some(total) = total_size {
        let bar = ProgressBar::with_draw_target(Some(total), draw_target);
        bar.set_style(
            ProgressStyle::with_template(
                "    {prefix:>12} [{bar:30.cyan/blue}] {bytes:>10}/{total_bytes:>10} {bytes_per_sec:>10} ETA {eta:>5}",
            )
            .unwrap_or_else(|_| ProgressStyle::default_bar())
            .progress_chars("=> "),
        );
        bar.set_prefix(label.to_owned());
        if resume {
            bar.set_position(already);
        }
        bar
    } else {
        let bar = ProgressBar::with_draw_target(None, draw_target);
        bar.set_prefix(label.to_owned());
        bar
    };

    // (Re)create or append. Persist the version token + total length BEFORE
    // any bytes hit disk so a kill-9 mid-transfer leaves a usable resume
    // anchor.
    let mut file = if resume {
        tokio::fs::OpenOptions::new()
            .append(true)
            .open(out_path)
            .await?
    } else {
        // Restarting fresh — drop any stale partial and meta.
        let _ = std::fs::remove_file(out_path);
        let _ = std::fs::remove_file(&meta_path);
        tokio::fs::File::create(out_path).await?
    };
    if let (Some(total), Some(token)) = (total_size, version_token.as_ref()) {
        let _ = std::fs::write(&meta_path, format!("{total}\t{token}"));
    }

    let mut written = if resume { already } else { 0 };
    let mut stream = resp.bytes_stream();
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        file.write_all(&chunk).await?;
        written += chunk.len() as u64;
        bar.set_position(written);
    }
    file.flush().await?;
    bar.finish_and_clear();

    // Successful download — meta sidecar served its purpose, drop it.
    let _ = std::fs::remove_file(&meta_path);

    Ok(written)
}

/// Extract a zip archive to `dest`, stripping the top-level directory.
/// Public so the gateway can extract a pre-downloaded archive without
/// re-downloading.
pub fn extract_zip_public(
    archive_path: &std::path::Path,
    dest: &std::path::Path,
) -> Result<()> {
    extract_zip(archive_path, dest)
}

fn extract_zip(archive_path: &std::path::Path, dest: &std::path::Path) -> Result<()> {
    let file = std::fs::File::open(archive_path)?;
    let mut archive = zip::ZipArchive::new(file)?;

    for i in 0..archive.len() {
        let mut file = archive.by_index(i)?;
        let Some(name) = file.enclosed_name().map(|n| n.to_owned()) else {
            continue;
        };

        // Strip the top-level directory (e.g. "chrome-linux64/chrome" → "chrome")
        let components: Vec<_> = name.components().collect();
        let rel_path = if components.len() > 1 {
            components[1..].iter().collect::<PathBuf>()
        } else {
            name.clone()
        };

        let out_path = dest.join(&rel_path);

        if file.is_dir() {
            std::fs::create_dir_all(&out_path)?;
        } else {
            if let Some(parent) = out_path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            // Stream extract: copy file-by-file instead of reading all into memory
            let mut out_file = std::fs::File::create(&out_path)?;
            std::io::copy(&mut file, &mut out_file)?;

            // Preserve executable permission on Unix
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if let Some(mode) = file.unix_mode() {
                    std::fs::set_permissions(&out_path, std::fs::Permissions::from_mode(mode))?;
                }
            }
        }
    }
    Ok(())
}

fn extract_tar_xz(archive_path: &std::path::Path, dest: &std::path::Path) -> Result<()> {
    let file = std::fs::File::open(archive_path)?;
    let buf = std::io::BufReader::new(file);
    let xz_reader = xz2::read::XzDecoder::new(buf);
    extract_tar(xz_reader, dest)
}

fn extract_tar_gz(archive_path: &std::path::Path, dest: &std::path::Path) -> Result<()> {
    let file = std::fs::File::open(archive_path)?;
    let buf = std::io::BufReader::new(file);
    let gz_reader = flate2::read::GzDecoder::new(buf);
    extract_tar(gz_reader, dest)
}

fn extract_tar_bz2(archive_path: &std::path::Path, dest: &std::path::Path) -> Result<()> {
    let file = std::fs::File::open(archive_path)?;
    let buf = std::io::BufReader::new(file);
    let bz2_reader = bzip2::read::BzDecoder::new(buf);
    extract_tar(bz2_reader, dest)
}

fn extract_tar<R: std::io::Read>(reader: R, dest: &std::path::Path) -> Result<()> {
    let mut archive = tar::Archive::new(reader);

    for entry in archive.entries()? {
        let mut entry = entry?;
        let path = entry.path()?.to_owned();

        // Strip top-level directory
        let components: Vec<_> = path.components().collect();
        let rel_path = if components.len() > 1 {
            components[1..].iter().collect::<PathBuf>()
        } else {
            path.to_path_buf()
        };

        if rel_path.as_os_str().is_empty() {
            continue;
        }

        let out_path = dest.join(&rel_path);

        if entry.header().entry_type().is_dir() {
            std::fs::create_dir_all(&out_path)?;
        } else {
            if let Some(parent) = out_path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            entry.unpack(&out_path)?;
        }
    }
    Ok(())
}