feat(maestro): maestro-cli — list/spawn/attach/kill
ci / rust (push) Successful in 1m7s

Closes NAP-216. Thin client for the registry HTTP API + per-session
daemon WebSocket. Becomes the headless test harness for NAP-217 and
unblocks the demo-by-script path before the web client lands (NAP-218).

Crate layout (`crates/maestro-cli/`):

- `cli.rs` — clap-derive parser. Commands: `list`, `spawn`, `attach`,
  `kill`, `set-registry`. Global `--registry-url` (env
  `MAESTRO_REGISTRY_URL`), `--config`, repeatable `-v`.
- `config.rs` — `CliConfig` persisted at `~/.config/maestro/cli.toml`,
  storing the default registry URL + the session cookie issued by the
  registry's cookie middleware.
- `http.rs` — `RegistryClient` wrapping `reqwest`. Attaches the
  persisted cookie, captures `Set-Cookie` responses (first-contact
  bootstrap and rotation), atomically writes the new value back to
  the config file.
- `sessions.rs` — `list/spawn/kill` + connect-info fetch. `list` prints
  a per-daemon grouped table; `--json` for scripting.
- `attach.rs` — raw-TTY WS proxy. Termios cfmakeraw with an RAII guard
  for restore-on-drop, SIGWINCH → `ClientControl::Resize` text frame,
  configurable detach key (default Ctrl-q; accepts `^X` form), echoes
  `Ping`/`Pong` for keepalive symmetry with the daemon side.

Workspace deps added: clap (derive+env), reqwest (rustls+cookies),
nix (term+signal).

Smoke-tested against the live registry at maestro-registry.n62.casa:
`maestro list` issued + persisted the cookie and printed the empty
catalog cleanly. 19 new unit tests (parser, config round-trip,
table-printing, cookie extraction, attach URL/detach-key parsing).
Full workspace `cargo test`: 97 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-25 09:49:46 +00:00
co-authored by Claude Opus 4.7
parent 8586f46dad
commit b68e39a9e5
10 changed files with 1394 additions and 10 deletions
+279
View File
@@ -0,0 +1,279 @@
//! `maestro attach` — raw-TTY proxy over the daemon's per-session WS endpoint.
//!
//! Wire-format mirrors `crates/maestro-daemon/src/attach.rs`:
//! - PTY bytes ride in **binary** frames both directions.
//! - `ClientControl::{Resize, Ping, Pong}` ride in **text** frames.
use std::io::{self, IsTerminal};
use std::os::fd::AsFd;
use std::sync::Arc;
use futures_util::{SinkExt, StreamExt};
use maestro_protocol::{ClientControl, ConnectInfo};
use nix::sys::termios::{cfmakeraw, tcgetattr, tcsetattr, SetArg, Termios};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio_tungstenite::tungstenite::Message;
use uuid::Uuid;
#[derive(Debug, thiserror::Error)]
#[allow(clippy::result_large_err)]
pub enum AttachError {
#[error("ws: {0}")]
WebSocket(#[from] tokio_tungstenite::tungstenite::Error),
#[error("io: {0}")]
Io(#[from] io::Error),
#[error("termios: {0}")]
Termios(#[from] nix::Error),
#[error("invalid daemon_url: {0}")]
InvalidDaemonUrl(String),
#[error("invalid detach key: {0}")]
InvalidDetachKey(String),
#[error("stdin must be a TTY for attach")]
NotATty,
}
/// Parse a detach key spec. Accepts `^X` for Ctrl-X (case-insensitive) or a
/// single literal character. Returns the resulting byte.
#[allow(clippy::result_large_err)]
pub fn parse_detach_key(spec: &str) -> Result<u8, AttachError> {
let bytes = spec.as_bytes();
match bytes {
[b'^', c] if c.is_ascii_alphabetic() => Ok(c.to_ascii_uppercase() - b'@'),
[c] => Ok(*c),
_ => Err(AttachError::InvalidDetachKey(spec.to_string())),
}
}
/// Build the attach WS URL from a `ConnectInfo` and session ID.
#[allow(clippy::result_large_err)]
pub fn attach_url(info: &ConnectInfo, session_id: Uuid) -> Result<String, AttachError> {
let base = info.daemon_url.trim_end_matches('/');
if !(base.starts_with("ws://") || base.starts_with("wss://")) {
return Err(AttachError::InvalidDaemonUrl(info.daemon_url.clone()));
}
Ok(format!(
"{base}/sessions/{session_id}/stream?token={token}",
token = urlencoding(&info.jwt)
))
}
/// Minimal percent-encoder for the token in a query string. JWTs only contain
/// `A-Z a-z 0-9 - _ .` (URL-safe base64 + dots) so this is paranoia, not need.
fn urlencoding(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(b as char);
}
_ => {
out.push('%');
out.push_str(&format!("{b:02X}"));
}
}
}
out
}
/// RAII guard that puts the terminal into raw mode and restores on drop.
#[derive(Debug)]
struct RawTty {
fd: std::os::fd::OwnedFd,
original: Termios,
}
impl RawTty {
#[allow(clippy::result_large_err)]
fn enable() -> Result<Self, AttachError> {
let stdin = io::stdin();
if !stdin.is_terminal() {
return Err(AttachError::NotATty);
}
// Dup stdin so we hold an OwnedFd whose lifetime we control.
let fd = stdin
.as_fd()
.try_clone_to_owned()
.map_err(AttachError::Io)?;
let original = tcgetattr(&fd)?;
let mut raw = original.clone();
cfmakeraw(&mut raw);
tcsetattr(&fd, SetArg::TCSANOW, &raw)?;
Ok(Self { fd, original })
}
}
impl Drop for RawTty {
fn drop(&mut self) {
let _ = tcsetattr(&self.fd, SetArg::TCSANOW, &self.original);
}
}
fn current_winsize() -> Option<(u16, u16)> {
use std::mem::MaybeUninit;
let mut ws = MaybeUninit::<libc::winsize>::uninit();
let r = unsafe { libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, ws.as_mut_ptr()) };
if r != 0 {
return None;
}
let ws = unsafe { ws.assume_init() };
Some((ws.ws_col, ws.ws_row))
}
/// Drive the attach loop until the client detaches or the remote closes.
///
/// `connect_info` is whatever `GET /api/sessions/:id/connect-info` returned;
/// `detach_byte` is the single byte that exits cleanly without killing the
/// session.
#[allow(clippy::result_large_err)]
pub async fn run_attach(
connect_info: ConnectInfo,
session_id: Uuid,
detach_byte: u8,
) -> Result<(), AttachError> {
let url = attach_url(&connect_info, session_id)?;
let (ws, _resp) = tokio_tungstenite::connect_async(&url).await?;
let (mut sink, mut stream) = ws.split();
let _raw = RawTty::enable()?;
// Send initial window size so the remote PTY matches our terminal.
if let Some((cols, rows)) = current_winsize() {
let frame =
serde_json::to_string(&ClientControl::Resize { cols, rows }).expect("serialize");
sink.send(Message::Text(frame)).await?;
}
let mut stdin = tokio::io::stdin();
let mut stdout = tokio::io::stdout();
// Resize signal stream.
let mut sigwinch =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::window_change())?;
let mut in_buf = [0u8; 4096];
let detach_msg = Arc::new(format!(
"\r\n[maestro] detached (key 0x{detach_byte:02x})\r\n"
));
loop {
tokio::select! {
// Server → local stdout
msg = stream.next() => {
match msg {
None => break,
Some(Err(e)) => return Err(AttachError::WebSocket(e)),
Some(Ok(Message::Binary(bytes))) => {
stdout.write_all(&bytes).await?;
stdout.flush().await?;
}
Some(Ok(Message::Text(text))) => {
if let Ok(ClientControl::Ping) = serde_json::from_str::<ClientControl>(&text) {
let pong = serde_json::to_string(&ClientControl::Pong)
.expect("serialize pong");
sink.send(Message::Text(pong)).await?;
}
}
Some(Ok(Message::Ping(p))) => {
sink.send(Message::Pong(p)).await?;
}
Some(Ok(Message::Close(_))) => break,
Some(Ok(_)) => {}
}
}
// Local stdin → server
n = stdin.read(&mut in_buf) => {
let n = n?;
if n == 0 {
break;
}
let chunk = &in_buf[..n];
if let Some(pos) = chunk.iter().position(|b| *b == detach_byte) {
if pos > 0 {
sink.send(Message::Binary(chunk[..pos].to_vec())).await.ok();
}
let _ = sink.send(Message::Close(None)).await;
// best-effort goodbye on the local terminal
stdout.write_all(detach_msg.as_bytes()).await.ok();
break;
}
sink.send(Message::Binary(chunk.to_vec())).await?;
}
// Window resize
_ = sigwinch.recv() => {
if let Some((cols, rows)) = current_winsize() {
let frame = serde_json::to_string(&ClientControl::Resize { cols, rows })
.expect("serialize");
sink.send(Message::Text(frame)).await?;
}
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use maestro_protocol::ConnectInfo;
use uuid::Uuid;
#[test]
fn parse_detach_key_handles_caret_form() {
assert_eq!(parse_detach_key("^q").unwrap(), 0x11);
assert_eq!(parse_detach_key("^Q").unwrap(), 0x11);
assert_eq!(parse_detach_key("^c").unwrap(), 0x03);
}
#[test]
fn parse_detach_key_handles_literal() {
assert_eq!(parse_detach_key("x").unwrap(), b'x');
}
#[test]
fn parse_detach_key_rejects_multi_char() {
assert!(matches!(
parse_detach_key("ab"),
Err(AttachError::InvalidDetachKey(_))
));
}
#[test]
fn attach_url_uses_ws_path_and_token_query() {
let info = ConnectInfo {
daemon_url: "ws://10.0.0.1:7070".into(),
jwt: "abc.def-ghi_jkl".into(),
};
let id = Uuid::from_u128(0x1234_5678);
let url = attach_url(&info, id).unwrap();
assert!(url.starts_with("ws://10.0.0.1:7070/sessions/"));
assert!(url.contains(&id.to_string()));
assert!(url.contains("/stream?token=abc.def-ghi_jkl"));
}
#[test]
fn attach_url_rejects_non_ws_scheme() {
let info = ConnectInfo {
daemon_url: "http://x".into(),
jwt: "t".into(),
};
assert!(matches!(
attach_url(&info, Uuid::nil()),
Err(AttachError::InvalidDaemonUrl(_))
));
}
#[test]
fn attach_url_trims_trailing_slash() {
let info = ConnectInfo {
daemon_url: "wss://reg.example.com/".into(),
jwt: "t".into(),
};
let id = Uuid::nil();
let url = attach_url(&info, id).unwrap();
assert!(!url.contains("//sessions"), "{url}");
}
}