collet 0.1.0

Relentless agentic coding orchestrator with zero-drop agent loops
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
/// CLI module: command parsing, flag processing, and main entry point utilities.
pub mod help;
pub mod remote;
pub mod util;

use anyhow::Result;

// Re-export commonly used items
pub use help::*;
pub use remote::*;

const SUBCOMMANDS: &[&str] = &[
    "setup", "secure", "unsecure", "status", "provider", "clis", "help", "web", "remote", "acp",
    "mcp", "update", "version", "evolve", "plugin",
];

/// Flag structure for parsing command-line arguments.
pub struct Flags {
    pub model: Option<String>,
    pub yolo: bool,
    pub watch: bool,
    pub r#continue: bool,
    pub resume: bool,
    /// Specific session ID to resume directly (from `--resume <id>`).
    pub resume_session_id: Option<String>,
    pub ext: Vec<String>,
    pub debounce: Option<u64>,
    /// Override working directory (--dir <path>).
    pub dir: Option<String>,
    /// Watch mode: directory to watch (--cwd).
    pub watch_dir: Option<String>,
    /// Watch mode: agent name to use (--agent).
    pub watch_agent: Option<String>,
    /// Output JSON metrics to stderr when headless mode finishes.
    pub json_metrics: bool,
}

/// Parse command-line flags from arguments.
pub fn parse_flags(args: &[String]) -> Flags {
    let mut flags = Flags {
        model: None,
        yolo: false,
        watch: false,
        r#continue: false,
        resume: false,
        resume_session_id: None,
        ext: Vec::new(),
        debounce: None,
        dir: None,
        watch_dir: None,
        watch_agent: None,
        json_metrics: false,
    };

    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--model" | "-m" => {
                flags.model = args.get(i + 1).cloned();
                i += 2;
            }
            "--yolo" | "-y" => {
                flags.yolo = true;
                i += 1;
            }
            "--watch" | "-w" => {
                flags.watch = true;
                i += 1;
            }
            "--continue" | "-c" => {
                flags.r#continue = true;
                i += 1;
            }
            "--resume" | "-r" => {
                // `--resume <session-id>` → direct resume; `--resume` alone → picker popup
                if let Some(next) = args.get(i + 1)
                    && !next.starts_with('-')
                {
                    flags.resume_session_id = Some(next.clone());
                    i += 2;
                    continue;
                }
                flags.resume = true;
                i += 1;
            }
            "--ext" | "-e" => {
                if let Some(exts) = args.get(i + 1) {
                    flags.ext = exts.split(',').map(|s| s.trim().to_string()).collect();
                }
                i += 2;
            }
            "--debounce" | "-D" => {
                flags.debounce = args.get(i + 1).and_then(|v| v.parse().ok());
                i += 2;
            }
            "--dir" | "-d" => {
                flags.dir = args.get(i + 1).cloned();
                i += 2;
            }
            "--cwd" => {
                flags.watch_dir = args.get(i + 1).cloned();
                i += 2;
            }
            "--agent" | "-a" => {
                flags.watch_agent = args.get(i + 1).cloned();
                i += 2;
            }
            "--json-metrics" => {
                flags.json_metrics = true;
                i += 1;
            }
            _ => {
                i += 1;
            }
        }
    }

    flags
}

/// Extract the prompt: first arg that isn't a subcommand or flag.
pub fn extract_prompt(args: &[String]) -> Option<String> {
    let mut i = 1;
    while i < args.len() {
        let arg = args[i].as_str();

        // Skip known subcommands
        if SUBCOMMANDS.contains(&arg) {
            return None;
        }

        // Skip flags and their values
        if arg.starts_with('-') {
            // Flags with values
            if matches!(
                arg,
                "--model" | "--ext" | "--debounce" | "--dir" | "-d" | "--cwd" | "--agent" | "-a"
            ) {
                i += 2;
            } else if matches!(arg, "--resume" | "-r") {
                // --resume may consume next arg (session ID)
                if args.get(i + 1).is_some_and(|n| !n.starts_with('-')) {
                    i += 2;
                } else {
                    i += 1;
                }
            } else {
                i += 1;
            }
            continue;
        }

        // First non-flag arg = prompt
        return Some(args[i].clone());
    }
    None
}

/// Check if an argument is a help flag.
pub fn is_help_arg(arg: Option<&String>) -> bool {
    arg.map(|s| matches!(s.as_str(), "help" | "--help" | "-h"))
        .unwrap_or(false)
}

/// `collet web` subcommand — parse web-specific flags and start the server.
pub async fn cmd_web(args: &[String]) -> Result<()> {
    #[cfg(not(feature = "web"))]
    {
        let _ = args;
        eprintln!("❌ Web server requires the `web` feature.");
        eprintln!("   Rebuild with: cargo build --features web");
        std::process::exit(1);
    }

    #[cfg(feature = "web")]
    {
        use std::net::SocketAddr;

        // Load config (API key needed for agent)
        let config = match crate::config::Config::load() {
            Ok(c) => c,
            Err(e) => {
                eprintln!("{e}");
                std::process::exit(1);
            }
        };
        let client = crate::api::provider::OpenAiCompatibleProvider::from_config(&config)?;

        // Parse web-specific flags (override config.toml [web] section)
        let mut host = config.web.host.clone();
        let mut port = config.web.port;
        let mut username = config.web.username.clone();
        let mut cors: Vec<String> = config.web.cors_origins.clone();
        let mut password = config.web.password.clone();

        let mut i = 2; // skip "collet" "web"
        while i < args.len() {
            match args[i].as_str() {
                "--host" | "-h" => {
                    host = args.get(i + 1).cloned().unwrap_or(host);
                    i += 2;
                }
                "--port" | "-p" => {
                    port = args.get(i + 1).and_then(|v| v.parse().ok()).unwrap_or(port);
                    i += 2;
                }
                "--username" | "-u" => {
                    username = args.get(i + 1).cloned().unwrap_or(username);
                    i += 2;
                }
                "--cors" => {
                    if let Some(origins) = args.get(i + 1) {
                        cors.extend(origins.split(',').map(|s| s.trim().to_string()));
                    }
                    i += 2;
                }
                "--password" | "-P" => {
                    password = args.get(i + 1).cloned();
                    i += 2;
                }
                _ => {
                    i += 1;
                }
            }
        }

        let bind: SocketAddr = format!("{host}:{port}")
            .parse()
            .map_err(|e| anyhow::anyhow!("Invalid bind address {host}:{port}: {e}"))?;

        let (event_bus, _) = tokio::sync::broadcast::channel::<crate::server::WebEvent>(4096);
        let working_dir = std::env::current_dir()?.to_string_lossy().to_string();

        let web_cfg = crate::config::WebConfig {
            host,
            port,
            username,
            password,
            cors_origins: cors,
        };

        let url = format!("http://{bind}");
        let auth_msg = if web_cfg.password.is_some() {
            "🔒 Password authentication enabled"
        } else {
            "⚠️  No password set; server is unsecured."
        };

        // ANSI: \x1b[1;97m = bold white, \x1b[2;37m = dim grey, \x1b[0m = reset
        eprintln!();
        eprintln!("  \x1b[2;37m          ·            ✦         .    ˚\x1b[0m");
        eprintln!("  \x1b[2;37m   .  ✧          ·          ˚        ·\x1b[0m");
        eprintln!("  \x1b[2;37m              ·       .    ✧     .\x1b[0m");
        eprintln!("  \x1b[1;97m      █▀▀ █▀▀█ █   █   █▀▀ ▀█▀\x1b[0m");
        eprintln!("  \x1b[1;97m      █   █  █ █   █   █▀▀  █\x1b[0m");
        eprintln!("  \x1b[1;97m      ▀▀▀ ▀▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀  ▀\x1b[0m");
        eprintln!("  \x1b[2;37m      ░▀▀ ░▀▀▀ ░▀▀ ░▀▀ ░▀▀ ░▀\x1b[0m");
        eprintln!("  \x1b[2;37m  ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\x1b[0m");
        eprintln!();
        eprintln!("  Web interface:  {url}");
        eprintln!("  {auth_msg}");
        if web_cfg.password.is_none() {
            eprintln!("  \x1b[2;37mSet credentials: collet secure --web\x1b[0m");
        }
        eprintln!();
        eprintln!("  Press Ctrl+C to stop.");
        eprintln!();

        let handle =
            crate::server::start(config, client, event_bus, bind, working_dir, web_cfg).await?;

        // Open browser
        let _ = util::open_url(&url);

        tokio::signal::ctrl_c().await.ok();
        eprintln!("\n🛑 Shutting down...");
        handle.abort();

        Ok(())
    }
}

/// `collet remote` subcommand — manage and run the remote control gateway.
pub async fn cmd_remote(args: &[String]) -> Result<()> {
    // Extract remote subcommand: collet remote <sub> [args...]
    let sub_args: Vec<String> = args
        .iter()
        .skip_while(|a| a.as_str() != "remote")
        .skip(1) // skip "remote" itself
        .cloned()
        .collect();

    let sub = sub_args.first().map(|s| s.as_str());

    match sub {
        Some("help") | Some("--help") | Some("-h") => {
            print_remote_usage();
            Ok(())
        }
        None | Some("start") => {
            let foreground = sub_args.iter().any(|a| a == "--fg" || a == "--foreground");
            if foreground {
                remote_start().await
            } else {
                remote_start_daemon()
            }
        }
        Some("add") => {
            let platform = sub_args.get(1).map(|s| s.as_str());
            remote_add(platform)
        }
        Some("rm") | Some("remove") => {
            let platform = sub_args.get(1).map(|s| s.as_str());
            remote_rm(platform)
        }
        Some("ls") | Some("list") => remote_ls(),
        Some("stop") => remote_stop(),
        Some("restart") => remote_restart(),
        Some("enable") => remote_enable(),
        Some("disable") => remote_disable(),
        Some("logs") | Some("log") => {
            let follow = sub_args.iter().any(|a| a == "-f" || a == "--follow");
            remote_logs(follow)
        }
        Some("status") => remote_status(),
        Some(other) => {
            eprintln!("Unknown remote subcommand: {other}");
            eprintln!();
            print_remote_usage();
            std::process::exit(1);
        }
    }
}

/// `collet acp serve` — start ACP server on stdio for IDE integration.
pub async fn cmd_acp(args: &[String]) -> Result<()> {
    let sub = args
        .iter()
        .skip_while(|a| a.as_str() != "acp")
        .nth(1)
        .map(|s| s.as_str());

    match sub {
        Some("help") | Some("--help") | Some("-h") => {
            print_acp_usage();
            Ok(())
        }
        Some("serve") => {
            let config = match crate::config::Config::load() {
                Ok(c) => c,
                Err(e) => {
                    eprintln!("{e}");
                    std::process::exit(1);
                }
            };
            let client = crate::api::provider::OpenAiCompatibleProvider::from_config(&config)?;
            crate::acp::server::run_acp_server(config, client).await
        }
        _ => {
            print_acp_usage();
            Ok(())
        }
    }
}

/// `collet mcp` subcommand — manage MCP server configuration.
pub fn cmd_mcp(args: &[String]) -> Result<()> {
    let sub = args.first().map(|s| s.as_str());
    match sub {
        Some("help") | Some("-h") | Some("--help") => {
            print_mcp_usage();
            Ok(())
        }
        _ => {
            let working_dir = std::env::current_dir()
                .unwrap_or_else(|_| std::path::PathBuf::from("."))
                .to_string_lossy()
                .to_string();
            let output = crate::commands::handle_mcp_command(args, &working_dir);
            // handle_mcp_command returns markdown — strip for CLI output
            for line in output.lines() {
                let line = line.trim_start_matches('#').trim_start_matches('*').trim();
                if !line.is_empty() {
                    eprintln!("{line}");
                }
            }
            Ok(())
        }
    }
}

/// `collet update` — check for updates.
pub async fn cmd_update() -> Result<()> {
    eprintln!("Checking for updates...");
    let current = env!("CARGO_PKG_VERSION");

    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(10))
        .build()?;
    let resp = client
        .get("https://crates.io/api/v1/crates/collet")
        .header("User-Agent", format!("collet/{current}"))
        .send()
        .await;

    match resp {
        Ok(r) if r.status().is_success() => {
            let body: serde_json::Value = r.json().await?;
            if let Some(latest) = body["crate"]["max_stable_version"].as_str() {
                if latest == current {
                    eprintln!("collet {current} is already the latest version.");
                } else {
                    eprintln!("Current version:  {current}");
                    eprintln!("Latest version:   {latest}");
                    eprintln!();
                    eprintln!("Update with:");
                    eprintln!("  cargo install collet");
                }
            } else {
                eprintln!("collet {current} (could not determine latest version)");
            }
        }
        Ok(r) => {
            eprintln!(
                "collet {current} (version check failed: HTTP {})",
                r.status()
            );
        }
        Err(e) => {
            eprintln!("collet {current} (version check failed: {e})");
        }
    }
    Ok(())
}