tutorial
Across the hosts.
So far fleet-top has watched your machine. Now we reach one running on another
box, over ssh, and show its top in your browser.
The trick is a mirror: the remote box serves the surface, a local parent folds its frames into a local copy of the same surface and re-serves that, and the browser only ever talks to the local copy. You use the same surface you already built. Swap the box behind it and the browser never notices.
What runs on the far box
The remote side is tiny: it serves the same top surface over stdin/stdout.
This is what the parent runs on each target:
ssh <host> fleet-top-agent --stdio for a remote box, the realised binary
directly for localhost. Each link gets a fresh agent, which suits a
re-run-fresh reader like top.
/**
* fleet-top-agent — serve the `top` surface over stdin/stdout.
*
* This is what `ssh <host> fleet-top-agent --stdio` runs on the far box. The
* agent is ephemeral (a fresh one per link — `serveOverStdio` makes THIS
* process be the server, and the framework exits the process once the awaited
* serve settles: 0 on `'end'`, 1 on `'error'`); the parent's `makeSession`
* re-spawns it on reconnect. That's the right shape for a re-run-fresh reader
* like `top`.
*
* `serveOverStdio` takes the two fields every transport takes: the flat `group`
* and the tag-keyed `handlers`. The framing is ndjson.
*
* **Stdout is the protocol channel** — every diagnostic goes to fd 2. A stray
* write to fd 1 corrupts the next frame.
*/
import { serveOverStdio } from "@kolu/surface/peer-server";
import { createTop } from "./top";
function log(line: string): void {
process.stderr.write(`fleet-top-agent: ${line}\n`);
}
async function main(): Promise<void> {
if (!process.argv.slice(2).includes("--stdio")) {
process.stderr.write("usage: fleet-top-agent --stdio\n");
process.exit(1);
}
const top = createTop();
top.start();
log(`serving top over stdio (pid ${process.pid})`);
const end = await serveOverStdio({
group: top.runtime.group,
handlers: top.runtime.handlers,
onFirstRequest: () => log("first RPC received — link is live"),
});
// Synchronous post-settle cleanup — the supported window before the
// framework-owned exit (see `serveOverStdio`'s "Lifetime" doc).
top.dispose();
log(`stdin closed (${end.reason}) — agent exiting`);
}
main().catch((err) => {
log(`fatal: ${(err as Error).message}`);
process.exit(1);
});
The three-hop mirror
On the parent, each host is one binding. First, dial it —
makeSession({ connectOnce: sshConnector(...) }) provisions the agent closure
onto the box and runs it (over ssh for a remote host, directly for localhost),
reconnecting on drop.
// `AgentClient` is the structural member face — there is no contract type to
// be generic over any more, and the connector takes the SURFACE as a VALUE:
// Effect RPC builds its client from `surface.group` and the face is re-nested
// from `surface.spec`, neither of which is recoverable from a type alone.
const session: Session<AgentClient, SshProv> = makeSession({
initialConnection: "probing",
connectOnce: sshConnector({
surface,
host,
binary: "fleet-top-agent",
// Policy-free: the CONSUMER composes the localhost arm's spawn env, keeping only
// the keys that are SET (an empty HOME/PATH would misdirect config/command lookup).
// kolu uses kolu-pty's `composeSpawnEnv`; a standalone example picks inline. Never
// the caller's ambient `process.env`; unused for a real ssh host.
localEnv: Object.fromEntries(
(["HOME", "PATH"] as const)
.map((k): [string, string | undefined] => [k, process.env[k]])
.filter((e): e is [string, string] => e[1] !== undefined),
),
// Constant resolver — this demo takes the already-selected agent .drv from
// the environment. Source-based consumers call `ctx.resolveAgentDrv`
// instead; the connector owns system selection and evaluation policy.
resolveDrvPath: () =>
Promise.resolve(directAgentDerivation(agentDrv, EXAMPLE_BINARY_CACHE)),
}),
label: `host:${host}`,
});
Then pump the agent’s frames inward, folding each into a local
implementSurface of the same surface. The local copy is what browser
subscribers read; makeSink writes the incoming frames through its ctx.
session.pin().catch(() => {
/* the failure rides the session's own state, which `projectState` reads */
});
let firstLoad = true;
void pumpRemoteSurface({
source: surface,
session,
makeSink: () => {
firstLoad = true;
return {
cells: {
load: (v) => {
if (firstLoad) {
firstLoad = false;
session.markConnected();
}
runtime.ctx.cells.load.set(v);
},
memory: (v) => runtime.ctx.cells.memory.set(v),
},
collections: {
processes: {
upsert: (k, v) => runtime.ctx.collections.processes.upsert(k, v),
remove: (k) => runtime.ctx.collections.processes.remove(k),
},
},
};
},
});
Finally re-serve: a directDispatch over the re-served surface is what the
browser reaches (reServeSurface hands back the same { group, handlers } pair
any transport takes, with nothing to finalize). After those three hops (dial,
pump, re-serve) the surface that started on another machine serves from this
process.
The remote box cannot report whether your link to it is healthy, so that state
is the parent’s to own. While the closure is copying or the session is
reconnecting, the parent projects warming (in motion, self-heals). Only a
bounded remote fault projects failed (needs intervention): a box that
answers-but-refuses, or one that gives up terminally.
One box’s trouble becomes one chip, never a crash. For why the parent is shaped this way, see The server half.
Before you run it
Multi-host needs two things the earlier parts did not.
- The agent as a
Nix derivation.
sshConnectorships a realised closure to each host, so it needs the agent’s.drvpath inFLEET_TOP_AGENT_DRV. The server refuses to boot without it, and there is no fallback. fleet-top ships the agent as a flake output, so one command resolves it from the repo root:nix eval --raw ./packages/surface/example#fleet-top-agent.drvPath. - A reachable host.
localhostis the easy one:sshConnectordetects it and runs the realised binary directly, with no ssh and no sshd. A non-localHOSTis a genuine ssh hop.
Watch it arrive
-
Point the parent at one host and start it.
HOSTis the target (localhosthere, so no ssh is needed).FLEET_TOP_AGENT_DRVis the agent’s flake output, resolved in place.# resolve the agent .drv (works from anywhere in the repo): export FLEET_TOP_AGENT_DRV="$(nix eval --raw "$(git rev-parse --show-toplevel)/packages/surface/example#fleet-top-agent.drvPath")" HOST=localhost pnpm run devfleet-top part 3 serving 1 host(s) on http://localhost:7740 -
Open http://localhost:5176. The header chip shows the host warming while the agent closure is realised, then flips to connected. The same live
topyou built in part 1 fills in, streaming from the agent the parent stood up (onlocalhost, directly; on a remote box, over ssh).
You changed nothing about the surface or the browser code. The box could be a laptop across the room; the mirror makes it read like local state.
Next
One box is a mirror. Many boxes is a map. In A fleet of surfaces you gather N hosts into one keyed surface, render them as chips, and watch a single box’s trouble stay confined to its own chip. That is fleet-top as a mini-drishti.