newt-agent 0.8.0

Newt-Agent — free, friendly, local agentic coder (vi to Hermes's emacs)
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! `newt dock` — the approved-dock management surface (newt-web mesh docking,
//! requirement 5 / Phase 3).
//!
//! A dock is the operator's standing, revocable approval for another of their
//! own agents to surface its sessions into a hub cockpit over agent-mesh. The
//! mesh handshake already proves same-operator; these commands record *which*
//! peer the operator meant, signed by the root key so the hub can refuse an
//! unapproved peer and drop a revoked one.
//!
//! Every write is root-key-gated and terminal-confirmed exactly like
//! `newt ocap revoke-credential`: a headless session cannot approve or revoke,
//! because it cannot be asked. `approve` additionally derives the 6-word SAS
//! from the peer's pubkey so the operator confirms the exact key, not a label.

use std::path::{Path, PathBuf};

use clap::Subcommand;

use newt_core::dock_registry;

/// Least authority by default: a dock may only mirror (read) unless the operator
/// explicitly asks for inject. Widening to `mirror-inject` is a deliberate choice
/// on the command line, never the default.
const DEFAULT_SCOPE: &str = "mirror";

#[derive(Subcommand, Debug)]
pub enum DockCmd {
    /// Approve a peer agent to dock into this hub. Shows the peer pubkey's 6-word
    /// mnemonic — the SAME words the peer's own newt-web prints when it binds its
    /// dock service — for you to compare, then (on confirmation) writes a signed
    /// approval to `~/.newt/ocap/docks.d/peers.toml`.
    ///
    /// `--staged` promotes a host that uplinked to this hub and was staged
    /// (see `newt dock list`), taking its key and name from the staged entry.
    Approve {
        /// The peer's mesh agent public key, 64 hex chars (the `pubkey` the
        /// peer's `newt-web` prints when it binds its dock service).
        #[arg(long, value_name = "HEX", required_unless_present = "staged")]
        pubkey: Option<String>,
        /// A staged host's agent fingerprint, or any unambiguous prefix of one.
        #[arg(long, value_name = "PEER-SHORT", conflicts_with = "pubkey")]
        staged: Option<String>,
        /// Operator-facing label for the peer (e.g. `laptop-b`). Defaults to a
        /// staged host's instance name.
        #[arg(long, value_name = "LABEL", required_unless_present = "staged")]
        label: Option<String>,
        /// Approval scope: `mirror` (read only, the default) or `mirror-inject`
        /// (also enqueue prompts, D2). Least authority by default.
        #[arg(long, default_value = DEFAULT_SCOPE)]
        scope: String,
        /// Operator root key. Default: `~/.newt/identity.pem`.
        #[arg(long, env = "NEWT_OPERATOR_KEY", value_name = "FILE")]
        operator_key_path: Option<PathBuf>,
    },
    /// Revoke one approved dock by peer-fingerprint prefix. The row is flagged
    /// and re-signed (not deleted) and its generation bumps, so a live dock is
    /// dropped at the responder's next re-check, not merely refused next time.
    Revoke {
        /// Peer agent fingerprint, or any unambiguous prefix of one.
        #[arg(value_name = "PEER-SHORT")]
        peer: String,
        /// Operator root key. Default: `~/.newt/identity.pem`.
        #[arg(long, env = "NEWT_OPERATOR_KEY", value_name = "FILE")]
        operator_key_path: Option<PathBuf>,
    },
    /// Revoke EVERY live dock atomically — the `/undock all` kill-switch.
    RevokeAll {
        /// Operator root key. Default: `~/.newt/identity.pem`.
        #[arg(long, env = "NEWT_OPERATOR_KEY", value_name = "FILE")]
        operator_key_path: Option<PathBuf>,
    },
    /// List the live (approved, non-revoked) docks. Read-only, no terminal gate.
    List {
        /// Operator root key. Default: `~/.newt/identity.pem`.
        #[arg(long, env = "NEWT_OPERATOR_KEY", value_name = "FILE")]
        operator_key_path: Option<PathBuf>,
    },
}

/// Dispatch `newt dock <cmd>`.
pub fn run(cmd: DockCmd, config: Option<&Path>) -> anyhow::Result<i32> {
    match cmd {
        DockCmd::Approve {
            pubkey,
            staged,
            label,
            scope,
            operator_key_path,
        } => {
            let (pubkey, label, pairing) = match staged {
                Some(prefix) => {
                    let host = staged_host(&config_path(config)?, &prefix)?;
                    let Some(pairing) = host.pairing() else {
                        anyhow::bail!(
                            "host `{}` has not completed pairing: run `newt-mesh dock` on it",
                            host.peer_label
                        );
                    };
                    (
                        host.peer_pubkey,
                        label.unwrap_or(host.peer_label),
                        Some(pairing),
                    )
                }
                None => (pubkey.unwrap_or_default(), label.unwrap_or_default(), None),
            };
            run_approve(
                &pubkey,
                &label,
                &scope,
                pairing.as_ref(),
                operator_key_path,
                config,
            )
        }
        DockCmd::Revoke {
            peer,
            operator_key_path,
        } => run_revoke(&peer, operator_key_path, config),
        DockCmd::RevokeAll { operator_key_path } => run_revoke_all(operator_key_path, config),
        DockCmd::List { operator_key_path } => run_list(operator_key_path, config),
    }
}

/// The one live staged host whose fingerprint starts with `prefix`.
fn staged_host(config_path: &Path, prefix: &str) -> anyhow::Result<dock_registry::StagedHost> {
    let mut matches: Vec<_> =
        dock_registry::staged_hosts(config_path, std::time::SystemTime::now())
            .into_iter()
            .filter(|host| !prefix.is_empty() && host.peer_agent_fingerprint.starts_with(prefix))
            .collect();
    match matches.len() {
        1 => Ok(matches.remove(0)),
        0 => anyhow::bail!("no staged host matches `{prefix}` (see `newt dock list`)"),
        n => anyhow::bail!("`{prefix}` matches {n} staged hosts; use a longer prefix"),
    }
}

fn config_path(config: Option<&Path>) -> anyhow::Result<PathBuf> {
    config
        .map(Path::to_path_buf)
        .or_else(newt_core::Config::user_config_path)
        .ok_or_else(|| anyhow::anyhow!("cannot locate the newt config directory"))
}

fn load_root(operator_key_path: Option<PathBuf>) -> anyhow::Result<newt_identity::UserKey> {
    let key_path = match operator_key_path {
        Some(path) => path,
        None => newt_identity::default_key_path()?,
    };
    Ok(newt_identity::load_user_key(&key_path)?)
}

/// Parse 64 lowercase/uppercase hex chars into a 32-byte agent public key.
fn parse_pubkey(hex: &str) -> anyhow::Result<[u8; 32]> {
    let hex = hex.trim();
    if hex.len() != 64 {
        anyhow::bail!("pubkey must be 64 hex chars (32 bytes), got {}", hex.len());
    }
    let mut out = [0u8; 32];
    for (i, byte) in out.iter_mut().enumerate() {
        *byte = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16)
            .map_err(|_| anyhow::anyhow!("pubkey is not valid hex"))?;
    }
    Ok(out)
}

/// `newt dock approve` — derive + show the SAS, confirm at the terminal, then
/// write the signed approval.
fn run_approve(
    pubkey_hex: &str,
    label: &str,
    scope: &str,
    pairing: Option<&dock_registry::Pairing>,
    operator_key_path: Option<PathBuf>,
    config: Option<&Path>,
) -> anyhow::Result<i32> {
    let config_path = config_path(config)?;
    let root_key = load_root(operator_key_path)?;
    let pubkey = parse_pubkey(pubkey_hex)?;
    let scope = dock_registry::DockScope::parse(scope)?;

    let issuer = root_key.public().fingerprint().hex();
    let peer_fp = dock_registry::agent_fingerprint_of_pubkey(&pubkey);
    // Fresh per-ceremony secrets so the SAS words are unpredictable and bound to
    // this approval. The unguessable id generator is the same randomness source
    // the CSP nonces trust — no second RNG dependency.
    let nonce = newt_core::new_conversation_id();
    let blinding = newt_core::new_conversation_id();
    let ceremony = dock_registry::dock_ceremony(
        &issuer,
        label,
        &pubkey,
        nonce.as_bytes(),
        blinding.as_bytes(),
    );

    // Terminal-gated (the capability, not a flag): a session with no terminal
    // cannot obtain the window and falls through to the decline arm.
    let window = newt_core::tty::Terminal::suspend_for_prompt(
        newt_core::tty::TerminalTaker::PlainCliConfirm,
    );
    window.notice(&format!(
        "dock approval for `{label}`\n  peer agent fp : {}\n  peer pubkey   : {}…\n  key words     : {}\nThe peer's newt-web prints these SAME words when it binds its dock service —\nconfirm they match before approving (a cross-check of the peer's key, not a\ntwo-party anti-MITM SAS: same-operator trust is already proven by the mesh handshake).",
        &peer_fp[..16.min(peer_fp.len())],
        &pubkey_hex[..16.min(pubkey_hex.len())],
        ceremony.sas_words.join(" "),
    ))?;
    if let Some(pairing) = pairing {
        window.notice(&format!(
            "  pairing code  : {}\nThe host's `newt-mesh dock` shows this SAME code for this pairing. \
             Approve only if they match.",
            pairing.code
        ))?;
    }
    if !newt_core::interaction_terminal::confirmed_on_terminal(
        &window,
        &newt_core::interaction_form::confirm(
            format!("approve dock with `{label}`?"),
            "",
            "yes, approve it",
            "no, leave it",
        ),
        // `[y/N]`: blank declines.
        false,
    ) {
        window.notice("dock approval declined; nothing changed")?;
        return Ok(1);
    }

    // A paired host's approval commits to the pairing transcript, and is
    // signed only while the host still holds the pairing compared.
    let approve = |transcript_id: &str| {
        dock_registry::approve_dock(
            &config_path,
            &peer_fp,
            label,
            pubkey_hex.trim(),
            scope,
            transcript_id,
            &root_key,
        )
    };
    let approved = match pairing {
        Some(p) => {
            dock_registry::promote_staged_host(&config_path, &peer_fp, &p.transcript_id, || {
                approve(&p.transcript_id)
            })
        }
        None => approve(&ceremony.transcript_id).inspect(|_| {
            // A host approved by key needs no staged entry either.
            let _ = dock_registry::unstage_host(&config_path, &peer_fp);
        }),
    };
    match approved {
        Ok(path) => {
            window.notice(&format!(
                "approved `{label}` ({}) → {}",
                &peer_fp[..16.min(peer_fp.len())],
                path.display()
            ))?;
            Ok(0)
        }
        Err(error) => {
            window.notice(&format!("dock approval failed: {error}"))?;
            Ok(1)
        }
    }
}

fn run_revoke(
    peer: &str,
    operator_key_path: Option<PathBuf>,
    config: Option<&Path>,
) -> anyhow::Result<i32> {
    let config_path = config_path(config)?;
    let root_key = load_root(operator_key_path)?;

    let window = newt_core::tty::Terminal::suspend_for_prompt(
        newt_core::tty::TerminalTaker::PlainCliConfirm,
    );
    if !newt_core::interaction_terminal::confirmed_on_terminal(
        &window,
        &newt_core::interaction_form::confirm(
            format!("revoke the dock for `{peer}`?"),
            "",
            "yes, revoke it",
            "no, leave it",
        ),
        // `[y/N]`: blank declines.
        false,
    ) {
        window.notice("revoke declined; nothing changed")?;
        return Ok(1);
    }
    match dock_registry::revoke_dock(&config_path, peer, &root_key) {
        Ok(full) => {
            window.notice(&format!("revoked dock {full}"))?;
            Ok(0)
        }
        Err(error) => {
            window.notice(&format!("revoke failed: {error}"))?;
            Ok(1)
        }
    }
}

fn run_revoke_all(
    operator_key_path: Option<PathBuf>,
    config: Option<&Path>,
) -> anyhow::Result<i32> {
    let config_path = config_path(config)?;
    let root_key = load_root(operator_key_path)?;

    let window = newt_core::tty::Terminal::suspend_for_prompt(
        newt_core::tty::TerminalTaker::PlainCliConfirm,
    );
    if !newt_core::interaction_terminal::confirmed_on_terminal(
        &window,
        &newt_core::interaction_form::confirm(
            "revoke ALL live docks?",
            "",
            "yes, revoke them all",
            "no, leave them",
        ),
        // `[y/N]`: blank declines.
        false,
    ) {
        window.notice("revoke-all declined; nothing changed")?;
        return Ok(1);
    }
    match dock_registry::revoke_all_docks(&config_path, &root_key) {
        Ok(revoked) => {
            window.notice(&format!("revoked {} dock(s)", revoked.len()))?;
            Ok(0)
        }
        Err(error) => {
            window.notice(&format!("revoke-all failed: {error}"))?;
            Ok(1)
        }
    }
}

fn run_list(operator_key_path: Option<PathBuf>, config: Option<&Path>) -> anyhow::Result<i32> {
    let config_path = config_path(config)?;
    let root_key = load_root(operator_key_path)?;
    let (registry, warnings) = dock_registry::load_docks(&config_path, Some(&root_key.public()));
    for warning in &warnings {
        eprintln!("warning: {warning}");
    }
    let staged = dock_registry::staged_hosts(&config_path, std::time::SystemTime::now());
    if !staged.is_empty() {
        println!("staged hosts (promote with `newt dock approve --staged <PEER-FP>`):");
        let rows: Vec<[String; 3]> = staged
            .iter()
            .map(|host| {
                [
                    host.peer_label.clone(),
                    host.peer_agent_fingerprint[..16].to_string(),
                    "staged".to_string(),
                ]
            })
            .collect();
        print!("{}", dock_table(&rows));
    }
    let docks = registry.live();
    if docks.is_empty() {
        println!("no approved docks");
        return Ok(0);
    }
    let rows: Vec<[String; 3]> = docks
        .iter()
        .map(|dock| {
            [
                dock.peer_label.clone(),
                dock.peer_agent_fingerprint[..16.min(dock.peer_agent_fingerprint.len())]
                    .to_string(),
                dock.scope.as_wire().to_string(),
            ]
        })
        .collect();
    print!("{}", dock_table(&rows));
    Ok(0)
}

/// Render the `newt dock list` listing.
///
/// Extracted so the exact bytes are testable without a dock registry (#1916).
/// Byte-identical to the `println!`s it replaces.
fn dock_table(rows: &[[String; 3]]) -> String {
    use newt_core::markup::table::{render_table, Column};
    let columns = [
        Column::new("LABEL"),
        Column::new("PEER-FP"),
        Column::new("scope"),
    ];
    let data: Vec<Vec<String>> = rows.iter().map(|r| r.to_vec()).collect();
    render_table(&columns, &data)
}

#[cfg(test)]
mod d3c {
    /// **The byte golden for `newt dock list` as it ships today** (#1916).
    /// Captured from the shipping renderer — see `models_cmd::d3c`.
    #[test]
    fn the_dock_listing_is_byte_exact() {
        let rows = [[
            "laptop-b".to_string(),
            "abcdef0123456789".to_string(),
            "mirror-inject".to_string(),
        ]];
        assert_eq!(
            super::dock_table(&rows),
            concat!(
                "| LABEL    | PEER-FP          | scope         |\n",
                "| -------- | ---------------- | ------------- |\n",
                "| laptop-b | abcdef0123456789 | mirror-inject |\n",
            )
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_pubkey_round_trips_and_rejects_bad_input() {
        let hex = "aa".repeat(32);
        assert_eq!(parse_pubkey(&hex).unwrap(), [0xaau8; 32]);
        assert!(parse_pubkey("short").is_err());
        assert!(parse_pubkey(&"zz".repeat(32)).is_err());
    }

    #[test]
    fn staged_resolves_one_unambiguous_live_host() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = dir.path().join("config.toml");
        let now = std::time::SystemTime::now();
        dock_registry::stage_host(&config, &[1; 32], "nuc1", &[9; 32], now).unwrap();
        dock_registry::stage_host(&config, &[2; 32], "nuc2", &[9; 32], now).unwrap();
        let nuc1 = dock_registry::agent_fingerprint_of_pubkey(&[1; 32]);

        let host = staged_host(&config, &nuc1[..12]).unwrap();
        assert_eq!(
            (host.peer_label.as_str(), host.peer_pubkey),
            ("nuc1", "01".repeat(32))
        );
        assert!(
            staged_host(&config, "").is_err(),
            "an empty prefix names nothing"
        );
        assert!(staged_host(&config, "zz").is_err(), "no match");

        let twin = (3..=u8::MAX)
            .map(|b| [b; 32])
            .find(|k| dock_registry::agent_fingerprint_of_pubkey(k)[..1] == nuc1[..1])
            .unwrap();
        dock_registry::stage_host(&config, &twin, "twin", &[9; 32], now).unwrap();
        assert!(
            staged_host(&config, &nuc1[..1]).is_err(),
            "a prefix two hosts share is ambiguous"
        );
    }

    #[test]
    fn approve_takes_either_a_pubkey_and_label_or_a_staged_host() {
        use clap::Parser;
        #[derive(Parser)]
        struct Cli {
            #[command(subcommand)]
            cmd: DockCmd,
        }
        let parse = |args: &[&str]| Cli::try_parse_from([&["newt"], args].concat()).map(|c| c.cmd);
        assert!(matches!(
            parse(&["approve", "--staged", "ab12"]),
            Ok(DockCmd::Approve {
                staged: Some(_),
                pubkey: None,
                label: None,
                ..
            })
        ));
        assert!(parse(&["approve", "--pubkey", "aa", "--label", "x"]).is_ok());
        assert!(
            parse(&["approve", "--label", "x"]).is_err(),
            "no key and no staged host"
        );
        assert!(parse(&["approve", "--staged", "ab", "--pubkey", "aa"]).is_err());
    }
}