granite-cli 0.2.0

CLI for discovering, configuring, and launching AI workflows powered by IBM Granite models.
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
// Standard
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

// Third Party
use alog::{MessageLevel, alog_channel, use_channel};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};

// Local
use crate::capabilities::{BindingType, ToolName};
use crate::define_factory;
use crate::registry::ConfigConstructable;
use crate::utils::ui::Ui;

use_channel!("LNCHR");

/*-- public --*/

/// Core trait for launcher implementations.
/// All launchers must implement this trait along with ConfigConstructable.
#[async_trait]
pub trait Launcher: crate::registry::Named + Send + Sync {
    fn name(&self) -> &str;

    /// The binary/command this instance will exec.
    /// Returns the full command string — either a bare binary name for PATH
    /// lookup (e.g. `"claude"`) or an absolute path set by the user in config.
    fn command(&self) -> &str;

    /// Bind a capability to this launcher instance.
    ///
    /// The implementation should validate that the capability's `binding_types()`
    /// are supported by this launcher type (per `metadata().supported_capabilities`),
    /// construct the appropriate `BindingRequest`, call `bind()`, and store the
    /// resolved `Binding` for use in `env_overlay` / `launch`.
    async fn bind_capability(
        &mut self,
        capability: &dyn crate::capabilities::Capability,
    ) -> anyhow::Result<()>;

    /// Resolve the binary to an absolute path.
    ///
    /// Checks the optional `command_path` override baked into the instance at
    /// construction time first, then falls back to a PATH lookup.
    ///
    /// **Not called during construction** — callers invoke this explicitly so
    /// that `catalog` and `list` work even when the tool is not installed.
    fn validate_command(&self) -> anyhow::Result<PathBuf>;

    /// Build the environment variable overlay for this launch.
    ///
    /// The default implementation returns an empty vec; concrete launchers
    /// override this once capability hooks are wired up.
    async fn env_overlay(&self, _ctx: &LaunchContext) -> anyhow::Result<Vec<EnvBinding>> {
        Ok(vec![])
    }

    /// Maps a canonical `ToolName` to this launcher's own native tool-name
    /// string, if it has an equivalent. Only meaningful for launchers
    /// implementing `BindingType::SubAgent`; the default handles the escape
    /// hatch (`ToolName::Other`, passed through verbatim) and returns `None`
    /// for every canonical/MCP variant, mirroring `env_overlay`'s "no-op
    /// until you actually support the feature" default -- a launcher that
    /// hasn't implemented sub-agent support needs no changes.
    fn map_tool_name(&self, tool: &ToolName) -> Option<String> {
        match tool {
            ToolName::Other(raw) => Some(raw.clone()),
            _ => None,
        }
    }

    /// Exec the tool as a subprocess with the env overlay applied.
    ///
    /// The default implementation resolves the binary and env overlay, then
    /// delegates to `run_command` so that dry_run and execution share
    /// an identical code path.  Concrete launchers override only when they need
    /// non-standard behaviour (e.g. a TUI-based launcher that doesn't spawn a
    /// subprocess at all).
    async fn launch(
        &self,
        args: &[String],
        ctx: &LaunchContext,
        ui: &dyn Ui,
    ) -> anyhow::Result<std::process::ExitStatus> {
        let binary = self.validate_command()?;
        let overlay = self.env_overlay(ctx).await?;
        alog_channel!(MessageLevel::Debug2, "Env Overlay: {:#?}", overlay);
        run_command(binary, &overlay, args, ctx, ui).await
    }
}

/// Translate WSL paths to Windows paths in env var values.
///
/// When running a native Windows binary from WSL (e.g., `opencode.exe`),
/// env vars like `OPENCODE_CONFIG` may contain WSL paths (`/mnt/c/Users/...`)
/// that the PE binary cannot understand. Convert them to Windows format.
fn translate_env_for_windows(binary: &PathBuf, env: &[EnvBinding]) -> Vec<EnvBinding> {
    // Only translate when the target is a Windows PE binary (ends in .exe)
    alog_channel!(MessageLevel::Debug2, "Translating for binary {:#?}", binary);
    if !binary.to_string_lossy().to_lowercase().ends_with(".exe") {
        return env.to_vec();
    }
    let mut out: Vec<_> = env
        .iter()
        .map(|b| {
            let value = crate::config::translate_wsl_to_windows(&b.value)
                .unwrap_or_else(|| b.value.clone());
            EnvBinding {
                key: b.key.clone(),
                value,
            }
        })
        .collect();
    // In order for WSL env vars to be seen by Windows, they need to be added
    // to the special WSLENV variable
    let wslenv = out
        .iter()
        .map(|b| b.key.clone())
        .collect::<Vec<_>>()
        .join(":");
    out.push(EnvBinding {
        key: "WSLENV".to_string(),
        value: wslenv,
    });
    alog_channel!(MessageLevel::Debug3, "Translated env vars: {:#?}", out);
    out
}

/// Resolve a command and run it, handling dry_run and exit status.
///
/// This is the shared utility that both the default `Launcher::launch` and
/// any custom launcher implementations should use when spawning a subprocess.
/// If `ctx.dry_run` is true the resolved binary, args, and env overlay are
/// printed to the UI without executing. Otherwise the command is spawned as a
/// subprocess with the overlay applied and a non-success exit status is turned
/// into an error.
pub(crate) async fn run_command(
    binary: PathBuf,
    overlay: &[EnvBinding],
    args: &[String],
    ctx: &LaunchContext,
    ui: &dyn Ui,
) -> anyhow::Result<std::process::ExitStatus> {
    if ctx.dry_run {
        ui.info(&format!("Would exec: {}", binary.display()));
        ui.info(&format!(
            "  args: {}",
            if args.is_empty() {
                "(none)".to_string()
            } else {
                args.join(" ")
            }
        ));
        if overlay.is_empty() {
            ui.info("  env overlay: (none)");
        } else {
            for binding in overlay {
                ui.info(&format!("  env: {}={}", binding.key, binding.value));
            }
        }
        // Return a dummy success status so callers don't need to special-case
        // dry_run.  The exit status is meaningless in this mode anyway.
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt;
            return Ok(std::process::ExitStatus::from_raw(0));
        }
        #[cfg(windows)]
        {
            use std::os::windows::process::ExitStatusExt;
            return Ok(std::process::ExitStatus::from_raw(0));
        }
    }

    // Translate WSL paths in env vars when spawning a native Windows binary.
    let translated_overlay = translate_env_for_windows(&binary, overlay);

    let mut cmd = std::process::Command::new(&binary);
    cmd.args(args);
    for binding in &translated_overlay {
        cmd.env(&binding.key, &binding.value);
    }

    // Spawn and wait on a blocking thread: `Child::wait` blocks the calling
    // thread until the subprocess exits, which would otherwise starve the
    // async runtime -- notably the usage-tracking proxy server, which needs
    // scheduler time concurrently with the child running.
    //
    // On Windows, some PE binaries (notably from official release builds run
    // in WSL) fail with os error 193 ("%1 is not a valid Win32 application")
    // when spawned directly. In those cases, fall back to invoking through
    // `cmd.exe /C`, which handles PE format compatibility correctly.
    #[cfg(windows)]
    let (binary_fallback, args_fallback, overlay_fallback) =
        (binary.clone(), args.to_vec(), translated_overlay);

    tokio::task::spawn_blocking(move || -> anyhow::Result<std::process::ExitStatus> {
        let mut spawn_cmd = cmd;

        // In WSL, the parent's CWD may be a WSL path that gets translated to
        // a UNC path for Windows processes. If the binary is on a Windows
        // drive, set the CWD to that drive's root to avoid the UNC issue.
        #[cfg(windows)]
        if let Some(drive) = binary_fallback.parent().and_then(|p| {
            p.to_str().and_then(|s| {
                let chars: Vec<char> = s.chars().collect();
                if chars.len() >= 2 && chars[1] == ':' {
                    Some(format!("{}\\", &s[..2]))
                } else {
                    None
                }
            })
        }) {
            spawn_cmd.current_dir(drive);
        }

        let mut child = match spawn_cmd.spawn() {
            Ok(child) => child,
            #[allow(unreachable_code)]
            Err(e) => {
                #[cfg(windows)]
                if let Some(193) = e.raw_os_error() {
                    let mut shell = std::process::Command::new("cmd.exe");
                    shell.arg("/C");
                    // Build the full command string for cmd.exe
                    let mut cmd_str = String::new();
                    cmd_str.push_str(&binary_fallback.to_string_lossy());
                    for arg in &args_fallback {
                        cmd_str.push(' ');
                        cmd_str.push_str(arg);
                    }
                    shell.arg(&cmd_str);
                    for binding in &overlay_fallback {
                        shell.env(&binding.key, &binding.value);
                    }
                    return shell.spawn()?.wait().map_err(anyhow::Error::from);
                }
                return Err(e.into());
            }
        };

        Ok(child.wait()?)
    })
    .await?
}

/// Resolve a command and run it, capturing stdout/stderr into returned strings.
///
/// Mirrors `run_command`'s structure but captures output instead of inheriting
/// stdio. Used for machine-consumed subprocess calls (e.g. a headless `pi
/// --print`) where the caller needs the subprocess's output as a string rather
/// than watching it in a terminal.
///
/// Returns `(exit_status, stdout, stderr)`. A non-success exit status is
/// returned as `Ok` -- the caller decides what a bad code means.
pub(crate) async fn run_command_captured(
    binary: PathBuf,
    overlay: &[EnvBinding],
    args: &[String],
    ctx: &LaunchContext,
) -> anyhow::Result<(std::process::ExitStatus, String, String)> {
    if ctx.dry_run {
        // Return a dummy success status so callers don't need to special-case
        // dry_run.  The exit status and captured strings are meaningless in this
        // mode anyway.
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt;
            return Ok((
                std::process::ExitStatus::from_raw(0),
                String::new(),
                String::new(),
            ));
        }
        #[cfg(windows)]
        {
            use std::os::windows::process::ExitStatusExt;
            return Ok((
                std::process::ExitStatus::from_raw(0),
                String::new(),
                String::new(),
            ));
        }
    }

    // Translate WSL paths in env vars when spawning a native Windows binary.
    let translated_overlay = translate_env_for_windows(&binary, overlay);

    let mut cmd = std::process::Command::new(&binary);
    cmd.args(args);
    for binding in &translated_overlay {
        cmd.env(&binding.key, &binding.value);
    }

    // Spawn and wait on a blocking thread: `Child::wait` blocks the calling
    // thread until the subprocess exits, which would otherwise starve the
    // async runtime -- notably the usage-tracking proxy server, which needs
    // scheduler time concurrently with the child running.
    //
    // On Windows, some PE binaries (notably from official release builds run
    // in WSL) fail with os error 193 ("%1 is not a valid Win32 application")
    // when spawned directly. In those cases, fall back to invoking through
    // `cmd.exe /C`, which handles PE format compatibility correctly.
    #[cfg(windows)]
    let (binary_fallback, args_fallback, overlay_fallback) =
        (binary.clone(), args.to_vec(), translated_overlay);

    tokio::task::spawn_blocking(
        move || -> anyhow::Result<(std::process::ExitStatus, String, String)> {
            let mut spawn_cmd = cmd;

            // In WSL, the parent's CWD may be a WSL path that gets translated to
            // a UNC path for Windows processes. If the binary is on a Windows
            // drive, set the CWD to that drive's root to avoid the UNC issue.
            #[cfg(windows)]
            if let Some(drive) = binary_fallback.parent().and_then(|p| {
                p.to_str().and_then(|s| {
                    let chars: Vec<char> = s.chars().collect();
                    if chars.len() >= 2 && chars[1] == ':' {
                        Some(format!("{}\\", &s[..2]))
                    } else {
                        None
                    }
                })
            }) {
                spawn_cmd.current_dir(drive);
            }

            let output = match spawn_cmd.output() {
                Ok(output) => output,
                #[allow(unreachable_code)]
                Err(e) => {
                    #[cfg(windows)]
                    if let Some(193) = e.raw_os_error() {
                        let mut shell = std::process::Command::new("cmd.exe");
                        shell.arg("/C");
                        // Build the full command string for cmd.exe
                        let mut cmd_str = String::new();
                        cmd_str.push_str(&binary_fallback.to_string_lossy());
                        for arg in &args_fallback {
                            cmd_str.push(' ');
                            cmd_str.push_str(arg);
                        }
                        shell.arg(&cmd_str);
                        for binding in &overlay_fallback {
                            shell.env(&binding.key, &binding.value);
                        }
                        return shell
                            .output()
                            .map(|o| {
                                (
                                    o.status,
                                    String::from_utf8_lossy(&o.stdout).into_owned(),
                                    String::from_utf8_lossy(&o.stderr).into_owned(),
                                )
                            })
                            .map_err(anyhow::Error::from);
                    }
                    return Err(e.into());
                }
            };

            Ok((
                output.status,
                String::from_utf8_lossy(&output.stdout).into_owned(),
                String::from_utf8_lossy(&output.stderr).into_owned(),
            ))
        },
    )
    .await?
}

/// Metadata describing a launcher implementation (type-level, catalog entry).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LauncherMetadata {
    pub name: String,
    pub description: String,
    /// The default binary name used for PATH lookup (e.g. `"claude"`, `"bob"`).
    pub default_command: String,
    /// Binding surfaces this launcher type can make use of.
    pub supported_capabilities: HashSet<BindingType>,
    pub tags: Vec<String>,
}

impl std::fmt::Display for LauncherMetadata {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.description)
    }
}

/// Runtime context passed through the launch lifecycle.
pub struct LaunchContext {
    pub launcher_id: String,
    /// The working directory for the spawned subprocess (i.e. the CWD the
    /// tool process will see). Typically set to the user's current directory.
    pub working_dir: PathBuf,
    /// Env vars already resolved (e.g. provider URL, model ID) before any
    /// capability bindings are merged on top.
    pub base_env: HashMap<String, String>,
    /// If true, only display what would be launched without executing.
    pub dry_run: bool,
}

/// A single environment variable binding contributed to the subprocess overlay.
#[derive(Debug, Clone)]
pub struct EnvBinding {
    pub key: String,
    pub value: String,
}

/*-- private --*/

define_factory!(Launcher, LauncherMetadata, LauncherFactory);

/*-- tests --*/

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::registry::ConfigConstructable;

    /// Minimal Launcher implementation used only in tests.
    pub(crate) struct FakeLauncher {
        instance_id: String,
        /// When `Some`, `validate_command` resolves to this path directly.
        command_path: Option<PathBuf>,
        command_name: String,
    }

    impl crate::registry::Named for FakeLauncher {
        fn instance_id(&self) -> &str {
            &self.instance_id
        }
    }

    impl ConfigConstructable for FakeLauncher {
        type Config = crate::registry::NoConfig;

        fn new(
            instance_id: &str,
            cfg: &serde_json::Value,
            _global_config: &crate::config::Config,
        ) -> Self {
            let command_name = cfg
                .get("command_name")
                .and_then(|v| v.as_str())
                .unwrap_or("fake-binary-that-does-not-exist")
                .to_string();
            let command_path = cfg
                .get("command_path")
                .and_then(|v| v.as_str())
                .map(PathBuf::from);
            Self {
                instance_id: instance_id.to_string(),
                command_name,
                command_path,
            }
        }
    }

    #[async_trait]
    impl Launcher for FakeLauncher {
        fn name(&self) -> &str {
            "Fake Launcher"
        }

        fn command(&self) -> &str {
            &self.command_name
        }

        async fn bind_capability(
            &mut self,
            _capability: &dyn crate::capabilities::Capability,
        ) -> anyhow::Result<()> {
            anyhow::bail!("Capability binding not supported");
        }

        fn validate_command(&self) -> anyhow::Result<PathBuf> {
            crate::utils::resolve_shell_command(
                &self
                    .command_path
                    .as_ref()
                    .map(|p| p.to_string_lossy().to_string()),
                &self.command_name,
            )
        }
    }

    impl HasLauncherMetadata for FakeLauncher {
        fn metadata() -> LauncherMetadata {
            LauncherMetadata {
                name: "Fake Launcher".to_string(),
                description: "Test double".to_string(),
                default_command: "fake-binary-that-does-not-exist".to_string(),
                supported_capabilities: HashSet::new(),
                tags: vec![],
            }
        }
    }

    #[test]
    fn validate_command_returns_err_for_unknown_binary() {
        let launcher = FakeLauncher::new(
            "my-fake",
            &serde_json::json!({
                "command_name": "this-binary-absolutely-does-not-exist-9x7z"
            }),
            &crate::config::Config::default(),
        );
        assert!(launcher.validate_command().is_err());
    }

    #[test]
    fn validate_command_returns_err_for_nonexistent_explicit_path() {
        let launcher = FakeLauncher::new(
            "my-fake",
            &serde_json::json!({
                "command_name": "fake",
                "command_path": "/this/path/does/not/exist/fake"
            }),
            &crate::config::Config::default(),
        );
        assert!(launcher.validate_command().is_err());
    }

    #[test]
    fn validate_command_falls_back_to_path_for_bare_command_name() {
        let launcher = FakeLauncher::new(
            "my-fake",
            &serde_json::json!({
                "command_path": "ls"
            }),
            &crate::config::Config::default(),
        );
        assert!(launcher.validate_command().is_ok());
    }

    #[tokio::test]
    async fn env_overlay_default_is_empty() {
        let launcher = FakeLauncher::new(
            "my-fake",
            &serde_json::json!({}),
            &crate::config::Config::default(),
        );
        let ctx = LaunchContext {
            launcher_id: "test".to_string(),
            working_dir: PathBuf::from("/tmp"),
            base_env: HashMap::new(),
            dry_run: false,
        };
        let overlay = launcher.env_overlay(&ctx).await.unwrap();
        assert!(overlay.is_empty());
    }

    #[test]
    fn map_tool_name_default_passes_through_other_and_returns_none_for_everything_else() {
        let launcher = FakeLauncher::new(
            "my-fake",
            &serde_json::json!({}),
            &crate::config::Config::default(),
        );
        assert_eq!(
            launcher.map_tool_name(&ToolName::Other("SomeRawTool".to_string())),
            Some("SomeRawTool".to_string())
        );
        assert_eq!(launcher.map_tool_name(&ToolName::FileRead), None);
        assert_eq!(
            launcher.map_tool_name(&ToolName::Mcp {
                server: "vision".to_string(),
                tool: None,
            }),
            None
        );
    }

    #[test]
    fn launcher_factory_register_and_get() {
        let mut factory = LauncherFactory::new();
        factory.register::<FakeLauncher>("fake");
        assert!(factory.get("fake").is_some());
        assert!(factory.get("nonexistent").is_none());
    }

    #[test]
    fn launcher_factory_construct() {
        let mut factory = LauncherFactory::new();
        factory.register::<FakeLauncher>("fake");
        let result = factory.construct(
            "fake",
            "my-fake",
            &serde_json::json!({}),
            &crate::config::Config::default(),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn launcher_metadata_display() {
        let meta = LauncherMetadata {
            name: "Test".to_string(),
            description: "A test launcher".to_string(),
            default_command: "test".to_string(),
            supported_capabilities: HashSet::new(),
            tags: vec![],
        };
        assert_eq!(meta.to_string(), "A test launcher");
    }

    #[tokio::test]
    async fn run_command_dry_run_returns_success() {
        use crate::utils::ui::backends::plain::PlainOutput;
        let ui = PlainOutput;
        let ctx = LaunchContext {
            launcher_id: "test".to_string(),
            working_dir: PathBuf::from("/tmp"),
            base_env: HashMap::new(),
            dry_run: true,
        };
        let status = run_command(
            PathBuf::from("/usr/bin/echo"),
            &[],
            &["hello".to_string()],
            &ctx,
            &ui,
        )
        .await
        .unwrap();
        assert!(status.success());
    }

    #[tokio::test]
    async fn run_command_non_dry_run_executes() {
        use crate::utils::ui::backends::plain::PlainOutput;
        let ui = PlainOutput;
        let ctx = LaunchContext {
            launcher_id: "test".to_string(),
            working_dir: PathBuf::from("/tmp"),
            base_env: HashMap::new(),
            dry_run: false,
        };
        #[cfg(unix)]
        let (binary, args) = (PathBuf::from("/bin/echo"), vec!["hello".to_string()]);
        #[cfg(windows)]
        let (binary, args) = (
            PathBuf::from("cmd"),
            vec!["/C".to_string(), "echo".to_string(), "hello".to_string()],
        );

        let status = run_command(binary, &[], &args, &ctx, &ui).await.unwrap();
        assert!(status.success());
    }
}