OXYGENHUB

Coverage / src/cli/agent.rs 91.8%

145 of 158 lines run, 14 of 36 functions · run #19 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, prints the one `oxy`
4
//! command that makes it the owner's, and records the agent only once the
5
//! owner's identity delegates to it. There is no agent without an owner.
6
7
use super::identity::{owner_home, refresh_event};
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
3021×
pub async fn add(ctx: &Ctx, a: Add) -> Result<i32> {
3121×
    if !valid_name(&a.name) {
320×
        bail!("an agent's name is lower-case letters, digits and dashes, starting with a letter or digit, at most 64");
3321×
    }
3421×
    if !KINDS.contains(&a.kind.as_str()) {
350×
        bail!("--kind is one of {}", KINDS.join(", "));
3621×
    }
37
    {
3821×
        let ledger = Ledger::open_read_only(&ctx.db()?).await?;
3921×
        let p = Principals::load(&ledger).await?;
4021×
        if p.agent_key(&a.name).is_some() {
410×
            bail!("an agent named {} already exists (spectra agent list)", a.name);
4221×
        }
4321×
        let known: Option<String> =
4421×
            sqlx::query_scalar("SELECT name FROM projects WHERE name = ?").bind(&a.project).fetch_optional(ledger.pool()).await?;
4521×
        if known.is_none() {
461×
            bail!("no project named {} (spectra project add PATH --name {})", a.project, a.project);
4720×
        }
48
    }
4920×
    let home = owner_home(ctx, a.owner_home.clone());
50
    // The agent's key, made once in its own home and reused if `add` is run again.
5120×
    let agent = if a.home.join("keys").exists() {
5219×
        KeyPair::load_home(&a.home).with_context(|| format!("reading the agent's key in {}", a.home.display()))?
53
    } else {
541×
        let pair = KeyPair::create_home(&a.home, &a.name, "")?;
551×
        println!("{} {}  {}", ui::done("Created"), ui::subject(format!("{}'s key", a.name)), ui::path(a.home.display()));
561×
        pair
57
    };
5821×
    let delegated = |id: &oxy_core::identity::Identity| id.delegates_to(&agent.key, DELEGATION_SCOPE, now_ms());
5920×
    if !delegated(&home_identity(&home)?) {
601×
        println!("{} {}", ui::caution(), ui::warn(format!("{} is not yours yet: delegate to its key, as yourself:", a.name)));
611×
        println!(
62
            "    {}",
631×
            ui::id(format!(
64
                "oxy identity delegate add {} --scope changes --expires 8h",
651×
                a.home.join("keys").join(format!("{}.identity", agent.key.to_hex())).display()
66
            ))
67
        );
681×
        let spin = ui::spinner(&format!(
691×
            "waiting for your delegation to {} (up to {} s; Ctrl-C stops, and running this again resumes)",
701×
            a.name, a.wait_secs
711×
        ));
721×
        let deadline = std::time::Instant::now() + Duration::from_secs(a.wait_secs);
73
        loop {
741×
            if home_identity(&home).is_ok_and(|id| delegated(&id)) {
750×
                spin.clear();
760×
                break;
771×
            }
781×
            if std::time::Instant::now() >= deadline {
791×
                spin.clear();
801×
                bail!("{}'s key is not delegated yet: run the command above, then this again", a.name);
810×
            }
820×
            tokio::time::sleep(Duration::from_secs(2)).await;
83
        }
8419×
    }
8519×
    let w = ctx.owner_writer(&home).await?;
8619×
    let mut events: Vec<_> = refresh_event(w.ledger(), &home).await?.into_iter().collect();
8719×
    let owner = KeyPair::load_home(&home)?;
8819×
    let mut p = identity_payload(&agent.identity);
8919×
    p["name"] = a.name.clone().into();
9019×
    p["kind"] = a.kind.into();
9119×
    p["project"] = a.project.into();
9219×
    p["home"] = a.home.display().to_string().into();
9319×
    p["owner"] = owner.key.to_hex().into();
9419×
    p["owner_name"] = owner.identity.name.clone().into();
9519×
    p["scopes"] = DEFAULT_SCOPES.into();
9619×
    if let Some(u) = a.uid {
972×
        p["uid"] = u.into();
9817×
    }
9919×
    p["learn_uid"] = a.learn_uid.into();
10019×
    let d = owner.identity.delegate(&agent.key).context("the delegation vanished")?;
10119×
    p["delegation"] = serde_json::json!({ "scope": d.scope.names(), "expires": d.expires });
10219×
    events.push(signed_event(&owner, "human", "agent.added", p));
10319×
    w.append(events).await?;
10419×
    println!("{} {}{}{}", ui::done("Added"), ui::subject(&a.name), ui::sep(), ui::author(format!("{}'s agent", owner.identity.name)));
10519×
    println!("{}", ui::kv("key", ui::hash(agent.key.to_hex())));
10619×
    let until = d.expires.map(|e| format!(" until {}", super::format::when(e))).unwrap_or_default();
10719×
    println!("{}", ui::kv("delegated", format!("{}{until}", d.scope.names().join(","))));
10819×
    println!("  {} {} {}", ui::note(), ui::dim("connect its client with"), ui::id(format!("spectra mcp --agent {}", a.name)));
10919×
    Ok(0)
11021×
}
111
112
/// An agent as `agent list` reads it, with its presence.
113
#[derive(sqlx::FromRow)]
114
struct AgentRow {
115
    name: String,
116
    key: String,
117
    kind: String,
118
    project: String,
119
    disabled_ms: Option<i64>,
120
    presence: Option<String>,
121
    status: Option<String>,
122
}
123
1245×
pub async fn list(ctx: &Ctx, json: bool) -> Result<i32> {
1255×
    let ledger = Ledger::open_read_only(&ctx.db()?).await?;
1265×
    let p = Principals::load(&ledger).await?;
1275×
    let rows: Vec<AgentRow> = sqlx::query_as(
1285×
        "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",
1295×
    )
1305×
    .fetch_all(ledger.pool())
1315×
    .await?;
1325×
    let owner = p.owner();
1335×
    let now = now_ms();
1345×
    let mut out = Vec::new();
1355×
    for AgentRow { name, key, kind, project, disabled_ms: disabled, presence, status } in rows {
1365×
        let k = oxy_core::hash::ObjectRef::from_hex(&key).context("a stored key")?;
1375×
        let state = match p.principal(&k, now) {
1383×
            Ok(_) => "ok".to_string(),
1392×
            Err(why) => why,
140
        };
1415×
        let expires = owner.and_then(|o| o.delegate(&k)).and_then(|d| d.expires);
1425×
        let who = match p.principal(&k, now) {
1433×
            Ok(pr @ Principal::Agent { .. }) => pr.display(),
1442×
            _ => format!("{name} · {}'s agent", owner.map(|o| o.name.as_str()).unwrap_or("?")),
145
        };
1465×
        let presence = if disabled.is_some() { "offline".to_string() } else { presence.unwrap_or_else(|| "offline".into()) };
1475×
        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() }));
148
    }
1495×
    if json {
1504×
        println!("{}", serde_json::Value::Array(out));
1514×
        return Ok(0);
1521×
    }
1531×
    if out.is_empty() {
1540×
        println!("{} {}", ui::note(), ui::dim("no agents yet: spectra agent add NAME --kind KIND --project PROJECT --home DIR"));
1551×
    }
1561×
    for a in out {
1571×
        let state = a["state"].as_str().unwrap_or("");
1581×
        let until = a["delegation_expires"].as_u64().map(|e| format!("{}until {}", ui::sep(), super::format::when(e))).unwrap_or_default();
1591×
        let display = a["display"].as_str().unwrap_or("");
1601×
        let (name, owner) = display.split_once(" · ").unwrap_or((display, ""));
1611×
        println!(
162
            "{} {} {}{}{}",
1631×
            marks::health(state),
1641×
            marks::presence(a["presence"].as_str().unwrap_or("offline")),
1651×
            ui::subject(name),
1661×
            ui::sep(),
1671×
            ui::author(owner)
168
        );
1691×
        if let Some(st) = a["status"].as_str() {
1700×
            println!("  {} {}", ui::note(), st);
1711×
        }
1721×
        println!(
173
            "  {}",
1741×
            ui::dim(format!(
175
                "{}{}{}{}{}{until}",
1761×
                a["kind"].as_str().unwrap_or(""),
1771×
                ui::sep(),
1781×
                a["project"].as_str().unwrap_or(""),
1791×
                ui::sep(),
1801×
                &a["key"].as_str().unwrap_or("")[..12]
181
            ))
182
        );
1831×
        if state != "ok" {
1841×
            println!("  {} {}", ui::caution(), ui::warn(state));
1851×
        }
186
    }
1871×
    Ok(0)
1885×
}
189
1902×
pub async fn disable(ctx: &Ctx, name: &str, owner_home_flag: Option<PathBuf>) -> Result<i32> {
1912×
    let home = owner_home(ctx, owner_home_flag);
1922×
    let w = ctx.owner_writer(&home).await?;
1931×
    let p = Principals::load(w.ledger()).await?;
1941×
    p.agent_key(name).with_context(|| format!("no agent named {name}"))?;
1951×
    let mut events: Vec<_> = refresh_event(w.ledger(), &home).await?.into_iter().collect();
1961×
    let owner = KeyPair::load_home(&home)?;
1971×
    events.push(signed_event(&owner, "human", "agent.disabled", serde_json::json!({ "name": name })));
1981×
    w.append(events).await?;
1991×
    println!("{} {}", ui::done("Disabled"), ui::subject(name));
2001×
    println!("  {} {}", ui::note(), ui::dim("its key is refused from now on; earlier events keep their signatures"));
2011×
    Ok(0)
2022×
}
203
20444×
pub fn valid_name(n: &str) -> bool {
20544×
    !n.is_empty()
20644×
        && n.len() <= 64
20744×
        && n.bytes().next().is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
208362×
        && n.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
20944×
}