Agent status over WSL: guest-resident hook relay + WSL-side hook installers (STA-1515) (#7903)

* docs: full design + context for agent status over WSL (STA-1515)

Why hooks don't work on Windows+WSL (loopback transport gap + WSL-side
installation gap), per-client transport map, the OMP-only fixes that
shipped (7642/7641) and why they don't generalize, the recommended
guest-resident relay over wsl.exe stdio mirroring the SSH relay plus
WSL-side hook installers, alternatives considered, validation facts and
gotchas from the 2026-07-08 Windows rig run, and acceptance criteria.

Co-authored-by: Orca <help@stably.ai>

* feat(agent-hooks): agent status over WSL — guest relay + WSL-side hook installers (STA-1515)

Agent hooks have never worked from inside WSL: under default NAT
networking, WSL's 127.0.0.1 is its own loopback, so every hook POST to
the Windows listener dies silently, and hook configs were only ever
written to the Windows home where WSL agents never see them.

Transport: a hooks-only guest relay (src/relay/wsl-agent-hook-relay.ts)
runs inside the distro, binds WSL loopback on the very port the clients
were already given (host-issued token; EADDRINUSE falls back to :0 with
endpoint-file re-coordination, which also covers mirrored networking),
and forwards parsed envelopes over its own wsl.exe stdio into
agentHookServer.ingestRemote — the same shape as the SSH relay. It exits
when stdin closes so a freed Windows port can never be forwarded into a
dead guest listener.

Installation: the unchanged SSH remote hook installers run against an
SFTP-shaped adapter whose primitives are home-scoped fs RPCs served by
the relay, so all 14 managed agents' hooks land in the WSL home over the
already-open channel with zero per-file wsl.exe spawns.

Lifecycle: per-distro manager ensured from buildPtyHostEnv on every WSL
PTY spawn (covers post-restart daemon reattach re-spawns), stale-bundle
reinstall via exit 42, no-node-43 cooldown, bounded retry for wsl.exe
'Catastrophic failure (E_UNEXPECTED)', breadcrumbed failures.

Zero per-client transport changes; listener stays Windows-loopback-only.

Co-authored-by: Orca <help@stably.ai>

* fix(agent-hooks): WSL relay link-death recovery + Codex runtime-home hook install (STA-1515)

Follow-ups from the first Windows-rig validation of PR #7903:

Link death: a mux protocol error or keepalive timeout could kill the
host<->guest link while the guest relay stayed alive returning 204s —
the manager stayed 'running' and every later envelope blackholed
silently (the exact observed signature: Claude hooks POST 204, store
never populates). wsl-hook-relay-link.ts now guarantees exactly-once
death handling from either signal (mux dispose OR child exit); the
manager breadcrumbs it, kills the child, and self-restarts after a
short cooldown since a live agent session produces no new PTY spawns
to re-trigger ensure. ORCA_WSL_HOOK_RELAY_DEBUG=1 traces each received
envelope pre-ingest. A live integration test pins the full host chain:
the real esbuild bundle over real child stdio through the real manager
into a real AgentHookServer.ingestRemote, exact Claude POST shape.

Codex: Orca launches WSL Codex with CODEX_HOME redirected to the
managed runtime home (~/.local/share/orca/codex-runtime-home/home), so
hooks installed to ~/.codex were never read. installRemote now accepts
an explicit codex home (flat layout), threaded from the relay manager;
the config.toml trust write is deferred while the file doesn't exist
(the launch path seeds it only-if-absent — creating it first would
cancel the seed), and the manager re-runs the byte-equality-idempotent
installers on later ensures (30s throttle) to upsert trust once the
seed lands.

Also: WSL test suites now run on Windows dev hosts (fs-backed suites
skip with rig coverage noted; manager suite uses a fixed POSIX home).

Co-authored-by: Orca <help@stably.ai>

* fix(agent-hooks): renderer ownership gate treats wsl:* connection ids as local (STA-1515)

Round-2 rig finding: with the link fixed, WSL hook envelopes reached
ingestRemote and the durable cache, but useIpcEvents.applyAgentStatus
drops any status whose stamped connectionId differs from the owning
repo's — 'wsl:<distro>' !== null for a local repo, so every WSL-relayed
status died before setAgentStatus and notifications.

wsl:* ids are transport provenance, not ownership: the gate now
normalizes them to local via isWslHookRelayConnectionId (shared
contract, also used by the relay link when stamping), while still
rejecting WSL-stamped events against SSH-owned repos. Provenance stays
stamped — it is what made this drop diagnosable.

Co-authored-by: Orca <help@stably.ai>

* fix(agent-hooks): adversarial-review hardening for the WSL hook relay (STA-1515)

Four independent review lenses over the branch; all confirmed findings
fixed before the next rig round:

Endpoint identity (4/4 reviewers): the guest endpoint dir was keyed by
the EPHEMERAL Windows hook port, so a daemon-surviving agent kept
sourcing the dead port-P1 file after an Orca restart — breaking the
restart-resume acceptance criterion and regressing shipped OMP
recovery. Now keyed by a restart-stable instance key (hash of the
Windows endpoint file path, crossed via ORCA_WSL_HOOK_INSTANCE): the
restarted instance's relay rewrites the SAME file, which is exactly
what re-coordinates survivors.

Restart policy: every failure arms the restart timer (one failed
relaunch no longer ends self-recovery), and the timer probes
wsl --list --running first — wsl -d BOOTS a stopped distro, so
recovery must never resurrect a VM the user shut down; stopped-distro
state is dropped instead. Failure counters reset only after 2min of
stable uptime, so connect-then-die loops escalate to the 10-min cap
instead of cycling every 10s. Timer policy extracted to
wsl-hook-relay-recovery.ts with direct tests.

Also: version-namespaced guest install dir (dev+prod instances no
longer reinstall over each other; PID-suffixed tmp files), 30s install
timeout (a wedged wsl.exe could pin the state machine at 'starting'
forever), per-candidate node version probing (apt node 12 on PATH no
longer masks nvm node 20 into a false no-node cooldown), WSL_UTF8=1 +
NUL-stripped stderr (catastrophic-failure matcher survives UTF-16LE),
ordered post-sentinel chunk handoff, port-fallback breadcrumb via the
home handshake, bad home reply now fails the connect, missing-bundle
warn-once, case-normalized distro keys, disposeAll wired to will-quit,
one-shot 60s reinstall timer for single-spawn Codex trust catch-up,
escaped + contract-derived spawn command.

Co-authored-by: Orca <help@stably.ai>

* docs: record round-3 rig validation status for agent status over WSL (STA-1515)

Co-authored-by: Orca <help@stably.ai>

* fix(agent-hooks): round-4 adversarial-review fixes for the WSL hook relay (STA-1515)

- dropState identity race: recovery re-checks state identity after the
  distro-running probe await, and the manager's dropState only deletes the
  exact state it was armed for — an ensure() landing mid-probe can no longer
  have its fresh relay orphaned outside the map.
- Distro-running probe fails CLOSED: a probe error no longer reports
  'running', so recovery can never wsl-d-boot a distro the user shut down.
- Relay spawns use --exec: bypasses the distro's default login shell
  (fish/nushell chsh) and passes argv verbatim, dropping the $-escape shim;
  same form as the Codex WSL login spawn.
- Post-sentinel chunk handoff rides a microtask so an envelope in the
  trailing bytes can no longer dispatch before the link's notification
  handler is registered.
- Guest relay mirrors the SSH relay's uncaughtException/unhandledRejection
  posture.
- Replay cache capped at 256 panes with recency eviction (the WSL relay has
  no per-pane teardown signal); meta map kept in lockstep.
- Launch script derives the stale-exit code from the shared contract
  constant; one-shot reinstall timer refuses to arm after dispose.
- New oracles: sentinel unit suite, fs-bridge scoping suite, fixed-token
  403/204, EADDRINUSE endpoint-file rewrite, cache-cap eviction, and the
  recovery/manager race regressions (verified to fail with fixes reverted).
- Doc: round-4 review section + revised curl.exe stance (kept as the
  no-node fallback — Codex is a native binary; fresh distros ship no node).

* docs: record round-4 pinned rig validation for agent status over WSL (STA-1515)

---------

Co-authored-by: Orca <help@stably.ai>
Co-authored-by: Brennan Benson <brennanbenson@Brennans-MacBook-Pro.local>
This commit is contained in:
Brennan Benson
2026-07-10 00:19:45 -07:00
committed by GitHub
co-authored by Orca Brennan Benson
parent 1383ba85cf
commit f238952be2
31 changed files with 3600 additions and 25 deletions
+88
View File
@@ -0,0 +1,88 @@
// Shared contract between the Windows host and the guest-resident WSL
// agent-hook relay. Both sides derive paths/methods from here so the guest
// process and the host manager can never drift on where the relay lives,
// which JSON-RPC methods the fs bridge speaks, or which exit codes signal
// "reinstall me" vs "no usable node".
// See docs/agent-status-over-wsl.md (STA-1515).
/** Guest-side install dir for the relay bundle, relative to `$HOME`. */
export const WSL_HOOK_RELAY_DIR = '.orca-wsl/hook-relay'
export const WSL_HOOK_RELAY_BUNDLE_NAME = 'wsl-agent-hook-relay.js'
export const WSL_HOOK_RELAY_VERSION_FILE = '.version'
/** Host-expected bundle version, crossed into the guest launch script via
* WSLENV so a stale guest install is detected by the guest itself. Also
* namespaces the guest install dir, so concurrent Orca instances with
* different bundle versions (dev + prod) never reinstall over each other. */
export const WSL_HOOK_RELAY_VERSION_ENV = 'ORCA_WSL_HOOK_RELAY_VERSION'
/** Stable per-instance identity for the guest endpoint dir, crossed via
* WSLENV. Derived from the Windows endpoint file path (userData +
* namespace), NOT the hook port: the port changes every app launch, and a
* port-keyed dir would leave daemon-surviving agents sourcing a stale file
* after an Orca restart — the exact re-coordination this exists to serve. */
export const WSL_HOOK_RELAY_INSTANCE_ENV = 'ORCA_WSL_HOOK_INSTANCE'
/** Launch-script exit codes. 42 mirrors the SSH relay's handshake-mismatch
* convention: the host reinstalls the bundle and relaunches once. */
export const WSL_HOOK_RELAY_STALE_EXIT_CODE = 42
export const WSL_HOOK_RELAY_NO_NODE_EXIT_CODE = 43
/** JSON-RPC methods for the relay's home-scoped fs bridge. The host runs the
* unchanged SSH remote hook installers against these via an SFTP-shaped
* adapter, so hook installation rides the already-open stdio channel instead
* of per-file wsl.exe spawns. */
export const WSL_HOOK_FS_METHODS = {
home: 'wslfs.home',
readFile: 'wslfs.readFile',
writeFile: 'wslfs.writeFile',
stat: 'wslfs.stat',
rename: 'wslfs.rename',
unlink: 'wslfs.unlink',
chmod: 'wslfs.chmod',
readdir: 'wslfs.readdir',
mkdir: 'wslfs.mkdir'
} as const
/** Result envelope for every fs-bridge method. Errors travel as data (not
* JSON-RPC faults) so the host adapter can map POSIX errno onto the ssh2
* status codes the shared installer error-classifiers already understand. */
export type WslFsFailure = { ok: false; errno: string; message: string }
export type WslFsResult<T extends object = object> = ({ ok: true } & T) | WslFsFailure
/** Where the guest relay publishes its endpoint file. Keyed by the stable
* instance key (restart-stable, instance-unique), so a restarted instance's
* relay REWRITES the same file that surviving agents' env already names —
* that rewrite is what re-coordinates them onto fresh port/token. */
export function wslHookRelayEndpointDir(guestHome: string, instanceKey: string): string {
const home = guestHome.endsWith('/') ? guestHome.slice(0, -1) : guestHome
return `${home}/.orca-wsl/agent-hooks/instance-${instanceKey}`
}
/** Keep instance keys shell/path-inert on both sides of the boundary. */
export function sanitizeWslHookInstanceKey(value: string | undefined): string | null {
const trimmed = value?.trim().toLowerCase() ?? ''
return /^[a-z0-9][a-z0-9-]{0,63}$/.test(trimmed) ? trimmed : null
}
/** The guest is always POSIX, so the Windows host must name the guest's
* endpoint file explicitly — its own `getEndpointFileName()` would say
* `endpoint.cmd`. Matches the POSIX branch of that helper. */
export const WSL_HOOK_RELAY_ENDPOINT_FILE = 'endpoint.env'
/** connectionId stamped on WSL-relayed hook envelopes. Transport provenance
* only: the pane is a LOCAL pane on a local repo, so ownership checks must
* treat these ids as local (null), not as a remote connection. */
export const WSL_HOOK_RELAY_CONNECTION_PREFIX = 'wsl:'
export function wslHookRelayConnectionId(distro: string): string {
return `${WSL_HOOK_RELAY_CONNECTION_PREFIX}${distro}`
}
export function isWslHookRelayConnectionId(value: string | null | undefined): boolean {
return typeof value === 'string' && value.startsWith(WSL_HOOK_RELAY_CONNECTION_PREFIX)
}
export function wslHookRelayEndpointFilePath(guestHome: string, instanceKey: string): string {
return `${wslHookRelayEndpointDir(guestHome, instanceKey)}/${WSL_HOOK_RELAY_ENDPOINT_FILE}`
}