Publish harness and TUI open-source

initial sync from the monorepo
This commit is contained in:
grokkybara[bot] 2026-07-16 06:46:02 +01:00
commit c68e39f604
2734 changed files with 1437016 additions and 0 deletions

View file

@ -0,0 +1,24 @@
[package]
license = "Apache-2.0"
name = "ptyctl-cli"
version = "0.1.0"
edition.workspace = true
description = "CLI for ptyctl headless PTY controller"
publish = false
[[bin]]
name = "ptyctl"
path = "src/main.rs"
[dependencies]
ptyctl = { path = "../ptyctl" }
axum = { workspace = true }
clap = { workspace = true, features = ["derive"] }
reqwest = { workspace = true, features = ["json"] }
tokio = { workspace = true, features = ["full"] }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
anyhow = { workspace = true }
env_logger = { workspace = true }
chrono = { workspace = true, features = ["serde"] }
dirs = { workspace = true }

View file

@ -0,0 +1,227 @@
//! CLI argument definitions using clap derive.
use std::path::PathBuf;
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[command(name = "ptyctl")]
#[command(about = "Run commands in PTY and control them via HTTP")]
#[command(version)]
#[command(arg_required_else_help = true)]
pub struct Cli {
#[command(subcommand)]
pub command: Commands,
}
#[derive(Subcommand)]
pub enum Commands {
/// Spawn a command in a PTY and start an HTTP control server
#[command(arg_required_else_help = true)]
Run {
/// Command to run (use -- before command)
#[arg(required = true, trailing_var_arg = true)]
command: Vec<String>,
/// Terminal width in columns
#[arg(short = 'W', long, default_value = "80")]
width: u16,
/// Terminal height in rows
#[arg(short = 'H', long, default_value = "24")]
height: u16,
/// Working directory
#[arg(short = 'c', long)]
cwd: Option<PathBuf>,
/// Environment variable (KEY=VAL, repeatable)
#[arg(short = 'e', long = "env", value_name = "KEY=VAL")]
env: Vec<String>,
/// TCP port to listen on (0 = auto-assign)
#[arg(short, long, default_value = "0")]
port: u16,
/// Session name (registers in ~/.local/state/ptyctl/sessions/)
#[arg(short, long)]
name: Option<String>,
/// Take over an existing session name (replaces the registration; does not stop the old server)
#[arg(long)]
force: bool,
/// Shutdown after N seconds
#[arg(short, long, value_name = "SECS")]
timeout: Option<u64>,
/// Keep server running after process exits
#[arg(short, long)]
linger: bool,
/// Suppress output (just print port number)
#[arg(short, long)]
quiet: bool,
},
/// Send keystrokes to a running session
#[command(arg_required_else_help = true)]
Send {
#[command(flatten)]
target: Target,
/// Keys to send (vim notation)
keys: String,
/// Append Enter (<CR>) after keys
#[arg(short = 'e', long)]
enter: bool,
},
/// Query terminal screen content
#[command(arg_required_else_help = true)]
Screen {
#[command(flatten)]
target: Target,
/// Row range, 1-indexed (e.g. "1:5")
#[arg(short, long)]
rows: Option<String>,
/// Column range, 1-indexed
#[arg(short = 'C', long)]
cols: Option<String>,
/// Output as JSON
#[arg(short, long, conflicts_with_all = ["ansi", "styled", "html"])]
json: bool,
/// Show cursor position with this character
#[arg(short = 'c', long)]
cursor: Option<char>,
/// Include ANSI escape codes
#[arg(short, long, conflicts_with_all = ["json", "styled", "html"])]
ansi: bool,
/// Output as styled JSON (LLM-friendly)
#[arg(short = 's', long, conflicts_with_all = ["json", "ansi", "html"])]
styled: bool,
/// Output as HTML
#[arg(long, conflicts_with_all = ["json", "ansi", "styled"])]
html: bool,
/// Include trailing empty lines
#[arg(long)]
full: bool,
/// Show line numbers
#[arg(short = 'l', long)]
line_numbers: bool,
},
/// Query process status
#[command(arg_required_else_help = true)]
Status {
#[command(flatten)]
target: Target,
},
/// Stop a running session
#[command(arg_required_else_help = true)]
Stop {
#[command(flatten)]
target: Target,
},
/// Resize terminal dimensions
#[command(arg_required_else_help = true)]
Resize {
#[command(flatten)]
target: Target,
/// New size as COLSxROWS (e.g. "120x40")
size: String,
},
/// Query cursor position
#[command(arg_required_else_help = true)]
Cursor {
#[command(flatten)]
target: Target,
},
/// Wait for a screen condition (event-driven, no polling).
/// Exit codes: 0 matched, 1 timeout (failure JSON on stdout), 2 usage/connection error
#[command(arg_required_else_help = true)]
#[command(group(clap::ArgGroup::new("condition").required(true)))]
Wait {
#[command(flatten)]
target: Target,
/// Wait until this text appears on screen
#[arg(long, group = "condition")]
text: Option<String>,
/// Wait until this regex matches the screen text
#[arg(long, group = "condition")]
regex: Option<String>,
/// Wait until this text is absent from the screen
#[arg(long, group = "condition")]
gone: Option<String>,
/// Wait until the screen has been unchanged for this many milliseconds
#[arg(long, value_name = "MS", group = "condition")]
stable_ms: Option<u64>,
/// Timeout in seconds (server caps at 120)
#[arg(short, long, default_value = "10")]
timeout: u64,
},
/// List registered sessions
List {
/// Output as JSON
#[arg(short, long)]
json: bool,
},
}
/// Target session — exactly one of host, port, or name must be provided.
#[derive(clap::Args)]
#[group(required = true, multiple = false)]
pub struct Target {
/// Remote host address (e.g. 127.0.0.1:8080)
#[arg(short = 'H', long)]
pub host: Option<String>,
/// Local server port
#[arg(short, long)]
pub port: Option<u16>,
/// Session name (from registry)
#[arg(short, long)]
pub name: Option<String>,
}
impl Target {
/// Resolve target to a base URL.
pub fn to_url(&self) -> anyhow::Result<String> {
if let Some(ref h) = self.host {
if h.starts_with("http") {
return Ok(h.clone());
}
return Ok(format!("http://{h}"));
}
if let Some(p) = self.port {
return Ok(format!("http://127.0.0.1:{p}"));
}
if let Some(ref n) = self.name {
let info = crate::registry::lookup_session(n)?;
return Ok(format!("http://127.0.0.1:{}", info.port));
}
anyhow::bail!("no target specified")
}
}

View file

@ -0,0 +1,196 @@
//! Client commands — send/screen/status/cursor/resize/stop via HTTP.
use anyhow::{Context, Result};
use reqwest::Client;
/// Send keystrokes to a session.
pub async fn send(url: &str, keys: &str, enter: bool) -> Result<()> {
let mut keys = keys.to_string();
if enter {
keys.push_str("<CR>");
}
let client = Client::new();
let resp = client
.post(format!("{url}/control/send"))
.json(&serde_json::json!({"keys": keys}))
.send()
.await
.context("failed to send keys")?;
if !resp.status().is_success() {
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("send failed: {body}");
}
Ok(())
}
/// Query screen content.
pub async fn screen(
url: &str,
rows: Option<&str>,
cols: Option<&str>,
cursor: Option<char>,
format: &str,
full: bool,
line_numbers: bool,
) -> Result<()> {
let client = Client::new();
let mut req = client.get(format!("{url}/query/screen"));
if let Some(r) = rows {
req = req.query(&[("rows", r)]);
}
if let Some(c) = cols {
req = req.query(&[("cols", c)]);
}
if let Some(ch) = cursor {
req = req.query(&[("cursor", &ch.to_string())]);
}
req = req.query(&[("format", format)]);
if full {
req = req.query(&[("full", "true")]);
}
let resp = req.send().await.context("failed to query screen")?;
if !resp.status().is_success() {
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("screen query failed: {body}");
}
let body = resp.text().await?;
if format == "html" || format == "styled" {
println!("{body}");
} else {
// Parse as JSON and print lines.
let output: serde_json::Value = serde_json::from_str(&body)?;
if let Some(lines) = output.get("lines").and_then(|l| l.as_array()) {
for (i, line) in lines.iter().enumerate() {
let text = line.as_str().unwrap_or("");
if line_numbers {
println!("{:4} {text}", i + 1);
} else {
println!("{text}");
}
}
}
}
Ok(())
}
/// Query cursor position.
pub async fn cursor(url: &str) -> Result<()> {
let client = Client::new();
let resp = client
.get(format!("{url}/query/cursor"))
.send()
.await
.context("failed to query cursor")?;
let body = resp.text().await?;
println!("{body}");
Ok(())
}
/// Query session status.
pub async fn status(url: &str) -> Result<()> {
let client = Client::new();
let resp = client
.get(format!("{url}/query/status"))
.send()
.await
.context("failed to query status")?;
let body = resp.text().await?;
println!("{body}");
Ok(())
}
/// Resize terminal.
pub async fn resize(url: &str, size: &str) -> Result<()> {
let (cols, rows) = size
.split_once('x')
.ok_or_else(|| anyhow::anyhow!("invalid size format, expected COLSxROWS (e.g. 120x40)"))?;
let cols: u16 = cols.parse().context("invalid cols")?;
let rows: u16 = rows.parse().context("invalid rows")?;
let client = Client::new();
let resp = client
.post(format!("{url}/control/resize"))
.json(&serde_json::json!({"cols": cols, "rows": rows}))
.send()
.await
.context("failed to resize")?;
if !resp.status().is_success() {
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("resize failed: {body}");
}
println!("Resized to {cols}x{rows}");
Ok(())
}
/// Long-poll the wait endpoint; prints the outcome JSON and returns whether it matched.
pub async fn wait(
url: &str,
text: Option<&str>,
regex: Option<&str>,
gone: Option<&str>,
stable_ms: Option<u64>,
timeout_secs: u64,
) -> Result<bool> {
// The HTTP timeout outlasts the wait so the server, not the client, decides the outcome.
let client = Client::builder()
.timeout(std::time::Duration::from_secs(
timeout_secs.saturating_add(5),
))
.build()
.context("failed to build HTTP client")?;
let mut req = client
.get(format!("{url}/wait"))
.query(&[("timeout_ms", timeout_secs.saturating_mul(1000).to_string())]);
if let Some(t) = text {
req = req.query(&[("text", t)]);
}
if let Some(r) = regex {
req = req.query(&[("regex", r)]);
}
if let Some(g) = gone {
req = req.query(&[("gone", g)]);
}
if let Some(ms) = stable_ms {
req = req.query(&[("stable_ms", ms.to_string())]);
}
let resp = req.send().await.context("failed to call wait")?;
if !resp.status().is_success() {
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("wait failed: {body}");
}
let outcome: serde_json::Value = resp.json().await.context("invalid wait response")?;
println!("{}", serde_json::to_string_pretty(&outcome)?);
Ok(outcome
.get("matched")
.and_then(|m| m.as_bool())
.unwrap_or(false))
}
/// Stop a session.
pub async fn stop(url: &str) -> Result<()> {
let client = Client::new();
let resp = client
.post(format!("{url}/control/stop"))
.send()
.await
.context("failed to stop session")?;
if !resp.status().is_success() {
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("stop failed: {body}");
}
println!("Session stopped");
Ok(())
}

View file

@ -0,0 +1,2 @@
pub mod client;
pub mod run;

View file

@ -0,0 +1,119 @@
//! `ptyctl run` — spawn a PTY session and start the HTTP server.
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::PathBuf;
use anyhow::{Context, Result, bail};
use tokio::net::TcpListener;
use ptyctl::pty::PtyConfig;
use ptyctl::server;
use ptyctl::session::{PtySession, SessionConfig};
use crate::registry;
/// Run the `ptyctl run` command.
#[allow(clippy::too_many_arguments)]
pub async fn run(
command: Vec<String>,
width: u16,
height: u16,
cwd: Option<PathBuf>,
env_vars: Vec<String>,
port: u16,
name: Option<String>,
force: bool,
timeout: Option<u64>,
linger: bool,
quiet: bool,
) -> Result<()> {
// Refuse to take over a name whose server is still reachable unless --force; stale entries are replaced.
if let Some(ref session_name) = name
&& !force
&& let Ok(existing) = registry::lookup_session(session_name)
&& registry::server_alive(existing.port).await
{
bail!(
"session '{session_name}' is already running on port {} (use --force to replace it)",
existing.port
);
}
// Parse env vars.
let mut env = HashMap::new();
for var in &env_vars {
if let Some((k, v)) = var.split_once('=') {
env.insert(k.to_string(), v.to_string());
}
}
let cwd_str = cwd
.as_ref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| ".".into());
let config = SessionConfig {
pty: PtyConfig {
command: command.clone(),
cols: width,
rows: height,
cwd,
env,
},
timeout,
linger,
};
// Start the session.
let session = PtySession::start(config).await?;
let pid = session.status_basic().1;
// Build the HTTP server.
let router = server::build_router(session);
// Bind to the requested port.
let addr = SocketAddr::from(([127, 0, 0, 1], port));
let listener = TcpListener::bind(addr)
.await
.context("failed to bind TCP listener")?;
let actual_addr = listener.local_addr()?;
let actual_port = actual_addr.port();
// Register named session.
if let Some(ref session_name) = name {
let info = registry::SessionInfo {
port: actual_port,
pid,
command: command.clone(),
cwd: cwd_str,
started_at: chrono::Utc::now().to_rfc3339(),
};
registry::register_session(session_name, &info)?;
}
if !quiet {
eprintln!("Command: {}", command.join(" "));
if let Some(p) = pid {
eprintln!("PID: {p}");
}
eprintln!("Server listening on port: {actual_port}");
} else {
println!("{actual_port}");
}
// Serve until shutdown.
let shutdown_result = axum::serve(listener, router)
.await
.context("HTTP server error");
// Clean up only a registration that still points at this server; a --force takeover may have replaced it.
if let Some(ref session_name) = name
&& let Ok(info) = registry::lookup_session(session_name)
&& info.port == actual_port
{
let _ = registry::unregister_session(session_name);
}
shutdown_result
}

View file

@ -0,0 +1,174 @@
//! ptyctl CLI — headless PTY controller.
use clap::Parser;
mod cli;
mod commands;
mod registry;
use cli::{Cli, Commands};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
env_logger::init();
let cli = Cli::parse();
match cli.command {
Commands::Run {
command,
width,
height,
cwd,
env,
port,
name,
force,
timeout,
linger,
quiet,
} => {
commands::run::run(
command, width, height, cwd, env, port, name, force, timeout, linger, quiet,
)
.await?;
}
Commands::Send {
target,
keys,
enter,
} => {
let url = target.to_url()?;
commands::client::send(&url, &keys, enter).await?;
}
Commands::Screen {
target,
rows,
cols,
json: _,
cursor,
ansi: _,
styled,
html,
full,
line_numbers,
} => {
let url = target.to_url()?;
let format = if styled {
"styled"
} else if html {
"html"
} else {
"text"
};
commands::client::screen(
&url,
rows.as_deref(),
cols.as_deref(),
cursor,
format,
full,
line_numbers,
)
.await?;
}
Commands::Status { target } => {
let url = target.to_url()?;
commands::client::status(&url).await?;
}
Commands::Stop { target } => {
let url = target.to_url()?;
commands::client::stop(&url).await?;
}
Commands::Resize { target, size } => {
let url = target.to_url()?;
commands::client::resize(&url, &size).await?;
}
Commands::Cursor { target } => {
let url = target.to_url()?;
commands::client::cursor(&url).await?;
}
Commands::Wait {
target,
text,
regex,
gone,
stable_ms,
timeout,
} => {
// Exit code contract: 0 matched, 1 timeout, 2 usage/connection errors.
let exit = |code: i32| -> ! { std::process::exit(code) };
let url = match target.to_url() {
Ok(url) => url,
Err(e) => {
eprintln!("Error: {e:#}");
exit(2);
}
};
match commands::client::wait(
&url,
text.as_deref(),
regex.as_deref(),
gone.as_deref(),
stable_ms,
timeout,
)
.await
{
Ok(true) => {}
Ok(false) => exit(1),
Err(e) => {
eprintln!("Error: {e:#}");
exit(2);
}
}
}
Commands::List { json } => {
let sessions = registry::list_sessions()?;
if json {
let mut items = Vec::new();
for (name, info) in &sessions {
items.push(serde_json::json!({
"name": name,
"port": info.port,
"pid": info.pid,
"command": info.command,
"started_at": info.started_at,
// "server_alive", not "alive": /query/status's "alive" means child-alive, which diverges under --linger.
"server_alive": registry::server_alive(info.port).await,
}));
}
println!("{}", serde_json::to_string_pretty(&items)?);
} else if sessions.is_empty() {
println!("No active sessions");
} else {
println!(
"{:<16} {:<8} {:<8} {:<8} COMMAND",
"NAME", "PORT", "PID", "SERVER"
);
println!("{}", "-".repeat(60));
for (name, info) in &sessions {
let pid = info
.pid
.map(|p| p.to_string())
.unwrap_or_else(|| "?".into());
let server = if registry::server_alive(info.port).await {
"live"
} else {
"dead"
};
println!(
"{:<16} {:<8} {:<8} {:<8} {}",
name,
info.port,
pid,
server,
info.command.join(" ")
);
}
}
}
}
Ok(())
}

View file

@ -0,0 +1,127 @@
//! Named session registry stored at ~/.local/state/ptyctl/sessions/.
use std::fs;
use std::path::PathBuf;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
/// Information about a registered session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInfo {
pub port: u16,
pub pid: Option<u32>,
pub command: Vec<String>,
pub cwd: String,
pub started_at: String,
}
/// Get the session registry directory.
fn registry_dir() -> Result<PathBuf> {
if let Ok(dir) = std::env::var("PTYCTL_SESSION_DIR") {
return Ok(PathBuf::from(dir));
}
let state_dir = dirs::state_dir()
.or_else(dirs::data_local_dir)
.context("cannot determine state directory")?;
Ok(state_dir.join("ptyctl").join("sessions"))
}
/// Register a named session.
pub fn register_session(name: &str, info: &SessionInfo) -> Result<()> {
let dir = registry_dir()?;
fs::create_dir_all(&dir).context("failed to create session registry directory")?;
let path = dir.join(format!("{name}.json"));
let json = serde_json::to_string_pretty(info)?;
// Atomic write: write to temp file, then rename.
let tmp = dir.join(format!(".{name}.json.tmp"));
fs::write(&tmp, &json).context("failed to write session file")?;
fs::rename(&tmp, &path).context("failed to rename session file")?;
Ok(())
}
/// Look up a named session.
pub fn lookup_session(name: &str) -> Result<SessionInfo> {
let dir = registry_dir()?;
let path = dir.join(format!("{name}.json"));
if !path.exists() {
bail!("session '{name}' not found");
}
let json = fs::read_to_string(&path).context("failed to read session file")?;
let info: SessionInfo = serde_json::from_str(&json).context("failed to parse session file")?;
Ok(info)
}
/// Remove a named session.
pub fn unregister_session(name: &str) -> Result<()> {
let dir = registry_dir()?;
let path = dir.join(format!("{name}.json"));
if path.exists() {
fs::remove_file(&path).context("failed to remove session file")?;
}
Ok(())
}
/// Check whether a registered session's ptyctl server is reachable.
///
/// Probes `GET /query/status` and requires a 200 with the ptyctl status body
/// shape — a bare TCP connect (or bare 200) would misread an unrelated
/// process on a recycled port as live. Not PID-based because the recorded
/// PID is the child, which may exit while a `--linger` server is still up.
pub async fn server_alive(port: u16) -> bool {
let Ok(client) = reqwest::Client::builder()
.timeout(std::time::Duration::from_millis(500))
.build()
else {
return false;
};
match client
.get(format!("http://127.0.0.1:{port}/query/status"))
.send()
.await
{
// Require the status body shape, not just a 200, so wildcard-200 servers read dead.
Ok(resp) if resp.status() == reqwest::StatusCode::OK => resp
.json::<serde_json::Value>()
.await
.is_ok_and(|v| v.get("size").is_some()),
_ => false,
}
}
/// List all registered sessions.
pub fn list_sessions() -> Result<Vec<(String, SessionInfo)>> {
let dir = registry_dir()?;
if !dir.exists() {
return Ok(Vec::new());
}
let mut sessions = Vec::new();
for entry in fs::read_dir(&dir).context("failed to read session directory")? {
let entry = entry?;
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) == Some("json") {
let name = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_string();
if name.starts_with('.') {
continue; // skip temp files
}
if let Ok(json) = fs::read_to_string(&path)
&& let Ok(info) = serde_json::from_str::<SessionInfo>(&json)
{
sessions.push((name, info));
}
}
}
Ok(sessions)
}