agent-ssh 0.4.1

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
param([string]$WindowSelector = '', [switch]$ProcessesOnly, [string]$ControlDirectory = '')
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$ProgressPreference = 'SilentlyContinue'
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
$workBase = [IO.Path]::GetFullPath([IO.Path]::GetTempPath())
if ($ControlDirectory) {
    $canonicalControl = [IO.Path]::GetFullPath($ControlDirectory)
    if ($canonicalControl -ne $ControlDirectory -or !(Test-Path -LiteralPath $canonicalControl -PathType Container)) { throw 'Invalid native capture control directory' }
    $workBase = $canonicalControl
}
$work = Join-Path $workBase ('agent-ssh-native-' + [guid]::NewGuid().ToString('N'))
$null = New-Item -ItemType Directory -Path $work
$activeHelper = $null
$activeLease = $null
$originalTab = $null
$lastSelected = $null
$inputTick = $null
$deadline = [DateTime]::UtcNow.AddSeconds(100)
$selectionWatchdog = $null
$selectionJournal = $null
$preserveArtifacts = $false
$control = $work
if ($ControlDirectory) {
    $control = [IO.Path]::GetFullPath($ControlDirectory)
    if ($control -ne $ControlDirectory -or !(Test-Path -LiteralPath $control -PathType Container)) { throw 'Invalid native capture control directory' }
}
try {
    $source = Join-Path $PSScriptRoot 'console-probe.cs'
    $compiler = Join-Path ([Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) 'csc.exe'
    if (!(Test-Path -LiteralPath $compiler)) { throw 'Windows .NET Framework C# compiler unavailable' }
    $helperExe = Join-Path $work 'console-probe.exe'
    $compileOutput = & $compiler /nologo /target:exe /reference:System.Web.Extensions.dll ("/out:" + $helperExe) $source 2>&1
    if ($LASTEXITCODE -ne 0) { throw 'Native console helper compilation failed' }
    $null = [Reflection.Assembly]::Load([IO.File]::ReadAllBytes($helperExe))
    $all = @(Get-CimInstance Win32_Process)
    $byPid = @{}
    foreach ($process in $all) { $byPid[[uint32]$process.ProcessId] = $process }
    foreach ($liveCodex in @(Get-Process -Name codex -ErrorAction SilentlyContinue)) {
        if (!$byPid.ContainsKey([uint32]$liveCodex.Id) -or $byPid[[uint32]$liveCodex.Id].Name -ne 'codex.exe') { throw 'Live Codex process is missing from the metadata census' }
    }
    $records = @()
    foreach ($process in $all) {
        if ($process.Name -notin @('codex.exe', 'ssh.exe', 'powershell.exe', 'pwsh.exe')) { continue }
        if (!$process.CommandLine -or !$process.CreationDate) {
            if ($process.Name -eq 'codex.exe') { throw 'Live Codex process command line or creation metadata is unavailable' }
            continue
        }
        $argv = @([CaptureNative]::Argv($process.CommandLine))
        if ($process.Name -eq 'codex.exe' -and ($argv -contains 'app-server' -or $argv -contains 'exec-server')) { continue }
        if ($process.Name -in @('powershell.exe','pwsh.exe')) {
            if ($argv.Count -ne 1 -or !$byPid.ContainsKey([uint32]$process.ParentProcessId) -or $byPid[[uint32]$process.ParentProcessId].Name -ne 'WindowsTerminal.exe') { continue }
        }
        $liveIdentity = Get-Process -Id $process.ProcessId -ErrorAction Stop
        if ([Math]::Abs($liveIdentity.StartTime.ToUniversalTime().Ticks - $process.CreationDate.ToUniversalTime().Ticks) -gt 10000) { throw 'CIM process identity changed' }
        $records += [pscustomobject]@{pid=[uint32]$process.ProcessId; parent_pid=[uint32]$process.ParentProcessId; start_ticks=[uint64]$liveIdentity.StartTime.ToUniversalTime().Ticks; executable=[string]$process.ExecutablePath; argv=$argv}
    }
    if ($ProcessesOnly) { ConvertTo-Json -InputObject @($records | Where-Object { [IO.Path]::GetFileName($_.executable) -eq 'codex.exe' }) -Depth 8 -Compress; return }
    Add-Type -AssemblyName UIAutomationClient
    Add-Type -AssemblyName UIAutomationTypes
    Add-Type -AssemblyName WindowsBase
    $scope = [System.Windows.Automation.TreeScope]::Descendants
    $trueCondition = [System.Windows.Automation.Condition]::TrueCondition
    function RuntimeKey($element) { return ($element.GetRuntimeId() -join ',') }
    function CheckInput {
        if ([DateTime]::UtcNow -gt $deadline) { throw 'Capture deadline exceeded' }
        if ([CaptureNative]::InputTick() -ne $inputTick) { throw 'Physical input changed during capture; save cancelled' }
        $scopedWindows = @([CaptureNative]::Windows() | Where-Object { $_.pid -eq $selectedWindow.pid })
        if ($scopedWindows.Count -ne 1 -or $scopedWindows[0].hwnd -ne $selectedWindow.hwnd) { throw 'Terminal HWND scope changed; sibling-window console capture is unsupported' }
        if ((Get-Process -Id $selectedWindow.pid).StartTime.ToUniversalTime().Ticks -ne $windowStart) { throw 'Terminal process identity changed' }
    }
    function AssertIdentity($record) {
        $live = Get-Process -Id $record.pid -ErrorAction Stop
        if ([uint64]$live.StartTime.ToUniversalTime().Ticks -ne $record.start_ticks) { throw 'Process identity changed during capture' }
    }
    function FinishHelper {
        if ($activeLease -and (Test-Path -LiteralPath $activeLease)) { Remove-Item -LiteralPath $activeLease -Force }
        if ($activeHelper) {
            if (!$activeHelper.WaitForExit(4000)) { throw 'Console helper failed to release its bounded challenge' }
        }
    }
    function Probe($record, [string]$nonce) {
        AssertIdentity $record
        $receipt = Join-Path $work ([guid]::NewGuid().ToString('N') + '.json')
        $script:activeLease = Join-Path $work ([guid]::NewGuid().ToString('N') + '.lease')
        if ($nonce) { [IO.File]::WriteAllText($activeLease, 'lease') }
        $parentProcess = Get-Process -Id $PID
        $psi = New-Object System.Diagnostics.ProcessStartInfo
        $psi.FileName = $helperExe
        $psi.Arguments = ('{0} {1} "{2}" "{3}" "{4}" {5} {6}' -f $record.pid,$record.start_ticks,$receipt,$nonce,$activeLease,$PID,$parentProcess.StartTime.ToUniversalTime().Ticks)
        $psi.UseShellExecute = $false
        $psi.CreateNoWindow = $true
        $script:activeHelper = [Diagnostics.Process]::Start($psi)
        $watch = [Diagnostics.Stopwatch]::StartNew()
        while ($watch.ElapsedMilliseconds -lt 3500) {
            if (Test-Path -LiteralPath $receipt) {
                try { $reply = Get-Content -Raw -LiteralPath $receipt | ConvertFrom-Json } catch { $reply = $null }
                if ($reply -and ($reply.ready -or $reply.done)) { return [pscustomobject]@{reply=$reply; path=$receipt; helper_pid=$activeHelper.Id} }
            }
            if ($activeHelper.HasExited -and !(Test-Path -LiteralPath $receipt)) { throw 'Console helper produced no receipt' }
            Start-Sleep -Milliseconds 10
        }
        throw 'Console helper timed out'
    }
    function VerifyProbe($probe, $record) {
        FinishHelper
        $reply = Get-Content -Raw -LiteralPath $probe.path | ConvertFrom-Json
        if ($reply.PSObject.Properties['error']) { throw ('Console observation failed: ' + $reply.error) }
        if (!$reply.done -or !$reply.identity_valid) { throw 'Incomplete console identity observation' }
        if ($reply.PSObject.Properties['title_restore'] -and $reply.title_restore -eq 'failed') { throw 'Console title restoration failed' }
        $before = @($reply.members | Where-Object { $_ -ne $probe.helper_pid } | Sort-Object)
        $after = @($reply.members_after | Where-Object { $_ -ne $probe.helper_pid } | Sort-Object)
        if (($before -join ',') -ne ($after -join ',')) { throw 'Console membership changed during capture' }
        AssertIdentity $record
        return $reply
    }
    function Leaves($window) {
        return @($window.FindAll($scope,$trueCondition) | Where-Object { $_.Current.ClassName -eq 'TermControl' -and $_.Current.ControlType -eq [System.Windows.Automation.ControlType]::Text })
    }
    function GeometryKey($leaves) {
        return (@($leaves | ForEach-Object { (RuntimeKey $_) + '|' + $_.Current.BoundingRectangle.ToString([Globalization.CultureInfo]::InvariantCulture) } | Sort-Object) -join ';')
    }
    $candidatePids = @{}
    foreach ($record in $records) { $candidatePids[$record.pid] = $record }
    $candidates = @()
    $terminalPids = @{}
    foreach ($record in $records) {
        $isShell = [IO.Path]::GetFileName($record.executable) -in @('powershell.exe','pwsh.exe')
        $ancestor = $record.parent_pid
        $visited = @{}
        $nested = $false
        $terminalPid = $null
        for ($depth=0; $depth -lt 128 -and $byPid.ContainsKey($ancestor); $depth++) {
            if ($visited.ContainsKey($ancestor)) { break }; $visited[$ancestor] = $true
            if ($candidatePids.ContainsKey($ancestor) -and [IO.Path]::GetFileName($candidatePids[$ancestor].executable) -notin @('powershell.exe','pwsh.exe')) { $nested = $true }
            if ($byPid[$ancestor].Name -eq 'WindowsTerminal.exe') { $terminalPid = $ancestor; break }
            $ancestor = [uint32]$byPid[$ancestor].ParentProcessId
        }
        if (!$nested -and $null -ne $terminalPid) { $candidates += $record; if (!$isShell) { $terminalPids[$terminalPid] = $true } }
    }
    if ($candidates.Count -eq 0) { throw 'No recognized interactive Codex or SSH console candidates' }
    $windows = @([CaptureNative]::Windows() | Where-Object { $_.visible -and $terminalPids.ContainsKey($_.pid) })
    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 })
    }
    if ($windows.Count -ne 1) { throw 'Terminal window scope is ambiguous or unavailable; pass an observed HWND or exact caption with --window' }
    $selectedWindow = $windows[0]
    if (@([CaptureNative]::Windows() | Where-Object { $_.pid -eq $selectedWindow.pid }).Count -ne 1) {
        throw 'Selected Terminal process hosts multiple HWNDs, including hidden siblings; exact console scope is unsupported'
    }
    $windowProcess = Get-Process -Id $selectedWindow.pid
    $windowStart = $windowProcess.StartTime.ToUniversalTime().Ticks
    $window = [System.Windows.Automation.AutomationElement]::FromHandle([IntPtr][long]$selectedWindow.hwnd)
    if ($window.Current.ProcessId -ne $selectedWindow.pid) { throw 'Terminal HWND identity changed' }
    $candidates = @($candidates | Where-Object {
        $ancestor=$_.parent_pid
        for($depth=0;$depth -lt 128 -and $byPid.ContainsKey($ancestor);$depth++) {
            if($ancestor -eq $selectedWindow.pid){return $true}
            $ancestor=[uint32]$byPid[$ancestor].ParentProcessId
        }
        return $false
    })
    $sshCandidatePids = @{}
    foreach ($record in $candidates) {
        if ([IO.Path]::GetFileName($record.executable) -eq 'ssh.exe') { $sshCandidatePids[$record.pid] = $true }
    }
    $connectionsBefore = @([CaptureNative]::Connections() | Where-Object { $sshCandidatePids.ContainsKey($_.pid) })
    foreach ($connection in $connectionsBefore) {
        $owner=$candidatePids[$connection.pid]
        if ($connection.created_filetime -lt ([uint64]$owner.start_ticks - [uint64]504911232000000000)) { throw 'TCP ownership timestamp predates the current SSH process incarnation' }
    }
    $inputTick = [CaptureNative]::InputTick()
    $consoleGroups = @{}
    $candidates = @($candidates | Sort-Object @{Expression={ if ([IO.Path]::GetFileName($_.executable) -in @('powershell.exe','pwsh.exe')) {1} else {0} }})
    foreach ($record in $candidates) {
        CheckInput
        $probe = Probe $record ''
        $reply = VerifyProbe $probe $record
        $members = @($reply.members | Where-Object { $_ -ne $probe.helper_pid } | Sort-Object)
        if ([IO.Path]::GetFileName($record.executable) -in @('powershell.exe','pwsh.exe')) {
            if ($members.Count -ne 1 -or $members[0] -ne $record.pid) { continue }
        }
        $key = $members -join ','
        if ($consoleGroups.ContainsKey($key)) { throw 'Ambiguous independent recognized owners share a console' }
        $consoleGroups[$key] = [pscustomobject]@{record=$record; members=$members; used=$false}
    }
    $tabs = @($window.FindAll($scope,$trueCondition) | Where-Object { $_.Current.ControlType -eq [System.Windows.Automation.ControlType]::TabItem })
    if ($tabs.Count -eq 0 -or $tabs.Count -gt 128) { throw 'Terminal tab count unavailable or exceeds bound' }
    $previousX = [double]::NegativeInfinity
    $tabKeys = @($tabs | ForEach-Object { RuntimeKey $_ })
    if (@($tabKeys | Select-Object -Unique).Count -ne $tabs.Count) { throw 'Duplicate tab RuntimeIds' }
    $selectedIndex = $null
    for ($i=0;$i -lt $tabs.Count;$i++) {
        $x=$tabs[$i].Current.BoundingRectangle.X
        if ($x -lt $previousX) { throw 'Tab order contradicts observed positions' };$previousX=$x
        if($tabs[$i].GetCurrentPattern([System.Windows.Automation.SelectionItemPattern]::Pattern).Current.IsSelected){if($originalTab){throw 'Multiple selected tabs'};$originalTab=$tabs[$i];$selectedIndex=$i}
    }
    if (!$originalTab) { throw 'Selected tab unavailable' }
    $uiClient = [System.Windows.Automation.AutomationElement].Assembly.Location
    $uiTypes = [System.Windows.Automation.ControlType].Assembly.Location
    $windowsBase = [System.Windows.Rect].Assembly.Location
    $watchdogExe = Join-Path $work 'selection-watchdog.exe'
    $compileOutput = & $compiler /nologo /target:exe /reference:System.Web.Extensions.dll ("/reference:" + $helperExe) ("/reference:" + $uiClient) ("/reference:" + $uiTypes) ("/reference:" + $windowsBase) ("/out:" + $watchdogExe) (Join-Path $PSScriptRoot 'selection-watchdog.cs') 2>&1
    if ($LASTEXITCODE -ne 0) { throw 'Independent selection watchdog compilation failed' }
    $collector = Get-Process -Id $PID
    $journalPath = Join-Path $control 'selection-journal.json'
    $watchdogReady = Join-Path $control 'selection-watchdog-ready.json'
    $watchdogReceipt = Join-Path $control 'selection-watchdog-receipt.json'
    $selectionJournal = [ordered]@{
        parent_pid=$PID; parent_start_ticks=$collector.StartTime.ToUniversalTime().Ticks
        hwnd=$selectedWindow.hwnd; window_pid=$selectedWindow.pid; window_start_ticks=$windowStart
        input_tick=$inputTick; original_tab=@($originalTab.GetRuntimeId()); owned_tab=@($originalTab.GetRuntimeId())
        pending_tab=$null; deadline_utc_ticks=$deadline.Ticks; stop=$false
    }
    function WriteSelectionJournal {
        $temporary = $journalPath + '.new'
        [IO.File]::WriteAllText($temporary, (ConvertTo-Json -InputObject $selectionJournal -Depth 5 -Compress))
        [CaptureNative]::PublishJournal($temporary,$journalPath)
    }
    WriteSelectionJournal
    $watchdogStart = New-Object Diagnostics.ProcessStartInfo
    $watchdogStart.FileName = $watchdogExe
    $watchdogStart.Arguments = ('"{0}" "{1}" "{2}"' -f $journalPath,$watchdogReady,$watchdogReceipt)
    $watchdogStart.UseShellExecute=$false
    $watchdogStart.CreateNoWindow=$true
    [IO.File]::WriteAllText((Join-Path $control 'selection-watchdog-started'), 'selection cleanup acknowledgement required')
    $selectionWatchdog = [Diagnostics.Process]::Start($watchdogStart)
    $readyWatch = [Diagnostics.Stopwatch]::StartNew()
    while (!(Test-Path -LiteralPath $watchdogReady)) {
        if ($selectionWatchdog.HasExited -or $readyWatch.ElapsedMilliseconds -gt 3000) { throw 'Selection watchdog failed to become ready' }
        Start-Sleep -Milliseconds 10
    }
    CheckInput
    $resultTabs = @()
    foreach ($tab in $tabs) {
        CheckInput
        $tabTitle = $tab.Current.Name
        $attemptTrace = New-Object 'Collections.Generic.List[object]'
        $traceTruncated = $false
        if ($selectionWatchdog.HasExited) { throw 'Selection restoration watchdog exited unexpectedly' }
        $selectionJournal.pending_tab = @($tab.GetRuntimeId())
        WriteSelectionJournal
        $lastSelected = $tab
        $tab.GetCurrentPattern([System.Windows.Automation.SelectionItemPattern]::Pattern).Select()
        $selectionJournal.owned_tab = @($tab.GetRuntimeId())
        $selectionJournal.pending_tab = $null
        WriteSelectionJournal
        Start-Sleep -Milliseconds 40
        CheckInput
        if (!$tab.GetCurrentPattern([System.Windows.Automation.SelectionItemPattern]::Pattern).Current.IsSelected) { throw 'Tab selection changed unexpectedly' }
        $leaves = @(Leaves $window)
        if ($leaves.Count -eq 0 -or $leaves.Count -gt 64) { throw 'Terminal leaf count unavailable or exceeds bound' }
        $geometry = GeometryKey $leaves
        $leafMap = @{}
        foreach ($leaf in $leaves) {
            $b=$leaf.Current.BoundingRectangle
            if ($b.IsEmpty -or $b.Width -le 0 -or $b.Height -le 0) { throw 'Terminal pane rectangle unavailable' }
            $leafMap[(RuntimeKey $leaf)] = [pscustomobject]@{title=$leaf.Current.Name;rect=[pscustomobject]@{x=$b.X;y=$b.Y;width=$b.Width;height=$b.Height};binding=$null}
        }
        for ($markerAttempt=0; $markerAttempt -lt 2; $markerAttempt++) {
        foreach ($group in @($consoleGroups.Values)) {
            if ($group.used) { continue }
            CheckInput
            $nonce = 'agent-ssh-capture-' + [guid]::NewGuid().ToString('N')
            $probe = Probe $group.record $nonce
            if ($probe.reply.PSObject.Properties['error']) { $null=VerifyProbe $probe $group.record; throw 'Console challenge failed' }
            $hits = @()
            $markerWatch=[Diagnostics.Stopwatch]::StartNew()
            while($markerWatch.ElapsedMilliseconds -lt 180) {
                $hits = @(Leaves $window | Where-Object { $_.Current.HelpText -eq $nonce -or $_.Current.Name -eq $nonce })
                if($hits.Count -gt 0){break};Start-Sleep -Milliseconds 10
            }
            $reply = VerifyProbe $probe $group.record
            if ([IO.Path]::GetFileName($group.record.executable) -in @('powershell.exe','pwsh.exe')) {
                $shellMembers=@($reply.members | Where-Object { $_ -ne $probe.helper_pid })
                if ($shellMembers.Count -ne 1 -or $shellMembers[0] -ne $group.record.pid) { throw 'Fresh-shell console gained another process during capture' }
            }
            if ($attemptTrace.Count -lt 512) {
                $attemptTrace.Add([pscustomobject]@{
                    console_pid=$group.record.pid
                    kind=[IO.Path]::GetFileName($group.record.executable)
                    attempt=$markerAttempt; nonce=$nonce; hit_count=$hits.Count
                    matched_runtime_ids=@($hits | ForEach-Object { RuntimeKey $_ })
                    title_restore=$reply.title_restore
                })
            } else { $traceTruncated=$true }
            CheckInput
            if ($hits.Count -gt 1) { throw 'Console challenge matched multiple terminal leaves' }
            if ($hits.Count -eq 1) {
                $key = RuntimeKey $hits[0]
                if (!$leafMap.ContainsKey($key) -or $leafMap[$key].binding) { throw 'Console leaf identity is ambiguous or changed' }
                $leafMap[$key].binding = $group
                $group.used=$true
            }
            if ((GeometryKey @(Leaves $window)) -ne $geometry) { throw 'Pane identity or geometry changed during capture' }
            if (@($leafMap.Values | Where-Object { !$_.binding }).Count -eq 0) { break }
        }
        if (@($leafMap.Values | Where-Object { !$_.binding }).Count -eq 0) { break }
        }
        $unbound = @($leafMap.Keys | Where-Object { !$leafMap[$_].binding })
        if ($unbound.Count -gt 0) {
            $diagnostic = [pscustomobject]@{
                version=1; tab_index=$resultTabs.Count
                initial_tab_title=$tabTitle.Substring(0,[Math]::Min($tabTitle.Length,256))
                unbound_leaves=@($unbound | ForEach-Object {
                    $value=$leafMap[$_]
                    [pscustomobject]@{runtime_id=$_;title=$value.title.Substring(0,[Math]::Min($value.title.Length,256));rect=$value.rect}
                })
                candidate_consoles=@($consoleGroups.Values | Select-Object -First 512 | ForEach-Object {
                    [pscustomobject]@{console_pid=$_.record.pid;kind=[IO.Path]::GetFileName($_.record.executable);already_bound=$_.used}
                })
                attempts=@($attemptTrace.ToArray()); trace_truncated=$traceTruncated
            }
            $diagnosticJson = ConvertTo-Json -InputObject $diagnostic -Depth 8 -Compress
            if ([Text.Encoding]::UTF8.GetByteCount($diagnosticJson) -gt 262144) { throw 'Binding diagnostic exceeds metadata bound' }
            $diagnosticPath = Join-Path $control 'binding-diagnostic.json'
            [IO.File]::WriteAllText($diagnosticPath,$diagnosticJson)
            $preserveArtifacts=$true
            throw ('Selected Terminal pane has no exact supported agent-console binding; bounded metadata diagnostic: ' + $diagnosticPath)
        }
        $panes=@()
        foreach($leaf in $leaves) {
            $value=$leafMap[(RuntimeKey $leaf)]
            if(!$value.binding){throw 'Selected Terminal pane has no exact supported agent-console binding'}
            $panes += [pscustomobject]@{console_pid=$value.binding.record.pid;console_start_ticks=$value.binding.record.start_ticks;title=$value.title;rect=$value.rect;members=@($value.binding.members)}
        }
        $resultTabs += [pscustomobject]@{title=$tabTitle;panes=@($panes)}
    }
    CheckInput
    $finalTabs=@($window.FindAll($scope,$trueCondition) | Where-Object { $_.Current.ControlType -eq [System.Windows.Automation.ControlType]::TabItem } | ForEach-Object {RuntimeKey $_})
    if(($finalTabs -join ';') -ne ($tabKeys -join ';')){throw 'Tab membership or order changed during capture'}
    if((Get-Process -Id $selectedWindow.pid).StartTime.ToUniversalTime().Ticks -ne $windowStart){throw 'Terminal process identity changed'}
    $selectedRecords=@($consoleGroups.Values | Where-Object {$_.used} | ForEach-Object {$_.record})
    foreach($record in $selectedRecords){
        AssertIdentity $record
        if ([IO.Path]::GetFileName($record.executable) -in @('powershell.exe','pwsh.exe')) {
            $probe=Probe $record ''
            $reply=VerifyProbe $probe $record
            $shellMembers=@($reply.members | Where-Object { $_ -ne $probe.helper_pid })
            if ($shellMembers.Count -ne 1 -or $shellMembers[0] -ne $record.pid) { throw 'Fresh-shell console membership changed after binding' }
        }
    }
    $selectedSshPids=@{}
    foreach($record in $selectedRecords){
        if ([IO.Path]::GetFileName($record.executable) -eq 'ssh.exe') { $selectedSshPids[$record.pid]=$true }
    }
    $connections=@([CaptureNative]::Connections() | Where-Object {$selectedSshPids.ContainsKey($_.pid)})
    foreach ($connection in $connections) {
        $owner=$candidatePids[$connection.pid]
        if ($connection.created_filetime -lt ([uint64]$owner.start_ticks - [uint64]504911232000000000)) { throw 'TCP ownership timestamp predates the current SSH process incarnation' }
    }
    function EndpointKey($rows){return (@($rows | ForEach-Object {'{0}|{1}|{2}|{3}|{4}|{5}' -f $_.pid,$_.local_address,$_.local_port,$_.remote_address,$_.remote_port,$_.created_filetime} | Sort-Object)-join ';')}
    if((EndpointKey @($connectionsBefore | Where-Object {$selectedSshPids.ContainsKey($_.pid)})) -ne (EndpointKey $connections)){throw 'SSH TCP endpoints changed during capture'}
    $result=[pscustomobject]@{version=1;hwnd=$selectedWindow.hwnd;selected_tab=$selectedIndex;tabs=@($resultTabs);processes=@($selectedRecords);connections=@($connections)}
} finally {
    try {
        if (Get-Command FinishHelper -ErrorAction SilentlyContinue) { FinishHelper }
    } finally {
        $selectionReleased = $false
        try {
            if ($originalTab -and $lastSelected -and [CaptureNative]::InputTick() -eq $inputTick -and $lastSelected.GetCurrentPattern([System.Windows.Automation.SelectionItemPattern]::Pattern).Current.IsSelected) {
                $originalTab.GetCurrentPattern([System.Windows.Automation.SelectionItemPattern]::Pattern).Select()
                if (!$originalTab.GetCurrentPattern([System.Windows.Automation.SelectionItemPattern]::Pattern).Current.IsSelected) { throw 'Original tab restoration failed' }
            }
            $selectionReleased = $true
        } finally {
            if ($selectionWatchdog) {
                if ($selectionReleased) {
                    $selectionJournal.stop = $true
                    WriteSelectionJournal
                }
                if (!$selectionWatchdog.WaitForExit(6000) -or !(Test-Path -LiteralPath $watchdogReceipt)) {
                    $preserveArtifacts = $true
                    throw ('Independent selection cleanup unacknowledged; preserve diagnostics at ' + $control)
                }
                $ack = Get-Content -Raw -LiteralPath $watchdogReceipt | ConvertFrom-Json
                if ($ack.status -like 'failed*') {
                    $preserveArtifacts = $true
                    throw ('Independent selection cleanup failed; preserve diagnostics at ' + $control)
                }
            }
            if (!$preserveArtifacts -and (Test-Path -LiteralPath $work)) {
                $canonical = [IO.Path]::GetFullPath($work)
                $temporaryRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\'
                if ($canonical -ne $work -or !$canonical.StartsWith($temporaryRoot,[StringComparison]::OrdinalIgnoreCase) -or [IO.Path]::GetFileName($canonical) -notmatch '^agent-ssh-native-[0-9a-f]{32}$') { throw 'Unsafe temporary cleanup path' }
                Remove-Item -LiteralPath $canonical -Recurse -Force
            }
        }
    }
}
ConvertTo-Json -InputObject $result -Depth 12 -Compress