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