use agent_ssh::{
attachment::CommandSpec,
resolver::{self, ResolverLimits},
snapshot::RemoteCodexReference,
};
use anyhow::{Context, Result, bail};
use base64::{Engine, engine::general_purpose::STANDARD};
use clap::Args;
use serde::Deserialize;
use serde_json::Value;
use std::{process::Command, time::Duration};
#[derive(Debug, Args)]
pub struct RecoverCli {
#[arg(long)]
on: String,
#[arg(long)]
reference: String,
#[arg(long)]
existing_only: bool,
}
#[derive(Debug, Deserialize)]
pub struct Observed {
pub connection: (String, u16, String, u16),
pub reference: RemoteCodexReference,
}
#[derive(Debug, Deserialize)]
pub struct Check {
pub state: String,
pub reason: Option<String>,
pub mode: Option<String>,
}
#[cfg(unix)]
#[derive(Deserialize)]
pub struct LocalObserved {
pub reference: RemoteCodexReference,
pub observation: Check,
}
#[cfg(unix)]
pub fn local_inventory() -> Result<Vec<LocalObserved>> {
let rows: Vec<LocalObserved> = serde_json::from_slice(&resolver::output(
&local_spec("observe-local", &Value::Null)?,
ResolverLimits {
timeout: Duration::from_secs(15),
output_bytes: 2 * 1024 * 1024,
},
)?)?;
if rows.len() > 256 {
bail!("direct agent inventory exceeds bound");
}
for row in &rows {
row.reference.validate()?;
}
Ok(rows)
}
#[cfg(unix)]
fn local_spec(action: &str, reference: &Value) -> Result<CommandSpec> {
let encoded = STANDARD.encode(include_bytes!("../scripts/remote-codex.py"));
Ok(CommandSpec {
program: "python3".into(),
args: vec![
"-c".into(),
format!("exec(__import__('base64').b64decode('{encoded}'))"),
action.into(),
serde_json::to_string(reference)?,
],
cwd: None,
})
}
#[cfg(unix)]
pub fn attach_local(reference: &RemoteCodexReference) -> Result<()> {
reference.validate()?;
let spec = local_spec("attach-existing", &serde_json::to_value(reference)?)?;
use std::os::unix::process::CommandExt;
Err(Command::new(spec.program).args(spec.args).exec())
.context("could not attach to direct Codex runtime")
}
fn quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
fn spec(host: &str, action: &str, request: &Value, interactive: bool) -> Result<CommandSpec> {
agent_ssh::attachment::validate_text(host)?;
if host.is_empty() || host.starts_with('-') || host.chars().any(char::is_whitespace) {
bail!("invalid SSH target");
}
let encoded = STANDARD.encode(include_bytes!("../scripts/remote-codex.py"));
let script = format!("exec(__import__('base64').b64decode('{encoded}'))");
let command = [
"python3".to_owned(),
"-c".into(),
script,
action.into(),
serde_json::to_string(request)?,
]
.iter()
.map(|s| quote(s))
.collect::<Vec<_>>()
.join(" ");
let mut args = vec![
"-o".into(),
"BatchMode=yes".into(),
"-o".into(),
"ConnectTimeout=8".into(),
if interactive { "-t" } else { "-T" }.into(),
"--".into(),
host.into(),
command,
];
#[cfg(windows)]
let program = crate::terminal::SSH_EXE;
#[cfg(not(windows))]
let program = "ssh";
let result = CommandSpec {
program: program.into(),
args: std::mem::take(&mut args),
cwd: None,
};
result.validate()?;
Ok(result)
}
fn read(host: &str, action: &str, request: &Value) -> Result<Vec<u8>> {
resolver::output(
&spec(host, action, request, false)?,
ResolverLimits {
timeout: Duration::from_secs(20),
output_bytes: 2 * 1024 * 1024,
},
)
.context("remote Codex recovery observation failed")
}
pub fn observe(host: &str, tuples: &[(String, u16, String, u16)]) -> Result<Vec<Observed>> {
let rows: Vec<Observed> =
serde_json::from_slice(&read(host, "observe", &serde_json::to_value(tuples)?)?)?;
if rows.len() > 256 {
bail!("remote Codex observation exceeds bound");
}
for row in &rows {
row.reference.validate()?;
if !tuples.contains(&row.connection) {
bail!("remote observation changed the requested connection tuple");
}
}
Ok(rows)
}
pub fn check(host: &str, reference: &RemoteCodexReference) -> Result<Check> {
reference.validate()?;
let result: Check =
serde_json::from_slice(&read(host, "check", &serde_json::to_value(reference)?)?)?;
if !matches!(
result.state.as_str(),
"attachable" | "already_running" | "unavailable"
) {
bail!("unsupported remote Codex recovery state");
}
Ok(result)
}
pub fn run(cli: RecoverCli) -> Result<()> {
let reference: RemoteCodexReference = serde_json::from_str(&cli.reference)?;
reference.validate()?;
let command = spec(
&cli.on,
if cli.existing_only {
"attach-existing"
} else {
"attach"
},
&serde_json::to_value(reference)?,
true,
)?;
let mut process = Command::new(command.program);
process.args(command.args).env("TERM", "xterm-256color");
let status = process
.status()
.context("cannot start remote Codex recovery")?;
if !status.success() {
bail!("remote Codex recovery exited with {status}");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn observer_uses_literal_arguments_and_never_allocates_a_pty() {
let command = spec(
"host",
"observe",
&serde_json::json!(["a'$(touch /tmp/nope)"]),
false,
)
.unwrap();
assert!(command.args.contains(&"-T".to_owned()));
assert!(!command.args.contains(&"-t".to_owned()));
assert!(command.args.last().unwrap().contains("'\\''"));
assert!(spec("-oProxyCommand=bad", "observe", &Value::Null, false).is_err());
}
}