OXYGENHUB
# f4b3e9369e28 spectra / src / cli / mod.rs
24.9 KiB · Rust · last changed spectra status, probe and bridge: what the VS Code extension drives (#31) 1 day ago source blame history raw
1
//! The `spectra` command line (spec §19). Output is modern: colour and
2
//! glyphs on a UTF-8 terminal, plain when piped, with `--plain` or with
3
//! `NO_COLOR`; `--json` prints one document on stdout and nothing else.
4
5
pub mod admin;
6
pub mod agent;
7
pub mod brief;
8
pub mod connect;
9
pub mod format;
10
pub mod human;
11
pub mod identity;
12
pub mod marks;
13
pub mod mcp;
14
pub mod open;
15
pub mod project;
16
pub mod serve;
17
pub mod setup;
18
pub mod ui;
19
20
use anyhow::{bail, Context, Result};
21
use clap::{Parser, Subcommand};
22
use std::path::PathBuf;
23
24
#[derive(Parser)]
25
#[command(name = "spectra", version = env!("SPECTRA_VERSION_LONG"), about = "A control plane for AI coding agents")]
26
pub struct Cli {
27
    /// Plain output: no colour or glyphs (also NO_COLOR, or when not a terminal)
28
    #[arg(long, global = true)]
29
    pub plain: bool,
30
    /// The data directory (default: $XDG_DATA_HOME/spectra, else ~/.local/share/spectra)
31
    #[arg(long, global = true, env = "SPECTRA_DATA")]
32
    pub data: Option<PathBuf>,
33
    #[command(subcommand)]
34
    pub command: Command,
35
}
36
37
#[derive(Subcommand)]
38
pub enum Command {
39
    /// The version and build of this binary
40
    Version {
41
        /// Machine-readable output
42
        #[arg(long)]
43
        json: bool,
44
    },
45
    /// Make this machine's Spectra: record the owner's identity (read from
46
    /// their OXY_HOME and proven by signing) and make the instance key
47
    Init {
48
        /// The owner's identity home (default: $SPECTRA_HOME, else ~/.config/spectra)
49
        #[arg(long)]
50
        owner_home: Option<PathBuf>,
51
        /// This instance's name (default: the host name)
52
        #[arg(long)]
53
        name: Option<String>,
54
        /// Set up a server without the owner's secret key: name the owner's
55
        /// KeyId, and they claim it from their machine with `spectra
56
        /// connect` (spec §8.6)
57
        #[arg(long, value_name = "KEYID", conflicts_with = "owner_home")]
58
        owner: Option<String>,
59
    },
60
    /// Use a Spectra on another machine: trust it through your delegation to
61
    /// its instance key, pin its certificate, and claim it if it is new
62
    Connect {
63
        /// The server, https://HOST[:PORT]
64
        url: String,
65
        /// Trust the server if its instance key starts with this, without asking
66
        #[arg(long, value_name = "KEYID-PREFIX")]
67
        expect: Option<String>,
68
        /// Trust it without asking (for scripts)
69
        #[arg(long, short = 'y')]
70
        yes: bool,
71
        /// The owner's identity home (default: $SPECTRA_HOME, else ~/.config/spectra)
72
        #[arg(long)]
73
        owner_home: Option<PathBuf>,
74
    },
75
    /// What is set up here: your identity, and the Spectra you use
76
    Status {
77
        #[arg(long)]
78
        json: bool,
79
    },
80
    /// What a server is (its name and instance key), without trusting it
81
    Probe {
82
        /// The server, https://HOST[:PORT]
83
        url: String,
84
        #[arg(long)]
85
        json: bool,
86
    },
87
    /// Sign as you for a program that cannot (the VS Code extension): a
88
    /// loopback proxy that ends when its input closes
89
    Bridge {
90
        #[arg(long, default_value_t = 0)]
91
        port: u16,
92
        #[arg(long)]
93
        owner_home: Option<PathBuf>,
94
    },
95
    /// What the agents are told: the overall brief and each project's
96
    Brief {
97
        #[command(subcommand)]
98
        command: BriefCmd,
99
    },
100
    /// The owner's and the instance's identities: show, refresh
101
    Identity {
102
        #[command(subcommand)]
103
        command: IdentityCmd,
104
    },
105
    /// Run the daemon: the ledger, Tuner on the Unix socket and a loopback port
106
    Serve {
107
        /// The address and port for browsers and HTTP clients (default:
108
        /// `[server] bind`, else 127.0.0.1:7350); beyond loopback, other
109
        /// machines connect over TLS (spec §8.6)
110
        #[arg(long)]
111
        bind: Option<String>,
112
        /// TLS on the TCP port: auto (beyond loopback only), on, or off
113
        /// (default: `[server] tls`, else auto)
114
        #[arg(long)]
115
        tls: Option<String>,
116
        /// Allow a non-loopback address in plain HTTP
117
        #[arg(long)]
118
        insecure: bool,
119
        /// Open Radar in the browser once serving (signs a link as the owner)
120
        #[arg(long)]
121
        open: bool,
122
    },
123
    /// Sign in to Radar: a one-time link signed with the owner's key
124
    Open {
125
        #[arg(long)]
126
        owner_home: Option<PathBuf>,
127
        /// Print the link without opening a browser
128
        #[arg(long)]
129
        no_browser: bool,
130
        /// With Spectra on another machine: the loopback port of the proxy
131
        /// Radar is served through (spec §8.6)
132
        #[arg(long, default_value_t = 7350)]
133
        port: u16,
134
    },
135
    /// The stdio MCP server for one agent: signs with its key and forwards to the daemon
136
    Mcp {
137
        /// The agent it speaks for
138
        #[arg(long)]
139
        agent: String,
140
        /// The agent's home (default: the one recorded when it was added)
141
        #[arg(long)]
142
        home: Option<PathBuf>,
143
    },
144
    /// Post a message as yourself
145
    Say {
146
        /// What to say (Markdown; @name mentions)
147
        body: String,
148
        /// The channel (default: #general)
149
        #[arg(short, long)]
150
        channel: Option<String>,
151
        /// Reply in the thread of this message
152
        #[arg(long)]
153
        reply_to: Option<String>,
154
        #[arg(long)]
155
        json: bool,
156
        #[arg(long)]
157
        owner_home: Option<PathBuf>,
158
    },
159
    /// Your unread mentions and direct messages; --follow waits for more
160
    Inbox {
161
        #[arg(long)]
162
        follow: bool,
163
        #[arg(long)]
164
        json: bool,
165
        #[arg(long)]
166
        owner_home: Option<PathBuf>,
167
    },
168
    /// Search what was said: words, "phrases", prefix*, AND/OR/NOT
169
    Search {
170
        query: String,
171
        #[arg(long)]
172
        channel: Option<String>,
173
        #[arg(long)]
174
        author: Option<String>,
175
        /// 7d, 3h, 30m
176
        #[arg(long)]
177
        since: Option<String>,
178
        #[arg(long, default_value_t = 20)]
179
        limit: u32,
180
        #[arg(long)]
181
        json: bool,
182
    },
183
    /// Any API call, signed as the owner: JSON out
184
    Api {
185
        method: String,
186
        path: String,
187
        /// The request body (JSON)
188
        #[arg(short = 'd', long = "body")]
189
        body: Option<String>,
190
        #[arg(long)]
191
        owner_home: Option<PathBuf>,
192
    },
193
    /// The checkouts agents work in: add, list
194
    Project {
195
        #[command(subcommand)]
196
        command: ProjectCmd,
197
    },
198
    /// Agents, each its owner's delegate: add, list, disable
199
    Agent {
200
        #[command(subcommand)]
201
        command: AgentCmd,
202
    },
203
    /// The ledger's own checks: verify, check, rebuild
204
    Admin {
205
        #[command(subcommand)]
206
        command: Admin,
207
    },
208
}
209
210
#[derive(Subcommand)]
211
pub enum IdentityCmd {
212
    /// Make your own identity: a key pair that signs as you (spec §8.0)
213
    Create {
214
        /// Your name, as agents and Radar show it
215
        #[arg(long)]
216
        name: String,
217
        /// An email or URL, if you want one shown
218
        #[arg(long, default_value = "")]
219
        contact: String,
220
        /// Where to keep it (default: $SPECTRA_HOME, else ~/.config/spectra)
221
        #[arg(long)]
222
        home: Option<PathBuf>,
223
        #[arg(long)]
224
        json: bool,
225
    },
226
    /// The owner and the instance as the ledger knows them
227
    Show {
228
        #[arg(long)]
229
        json: bool,
230
    },
231
    /// Record the owner's current identity if the ledger has missed a successor
232
    Refresh {
233
        #[arg(long)]
234
        owner_home: Option<PathBuf>,
235
    },
236
}
237
238
#[derive(Subcommand)]
239
pub enum BriefCmd {
240
    /// Show the overall brief, or a project's
241
    Show {
242
        #[arg(long)]
243
        project: Option<String>,
244
        #[arg(long)]
245
        json: bool,
246
    },
247
    /// Set the overall brief, or a project's (an empty text clears it)
248
    Set {
249
        #[arg(long)]
250
        project: Option<String>,
251
        /// The text
252
        text: Option<String>,
253
        /// Read the text from a file (- for standard input)
254
        #[arg(long, short = 'f')]
255
        file: Option<PathBuf>,
256
        #[arg(long)]
257
        owner_home: Option<PathBuf>,
258
    },
259
    /// Edit it in $VISUAL or $EDITOR
260
    Edit {
261
        #[arg(long)]
262
        project: Option<String>,
263
        #[arg(long)]
264
        owner_home: Option<PathBuf>,
265
    },
266
}
267
268
#[derive(Subcommand)]
269
pub enum ProjectCmd {
270
    /// Add a project: any kind of work, with a folder if it has one
271
    Add {
272
        /// A folder (its name becomes the project's), or just a name
273
        target: String,
274
        /// Its name, when TARGET is a folder
275
        #[arg(long)]
276
        name: Option<String>,
277
        /// The work's folder, when TARGET is a name; Spectra never reads it
278
        #[arg(long)]
279
        path: Option<PathBuf>,
280
        /// What the work is, for agents and Radar
281
        #[arg(long, short = 'd', default_value = "")]
282
        description: String,
283
        /// A link to it, if any
284
        #[arg(long)]
285
        url: Option<String>,
286
        #[arg(long)]
287
        owner_home: Option<PathBuf>,
288
    },
289
    /// Say that one project depends on another (`delegate to: downstream` follows links)
290
    Link {
291
        project: String,
292
        #[arg(long)]
293
        depends_on: String,
294
        /// Remove the link instead
295
        #[arg(long)]
296
        remove: bool,
297
        #[arg(long)]
298
        owner_home: Option<PathBuf>,
299
    },
300
    /// Every project with its links and agents
301
    List {
302
        #[arg(long)]
303
        json: bool,
304
    },
305
}
306
307
#[derive(Subcommand)]
308
pub enum AgentCmd {
309
    /// Make an agent's key in its own home, delegate to it, and record it
310
    Add {
311
        /// Lower-case letters, digits and dashes
312
        name: String,
313
        /// claude-code, antigravity, kimi-code, codex or other
314
        #[arg(long)]
315
        kind: String,
316
        /// The project it works in
317
        #[arg(long)]
318
        project: String,
319
        /// The agent's own identity home, where its key is made and kept
320
        #[arg(long)]
321
        home: PathBuf,
322
        /// Bind the key to this Unix user: a request from another is refused
323
        #[arg(long)]
324
        uid: Option<u32>,
325
        /// Bind the key to the Unix user of its first signed connection
326
        #[arg(long, conflicts_with = "uid")]
327
        learn_uid: bool,
328
        /// How long the agent may act for you: 30m, 8h, 7d (default: until disabled)
329
        #[arg(long)]
330
        expires: Option<String>,
331
        /// Delegate without asking (for scripts)
332
        #[arg(long, short = 'y')]
333
        yes: bool,
334
        /// The owner's identity home
335
        #[arg(long)]
336
        owner_home: Option<PathBuf>,
337
    },
338
    /// Give an agent more time: delegate to its key again with a new expiry
339
    Renew {
340
        name: String,
341
        /// 30m, 8h, 7d, or `never`
342
        #[arg(long)]
343
        expires: String,
344
        #[arg(long)]
345
        owner_home: Option<PathBuf>,
346
    },
347
    /// Every agent with its owner, key, delegation and state
348
    List {
349
        #[arg(long)]
350
        json: bool,
351
    },
352
    /// Refuse an agent's key from now on
353
    Disable {
354
        name: String,
355
        #[arg(long)]
356
        owner_home: Option<PathBuf>,
357
    },
358
}
359
360
#[derive(Subcommand)]
361
pub enum Admin {
362
    /// Recompute the hash chain and check every checkpoint and proof (exit 1 on any finding)
363
    Verify {
364
        /// Machine-readable output
365
        #[arg(long)]
366
        json: bool,
367
    },
368
    /// Whether the projections equal a rebuild from the ledger
369
    Check,
370
    /// Replay the ledger into every projection
371
    Rebuild,
372
}
373
374
/// What every command needs: where the data lives.
375
pub struct Ctx {
376
    pub data: PathBuf,
377
}
378
379
impl Ctx {
380
    /// The ledger's database, which must exist.
381
    pub fn db(&self) -> Result<PathBuf> {
382
        let db = self.data.join("spectra.db");
383
        if !db.exists() {
384
            bail!("no Spectra in {} (run `spectra init`, or pass --data)", self.data.display());
385
        }
386
        Ok(db)
387
    }
388
389
    /// The ledger, for writing: the instance key signs its checkpoints, and
390
    /// the lock keeps any other writer out.
391
    pub async fn writer(&self) -> Result<spectra_core::ledger::Ledger> {
392
        let db = self.db()?;
393
        let instance = spectra_core::keys::KeyPair::instance(&self.data, "spectra")?;
394
        spectra_core::ledger::Ledger::open(&db, Some(instance)).await
395
    }
396
397
    /// The daemon's Unix socket.
398
    pub fn socket(&self) -> PathBuf {
399
        self.data.join("spectra.sock")
400
    }
401
402
    /// The Spectra on another machine this one uses, if any (spec §8.6).
403
    pub fn remote(&self) -> Result<Option<connect::ClientCfg>> {
404
        connect::load()
405
    }
406
407
    /// Where the daemon is: the configured server, else the local socket.
408
    pub fn endpoint(&self) -> Result<spectra_mcp::client::Endpoint> {
409
        Ok(match self.remote()? {
410
            Some(c) => c.endpoint()?,
411
            None => spectra_mcp::client::Endpoint::Unix(self.socket()),
412
        })
413
    }
414
415
    /// A client signing as the owner: to the configured server (spec §8.6),
416
    /// or to the local daemon when it is serving; none when neither. It
417
    /// signs with the owner identity the ledger records, since the daemon
418
    /// may not know a newer one yet.
419
    pub async fn owner_client(&self, owner_home: &std::path::Path) -> Result<Option<spectra_mcp::client::Client>> {
420
        use spectra_mcp::client::Client;
421
        if let Some(cfg) = self.remote()? {
422
            let ep = cfg.endpoint()?;
423
            let pair = remote_owner(&ep, owner_home).await?;
424
            return Ok(Some(Client::at(ep, Some(pair))));
425
        }
426
        if !self.data.join("spectra.db").exists() || !Client::alive(&self.socket()).await {
427
            return Ok(None);
428
        }
429
        let ledger = spectra_core::ledger::Ledger::open_read_only(&self.db()?).await?;
430
        Ok(Some(Client::new(&self.socket(), Some(identity::recorded_owner(&ledger, owner_home).await?))))
431
    }
432
433
    /// Somewhere to append the owner's signed events: the configured server,
434
    /// the local daemon when it is serving, else straight to the ledger
435
    /// (spec §8.5, §8.6).
436
    pub async fn owner_writer(&self, owner_home: &std::path::Path) -> Result<Writer> {
437
        if let Some(cfg) = self.remote()? {
438
            let ep = cfg.endpoint()?;
439
            let pair = remote_owner(&ep, owner_home).await?;
440
            let recorded = pair.identity.clone();
441
            return Ok(Writer::Remote { client: Box::new(spectra_mcp::client::Client::at(ep, Some(pair))), recorded });
442
        }
443
        let db = self.db()?;
444
        if spectra_mcp::client::Client::alive(&self.socket()).await {
445
            let ledger = spectra_core::ledger::Ledger::open_read_only(&db).await?;
446
            let transport = identity::recorded_owner(&ledger, owner_home).await?;
447
            return Ok(Writer::Daemon { ledger, client: Box::new(spectra_mcp::client::Client::new(&self.socket(), Some(transport))) });
448
        }
449
        Ok(Writer::Direct(self.writer().await?))
450
    }
451
452
    /// Refuse a command that needs the ledger file on this machine.
453
    pub fn local_only(&self, what: &str) -> Result<()> {
454
        if self.remote()?.is_some() {
455
            bail!("{what} runs on the server, which holds the ledger (this machine uses {})", connect::path().display());
456
        }
457
        Ok(())
458
    }
459
460
    /// `[owner] home` from spectra.toml.
461
    pub fn config_owner_home(&self) -> Option<PathBuf> {
462
        let text = std::fs::read_to_string(self.data.join("spectra.toml")).ok()?;
463
        let t: toml::Table = text.parse().ok()?;
464
        t.get("owner")?.get("home")?.as_str().map(PathBuf::from)
465
    }
466
}
467
468
/// Where the owner's events go.
469
pub enum Writer {
470
    Direct(spectra_core::ledger::Ledger),
471
    Daemon {
472
        ledger: spectra_core::ledger::Ledger,
473
        client: Box<spectra_mcp::client::Client>,
474
    },
475
    /// A Spectra on another machine; `recorded` is the owner identity it knows.
476
    Remote {
477
        client: Box<spectra_mcp::client::Client>,
478
        recorded: spectra_core::identity::Identity,
479
    },
480
}
481
482
impl Writer {
483
    /// The ledger on this machine, for reading, if there is one.
484
    pub fn ledger(&self) -> Option<&spectra_core::ledger::Ledger> {
485
        match self {
486
            Writer::Direct(l) | Writer::Daemon { ledger: l, .. } => Some(l),
487
            Writer::Remote { .. } => None,
488
        }
489
    }
490
491
    /// A client of the daemon, when one is serving.
492
    pub fn client(&self) -> Option<&spectra_mcp::client::Client> {
493
        match self {
494
            Writer::Daemon { client, .. } | Writer::Remote { client, .. } => Some(client),
495
            Writer::Direct(_) => None,
496
        }
497
    }
498
499
    /// The rotation that brings the recorded owner to the current identity
500
    /// in `home`, if it has moved.
501
    pub async fn refresh_event(&self, home: &std::path::Path) -> Result<Option<spectra_core::event::NewEvent>> {
502
        match self {
503
            Writer::Direct(l) | Writer::Daemon { ledger: l, .. } => identity::refresh_event(l, home).await,
504
            Writer::Remote { recorded, .. } => identity::rotation(recorded, home),
505
        }
506
    }
507
508
    /// Append events signed over their payload, then checkpoint.
509
    pub async fn append(&self, events: Vec<spectra_core::event::NewEvent>) -> Result<()> {
510
        match self {
511
            Writer::Direct(l) => {
512
                l.append(events).await?;
513
                l.checkpoint().await?;
514
            }
515
            Writer::Daemon { client, .. } | Writer::Remote { client, .. } => {
516
                let wire: Vec<_> = events.iter().map(spectra_core::daemon::WireEvent::from_new).collect();
517
                let r = client.send("POST", "/api/v1/ledger/events", &[], serde_json::to_vec(&wire)?).await?;
518
                if r.status != 200 {
519
                    let why = r
520
                        .json()
521
                        .ok()
522
                        .and_then(|v| v.get("title").and_then(|t| t.as_str()).map(String::from))
523
                        .unwrap_or_else(|| String::from_utf8_lossy(&r.body).into());
524
                    bail!("the daemon refused: {why}");
525
                }
526
            }
527
        }
528
        Ok(())
529
    }
530
}
531
532
/// The owner identity a server records, as a key pair from the owner's
533
/// home: what requests to it are signed with.
534
async fn remote_owner(ep: &spectra_mcp::client::Endpoint, home: &std::path::Path) -> Result<spectra_core::keys::KeyPair> {
535
    let r = spectra_mcp::client::Client::at(ep.clone(), None).send("GET", "/api/v1/instance", &[], vec![]).await?;
536
    let info = r.json()?;
537
    let key = info.get("owner").and_then(|o| o.as_str()).context("the server has no owner yet: spectra connect claims it")?;
538
    let keys = home.join("keys");
539
    spectra_core::keys::KeyPair::load(&keys.join(format!("{key}.secret")), &keys.join(format!("{key}.identity")))
540
        .with_context(|| format!("the server's owner {} is not an identity in {}", &key[..12.min(key.len())], home.display()))
541
}
542
543
/// An API call; a refusal becomes an error that says why.
544
pub async fn call(c: &spectra_mcp::client::Client, method: &str, path: &str, body: Option<serde_json::Value>) -> Result<serde_json::Value> {
545
    let r = c.send(method, path, &[], body.map(|b| serde_json::to_vec(&b)).transpose()?.unwrap_or_default()).await?;
546
    let v: serde_json::Value = r.json().unwrap_or(serde_json::Value::Null);
547
    if r.status >= 400 {
548
        let why = v
549
            .get("detail")
550
            .or(v.get("title"))
551
            .and_then(serde_json::Value::as_str)
552
            .map(String::from)
553
            .unwrap_or_else(|| String::from_utf8_lossy(&r.body).into());
554
        bail!("{why}");
555
    }
556
    Ok(v)
557
}
558
559
/// A query string value, percent-encoded.
560
pub fn encode(s: &str) -> String {
561
    s.bytes()
562
        .map(|b| match b {
563
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
564
            _ => format!("%{b:02X}"),
565
        })
566
        .collect()
567
}
568
569
fn init_logging() {
570
    let filter = tracing_subscriber::EnvFilter::try_from_env("SPECTRA_LOG").unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn"));
571
    tracing_subscriber::fmt().with_env_filter(filter).with_writer(std::io::stderr).init();
572
}
573
574
fn default_data() -> PathBuf {
575
    if let Ok(x) = std::env::var("XDG_DATA_HOME") {
576
        return PathBuf::from(x).join("spectra");
577
    }
578
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
579
    PathBuf::from(home).join(".local").join("share").join("spectra")
580
}
581
582
fn runtime() -> Result<tokio::runtime::Runtime> {
583
    Ok(tokio::runtime::Builder::new_multi_thread().enable_all().build()?)
584
}
585
586
pub fn run() -> Result<i32> {
587
    let cli = Cli::parse();
588
    ui::init(cli.plain);
589
    let ctx = Ctx { data: cli.data.unwrap_or_else(default_data) };
590
    match cli.command {
591
        Command::Version { json } => version(json),
592
        Command::Status { json } => runtime()?.block_on(setup::status(&ctx, json)),
593
        Command::Probe { url, json } => runtime()?.block_on(setup::probe(&url, json)),
594
        Command::Bridge { port, owner_home } => runtime()?.block_on(setup::bridge(&ctx, port, owner_home)),
595
        Command::Brief { command } => runtime()?.block_on(async {
596
            match command {
597
                BriefCmd::Show { project, json } => brief::show(&ctx, project, json).await,
598
                BriefCmd::Set { project, text, file, owner_home } => {
599
                    brief::set(&ctx, project, brief::text_of(text, file)?, owner_home).await
600
                }
601
                BriefCmd::Edit { project, owner_home } => brief::edit(&ctx, project, owner_home).await,
602
            }
603
        }),
604
        Command::Connect { url, owner_home, expect, yes } => runtime()?.block_on(connect::connect(&ctx, &url, owner_home, expect, yes)),
605
        Command::Init { owner_home, name, owner: Some(key) } => {
606
            let _ = owner_home;
607
            runtime()?.block_on(identity::init_for(&ctx, &key, name))
608
        }
609
        Command::Init { owner_home, name, owner: None } => runtime()?.block_on(identity::init(&ctx, owner_home, name)),
610
        Command::Identity { command } => runtime()?.block_on(async {
611
            match command {
612
                IdentityCmd::Create { name, contact, home, json } => identity::create(&name, &contact, home, json),
613
                IdentityCmd::Show { json } => identity::show(&ctx, json).await,
614
                IdentityCmd::Refresh { owner_home } => identity::refresh(&ctx, owner_home).await,
615
            }
616
        }),
617
        Command::Serve { bind, tls, insecure, open } => {
618
            init_logging();
619
            runtime()?.block_on(serve::serve(&ctx, bind, tls, insecure, open))
620
        }
621
        Command::Open { owner_home, no_browser, port } => runtime()?.block_on(async {
622
            if ctx.remote()?.is_some() {
623
                open::open_remote(&ctx, owner_home, !no_browser, port).await
624
            } else {
625
                open::open(&ctx, owner_home, !no_browser).await
626
            }
627
        }),
628
        Command::Mcp { agent, home } => runtime()?.block_on(mcp::run(&ctx, &agent, home)),
629
        Command::Say { body, channel, reply_to, json, owner_home } => {
630
            runtime()?.block_on(human::say(&ctx, channel, reply_to, body, owner_home, json))
631
        }
632
        Command::Inbox { follow, json, owner_home } => runtime()?.block_on(human::inbox(&ctx, follow, owner_home, json)),
633
        Command::Search { query, channel, author, since, limit, json } => {
634
            runtime()?.block_on(human::search(&ctx, &query, channel, author, since, limit, json))
635
        }
636
        Command::Api { method, path, body, owner_home } => runtime()?.block_on(human::raw(&ctx, &method, &path, body, owner_home)),
637
        Command::Project { command } => runtime()?.block_on(async {
638
            match command {
639
                ProjectCmd::Add { target, name, path, description, url, owner_home } => {
640
                    project::add(&ctx, project::Add { target, name, path, description, url }, owner_home).await
641
                }
642
                ProjectCmd::Link { project, depends_on, remove, owner_home } => {
643
                    project::link(&ctx, &project, &depends_on, remove, owner_home).await
644
                }
645
                ProjectCmd::List { json } => project::list(&ctx, json).await,
646
            }
647
        }),
648
        Command::Agent { command } => runtime()?.block_on(async {
649
            match command {
650
                AgentCmd::Add { name, kind, project, home, uid, learn_uid, expires, yes, owner_home } => {
651
                    agent::add(&ctx, agent::Add { name, kind, project, home, uid, learn_uid, expires, yes, owner_home }).await
652
                }
653
                AgentCmd::Renew { name, expires, owner_home } => agent::renew(&ctx, &name, &expires, owner_home).await,
654
                AgentCmd::List { json } => agent::list(&ctx, json).await,
655
                AgentCmd::Disable { name, owner_home } => agent::disable(&ctx, &name, owner_home).await,
656
            }
657
        }),
658
        Command::Admin { command } => runtime()?.block_on(async {
659
            match command {
660
                Admin::Verify { json } => admin::verify(&ctx, json).await,
661
                Admin::Check => admin::check(&ctx).await,
662
                Admin::Rebuild => admin::rebuild(&ctx).await,
663
            }
664
        }),
665
    }
666
}
667
668
fn version(as_json: bool) -> Result<i32> {
669
    if as_json {
670
        println!(
671
            "{}",
672
            serde_json::json!({
673
                "version": env!("CARGO_PKG_VERSION"),
674
                "build": env!("SPECTRA_BUILD_ID"),
675
                "mcp_protocol_versions": spectra_mcp::PROTOCOL_VERSIONS,
676
                "ledger_format": spectra_core::LEDGER_FORMAT,
677
            })
678
        );
679
    } else {
680
        println!("spectra {}", env!("SPECTRA_VERSION_LONG"));
681
    }
682
    Ok(0)
683
}