agent-ssh 0.4.5

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
use agent_ssh::snapshot::{RecoveryTarget, RemoteCodexReference, SavedState};
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::{env, ffi::c_void, fs::File, io::Read, path::Path};

const SNAPSHOT_LIMIT: u64 = 2 * 1024 * 1024;
const RECEIPT_LIMIT: u64 = 4096;

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Receipt {
    version: u32,
    snapshot_sha256: String,
}

pub(super) fn recover(host: &str, payload: &[u8]) -> Result<Option<RemoteCodexReference>> {
    let Some(base) = env::var_os("LOCALAPPDATA").filter(|s| !s.is_empty()) else {
        return Ok(None);
    };
    recover_from(&Path::new(&base).join("agent-ssh"), host, payload)
        .context("invalid configured legacy recovery baseline")
}

fn recover_from(base: &Path, host: &str, payload: &[u8]) -> Result<Option<RemoteCodexReference>> {
    let receipt = match File::open(base.join("legacy-recovery-baseline.json")) {
        Ok(file) => file,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(error).context("cannot open legacy recovery receipt"),
    };
    if !base.is_absolute() {
        bail!("legacy recovery directory must be absolute");
    }
    let receipt: Receipt = serde_json::from_slice(&bounded(receipt, RECEIPT_LIMIT)?)
        .context("invalid legacy recovery receipt JSON")?;
    let hash = &receipt.snapshot_sha256;
    if receipt.version != 1 || hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
        bail!("legacy recovery receipt requires version 1 and a SHA256 digest");
    }
    let hash = hash.to_ascii_lowercase();
    let snapshot = File::open(base.join("baselines").join(format!("{hash}.json")))
        .context("cannot open pinned legacy recovery snapshot")?;
    let bytes = bounded(snapshot, SNAPSHOT_LIMIT)?;
    if format!("{:x}", Sha256::digest(&bytes)) != hash {
        bail!("pinned legacy recovery snapshot SHA256 mismatch");
    }
    let state = SavedState::parse(std::str::from_utf8(&bytes)?)
        .context("invalid pinned legacy recovery snapshot")?;
    select(&state, host, payload)
}

fn bounded(file: File, limit: u64) -> Result<Vec<u8>> {
    if !file.metadata()?.is_file() {
        bail!("legacy recovery source must be a regular file");
    }
    let mut bytes = Vec::new();
    file.take(limit + 1).read_to_end(&mut bytes)?;
    if bytes.len() as u64 > limit {
        bail!("legacy recovery source exceeds size limit");
    }
    Ok(bytes)
}

fn select(state: &SavedState, host: &str, payload: &[u8]) -> Result<Option<RemoteCodexReference>> {
    let mut matched: Option<(String, RemoteCodexReference)> = None;
    for pane in state.panes() {
        let RecoveryTarget::RemoteCodex {
            host: candidate_host,
            reference,
        } = &pane.target
        else {
            continue;
        };
        if candidate_host != host {
            continue;
        }
        let canonical = serde_json::to_string(reference)?;
        if projection(&canonical)?.as_deref().map(str::as_bytes) != Some(payload) {
            continue;
        }
        if let Some((previous, _)) = &matched {
            if previous != &canonical {
                bail!("legacy recovery reference is ambiguous in pinned snapshot");
            }
        } else {
            matched = Some((canonical, reference.as_ref().clone()));
        }
    }
    Ok(matched.map(|(_, reference)| reference))
}

#[link(name = "shell32")]
unsafe extern "system" {
    fn CommandLineToArgvW(command: *const u16, count: *mut i32) -> *mut *mut u16;
}
#[link(name = "kernel32")]
unsafe extern "system" {
    fn LocalFree(memory: *mut c_void) -> *mut c_void;
}

fn projection(canonical: &str) -> Result<Option<String>> {
    let command: Vec<u16> = format!("dummy.exe {canonical}")
        .encode_utf16()
        .chain([0])
        .collect();
    let mut count = 0;
    unsafe {
        let args = CommandLineToArgvW(command.as_ptr(), &mut count);
        if args.is_null() {
            return Err(std::io::Error::last_os_error())
                .context("cannot project legacy Windows argument");
        }
        let projected = if count == 2 {
            let value = *args.add(1);
            let mut length = 0;
            while *value.add(length) != 0 {
                length += 1;
            }
            Some(String::from_utf16(std::slice::from_raw_parts(
                value, length,
            )))
        } else {
            None
        };
        LocalFree(args.cast());
        projected
            .transpose()
            .context("invalid UTF-16 legacy Windows argument")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use agent_ssh::snapshot::{PaneTree, SavedPane, SavedTab};
    use std::{fs, path::PathBuf};

    fn reference() -> RemoteCodexReference {
        RemoteCodexReference {
            thread_id: "12345678-1234-1234-1234-123456789abc".into(),
            cwd: "/work/a path".into(),
            yolo: false,
            codex_program: "/bin/codex".into(),
            managed_program: "/bin/managed".into(),
            codex_home: "/home/test/.codex".into(),
            launcher_pid: 42,
            launcher_start: 123,
            state_file: "/tmp/session.json".into(),
        }
    }

    fn state(references: Vec<RemoteCodexReference>) -> SavedState {
        SavedState {
            version: 3,
            restorable: true,
            selected_tab: Some(0),
            tabs: references
                .into_iter()
                .enumerate()
                .map(|(index, reference)| SavedTab {
                    title: "fixture".into(),
                    focused_pane: None,
                    root: PaneTree::Pane {
                        pane: SavedPane {
                            key: format!("pane-{index}"),
                            title: "fixture".into(),
                            target: RecoveryTarget::RemoteCodex {
                                host: "fixture-host".into(),
                                reference: Box::new(reference),
                            },
                        },
                    },
                })
                .collect(),
        }
    }

    struct Baseline(PathBuf);

    impl Baseline {
        fn new(bytes: &[u8]) -> Self {
            let base =
                std::env::temp_dir().join(format!("agent-ssh-legacy-{}", uuid::Uuid::new_v4()));
            fs::create_dir_all(base.join("baselines")).unwrap();
            let hash = format!("{:x}", Sha256::digest(bytes));
            fs::write(base.join("baselines").join(format!("{hash}.json")), bytes).unwrap();
            fs::write(
                base.join("legacy-recovery-baseline.json"),
                format!(r#"{{"version":1,"snapshot_sha256":"{hash}"}}"#),
            )
            .unwrap();
            Self(base)
        }

        fn recover(&self, host: &str, payload: &[u8]) -> Result<Option<RemoteCodexReference>> {
            recover_from(&self.0, host, payload)
        }
    }

    impl Drop for Baseline {
        fn drop(&mut self) {
            assert_eq!(self.0.parent(), Some(std::env::temp_dir().as_path()));
            assert!(
                self.0
                    .file_name()
                    .unwrap()
                    .to_str()
                    .unwrap()
                    .starts_with("agent-ssh-legacy-")
            );
            fs::remove_dir_all(&self.0).unwrap();
        }
    }

    #[test]
    fn retained_windows_argument_recovers_only_the_exact_host_and_original_reference() {
        let original = reference();
        let state = state(vec![original.clone()]);
        let baseline = Baseline::new(&serde_json::to_vec(&state).unwrap());
        let payload = br#"{thread_id:12345678-1234-1234-1234-123456789abc,cwd:/work/a path,yolo:false,codex_program:/bin/codex,managed_program:/bin/managed,codex_home:/home/test/.codex,launcher_pid:42,launcher_start:123,state_file:/tmp/session.json}"#;
        assert_eq!(
            serde_json::to_value(baseline.recover("fixture-host", payload).unwrap().unwrap())
                .unwrap(),
            serde_json::to_value(original).unwrap()
        );
        assert!(baseline.recover("other-host", payload).unwrap().is_none());
        assert!(
            baseline
                .recover("fixture-host", &payload[1..])
                .unwrap()
                .is_none()
        );
        assert!(
            baseline
                .recover("fixture-host", b"arbitrary malformed JSON")
                .unwrap()
                .is_none()
        );
        assert!(
            baseline
                .recover("fixture-host", b" {thread_id:123}")
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn native_projection_preserves_spaces_and_escaped_quotes_and_requires_one_argument() {
        assert_eq!(
            projection(r#"{"cwd":"/a path","q":"a\"b"}"#)
                .unwrap()
                .as_deref(),
            Some(r#"{cwd:/a path,q:a"b}"#)
        );
        assert!(projection("a b").unwrap().is_none());
        assert_eq!(
            projection(r#"{"a":12}"#).unwrap(),
            projection(r#"{"a":"12"}"#).unwrap()
        );
    }

    #[test]
    fn colliding_typed_references_are_rejected_and_identical_candidates_deduplicate() {
        let mut first = reference();
        first.codex_program = "/a,managed_program:/b".into();
        first.managed_program = "/c".into();
        let mut second = first.clone();
        second.codex_program = "/a".into();
        second.managed_program = "/b,managed_program:/c".into();
        first.validate().unwrap();
        second.validate().unwrap();
        let payload = projection(&serde_json::to_string(&first).unwrap())
            .unwrap()
            .unwrap();
        assert_eq!(
            Some(payload.clone()),
            projection(&serde_json::to_string(&second).unwrap()).unwrap()
        );
        assert!(
            select(
                &state(vec![first.clone(), second]),
                "fixture-host",
                payload.as_bytes()
            )
            .unwrap_err()
            .to_string()
            .contains("ambiguous")
        );
        assert!(
            select(
                &state(vec![first.clone(), first]),
                "fixture-host",
                payload.as_bytes()
            )
            .unwrap()
            .is_some()
        );
    }

    #[test]
    fn absent_receipt_is_optional_but_configured_corruption_fails_closed() {
        let baseline = Baseline::new(b"{}");
        let receipt = baseline.0.join("legacy-recovery-baseline.json");
        fs::remove_file(&receipt).unwrap();
        assert!(baseline.recover("fixture-host", b"bad").unwrap().is_none());
        for invalid in [
            "{}",
            r#"{"version":2,"snapshot_sha256":"abc"}"#,
            r#"{"version":1,"snapshot_sha256":"../../outside","extra":1}"#,
        ] {
            fs::write(&receipt, invalid).unwrap();
            assert!(baseline.recover("fixture-host", b"bad").is_err());
        }
        fs::write(&receipt, vec![b' '; RECEIPT_LIMIT as usize + 1]).unwrap();
        assert!(
            baseline
                .recover("fixture-host", b"bad")
                .unwrap_err()
                .to_string()
                .contains("size limit")
        );
    }

    #[test]
    fn pinned_snapshot_requires_matching_hash_strict_schema_and_bound() {
        let baseline = Baseline::new(b"{}");
        assert!(
            baseline
                .recover("fixture-host", b"bad")
                .unwrap_err()
                .to_string()
                .contains("invalid pinned")
        );
        let hash = format!("{:x}", Sha256::digest(b"{}"));
        let snapshot = baseline.0.join("baselines").join(format!("{hash}.json"));
        fs::write(&snapshot, b"changed").unwrap();
        assert!(
            baseline
                .recover("fixture-host", b"bad")
                .unwrap_err()
                .to_string()
                .contains("SHA256 mismatch")
        );
        fs::write(&snapshot, vec![b' '; SNAPSHOT_LIMIT as usize + 1]).unwrap();
        assert!(
            baseline
                .recover("fixture-host", b"bad")
                .unwrap_err()
                .to_string()
                .contains("size limit")
        );
        let mut invalid = serde_json::to_value(state(vec![reference()])).unwrap();
        invalid["unknown"] = true.into();
        let baseline = Baseline::new(&serde_json::to_vec(&invalid).unwrap());
        assert!(baseline.recover("fixture-host", b"bad").is_err());
    }
}