parley-md 0.1.2

Reference CLI for the Parley agent-to-agent messaging protocol. Installs the `parley` binary.
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use anyhow::Result;
use parley_core::pow;
use parley_mls::build_key_packages;
use std::io::Write as _;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::client::Client;
use crate::state::{load_identity, load_party_keys, load_server, save_party_keys, save_server};

pub async fn run(
    home: &Path,
    server: Option<String>,
    network: Option<String>,
    count: usize,
    handle: Option<String>,
) -> Result<()> {
    let mut server_cfg = load_server(home).unwrap_or_default();
    if let Some(url) = server {
        server_cfg.server_url = url;
    }
    if let Some(net) = network {
        server_cfg.network_id = net;
    }
    if server_cfg.server_url.is_empty() {
        anyhow::bail!("no server URL configured. Run `parley register --server https://...`.");
    }
    if server_cfg.network_id.is_empty() {
        server_cfg.network_id = "parley-mainnet".to_string();
    }
    save_server(home, &server_cfg)?;

    let identity = load_identity(home)?;
    let party = load_party_keys(home, &identity)?;
    let client = Client::new(&server_cfg, &identity)?;
    let pubkey = identity.pubkey()?;
    let network = server_cfg.network()?;

    // 0. Register identity. Two paths:
    //
    //    Probe-first via a sentinel-PoW register call. The server's
    //    idempotent fast path short-circuits BEFORE PoW verification
    //    when the pubkey is already in `agents`, so we cheaply learn
    //    whether this is a fresh identity or a re-run.
    //
    //    Either way we always run the animation + real PoW solve — it's
    //    a useful benchmark on first run and a nice way to enjoy the
    //    sequence on re-runs. We only POST the proof to the server when
    //    it would actually do something.
    let probe = client.register(1, 0, "").await;
    let already_registered = probe
        .as_ref()
        .ok()
        .and_then(|v| v.get("already_registered")?.as_bool())
        .unwrap_or(false);

    let info = client.network_info().await?;
    let pow_version = info
        .get("pow")
        .and_then(|p| p.get("version"))
        .and_then(|v| v.as_u64())
        .unwrap_or(1) as u8;
    let pow_difficulty = info
        .get("pow")
        .and_then(|p| p.get("difficulty"))
        .and_then(|v| v.as_u64())
        .unwrap_or(24) as u8;

    let nonce = solve_with_animation(pow_version, &network, &pubkey, pow_difficulty)?;
    let interactive = is_interactive_stdout();

    if already_registered {
        if interactive {
            println!("  \x1b[2midentity: already registered (proof discarded)\x1b[0m");
        } else {
            println!("identity: already registered (proof discarded)");
        }
    } else {
        client
            .register(pow_version, pow_difficulty, &pow::encode_nonce(&nonce))
            .await?;
        if interactive {
            println!("  \x1b[1;32midentity: registered\x1b[0m");
        } else {
            println!("identity: registered");
        }
    }
    println!();

    // 1. Publish KeyPackages.
    //
    // If the inventory is already full this is not really an error —
    // the user is set up and other agents can claim packages without
    // us pushing more. Treat the cap as "all set" rather than failure.
    let bundles = build_key_packages(&party, count)?;
    let packages: Vec<(Vec<u8>, Vec<u8>)> = bundles
        .iter()
        .map(|b| (b.package_id.to_vec(), b.blob.clone()))
        .collect();
    let bold = if interactive { "\x1b[1m" } else { "" };
    let dim = if interactive { "\x1b[2m" } else { "" };
    let reset = if interactive { "\x1b[0m" } else { "" };
    match client.publish_key_packages(packages).await {
        Ok(resp) => {
            save_party_keys(home, &party)?;
            println!(
                "  published {bold}{}{reset} KeyPackages ({} unclaimed on server)",
                resp.get("published").and_then(|v| v.as_u64()).unwrap_or(0),
                resp.get("unclaimed_now")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0),
            );
        }
        Err(e) if e.to_string().contains("key_package_inventory_full") => {
            println!("  {dim}KeyPackage inventory already full; no new packages needed.{reset}");
        }
        Err(e) => return Err(e),
    }
    println!("  {dim}server:{reset} {}", server_cfg.server_url);
    println!("  {dim}pubkey:{reset} {}", identity.public_b64);

    // 2. Optionally claim a handle.
    if let Some(h) = handle {
        match client.claim_handle(&h).await {
            Ok(resp) => {
                let canonical = resp
                    .get("handle")
                    .and_then(|v| v.as_str())
                    .unwrap_or(h.as_str());
                let already = resp
                    .get("already_yours")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                if already {
                    println!("handle: '{canonical}' (already yours)");
                } else {
                    println!("handle: '{canonical}' (claimed)");
                }
            }
            Err(e) => {
                eprintln!("warning: could not claim handle '{h}': {e}");
                eprintln!(
                    "(your KeyPackages are still published; other agents can add you by pubkey)"
                );
            }
        }
    }

    Ok(())
}

// =====================================================================
// PoW solver with terminal eye-candy
// =====================================================================
//
// Run the (CPU-bound) hashcash solver on a background OS thread while
// the main async task draws an animation in place. Two pieces of
// shared state:
//
// - `attempts` — total nonces tried so far (atomic counter, updated
//   every iteration by the solver via the existing pow::solve callback)
// - `best_bits` — the best leading-zero-bits we've seen (so the
//   animation can show progress toward the target difficulty even when
//   `attempts` is going up by millions)
//
// The display itself is hand-rolled ANSI: cursor-up + clear-line, no
// `crossterm` / `indicatif` dep.

/// Minimum wall time for the animation, regardless of how fast the
/// solver actually finishes. Without a floor, low-difficulty solves
/// (or registrations on a fast machine) flash by in under a frame —
/// the user-experience point of the animation is to make this feel
/// like a deliberate moment, not a hidden chore. 2.5s is long enough
/// to enjoy, short enough to not annoy on every register.
const MIN_ANIMATION: Duration = Duration::from_millis(2500);

/// True when stdout is a real terminal. False when output is piped,
/// redirected, or captured by a parent process (an LLM tool runner,
/// CI, an editor, etc.). The matrix-rain animation only makes sense
/// in the true case — in the captured case, ANSI escape codes show as
/// raw bytes and multi-line cursor manipulation looks like garbage.
fn is_interactive_stdout() -> bool {
    use std::io::IsTerminal as _;
    std::io::stdout().is_terminal()
}

fn solve_with_animation(
    version: u8,
    network: &parley_core::NetworkId,
    pubkey: &parley_core::AgentPubkey,
    difficulty: u8,
) -> Result<Vec<u8>> {
    let interactive = is_interactive_stdout();
    if interactive {
        print_intro_banner(difficulty);
    } else {
        // Plain-text mode for LLM tool-runners, pipes, CI, etc.
        // No box drawing, no color codes, no cursor manipulation.
        println!();
        println!("PARLEY · IDENTITY REGISTRATION");
        println!(
            "Computing one-shot proof of work (difficulty {difficulty}). \
             This is the protocol's anti-Sybil floor; expect ~1-3s of CPU."
        );
        println!();
    }

    let attempts = Arc::new(AtomicU64::new(0));
    let best_bits = Arc::new(AtomicU32::new(0));
    let done_flag = Arc::new(AtomicBool::new(false));
    // Wall-time the solver actually used, in microseconds. Captured
    // INSIDE the solver thread the moment the solution is found, so
    // the displayed time reflects the real PoW work — not whatever
    // the animation's minimum duration extended us to.
    let solve_micros = Arc::new(AtomicU64::new(0));

    let started = Instant::now();
    let attempts_solver = Arc::clone(&attempts);
    let best_solver = Arc::clone(&best_bits);
    let done_solver = Arc::clone(&done_flag);
    let solve_micros_solver = Arc::clone(&solve_micros);
    let version_owned = version;
    let difficulty_owned = difficulty;
    let network_owned = network.clone();
    let pubkey_owned = *pubkey;
    let started_for_solver = started;

    let solver = std::thread::spawn(move || {
        let challenge = pow::challenge_bytes(
            version_owned,
            &network_owned,
            &pubkey_owned,
            difficulty_owned,
        );
        let need = u32::from(difficulty_owned);
        let mut nonce: u64 = 0;
        loop {
            let nb = nonce.to_be_bytes();
            let bits = pow::leading_zero_bits_of_hash(&challenge, &nb);
            if bits > best_solver.load(Ordering::Relaxed) {
                best_solver.store(bits, Ordering::Relaxed);
            }
            if bits >= need {
                attempts_solver.store(nonce, Ordering::Relaxed);
                let elapsed_us =
                    u64::try_from(started_for_solver.elapsed().as_micros()).unwrap_or(u64::MAX);
                solve_micros_solver.store(elapsed_us, Ordering::Release);
                done_solver.store(true, Ordering::Release);
                return nb.to_vec();
            }
            nonce = nonce.wrapping_add(1);
            if nonce.is_multiple_of(8192) {
                attempts_solver.store(nonce, Ordering::Relaxed);
            }
        }
    });

    if interactive {
        run_matrix_animation(&attempts, &best_bits, difficulty, &done_flag, started);
    }
    // In non-interactive mode the solver thread runs to completion on
    // its own; `solver.join()` below blocks until done. No animation,
    // no per-frame redraws.

    let nonce = solver
        .join()
        .map_err(|_| anyhow::anyhow!("solver thread panicked"))?;
    let solve_elapsed = Duration::from_micros(solve_micros.load(Ordering::Acquire));
    let count = attempts.load(Ordering::Relaxed);

    if interactive {
        println!(
            "  \x1b[1;32m✓\x1b[0m proof found in \x1b[1m{:.2}s\x1b[0m  ({} hashes, {} leading zero bits)",
            solve_elapsed.as_secs_f32(),
            format_count(count),
            difficulty,
        );
    } else {
        println!(
            "proof found in {:.2}s ({} hashes, {} leading zero bits)",
            solve_elapsed.as_secs_f32(),
            format_count(count),
            difficulty,
        );
    }
    println!();
    Ok(nonce)
}

// =====================================================================
// The animation
// =====================================================================
//
// Falling-character "matrix rain" in green over a fixed-size area, with
// a real-time stats line below it. Decoupled from solver progress: the
// animation runs for at least MIN_ANIMATION even if the solver finishes
// instantly. The stats line still shows the legitimate hash count and
// best-bits-so-far throughout.

const RAIN_COLS: usize = 64;
const RAIN_ROWS: usize = 8;
const RAIN_TRAIL: usize = 7;
const RAIN_PAUSE: usize = 5; // blank rows between waves on each column
const RAIN_FRAME_MS: u64 = 55;
const TOTAL_RESERVED_LINES: usize = RAIN_ROWS + 2; // rain + blank + stats

fn run_matrix_animation(
    attempts: &Arc<AtomicU64>,
    best_bits: &Arc<AtomicU32>,
    target: u8,
    done_flag: &Arc<AtomicBool>,
    started: Instant,
) {
    use rand::Rng as _;
    let mut rng = rand::thread_rng();

    // Per-column random parameters. Speed in rows-per-frame; phase
    // staggers columns so they don't all line up.
    let cycle_len: f32 = (RAIN_ROWS + RAIN_TRAIL + RAIN_PAUSE) as f32;
    let cols: Vec<(f32, f32)> = (0..RAIN_COLS)
        .map(|_| {
            let speed = 0.25 + rng.gen::<f32>() * 0.85; // 0.25..1.10
            let phase = rng.gen::<f32>() * cycle_len;
            (speed, phase)
        })
        .collect();

    // Hide cursor, reserve our visual region.
    print!("\x1b[?25l");
    for _ in 0..TOTAL_RESERVED_LINES {
        println!();
    }

    let chars: &[u8] = b"0123456789abcdef";
    let mut frame: u64 = 0;
    loop {
        std::thread::sleep(Duration::from_millis(RAIN_FRAME_MS));
        let elapsed = started.elapsed();
        let solver_done = done_flag.load(Ordering::Acquire);
        if solver_done && elapsed >= MIN_ANIMATION {
            break;
        }

        // Move cursor back up to the top of our reserved region.
        print!("\x1b[{}A", TOTAL_RESERVED_LINES);

        // Render rain rows.
        for row in 0..RAIN_ROWS {
            print!("\x1b[2K\r  ");
            for &(speed, phase) in &cols {
                let raw = frame as f32 * speed + phase;
                let cycle_pos = raw.rem_euclid(cycle_len);
                // head_pos < 0 means head is still above the screen
                // (during pause); head moves down monotonically.
                let head_pos = cycle_pos - RAIN_PAUSE as f32;
                let dist = head_pos - row as f32;
                if dist >= 0.0 && dist < RAIN_TRAIL as f32 {
                    let ch = chars[rng.gen_range(0..chars.len())] as char;
                    let color = if dist < 0.5 {
                        // Leading edge: bright white, looks like "incoming"
                        "\x1b[1;97m"
                    } else if dist < 1.5 {
                        "\x1b[1;92m" // bold bright green
                    } else if dist < 3.5 {
                        "\x1b[32m" // green
                    } else {
                        "\x1b[2;32m" // dim green
                    };
                    print!("{color}{ch}\x1b[0m");
                } else {
                    print!(" ");
                }
            }
            println!();
        }

        // Blank separator.
        print!("\x1b[2K\r");
        println!();

        // Stats line (real numbers).
        let attempts_v = attempts.load(Ordering::Relaxed);
        let bits = best_bits.load(Ordering::Relaxed);
        let bar = bit_bar(bits, target);
        let label = if solver_done {
            "\x1b[1;32m FOUND \x1b[0m"
        } else {
            "\x1b[1;36m COMPUTING \x1b[0m"
        };
        print!("\x1b[2K\r");
        println!(
            "  [{label}]  {bar}  best: \x1b[1m{bits:>2}\x1b[0m/{target} bits   \
             \x1b[1m{:>11}\x1b[0m hashes   \x1b[2m{:.1}s\x1b[0m",
            format_count(attempts_v),
            elapsed.as_secs_f32()
        );

        let _ = std::io::stdout().flush();
        frame += 1;
    }

    // Clear the entire reserved region.
    print!("\x1b[{}A", TOTAL_RESERVED_LINES);
    for _ in 0..TOTAL_RESERVED_LINES {
        println!("\x1b[2K");
    }
    print!("\x1b[{}A", TOTAL_RESERVED_LINES);
    print!("\x1b[?25h"); // restore cursor
    let _ = std::io::stdout().flush();
}

fn print_intro_banner(_difficulty: u8) {
    let cyan = "\x1b[1;36m";
    let bold = "\x1b[1m";
    let dim = "\x1b[2m";
    let r = "\x1b[0m";
    println!();
    println!("  {cyan}{r}  {bold}PARLEY  ·  IDENTITY REGISTRATION{r}");
    println!();
    println!("  {dim}Establishing your identity on the network.{r}");
    println!();
}

/// Visual progress bar showing leading-zero-bit progress toward target.
/// Each cell = 1 bit.
fn bit_bar(have: u32, target: u8) -> String {
    let target = u32::from(target).max(1);
    let filled = have.min(target) as usize;
    let empty = (target as usize).saturating_sub(filled);
    let mut s = String::with_capacity(target as usize + 16);
    s.push_str("\x1b[32m");
    for _ in 0..filled {
        s.push('');
    }
    s.push_str("\x1b[2m");
    for _ in 0..empty {
        s.push('·');
    }
    s.push_str("\x1b[0m");
    s
}

fn format_count(n: u64) -> String {
    let s = n.to_string();
    let bytes = s.as_bytes();
    let mut out = String::with_capacity(s.len() + s.len() / 3);
    for (i, b) in bytes.iter().enumerate() {
        if i > 0 && (bytes.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(*b as char);
    }
    out
}