agent-ssh 0.4.0

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
param([string]$WindowSelector = '', [string]$ControlDirectory = '')
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$ProgressPreference = 'SilentlyContinue'
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
Add-Type -Path (Join-Path $PSScriptRoot 'console-probe.cs') -ReferencedAssemblies System.Web.Extensions
Add-Type -Path (Join-Path $PSScriptRoot 'passive-environment.cs')
$all = @(Get-CimInstance Win32_Process)
if ($all.Count -gt 32768) { throw 'Process census exceeds bound' }
$byPid = @{}
foreach ($p in $all) { $byPid[[uint32]$p.ProcessId] = $p }
$windows = @([CaptureNative]::Windows() | Where-Object { $_.visible })
if ($WindowSelector) {
    if ($WindowSelector -match '^0x[0-9a-fA-F]+$') { $WindowSelector = [Convert]::ToInt64($WindowSelector.Substring(2),16).ToString() }
    $windows = @($windows | Where-Object { $_.hwnd -eq $WindowSelector -or $_.title -eq $WindowSelector })
}
$records = @()
foreach ($p in $all) {
    if ($p.Name -notin @('codex.exe','ssh.exe','powershell.exe','pwsh.exe') -or !$p.CommandLine -or !$p.ExecutablePath) { continue }
    $argv = @([CaptureNative]::Argv($p.CommandLine))
    if ($p.Name -eq 'codex.exe' -and ($argv -contains 'app-server' -or $argv -contains 'exec-server')) { continue }
    if ($p.Name -in @('powershell.exe','pwsh.exe') -and $argv.Count -ne 1) { continue }
    $ancestor = [uint32]$p.ParentProcessId
    $terminal = $null
    $visited = @{}
    for ($depth=0; $depth -lt 128 -and $byPid.ContainsKey($ancestor); $depth++) {
        if ($visited.ContainsKey($ancestor)) { break }; $visited[$ancestor]=$true
        if ($byPid[$ancestor].Name -eq 'WindowsTerminal.exe') { $terminal=$ancestor; break }
        $ancestor=[uint32]$byPid[$ancestor].ParentProcessId
    }
    if ($null -eq $terminal) { continue }
    $live = Get-Process -Id $p.ProcessId -ErrorAction SilentlyContinue
    if (!$live) { continue }
    $ticks = $live.StartTime.ToUniversalTime().Ticks
    if ([Math]::Abs($ticks - $p.CreationDate.ToUniversalTime().Ticks) -gt 10000) { throw 'Process identity changed during census' }
    $session = [PassiveEnvironment]::Session($p.ProcessId,$ticks)
    if (!$session) { continue }
    $records += [pscustomobject]@{pid=[uint32]$p.ProcessId;parent_pid=[uint32]$p.ParentProcessId;start_ticks=[uint64]$ticks;executable=[string]$p.ExecutablePath;argv=$argv;session_id=$session;terminal_pid=$terminal}
}
# Choose the caller's terminal instance if identifiable, otherwise require one candidate.
$terminalPids = @($records | Where-Object { $_.argv[0] -match '(?i)(codex|ssh)(\.exe)?$' } | Select-Object -ExpandProperty terminal_pid -Unique)
$windows = @($windows | Where-Object { $terminalPids -contains $_.pid })
if (!$WindowSelector -and $env:WT_SESSION) {
    $callerPids = @($records | Where-Object { $_.session_id -eq $env:WT_SESSION } | Select-Object -ExpandProperty terminal_pid -Unique)
    if ($callerPids.Count -eq 1) { $windows = @($windows | Where-Object { $_.pid -eq $callerPids[0] }) }
}
if ($windows.Count -ne 1) { throw 'Passive Terminal scope is ambiguous; use save --window <HWND or exact caption>' }
$window = $windows[0]
if (@([CaptureNative]::Windows() | Where-Object { $_.pid -eq $window.pid }).Count -ne 1) { throw 'Multiple windows in one Terminal process need an explicit window-to-session registry; refusing to guess' }
$terminalProcess = Get-Process -Id $window.pid
$exe = $terminalProcess.Path
$directory = Split-Path -Parent $exe
if (Test-Path -LiteralPath (Join-Path $directory '.portable')) {
    $statePath = Join-Path $directory 'settings\state.json'
} elseif ($exe -match 'Microsoft.WindowsTerminalPreview_') {
    $statePath = Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\state.json'
} elseif ($exe -match 'Microsoft.WindowsTerminal_') {
    $statePath = Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\state.json'
} else { throw 'Unsupported Terminal distribution; passive state location cannot be established' }
$state = Get-Item -LiteralPath $statePath
if ($state.Length -gt 8388608) { throw 'Native layout checkpoint exceeds size bound' }
$before = [IO.File]::ReadAllBytes($statePath)
$stamp = $state.LastWriteTimeUtc
$after = [IO.File]::ReadAllBytes($statePath)
if ([Convert]::ToBase64String($before) -ne [Convert]::ToBase64String($after)) { throw 'Native layout checkpoint changed while reading; retry save' }
if (([DateTime]::UtcNow - $stamp).TotalSeconds -gt 420) { throw 'No recent passive layout checkpoint. Enable Windows Terminal firstWindowPreference=persistedWindowLayout and allow its first five-minute checkpoint.' }
$layout = [Text.Encoding]::UTF8.GetString($before).TrimStart([char]0xfeff) | ConvertFrom-Json
if (!$layout.PSObject.Properties['persistedWindowLayouts'] -or @($layout.persistedWindowLayouts).Count -eq 0) { throw 'No passive layout checkpoint yet. Enable Windows Terminal firstWindowPreference=persistedWindowLayout and allow its first five-minute checkpoint.' }
$selectedRecords = @($records | Where-Object { $_.terminal_pid -eq $window.pid })
# Recheck all process identities after sampling the checkpoint and TCP ownership.
$connections = @([CaptureNative]::Connections())
foreach ($record in $selectedRecords) {
    $live = Get-Process -Id $record.pid -ErrorAction Stop
    if ($live.StartTime.ToUniversalTime().Ticks.ToString() -ne $record.start_ticks.ToString()) { throw 'Process identity changed during passive observation' }
}
if ($terminalProcess.StartTime.ToUniversalTime().Ticks -ne (Get-Process -Id $window.pid).StartTime.ToUniversalTime().Ticks) { throw 'Terminal process identity changed' }
[pscustomobject]@{hwnd=$window.hwnd;records=$selectedRecords;connections=$connections;layout=$layout;checkpoint_utc=$stamp.ToString('o');age_seconds=[Math]::Max(0,([DateTime]::UtcNow-$stamp).TotalSeconds)} | ConvertTo-Json -Depth 32 -Compress