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