OXYGENHUB

Coverage / src/cli/agent.rs 88.8%

215 of 242 lines run, 35 of 80 functions · run #25 on main · run missed

1
//! `spectra agent`: agents as their owner's delegates (spec §8.1).
2
//!
3
//! `add` makes the agent's key pair in its own home, asks the owner to
4
//! confirm, signs the owner's successor that delegates to it, and records
5
//! both. There is no agent without an owner.
6
7
use super::identity::owner_home;
8
use super::{call, 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};
14
use std::path::PathBuf;
15
16
pub const KINDS: &[&str] = &["claude-code", "antigravity", "kimi-code", "codex", "other"];
17
18
pub struct Add {
19
    pub name: String,
20
    pub kind: String,
21
    pub project: String,
22
    pub home: PathBuf,
23
    pub uid: Option<u32>,
24
    pub learn_uid: bool,
25
    pub expires: Option<String>,
26
    pub yes: bool,
27
    pub owner_home: Option<PathBuf>,
28
}
29
30
/// `30m`, `8h`, `7d` from now, in ms; `never` is none.
313×
pub fn expiry(s: &str) -> Result<Option<u64>> {
323×
    let s = s.trim();
333×
    if s == "never" {
341×
        return Ok(None);
352×
    }
364×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
372×
    let n: u64 = n.parse().with_context(|| format!("{s} is not a length of time (30m, 8h, 7d)"))?;
382×
    let ms = match unit {
392×
        "s" => n * 1000,
402×
        "m" => n * 60_000,
412×
        "h" => n * 3_600_000,
420×
        "d" | "" => n * 86_400_000,
430×
        _ => bail!("{s} is not a length of time (30m, 8h, 7d)"),
44
    };
452×
    Ok(Some(now_ms() + ms))
463×
}
47
48
/// Ask the owner at the terminal; `yes` answers for scripts.
4925×
pub fn confirm(question: &str, yes: bool) -> Result<()> {
50
    use std::io::IsTerminal;
5125×
    if yes {
5223×
        return Ok(());
532×
    }
542×
    if !std::io::stdin().is_terminal() {
552×
        bail!("{question}: not asked, since this is not a terminal (--yes answers for a script)");
560×
    }
570×
    print!("{} {} {} ", ui::glyph("?", "?"), question, ui::dim("[y/N]"));
58
    use std::io::Write;
590×
    std::io::stdout().flush().ok();
600×
    let mut line = String::new();
610×
    std::io::stdin().read_line(&mut line)?;
620×
    if !matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes") {
630×
        bail!("not delegated: nothing was changed");
640×
    }
650×
    Ok(())
6625×
}
67
6823×
pub async fn add(ctx: &Ctx, a: Add) -> Result<i32> {
6923×
    if !valid_name(&a.name) {
700×
        bail!("an agent's name is lower-case letters, digits and dashes, starting with a letter or digit, at most 64");
7123×
    }
7223×
    if !KINDS.contains(&a.kind.as_str()) {
730×
        bail!("--kind is one of {}", KINDS.join(", "));
7423×
    }
7523×
    let home = owner_home(ctx, a.owner_home.clone());
7623×
    let (exists, known) = match ctx.owner_client(&home).await? {
773×
        Some(c) => {
783×
            let agents = call(&c, "GET", "/api/v1/agents", None).await?;
793×
            let projects = call(&c, "GET", "/api/v1/projects", None).await?;
806×
            let has = |v: &serde_json::Value, n: &str| v.as_array().is_some_and(|l| l.iter().any(|x| x["name"] == n));
813×
            (has(&agents, &a.name), has(&projects, &a.project))
82
        }
83
        None => {
8420×
            let ledger = Ledger::open_read_only(&ctx.db()?).await?;
8520×
            let p = Principals::load(&ledger).await?;
8620×
            let known: Option<String> =
8720×
                sqlx::query_scalar("SELECT name FROM projects WHERE name = ?").bind(&a.project).fetch_optional(ledger.pool()).await?;
8820×
            (p.agent_key(&a.name).is_some(), known.is_some())
89
        }
90
    };
9123×
    if exists {
920×
        bail!("an agent named {} already exists (spectra agent list)", a.name);
9323×
    }
9423×
    if !known {
951×
        bail!("no project named {} (spectra project add PATH --name {})", a.project, a.project);
9622×
    }
97
    // The agent's key, made once in its own home and reused if `add` is run again.
9822×
    let agent = if a.home.join("keys").exists() {
991×
        KeyPair::load_home(&a.home).with_context(|| format!("reading the agent's key in {}", a.home.display()))?
100
    } else {
10121×
        let pair = KeyPair::create_home(&a.home, &a.name, "")?;
10221×
        println!("{} {}  {}", ui::done("Created"), ui::subject(format!("{}'s key", a.name)), ui::path(a.home.display()));
10321×
        pair
104
    };
10522×
    let expires = a.expires.as_deref().map(expiry).transpose()?.flatten();
10622×
    let current = home_identity(&home)?;
10722×
    if current.delegate(&agent.key).map(|d| d.expires) != Some(expires) {
10822×
        let until = expires.map(|e| format!("until {}", super::format::when(e))).unwrap_or_else(|| "until you disable it".into());
10922×
        println!("{}", ui::kv("agent", format!("{}{}{}", ui::subject(&a.name), ui::sep(), ui::hash(agent.key.short(12)))));
11022×
        println!("{}", ui::kv("acts for", format!("{}{}{until}", ui::author(&current.name), ui::sep())));
11122×
        confirm(&format!("Let {} act for you", a.name), a.yes)?;
11221×
        spectra_core::keys::delegate(&home, agent.key, expires)?;
1130×
    }
11421×
    let w = ctx.owner_writer(&home).await?;
11521×
    let mut events: Vec<_> = w.refresh_event(&home).await?.into_iter().collect();
11621×
    let owner = KeyPair::load_home(&home)?;
11721×
    let mut p = identity_payload(&agent.identity);
11821×
    p["name"] = a.name.clone().into();
11921×
    p["kind"] = a.kind.into();
12021×
    p["project"] = a.project.into();
12121×
    p["home"] = a.home.display().to_string().into();
12221×
    p["owner"] = owner.key.to_hex().into();
12321×
    p["owner_name"] = owner.identity.name.clone().into();
12421×
    p["scopes"] = DEFAULT_SCOPES.into();
12521×
    if let Some(u) = a.uid {
1262×
        p["uid"] = u.into();
12719×
    }
12821×
    p["learn_uid"] = a.learn_uid.into();
12921×
    let d = owner.identity.delegate(&agent.key).context("the delegation vanished")?;
13021×
    p["delegation"] = serde_json::json!({ "expires": d.expires });
13121×
    events.push(signed_event(&owner, "human", "agent.added", p));
13221×
    w.append(events).await?;
13321×
    println!("{} {}{}{}", ui::done("Added"), ui::subject(&a.name), ui::sep(), ui::author(format!("{}'s agent", owner.identity.name)));
13421×
    println!("{}", ui::kv("key", ui::hash(agent.key.to_hex())));
13521×
    let until = d.expires.map(|e| format!("until {}", super::format::when(e))).unwrap_or_else(|| "until you disable it".into());
13621×
    println!("{}", ui::kv("delegated", until));
137
    // With Spectra on another machine the shim cannot look the home up.
13821×
    let shim = if ctx.remote()?.is_some() {
1392×
        format!("spectra mcp --agent {} --home {}", a.name, a.home.display())
140
    } else {
14119×
        format!("spectra mcp --agent {}", a.name)
142
    };
14321×
    println!("  {} {} {}", ui::note(), ui::dim("connect its client with"), ui::id(shim));
14421×
    Ok(0)
14523×
}
146
147
/// An agent as `agent list` reads it, with its presence.
148
#[derive(sqlx::FromRow)]
149
struct AgentRow {
150
    name: String,
151
    key: String,
152
    kind: String,
153
    project: String,
154
    disabled_ms: Option<i64>,
155
    presence: Option<String>,
156
    status: Option<String>,
157
}
158
1596×
pub async fn list(ctx: &Ctx, json: bool) -> Result<i32> {
1606×
    let out = match ctx.owner_client(&owner_home(ctx, None)).await? {
1612×
        Some(c) => call(&c, "GET", "/api/v1/agents", None).await?.as_array().cloned().unwrap_or_default(),
1624×
        None => list_local(ctx).await?,
163
    };
1646×
    print_list(out, json)
1656×
}
166
1674×
async fn list_local(ctx: &Ctx) -> Result<Vec<serde_json::Value>> {
1684×
    let ledger = Ledger::open_read_only(&ctx.db()?).await?;
1694×
    let p = Principals::load(&ledger).await?;
1704×
    let rows: Vec<AgentRow> = sqlx::query_as(
1714×
        "SELECT a.name, a.key, a.kind, a.project, a.disabled_ms, p.state AS presence, p.status_text AS status FROM agents a LEFT JOIN presence p ON p.agent = a.name ORDER BY a.name",
1724×
    )
1734×
    .fetch_all(ledger.pool())
1744×
    .await?;
1754×
    let owner = p.owner();
1764×
    let now = now_ms();
1774×
    let mut out = Vec::new();
1784×
    for AgentRow { name, key, kind, project, disabled_ms: disabled, presence, status } in rows {
1794×
        let k = spectra_core::identity::KeyId::from_hex(&key).context("a stored key")?;
1804×
        let state = match p.principal(&k, now) {
1812×
            Ok(_) => "ok".to_string(),
1822×
            Err(why) => why,
183
        };
1844×
        let expires = owner.and_then(|o| o.delegate(&k)).and_then(|d| d.expires);
1854×
        let who = match p.principal(&k, now) {
1862×
            Ok(pr @ Principal::Agent { .. }) => pr.display(),
1872×
            _ => format!("{name} · {}'s agent", owner.map(|o| o.name.as_str()).unwrap_or("?")),
188
        };
1894×
        let presence = if disabled.is_some() { "offline".to_string() } else { presence.unwrap_or_else(|| "offline".into()) };
1904×
        out.push(serde_json::json!({ "name": name, "display": who, "key": key, "kind": kind, "project": project, "state": state, "presence": presence, "status": status, "delegation_expires": expires, "disabled": disabled.is_some() }));
191
    }
1924×
    Ok(out)
1934×
}
194
1956×
fn print_list(out: Vec<serde_json::Value>, json: bool) -> Result<i32> {
1966×
    if json {
1975×
        println!("{}", serde_json::Value::Array(out));
1985×
        return Ok(0);
1991×
    }
2001×
    if out.is_empty() {
2010×
        println!("{} {}", ui::note(), ui::dim("no agents yet: spectra agent add NAME --kind KIND --project PROJECT --home DIR"));
2021×
    }
2031×
    for a in out {
2041×
        let state = a["state"].as_str().unwrap_or("");
2051×
        let until = a["delegation_expires"].as_u64().map(|e| format!("{}until {}", ui::sep(), super::format::when(e))).unwrap_or_default();
2061×
        let display = a["display"].as_str().unwrap_or("");
2071×
        let (name, owner) = display.split_once(" · ").unwrap_or((display, ""));
2081×
        println!(
209
            "{} {} {}{}{}",
2101×
            marks::health(state),
2111×
            marks::presence(a["presence"].as_str().unwrap_or("offline")),
2121×
            ui::subject(name),
2131×
            ui::sep(),
2141×
            ui::author(owner)
215
        );
2161×
        if let Some(st) = a["status"].as_str() {
2170×
            println!("  {} {}", ui::note(), st);
2181×
        }
2191×
        println!(
220
            "  {}",
2211×
            ui::dim(format!(
222
                "{}{}{}{}{}{until}",
2231×
                a["kind"].as_str().unwrap_or(""),
2241×
                ui::sep(),
2251×
                a["project"].as_str().unwrap_or(""),
2261×
                ui::sep(),
2271×
                &a["key"].as_str().unwrap_or("")[..12]
228
            ))
229
        );
2301×
        if state != "ok" {
2311×
            println!("  {} {}", ui::caution(), ui::warn(state));
2321×
        }
233
    }
2341×
    Ok(0)
2356×
}
236
2373×
pub async fn disable(ctx: &Ctx, name: &str, owner_home_flag: Option<PathBuf>) -> Result<i32> {
2383×
    let home = owner_home(ctx, owner_home_flag);
2393×
    let w = ctx.owner_writer(&home).await?;
2402×
    let known = match (w.ledger(), w.client()) {
2412×
        (_, Some(c)) => call(c, "GET", "/api/v1/agents", None).await?.as_array().is_some_and(|l| l.iter().any(|x| x["name"] == name)),
2421×
        (Some(l), None) => Principals::load(l).await?.agent_key(name).is_some(),
2430×
        (None, None) => false,
244
    };
2452×
    if !known {
2460×
        bail!("no agent named {name}");
2472×
    }
248
    // Stop delegating to its key too, where the owner's identity names it.
2492×
    if let Some(key) = agent_key(&w, name).await? {
2502×
        if home_identity(&home)?.delegate(&key).is_some() {
2512×
            spectra_core::keys::undelegate(&home, key)?;
2520×
        }
2530×
    }
2542×
    let mut events: Vec<_> = w.refresh_event(&home).await?.into_iter().collect();
2552×
    let owner = KeyPair::load_home(&home)?;
2562×
    events.push(signed_event(&owner, "human", "agent.disabled", serde_json::json!({ "name": name })));
2572×
    w.append(events).await?;
2582×
    println!("{} {}", ui::done("Disabled"), ui::subject(name));
2592×
    println!("  {} {}", ui::note(), ui::dim("its key is refused from now on; earlier events keep their signatures"));
2602×
    Ok(0)
2613×
}
262
263
/// An agent's key by name, from the daemon or the ledger here.
2643×
async fn agent_key(w: &super::Writer, name: &str) -> Result<Option<spectra_core::identity::KeyId>> {
2653×
    Ok(match (w.client(), w.ledger()) {
2661×
        (Some(c), _) => call(c, "GET", "/api/v1/agents", None).await?.as_array().and_then(|l| {
2672×
            l.iter().find(|x| x["name"] == name).and_then(|x| x["key"].as_str().and_then(spectra_core::identity::KeyId::from_hex))
2681×
        }),
2692×
        (None, Some(l)) => Principals::load(l).await?.agent_key(name),
2700×
        (None, None) => None,
271
    })
2723×
}
273
274
/// `spectra agent renew NAME --expires 8h`: the owner's successor with a
275
/// new expiry for the agent's key, recorded.
2761×
pub async fn renew(ctx: &Ctx, name: &str, expires: &str, owner_home_flag: Option<PathBuf>) -> Result<i32> {
2771×
    let home = owner_home(ctx, owner_home_flag);
2781×
    let w = ctx.owner_writer(&home).await?;
2791×
    let key = agent_key(&w, name).await?.with_context(|| format!("no agent named {name}"))?;
2801×
    let expires = expiry(expires)?;
2811×
    spectra_core::keys::delegate(&home, key, expires)?;
2821×
    let events: Vec<_> = w.refresh_event(&home).await?.into_iter().collect();
2831×
    w.append(events).await?;
2841×
    let until = expires.map(|e| format!("until {}", super::format::when(e))).unwrap_or_else(|| "until you disable it".into());
2851×
    println!("{} {}{}{}", ui::done("Renewed"), ui::subject(name), ui::sep(), until);
2861×
    Ok(0)
2871×
}
288
28946×
pub fn valid_name(n: &str) -> bool {
29046×
    !n.is_empty()
29146×
        && n.len() <= 64
29246×
        && n.bytes().next().is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
293371×
        && n.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
29446×
}