use std::{
collections::{BTreeMap, HashSet},
path::{Path, PathBuf},
time::Duration,
};
use agent_ssh::{
attachment::CommandSpec,
resolver::{self, ResolverLimits},
snapshot::{self, PositionedPane, RecoveryTarget, Rect, SavedPane, SavedState, SavedTab},
};
use anyhow::{Context, Result, bail};
use clap::Args;
use serde::{Deserialize, Serialize};
use crate::{
capture::{self, NativeCapture, NativeProcess},
observations::ClientSnapshot,
};
#[derive(Debug, Args)]
pub struct SaveCli {
pub path: Option<PathBuf>,
#[arg(long)]
pub window: Option<String>,
#[arg(long, default_value = "agent-ssh")]
pub remote_program: String,
#[arg(long)]
pub shell_directory: Option<PathBuf>,
}
fn kind(process: &NativeProcess) -> String {
process
.executable
.rsplit(['/', '\\'])
.next()
.unwrap_or("")
.to_ascii_lowercase()
}
fn local_target(process: &NativeProcess) -> Result<RecoveryTarget> {
let mut args = process.argv.iter().skip(1);
let mut thread = None;
let mut cwd = None;
let mut yolo = false;
while let Some(arg) = args.next() {
match arg.as_str() {
"--yolo" | "--dangerously-bypass-approvals-and-sandbox" => yolo = true,
"--cd" | "-C" => {
cwd = Some(
args.next()
.context("missing explicit Codex working directory")?
.clone(),
)
}
"resume" if thread.is_none() => {
thread = Some(
args.next()
.context("missing explicit Codex thread ID")?
.clone(),
)
}
value if value.starts_with("--cd=") => cwd = Some(value[5..].to_owned()),
_ => bail!(
"Codex PID {} has unsupported recovery arguments; an explicit resume UUID and working directory are required",
process.pid
),
}
}
let target = RecoveryTarget::LocalCodex {
executable: process.executable.clone(),
thread_id: thread.context("live Codex does not expose an explicit resume UUID")?,
cwd: cwd.context("live Codex does not expose an explicit working directory")?,
yolo,
};
target.validate()?;
if let RecoveryTarget::LocalCodex { cwd, .. } = &target {
let bytes = cwd.as_bytes();
if !(Path::new(cwd).is_absolute()
|| cwd.starts_with("\\\\")
|| bytes.len() > 2
&& bytes[0].is_ascii_alphabetic()
&& bytes[1] == b':'
&& b"/\\".contains(&bytes[2]))
{
bail!("Codex working directory is not an explicit absolute path");
}
}
Ok(target)
}
fn ssh_host(process: &NativeProcess) -> Result<String> {
let mut args = process.argv.iter().skip(1);
while let Some(arg) = args.next() {
if arg == "--" {
return args.next().cloned().context("missing SSH destination");
}
if !arg.starts_with('-') {
return Ok(arg.clone());
}
if [
"-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o",
"-p", "-Q", "-R", "-S", "-W", "-w",
]
.contains(&arg.as_str())
{
args.next().context("missing SSH option value")?;
} else if !(arg.starts_with("-o") && arg.len() > 2
|| arg.len() > 1
&& arg[1..]
.chars()
.all(|c| "46AaCfGgKkMNnqsTtVvXxYy".contains(c)))
{
bail!(
"SSH PID {} uses unsupported destination arguments",
process.pid
);
}
}
bail!("SSH destination is unavailable")
}
fn provider(args: Vec<String>) -> Result<Vec<u8>> {
resolver::output(
&CommandSpec {
program: std::env::current_exe()?
.to_str()
.context("agent-ssh path is not UTF-8")?
.into(),
args,
cwd: None,
},
ResolverLimits {
timeout: Duration::from_secs(35),
output_bytes: 2 * 1024 * 1024,
},
)
}
fn observe(host: &str, remote_program: &str) -> Result<ClientSnapshot> {
let bytes = provider(vec![
"tmux".into(),
"--on".into(),
host.into(),
"--remote-program".into(),
remote_program.into(),
"clients".into(),
"--json".into(),
])?;
let result: ClientSnapshot =
serde_json::from_slice(&bytes).context("invalid remote client observation")?;
if result.version != 1 || !result.socket.starts_with('/') || result.clients.len() > 256 {
bail!("unsupported or incomplete remote client observation");
}
Ok(result)
}
fn build(
capture: &NativeCapture,
remote_program: &str,
shell_directory: &str,
mut observe: impl FnMut(&str) -> Result<ClientSnapshot>,
) -> Result<SavedState> {
let mut remote = BTreeMap::new();
let mut keys = HashSet::new();
let mut tabs = Vec::new();
for tab in &capture.tabs {
let mut positioned = Vec::new();
for pane in &tab.panes {
let process = capture
.processes
.iter()
.find(|p| p.pid == pane.console_pid && p.start_ticks == pane.console_start_ticks)
.context("captured pane process identity is unavailable")?;
let target = match kind(process).as_str() {
"codex.exe" => {
local_target(process).unwrap_or_else(|error| RecoveryTarget::Unavailable {
reason: error.to_string(),
})
}
"powershell.exe" | "pwsh.exe" if process.argv.len() == 1 => {
RecoveryTarget::FreshShell {
executable: process.executable.clone(),
cwd: shell_directory.into(),
}
}
"ssh.exe" => {
let host = ssh_host(process)?;
if !remote.contains_key(&host) {
remote.insert(host.clone(), observe(&host));
}
if let Ok(snapshot) = &remote[&host] {
let connections = capture
.connections
.iter()
.filter(|c| c.pid == process.pid)
.collect::<Vec<_>>();
let mut matches = Vec::new();
for connection in &connections {
for client in &snapshot.clients {
if let Some(peer) = &client.connection
&& peer.client_address == connection.local_address
&& peer.client_port == connection.local_port
&& peer.server_address == connection.remote_address
&& peer.server_port == connection.remote_port
{
matches.push(client);
}
}
}
if connections.len() != 1 || matches.len() != 1 {
RecoveryTarget::Unavailable {
reason: format!(
"SSH host {host}, PID {}: connection has no unique live tmux client; unmanaged agents require explicit recovery support",
process.pid
),
}
} else if connections[0].state != 5 && !matches[0].socket_verified {
RecoveryTarget::Unavailable {
reason: format!(
"SSH host {host}, PID {}: TCP state {} needs independent remote socket ownership proof",
process.pid, connections[0].state
),
}
} else {
RecoveryTarget::RemoteTmux {
host,
socket: snapshot.socket.clone(),
session: matches[0].session.clone(),
remote_program: remote_program.into(),
}
}
} else {
RecoveryTarget::Unavailable {
reason: format!(
"SSH host {host}: live tmux client observation is unavailable"
),
}
}
}
_ => bail!("pane has no supported recovery identity"),
};
if let RecoveryTarget::LocalCodex { thread_id, .. } = &target
&& !keys.insert(thread_id.to_ascii_lowercase())
{
bail!("multiple local panes claim the same Codex conversation");
}
positioned.push(PositionedPane {
rect: Rect {
x: pane.rect.x,
y: pane.rect.y,
width: pane.rect.width,
height: pane.rect.height,
},
pane: SavedPane {
key: format!("console-{}-{}", pane.console_pid, pane.console_start_ticks),
title: pane.title.clone(),
target,
},
});
}
tabs.push(SavedTab {
title: tab.title.clone(),
root: snapshot::reconstruct(positioned)?,
focused_pane: None,
});
}
let mut state = SavedState {
version: 3,
restorable: true,
tabs,
selected_tab: capture.selected_tab,
};
state.restorable = !state
.panes()
.iter()
.any(|p| matches!(p.target, RecoveryTarget::Unavailable { .. }));
state.validate()?;
Ok(state)
}
pub fn run(cli: SaveCli) -> Result<()> {
if let Some(path) = &cli.path {
match path.symlink_metadata() {
Ok(_) => bail!("snapshot already exists; choose a new filename"),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
}
let directory = if cli.path.is_none() {
Some(agent_ssh::snapshot_store::default_directory()?)
} else {
None
};
agent_ssh::attachment::validate_text(&cli.remote_program)?;
if cli.remote_program.trim().is_empty() || cli.remote_program.starts_with('-') {
bail!("invalid remote agent-ssh executable");
}
let shell_directory = cli
.shell_directory
.or_else(|| {
std::env::var_os("USERPROFILE")
.or_else(|| std::env::var_os("HOME"))
.map(PathBuf::from)
})
.context("fresh-shell recovery directory is unavailable")?;
if !shell_directory.is_absolute() || !shell_directory.is_dir() {
bail!("fresh-shell recovery directory must be an existing absolute directory");
}
let shell_directory = shell_directory
.to_str()
.context("fresh-shell directory is not UTF-8")?;
agent_ssh::attachment::validate_text(shell_directory)?;
eprintln!(
"Capturing terminal panes; tab selection and titles change briefly. Keep keyboard and mouse idle until capture completes."
);
let capture = capture::collect(cli.window.as_deref())?;
let state = build(&capture, &cli.remote_program, shell_directory, |host| {
observe(host, &cli.remote_program)
})?;
let path = match cli.path {
Some(path) => {
state.write_new(&path)?;
path
}
None => {
let directory = directory.unwrap();
agent_ssh::snapshot_store::write_timestamped(&state, &directory)?
}
};
println!(
"Saved {} panes in {} tabs to {}",
state.panes().len(),
state.tabs.len(),
path.display()
);
if !state.restorable {
for pane in state.panes() {
if let RecoveryTarget::Unavailable { reason } = &pane.target {
eprintln!("{}: {reason}", pane.title);
}
}
bail!(
"snapshot saved with unavailable targets; load is blocked; inspect with agent-ssh load \"{}\" --plan",
path.display()
);
}
Ok(())
}
#[derive(Debug, Serialize)]
pub struct PaneCheck {
pub title: String,
pub state: String,
pub reason: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct RestoreReport {
pub version: u32,
pub blocked: bool,
pub panes: Vec<PaneCheck>,
pub terminal_args: Vec<String>,
}
#[derive(Deserialize)]
struct ListedSession {
name: String,
}
pub fn plan(state: &SavedState, window: &str, include_focus: bool) -> Result<RestoreReport> {
state.validate()?;
let local = if state
.panes()
.iter()
.any(|p| matches!(p.target, RecoveryTarget::LocalCodex { .. }))
{
Some(capture::processes())
} else {
None
};
let mut remote = BTreeMap::<(String, String, String), Result<Vec<String>>>::new();
let mut checks = Vec::new();
for pane in state.panes() {
let observation = match &pane.target {
RecoveryTarget::Unavailable { reason } => Err(anyhow::anyhow!(reason.clone())),
RecoveryTarget::FreshShell { executable, cwd } => {
if Path::new(executable).is_file() && Path::new(cwd).is_dir() {
Ok(())
} else {
Err(anyhow::anyhow!(
"fresh-shell executable or recovery directory is unavailable"
))
}
}
RecoveryTarget::LocalCodex {
executable,
thread_id,
cwd,
..
} => {
match local
.as_ref()
.context("local ownership observation is unavailable")?
{
Err(_) => Err(anyhow::anyhow!(
"local ownership observation is unavailable"
)),
Ok(processes) => {
let mut conflict = false;
let mut uncertain = false;
for process in processes {
match local_target(process) {
Ok(RecoveryTarget::LocalCodex {
thread_id: live, ..
}) if live.eq_ignore_ascii_case(thread_id) => conflict = true,
Err(_) => uncertain = true,
_ => {}
}
}
if conflict {
Err(anyhow::anyhow!(
"conversation already has a live local Codex owner"
))
} else if uncertain {
Err(anyhow::anyhow!(
"a live local Codex owner has an unknown thread binding"
))
} else if !Path::new(executable).is_file() || !Path::new(cwd).is_dir() {
Err(anyhow::anyhow!(
"local executable or working directory is unavailable"
))
} else {
Ok(())
}
}
}
}
RecoveryTarget::RemoteTmux {
host,
socket,
remote_program,
session,
} => {
let key = (host.clone(), socket.clone(), remote_program.clone());
let records = remote.entry(key).or_insert_with(|| {
let bytes = provider(vec![
"tmux".into(),
"--on".into(),
host.clone(),
"--socket".into(),
socket.clone(),
"--remote-program".into(),
remote_program.clone(),
"list".into(),
"--json".into(),
])?;
let sessions: Vec<ListedSession> = serde_json::from_slice(&bytes)?;
Ok(sessions.into_iter().map(|s| s.name).collect())
});
match records {
Ok(names) if names.contains(session) => Ok(()),
Ok(_) => Err(anyhow::anyhow!(
"saved tmux session does not exist; replacement agents will not be launched"
)),
Err(_) => Err(anyhow::anyhow!("remote session observation is unavailable")),
}
}
};
let reason = observation.err().map(|e| e.to_string());
checks.push(PaneCheck {
title: pane.title.clone(),
state: if reason.is_none() {
"attachable"
} else {
"unavailable"
}
.into(),
reason,
});
}
let blocked = checks.iter().any(|p| p.reason.is_some());
let args = if blocked {
Vec::new()
} else {
state.wt_args(window, include_focus)?
};
Ok(RestoreReport {
version: 3,
blocked,
panes: checks,
terminal_args: args,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::capture::{NativeConnection, NativePane, NativeRect, NativeTab};
use crate::observations::{ClientObservation, SshConnection};
fn process(argv: &[&str]) -> NativeProcess {
NativeProcess {
pid: 123,
parent_pid: 1,
start_ticks: 456,
executable: argv[0].into(),
argv: argv.iter().map(|v| (*v).into()).collect(),
}
}
#[test]
fn local_resume_preserves_explicit_identity_and_policy() {
let target = local_target(&process(&[
"C:\\tools\\codex.exe",
"--yolo",
"resume",
"01a1f01b-c871-7000-b16e-58b56efdd6e4",
"--cd",
"C:\\Work Projects",
]))
.unwrap();
assert!(
matches!(target, RecoveryTarget::LocalCodex { thread_id, cwd, yolo: true, .. } if thread_id == "01a1f01b-c871-7000-b16e-58b56efdd6e4" && cwd == "C:\\Work Projects")
);
assert!(local_target(&process(&["codex.exe", "--yolo"])).is_err());
assert!(local_target(&process(&["codex.exe", "resume", "--last"])).is_err());
}
#[test]
fn ssh_destination_comes_from_argument_boundaries_not_remote_script_names() {
assert_eq!(
ssh_host(&process(&[
"ssh.exe",
"-tt",
"-o",
"ConnectTimeout=8",
"pulse-admin",
"/some/open-10.sh"
]))
.unwrap(),
"pulse-admin"
);
assert!(ssh_host(&process(&["ssh.exe", "-p"])).is_err());
assert!(ssh_host(&process(&["ssh.exe", "-unrecognized", "pulse-admin"])).is_err());
}
fn joined_capture() -> NativeCapture {
let mut ssh = process(&["ssh.exe", "-t", "host", "/historical/open-10.sh"]);
ssh.pid = 10;
let mut local = process(&[
"codex.exe",
"--yolo",
"resume",
"01a1f01b-c871-7000-b16e-58b56efdd6e4",
"--cd",
"C:\\Work Projects",
]);
local.pid = 11;
let mut second = process(&["ssh.exe", "host"]);
second.pid = 12;
let pane = |pid, x| NativePane {
console_pid: pid,
console_start_ticks: 456,
title: "same title".into(),
rect: NativeRect {
x,
y: 0.0,
width: 100.0,
height: 100.0,
},
members: vec![pid],
};
NativeCapture {
version: 1,
hwnd: "42".into(),
selected_tab: Some(1),
tabs: vec![
NativeTab {
title: "first".into(),
panes: vec![pane(10, 0.0), pane(11, 104.0)],
},
NativeTab {
title: "second".into(),
panes: vec![pane(12, 0.0)],
},
],
processes: vec![ssh, local, second],
connections: vec![
NativeConnection {
pid: 10,
state: 5,
created_filetime: 1,
local_address: "192.0.2.1".into(),
local_port: 40001,
remote_address: "192.0.2.2".into(),
remote_port: 22,
},
NativeConnection {
pid: 12,
state: 5,
created_filetime: 1,
local_address: "192.0.2.1".into(),
local_port: 40002,
remote_address: "192.0.2.2".into(),
remote_port: 22,
},
],
}
}
fn observed_clients() -> ClientSnapshot {
ClientSnapshot {
version: 1,
socket: "/tmp/private/socket".into(),
clients: [40001, 40002]
.into_iter()
.enumerate()
.map(|(index, port)| ClientObservation {
socket_verified: true,
pid: 500 + index as u32,
start_time: 789,
session_id: "$7".into(),
session: "actual-session".into(),
tty: format!("/dev/pts/{index}"),
connection: Some(SshConnection {
client_address: "192.0.2.1".into(),
client_port: port,
server_address: "192.0.2.2".into(),
server_port: 22,
}),
})
.collect(),
}
}
#[test]
fn live_socket_joins_preserve_geometry_and_allow_two_interfaces_to_one_remote_agent() {
let capture = joined_capture();
let mut calls = 0;
let saved = build(&capture, "agent-ssh", "C:/workspace", |host| {
assert_eq!(host, "host");
calls += 1;
Ok(observed_clients())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(saved.tabs.len(), 2);
assert_eq!(saved.selected_tab, Some(1));
assert!(
matches!(&saved.tabs[0].root, snapshot::PaneTree::Split { axis: snapshot::Axis::Vertical, first_fraction, .. } if (*first_fraction - 0.5).abs() < 0.001)
);
let panes = saved.panes();
assert_eq!(panes.len(), 3);
assert!(
matches!(&panes[0].target, RecoveryTarget::RemoteTmux { session, socket, .. } if session=="actual-session" && socket=="/tmp/private/socket")
);
assert!(
matches!(&panes[1].target, RecoveryTarget::LocalCodex { thread_id, .. } if thread_id=="01a1f01b-c871-7000-b16e-58b56efdd6e4")
);
assert!(
matches!(&panes[2].target, RecoveryTarget::RemoteTmux { session, .. } if session=="actual-session")
);
}
#[test]
fn missing_or_ambiguous_socket_joins_never_fall_back_to_titles_or_script_numbers() {
let capture = joined_capture();
for ambiguous in [false, true] {
let saved = build(&capture, "agent-ssh", "C:/workspace", |_| {
let mut clients = observed_clients();
if ambiguous {
clients.clients.push(clients.clients[0].clone());
} else {
clients.clients[0].connection.as_mut().unwrap().client_port = 59999;
}
Ok(clients)
})
.unwrap();
assert_eq!(saved.panes().len(), 3);
assert!(!saved.restorable);
assert!(matches!(
saved.panes()[0].target,
RecoveryTarget::Unavailable { .. }
));
assert!(saved.wt_args("new", true).is_err());
}
}
#[test]
fn unusual_tcp_states_need_peer_proof_and_every_owned_endpoint_must_be_unique() {
let mut capture = joined_capture();
capture.connections[0].state = 1;
let without_proof = build(&capture, "agent-ssh", "C:/workspace", |_| {
let mut clients = observed_clients();
clients.clients[0].socket_verified = false;
Ok(clients)
})
.unwrap();
assert!(!without_proof.restorable);
assert!(matches!(
without_proof.panes()[0].target,
RecoveryTarget::Unavailable { .. }
));
let corroborated = build(&capture, "agent-ssh", "C:/workspace", |_| {
Ok(observed_clients())
})
.unwrap();
assert!(corroborated.restorable);
capture.connections.push(NativeConnection {
pid: 10,
local_address: "192.0.2.1".into(),
local_port: 50000,
remote_address: "192.0.2.2".into(),
remote_port: 22,
state: 1,
created_filetime: 1,
});
let ambiguous = build(&capture, "agent-ssh", "C:/workspace", |_| {
Ok(observed_clients())
})
.unwrap();
assert!(!ambiguous.restorable);
assert!(matches!(
ambiguous.panes()[0].target,
RecoveryTarget::Unavailable { .. }
));
}
}