Plan: Remote execution phase 5 — the Windows client, ports, and a helper that survives the link

Closes: #493 (phase 5), #501. Relates to: #488 (meta plan: plans/remote-execution.adoc), #498 (2c), #492 (4). Branches: fix/windows-client-paths, feat/ssh-forward, feat/ssh-resilient-helper, one MR each, in that order. Status: Done (2026-10-27) — implemented as planned, with the errata below

Why

Phase 4 completed what runs on the remote. Three things remain before the program is whole. On a Windows client pi’s own tools cannot reach the remote at all (#501): every path is mangled before it reaches pi-ssh’s operations. A dev server on the remote cannot be opened from here. And a Wi-Fi drop mid-command kills the command and loses its output, since nothing the helper starts outlives its connection (helper.mjs:9-11, 270-279). The meta plan carries all three as phase 5 (remote-execution.adoc:96). They are independent, so each is a unit with its own branch and MR, planned here together, as the operator asked.

Design

5a. The Windows client (packages/pi-ssh/ops.ts, extension.ts; #501)

What breaks. pi’s read, write, edit and ls resolve a tool’s path with resolveToCwd(path, ctx.cwd) before calling the operations (write.js:31, read.js:73): pi’s resolvePath (utils/paths.js:83-87), which is node:path’s `resolve, win32 on a Windows client. pi-ssh hands the tools the remote root as their cwd (extension.ts, switched, remoteContext). A rooted path with no drive borrows one from process.cwd(), so on a Windows client src/x.ts against /home/me/app reaches the operations as C:\home\me\app\src\x.ts, which ws.resolve (ssh-workspace.ts:306-309) reads as a relative POSIX path under the root. (~ is not among the shapes: withRemoteHome, extension.ts:70-75, rewrites it to the remote home before pi resolves anything.)

The fix: a base pi cannot confuse with a local path, and one function to turn it back. On a win32 client switched gives the tools, as their cwd, the remote root spelled under a UNC device that names the session: \\pi-ssh\<anchor id>\home\me\app, where <anchor id> is the anchor’s 12-hex hash (anchor.ts, anchorFor). win32’s resolve keeps a base’s device and never consults process.cwd() for it, so every tool path comes back under that device, measured on this box with path.win32:

The model wrote The operations receive

src/x.ts

\\pi-ssh\<id>\home\me\app\src\x.ts

/etc/hosts

\\pi-ssh\<id>\etc\hosts

../other/y

\\pi-ssh\<id>\home\me\other\y

C:\Users\me\.pi\agent\remotes\box\app-<id>\src\x.ts (the anchor)

unchanged

C:\Users\me\Desktop\x (a local path, by mistake)

unchanged

hostPath(received, ws) in ops.ts, a pure function of two strings, called by every operation before ws.resolve:

Received Host path

Under \\pi-ssh\<id>

The rest, with /: /home/me/app/src/x.ts

Under the anchor (compared with both separators normalised to /)

As is; ws.resolve maps it under the root

Any other path with a device or drive

Refused: ENOENT naming the path, plus "a Windows path; the remote is POSIX"

On a POSIX client

The identity

The device is per anchor so two remote sessions in one pi (a helper’s worktree view, phase 4) never share one. ls, find and grep results are stated as remote POSIX paths already (2b); bash’s cwd passes through as the root; pi’s relative paths in results (`formatPathRelativeToCwdOrAbsolute) are relative to the UNC base and printed with /, so they read as the remote’s. The <cwd> block (2c) keeps showing the remote root, so the model writes POSIX paths.

Verification on Windows. The read/write/edit/ls parity block (test/parity.test.ts:197) skips on win32 (const POSIX), so pi-win never runs it. 5a lifts the skip for that block: the pipe transport runs the helper as a local child, and on Windows those four operations need no shell, rg or fd. The image case stays POSIX-only, since the sniff runs head on the remote (ops.ts, detectImageMimeType), which a Windows stand-in remote does not have; in production the remote is POSIX. bash, find and grep parity stay POSIX-only. The regression test for #501: the operations given the win32-resolved forms in the table (computed with path.win32, so it runs on any platform) reach the remote paths in the right column. pi-win runs the suite (topic pi-dev-win), and the acceptance is the operator’s live session from Windows: a read, write, edit and ls of relative, remote-absolute and anchor paths, logged.

5b. Port forwarding (packages/pi-ssh/forwards.ts, config.ts, commands.ts, helper.mjs, protocol.ts)

Commands.

Command What it does

/ssh forward <remote>[:<local>]

Starts ssh -N -o ExitOnForwardFailure=yes -o BatchMode=yes -L <local>:127.0.0.1:<remote> <destination>; <local> defaults to <remote>. Ready when a TCP connect to 127.0.0.1:<local> is accepted (polled, bounded by CONNECT_TIMEOUT_S); failed when the child exits first, reported with ssh’s last stderr line ("Address already in use", an auth failure). Replies with http://127.0.0.1:<local>;.

/ssh forwards

Each forward: remote port, local port, since when, live or ended (<reason>).

/ssh unforward <remote>

SIGTERM to the child; removed from the list.

A Forwards registry per session holds {remote, local, child, since, state}, with the spawner injected for tests. Every forward is torn down at session_shutdown and when /ssh switches session. A forward is its own ssh connection: a dropped helper link does not drop it, and a forward whose child exits is listed ended.

The port watch. A new streamed helper operation, ports, started by pi after the hello of a remote session and ended with the connection. Every PORT_POLL_MS (2 000) the helper lists listening TCP ports, from ss -ltnH where it is on PATH, else from /proc/net/tcp and tcp6 parsed directly (so a minimal host serves too), and emits a ports event when the set changes: {added: [{port, command?}], removed: [port]}, the command from /proc/<pid>/cmdline when readable. Where neither source exists (not Linux) the stream ends with one unsupported event. pi’s handling of added: a port already forwarded is ignored; otherwise with autoForward: false pi notifies "port 3000 is listening on the remote (node server.js); /ssh forward 3000`", and with `autoForward: true it starts the forward and notifies the URL. Never auto-forwarded, only notified: ports below 1024, and the remote’s sshd port, which the helper reads from its own SSH_CONNECTION (its fourth field) and puts in the hello as sshdPort.

Config. ~/.pi/agent/pi-ssh.json, parsed into a typed shape when the extension loads: { "autoForward"?: boolean, "node"?: string } (node is the remote node path the transport already takes, today unconfigurable). An invalid file is refused by name at load, with the notice naming the key; an absent file is the defaults. It is read from the agent directory only; a repository’s .pi/ cannot set it, since a remote project must not open ports on this machine.

Where the asks go. /ssh forward is the human’s command and an auto-forward is the operator’s standing decision in config: neither is judged. No tool is added; a model that wants a forward asks the human in words.

Shape. The helper becomes a daemon of the remote user’s session, and each ssh connection a relay to it. Today’s bootstrap uploads the helper and execs it on the connection’s stdio (connection.ts:88-95). In 5c the bootstrap uploads as now, then: if nothing answers on $HOME/.pi-ssh/daemon-<hash>.sock, starts setsid node helper.mjs --daemon <sock> with its stdio to $HOME/.pi-ssh/daemon-<hash>.log and waits for the socket (bounded, DAEMON_START_S, 5); then execs node helper.mjs --relay <sock>, which copies the connection’s stdin to the socket and the socket to stdout, byte for byte, and exits when either ends. Two connections racing to start a daemon are serialised by mkdir "$sock.lock" (atomic on POSIX; the loser waits for the socket; a lock older than DAEMON_START_S is stale and taken over). A socket file whose connect is refused is a dead daemon’s: removed, and a daemon started. The hash in the names means a new helper version is a new daemon beside the old one, which idles out.

Constant Value Meaning

DAEMON_IDLE_MS

600 000

With no client attached and no running request for this long, the daemon kills what it started and exits.

RESUME_BUFFER_BYTES

1 MiB per stream

The ring a running request keeps for replay; past it the oldest bytes go, and a gap frame says how many.

FINISHED_KEEP_MS

300 000

How long a finished request’s frames stay replayable.

RECONNECT_ATTEMPTS

5

Reconnects tried for in-flight work, with backoff over about 30 s, before it fails as today.

The conversation on a connection. The daemon speaks first, as today: hello (protocol 2, the helper hash, node, platform, arch, home, sshdPort, daemon: true, session: the daemon’s id). The client answers attach {client}, its id random per pi session, and the daemon replies attached {running: [{id, lastSeq}]}, the requests it still holds for that client. The client then sends resume {id, after} for each it awaits, and the daemon replays from after + 1 and continues live. A request the daemon no longer knows (a new daemon, the kept window passed) answers EGONE.

A request across a drop. exec and spawn events carry seq, from 1 per request, and the daemon keeps a ring per running request. When a client’s connection ends, that client’s running requests are NOT killed; they run on, buffering. Invariant, pinned by a concurrency test: a command’s output across a reconnect arrives once and in order, with no byte duplicated or lost, and a gap {bytes} frame where the ring overflowed.

Who reconnects, and who owns what. connection.ts splits into a framed channel per ssh child (today’s Connection, now with no pending of its own) and a Link that owns successive channels and holds the pending calls and open streams across them. Connection’s public surface for callers (`request, stream, onLost, close) is unchanged, served by the Link. ssh-workspace.ts’s lazy `connection() is unchanged too: a call after a drop reconnects, as today. What is new: a Link with in-flight work (a running exec, an open spawn, a ports watch) reconnects on its own when its channel drops, RECONNECT_ATTEMPTS times, and resumes; one with nothing in flight waits for the next call, as today. On reconnect, idempotent reads sent before the loss with no reply (stat, lstat, readFile, readCapped, readdir, realpath, glob) are re-sent; a writeFile, mkdir, rm or rename in that window is unknown, since the daemon may or may not have run it, and fails closed with ECONNRESET as today, which pi’s write tool and the commit guard report. remoteMonitorProcess (monitor-process.ts:223-252) needs no change: it awaits proc.exited, and a pause is not an exit. /ssh status shows daemon <session>, up <t>, <n> running.

Who kills what. Today a lost connection ends every child (helper.mjs:270-279). In 5c that is the idle timeout’s job and cancel’s: `session_shutdown sends cancel for every running request first, so a normal exit still ends what it started, and a client gone for good leaves its requests to finish or to the idle timeout. Monitors (phase 4) are spawn`s, so a dropped link no longer ends one: it pauses and resumes with the link. That changes phase 4’s fail mode ("a link that drops under a monitor ends it"); `ssh.adoc and modes.adoc say so, and the phase 4 test for it becomes the resume case.

Protocol version. PROTOCOL_VERSION becomes 2. A version-1 helper on a host is never spoken to: the hash names the file, so a new client uploads and starts its own daemon.

Fail modes

Each named with its class: closed (nothing happens, the caller is told), open (the feature degrades, the caller is told), loud (always).

  • 5a: a drive path the model named (C:..., neither anchor nor UNC base): closed, loud; ENOENT naming it with the Windows-path sentence. Never mapped to the remote.

  • 5a: the local home is the anchor’s prefix (it is: ~/.pi/agent/remotes/…​): the anchor rule runs before any other; an anchor path is never read as a local one. Pinned.

  • 5b: ssh exits at once (port in use, auth): closed, loud; the command reports ssh’s last stderr line and lists nothing as live.

  • 5b: the forward never becomes ready and ssh does not exit: closed, loud; after CONNECT_TIMEOUT_S the child is killed and the command says so.

  • 5b: no ss and no /proc (not Linux): open, loud once; the watch reports unsupported and stops; /ssh forward still works.

  • 5b: an auto-forward’s local port is taken: open, loud; notified with the hint /ssh forward 3000:3001, not forwarded.

  • 5c: the daemon cannot start (no setsid, $HOME not writable, the socket refused): open, loud; the bootstrap falls back to today’s shape, helper on the connection’s stdio, hello.daemon: false, and /ssh status says the link is not resilient.

  • 5c: a resume for a request the daemon lost: closed, loud; EGONE, the call fails with "the command’s output was lost with the connection". Nothing is re-run on its own.

  • 5c: the ring overflows during a long drop: open, loud; a gap frame, shown in bash’s output as `[… N bytes lost while the link was down]; the exit code is still the real one.

  • 5c: the reconnect attempts run out: closed, loud; every in-flight call fails as today, and the next call starts afresh.

  • 5c: two pi sessions on one remote: each client’s requests are held apart by its id; a second client never sees the first’s buffers. Pinned.

Limitations

  • 5a: a remote path spelled /c/x or /mnt/c/x on a Windows client is rewritten by pi to a drive path before pi-ssh sees it (paths.js:50-58), and is refused as one. Spell it relative, or under the anchor.

  • 5b: forwards are TCP, local-to-remote only; no -R, no UDP, no Unix sockets. Each forward is its own ssh authentication.

  • 5c: a write sent in the instant of a drop is unknown and fails; the caller re-reads before retrying. Interactive programs still do not work.

  • 5c: the daemon idles out ten minutes after its last client leaves; a command still running then is killed. (pi running is a client: a monitor is kept by it.)

  • Per-operation costs: this box cannot ssh to itself, so 5c’s MR measures the protocol’s cost over the pipe transport (each operation, and a resume) and puts the table in ssh.adoc; LAN and WAN figures over real ssh come from the operator’s live sessions in phase 6, which the meta plan’s phase 5 row placed here. A meta-plan erratum says so.

Scope

  • packages/pi-ssh/: ops.ts (hostPath), extension.ts (the UNC base on win32), forwards.ts and config.ts (new), commands.ts, helper.mjs (daemon, relay, ports, seq, resume, attach, idle exit, SSH_CONNECTION), connection.ts (channel and Link), ssh-workspace.ts (exited across a resume), protocol.ts (version 2, the new frames), diag.ts, prompt.ts (forwards in the <gadhs-ssh> block), test/transports.ts.

  • packages/pi-modes/: monitor-process.ts doc comment; the phase 4 drop test becomes the resume case. Nothing else.

  • Tests, by unit and category:

    • 5a, regression (#501): hostPath over the table’s forms, computed with path.win32; the parity block for read/write/edit/ls on win32 over the pipe transport; the anchor-before-device order. Property: for any relative path of safe segments p, hostPath(win32.resolve(base, p)) equals posix.resolve(root, p).

    • 5b: Forwards with a fake spawner (ready by connect, exit before ready with the stderr line, the timeout, unforward, exit while listed); the watch against a fixture ss output and a fixture /proc/net/tcp; the below-1024 and sshd-port rules, and "already forwarded is ignored"; config: a valid file, an absent file, each invalid shape refused by name, and a repository .pi/pi-ssh.json ignored. Integration: a forward through a stand-in ssh (a child that listens on <local> and proxies to a listener the test opened, as test/bootstrap.test.ts:84 stands in for ssh) reaches the listener; pi-win skips it.

    • 5c, contract (wire): test/protocol.test.ts round-trips every new frame (hello v2, attach, attached, resume, seq on events, gap, ports, EGONE) and refuses version 1. Concurrency: a client that drops mid-exec at a random point, reconnects, and receives the rest once and in order, 50 runs; gap on overflow; EGONE past the kept window; the idle exit with and without a running request; two clients apart; the no-daemon fallback; cancel at shutdown; the idempotent re-send list, and a writeFile in the window failing closed. All over Unix sockets on this machine, no ssh. The workspace contract suite passes against the daemon shape, and pi-workflow’s GADHS_PI_WORKFLOW_TEST_WS=ssh run does too.

  • Mutation check per unit, each killed before its MR: 5a’s anchor-before-device order and the drive-path refusal; 5b’s below-1024 rule, the sshd-port rule, the port-in-use refusal and the readiness timeout; 5c’s after + 1 replay, the gap on overflow, the idempotent-only re-send list, and the idle timer’s "no running request" condition.

  • Docs: ssh.adoc (the Windows client; ports; the resilient link and the changed monitor fail mode; the cost table over the pipe transport; the limitations above), modes.adoc (the monitor’s drop behaviour), an ADR-006 amendment (daemon and relay; the UNC base on a Windows client), CHANGELOG.adoc (Added: forwards, the resilient link; Fixed: #501), the meta-plan erratum on measured costs.

  • Delivery: three MRs in order; Closes #501 on the first, Closes #493 on the third; each merge SHA on #488. Then phase 6 (#494): the cookbook, the LAN and WAN figures from the operator’s sessions, and the release the operator tests.

Out

A Windows remote host. Reverse and dynamic forwards. mosh or ET. Re-running a non-idempotent call after a drop. Agent forwarding. More than one daemon per helper hash per user. pi-remote’s phone link, which is its own program.

Named but not supplied to the cold reviewer (the review budget is twelve files): pi’s dist/utils/paths.js and dist/core/tools/{write,read,path-utils}.js (installed under ~/.local/share/pi-node), packages/pi-ssh/{prompt,diag,session,anchor}.ts, packages/pi-ssh/test/{bootstrap,protocol}.test.ts, packages/pi-modes/monitor-process.ts, docs/modules/ROOT/pages/{ssh,modes}.adoc, CHANGELOG.adoc.

Erratum (2026-10-27): 5a’s UNC share is a hash of the anchor path, not `anchorFor’s hash, so a helper’s worktree view (whose anchor is not `anchorFor’s) has its own share too.

Erratum (2026-10-27): 5a also maps a switched tool’s result text and error messages to host paths (inHostTerms, resultInHostTerms, errorInHostTerms), since ls names its resolved path in errors. On a POSIX client these return the very objects they were given.

Erratum (2026-10-27): 5a’s mutation check finds two mutants equivalent on a POSIX test host. The anchor-before-device order is equivalent anywhere: an anchor is a drive path and the device a //pi-ssh/ path, so no path is under both. toolBase in switched returns the root on a POSIX client. That second mutant is killed only on a Windows client, by the read/write/edit/ls parity block whose skip 5a lifts, which pi-win runs.

Erratum (2026-10-27): the pipe transport in the tests starts the helper in the temp directory, so a Windows client’s drive-less stand-in remote root resolves on the temp directory’s drive.

Erratum (2026-10-27): pi-ssh’s operations factories (readOps, writeOps, editOps, lsOps, bashOps) take the client platform, defaulting to process.platform, so the tests drive a Windows client’s paths without changing anything global. A first version spoofed process.platform in one test file. That leaked into the parity run, whose tools then wrote under a UNC-named directory inside the package; validate caught it.

Erratum (2026-10-27): 5b’s port watch takes the first listing of each connection as a baseline: ports already listening when the session connects are not news, and are not named or forwarded. Only ports that start listening after it are. This keeps a host’s standing services (a database, sshd) from flooding each session start.

Erratum (2026-10-27): 5b’s watch is the SSH workspace’s watchPorts, re-armed through a new onConnect listener on each connection the workspace makes, so a reconnect restarts it with a fresh baseline. The helper’s ports operation takes stand-in sources (ss, /proc/net, /proc) for the tests.

Erratum (2026-10-27): 5b’s /ssh forward also refuses a local port that already accepts connections before ssh starts. ssh’s own bind failure (ExitOnForwardFailure) still covers the race between that check and ssh’s bind.

Erratum (2026-10-27): with an invalid pi-ssh.json, pi-ssh still registers its tools, so a session in an anchor refuses them rather than acting on the anchor’s files. Its session start says what is wrong, and /ssh refuses to open or reconnect. A remote command line in a port notice has its control characters replaced before it is shown.

Erratum (2026-10-27): 5c’s daemon start lives in the helper, not the shell. The bootstrap stays one line, exec node helper --connect <socket>. The helper tries the socket, starts the daemon with Node’s detached (a new session, as setsid makes) behind a mkdir lock taken over when stale, waits for it, then relays, and serves on stdio when no daemon can be had. The socket’s name carries 16 hex characters of the helper’s hash, because a Unix socket path is limited to about 104 bytes.

Erratum (2026-10-27): 5c’s idle rule. With no client attached and nothing held, the daemon ends at once, so a closed session leaves no process behind. With requests still running or kept, it waits DAEMON_IDLE_MS, then kills them and ends. The "no running request" mutant therefore became the "holds nothing" condition. At the end of a session, a bye replaces a cancel per request: the daemon cancels and forgets everything that client started.

Erratum (2026-10-27): 5c also needs two ordering rules the plan did not name, both found by the 50-drop concurrency test. First, after an attach, a held stream sends nothing new until the client resumes it, or live events overtook the replay and were deduplicated away. Second, a stream start the same daemon does not hold never reached it (the daemon holds every stream it received until it is finished and its kept window passes), so the link sends it again. From a restarted daemon (another session) it is EGONE. The daemon also ignores its connections' read errors (ECONNRESET from a relay that died), which had ended it.

Erratum (2026-10-27): 5c’s /ssh status names whether the link is resilient and the daemon’s session, not its uptime or a running count, which the protocol does not carry. The daemon’s bounds are overridable by GADHS_PI_SSH_* variables for the tests. pi-workflow’s SSH run reaches the daemon through --connect on a socket in a temp directory, so the real home holds no socket.

Erratum (2026-10-27): the cost table in ssh.adoc is pi’s own overhead per operation through the helper (stdio and through the daemon), plus a drop’s cost, measured on one machine through the test transport. LAN and WAN figures over real ssh come from the operator’s sessions with the release.

Edit this page · latest