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