| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 27 |
#[arg(long, global = true)] |
| 28 |
pub plain: bool, |
| 29 |
|
| 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 |
|
| 39 |
Version { |
| 40 |
|
| 41 |
#[arg(long)] |
| 42 |
json: bool, |
| 43 |
}, |
| 44 |
|
| 45 |
|
| 46 |
Init { |
| 47 |
|
| 48 |
#[arg(long)] |
| 49 |
owner_home: Option<PathBuf>, |
| 50 |
|
| 51 |
#[arg(long)] |
| 52 |
name: Option<String>, |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
#[arg(long, value_name = "KEYID", conflicts_with = "owner_home")] |
| 57 |
owner: Option<String>, |
| 58 |
}, |
| 59 |
|
| 60 |
|
| 61 |
Connect { |
| 62 |
|
| 63 |
url: String, |
| 64 |
|
| 65 |
#[arg(long)] |
| 66 |
owner_home: Option<PathBuf>, |
| 67 |
}, |
| 68 |
|
| 69 |
Identity { |
| 70 |
#[command(subcommand)] |
| 71 |
command: IdentityCmd, |
| 72 |
}, |
| 73 |
|
| 74 |
Serve { |
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
#[arg(long)] |
| 79 |
bind: Option<String>, |
| 80 |
|
| 81 |
|
| 82 |
#[arg(long)] |
| 83 |
tls: Option<String>, |
| 84 |
|
| 85 |
#[arg(long)] |
| 86 |
insecure: bool, |
| 87 |
|
| 88 |
#[arg(long)] |
| 89 |
open: bool, |
| 90 |
}, |
| 91 |
|
| 92 |
Open { |
| 93 |
#[arg(long)] |
| 94 |
owner_home: Option<PathBuf>, |
| 95 |
|
| 96 |
#[arg(long)] |
| 97 |
no_browser: bool, |
| 98 |
|
| 99 |
|
| 100 |
#[arg(long, default_value_t = 7350)] |
| 101 |
port: u16, |
| 102 |
}, |
| 103 |
|
| 104 |
Mcp { |
| 105 |
|
| 106 |
#[arg(long)] |
| 107 |
agent: String, |
| 108 |
|
| 109 |
#[arg(long)] |
| 110 |
home: Option<PathBuf>, |
| 111 |
}, |
| 112 |
|
| 113 |
Say { |
| 114 |
|
| 115 |
body: String, |
| 116 |
|
| 117 |
#[arg(short, long)] |
| 118 |
channel: Option<String>, |
| 119 |
|
| 120 |
#[arg(long)] |
| 121 |
reply_to: Option<String>, |
| 122 |
#[arg(long)] |
| 123 |
json: bool, |
| 124 |
#[arg(long)] |
| 125 |
owner_home: Option<PathBuf>, |
| 126 |
}, |
| 127 |
|
| 128 |
Inbox { |
| 129 |
#[arg(long)] |
| 130 |
follow: bool, |
| 131 |
#[arg(long)] |
| 132 |
json: bool, |
| 133 |
#[arg(long)] |
| 134 |
owner_home: Option<PathBuf>, |
| 135 |
}, |
| 136 |
|
| 137 |
Search { |
| 138 |
query: String, |
| 139 |
#[arg(long)] |
| 140 |
channel: Option<String>, |
| 141 |
#[arg(long)] |
| 142 |
author: Option<String>, |
| 143 |
|
| 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 |
|
| 152 |
Api { |
| 153 |
method: String, |
| 154 |
path: String, |
| 155 |
|
| 156 |
#[arg(short = 'd', long = "body")] |
| 157 |
body: Option<String>, |
| 158 |
#[arg(long)] |
| 159 |
owner_home: Option<PathBuf>, |
| 160 |
}, |
| 161 |
|
| 162 |
Project { |
| 163 |
#[command(subcommand)] |
| 164 |
command: ProjectCmd, |
| 165 |
}, |
| 166 |
|
| 167 |
Agent { |
| 168 |
#[command(subcommand)] |
| 169 |
command: AgentCmd, |
| 170 |
}, |
| 171 |
|
| 172 |
Admin { |
| 173 |
#[command(subcommand)] |
| 174 |
command: Admin, |
| 175 |
}, |
| 176 |
} |
| 177 |
|
| 178 |
#[derive(Subcommand)] |
| 179 |
pub enum IdentityCmd { |
| 180 |
|
| 181 |
Show { |
| 182 |
#[arg(long)] |
| 183 |
json: bool, |
| 184 |
}, |
| 185 |
|
| 186 |
Refresh { |
| 187 |
#[arg(long)] |
| 188 |
owner_home: Option<PathBuf>, |
| 189 |
}, |
| 190 |
} |
| 191 |
|
| 192 |
#[derive(Subcommand)] |
| 193 |
pub enum ProjectCmd { |
| 194 |
|
| 195 |
Add { |
| 196 |
path: PathBuf, |
| 197 |
|
| 198 |
#[arg(long)] |
| 199 |
name: Option<String>, |
| 200 |
|
| 201 |
#[arg(long)] |
| 202 |
remote: Option<String>, |
| 203 |
#[arg(long)] |
| 204 |
owner_home: Option<PathBuf>, |
| 205 |
}, |
| 206 |
|
| 207 |
List { |
| 208 |
#[arg(long)] |
| 209 |
json: bool, |
| 210 |
}, |
| 211 |
} |
| 212 |
|
| 213 |
#[derive(Subcommand)] |
| 214 |
pub enum AgentCmd { |
| 215 |
|
| 216 |
Add { |
| 217 |
|
| 218 |
name: String, |
| 219 |
|
| 220 |
#[arg(long)] |
| 221 |
kind: String, |
| 222 |
|
| 223 |
#[arg(long)] |
| 224 |
project: String, |
| 225 |
|
| 226 |
#[arg(long)] |
| 227 |
home: PathBuf, |
| 228 |
|
| 229 |
#[arg(long)] |
| 230 |
uid: Option<u32>, |
| 231 |
|
| 232 |
#[arg(long, conflicts_with = "uid")] |
| 233 |
learn_uid: bool, |
| 234 |
|
| 235 |
#[arg(long, default_value_t = 600)] |
| 236 |
wait: u64, |
| 237 |
|
| 238 |
#[arg(long)] |
| 239 |
owner_home: Option<PathBuf>, |
| 240 |
}, |
| 241 |
|
| 242 |
List { |
| 243 |
#[arg(long)] |
| 244 |
json: bool, |
| 245 |
}, |
| 246 |
|
| 247 |
Disable { |
| 248 |
name: String, |
| 249 |
#[arg(long)] |
| 250 |
owner_home: Option<PathBuf>, |
| 251 |
}, |
| 252 |
} |
| 253 |
|
| 254 |
#[derive(Subcommand)] |
| 255 |
pub enum Admin { |
| 256 |
|
| 257 |
Verify { |
| 258 |
|
| 259 |
#[arg(long)] |
| 260 |
json: bool, |
| 261 |
}, |
| 262 |
|
| 263 |
Check, |
| 264 |
|
| 265 |
Rebuild, |
| 266 |
} |
| 267 |
|
| 268 |
|
| 269 |
pub struct Ctx { |
| 270 |
pub data: PathBuf, |
| 271 |
} |
| 272 |
|
| 273 |
impl Ctx { |
| 274 |
|
| 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 |
|
| 284 |
|
| 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 |
|
| 292 |
pub fn socket(&self) -> PathBuf { |
| 293 |
self.data.join("spectra.sock") |
| 294 |
} |
| 295 |
|
| 296 |
|
| 297 |
pub fn remote(&self) -> Result<Option<connect::ClientCfg>> { |
| 298 |
connect::load() |
| 299 |
} |
| 300 |
|
| 301 |
|
| 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 |
|
| 310 |
|
| 311 |
|
| 312 |
|
| 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 |
|
| 328 |
|
| 329 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 370 |
Remote { |
| 371 |
client: Box<spectra_mcp::client::Client>, |
| 372 |
recorded: oxy_core::identity::Identity, |
| 373 |
}, |
| 374 |
} |
| 375 |
|
| 376 |
impl Writer { |
| 377 |
|
| 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 |
|
| 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 |
|
| 394 |
|
| 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 |
|
| 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 |
|
| 427 |
|
| 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 |
|
| 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 |
|
| 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 |
} |