agent-ssh 0.4.0

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Supported Windows console metadata and UI Automation capture. No actor lifecycle authority.
use anyhow::{Context, Result, bail};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeCapture {
    pub version: u32,
    #[serde(default)]
    pub checkpoint_age_seconds: Option<u64>,
    pub hwnd: String,
    pub selected_tab: Option<usize>,
    pub tabs: Vec<NativeTab>,
    pub processes: Vec<NativeProcess>,
    pub connections: Vec<NativeConnection>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeTab {
    pub title: String,
    pub panes: Vec<NativePane>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativePane {
    pub console_pid: u32,
    pub console_start_ticks: u64,
    pub title: String,
    pub rect: NativeRect,
    pub members: Vec<u32>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeRect {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeProcess {
    pub pid: u32,
    pub parent_pid: u32,
    pub start_ticks: u64,
    pub executable: String,
    pub argv: Vec<String>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NativeConnection {
    pub pid: u32,
    pub local_address: String,
    pub local_port: u16,
    pub remote_address: String,
    pub remote_port: u16,
    pub state: u32,
    pub created_filetime: u64,
}

/// Read a native periodic checkpoint and exact live session identities.
/// Never selects tabs, writes titles, or requires idle physical input.
pub fn collect(window: Option<&str>) -> Result<NativeCapture> {
    let capture = crate::passive::collect(&run(window, false)?)?;
    capture.validate()?;
    Ok(capture)
}

/// Read only live Codex process argv and creation identities; no UI or title changes.
pub fn processes() -> Result<Vec<NativeProcess>> {
    let records: Vec<NativeProcess> = serde_json::from_slice(&run(None, true)?)
        .context("invalid native process metadata response")?;
    validate_processes(&records)?;
    Ok(records)
}

fn validate_processes(records: &[NativeProcess]) -> Result<()> {
    let mut seen = std::collections::HashSet::new();
    if records.len() > 8192 {
        bail!("native process count exceeds bound");
    }
    for p in records {
        if p.pid == 0
            || p.parent_pid == p.pid
            || p.start_ticks == 0
            || !seen.insert(p.pid)
            || p.executable.is_empty()
            || p.argv.is_empty()
            || p.argv.len() > 4096
            || p.argv.iter().any(|a| a.len() > 131_072 || a.contains('\0'))
        {
            bail!("invalid or ambiguous native process identity");
        }
    }
    Ok(())
}
impl NativeCapture {
    fn validate(&self) -> Result<()> {
        validate_processes(&self.processes)?;
        if self.version != 1
            || self.hwnd.parse::<u64>().ok().filter(|h| *h != 0).is_none()
            || self.tabs.is_empty()
            || self.tabs.len() > 128
            || self.selected_tab.is_none_or(|i| i >= self.tabs.len())
        {
            bail!("invalid native terminal scope");
        }
        let mut seen = std::collections::HashSet::new();
        for tab in &self.tabs {
            if tab.panes.is_empty() || tab.panes.len() > 64 {
                bail!("invalid native pane count");
            }
            for pane in &tab.panes {
                let r = &pane.rect;
                if ![r.x, r.y, r.width, r.height].iter().all(|n| n.is_finite())
                    || r.width <= 0.0
                    || r.height <= 0.0
                    || !seen.insert(pane.console_pid)
                    || !pane.members.contains(&pane.console_pid)
                    || pane.members.len() > 4096
                    || !self.processes.iter().any(|p| {
                        p.pid == pane.console_pid && p.start_ticks == pane.console_start_ticks
                    })
                {
                    bail!("invalid or ambiguous native pane binding");
                }
            }
        }
        if seen.len() != self.processes.len() {
            bail!("native process/pane membership mismatch");
        }
        if self.connections.len() > 16384
            || self.connections.iter().any(|c| {
                !seen.contains(&c.pid)
                    || !self.processes.iter().any(|p| {
                        p.pid == c.pid
                            && p.start_ticks
                                .checked_sub(504_911_232_000_000_000)
                                .is_some_and(|start| c.created_filetime >= start)
                            && p.executable
                                .rsplit(['\\', '/'])
                                .next()
                                .is_some_and(|name| name.eq_ignore_ascii_case("ssh.exe"))
                    })
                    || c.local_address.parse::<std::net::IpAddr>().is_err()
                    || c.remote_address.parse::<std::net::IpAddr>().is_err()
                    || c.local_port == 0
                    || c.remote_port == 0
                    || c.created_filetime == 0
            })
        {
            bail!("invalid native socket metadata");
        }
        Ok(())
    }
}

#[cfg(not(windows))]
fn run(_window: Option<&str>, _processes_only: bool) -> Result<Vec<u8>> {
    bail!("live terminal capture requires Windows");
}

#[cfg(windows)]
fn wait_for_watchdog(receipt: &serde_json::Value) -> Result<()> {
    use std::ffi::c_void;
    type Handle = *mut c_void;
    #[repr(C)]
    #[derive(Default)]
    struct FileTime {
        low: u32,
        high: u32,
    }
    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn OpenProcess(access: u32, inherit: i32, pid: u32) -> Handle;
        fn GetProcessTimes(
            handle: Handle,
            creation: *mut FileTime,
            exit: *mut FileTime,
            kernel: *mut FileTime,
            user: *mut FileTime,
        ) -> i32;
        fn WaitForSingleObject(handle: Handle, milliseconds: u32) -> u32;
        fn CloseHandle(handle: Handle) -> i32;
        fn GetLastError() -> u32;
    }
    let pid = receipt
        .get("pid")
        .and_then(|v| v.as_u64())
        .and_then(|n| u32::try_from(n).ok())
        .filter(|n| *n != 0)
        .context("invalid watchdog process receipt")?;
    let expected = receipt
        .get("start_ticks")
        .and_then(|v| v.as_u64())
        .context("watchdog creation identity missing")?;
    // Wait on an exact process handle, never merely a recycled PID.
    unsafe {
        let handle = OpenProcess(0x0010_0000 | 0x1000, 0, pid);
        if handle.is_null() {
            if GetLastError() == 87 {
                return Ok(());
            }
            bail!("cannot observe selection watchdog exit");
        }
        struct Close(Handle);
        impl Drop for Close {
            fn drop(&mut self) {
                unsafe {
                    CloseHandle(self.0);
                }
            }
        }
        let _close = Close(handle);
        let (mut creation, mut exit, mut kernel, mut user) = (
            FileTime::default(),
            FileTime::default(),
            FileTime::default(),
            FileTime::default(),
        );
        if GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) == 0 {
            bail!("watchdog creation identity unavailable");
        }
        let ticks = ((u64::from(creation.high) << 32) | u64::from(creation.low))
            .checked_add(504_911_232_000_000_000);
        if ticks != Some(expected) {
            return Ok(());
        } // Original process exited; its PID was reused.
        if WaitForSingleObject(handle, 5000) != 0 {
            bail!("selection watchdog did not exit after receipt");
        }
    }
    Ok(())
}

#[cfg(windows)]
fn run(window: Option<&str>, processes_only: bool) -> Result<Vec<u8>> {
    use std::os::windows::process::CommandExt;
    use std::{
        fs,
        io::Read,
        process::{Command, Stdio},
        sync::mpsc,
        thread,
        time::{Duration, Instant, SystemTime, UNIX_EPOCH},
    };
    const OUTPUT_LIMIT: usize = 8 * 1024 * 1024;
    const ERROR_LIMIT: usize = 8192;
    if window.is_some_and(|w| w.len() > 32768 || w.contains(['\0', '\r', '\n'])) {
        bail!("invalid Terminal window selector");
    }
    let root = std::env::temp_dir().join(format!(
        "agent-ssh-capture-{}-{}",
        std::process::id(),
        SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos()
    ));
    fs::create_dir(&root).context("cannot create private native capture directory")?;
    struct Cleanup {
        root: std::path::PathBuf,
        remove: bool,
    }
    impl Drop for Cleanup {
        fn drop(&mut self) {
            if !self.remove {
                return;
            }
            if let (Ok(root), Ok(temporary)) = (
                self.root.canonicalize(),
                std::env::temp_dir().canonicalize(),
            ) && root.parent() == Some(temporary.as_path())
                && root
                    .file_name()
                    .is_some_and(|n| n.to_string_lossy().starts_with("agent-ssh-capture-"))
            {
                let _ = std::fs::remove_dir_all(root);
            }
        }
    }
    let mut cleanup = Cleanup {
        root: root.clone(),
        remove: true,
    };
    fs::write(
        root.join("capture-windows.ps1"),
        if processes_only {
            include_str!("../scripts/capture-windows.ps1")
        } else {
            include_str!("../scripts/passive-windows.ps1")
        },
    )?;
    fs::write(
        root.join("passive-environment.cs"),
        include_str!("../scripts/passive-environment.cs"),
    )?;
    fs::write(
        root.join("console-probe.cs"),
        include_str!("../scripts/console-probe.cs"),
    )?;
    fs::write(
        root.join("selection-watchdog.cs"),
        include_str!("../scripts/selection-watchdog.cs"),
    )?;
    let windows = std::env::var_os("SystemRoot").context("SystemRoot unavailable")?;
    let powershell =
        std::path::PathBuf::from(windows).join("System32/WindowsPowerShell/v1.0/powershell.exe");
    let mut command = Command::new(powershell);
    command
        .args([
            "-NoLogo",
            "-NoProfile",
            "-NonInteractive",
            "-ExecutionPolicy",
            "Bypass",
            "-File",
        ])
        .arg(root.join("capture-windows.ps1"))
        .arg("-ControlDirectory")
        .arg(&root)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .creation_flags(0x0800_0000);
    if processes_only {
        command.arg("-ProcessesOnly");
    }
    if let Some(selector) = window {
        command.arg("-WindowSelector").arg(selector);
    }
    let mut child = command
        .spawn()
        .context("could not start native Windows metadata collector")?;
    let stdout = child
        .stdout
        .take()
        .context("collector stdout unavailable")?;
    let stderr = child
        .stderr
        .take()
        .context("collector stderr unavailable")?;
    let (send, receive) = mpsc::channel();
    let sender = send.clone();
    thread::spawn(move || {
        let mut b = Vec::new();
        let r = stdout
            .take((OUTPUT_LIMIT + 1) as u64)
            .read_to_end(&mut b)
            .map(|_| b);
        let _ = sender.send((true, r));
    });
    thread::spawn(move || {
        let mut b = Vec::new();
        let r = stderr
            .take((ERROR_LIMIT + 1) as u64)
            .read_to_end(&mut b)
            .map(|_| b);
        let _ = send.send((false, r));
    });
    let deadline = Instant::now() + Duration::from_secs(if processes_only { 20 } else { 110 });
    let mut timed_out = false;
    let status = loop {
        if let Some(status) = child.try_wait()? {
            break status;
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            timed_out = true;
            break child
                .try_wait()?
                .context("native collector did not terminate")?;
        }
        thread::sleep(Duration::from_millis(10));
    };
    if root.join("selection-watchdog-started").exists() {
        let cleanup_deadline = Instant::now() + Duration::from_secs(8);
        let receipt_path = root.join("selection-watchdog-receipt.json");
        let receipt = loop {
            if let Ok(bytes) = fs::read(&receipt_path)
                && bytes.len() <= 8192
                && let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes)
            {
                break Some(value);
            }
            if Instant::now() >= cleanup_deadline {
                break None;
            }
            thread::sleep(Duration::from_millis(20));
        };
        if receipt
            .as_ref()
            .and_then(|r| r.get("status"))
            .and_then(|s| s.as_str())
            .is_none_or(|s| {
                !matches!(
                    s,
                    "normal_stop_acknowledged"
                        | "restored"
                        | "no_owned_selection"
                        | "skipped_window_identity_changed"
                        | "skipped_window_missing"
                        | "skipped_physical_input_changed"
                        | "skipped_hwnd_reused"
                        | "skipped_selection_changed"
                )
            })
        {
            cleanup.remove = false;
            bail!(
                "selection cleanup failed or was not acknowledged; retained diagnostics at {}",
                root.display()
            );
        }
        if let Err(error) = wait_for_watchdog(receipt.as_ref().expect("receipt validated above")) {
            cleanup.remove = false;
            bail!("{}; retained diagnostics at {}", error, root.display());
        }
    }
    if !status.success() {
        const TITLE_HELPER_LEASE_GRACE: Duration = Duration::from_secs(3);
        thread::sleep(TITLE_HELPER_LEASE_GRACE);
    }
    if timed_out {
        bail!("native capture timed out; independent cleanup acknowledged");
    }
    let mut output = None;
    let mut errors = None;
    for _ in 0..2 {
        let (is_stdout, bytes) = receive
            .recv_timeout(deadline.saturating_duration_since(Instant::now()))
            .context("native capture output did not close before deadline")?;
        let bytes = bytes?;
        if is_stdout {
            output = Some(bytes);
        } else {
            errors = Some(bytes);
        }
    }
    let output = output.context("native capture stdout missing")?;
    let errors = errors.context("native capture stderr missing")?;
    if root.join("binding-diagnostic.json").is_file() {
        cleanup.remove = false;
    }
    if output.len() > OUTPUT_LIMIT || errors.len() > ERROR_LIMIT {
        bail!("native capture output exceeds bound");
    }
    if !status.success() {
        let reason: String = String::from_utf8_lossy(&errors)
            .chars()
            .filter(|c| !c.is_control() || *c == '\n')
            .take(4096)
            .collect();
        bail!("native capture failed: {}", reason.trim());
    }
    if !errors.is_empty() {
        bail!("native capture reported an error despite successful exit");
    }
    Ok(output)
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn accepts_only_ssh_owned_endpoint_metadata() {
        let mut capture: NativeCapture = serde_json::from_value(serde_json::json!({
            "version":1,"hwnd":"10","selected_tab":0,
            "tabs":[{"title":"tab","panes":[{"console_pid":12,"console_start_ticks":504911232000000100u64,
                "title":"pane","rect":{"x":0,"y":0,"width":100,"height":100},"members":[12]}]}],
            "processes":[{"pid":12,"parent_pid":1,"start_ticks":504911232000000100u64,"executable":"codex.exe","argv":["codex.exe"]}],
            "connections":[{"pid":12,"local_address":"127.0.0.1","local_port":1000,
                "remote_address":"127.0.0.2","remote_port":22,"state":5,"created_filetime":101}]
        })).unwrap();
        assert!(capture.validate().is_err());
        capture.processes[0].executable = r"C:\Windows\System32\OpenSSH\SSH.EXE".into();
        capture.processes[0].argv = vec!["ssh.exe".into()];
        assert!(capture.validate().is_ok());
        capture.connections[0].state = 1;
        assert!(capture.validate().is_ok());
        capture.connections[0].created_filetime = 99;
        assert!(capture.validate().is_err());
        capture.connections[0].created_filetime = 101;
        capture.connections.clear();
        capture.processes[0].executable =
            r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe".into();
        capture.processes[0].argv = vec!["powershell.exe".into()];
        assert!(capture.validate().is_ok());
    }

    #[test]
    fn rejects_duplicate_pid_identity_and_unmapped_native_leaf() {
        let record = r#"{"pid":12,"parent_pid":1,"start_ticks":100,"executable":"codex.exe","argv":["codex.exe"]}"#;
        let duplicate: Vec<NativeProcess> =
            serde_json::from_str(&format!("[{record},{record}]")).unwrap();
        assert!(validate_processes(&duplicate).is_err());
        let capture: NativeCapture = serde_json::from_str(&format!(r#"{{"version":1,"hwnd":"10","selected_tab":0,"tabs":[{{"title":"tab","panes":[{{"console_pid":13,"console_start_ticks":100,"title":"pane","rect":{{"x":0,"y":0,"width":100,"height":100}},"members":[13]}}]}}],"processes":[{record}],"connections":[]}}"#)).unwrap();
        assert!(capture.validate().is_err());
    }
}