agent-ssh 0.4.1

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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
use super::{Inventory, Reference, Row, Scope, StartCli};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::{
    ffi::OsString,
    fs,
    io::{Read, Write},
    path::PathBuf,
    time::{Duration, SystemTime, UNIX_EPOCH},
};
use tmux_session::{
    ConfigOp, CreateSession, EnvEntry, Limits, LiteralCommand, OwnedSession, OwnershipMarker,
    PaneEnvironment, Runtime, SessionName, Tmux,
};

const MARKER: &str = "AGENT_SSH_SESSION_TOKEN";

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Record {
    version: u32,
    id: String,
    name: String,
    agent: String,
    preset: String,
    socket: String,
    session: String,
    token: String,
    created_at: u64,
}

fn store() -> Result<PathBuf> {
    Ok(agent_ssh::snapshot_store::default_directory()?
        .parent()
        .context("state directory unavailable")?
        .join("sessions"))
}

fn records() -> Result<Vec<Record>> {
    let path = store()?;
    if !path.exists() {
        return Ok(Vec::new());
    }
    let mut result = Vec::new();
    for entry in fs::read_dir(path)? {
        let path = entry?.path();
        if path.extension().is_none_or(|s| s != "json") {
            continue;
        }
        if result.len() >= 4096 {
            bail!("session registry exceeds bound");
        }
        let metadata = path.symlink_metadata()?;
        if !metadata.is_file() || metadata.len() > 65536 {
            bail!("invalid session registry file {}", path.display());
        }
        let mut text = String::new();
        fs::File::open(&path)?
            .take(65537)
            .read_to_string(&mut text)?;
        let record: Record = serde_json::from_str(&text)
            .with_context(|| format!("invalid session record {}", path.display()))?;
        if record.version != 1
            || uuid::Uuid::parse_str(&record.id).is_err()
            || uuid::Uuid::parse_str(&record.token).is_err()
            || !record.socket.starts_with('/')
            || !record.session.starts_with("agent-ssh-")
        {
            bail!("invalid session registry identity");
        }
        result.push(record);
    }
    Ok(result)
}

fn server(socket: Option<&str>) -> Result<(Tmux, Runtime)> {
    let mut builder = Tmux::builder().client_env_remove("TMUX").limits(Limits {
        timeout: Duration::from_secs(12),
        ..Limits::default()
    });
    if let Some(socket) = socket {
        builder = builder.socket_path(socket);
    }
    Ok((builder.build()?, Runtime::new()?))
}

fn marker(record: &Record) -> Result<OwnedSession> {
    Ok(OwnedSession::new(
        SessionName::new(&record.session)?,
        OwnershipMarker::new(MARKER, &record.token)?,
    ))
}

pub fn inventory(scope: &Scope) -> Result<Inventory> {
    if scope.socket.is_none() {
        let mut merged = match inventory_at(scope) {
            Ok(result) => result,
            Err(error) => Inventory {
                warnings: vec![format!("Default tmux server: {error:#}")],
                ..Inventory::default()
            },
        };
        let mut sockets = std::collections::BTreeSet::from([managed_socket()?]);
        match records() {
            Ok(records) => sockets.extend(records.into_iter().map(|r| PathBuf::from(r.socket))),
            Err(e) => merged.warnings.push(format!("Session registry: {e:#}")),
        }
        if sockets.len() > 64 {
            bail!("registered tmux socket count exceeds bound");
        }
        for socket in sockets {
            if socket.exists() && !merged.sessions.iter().any(|r|matches!(&r.reference,Reference::Tmux{socket:existing,..} if std::path::Path::new(existing)==socket)) {
            let mut scoped = scope.clone();
            scoped.socket = Some(
                socket
                    .to_str()
                    .context("managed socket is not UTF-8")?
                    .into(),
            );
            match inventory_at(&scoped) {
                Ok(extra) => merged.sessions.extend(extra.sessions),
                Err(error) => merged.warnings.push(format!("managed sessions: {error:#}")),
            }
        }
        }
        match crate::remote_codex::local_inventory() {
            Ok(rows) => {
                for row in rows {
                    let state = if row.observation.state == "already_running" {
                        "running"
                    } else {
                        "detached"
                    };
                    let capabilities = if row.observation.state == "attachable"
                        && row.observation.mode.as_deref() == Some("reattach")
                    {
                        vec!["attach".into()]
                    } else {
                        vec![]
                    };
                    merged.sessions.push(Row {
                        id: row.reference.thread_id.clone(),
                        name: format!("codex-{}", &row.reference.thread_id[..8]),
                        agent: Some("codex".into()),
                        host: "local".into(),
                        on: None,
                        backend: "marshal-codex".into(),
                        clients: Some(if state == "running" { 1 } else { 0 }),
                        state: state.into(),
                        recovery: if capabilities.is_empty() {
                            "in-use"
                        } else {
                            "attach"
                        }
                        .into(),
                        capabilities,
                        reference: Reference::RemoteCodex {
                            reference: Box::new(row.reference),
                        },
                    });
                }
            }
            Err(error) => merged
                .warnings
                .push(format!("Direct Codex sessions: {error:#}")),
        }
        return Ok(merged);
    }
    inventory_at(scope)
}

fn inventory_at(scope: &Scope) -> Result<Inventory> {
    let (server, runtime) = server(scope.socket.as_deref())?;
    let sessions = runtime.block_on(server.sessions())?;
    if sessions.is_empty() {
        return Ok(Inventory::default());
    }
    let socket = runtime
        .block_on(server.server_socket_path())?
        .to_str()
        .context("tmux socket is not UTF-8")?
        .to_owned();
    let records = records()?;
    let process_tree = process_tree();
    let mut result = Inventory::default();
    for session in sessions {
        let name = session
            .name
            .to_str()
            .context("tmux session name is not UTF-8")?
            .to_owned();
        let candidates = records
            .iter()
            .filter(|r| r.socket == socket && r.session == name)
            .collect::<Vec<_>>();
        let token = if candidates.is_empty() {
            None
        } else {
            match runtime.block_on(server.session_env(session.id, std::ffi::OsStr::new(MARKER)))? {
                EnvEntry::Value(value) => Some(value),
                _ => None,
            }
        };
        let owner = candidates.into_iter().find(|r| {
            token
                .as_ref()
                .is_some_and(|value| value == std::ffi::OsStr::new(&r.token))
        });
        let (id, label, agent, capabilities) = if let Some(record) = owner {
            (
                record.id.clone(),
                record.name.clone(),
                Some(record.agent.clone()),
                vec!["attach".into(), "detach".into(), "stop".into()],
            )
        } else {
            let agent = runtime
                .block_on(server.active_pane(session.id))?
                .and_then(|pane| pane.pid)
                .and_then(|pid| agent_below(pid, &process_tree));
            (
                format!("tmux:{}", session.id),
                name.clone(),
                agent,
                vec!["attach".into()],
            )
        };
        result.sessions.push(Row {
            id,
            name: label,
            agent,
            host: "local".into(),
            on: None,
            backend: "tmux".into(),
            clients: Some(session.attached_clients),
            state: if session.attached_clients > 0 {
                "attached"
            } else {
                "detached"
            }
            .into(),
            recovery: "attach".into(),
            capabilities,
            reference: Reference::Tmux {
                socket: socket.clone(),
                session: name,
            },
        });
    }
    Ok(result)
}

// Display metadata only: process names never grant lifecycle ownership.
#[cfg(not(target_os = "linux"))]
fn process_tree() -> std::collections::BTreeMap<u32, (u32, String)> {
    std::collections::BTreeMap::new()
}

#[cfg(target_os = "linux")]
fn process_tree() -> std::collections::BTreeMap<u32, (u32, String)> {
    let mut result = std::collections::BTreeMap::new();
    if let Ok(entries) = fs::read_dir("/proc") {
        let deadline = std::time::Instant::now() + Duration::from_secs(3);
        for entry in entries.take(32768).flatten() {
            if std::time::Instant::now() >= deadline {
                break;
            }
            let Ok(pid) = entry.file_name().to_string_lossy().parse::<u32>() else {
                continue;
            };
            let Ok(stat) = fs::read_to_string(entry.path().join("stat")) else {
                continue;
            };
            let Some((_, tail)) = stat.rsplit_once(") ") else {
                continue;
            };
            let Some(parent) = tail
                .split_whitespace()
                .nth(1)
                .and_then(|s| s.parse::<u32>().ok())
            else {
                continue;
            };
            let Ok(command) = fs::read_to_string(entry.path().join("comm")) else {
                continue;
            };
            result.insert(pid, (parent, command.trim().to_owned()));
        }
    }
    result
}

fn agent_below(
    root: u32,
    processes: &std::collections::BTreeMap<u32, (u32, String)>,
) -> Option<String> {
    let mut found = std::collections::BTreeSet::new();
    let mut visited = std::collections::BTreeSet::new();
    let mut pending = vec![root];
    while let Some(pid) = pending.pop() {
        if visited.len() >= 4096 || !visited.insert(pid) {
            break;
        }
        if let Some((_, name)) = processes.get(&pid)
            && ["codex", "claude", "gemini", "opencode"].contains(&name.as_str())
        {
            found.insert(name.clone());
        }
        pending.extend(
            processes.iter().filter_map(
                |(child, (parent, _))| if *parent == pid { Some(*child) } else { None },
            ),
        );
    }
    if found.len() == 1 {
        found.into_iter().next()
    } else if found.len() > 1 {
        Some("mixed".into())
    } else {
        None
    }
}

pub fn start(cli: StartCli) -> Result<()> {
    let settings = super::config::load()?;
    let preset = settings
        .presets
        .get(&cli.agent)
        .with_context(|| format!("unknown preset {:?}; run agent-ssh presets", cli.agent))?;
    let id = uuid::Uuid::new_v4().to_string();
    let name = cli
        .name
        .unwrap_or_else(|| format!("{}-{}", cli.agent, &id[..8]));
    super::config::name(&name)?;
    let cwd = cli
        .cwd
        .map(PathBuf::from)
        .unwrap_or(std::env::current_dir()?);
    if !cwd.is_absolute() || !cwd.is_dir() {
        bail!("working directory must be an existing absolute directory");
    }
    let physical = format!(
        "agent-ssh-{}",
        name.as_bytes()
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect::<String>()
    );
    let socket = cli
        .scope
        .socket
        .as_ref()
        .map(PathBuf::from)
        .unwrap_or(managed_socket()?);
    if !socket.is_absolute() {
        bail!("tmux socket path must be absolute");
    }
    if let Some(parent) = socket.parent() {
        fs::create_dir_all(parent)?;
    }
    let (server, runtime) = server(Some(socket.to_str().context("tmux socket is not UTF-8")?))?;
    if runtime
        .block_on(server.session_exact(&SessionName::new(&physical)?))?
        .is_some()
    {
        bail!("session {name:?} already exists; use agent-ssh attach {name}");
    }
    let record = Record {
        version: 1,
        id: id.clone(),
        name: name.clone(),
        agent: preset.agent.clone().unwrap_or_else(|| cli.agent.clone()),
        preset: cli.agent.clone(),
        socket: socket.to_str().context("tmux socket is not UTF-8")?.into(),
        session: physical.clone(),
        token: uuid::Uuid::new_v4().simple().to_string(),
        created_at: SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(),
    };
    let directory = store()?;
    fs::create_dir_all(&directory)?;
    let path = directory.join(format!("{id}.json"));
    let pending = directory.join(format!("{id}.pending"));
    use std::os::unix::fs::OpenOptionsExt;
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(&pending)?;
    file.write_all(&serde_json::to_vec(&record)?)?;
    file.sync_all()?;
    drop(file);
    fs::hard_link(&pending, &path)?;
    fs::remove_file(&pending)?;
    let args = preset
        .command
        .iter()
        .skip(1)
        .chain(&cli.args)
        .map(OsString::from)
        .collect::<Vec<_>>();
    let mut spec = CreateSession::new(
        SessionName::new(&physical)?,
        LiteralCommand::new(&preset.command[0], args, cwd)?,
    );
    spec.window_name = Some(name.clone().into());
    spec.marker = Some(OwnershipMarker::new(MARKER, &record.token)?);
    spec.pane_env = PaneEnvironment::default()
        .remove("WT_SESSION")
        .remove("WT_PROFILE_ID")
        .remove("WEZTERM_PANE")
        .remove("SSH_CONNECTION")
        .remove("SSH_CLIENT")
        .remove("SSH_TTY");
    for key in [
        "MARSHAL_AGENT_ID",
        "MARSHAL_LAUNCH_ID",
        "MARSHAL_LAUNCH_KEY",
        "MARSHAL_LAUNCH_CWD",
        "MARSHAL_HOST",
    ] {
        spec.pane_env = spec.pane_env.remove(key);
    }
    for (key, value) in &preset.environment {
        spec.pane_env = spec.pane_env.set(key, value);
    }
    // The explicit launch name is display metadata for agent wrappers, not an
    // ownership credential. Always replace any inherited or preset value.
    spec.pane_env = spec.pane_env.set("AGENT_SESSION_NAME", &name);
    let session = runtime
        .block_on(server.create(spec))
        .context("session launch failed; inspect agent-ssh list before retrying")?;
    runtime.block_on(server.configure(
        session.id,
        &[
            ConfigOp::SessionOption {
                key: "status".into(),
                value: "off".into(),
            },
            ConfigOp::SessionOption {
                key: "mouse".into(),
                value: "on".into(),
            },
        ],
    ))?;
    let actual_socket = runtime.block_on(server.server_socket_path())?;
    if actual_socket != socket {
        bail!(
            "tmux selected a different socket than the launch record; inspect existing sessions before retrying"
        );
    }
    if cli.json {
        let mut inv = inventory(&cli.scope)?;
        inv.sessions.retain(|r| r.id == id);
        println!("{}", serde_json::to_string_pretty(&inv)?);
    } else {
        println!(
            "Started {name} ({})\n  Attach: agent-ssh attach {name}",
            &id[..8]
        );
    }
    Ok(())
}

fn managed_socket() -> Result<PathBuf> {
    Ok(store()?
        .parent()
        .context("session state directory unavailable")?
        .join("tmux.sock"))
}

pub fn action(scope: &Scope, row: &Row, verb: &str) -> Result<()> {
    let Reference::Tmux { socket, session } = &row.reference else {
        bail!("unsupported local session backend");
    };
    let (server, runtime) = server(Some(socket))?;
    let found = runtime
        .block_on(server.session_exact(&SessionName::new(session)?))?
        .context("session no longer exists")?;
    if verb == "attach" {
        if row.capabilities.iter().any(|c| c == "stop") {
            let record = records()?
                .into_iter()
                .find(|r| r.id == row.id)
                .context("session ownership record is missing")?;
            if !matches!(
                runtime.block_on(server.find_owned(&marker(&record)?))?,
                tmux_session::OwnedLookup::Found(_)
            ) {
                bail!("session ownership changed");
            }
        }
        let mut command = server.attach_command(&found);
        drop(runtime);
        use std::os::unix::process::CommandExt;
        return Err(command.exec()).context("cannot attach to session");
    }
    let record = records()?
        .into_iter()
        .find(|r| r.id == row.id && r.socket == *socket && r.session == *session)
        .context("this session is managed externally; only attach is supported here")?;
    let wanted = marker(&record)?;
    match verb {
        "stop" => match runtime.block_on(server.stop_owned(&wanted))? {
            tmux_session::StopOutcome::Mismatch => bail!("session ownership changed"),
            tmux_session::StopOutcome::Stopped | tmux_session::StopOutcome::Gone => {}
        },
        "detach" => match runtime.block_on(server.detach_owned(&wanted))? {
            tmux_session::DetachOutcome::Mismatch => bail!("session ownership changed"),
            tmux_session::DetachOutcome::Detached | tmux_session::DetachOutcome::Gone => {}
        },
        _ => bail!("unknown session action"),
    }
    let _ = scope;
    println!(
        "{} {}",
        if verb == "stop" {
            "Stopped"
        } else {
            "Detached"
        },
        row.name
    );
    Ok(())
}