OXYGENHUB

Coverage / src/cli/agent.rs 92.4%

170 of 184 lines run, 22 of 50 functions · run #22 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;
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, 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
3023×
pub async fn add(ctx: &Ctx, a: Add) -> Result<i32> {
3123×
    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");
3323×
    }
3423×
    if !KINDS.contains(&a.kind.as_str()) {
350×
        bail!("--kind is one of {}", KINDS.join(", "));
3623×
    }
3723×
    let home = owner_home(ctx, a.owner_home.clone());
3823×
    let (exists, known) = match ctx.owner_client(&home).await? {
393×
        Some(c) => {
403×
            let agents = call(&c, "GET", "/api/v1/agents", None).await?;
413×
            let projects = call(&c, "GET", "/api/v1/projects", None).await?;
426×
            let has = |v: &serde_json::Value, n: &str| v.as_array().is_some_and(|l| l.iter().any(|x| x["name"] == n));
433×
            (has(&agents, &a.name), has(&projects, &a.project))
44
        }
45
        None => {
4620×
            let ledger = Ledger::open_read_only(&ctx.db()?).await?;
4720×
            let p = Principals::load(&ledger).await?;
4820×
            let known: Option<String> =
4920×
                sqlx::query_scalar("SELECT name FROM projects WHERE name = ?").bind(&a.project).fetch_optional(ledger.pool()).await?;
5020×
            (p.agent_key(&a.name).is_some(), known.is_some())
51
        }
52
    };
5323×
    if exists {
540×
        bail!("an agent named {} already exists (spectra agent list)", a.name);
5523×
    }
5623×
    if !known {
571×
        bail!("no project named {} (spectra project add PATH --name {})", a.project, a.project);
5822×
    }
59
    // The agent's key, made once in its own home and reused if `add` is run again.
6022×
    let agent = if a.home.join("keys").exists() {
6121×
        KeyPair::load_home(&a.home).with_context(|| format!("reading the agent's key in {}", a.home.display()))?
62
    } else {
631×
        let pair = KeyPair::create_home(&a.home, &a.name, "")?;
641×
        println!("{} {}  {}", ui::done("Created"), ui::subject(format!("{}'s key", a.name)), ui::path(a.home.display()));
651×
        pair
66
    };
6723×
    let delegated = |id: &oxy_core::identity::Identity| id.delegates_to(&agent.key, DELEGATION_SCOPE, now_ms());
6822×
    if !delegated(&home_identity(&home)?) {
691×
        println!("{} {}", ui::caution(), ui::warn(format!("{} is not yours yet: delegate to its key, as yourself:", a.name)));
701×
        println!(
71
            "    {}",
721×
            ui::id(format!(
73
                "oxy identity delegate add {} --scope changes --expires 8h",
741×
                a.home.join("keys").join(format!("{}.identity", agent.key.to_hex())).display()
75
            ))
76
        );
771×
        let spin = ui::spinner(&format!(
781×
            "waiting for your delegation to {} (up to {} s; Ctrl-C stops, and running this again resumes)",
791×
            a.name, a.wait_secs
801×
        ));
811×
        let deadline = std::time::Instant::now() + Duration::from_secs(a.wait_secs);
82
        loop {
831×
            if home_identity(&home).is_ok_and(|id| delegated(&id)) {
840×
                spin.clear();
850×
                break;
861×
            }
871×
            if std::time::Instant::now() >= deadline {
881×
                spin.clear();
891×
                bail!("{}'s key is not delegated yet: run the command above, then this again", a.name);
900×
            }
910×
            tokio::time::sleep(Duration::from_secs(2)).await;
92
        }
9321×
    }
9421×
    let w = ctx.owner_writer(&home).await?;
9521×
    let mut events: Vec<_> = w.refresh_event(&home).await?.into_iter().collect();
9621×
    let owner = KeyPair::load_home(&home)?;
9721×
    let mut p = identity_payload(&agent.identity);
9821×
    p["name"] = a.name.clone().into();
9921×
    p["kind"] = a.kind.into();
10021×
    p["project"] = a.project.into();
10121×
    p["home"] = a.home.display().to_string().into();
10221×
    p["owner"] = owner.key.to_hex().into();
10321×
    p["owner_name"] = owner.identity.name.clone().into();
10421×
    p["scopes"] = DEFAULT_SCOPES.into();
10521×
    if let Some(u) = a.uid {
1062×
        p["uid"] = u.into();
10719×
    }
10821×
    p["learn_uid"] = a.learn_uid.into();
10921×
    let d = owner.identity.delegate(&agent.key).context("the delegation vanished")?;
11021×
    p["delegation"] = serde_json::json!({ "scope": d.scope.names(), "expires": d.expires });
11121×
    events.push(signed_event(&owner, "human", "agent.added", p));
11221×
    w.append(events).await?;
11321×
    println!("{} {}{}{}", ui::done("Added"), ui::subject(&a.name), ui::sep(), ui::author(format!("{}'s agent", owner.identity.name)));
11421×
    println!("{}", ui::kv("key", ui::hash(agent.key.to_hex())));
11521×
    let until = d.expires.map(|e| format!(" until {}", super::format::when(e))).unwrap_or_default();
11621×
    println!("{}", ui::kv("delegated", format!("{}{until}", d.scope.names().join(","))));
11721×
    println!("  {} {} {}", ui::note(), ui::dim("connect its client with"), ui::id(format!("spectra mcp --agent {}", a.name)));
11821×
    Ok(0)
11923×
}
120
121
/// An agent as `agent list` reads it, with its presence.
122
#[derive(sqlx::FromRow)]
123
struct AgentRow {
124
    name: String,
125
    key: String,
126
    kind: String,
127
    project: String,
128
    disabled_ms: Option<i64>,
129
    presence: Option<String>,
130
    status: Option<String>,
131
}
132
1336×
pub async fn list(ctx: &Ctx, json: bool) -> Result<i32> {
1346×
    let out = match ctx.owner_client(&owner_home(ctx, None)).await? {
1352×
        Some(c) => call(&c, "GET", "/api/v1/agents", None).await?.as_array().cloned().unwrap_or_default(),
1364×
        None => list_local(ctx).await?,
137
    };
1386×
    print_list(out, json)
1396×
}
140
1414×
async fn list_local(ctx: &Ctx) -> Result<Vec<serde_json::Value>> {
1424×
    let ledger = Ledger::open_read_only(&ctx.db()?).await?;
1434×
    let p = Principals::load(&ledger).await?;
1444×
    let rows: Vec<AgentRow> = sqlx::query_as(
1454×
        "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",
1464×
    )
1474×
    .fetch_all(ledger.pool())
1484×
    .await?;
1494×
    let owner = p.owner();
1504×
    let now = now_ms();
1514×
    let mut out = Vec::new();
1524×
    for AgentRow { name, key, kind, project, disabled_ms: disabled, presence, status } in rows {
1534×
        let k = oxy_core::hash::ObjectRef::from_hex(&key).context("a stored key")?;
1544×
        let state = match p.principal(&k, now) {
1552×
            Ok(_) => "ok".to_string(),
1562×
            Err(why) => why,
157
        };
1584×
        let expires = owner.and_then(|o| o.delegate(&k)).and_then(|d| d.expires);
1594×
        let who = match p.principal(&k, now) {
1602×
            Ok(pr @ Principal::Agent { .. }) => pr.display(),
1612×
            _ => format!("{name} · {}'s agent", owner.map(|o| o.name.as_str()).unwrap_or("?")),
162
        };
1634×
        let presence = if disabled.is_some() { "offline".to_string() } else { presence.unwrap_or_else(|| "offline".into()) };
1644×
        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() }));
165
    }
1664×
    Ok(out)
1674×
}
168
1696×
fn print_list(out: Vec<serde_json::Value>, json: bool) -> Result<i32> {
1706×
    if json {
1715×
        println!("{}", serde_json::Value::Array(out));
1725×
        return Ok(0);
1731×
    }
1741×
    if out.is_empty() {
1750×
        println!("{} {}", ui::note(), ui::dim("no agents yet: spectra agent add NAME --kind KIND --project PROJECT --home DIR"));
1761×
    }
1771×
    for a in out {
1781×
        let state = a["state"].as_str().unwrap_or("");
1791×
        let until = a["delegation_expires"].as_u64().map(|e| format!("{}until {}", ui::sep(), super::format::when(e))).unwrap_or_default();
1801×
        let display = a["display"].as_str().unwrap_or("");
1811×
        let (name, owner) = display.split_once(" · ").unwrap_or((display, ""));
1821×
        println!(
183
            "{} {} {}{}{}",
1841×
            marks::health(state),
1851×
            marks::presence(a["presence"].as_str().unwrap_or("offline")),
1861×
            ui::subject(name),
1871×
            ui::sep(),
1881×
            ui::author(owner)
189
        );
1901×
        if let Some(st) = a["status"].as_str() {
1910×
            println!("  {} {}", ui::note(), st);
1921×
        }
1931×
        println!(
194
            "  {}",
1951×
            ui::dim(format!(
196
                "{}{}{}{}{}{until}",
1971×
                a["kind"].as_str().unwrap_or(""),
1981×
                ui::sep(),
1991×
                a["project"].as_str().unwrap_or(""),
2001×
                ui::sep(),
2011×
                &a["key"].as_str().unwrap_or("")[..12]
202
            ))
203
        );
2041×
        if state != "ok" {
2051×
            println!("  {} {}", ui::caution(), ui::warn(state));
2061×
        }
207
    }
2081×
    Ok(0)
2096×
}
210
2113×
pub async fn disable(ctx: &Ctx, name: &str, owner_home_flag: Option<PathBuf>) -> Result<i32> {
2123×
    let home = owner_home(ctx, owner_home_flag);
2133×
    let w = ctx.owner_writer(&home).await?;
2142×
    let known = match (w.ledger(), w.client()) {
2152×
        (_, Some(c)) => call(c, "GET", "/api/v1/agents", None).await?.as_array().is_some_and(|l| l.iter().any(|x| x["name"] == name)),
2161×
        (Some(l), None) => Principals::load(l).await?.agent_key(name).is_some(),
2170×
        (None, None) => false,
218
    };
2192×
    if !known {
2200×
        bail!("no agent named {name}");
2212×
    }
2222×
    let mut events: Vec<_> = w.refresh_event(&home).await?.into_iter().collect();
2232×
    let owner = KeyPair::load_home(&home)?;
2242×
    events.push(signed_event(&owner, "human", "agent.disabled", serde_json::json!({ "name": name })));
2252×
    w.append(events).await?;
2262×
    println!("{} {}", ui::done("Disabled"), ui::subject(name));
2272×
    println!("  {} {}", ui::note(), ui::dim("its key is refused from now on; earlier events keep their signatures"));
2282×
    Ok(0)
2293×
}
230
23147×
pub fn valid_name(n: &str) -> bool {
23247×
    !n.is_empty()
23347×
        && n.len() <= 64
23447×
        && n.bytes().next().is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
235386×
        && n.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
23647×
}