mod config;
#[cfg(unix)]
mod unix;
use agent_ssh::{
attachment::CommandSpec,
resolver::{self, ResolverLimits},
snapshot::{RecoveryTarget, RemoteCodexReference, SavedState},
};
use anyhow::{Context, Result, bail};
use base64::{Engine, engine::general_purpose::STANDARD};
use clap::Args;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeSet, fs, io::Read, process::Command, time::Duration};
#[derive(Clone, Debug, Args)]
pub struct Scope {
/// SSH execution host. Defaults to local on Unix or the configured default host.
#[arg(long, conflicts_with = "local")]
pub on: Option<String>,
/// Restrict discovery/execution to this machine.
#[arg(long)]
pub local: bool,
/// Exact tmux socket path on the execution host.
#[arg(long)]
pub socket: Option<String>,
/// Installed agent-ssh executable on the execution host.
#[arg(long, default_value = "agent-ssh")]
pub remote_program: String,
}
impl Default for Scope {
fn default() -> Self {
Self {
on: None,
local: false,
socket: None,
remote_program: "agent-ssh".into(),
}
}
}
#[derive(Debug, Args)]
pub struct StartCli {
/// Configured agent preset; see agent-ssh presets.
pub agent: String,
/// Friendly session name, unique on the execution host/socket.
#[arg(long, short)]
pub name: Option<String>,
/// Working directory on the execution host; defaults to its current directory.
#[arg(long)]
pub cwd: Option<String>,
#[command(flatten)]
pub scope: Scope,
#[arg(long)]
pub json: bool,
/// Literal arguments appended to the configured command, following --.
#[arg(last = true)]
pub args: Vec<String>,
}
#[derive(Debug, Args)]
pub struct ListCli {
#[command(flatten)]
pub scope: Scope,
#[arg(long)]
pub json: bool,
}
#[derive(Debug, Args)]
pub struct ActionCli {
/// Exact name, runtime ID or unique ID prefix (at least six characters).
pub session: String,
#[command(flatten)]
pub scope: Scope,
}
#[derive(Debug, Args)]
pub struct PresetsCli {
#[command(flatten)]
pub scope: Scope,
#[arg(long)]
pub json: bool,
}
#[derive(Debug, Args)]
pub struct RequestCli {
pub payload: String,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Request {
version: u32,
args: Vec<String>,
}
pub fn dispatch(cli: RequestCli) -> Result<()> {
if cli.payload.len() > 32768 {
bail!("session request exceeds bound");
}
let request: Request = serde_json::from_slice(&STANDARD.decode(cli.payload)?)?;
if request.version != 1 || request.args.len() > 256 {
bail!("unsupported session request");
}
let mut args = vec!["agent-ssh".to_owned()];
args.extend(request.args);
let cli = crate::parse_arguments(args).map_err(|e| anyhow::anyhow!(e.to_string()))?;
use crate::Operation;
match cli.operation {
Some(Operation::Start(cli)) if cli.scope.local => {
let json = cli.json;
match start(cli) {
Err(error) if json => {
println!(
"{}",
serde_json::json!({"version":1,"error":format!("{error:#}")})
);
Ok(())
}
result => result,
}
}
Some(Operation::List(cli)) if cli.scope.local => list(cli),
Some(Operation::Attach(cli)) if cli.scope.local => action(cli, "attach"),
Some(Operation::Detach(cli)) if cli.scope.local => action(cli, "detach"),
Some(Operation::Stop(cli)) if cli.scope.local => action(cli, "stop"),
Some(Operation::Presets(cli)) if cli.scope.local => presets(cli),
_ => bail!("session requests must select one local session operation"),
}
}
#[derive(Serialize, Deserialize)]
pub struct Inventory {
#[serde(default = "protocol")]
pub version: u32,
pub sessions: Vec<Row>,
pub warnings: Vec<String>,
}
fn protocol() -> u32 {
1
}
impl Default for Inventory {
fn default() -> Self {
Self {
version: 1,
sessions: Vec::new(),
warnings: Vec::new(),
}
}
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Row {
pub id: String,
pub name: String,
pub agent: Option<String>,
pub host: String,
pub on: Option<String>,
pub backend: String,
pub clients: Option<u32>,
pub state: String,
pub recovery: String,
pub capabilities: Vec<String>,
pub reference: Reference,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Reference {
Tmux {
socket: String,
session: String,
},
RemoteCodex {
reference: Box<RemoteCodexReference>,
},
LocalCodex {
thread_id: String,
},
LocalProcess {
pid: u32,
start_ticks: u64,
},
}
fn quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
fn command(
scope: &Scope,
host: &str,
verb: &str,
args: Vec<String>,
interactive: bool,
) -> Result<CommandSpec> {
config::host(host)?;
if scope.remote_program.is_empty()
|| scope.remote_program.starts_with('-')
|| scope.remote_program.chars().any(char::is_control)
{
bail!("invalid remote agent-ssh executable");
}
agent_ssh::attachment::validate_text(&scope.remote_program)?;
let mut words = vec![scope.remote_program.clone(), verb.into(), "--local".into()];
if let Some(socket) = &scope.socket {
words.extend(["--socket".into(), socket.clone()]);
}
words.extend(args);
let request = STANDARD.encode(serde_json::to_vec(&Request {
version: 1,
args: words.iter().skip(1).cloned().collect(),
})?);
if request.len() > 24000 {
bail!("remote session arguments exceed transport bound");
}
let words = [
scope.remote_program.clone(),
"session-request".into(),
request,
];
#[cfg(windows)]
let executable = crate::terminal::SSH_EXE;
#[cfg(not(windows))]
let executable = "ssh";
Ok(CommandSpec {
program: executable.into(),
args: vec![
"-o".into(),
"BatchMode=yes".into(),
"-o".into(),
"ConnectTimeout=8".into(),
if interactive { "-t" } else { "-T" }.into(),
"--".into(),
host.into(),
words.iter().map(|s| quote(s)).collect::<Vec<_>>().join(" "),
],
cwd: None,
})
}
fn remote_inventory(scope: &Scope, host: &str) -> Result<Inventory> {
let spec = command(scope, host, "list", vec!["--json".into()], false)?;
let bytes = resolver::output(
&spec,
ResolverLimits {
timeout: Duration::from_secs(25),
output_bytes: 4 * 1024 * 1024,
},
);
let mut inventory: Inventory = match bytes
.and_then(|b| serde_json::from_slice(&b).context("invalid session inventory"))
{
Ok(inv) => inv,
Err(original) => {
let mut words = vec![scope.remote_program.clone(), "tmux".into()];
if let Some(socket) = &scope.socket {
words.extend(["--socket".into(), socket.clone()]);
}
words.extend(["list".into(), "--json".into()]);
let mut legacy = spec.clone();
*legacy.args.last_mut().context("missing SSH command")? =
words.iter().map(|s| quote(s)).collect::<Vec<_>>().join(" ");
#[derive(Deserialize)]
struct Legacy {
id: String,
name: String,
attached_clients: u32,
}
let bytes = resolver::output(
&legacy,
ResolverLimits {
timeout: Duration::from_secs(20),
output_bytes: 4 * 1024 * 1024,
},
)
.with_context(|| format!("session discovery failed: {original:#}"))?;
let rows: Vec<Legacy> = serde_json::from_slice(&bytes)?;
let socket = if let Some(path) = &scope.socket {
path.clone()
} else {
words.truncate(2);
words.extend(["clients".into(), "--json".into()]);
*legacy.args.last_mut().context("missing SSH command")? =
words.iter().map(|s| quote(s)).collect::<Vec<_>>().join(" ");
let bytes = resolver::output(&legacy, ResolverLimits::default())?;
let clients: crate::observations::ClientSnapshot = serde_json::from_slice(&bytes)?;
clients.socket
};
Inventory{version:1,warnings:vec!["Named-session metadata unavailable; showing tmux inventory. Check the target version/configuration.".into()],sessions:rows.into_iter().map(|r|Row{id:format!("tmux:{}",r.id),name:r.name.clone(),agent:None,host:host.into(),on:Some(host.into()),backend:"tmux".into(),clients:Some(r.attached_clients),state:if r.attached_clients>0{"attached"}else{"detached"}.into(),recovery:"attach".into(),capabilities:vec!["attach".into()],reference:Reference::Tmux{socket:socket.clone(),session:r.name}}).collect()}
}
};
if inventory.version != 1 || inventory.sessions.len() > 4096 {
bail!("unsupported session inventory");
}
for row in &mut inventory.sessions {
row.host = host.into();
row.on = Some(host.into());
if let Reference::Tmux { socket, session } = &row.reference {
if !socket.starts_with('/')
|| session.is_empty()
|| session.chars().any(char::is_control)
{
bail!("invalid remote tmux reference");
}
} else if let Reference::RemoteCodex { reference } = &row.reference {
reference.validate()?;
if row.capabilities.iter().any(|s| s != "attach") {
bail!("invalid direct agent capabilities");
}
} else if let Reference::LocalCodex { thread_id } = &row.reference {
uuid::Uuid::parse_str(thread_id).context("invalid remote local conversation ID")?;
if !row.capabilities.is_empty() {
bail!("unsupported remote native Codex actions");
}
} else {
bail!("remote local inventory returned an unsupported reference");
}
}
Ok(inventory)
}
fn saved() -> Result<Option<SavedState>> {
let directory = agent_ssh::snapshot_store::default_directory()?;
if !directory.exists() {
return Ok(None);
}
let path = match agent_ssh::snapshot_store::latest(&directory) {
Ok(path) => path,
Err(error) => {
if fs::read_dir(&directory)?.next().is_none() {
return Ok(None);
}
return Err(error);
}
};
let mut text = String::new();
fs::File::open(&path)?
.take(2 * 1024 * 1024 + 1)
.read_to_string(&mut text)?;
SavedState::parse(&text).map(Some).with_context(|| {
format!(
"cannot read saved session references from {}",
path.display()
)
})
}
fn host_directory() -> Result<std::path::PathBuf> {
Ok(agent_ssh::snapshot_store::default_directory()?
.parent()
.context("state directory unavailable")?
.join("hosts"))
}
fn known_hosts() -> Result<BTreeSet<String>> {
let directory = host_directory()?;
let mut hosts = BTreeSet::new();
if !directory.exists() {
return Ok(hosts);
}
for (index, entry) in fs::read_dir(directory)?.enumerate() {
if index >= 4096 {
bail!("known host registry exceeds bound");
}
let path = entry?.path();
if path.extension().is_none_or(|e| e != "json") {
continue;
}
let meta = path.symlink_metadata()?;
if !meta.is_file() || meta.len() > 4096 {
bail!("invalid known host record");
}
let host: String = serde_json::from_slice(&fs::read(path)?)?;
config::host(&host)?;
hosts.insert(host);
}
Ok(hosts)
}
fn remember_host(host: &str) -> Result<()> {
use std::{
hash::{Hash, Hasher},
io::Write,
};
let directory = host_directory()?;
fs::create_dir_all(&directory)?;
let mut hash = std::collections::hash_map::DefaultHasher::new();
host.hash(&mut hash);
let path = directory.join(format!("{:016x}.json", hash.finish()));
if path.exists() {
return Ok(());
}
let pending = directory.join(format!("{}.pending", uuid::Uuid::new_v4()));
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&pending)?;
file.write_all(&serde_json::to_vec(host)?)?;
file.sync_all()?;
drop(file);
let published = fs::hard_link(&pending, &path);
fs::remove_file(pending)?;
match published {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
Err(e) => Err(e.into()),
}
}
pub(crate) fn sockets_on(host: &str, remote_program: &str) -> Result<Vec<String>> {
let scope = Scope {
remote_program: remote_program.into(),
..Scope::default()
};
let inventory = remote_inventory(&scope, host)?;
let mut sockets = BTreeSet::new();
for row in inventory.sessions {
if let Reference::Tmux { socket, .. } = row.reference {
sockets.insert(socket);
}
}
Ok(sockets.into_iter().collect())
}
pub fn inventory(scope: &Scope) -> Result<Inventory> {
let settings = config::load()?;
let mut output = Inventory {
version: 1,
..Inventory::default()
};
let snapshot = match saved() {
Ok(s) => s,
Err(e) => {
output.warnings.push(format!("Saved sessions: {e:#}"));
None
}
};
let mut hosts = BTreeSet::new();
if let Some(host) = &scope.on {
config::host(host)?;
hosts.insert(host.clone());
} else if !scope.local {
match known_hosts() {
Ok(known) => hosts.extend(known),
Err(e) => output.warnings.push(format!("Known hosts: {e:#}")),
}
hosts.extend(settings.hosts);
if let Some(host) = settings.default_host {
hosts.insert(host);
}
if let Some(state) = &snapshot {
for pane in state.panes() {
match &pane.target {
RecoveryTarget::RemoteTmux { host, .. }
| RecoveryTarget::RemoteCodex { host, .. } => {
hosts.insert(host.clone());
}
_ => {}
}
}
}
}
if scope.on.is_none() {
#[cfg(unix)]
match unix::inventory(scope) {
Ok(inv) => {
output.sessions.extend(inv.sessions);
output.warnings.extend(inv.warnings);
}
Err(e) => output.warnings.push(format!("Local tmux: {e:#}")),
}
}
#[cfg(windows)]
let local = if scope.on.is_none() {
Some(crate::capture::processes())
} else {
None
};
#[cfg(not(windows))]
let local: Option<Result<Vec<crate::capture::NativeProcess>>> = None;
if let Some(Ok(processes)) = &local {
for process in processes {
let (id, name, reference) = match crate::save::local_target(process) {
Ok(RecoveryTarget::LocalCodex { thread_id, .. }) => (
thread_id.clone(),
format!("codex-{}", &thread_id[..8]),
Reference::LocalCodex { thread_id },
),
_ => (
format!("process:{}:{}", process.pid, process.start_ticks),
format!("codex-{}", process.pid),
Reference::LocalProcess {
pid: process.pid,
start_ticks: process.start_ticks,
},
),
};
output.sessions.push(Row {
id,
name,
agent: Some("codex".into()),
host: "local".into(),
on: None,
backend: "local-codex".into(),
clients: Some(1),
state: "running".into(),
recovery: "in-use".into(),
capabilities: vec![],
reference,
});
}
}
for host in &hosts {
match remote_inventory(scope, host) {
Ok(inv) => {
output.sessions.extend(inv.sessions);
output
.warnings
.extend(inv.warnings.into_iter().map(|w| format!("{host}: {w}")));
}
Err(e) => output.warnings.push(format!("{host}: {e:#}")),
}
}
if let Some(snapshot) = snapshot {
for pane in snapshot.panes() {
match &pane.target {
RecoveryTarget::LocalCodex { thread_id, .. } if scope.on.is_none() => {
let state = match &local {
Some(Ok(processes))
if processes.iter().any(|p| {
p.argv.iter().any(|a| a.eq_ignore_ascii_case(thread_id))
}) =>
{
"running"
}
Some(Ok(_)) => "resume_available",
_ => "unknown",
};
output.sessions.push(Row {
id: thread_id.clone(),
name: format!("codex-{}", &thread_id[..8]),
agent: Some("codex".into()),
host: "local".into(),
on: None,
backend: "local-codex".into(),
clients: if state == "running" { Some(1) } else { None },
state: state.into(),
recovery: if state == "resume_available" {
"resume"
} else {
"in-use"
}
.into(),
capabilities: vec![],
reference: Reference::LocalCodex {
thread_id: thread_id.clone(),
},
});
}
RecoveryTarget::RemoteCodex { host, reference } if hosts.contains(host) => {
if output
.sessions
.iter()
.any(|row| row.host == *host && row.id == reference.thread_id)
{
continue;
}
let check = crate::remote_codex::check(host, reference);
if check
.as_ref()
.is_ok_and(|c| c.mode.as_deref() == Some("managed"))
{
continue;
}
let (state, recovery, capabilities) = match check {
Ok(c) if c.state == "already_running" => ("running", "in-use", vec![]),
Ok(c)
if c.state == "attachable" && c.mode.as_deref() == Some("reattach") =>
{
("detached", "attach", vec!["attach".into()])
}
Ok(c) if c.state == "attachable" => ("resume_available", "resume", vec![]),
_ => ("unknown", "unavailable", vec![]),
};
output.sessions.push(Row {
id: reference.thread_id.clone(),
name: format!("codex-{}", &reference.thread_id[..8]),
agent: Some("codex".into()),
host: host.clone(),
on: Some(host.clone()),
backend: "marshal-codex".into(),
clients: if state == "running" { Some(1) } else { Some(0) },
state: state.into(),
recovery: recovery.into(),
capabilities,
reference: Reference::RemoteCodex {
reference: reference.clone(),
},
});
}
_ => {}
}
}
}
output
.sessions
.sort_by(|a, b| (&a.host, &a.name, &a.id).cmp(&(&b.host, &b.name, &b.id)));
output
.sessions
.dedup_by(|a, b| a.host == b.host && a.id == b.id && a.backend == b.backend);
Ok(output)
}
pub fn list(cli: ListCli) -> Result<()> {
let progress = crate::progress::Progress::new("Discovering sessions", !cli.json);
let result = inventory(&cli.scope)?;
drop(progress);
if cli.json {
println!("{}", serde_json::to_string_pretty(&result)?);
return Ok(());
}
for warning in &result.warnings {
eprintln!("Warning: {warning}");
}
if result.sessions.is_empty() {
if !result.warnings.is_empty() {
println!("No sessions could be confirmed. Check the warnings above.");
return Ok(());
}
println!("No sessions found. Start one with agent-ssh start codex --on <host>.");
return Ok(());
}
println!(
"{:<10} {:<22} {:<8} {:<12} {:<7} STATUS",
"ID", "NAME", "AGENT", "HOST", "CLIENTS"
);
for row in result.sessions {
let id = if uuid::Uuid::parse_str(&row.id).is_ok() {
&row.id[..8]
} else {
&row.id
};
println!(
"{:<10} {:<22} {:<8} {:<12} {:<7} {}",
cell(id, 10),
cell(&row.name, 22),
cell(row.agent.as_deref().unwrap_or("—"), 8),
cell(&row.host, 12),
row.clients
.map(|n| n.to_string())
.unwrap_or_else(|| "—".into()),
match row.state.as_str() {
"resume_available" => "resumable",
"running" if row.recovery == "in-use" => "in use",
other => other,
}
);
}
Ok(())
}
fn cell(value: &str, width: usize) -> String {
let text = value
.chars()
.map(|c| if c.is_control() { '�' } else { c })
.collect::<String>();
if text.chars().count() > width {
format!("{}…", text.chars().take(width - 1).collect::<String>())
} else {
text
}
}
fn execution_host(scope: &Scope) -> Result<Option<String>> {
if scope.local {
return Ok(None);
}
let host = scope.on.clone().or(config::load()?.default_host);
if let Some(h) = &host {
config::host(h)?;
}
Ok(host)
}
fn handoff(spec: CommandSpec, interactive: bool) -> Result<()> {
let mut command = Command::new(spec.program);
command.args(spec.args);
if interactive {
command.env(
"TERM",
std::env::var("TERM")
.ok()
.filter(|s| !s.is_empty() && s != "dumb")
.unwrap_or_else(|| "xterm-256color".into()),
);
}
let status = command.status().context("cannot execute session command")?;
if !status.success() {
bail!("session command exited with {status}");
}
Ok(())
}
pub fn start(cli: StartCli) -> Result<()> {
config::name(&cli.agent)?;
if let Some(name) = &cli.name {
config::name(name)?;
}
if let Some(host) = execution_host(&cli.scope)? {
let mut args = vec![cli.agent.clone()];
if let Some(name) = &cli.name {
args.extend(["--name".into(), name.clone()]);
}
if let Some(cwd) = &cli.cwd {
args.extend(["--cwd".into(), cwd.clone()]);
}
args.push("--json".into());
if !cli.args.is_empty() {
args.push("--".into());
args.extend(cli.args.clone());
}
let progress = crate::progress::Progress::new("Starting session", !cli.json);
let bytes=resolver::output(&command(&cli.scope,&host,"start",args,false)?,ResolverLimits{timeout:Duration::from_secs(35),output_bytes:1024*1024}).with_context(||format!("launch on {host} was not confirmed; inspect agent-ssh list --on {host} before retrying"))?;
let response: serde_json::Value = serde_json::from_slice(&bytes).with_context(|| {
format!(
"launch response on {host} was invalid; inspect existing sessions before retrying"
)
})?;
if let Some(error) = response.get("error").and_then(serde_json::Value::as_str) {
bail!("{host}: {error}");
}
let mut result: Inventory = serde_json::from_value(response).with_context(|| {
format!(
"launch response on {host} was invalid; inspect existing sessions before retrying"
)
})?;
if result.version != 1 || result.sessions.len() != 1 {
bail!(
"launch response did not identify exactly one runtime; inspect existing sessions before retrying"
);
}
uuid::Uuid::parse_str(&result.sessions[0].id).context(
"launch returned an invalid runtime ID; inspect existing sessions before retrying",
)?;
config::name(&result.sessions[0].name)?;
if cli
.name
.as_ref()
.is_some_and(|name| name != &result.sessions[0].name)
{
bail!(
"launch returned an unexpected session name; inspect existing sessions before retrying"
);
}
let row = &mut result.sessions[0];
row.on = Some(host.clone());
row.host = host.clone();
drop(progress);
if let Err(e) = remember_host(&host) {
eprintln!("Warning: session started, but the host could not be remembered: {e:#}");
}
if cli.json {
println!("{}", serde_json::to_string_pretty(&result)?);
} else {
println!(
"Started {} on {} ({})\n Attach: agent-ssh attach {} --on {}",
row.name,
host,
&row.id[..8],
row.name,
host
);
}
return Ok(());
}
#[cfg(unix)]
{
unix::start(cli)
}
#[cfg(not(unix))]
{
let _ = cli;
bail!(
"local persistent launches require Unix; specify --on HOST or configure default_host"
);
}
}
pub fn select<'a>(rows: &'a [Row], selector: &str) -> Result<&'a Row> {
let exact = rows
.iter()
.filter(|r| r.id == selector || r.name == selector)
.collect::<Vec<_>>();
let found = if exact.is_empty() && selector.len() >= 6 {
rows.iter()
.filter(|r| r.id.starts_with(selector))
.collect::<Vec<_>>()
} else {
exact
};
match found.as_slice() {
[row] => Ok(row),
[] => bail!("session {selector:?} not found; run agent-ssh list"),
_ => bail!(
"session {selector:?} is ambiguous; specify --on HOST and an exact name or longer runtime ID"
),
}
}
pub fn action(cli: ActionCli, verb: &str) -> Result<()> {
let mut scope = cli.scope;
if scope.on.is_none() && !scope.local {
scope.on = config::load()?.default_host;
}
let inventory = inventory(&scope)?;
let row = select(&inventory.sessions, &cli.session)?;
if !row.capabilities.iter().any(|c| c == verb) {
bail!(
"{} supports [{}] through agent-ssh; state: {}. Use the owning backend for other operations.",
row.name,
row.capabilities.join(", "),
row.state
);
}
if let Reference::RemoteCodex { reference } = &row.reference {
#[cfg(unix)]
if row.on.is_none() {
return crate::remote_codex::attach_local(reference);
}
let mut args = vec![
"codex-recover".into(),
"--on".into(),
row.on.clone().context("remote host unavailable")?,
"--existing-only".into(),
"--reference".into(),
serde_json::to_string(reference)?,
];
let status = Command::new(std::env::current_exe()?)
.args(std::mem::take(&mut args))
.status()?;
if !status.success() {
bail!("reattachment failed");
}
return Ok(());
}
if let Some(host) = &row.on {
let Reference::Tmux { socket, session } = &row.reference else {
bail!("unsupported remote session backend");
};
if verb == "attach" && !row.capabilities.iter().any(|c| c == "stop") {
return crate::tmux::attach_known(
Some(host.clone()),
socket.clone(),
session.clone(),
scope.remote_program.clone(),
);
}
let mut scoped = scope.clone();
scoped.socket = Some(socket.clone());
return handoff(
command(
&scoped,
host,
verb,
vec!["--".into(), row.id.clone()],
verb == "attach",
)?,
verb == "attach",
);
}
#[cfg(unix)]
{
unix::action(&scope, row, verb)
}
#[cfg(not(unix))]
{
bail!("this local session cannot be attached through agent-ssh");
}
}
pub fn presets(cli: PresetsCli) -> Result<()> {
if let Some(host) = execution_host(&cli.scope)? {
return handoff(
command(
&cli.scope,
&host,
"presets",
if cli.json {
vec!["--json".into()]
} else {
vec![]
},
false,
)?,
false,
);
}
let settings = config::load()?;
if cli.json {
println!("{}", serde_json::to_string_pretty(&settings.presets)?);
} else {
println!("{:<18} {:<14} DESCRIPTION", "PRESET", "AGENT");
for (name, preset) in settings.presets {
println!(
"{:<18} {:<14} {}",
name,
preset.agent.as_deref().unwrap_or("—"),
preset.description
);
}
println!(
"\nConfiguration: {}",
config::directory()?.join("config.json").display()
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn row(id: &str, name: &str, host: &str) -> Row {
Row {
id: id.into(),
name: name.into(),
agent: Some("codex".into()),
host: host.into(),
on: Some(host.into()),
backend: "tmux".into(),
clients: Some(0),
state: "detached".into(),
recovery: "attach".into(),
capabilities: vec!["attach".into()],
reference: Reference::Tmux {
socket: "/tmp/example.sock".into(),
session: name.into(),
},
}
}
#[test]
fn selection_is_exact_or_uniquely_identified_across_hosts() {
let rows = vec![
row("12345678-aaaa", "review", "a"),
row("87654321-bbbb", "review-long", "b"),
];
assert_eq!(select(&rows, "review").unwrap().host, "a");
assert_eq!(select(&rows, "876543").unwrap().host, "b");
assert!(select(&rows, "review-l").is_err());
let duplicate = vec![
row("12345678-aaaa", "review", "a"),
row("12345679-bbbb", "review", "b"),
];
assert!(select(&duplicate, "review").is_err());
assert!(select(&duplicate, "123456").is_err());
}
#[test]
fn remote_commands_quote_arguments_and_attach_is_the_only_pty_operation() {
let scope = Scope::default();
let spec = command(
&scope,
"host",
"start",
vec!["codex".into(), "--".into(), "a'$(touch bad);value".into()],
false,
)
.unwrap();
assert!(spec.args.contains(&"-T".into()));
let encoded = spec.args.last().unwrap().split('\'').nth(5).unwrap();
let request: Request = serde_json::from_slice(&STANDARD.decode(encoded).unwrap()).unwrap();
assert_eq!(request.args.last().unwrap(), "a'$(touch bad);value");
assert!(command(&scope, "-oProxyCommand=bad", "list", vec![], false).is_err());
assert!(
command(&scope, "host", "attach", vec!["review".into()], true)
.unwrap()
.args
.contains(&"-t".into())
);
}
}