| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | | use super::identity::{owner_home, refresh_owner}; |
| 8 | | use super::{marks, ui, Ctx}; |
| 9 | | use anyhow::{bail, Context, Result}; |
| 10 | | use spectra_core::ids::now_ms; |
| 11 | | use spectra_core::keys::{home_identity, KeyPair}; |
| 12 | | use spectra_core::ledger::Ledger; |
| 13 | | use spectra_core::principals::{identity_payload, signed_event, Principal, Principals, DEFAULT_SCOPES, DELEGATION_SCOPE}; |
| 14 | | use std::path::PathBuf; |
| 15 | | use std::time::Duration; |
| 16 | |
|
| 17 | | pub const KINDS: &[&str] = &["claude-code", "antigravity", "kimi-code", "codex", "other"]; |
| 18 | |
|
| 19 | | pub struct Add { |
| 20 | | pub name: String, |
| 21 | | pub kind: String, |
| 22 | | pub project: String, |
| 23 | | pub home: PathBuf, |
| 24 | | pub uid: Option<u32>, |
| 25 | | pub learn_uid: bool, |
| 26 | | pub wait_secs: u64, |
| 27 | | pub owner_home: Option<PathBuf>, |
| 28 | | } |
| 29 | |
|
| 30 | 2× | pub async fn add(ctx: &Ctx, a: Add) -> Result<i32> { |
| 31 | 2× | if !valid_name(&a.name) { |
| 32 | 0× | bail!("an agent's name is lower-case letters, digits and dashes, starting with a letter or digit, at most 64"); |
| 33 | 2× | } |
| 34 | 2× | if !KINDS.contains(&a.kind.as_str()) { |
| 35 | 0× | bail!("--kind is one of {}", KINDS.join(", ")); |
| 36 | 2× | } |
| 37 | | { |
| 38 | 2× | let ledger = Ledger::open_read_only(&ctx.db()?).await?; |
| 39 | 2× | let p = Principals::load(&ledger).await?; |
| 40 | 2× | if p.agent_key(&a.name).is_some() { |
| 41 | 0× | bail!("an agent named {} already exists (spectra agent list)", a.name); |
| 42 | 2× | } |
| 43 | | } |
| 44 | 2× | let home = owner_home(ctx, a.owner_home.clone()); |
| 45 | | |
| 46 | 2× | let agent = if a.home.join("keys").exists() { |
| 47 | 1× | KeyPair::load_home(&a.home).with_context(|| format!("reading the agent's key in {}", a.home.display()))? |
| 48 | | } else { |
| 49 | 1× | let pair = KeyPair::create_home(&a.home, &a.name, "")?; |
| 50 | 1× | println!("{} {} {}", ui::done("Created"), ui::subject(format!("{}'s key", a.name)), ui::path(a.home.display())); |
| 51 | 1× | pair |
| 52 | | }; |
| 53 | 3× | let delegated = |id: &oxy_core::identity::Identity| id.delegates_to(&agent.key, DELEGATION_SCOPE, now_ms()); |
| 54 | 2× | if !delegated(&home_identity(&home)?) { |
| 55 | 1× | println!("{} {}", ui::caution(), ui::warn(format!("{} is not yours yet: delegate to its key, as yourself:", a.name))); |
| 56 | 1× | println!( |
| 57 | | " {}", |
| 58 | 1× | ui::id(format!( |
| 59 | | "oxy identity delegate add {} --scope changes --expires 8h", |
| 60 | 1× | a.home.join("keys").join(format!("{}.identity", agent.key.to_hex())).display() |
| 61 | | )) |
| 62 | | ); |
| 63 | 1× | let spin = ui::spinner(&format!( |
| 64 | 1× | "waiting for your delegation to {} (up to {} s; Ctrl-C stops, and running this again resumes)", |
| 65 | 1× | a.name, a.wait_secs |
| 66 | 1× | )); |
| 67 | 1× | let deadline = std::time::Instant::now() + Duration::from_secs(a.wait_secs); |
| 68 | | loop { |
| 69 | 1× | if home_identity(&home).is_ok_and(|id| delegated(&id)) { |
| 70 | 0× | spin.clear(); |
| 71 | 0× | break; |
| 72 | 1× | } |
| 73 | 1× | if std::time::Instant::now() >= deadline { |
| 74 | 1× | spin.clear(); |
| 75 | 1× | bail!("{}'s key is not delegated yet: run the command above, then this again", a.name); |
| 76 | 0× | } |
| 77 | 0× | tokio::time::sleep(Duration::from_secs(2)).await; |
| 78 | | } |
| 79 | 1× | } |
| 80 | 1× | let ledger = ctx.writer().await?; |
| 81 | 1× | refresh_owner(&ledger, &home).await?; |
| 82 | 1× | let owner = KeyPair::load_home(&home)?; |
| 83 | 1× | let mut p = identity_payload(&agent.identity); |
| 84 | 1× | p["name"] = a.name.clone().into(); |
| 85 | 1× | p["kind"] = a.kind.into(); |
| 86 | 1× | p["project"] = a.project.into(); |
| 87 | 1× | p["home"] = a.home.display().to_string().into(); |
| 88 | 1× | p["owner"] = owner.key.to_hex().into(); |
| 89 | 1× | p["owner_name"] = owner.identity.name.clone().into(); |
| 90 | 1× | p["scopes"] = DEFAULT_SCOPES.into(); |
| 91 | 1× | if let Some(u) = a.uid { |
| 92 | 0× | p["uid"] = u.into(); |
| 93 | 1× | } |
| 94 | 1× | p["learn_uid"] = a.learn_uid.into(); |
| 95 | 1× | let d = owner.identity.delegate(&agent.key).context("the delegation vanished")?; |
| 96 | 1× | p["delegation"] = serde_json::json!({ "scope": d.scope.names(), "expires": d.expires }); |
| 97 | 1× | ledger.append_one(signed_event(&owner, "human", "agent.added", p)).await?; |
| 98 | 1× | ledger.checkpoint().await?; |
| 99 | 1× | println!("{} {}{}{}", ui::done("Added"), ui::subject(&a.name), ui::sep(), ui::author(format!("{}'s agent", owner.identity.name))); |
| 100 | 1× | println!("{}", ui::kv("key", ui::hash(agent.key.to_hex()))); |
| 101 | 1× | let until = d.expires.map(|e| format!(" until {}", super::format::when(e))).unwrap_or_default(); |
| 102 | 1× | println!("{}", ui::kv("delegated", format!("{}{until}", d.scope.names().join(",")))); |
| 103 | 1× | println!(" {} {} {}", ui::note(), ui::dim("connect its client with"), ui::id(format!("spectra mcp --agent {}", a.name))); |
| 104 | 1× | Ok(0) |
| 105 | 2× | } |
| 106 | |
|
| 107 | 3× | pub async fn list(ctx: &Ctx, json: bool) -> Result<i32> { |
| 108 | 3× | let ledger = Ledger::open_read_only(&ctx.db()?).await?; |
| 109 | 3× | let p = Principals::load(&ledger).await?; |
| 110 | 3× | let rows: Vec<(String, String, String, String, Option<i64>)> = |
| 111 | 3× | sqlx::query_as("SELECT name, key, kind, project, disabled_ms FROM agents ORDER BY name").fetch_all(ledger.pool()).await?; |
| 112 | 3× | let owner = p.owner(); |
| 113 | 3× | let now = now_ms(); |
| 114 | 3× | let mut out = Vec::new(); |
| 115 | 3× | for (name, key, kind, project, disabled) in rows { |
| 116 | 3× | let k = oxy_core::hash::ObjectRef::from_hex(&key).context("a stored key")?; |
| 117 | 3× | let state = match p.principal(&k, now) { |
| 118 | 1× | Ok(_) => "ok".to_string(), |
| 119 | 2× | Err(why) => why, |
| 120 | | }; |
| 121 | 3× | let expires = owner.and_then(|o| o.delegate(&k)).and_then(|d| d.expires); |
| 122 | 3× | let who = match p.principal(&k, now) { |
| 123 | 1× | Ok(pr @ Principal::Agent { .. }) => pr.display(), |
| 124 | 2× | _ => format!("{name} · {}'s agent", owner.map(|o| o.name.as_str()).unwrap_or("?")), |
| 125 | | }; |
| 126 | 3× | out.push(serde_json::json!({ "name": name, "display": who, "key": key, "kind": kind, "project": project, "state": state, "delegation_expires": expires, "disabled": disabled.is_some() })); |
| 127 | | } |
| 128 | 3× | if json { |
| 129 | 2× | println!("{}", serde_json::Value::Array(out)); |
| 130 | 2× | return Ok(0); |
| 131 | 1× | } |
| 132 | 1× | if out.is_empty() { |
| 133 | 0× | println!("{} {}", ui::note(), ui::dim("no agents yet: spectra agent add NAME --kind KIND --project PROJECT --home DIR")); |
| 134 | 1× | } |
| 135 | 1× | for a in out { |
| 136 | 1× | let state = a["state"].as_str().unwrap_or(""); |
| 137 | 1× | let until = a["delegation_expires"].as_u64().map(|e| format!("{}until {}", ui::sep(), super::format::when(e))).unwrap_or_default(); |
| 138 | 1× | let display = a["display"].as_str().unwrap_or(""); |
| 139 | 1× | let (name, owner) = display.split_once(" · ").unwrap_or((display, "")); |
| 140 | 1× | println!("{} {}{}{}", marks::health(state), ui::subject(name), ui::sep(), ui::author(owner)); |
| 141 | 1× | println!( |
| 142 | | " {}", |
| 143 | 1× | ui::dim(format!( |
| 144 | | "{}{}{}{}{}{until}", |
| 145 | 1× | a["kind"].as_str().unwrap_or(""), |
| 146 | 1× | ui::sep(), |
| 147 | 1× | a["project"].as_str().unwrap_or(""), |
| 148 | 1× | ui::sep(), |
| 149 | 1× | &a["key"].as_str().unwrap_or("")[..12] |
| 150 | | )) |
| 151 | | ); |
| 152 | 1× | if state != "ok" { |
| 153 | 1× | println!(" {} {}", ui::caution(), ui::warn(state)); |
| 154 | 1× | } |
| 155 | | } |
| 156 | 1× | Ok(0) |
| 157 | 3× | } |
| 158 | |
|
| 159 | 2× | pub async fn disable(ctx: &Ctx, name: &str, owner_home_flag: Option<PathBuf>) -> Result<i32> { |
| 160 | 2× | let ledger = ctx.writer().await?; |
| 161 | 1× | let p = Principals::load(&ledger).await?; |
| 162 | 1× | p.agent_key(name).with_context(|| format!("no agent named {name}"))?; |
| 163 | 1× | let home = owner_home(ctx, owner_home_flag); |
| 164 | 1× | refresh_owner(&ledger, &home).await?; |
| 165 | 1× | let owner = KeyPair::load_home(&home)?; |
| 166 | 1× | ledger.append_one(signed_event(&owner, "human", "agent.disabled", serde_json::json!({ "name": name }))).await?; |
| 167 | 1× | ledger.checkpoint().await?; |
| 168 | 1× | println!("{} {}", ui::done("Disabled"), ui::subject(name)); |
| 169 | 1× | println!(" {} {}", ui::note(), ui::dim("its key is refused from now on; earlier events keep their signatures")); |
| 170 | 1× | Ok(0) |
| 171 | 2× | } |
| 172 | |
|
| 173 | 2× | pub fn valid_name(n: &str) -> bool { |
| 174 | 2× | !n.is_empty() |
| 175 | 2× | && n.len() <= 64 |
| 176 | 2× | && n.bytes().next().is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) |
| 177 | 26× | && n.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') |
| 178 | 2× | } |