OXYGENHUB

Coverage / src/cli/agent.rs 90.7%

127 of 140 lines run, 13 of 34 functions · run #5 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_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
302×
pub async fn add(ctx: &Ctx, a: Add) -> Result<i32> {
312×
    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");
332×
    }
342×
    if !KINDS.contains(&a.kind.as_str()) {
350×
        bail!("--kind is one of {}", KINDS.join(", "));
362×
    }
37
    {
382×
        let ledger = Ledger::open_read_only(&ctx.db()?).await?;
392×
        let p = Principals::load(&ledger).await?;
402×
        if p.agent_key(&a.name).is_some() {
410×
            bail!("an agent named {} already exists (spectra agent list)", a.name);
422×
        }
43
    }
442×
    let home = owner_home(ctx, a.owner_home.clone());
45
    // The agent's key, made once in its own home and reused if `add` is run again.
462×
    let agent = if a.home.join("keys").exists() {
471×
        KeyPair::load_home(&a.home).with_context(|| format!("reading the agent's key in {}", a.home.display()))?
48
    } else {
491×
        let pair = KeyPair::create_home(&a.home, &a.name, "")?;
501×
        println!("{} {}  {}", ui::done("Created"), ui::subject(format!("{}'s key", a.name)), ui::path(a.home.display()));
511×
        pair
52
    };
533×
    let delegated = |id: &oxy_core::identity::Identity| id.delegates_to(&agent.key, DELEGATION_SCOPE, now_ms());
542×
    if !delegated(&home_identity(&home)?) {
551×
        println!("{} {}", ui::caution(), ui::warn(format!("{} is not yours yet: delegate to its key, as yourself:", a.name)));
561×
        println!(
57
            "    {}",
581×
            ui::id(format!(
59
                "oxy identity delegate add {} --scope changes --expires 8h",
601×
                a.home.join("keys").join(format!("{}.identity", agent.key.to_hex())).display()
61
            ))
62
        );
631×
        let spin = ui::spinner(&format!(
641×
            "waiting for your delegation to {} (up to {} s; Ctrl-C stops, and running this again resumes)",
651×
            a.name, a.wait_secs
661×
        ));
671×
        let deadline = std::time::Instant::now() + Duration::from_secs(a.wait_secs);
68
        loop {
691×
            if home_identity(&home).is_ok_and(|id| delegated(&id)) {
700×
                spin.clear();
710×
                break;
721×
            }
731×
            if std::time::Instant::now() >= deadline {
741×
                spin.clear();
751×
                bail!("{}'s key is not delegated yet: run the command above, then this again", a.name);
760×
            }
770×
            tokio::time::sleep(Duration::from_secs(2)).await;
78
        }
791×
    }
801×
    let ledger = ctx.writer().await?;
811×
    refresh_owner(&ledger, &home).await?;
821×
    let owner = KeyPair::load_home(&home)?;
831×
    let mut p = identity_payload(&agent.identity);
841×
    p["name"] = a.name.clone().into();
851×
    p["kind"] = a.kind.into();
861×
    p["project"] = a.project.into();
871×
    p["home"] = a.home.display().to_string().into();
881×
    p["owner"] = owner.key.to_hex().into();
891×
    p["owner_name"] = owner.identity.name.clone().into();
901×
    p["scopes"] = DEFAULT_SCOPES.into();
911×
    if let Some(u) = a.uid {
920×
        p["uid"] = u.into();
931×
    }
941×
    p["learn_uid"] = a.learn_uid.into();
951×
    let d = owner.identity.delegate(&agent.key).context("the delegation vanished")?;
961×
    p["delegation"] = serde_json::json!({ "scope": d.scope.names(), "expires": d.expires });
971×
    ledger.append_one(signed_event(&owner, "human", "agent.added", p)).await?;
981×
    ledger.checkpoint().await?;
991×
    println!("{} {}{}{}", ui::done("Added"), ui::subject(&a.name), ui::sep(), ui::author(format!("{}'s agent", owner.identity.name)));
1001×
    println!("{}", ui::kv("key", ui::hash(agent.key.to_hex())));
1011×
    let until = d.expires.map(|e| format!(" until {}", super::format::when(e))).unwrap_or_default();
1021×
    println!("{}", ui::kv("delegated", format!("{}{until}", d.scope.names().join(","))));
1031×
    println!("  {} {} {}", ui::note(), ui::dim("connect its client with"), ui::id(format!("spectra mcp --agent {}", a.name)));
1041×
    Ok(0)
1052×
}
106
1073×
pub async fn list(ctx: &Ctx, json: bool) -> Result<i32> {
1083×
    let ledger = Ledger::open_read_only(&ctx.db()?).await?;
1093×
    let p = Principals::load(&ledger).await?;
1103×
    let rows: Vec<(String, String, String, String, Option<i64>)> =
1113×
        sqlx::query_as("SELECT name, key, kind, project, disabled_ms FROM agents ORDER BY name").fetch_all(ledger.pool()).await?;
1123×
    let owner = p.owner();
1133×
    let now = now_ms();
1143×
    let mut out = Vec::new();
1153×
    for (name, key, kind, project, disabled) in rows {
1163×
        let k = oxy_core::hash::ObjectRef::from_hex(&key).context("a stored key")?;
1173×
        let state = match p.principal(&k, now) {
1181×
            Ok(_) => "ok".to_string(),
1192×
            Err(why) => why,
120
        };
1213×
        let expires = owner.and_then(|o| o.delegate(&k)).and_then(|d| d.expires);
1223×
        let who = match p.principal(&k, now) {
1231×
            Ok(pr @ Principal::Agent { .. }) => pr.display(),
1242×
            _ => format!("{name} · {}'s agent", owner.map(|o| o.name.as_str()).unwrap_or("?")),
125
        };
1263×
        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
    }
1283×
    if json {
1292×
        println!("{}", serde_json::Value::Array(out));
1302×
        return Ok(0);
1311×
    }
1321×
    if out.is_empty() {
1330×
        println!("{} {}", ui::note(), ui::dim("no agents yet: spectra agent add NAME --kind KIND --project PROJECT --home DIR"));
1341×
    }
1351×
    for a in out {
1361×
        let state = a["state"].as_str().unwrap_or("");
1371×
        let until = a["delegation_expires"].as_u64().map(|e| format!("{}until {}", ui::sep(), super::format::when(e))).unwrap_or_default();
1381×
        let display = a["display"].as_str().unwrap_or("");
1391×
        let (name, owner) = display.split_once(" · ").unwrap_or((display, ""));
1401×
        println!("{} {}{}{}", marks::health(state), ui::subject(name), ui::sep(), ui::author(owner));
1411×
        println!(
142
            "  {}",
1431×
            ui::dim(format!(
144
                "{}{}{}{}{}{until}",
1451×
                a["kind"].as_str().unwrap_or(""),
1461×
                ui::sep(),
1471×
                a["project"].as_str().unwrap_or(""),
1481×
                ui::sep(),
1491×
                &a["key"].as_str().unwrap_or("")[..12]
150
            ))
151
        );
1521×
        if state != "ok" {
1531×
            println!("  {} {}", ui::caution(), ui::warn(state));
1541×
        }
155
    }
1561×
    Ok(0)
1573×
}
158
1592×
pub async fn disable(ctx: &Ctx, name: &str, owner_home_flag: Option<PathBuf>) -> Result<i32> {
1602×
    let ledger = ctx.writer().await?;
1611×
    let p = Principals::load(&ledger).await?;
1621×
    p.agent_key(name).with_context(|| format!("no agent named {name}"))?;
1631×
    let home = owner_home(ctx, owner_home_flag);
1641×
    refresh_owner(&ledger, &home).await?;
1651×
    let owner = KeyPair::load_home(&home)?;
1661×
    ledger.append_one(signed_event(&owner, "human", "agent.disabled", serde_json::json!({ "name": name }))).await?;
1671×
    ledger.checkpoint().await?;
1681×
    println!("{} {}", ui::done("Disabled"), ui::subject(name));
1691×
    println!("  {} {}", ui::note(), ui::dim("its key is refused from now on; earlier events keep their signatures"));
1701×
    Ok(0)
1712×
}
172
1732×
pub fn valid_name(n: &str) -> bool {
1742×
    !n.is_empty()
1752×
        && n.len() <= 64
1762×
        && n.bytes().next().is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
17726×
        && n.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
1782×
}