use crate::agent::client::AgentClient;
use crate::agent::hub::{self, HubClient};
use crate::deeplink::{self, ConfirmError, Confirmed, Context, Handoffs, LinkError, Preview};
use serde_json::{json, Value};
use std::io::{BufRead, Write};
use std::time::Duration;
const USAGE: &str = "usage: zc link <zakuro://…> [--yes] [--json]";
#[derive(Debug, Default, PartialEq)]
pub struct Args {
pub link: Option<String>,
pub yes: bool,
pub help: bool,
}
pub fn parse(args: &[String]) -> Result<Args, String> {
let mut out = Args::default();
for a in args {
match a.as_str() {
"-y" | "--yes" => out.yes = true,
"-h" | "--help" => out.help = true,
"--json" => {}
s if s.starts_with('-') => return Err(format!("unknown flag '{s}'")),
s if out.link.is_none() => out.link = Some(s.to_string()),
s => return Err(format!("unexpected argument '{s}'")),
}
}
Ok(out)
}
enum Outcome {
Done(Confirmed),
NotAvailable { until: String, view: String },
Failed { code: String, message: String },
}
pub fn format_preview(p: &Preview) -> String {
let mut out = format!("\n {}\n {}\n", p.title, p.summary);
for d in &p.details {
out.push_str(&format!(" {:<12} {}\n", d.label, d.value));
}
if let Some(exp) = p.exp {
let left = exp - chrono::Utc::now().timestamp();
if left > 0 {
out.push_str(&format!(
" {:<12} {} min left\n",
"Valid",
(left + 59) / 60
));
}
}
if !p.available {
out.push_str(&format!(
"\n Not available in this zc yet{}.\n",
p.until
.as_deref()
.map(|u| format!(" (ships with {u})"))
.unwrap_or_default()
));
}
out
}
pub fn next_steps(done: &Confirmed) -> Vec<String> {
let mut out = vec![];
if let Some(Value::Object(m)) = &done.prefill {
if let Some(p) = m.get("price_per_hour").and_then(Value::as_f64) {
out.push(format!("zc price {p}"));
}
if let Some(on) = m.get("sharing").and_then(Value::as_bool) {
out.push(if on {
"zc share".into()
} else {
"zc unshare".into()
});
}
}
out
}
fn ask(question: &str) -> bool {
print!("{question} [y/N] ");
let _ = std::io::stdout().flush();
let mut line = String::new();
if std::io::stdin().lock().read_line(&mut line).is_err() {
return false;
}
matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes")
}
pub fn run(args: &[String], json: bool) -> i32 {
let a = match parse(args) {
Ok(a) => a,
Err(e) => {
eprintln!("{e}\n{USAGE}");
return 2;
}
};
if a.help {
println!("{USAGE}\n\nVerify a zakuro:// link from the hub, show what it changes, and run it after you confirm.");
return 0;
}
let Some(link) = a.link else {
eprintln!("{USAGE}");
return 2;
};
crate::credentials::load_into_env();
let agent = match find_agent() {
AgentState::Running(c) => Some(c),
AgentState::NotRunning => None,
AgentState::Busy => {
return fail(
json,
"agent_busy",
"the Zakuro agent is running but did not answer; try again in a moment",
)
}
};
let mut local: Option<Handoffs> = None;
let preview = match &agent {
Some(c) => match c.post_raw(
"/v2/handoff",
Some(json!({ "link": link })),
Duration::from_secs(10),
) {
Ok((200, v)) => match serde_json::from_value::<Preview>(v) {
Ok(p) => p,
Err(e) => {
return fail(
json,
"invalid",
&format!("the agent's answer did not decode: {e}"),
)
}
},
Ok((_, v)) => {
return fail(
json,
v["error"]["code"].as_str().unwrap_or("error"),
v["error"]["message"]
.as_str()
.unwrap_or("the agent refused the link"),
)
}
Err(e) => return fail(json, "unreachable", &e),
},
None => {
let mut h = Handoffs::new(
crate::credentials::dir()
.map(|d| d.join("agent").join(crate::agent::core::HANDOFF_SEEN_FILE)),
);
match open_locally(&mut h, &link) {
Ok(p) => {
local = Some(h);
p
}
Err(e) => return fail(json, e.code(), &e.message()),
}
}
};
if json {
println!("{}", json!({ "event": "preview", "preview": preview }));
} else {
print!("{}", format_preview(&preview));
}
let Some(jti) = preview.jti.clone() else {
if !json && preview.act == "open" {
{
println!(
"\n Nothing changes. Open the Zakuro app to see {}.",
preview.view
);
}
}
return if preview.available { 0 } else { 3 };
};
if !preview.available {
if !json {
println!(" Nothing changed; the link stays valid until it expires.");
}
return 3;
}
if !a.yes && !json && !ask("\n Confirm?") {
println!(" Cancelled. Nothing changed.");
return 1;
}
if !a.yes && json {
println!("{}", json!({ "event": "cancelled" }));
return 1;
}
let outcome = match (&agent, local.as_mut()) {
(Some(c), _) => match c.post_raw(
&format!("/v2/handoff/{jti}/confirm"),
None,
Duration::from_secs(30),
) {
Ok((200, v)) => match serde_json::from_value::<Confirmed>(v) {
Ok(d) => Outcome::Done(d),
Err(e) => Outcome::Failed {
code: "invalid".into(),
message: e.to_string(),
},
},
Ok((501, v)) => Outcome::NotAvailable {
until: v["error"]["until"].as_str().unwrap_or_default().into(),
view: v["error"]["view"].as_str().unwrap_or_default().into(),
},
Ok((_, v)) => Outcome::Failed {
code: v["error"]["code"].as_str().unwrap_or("error").into(),
message: v["error"]["message"]
.as_str()
.unwrap_or("the agent refused")
.into(),
},
Err(e) => Outcome::Failed {
code: "unreachable".into(),
message: e,
},
},
(None, Some(h)) => match h.confirm(&jti, chrono::Utc::now().timestamp()) {
Ok(d) => Outcome::Done(d),
Err(ConfirmError::NotAvailable { until, view }) => {
Outcome::NotAvailable { until, view }
}
Err(ConfirmError::NotFound) => Outcome::Failed {
code: "not_found".into(),
message: "open the link again".into(),
},
Err(ConfirmError::Link(e)) => Outcome::Failed {
code: e.code().into(),
message: e.message(),
},
},
(None, None) => unreachable!("a signed link was verified on one path"),
};
match outcome {
Outcome::Done(d) => {
if json {
println!("{}", json!({ "event": "done", "result": d }));
} else {
println!(" ✓ Done.");
let steps = next_steps(&d);
if !steps.is_empty() {
println!(" To apply it from the terminal:");
for s in steps {
println!(" {s}");
}
}
}
0
}
Outcome::NotAvailable { until, view } => {
if json {
println!(
"{}",
json!({ "event": "not_available", "until": until, "view": view })
);
} else {
println!(" Not available in this zc yet (ships with {until}). Nothing changed; the link stays valid until it expires.");
}
3
}
Outcome::Failed { code, message } => fail(json, &code, &message),
}
}
enum AgentState {
Running(AgentClient),
NotRunning,
Busy,
}
fn find_agent() -> AgentState {
let Some(c) = crate::credentials::dir().and_then(|d| AgentClient::from_dir(&d.join("agent")))
else {
return AgentState::NotRunning;
};
if c.summary(Duration::from_secs(1)).is_ok() {
return AgentState::Running(c);
}
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], c.port()));
if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(500)).is_err() {
return AgentState::NotRunning;
}
match c.summary(Duration::from_secs(5)) {
Ok(_) => AgentState::Running(c),
Err(_) => AgentState::Busy,
}
}
fn fail(json: bool, code: &str, message: &str) -> i32 {
if json {
println!(
"{}",
json!({ "event": "error", "code": code, "message": message })
);
} else {
eprintln!("✗ {message}");
}
1
}
fn open_locally(h: &mut Handoffs, link: &str) -> Result<Preview, LinkError> {
let state_dir = crate::credentials::dir();
let api_url = std::env::var("ZAKURO_API_URL")
.ok()
.filter(|u| !u.trim().is_empty())
.or_else(|| {
hub::read_credentials(&state_dir.clone()?.join("credentials")).and_then(|c| c.api_url)
});
let env = deeplink::env_for_api_url(api_url.as_deref());
let keys = deeplink::keys_for(env).map_err(LinkError::KeyConfig)?;
let parsed = deeplink::parse_link(link)?;
let node = crate::broker::node_identity::NodeKey::load_in(state_dir.clone());
let (node_fp, node_pk) = node
.map(|k| (k.fingerprint(), k.public_b64()))
.unwrap_or_default();
let sub = if parsed.act().signed() && !keys.is_empty() {
account_sub(state_dir)
} else {
None
};
let ctx = Context {
keys: &keys,
env: env.name(),
account_sub: sub.as_deref(),
node_fp: &node_fp,
node_pubkey: &node_pk,
now: chrono::Utc::now().timestamp(),
};
h.open(link, &ctx, &deeplink::ISSUES)
}
fn account_sub(state_dir: Option<std::path::PathBuf>) -> Option<String> {
let creds = std::env::var("ZAKURO_API_KEY")
.ok()
.filter(|k| !k.trim().is_empty())
.map(|api_key| hub::Credentials {
api_key,
api_url: std::env::var("ZAKURO_API_URL").ok(),
})
.or_else(|| hub::read_credentials(&state_dir?.join("credentials")))?;
let base = creds
.api_url
.clone()
.unwrap_or_else(crate::credentials::default_api_url);
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.ok()?;
rt.block_on(async move {
let client = HubClient::new(&base, &creds.api_key, Duration::from_secs(10));
let s = client.summary("UTC").await.ok()?;
s.account.zakuro_user_id.filter(|s| !s.trim().is_empty())
})
}
#[cfg(test)]
mod tests {
use super::*;
fn args(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
#[test]
fn parses_the_link_and_flags() {
let a = parse(&args(&["zakuro://open?view=jobs", "--yes"])).unwrap();
assert_eq!(
(a.link.as_deref(), a.yes),
(Some("zakuro://open?view=jobs"), true)
);
assert!(parse(&args(&["a", "b"])).is_err());
assert!(parse(&args(&["--force"])).is_err());
}
#[test]
fn a_confirmed_budget_link_says_how_to_apply_it() {
let d = Confirmed {
status: "done".into(),
act: "share/budget".into(),
jti: "j".into(),
view: "budget".into(),
prefill: Some(json!({"price_per_hour": 120.0, "sharing": true})),
};
assert_eq!(next_steps(&d), vec!["zc price 120", "zc share"]);
}
#[test]
fn the_terminal_sheet_names_what_is_not_available() {
let link = deeplink::parse_link("zakuro://auth/callback?code=c&state=s").unwrap();
let p = deeplink::describe(&link, None, &deeplink::ISSUES);
let text = format_preview(&p);
assert!(text.contains("Finish signing in"));
assert!(text.contains("Not available in this zc yet"));
}
}