agent-ssh 0.4.0

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
"""Real Unix lifecycle tests on a private socket with fake workers, never models."""
import json
import os
from pathlib import Path
import pty
import subprocess
import sys
import tempfile
import time


def main():
    binary = str(Path(sys.argv[1]).resolve())
    with tempfile.TemporaryDirectory(prefix='agent-ssh-lifecycle-') as directory:
        root = Path(directory)
        socket = str(root / 'tmux.sock')
        config = root / 'config'
        config.mkdir()
        work = root / 'work space'
        work.mkdir()
        receipt = root / 'worker.json'
        worker = root / 'fake worker.py'
        worker.write_text('import json,os,sys,time\nfrom pathlib import Path\nPath(sys.argv[1]).write_text(json.dumps(dict(argv=sys.argv[2:],cwd=os.getcwd(),marker=os.environ.get("FIXTURE_PRESET"),ssh=os.environ.get("SSH_CONNECTION"),wt=os.environ.get("WT_SESSION"))))\ntime.sleep(180)\n')
        (config / 'config.json').write_text(json.dumps(dict(version=1, presets=dict(smoke=dict(command=[sys.executable, str(worker), str(receipt)], environment=dict(FIXTURE_PRESET='configured'), agent='fixture', description='No model')))))
        environment = dict(os.environ, AGENT_SSH_CONFIG_DIR=str(config), XDG_STATE_HOME=str(root / 'state'), XDG_CONFIG_HOME=str(root / 'xdg'), WT_SESSION='parent-session', SSH_CONNECTION='inherited-unrelated-connection')
        environment.pop('TMUX', None)
        base = [binary]
        scope = ['--local', '--socket', socket]
        attached = None
        master = slave = None
        def run(*args, ok=True):
            result = subprocess.run([*base, *args], env=environment, capture_output=True, text=True, timeout=30)
            assert (result.returncode == 0) == ok, (args, result.stdout, result.stderr)
            return result
        def inventory():
            result = json.loads(run('list', *scope, '--json').stdout)
            assert result['version'] == 1 and not result['warnings'], result
            return result['sessions']
        try:
            args = ['--tag', "literal 'quote'; $HOME"]
            created = json.loads(run('start', 'smoke', '--name', 'review', '--cwd', str(work), *scope, '--json', '--', *args).stdout)
            assert len(created['sessions']) == 1, created
            session_id = created['sessions'][0]['id']
            deadline = time.monotonic() + 5
            while not receipt.exists():
                assert time.monotonic() < deadline, 'worker did not start'
                time.sleep(.05)
            data = json.loads(receipt.read_text())
            assert data == dict(argv=args, cwd=str(work), marker='configured', ssh=None, wt=None), data
            rows = inventory()
            assert rows[0]['id'] == session_id and rows[0]['name'] == 'review' and rows[0]['agent'] == 'fixture'
            assert sorted(rows[0]['capabilities']) == ['attach', 'detach', 'stop']
            assert 'token' not in json.dumps(rows)
            physical = rows[0]['reference']['session']
            run('start', 'smoke', '--name', 'review', *scope, ok=False)
            assert len(inventory()) == 1
            # Attach from a real pseudo-terminal, then detach only that owned session.
            master, slave = pty.openpty()
            attached = subprocess.Popen([binary, 'attach', 'review', *scope], env=dict(environment, TERM='xterm-256color'), stdin=slave, stdout=slave, stderr=slave, start_new_session=True)
            deadline = time.monotonic() + 8
            while not any(row['clients'] == 1 for row in inventory()):
                assert attached.poll() is None, 'attach exited before connecting'
                assert time.monotonic() < deadline, 'attach did not connect'
                time.sleep(.05)
            run('detach', 'review', *scope)
            attached.wait(timeout=5)
            assert inventory()[0]['clients'] == 0
            assert subprocess.run(['tmux', '-S', socket, 'show-options', '-t', physical, '-v', 'status'], capture_output=True, text=True).stdout.strip() == 'off'
            # A foreign session stays visible, but our lifecycle never claims its ownership.
            subprocess.run(['tmux', '-S', socket, 'new-session', '-d', '-s', 'foreign', '/bin/sleep', '180'], check=True)
            run('stop', 'foreign', *scope, ok=False)
            assert any(row['name'] == 'foreign' for row in inventory())
            # Changing the owner marker blocks both stop and detach.
            record = next((root / 'state/agent-ssh/sessions').glob('*.json'))
            token = json.loads(record.read_text())['token']
            subprocess.run(['tmux', '-S', socket, 'set-environment', '-t', physical, 'AGENT_SSH_SESSION_TOKEN', 'different_owner'], check=True)
            run('stop', session_id, *scope, ok=False)
            run('detach', session_id, *scope, ok=False)
            subprocess.run(['tmux', '-S', socket, 'set-environment', '-t', physical, 'AGENT_SSH_SESSION_TOKEN', token], check=True)
            run('start', 'smoke', '--name', 'review-long', *scope)
            run('stop', 'review', *scope)
            assert {row['name'] for row in inventory()} == {'review-long', 'foreign'}
            run('attach', 'missing', *scope, ok=False)
            assert {row['name'] for row in inventory()} == {'review-long', 'foreign'}
            run('stop', 'review-long', *scope)
            assert [row['name'] for row in inventory()] == ['foreign']
            print('Session lifecycle passed: literal presets, stable identities, duplicate rejection, real PTY attach/detach, exact owned stop, ownership mismatch, no implicit creation.')
        finally:
            if attached is not None and attached.poll() is None:
                attached.terminate()
                attached.wait(timeout=5)
            for fd in [master, slave]:
                if fd is not None:
                    os.close(fd)
            subprocess.run(['tmux', '-S', socket, 'kill-server'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


if __name__ == '__main__':
    main()