# agent-ssh
Arrange agent terminal layouts and reconnect through provider attachment plans. `agent-ssh` is the command. The repository is `ignition-is-go/agent-ssh`.
Run `agent-ssh` without arguments for a quick start, or `agent-ssh --help` for all commands and options. The quick start does not require an SSH configuration or open any sessions.
See [the experimental attachment contract](docs/attachment-contract.md) for version 2 terminal layouts, provider resolution, and machine-readable restore plans.
## Named agent sessions
```powershell
agent-ssh presets --on <host>
agent-ssh start codex --name review --on <host> --cwd /work/project
agent-ssh list
agent-ssh attach review --on <host>
agent-ssh detach review --on <host>
agent-ssh stop review --on <host>
```
`start` creates a detached persistent tmux session and prints its runtime ID and attachment command. It rejects a duplicate friendly name instead of restarting or attaching to it. Append literal agent arguments after `--`. `attach` only reconnects to an existing runtime; it never starts an agent or cold-resumes a conversation. `detach` disconnects clients while retaining the runtime. `stop` ends the session after an ownership check. These lifecycle operations use the published `tmux-session` backend.
`list` combines local sessions, remembered hosts from successful starts, configured hosts and saved recovery references. It discovers tmux sessions and direct Marshal Codex launchers on execution hosts; on Windows it also discovers live local Codex processes without requiring a prior save. The table includes friendly name, runtime ID, agent, host, client count, state and recovery mode. Select an exact name, full runtime ID or unique ID prefix of at least six characters. Ambiguous selections fail; use `--on HOST` to narrow them. Use `--local` to suppress remote discovery, `--socket PATH` for one exact socket, and `--json` for structured inventory including supported `capabilities`.
Externally managed tmux sessions remain visible and attachable. Their ownership is not adopted: stop/detach apply to sessions created by agent-ssh. Live native Codex interfaces are listed as in use; agent-ssh does not duplicate them. An exited direct runtime can be resumed through `load`, while `attach` explicitly refuses cold creation. Inventory failures are reported as warnings rather than claiming absent agents.
New owned sessions use a private `tmux.sock` next to the snapshot state directory, unless an exact `--socket` is provided. Save discovers these sockets too, so their attachment references survive layout save/load. Existing default-server sessions remain visible and unchanged. Session status bars are hidden and mouse support is enabled per session.
### Presets and host defaults
Built-in presets are `codex`, `claude`, `gemini` and `opencode`. On Windows configure `%APPDATA%/agent-ssh/config.json`; on Unix use `$XDG_CONFIG_HOME/agent-ssh/config.json` or `~/.config/agent-ssh/config.json`. Deployment-owned JSON files under `presets.d/` are loaded first; the user config overrides them. `AGENT_SSH_CONFIG_DIR` can select an absolute configuration directory.
```json
{
"version": 1,
"default_host": "my-agent-host",
"hosts": ["my-agent-host"],
"presets": {
"review": {
"agent": "codex",
"description": "Project review agent",
"command": ["codex"],
"environment": {}
}
}
}
```
Omit `default_host` to execute locally on Unix or require `--on` for launches from Windows. Commands are literal argument arrays, not shell scripts. The execution host resolves its own presets and cwd. Managed guests configure their Codex preset through Pulse deployment so Marshal launch policy is retained. A successful explicit remote start remembers that host for later inventory; it does not change your default execution host. New remote lifecycle commands require an updated target-side agent-ssh. Older installations still provide read-only tmux inventory and exact attachment, with an upgrade warning.
## Save the current Windows Terminal layout
```powershell
agent-ssh save
agent-ssh load --plan
agent-ssh load
agent-ssh save "$HOME\agents-before-restart.json"
agent-ssh load "$HOME\agents-before-restart.json" --plan
agent-ssh load "$HOME\agents-before-restart.json"
```
Interactive save/load show a transient progress spinner on stderr. Redirected output and `load --plan` omit the spinner; JSON plans remain clean.
Without PATH, `save` writes to `%LOCALAPPDATA%/agent-ssh/snapshots` on Windows. `load` selects the newest managed snapshot there. On Unix the directory is `$XDG_STATE_HOME/agent-ssh/snapshots`, or `$HOME/.local/state/agent-ssh/snapshots` when XDG_STATE_HOME is empty or relative. Managed names use a sortable UTC epoch timestamp taken after capture: `snapshot-<20-digit-seconds>-<9-digit-nanoseconds>.json`. Newest means the greatest filename timestamp, not file modification or completion time. Unrelated files, directories and symbolic links are ignored. A corrupt newest snapshot blocks loading; it never silently selects an older one. Valid snapshots with recovery gaps retain every pane and use labelled shell placeholders for those gaps. An explicit save PATH is a named export and does not become the default load target. There is no mutable latest pointer. Provide PATH to load a different recovery file.
`save` reads Windows Terminal's latest native layout checkpoint and binds its pane session GUIDs to live process metadata, local Codex conversation IDs and remote tmux attachments. It never overwrites an existing file. Restore opens a fresh window with those tab boundaries and normalized split proportions. It does not rearrange existing interfaces.
Save is passive: it does not select tabs, change console titles, send input or require idle keyboard/mouse input. Enable `"firstWindowPreference": "persistedWindowLayout"` in Windows Terminal settings and allow its first five-minute checkpoint. This setting also enables Terminal's own startup layout restoration; avoid running two independent startup restorers. Save includes the checkpoint's age in its completion summary and rejects checkpoints older than seven minutes, closed/unbound panes, or live panes absent from the checkpoint. Layout-only changes can remain stale until the next checkpoint. Native state parsing and read-only x64 process-environment binding are compatibility adapters for the tested Windows/Terminal versions, not a stable live topology API. Unsupported architectures/distributions and ambiguous bindings fail without falling back to invasive capture. A Terminal process with multiple windows is currently unsupported.
Version 3 snapshots retain every observed pane. `restorable: false` and an `unavailable` target identify missing recovery support. A successfully written save exits successfully and reports any gaps. Load restores available targets while preserving unavailable or already-running positions as labelled PowerShell panes, with reasons printed before launch. `--plan` reports `partial`, per-pane states and the exact terminal arguments without launching agents. Corrupt snapshots still fail before opening terminals. A successful save does not promise every runtime is available.
Local Codex recovery requires an explicit resume UUID and working directory in the live command arguments. Restore refuses to resume an already-running local conversation or when another local Codex process has an unknown binding. Remote recovery attaches an exact existing tmux session name on its captured socket. It follows that logical name if someone deliberately recreates it; it does not reserve the original process incarnation. Direct Marshal `codex-run` sessions are also recognized: an exact SSH socket/sshd ancestry join identifies the launcher, its recorded conversation UUID is verified against on-disk session metadata, and cwd plus launch policy are saved. Recovery refuses to duplicate a live interface. A surviving bridge without its interface can be reattached; after the original launcher exits, its exact saved conversation resumes through the deployed managed-launch helper and therefore receives the normal tmux wrapper. This resumes history, not lost process memory or a guaranteed continuation of an interrupted turn. Other unrecognized direct agents remain explicit recovery gaps. Save does not migrate or interrupt a running process.
Bare, single-process PowerShell panes become explicit fresh-shell targets. Their memory and current directory cannot be captured. They reopen in your home directory, or the directory supplied with `save --shell-directory PATH`. Other running shell commands are unsupported.
Use `save --window HWND` to select an observed Terminal window, and `--remote-program PATH` when target-side `agent-ssh` is not on PATH. Remote hosts need the version that provides `tmux clients --json`. Snapshot files contain trusted executable paths and recovery arguments; restore only files you trust. A PC restart preserves remote tmux runtimes while they remain running on the remote host. Local Codex resumes stored conversation history rather than process memory.
## Attach to an existing tmux session
Unix-side tmux inspection and attachment use the independent [`tmux-session`](https://github.com/ignition-is-go/tmux-session) package:
```text
agent-ssh tmux list --json
agent-ssh tmux attach pulse-agent
agent-ssh tmux --socket /run/user/1000/tmux.sock list --json
```
On Windows, select an SSH host with Unix `agent-ssh` 0.3.5 installed:
```text
agent-ssh tmux list --on pulse-admin --json
agent-ssh tmux attach pulse-agent --on pulse-admin
agent-ssh tmux list --on pulse-admin --remote-program /root/.cargo/bin/agent-ssh --json
```
`--socket` selects a path on the execution host. Session names are literal names, not tmux selectors or prefix searches. Attachment fails if the exact name is absent and never creates a session or agent. The SSH path executes the installed target-side command without a raw-tmux fallback.
The upstream library supplies session queries and exact-name lookup. Its published API captures command output and has no inherited-terminal attachment operation. After a successful lookup, this application hands the terminal to native `tmux attach-session` on the captured socket. Cancelling that attachment does not terminate the tmux session. Availability can change between lookup and handoff; this is a logical named attachment, not a lease on a process incarnation.
Session subcommands do not accept Windows Terminal layout flags. In host lists, use `--` before an SSH alias that matches a command name, such as `list`, `start`, `tmux`, `save` or `load`.
## Legacy layouts and recovery
```powershell
# Save selected SSH hosts without opening terminals.
agent-ssh --group production --save-workspace production.json --panes-per-tab 4
# Restore saved attach/resume commands in four-pane grids.
agent-ssh load production.json --window agents
agent-ssh load production.json --panes-per-tab 4 --dry-run
# Regroup 16 EXISTING single-pane tabs, beginning at tab zero.
agent-ssh --regroup 16 --window agents
```
`--regroup` moves existing panes without starting or stopping their processes. Run it only against the specified number of single-pane tabs; it is not idempotent. `--first-tab` selects a zero-based starting tab. Terminal chooses split direction when moving existing panes; restoring a workspace explicitly builds balanced grids. Existing tabs outside the selected range remain in place.
`load` opens new terminal interfaces. Remote attach commands should reconnect to an existing `tmux` session; local Codex commands should use an explicit thread ID. Repeating restore can create duplicate interfaces, especially for local agents. A saved workspace retains commands and layout, not process memory or in-flight command state. Restoring does not stop an already-open interface or take over a conversation lock.
Workspace JSON uses version 1, an ordered pane list, and a per-tab pane count:
```json
{
"version": 1,
"panes_per_tab": 4,
"panes": [
{
"title": "remote agent",
"command": ["ssh.exe", "-t", "pulse-admin", "/root/.local/share/agent-sessions/open-agent.sh"]
},
{
"title": "local agent",
"cwd": "C:\\Work Projects",
"command": ["codex.cmd", "resume", "EXPLICIT-THREAD-ID"]
}
]
}
```
Each pane may specify a Windows Terminal `profile`. Commands are argument arrays, not shell strings. Use only trusted workspace files: restoring executes their commands. Semicolons and line breaks in pane fields are rejected because Windows Terminal interprets semicolons as action separators. Saving to an existing filename is refused. `--save-workspace` saves selected SSH destinations, not automatic discovery of active agent IDs; provide explicit resume/attach commands for agent recovery.
See [Marshal integration](docs/marshal-integration.md) for the boundary with the work-in-progress `LaunchBackend` API.
`agent-ssh` opens SSH aliases from `~/.ssh/config` as balanced pane grids or tabs in Windows Terminal. Groups and colors are declared with comments:
```ssh-config
# @group production #E57000
Host app-one
HostName app-one.example.com
Host app-two
HostName app-two.example.com
User deploy
```
## Install
```powershell
cargo install agent-ssh --version 0.4.0 --locked
agent-ssh --sync
```
To install from a source checkout, run `cargo install --path . --force`.
Restart Windows Terminal after the initial sync.
## Usage
```text
agent-ssh --group production
agent-ssh --group production --new-window
agent-ssh --group development --tabs
agent-ssh --group production --command uptime
agent-ssh --list
agent-ssh --sync
agent-ssh --group production --dry-run
```
Inside a grid, Windows Terminal's `Alt+Shift+B` toggles broadcast input, `Alt+Shift+Z` zooms the focused pane, and `Alt+Arrow` moves focus.
## Releases
Push a semantic-version tag matching `Cargo.toml` to create a GitHub Release:
```powershell
git tag v0.3.0
git push origin v0.3.0
```
The release workflow verifies the version, runs the full quality suite, builds the Windows executable, and publishes a ZIP plus a SHA-256 checksum.
When releasing a new shared protocol version, publish it before the terminal crate. Skip the first command if that protocol version is already published:
```powershell
cargo publish -p agent-attachment-protocol
cargo publish -p agent-ssh
```
## Inspect provider-backed layouts
Version 2 layouts retain references and resolve their attachment plans on every restore. Use the provider on the same host as the terminal consumer. A remote producer's local executable path is not a local Windows executable.
```powershell
agent-ssh load my-layout.json --window agents --plan
agent-ssh load my-layout.json --window agents
agent-ssh load my-layout.json --window agents --allow-partial
```
Default restore blocks if a provider cannot attach every referenced agent. Partial restore is explicit. Neither mode starts replacement agents or replays prompts. See the [ownership decision](docs/architecture.md) and [acceptance record](docs/acceptance.md).
To convert a version 1 recovery file, use the migration tool. It compares both files through the actual CLI before writing and refuses to overwrite an existing destination.
```powershell
python scripts/migrate_layout.py old-layout.json terminal-layout.json --binary agent-ssh
```
Pulse Agents 1.82.2 provides the managed `attachment-plan` and `attach` commands. Install that provider before using its provider-backed layouts. Existing configured SSH and local recovery commands remain supported.