agent-ssh 0.4.0

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
"""Read-only discovery/check; only the explicit attach action may exec a frontend.

No shell commands, model requests, signals, environment exports, or process adoption.
Existing live owners are never replaced. A dead legacy launcher resumes its exact
recorded conversation through the deployed managed-launch helper.
"""
import ipaddress
import json
import os
from pathlib import Path
import sys
import time
import uuid
from urllib.parse import urlsplit

DEADLINE = time.monotonic() + 8
HOME = Path.home()


def bounded(path, maximum=1048576):
    if time.monotonic() > DEADLINE:
        raise ValueError("remote observation deadline exceeded")
    with open(path, "rb") as file:
        value = file.read(maximum + 1)
    if len(value) > maximum:
        raise ValueError("remote observation exceeds bound")
    return value


def proc(pid):
    root = Path('/proc') / str(pid)
    stat = bounded(root / 'stat', 65536).decode().rsplit(') ', 1)[1].split()
    return dict(pid=int(pid), parent=int(stat[1]), start=int(stat[19]),
                argv=[x.decode() for x in bounded(root / 'cmdline').split(b'\0') if x])


def env(pid):
    values = {}
    for item in bounded(Path('/proc') / str(pid) / 'environ').split(b'\0'):
        key, sep, value = item.partition(b'=')
        if sep and key in (b'SSH_CONNECTION', b'CODEX_HOME', b'TMUX'):
            if key in values:
                raise ValueError('duplicate identity environment variable')
            values[key] = value.decode()
    return values


def option(argv, name):
    locations = [i for i, value in enumerate(argv) if value == name]
    if len(locations) != 1 or locations[0] + 1 >= len(argv):
        raise ValueError('missing or ambiguous launcher option ' + name)
    return argv[locations[0] + 1]


def state(path):
    value = json.loads(bounded(path))
    if not isinstance(value, dict):
        raise ValueError('invalid launcher state')
    return value


def thread_ids(value):
    result = set()
    for key in ('activeThreadId', 'retainedThreadId', 'threadId'):
        if value.get(key):
            result.add(str(uuid.UUID(value[key])))
    for item in value.get('keptThreads', []):
        candidate = item if isinstance(item, str) else item.get('threadId')
        if candidate:
            result.add(str(uuid.UUID(candidate)))
    return result


def census():
    result = {}
    for index, entry in enumerate(Path('/proc').iterdir()):
        if index > 32768:
            raise ValueError('process census exceeds bound')
        if entry.name.isdigit():
            try:
                result[int(entry.name)] = proc(entry.name)
            except (FileNotFoundError, ProcessLookupError, PermissionError):
                pass
    return result


def launchers(rows):
    result = []
    for bridge in rows.values():
        argv = bridge['argv']
        if len(argv) < 2 or Path(argv[0]).name != 'marshal-shim' or argv[1] != 'codex-bridge':
            continue
        launcher = rows.get(bridge['parent'])
        if not launcher or len(launcher['argv']) < 2 or launcher['argv'][1] != 'codex-run':
            continue
        try:
            path = option(argv, '--launcher-state-file')
            data = state(path)
            cwd = option(argv, '--launcher-cwd')
            endpoint = (option(argv, '--proxy-endpoint') if '--proxy-endpoint' in argv else
                        option(argv, '--endpoint') if '--endpoint' in argv else None)
            frontends = [p for p in rows.values() if p['parent'] == launcher['pid'] and
                         '--remote' in p['argv'] and (endpoint is None or option(p['argv'], '--remote') == endpoint)]
            servers = [p for p in rows.values() if p['parent'] == launcher['pid'] and
                       len(p['argv']) > 1 and p['argv'][1] == 'app-server']
            result.append(dict(launcher=launcher, bridge=bridge, state_file=path,
                               state=data, ids=thread_ids(data), cwd=cwd,
                               endpoint=endpoint, frontends=frontends, servers=servers))
        except FileNotFoundError:
            # A launcher shutting down cannot provide an exact recovery binding.
            continue
    return result


def connection(value):
    parts = value.split()
    if len(parts) != 4:
        raise ValueError('invalid SSH connection tuple')
    return (str(ipaddress.ip_address(parts[0])), int(parts[1]),
            str(ipaddress.ip_address(parts[2])), int(parts[3]))


def socket_proof(item, expected, rows):
    # Match the exact established TCP tuple, then prove its socket is owned by
    # an sshd ancestor of this launcher. Inherited environment alone is not proof.
    inodes = set()
    def endpoint(text, ipv6):
        address, port = text.split(':')
        octets = b''.join(int(address[i:i+8], 16).to_bytes(4, sys.byteorder)
                          for i in range(0, len(address), 8))
        ip = ipaddress.ip_address(octets)
        if ipv6 and ip.ipv4_mapped:
            ip = ip.ipv4_mapped
        return str(ip), int(port, 16)
    for name, ipv6 in [('tcp', False), ('tcp6', True)]:
        for line in bounded('/proc/net/' + name, 4194304).decode().splitlines()[1:]:
            fields = line.split()
            if len(fields) < 10 or fields[3] != '01':
                continue
            local, remote = endpoint(fields[1], ipv6), endpoint(fields[2], ipv6)
            if (remote[0], remote[1], local[0], local[1]) == expected:
                inodes.add('socket:[' + fields[9] + ']')
    parent = item['launcher']['parent']
    for _ in range(128):
        p = rows.get(parent)
        if not p:
            break
        if p['argv'] and Path(p['argv'][0].split(':')[0]).name == 'sshd':
            try:
                if any(os.readlink(fd) in inodes for fd in (Path('/proc') / str(parent) / 'fd').iterdir()):
                    return True
            except FileNotFoundError:
                return False
        parent = p['parent']
    return False


def rollout(reference):
    root = Path(reference['codex_home']) / 'sessions'
    for index, path in enumerate(root.rglob('*' + reference['thread_id'] + '*.jsonl')):
        if index >= 16 or time.monotonic() > DEADLINE:
            raise ValueError('conversation lookup exceeds bound')
        with path.open('rb') as file:
            line = file.readline(65537)
        if len(line) > 65536:
            continue
        data = json.loads(line)
        if data.get('type') == 'session_meta' and data.get('payload', {}).get('id') == reference['thread_id']:
            return True
    return False


def reference_for(item, environment):
    data = item['state']
    thread = data.get('activeThreadId') or data.get('retainedThreadId') or data.get('threadId')
    thread = str(uuid.UUID(thread))
    if len(item['servers']) != 1 or len(item['frontends']) > 1:
        raise ValueError('legacy launcher has no unique server/frontend identity')
    managed = HOME / '.local/bin/marshal-codex-session'
    reference = dict(thread_id=thread, cwd=item['cwd'],
                     yolo=any(x in item['launcher']['argv'] for x in ('--yolo', '--dangerously-bypass-approvals-and-sandbox')),
                     codex_program=item['servers'][0]['argv'][0], managed_program=str(managed),
                     codex_home=environment.get(b'CODEX_HOME', str(HOME / '.codex')),
                     launcher_pid=item['launcher']['pid'], launcher_start=item['launcher']['start'],
                     state_file=item['state_file'])
    if not managed.is_file() or not rollout(reference) or not Path(reference['cwd']).is_dir():
        raise ValueError('legacy conversation has no verified managed resume path')
    if proc(item['launcher']['pid'])['start'] != reference['launcher_start']:
        raise ValueError('launcher identity changed')
    return reference


def observe(request, rows, items):
    found = []
    for item in items:
        environment = env(item['launcher']['pid'])
        if b'SSH_CONNECTION' not in environment:
            continue
        peer = connection(environment[b'SSH_CONNECTION'])
        matches = [c for c in request if tuple(c) == peer]
        if not matches or not socket_proof(item, peer, rows):
            continue
        reference = reference_for(item, environment)
        found.append(dict(connection=list(peer), reference=reference))
    return found


def check(reference, rows, items):
    owners = [item for item in items if reference['thread_id'] in item['ids']]
    if len(owners) > 1:
        return dict(state='unavailable', reason='multiple remote launchers own this conversation')
    if owners:
        item = owners[0]
        same = (item['launcher']['pid'] == reference['launcher_pid'] and
                item['launcher']['start'] == reference['launcher_start'] and
                item['state_file'] == reference['state_file'])
        if not same or item['frontends']:
            mode = 'managed' if env(item['launcher']['pid']).get(b'TMUX') else 'direct'
            return dict(state='already_running', mode=mode, reason='remote conversation already has a live interface; it will not be duplicated')
        if len(item['servers']) == 1 and item['bridge']['pid'] in rows and item['endpoint']:
            endpoint = urlsplit(item['endpoint'])
            if endpoint.scheme != 'ws' or endpoint.hostname not in ('127.0.0.1', '::1') or not endpoint.port:
                return dict(state='unavailable', reason='runtime endpoint is not a verified loopback bridge')
            return dict(state='attachable', mode='reattach', endpoint=item['endpoint'])
        return dict(state='unavailable', reason='remote runtime has no verified live app-server')
    # The original process might have changed thread/state; never start over it.
    original = rows.get(reference['launcher_pid'])
    if original and original['start'] == reference['launcher_start']:
        return dict(state='unavailable', reason='original launcher still exists but its conversation binding changed')
    for process in rows.values():
        if process.get('argv') and Path(process['argv'][0]).name == 'codex' and reference['thread_id'] in process['argv']:
            return dict(state='already_running', reason='remote conversation has another explicit Codex owner')
    if not Path(reference['managed_program']).is_file() or not Path(reference['cwd']).is_dir() or not rollout(reference):
        return dict(state='unavailable', reason='recorded conversation or managed resume program is unavailable')
    return dict(state='attachable', mode='resume')


def main():
    action = sys.argv[1]
    request = json.loads(sys.argv[2])
    rows = census()
    items = launchers(rows)
    if action == 'observe-local':
        result = []
        for item in items:
            environment = env(item['launcher']['pid'])
            if environment.get(b'TMUX'):
                continue
            reference = reference_for(item, environment)
            result.append(dict(reference=reference, observation=check(reference, rows, items)))
    elif action == 'observe':
        result = observe(request, rows, items)
    else:
        str(uuid.UUID(request['thread_id']))
        result = check(request, rows, items)
        if action in ('attach', 'attach-existing'):
            if result['state'] != 'attachable':
                raise ValueError(result['reason'])
            if action == 'attach-existing' and result['mode'] != 'reattach':
                raise ValueError('runtime has exited; attach never creates a replacement. Use agent-ssh load to resume the saved conversation.')
            argv = ['resume', request['thread_id'], '--cd', request['cwd']]
            if request['yolo']:
                argv.append('--yolo')
            os.chdir(request['cwd'])
            os.environ['CODEX_HOME'] = request['codex_home']
            if result['mode'] == 'reattach':
                program = request['codex_program']
                argv = ['--remote', result['endpoint'], *argv]
            else:
                program = request['managed_program']
            os.execv(program, [program, *argv])
    print(json.dumps(result, separators=(',', ':')))


if __name__ == '__main__':
    try:
        main()
    except Exception as error:
        print('Remote Codex recovery: ' + str(error), file=sys.stderr)
        sys.exit(1)