zc2 0.0.27

P2P compute broker with credit-based 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
//! `zc agent install | uninstall | status` (spec §6.1).

use crate::agent::client::AgentClient;
use crate::agent::config::AgentConfig;
use crate::agent::launchd::Launchctl;
use std::path::Path;
use std::time::{Duration, Instant};

pub fn format_status(s: &serde_json::Value) -> String {
    let m = &s["this_mac"];
    let mut out = format!(
        "  This Mac   {} · broker {} · workers {}/{} running ({} busy)\n",
        if m["sharing"] == true {
            "sharing"
        } else {
            "paused"
        },
        m["broker"].as_str().unwrap_or("?"),
        m["workers"]["running"],
        m["workers"]["desired"],
        m["workers"]["busy"],
    );
    let price = &s["prices"]["this_mac"];
    if let Some(p) = price["effective_per_hour"].as_f64() {
        out += &format!(
            "  Price      {p} cr/h ({})\n",
            price["state"].as_str().unwrap_or("?")
        );
    }
    if s["account"].is_object() {
        out += &format!(
            "  Account    {} · {} credits\n",
            s["account"]["username"].as_str().unwrap_or("?"),
            s["account"]["credits_balance"]
        );
    }
    if s["earnings"].is_object() {
        out += &format!(
            "  Earnings   {} today · {} last 7 days\n",
            s["earnings"]["today"], s["earnings"]["last_7d"]
        );
    }
    out += &format!(
        "  Devices    {}/{} online\n",
        s["devices_online"], s["devices_total"]
    );
    for p in s["problems"].as_array().into_iter().flatten() {
        let hint = p["hint"]
            .as_str()
            .map(|h| format!("{h}"))
            .unwrap_or_default();
        out += &format!("  ! {}{hint}\n", p["message"].as_str().unwrap_or(""));
    }
    out
}

pub fn status(json: bool) -> i32 {
    let Some(dir) = crate::credentials::dir().map(|d| d.join("agent")) else {
        eprintln!("zc agent: no HOME or ZAKURO_HOME");
        return 1;
    };
    let summary = AgentClient::from_dir(&dir)
        .ok_or_else(|| "no ~/.zakuro/agent/agent.json".to_string())
        .and_then(|c| c.summary(Duration::from_secs(2)));
    match summary {
        Ok(s) if json => {
            println!("{}", serde_json::to_string_pretty(&s).unwrap_or_default());
            0
        }
        Ok(s) => {
            print!("{}", format_status(&s));
            0
        }
        Err(e) => {
            eprintln!("zc agent is not reachable: {e}");
            1
        }
    }
}

/// The install logic, minus anything macOS-specific: `install_and_wait`,
/// then a one-line report. Platform-neutral so it runs and is tested on
/// every OS; only the no-arg `install()` below is macOS-gated.
pub fn install_with(
    launchctl: Launchctl,
    domain: &str,
    exe: &Path,
    home: &Path,
    env: &[(&str, String)],
    cfg: &AgentConfig,
) -> i32 {
    match install_and_wait(launchctl, domain, exe, home, env, cfg) {
        Ok(port) => {
            println!(
                "✓ zc agent is running on 127.0.0.1:{port} (launchd {})",
                crate::agent::launchd::LABEL
            );
            0
        }
        Err(e) => {
            eprintln!("{e}");
            1
        }
    }
}

/// Write the plist via `crate::agent::launchd::install`, then wait up to 5 s
/// for the agent to answer. The port returned is read back from `agent.json`
/// once the agent answers on it: the port the agent launchd started really
/// bound, whatever the installing shell's config asked for.
pub fn install_and_wait(
    launchctl: Launchctl,
    domain: &str,
    exe: &Path,
    home: &Path,
    env: &[(&str, String)],
    cfg: &AgentConfig,
) -> Result<u16, String> {
    crate::agent::launchd::install(launchctl, domain, exe, home, env, &cfg.dir, cfg.port)
        .map_err(|e| format!("zc agent install: {e}"))?;
    wait_for_agent(&cfg.dir, Duration::from_secs(5)).ok_or_else(|| {
        format!(
            "zc agent was installed but did not answer within 5 s; see {}",
            cfg.dir.join(crate::agent::files::LOG_FILE).display()
        )
    })
}

/// Poll the agent that `agent.json` in `dir` names until it answers, and
/// return the port it answered on.
pub fn wait_for_agent(dir: &Path, timeout: Duration) -> Option<u16> {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if let Some(c) = AgentClient::from_dir(dir) {
            if c.summary(Duration::from_secs(1)).is_ok() {
                return Some(c.port());
            }
        }
        std::thread::sleep(Duration::from_millis(250));
    }
    None
}

#[cfg(not(target_os = "macos"))]
pub fn install() -> i32 {
    eprintln!("zc agent install is not supported on this platform yet");
    2
}

#[cfg(target_os = "macos")]
pub fn install() -> i32 {
    let cfg = match AgentConfig::from_env() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("zc agent install: {e}");
            return 1;
        }
    };
    let home = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default());
    let exe = match std::env::current_exe() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("zc agent install: {e}");
            return 1;
        }
    };
    let env = crate::agent::launchd::carried_env(|k| std::env::var(k).ok());
    install_with(
        &crate::agent::launchd::run_launchctl,
        &crate::agent::launchd::gui_domain(),
        &exe,
        &home,
        &env,
        &cfg,
    )
}

/// Stop sharing first (drain, bounded by spec §6.5's timeouts), then remove
/// the LaunchAgent via `crate::agent::launchd::uninstall`. `~/.zakuro/agent/`
/// is kept. Platform-neutral so it runs and is tested on every OS; only the
/// no-arg `uninstall()` below is macOS-gated.
pub fn uninstall_with(launchctl: Launchctl, domain: &str, home: &Path, cfg: &AgentConfig) -> i32 {
    if let Some(c) = AgentClient::from_dir(&cfg.dir) {
        if c.put(
            "/v1/sharing",
            serde_json::json!({ "on": false }),
            Duration::from_secs(5),
        )
        .is_ok()
        {
            let t = &cfg.timings;
            let bound = t.drain_timeout + t.kill_grace + t.broker_stop_wait;
            println!("  draining workers (up to {} s)…", bound.as_secs());
            let deadline = Instant::now() + bound;
            while Instant::now() < deadline {
                match c.summary(Duration::from_secs(2)) {
                    Ok(s)
                        if s["this_mac"]["broker"] != "running"
                            && s["this_mac"]["workers"]["running"] == 0 =>
                    {
                        break
                    }
                    Err(_) => break,
                    _ => std::thread::sleep(Duration::from_secs(1)),
                }
            }
        }
    }
    match crate::agent::launchd::uninstall(launchctl, domain, home) {
        Ok(()) => {
            println!("✓ zc agent uninstalled ({} kept)", cfg.dir.display());
            0
        }
        Err(e) => {
            eprintln!("zc agent uninstall: {e}");
            1
        }
    }
}

#[cfg(not(target_os = "macos"))]
pub fn uninstall() -> i32 {
    eprintln!("zc agent uninstall is not supported on this platform yet");
    2
}

#[cfg(target_os = "macos")]
pub fn uninstall() -> i32 {
    let cfg = match AgentConfig::from_env() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("zc agent uninstall: {e}");
            return 1;
        }
    };
    let home = std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default());
    uninstall_with(
        &crate::agent::launchd::run_launchctl,
        &crate::agent::launchd::gui_domain(),
        &home,
        &cfg,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::client::tests::AgentGuard;
    use crate::agent::config::AgentConfig;
    use crate::agent::files::tests::tmp;

    #[test]
    fn status_prints_the_essentials_and_every_problem() {
        let fixture: serde_json::Value =
            serde_json::from_str(include_str!("../../docs/agent-api/summary.v1.json")).unwrap();
        let out = super::format_status(&fixture);
        assert!(
            out.contains("sharing · broker running · workers 2/2 running (1 busy)"),
            "{out}"
        );
        assert!(out.contains("18 cr/h (set)"), "{out}");
        assert!(out.contains("jean · 1240.5 credits"), "{out}");
        assert!(out.contains("12.4 today · 88.1 last 7 days"), "{out}");
        assert!(out.contains("2/3 online"), "{out}");
        assert!(
            out.contains("! uv is not installed — brew install uv"),
            "{out}"
        );
    }

    /// A fake `launchctl` that records every call it receives and always
    /// reports success.
    struct FakeLaunchctl {
        calls: std::sync::Mutex<Vec<Vec<String>>>,
    }

    impl FakeLaunchctl {
        fn new() -> Self {
            Self {
                calls: std::sync::Mutex::new(vec![]),
            }
        }

        fn call(&self, args: &[&str]) -> std::io::Result<std::process::ExitStatus> {
            self.calls
                .lock()
                .unwrap()
                .push(args.iter().map(|s| s.to_string()).collect());
            std::process::Command::new("true").status()
        }

        fn calls(&self) -> Vec<Vec<String>> {
            self.calls.lock().unwrap().clone()
        }
    }

    /// Like `client::tests::idle_agent`, but returns the `AgentConfig` too so
    /// `uninstall_with` can be pointed at this agent's directory and short
    /// drain timings.
    fn running_agent() -> (AgentConfig, AgentGuard) {
        let free = || {
            std::net::TcpListener::bind("127.0.0.1:0")
                .unwrap()
                .local_addr()
                .unwrap()
                .port()
        };
        let sleeper = vec![
            "sh".to_string(),
            "-c".to_string(),
            "exec sleep 30".to_string(),
        ];
        let mut cfg = AgentConfig::for_dirs(tmp("cli-uninstall"));
        cfg.port = 0;
        cfg.broker_port = free();
        cfg.max_workers = 3;
        cfg.broker_argv = sleeper.clone();
        cfg.worker_template = sleeper;
        cfg.worker_template_overridden = true;
        cfg.timings.shutdown_wait = std::time::Duration::from_secs(2);
        cfg.timings.drain_timeout = std::time::Duration::from_secs(1);
        cfg.timings.kill_grace = std::time::Duration::from_secs(0);
        cfg.timings.broker_stop_wait = std::time::Duration::from_secs(0);
        let (_, _, stop, thread) =
            crate::agent::run::start_background(cfg.clone()).expect("agent starts");
        (cfg, AgentGuard::new(stop, thread))
    }

    #[test]
    fn uninstall_turns_sharing_off_through_the_client_before_booting_out() {
        let (cfg, guard) = running_agent();
        let client =
            crate::agent::client::AgentClient::from_dir(&cfg.dir).expect("agent.json written");
        let t = std::time::Duration::from_secs(2);
        // Sharing on first, so a bootout that ran before the pause would see it on.
        client
            .put("/v1/sharing", serde_json::json!({ "on": true }), t)
            .unwrap();
        assert_eq!(client.summary(t).unwrap()["this_mac"]["sharing"], true);

        let home = tmp("cli-uninstall-home");
        std::fs::create_dir_all(&home).unwrap();
        let fake = FakeLaunchctl::new();
        // What the agent reported each time bootout ran. The fake bootout
        // doesn't stop the agent, so it can still be asked.
        let sharing_at_bootout = std::sync::Mutex::new(vec![]);
        let launchctl = |args: &[&str]| {
            if args.first() == Some(&"bootout") {
                sharing_at_bootout.lock().unwrap().push(
                    client
                        .summary(t)
                        .ok()
                        .map(|s| s["this_mac"]["sharing"].clone()),
                );
            }
            fake.call(args)
        };
        let code = uninstall_with(&launchctl, "gui/501", &home, &cfg);
        assert_eq!(code, 0);

        assert_eq!(
            *sharing_at_bootout.lock().unwrap(),
            vec![Some(serde_json::json!(false))],
            "one bootout, and sharing was already off when it ran"
        );
        assert_eq!(
            fake.calls().last().unwrap(),
            &vec!["bootout", "gui/501/ai.zakuro.agent"]
        );
        drop(guard);
    }

    /// The port `install` reports is the one the agent launchd started really
    /// bound, read back from `agent.json` once it answers, not the port in the
    /// installing shell's config.
    #[test]
    fn install_reports_the_port_the_launched_agent_answers_on() {
        let home = tmp("cli-install-home");
        std::fs::create_dir_all(&home).unwrap();
        // What "launchd" starts: the same agent dir, on a port of its own.
        let launched = crate::agent::client::tests::sleeper_cfg("cli-install");
        let mut asked = launched.clone();
        asked.port = 1; // never what an agent binds
        let started = std::sync::Mutex::new(None);
        let launchctl = |args: &[&str]| {
            if args.first() == Some(&"bootstrap") {
                let (_, _, stop, thread) =
                    crate::agent::run::start_background(launched.clone()).expect("agent starts");
                *started.lock().unwrap() = Some(AgentGuard::new(stop, thread));
            }
            // `print` exits non-zero: no old agent is loaded, so `install`
            // bootstraps straight away instead of waiting for it.
            let ok = args.first() != Some(&"print");
            std::process::Command::new(if ok { "true" } else { "false" }).status()
        };

        let port = install_and_wait(
            &launchctl,
            "gui/501",
            std::path::Path::new("/usr/local/bin/zc"),
            &home,
            &[],
            &asked,
        )
        .expect("the launched agent answers");

        let bound = crate::agent::files::load_json::<crate::agent::files::AgentFile>(
            &asked.dir.join(crate::agent::files::AGENT_FILE),
        )
        .unwrap()
        .port;
        assert_eq!(port, bound, "the port the launched agent answers on");
        assert_ne!(port, asked.port, "not the port the config asked for");
        drop(started);
    }
}