zc2 0.0.47

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! `zc link <zakuro://…> [--yes] [--json]`: the CLI side of ADR ZC-0020 §5.
//! The same verification as the app, with a terminal prompt in place of the
//! sheet. Through the running agent (`POST /v2/handoff`, then `…/confirm`)
//! when there is one, so a link used here is used everywhere; otherwise the
//! CLI verifies it itself against the same files, under the same rules.

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)
}

/// The outcome of a confirmation, whichever path ran it.
enum Outcome {
    Done(Confirmed),
    NotAvailable { until: String, view: String },
    Failed { code: String, message: String },
}

/// The terminal sheet.
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
}

/// What to run in the terminal for a confirmed action.
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;

    // 1. Verify.
    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));
    }

    // Nothing for the agent to run: `open` and `auth/callback`.
    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 };
    };

    // Verified, but this zc cannot run it: the sheet already said so, and
    // confirming would only answer 501. The link stays unused.
    if !preview.available {
        if !json {
            println!("  Nothing changed; the link stays valid until it expires.");
        }
        return 3;
    }

    // 2. Confirm: the click.
    if !a.yes && !json && !ask("\n  Confirm?") {
        println!("  Cancelled. Nothing changed.");
        return 1;
    }
    if !a.yes && json {
        // JSON callers confirm with --yes; never prompt on a pipe.
        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,
    /// Something listens on the agent's port but `summary` timed out.
    Busy,
}

/// Running, not running, or busy. A busy agent is NOT "not running": the
/// local fallback would verify against the same used-id file while the
/// agent holds its own view of it, so `zc link` waits for the agent instead.
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() {
        // Stale agent.json: nobody listens.
        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
}

/// Verify without an agent: the account comes from the hub, the node from
/// the local node key, the used ids from the agent's file.
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();
    // Only a signed link needs the account: don't call the hub for `open`.
    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)
}

/// The signed-in account's `zakuro_user_id`, from the hub's provider summary.
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"));
    }
}