Plan: Remote execution phase 2a — the helper, the protocol, the SSH workspace

Closes: #496 (phase 2a). #490 stays for phase 2b. Relates to: #488 (meta plan: plans/remote-execution.adoc), #489. Branch: feat/pi-ssh-workspace. Status: Done (2026-10-26) — implemented as planned, with the errata below

Design

What this phase is for

Phase 1 gave every later phase one interface, Workspace (packages/pi-workspace/types.ts), and a suite that defines its semantics (packages/pi-workspace/contract.ts). This phase builds the implementation that acts on another host, and proves it with that suite: the same cases, run against a helper on the far side of a pipe. Everything the tools, guards and containment checks will do remotely in phases 2b to 4 reduces to this one object working.

It is split from the tools (2b) because it is fully testable without ssh, and because its two hard-to-reverse parts, the wire protocol and the connection lifecycle, deserve a review of their own.

Erratum to the meta plan: Node 22, not 20

The helper’s glob is fs.promises.glob, Node 22 and later; Node 20 has been end-of-life since April 2026. The remote needs Node 22 or later. Recorded on #490; this phase adds the meta plan’s first Erratum (date): … line (it has none yet) and an amendment section to ADR-006, whose Decision and Consequences say "Node 20" twice, also noting the helper as a JavaScript copy of the local implementation (below).

The package: @gadhs/pi-ssh

packages/pi-ssh/, the extension package ADR-006 names. This phase ships its library half: helper.mjs (+ helper.d.mts), protocol.ts, connection.ts, ssh-workspace.ts, index.ts. No default-export extension and no @gadhs/pi loader yet (2b adds both), so distribution.test.ts’s loader-per-dependency rule is untouched. It depends on `@gadhs/pi-workspace (workspace:*) for the interface and the contract suite; nothing else. files ship the .ts, helper.mjs and helper.d.mts, as pi-vertex ships its .mjs.

The helper: helper.mjs

One plain-JavaScript ES module, no imports but node: built-ins, so it runs under the remote’s own node with no install step. It is the remote half of localWorkspace (packages/pi-workspace/local.ts): the same operations, the same semantics (stat undefined on ENOENT, realpath undefined on ENOENT and ENOTDIR, readCapped never truncated, env additive, exec with the per-stream byte cap and the SIGTERM-then-SIGKILL timeout, spawn detached into its own group), written once more in JS because an uploadable file cannot import the TypeScript. ADR-004 prefers copies held equal by test only for constants, and a library for logic; here the library cannot reach the remote, so the copy is the design, and the contract suite, the strongest equality test the repository has, is what holds the two equal. ADR-006’s amendment (above) records that. helper.d.mts types its one export for the tests that import it.

On start it writes one hello line and then serves requests until stdin ends. When stdin ends or it receives SIGHUP (the ssh session gone), it kills every process group it spawned and exits: in this phase nothing on the remote outlives the connection (phase 5 changes that deliberately).

The protocol: protocol.ts

Newline-delimited JSON, one object per line, both ways. protocol.ts holds the TypeScript types, the encoder and the frame parser the client uses; the helper mirrors them in JS. Binary travels as base64. Each request carries a client-chosen id.

Frame Shape

hello (helper → client, once)

{ hello: { protocol: 1, helper: "<sha256 of helper.mjs>", node: "v22.x", platform, home } }

request

{ id, op, args } with op one of readFile, readCapped, writeFile, mkdir, stat, lstat, realpath, readdir, rm, rename, glob, exec, spawn, kill, cancel; args is the method’s arguments, paths absolute on the remote, bytes base64

reply

{ id, ok: true, result } or { id, ok: false, code, message } (code is the host’s, as WorkspaceError.code)

stream (exec, spawn)

{ id, ev: "started", pid }, then { id, ev: "stdout" | "stderr", data: "<base64>" } as output arrives, then { id, ev: "exit", code, signal, timedOut, truncated }; for exec the exit event is also the reply

cancel

{ id, op: "cancel", args: { id: <the exec’s id> } } ends an exec as its signal would; { op: "kill", args: { pid, signal } } signals a `spawn’s group

Decisions: one frame per line because it is trivial to debug with /diag and cat, and the volume (a few KB per operation, a 3 MiB file as 4 MiB of base64 in one line) is within what JSON.parse handles in milliseconds. exec’s `stdin is sent whole in the request (the interface takes a whole buffer). A request’s args never include an environment beyond env additions. The hello carries the helper’s own hash so the client can tell a stale helper from the one it shipped.

The connection: connection.ts

connect(target, options) returns a Connection with request(op, args), stream(op, args, onEvent), close(), and onLost(cb). It owns one child process whose stdin and stdout carry the protocol; the child is ssh for a remote, and anything that speaks the protocol for tests (options.transport, default: the ssh spawn).

Diagnostics go through options.log(event, details), a callback that defaults to a no-op: this half of the package is a library and takes no dependency on pi-modes; phase 2b’s extension passes pi-modes' debugLog (@gadhs/pi-modes/diagnostics, as pi-remote imports it). The tests pass a recording callback.

One connection, one shell line. The client spawns ssh -o BatchMode=yes -o ConnectTimeout=15 <target> sh -c '<bootstrap>', writes the helper’s bytes to its stdin first, then the protocol. The bootstrap is:

f="$HOME/.pi-ssh/helper-<hash>.mjs"
if [ -f "$f" ]; then head -c <bytes> >/dev/null
else mkdir -p "$HOME/.pi-ssh" && head -c <bytes> >"$f.$$" && mv "$f.$$" "$f"; fi
exec <node> "$f"

head -c takes exactly the helper’s bytes off stdin whether or not the file exists, so the client never needs to know, and the protocol follows on the same stream. The file is named by its hash: a new pi-ssh uploads a new file, old ones are harmless, and two sessions cannot half-write one another’s. <node> is node from the remote’s non-interactive PATH, or options.nodePath. Cost: about 20 KB of upload per connect, and one authentication per session, with no ControlMaster needed, so a Windows client works.

Refusals, each with its reason in a WorkspaceError: ssh exits before any frame (auth failed, host key unknown, no route): ECONNREFUSED with ssh’s stderr, and for the host-key case the hint "run ssh <target> once to accept the host key"; the bootstrap exits 127: ENOENT "node is not on the remote’s PATH; set nodePath`"; `hello.protocol differs: EPROTO naming both versions; hello.helper differs from the shipped hash: EPROTO "stale helper" (it cannot happen through the bootstrap, since the file is named by hash; it means someone edited it); the remote’s Node below 22: EPROTO naming the version.

Lost mid-session. When the child exits, every pending request rejects with ECONNRESET, every open stream gets a synthetic exit with code: null, signal: "SIGHUP", and onLost fires. The connection does not reconnect by itself: the SSH workspace (below) does, once per failed call, so a caller sees one error and the next call a fresh connection, or the reason it could not be made. Diagnostics: ssh.connected (target, node, helper uploaded or found, ms), ssh.lost (ssh’s exit code and last stderr line), ssh.reconnected.

The SSH workspace: ssh-workspace.ts

sshWorkspace({ target, root, anchor, connect }) implements Workspace over a Connection:

  • label is user@host:/path, isRemote true, root the remote path, anchor the local directory pi runs in (phase 2b supplies it; tests pass a scratch one).

  • resolve(p): absolute under anchor maps under root; absolute otherwise passes; relative resolves against root; all with node:path/posix, since the remote is POSIX.

  • Every file method is one request; results that carry bytes are decoded. Errors come back as WorkspaceError(code, message, path).

  • exec is a stream: chunks are forwarded to onStdout/onStderr as they arrive, collected for the result, and the exit event completes it. signal sends cancel; timeoutMs and maxBytes go in the request, since the helper enforces them where the process is.

  • The environment the helper gets for a command is its own login environment, plus the caller’s env, plus an allowlist the workspace adds from the local environment: TERM, LANG, LC_*, COLUMNS. Nothing else local ever crosses: ExecOptions.env is additions only (phase 1), and the workspace sends only those. A contract case pins it (below).

  • spawn is a stream too: the started event gives the pid and resolves the Process; output events feed the callbacks; exit resolves exited; kill sends kill.

  • Lazy connection: the first call connects; a call that finds the connection lost reconnects once and retries that one call only if it had not started (a request that was never written), otherwise it fails with ECONNRESET and the next call reconnects.

Fail modes

  • Connection cannot be made (auth, host key, no node, old node, old protocol): the call fails closed with the reason; nothing falls back to the local filesystem. The SSH workspace never silently becomes a local one.

  • Connection lost mid-call: fail-closed, loud: ECONNRESET on the call, synthetic exit on streams, ssh.lost recorded; the next call reconnects. A spawn’s process is dead with the helper (it kills its groups on `SIGHUP), so a monitor over SSH in phase 4 restarts rather than resumes (phase 5 changes that).

  • A malformed frame from the helper (a truncated line, not JSON): the connection is closed as lost, with the line’s first 200 characters in the diagnostics record, never fed to a caller (fail-closed).

  • A request too large for one line (a write of hundreds of MB): it is sent and parsed, slowly, and completes; no limit is imposed in this phase (silent: slow, not wrong). A later phase chunks writes if a caller needs it.

  • The remote fills $HOME/.pi-ssh with helpers: one file per pi-ssh version, about 20 KB each (silent, bounded by releases). Documented.

  • Two pi sessions on one remote: each has its own ssh child and helper process; files are shared through the filesystem as two local sessions share them (silent, by design, the same as today). Two first connects at once each write helper-<hash>.mjs.$$ and mv it into place: both end with a whole file, pinned by a test.

  • The workspace never becomes local: every path through sshWorkspace fails closed on a connection it cannot make or has lost; pinned by a test at the workspace level, not only the connection’s.

Scope

In

  • This plan, committed as docs/modules/ROOT/pages/plans/remote-2a-ssh-workspace.adoc with its nav entry, In progress at the start.

  • packages/pi-ssh/: package.json (@gadhs/pi-ssh 0.1.0, dependency @gadhs/pi-workspace, files with helper.mjs and helper.d.mts, engines as the others), tsconfig.json, vitest.config.ts (threshold at the measured level), README.md, LICENSE, helper.mjs, helper.d.mts, protocol.ts, connection.ts, ssh-workspace.ts, index.ts. index.ts exports sshWorkspace, connect, the Connection, ConnectOptions, SshTarget and Transport types, PROTOCOL_VERSION, helperSource() (the bytes and hash of the shipped helper) and the frame types from protocol.ts.

  • Tests, by category:

    • Contract: test/ssh-workspace.contract.test.ts runs phase 1’s workspaceContract unchanged against sshWorkspace over a transport that spawns node helper.mjs directly (pipes, no ssh), with a scratch root; and once more over a real ssh localhost when ssh -o BatchMode=yes localhost true succeeds on the box, skipped visibly otherwise (it does not succeed on this box today).

    • Security (contract): exec on the helper reaches it with none of the local environment but the allowlist: with GADHS_LEAK=1 and GITLAB_TOKEN=x stubbed locally, env on the remote shows neither; TERM crosses.

    • Wire-format (contract + property): every request and reply shape in the table round-trips through the encoder and parser; the parser handles a frame split across chunks and two frames in one chunk; fast-check over arbitrary strings and bytes in args round-trips.

    • Unit, the bootstrap: run locally with sh -c '<bootstrap>' and HOME a scratch directory: a missing helper is written and started; a present one is left as is and the bytes are drained; a mismatching hash on disk is never used (the name carries the hash); two bootstraps at once against a missing helper both end with a whole, identical file (concurrency).

    • Unit, the connection: a fake transport scripts the failures: no hello then exit (ECONNREFUSED with stderr), exit 127 (ENOENT with the hint), wrong protocol, wrong helper hash, old node, a malformed line (the connection closes as lost, the pending request rejects ECONNRESET with no result ever delivered, and log received ssh.lost with the line’s first 200 characters), loss mid-request (ECONNRESET, synthetic exit, onLost), and reconnect-once on the next call.

    • Unit, the workspace fails closed: sshWorkspace over a transport that cannot connect: stat, readFile and exec each reject with the connection’s WorkspaceError; none answers from the local filesystem.

    • Unit, the helper’s cleanup: a spawned sleep dies when the helper’s stdin closes.

    • Mutation check: the head -c drain branch, the hash in the file name, the protocol-version check, the env allowlist, ECONNRESET on loss, the reconnect-once rule, the helper’s group kill on SIGHUP; each killed before the MR.

  • Docs: the meta plan’s Erratum line (Node 22), its status unchanged; ADR-006’s amendment section (Node 22; the helper as a JS copy held equal by the contract suite); the package README; a row in packages.adoc’s table; `CHANGELOG.adoc == Unreleased === Added, one entry (Unreleased is empty today).

  • Named but not supplied to the cold reviewer: CHANGELOG.adoc, docs/modules/ROOT/pages/adrs/adr-004-package-boundaries.adoc (cited for its amendment on copies and libraries), docs/modules/ROOT/nav.adoc, packages/pi-modes/diagnostics.ts (the debugLog 2b will pass).

  • Delivery: one MR, Closes #496, Relates to #490 and #488; the merge SHA on #488 and #490; 2b’s plan next.

Out

  • Any tool replacement, user_bash, /ssh, the anchor directory’s creation, the AGENTS.md mirror, the loader, the system prompt (2b). Port forwarding, daemonised helper, reconnect of a running command (phase 5). A Windows remote. Chunked transfer of very large files. ControlMaster.

Erratum (2026-10-26): the helper is strict about its input. A request line that is not a frame means the stream is corrupt, so the helper writes malformed request: <excerpt> to stderr, kills what it started, and exits 2, and the client records the loss with those words. The mutation check found the need: a lenient helper that skipped such lines let a bootstrap that never drained the helper’s bytes pass unnoticed.

Erratum (2026-10-26): exec’s exit event carries `truncated, as the protocol table says, because output past the cap is dropped on the helper when no callback streams it and the client cannot see that. There is no separate ssh.reconnected record: every connect writes ssh.connected, so a reconnect shows as one following an ssh.lost. Whether the helper was uploaded or found is the bootstrap’s decision on the remote and is not reported. A deliberate close() records ssh.closed, not ssh.lost.

Erratum (2026-10-26): one test beyond the plan exercises the default sshTransport end to end. A stand-in ssh on PATH asserts the batch-mode and connect-timeout options and hands the remote command to sh, as the remote login shell would. It covers the quoting of the bootstrap, which no other test reaches without real ssh.

Edit this page · latest