Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/engines.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { existsSync, readFileSync, statSync } from "node:fs";
import { homedir } from "node:os";
import path from "node:path";

import { setActiveChildInput } from "./mirror.mjs";
import { captureSpec } from "./pty.mjs";

export const ENGINES = {
Expand Down Expand Up @@ -509,11 +510,27 @@ export function openPassthrough(target, args = [], { onOutput } = {}) {
// the child the tty's own file descriptors, so none of its bytes ever pass
// through this process. See src/pty.mjs for why this is script(1) and not
// a pipe or node-pty.
const launch = captureSpec(spec, onOutput);
const cleanup = () => launch.stop();
//
// `input` asks for the same pty to be one we can type into. An engine is
// the whole reason it exists: it puts up menus and trust prompts that only
// move for a keypress, and until we owned its stdin a session page could
// watch one of those appear and had no way to answer it.
const launch = captureSpec(spec, onOutput, { input: true });
// Route web keys here for as long as this child is up, and only when there
// is really somewhere for them to go — an unmirrored pit, or a box with no
// `script(1)`, still runs the plain inherited launch, and saying otherwise
// would have pressKey silently swallow keys the pit could have handled.
// Registered before the spawn on purpose: the fifo buffers, so a key that
// arrives while the engine is still starting is delivered, not dropped.
const typeable = launch.stdio !== "inherit";
if (typeable) setActiveChildInput(launch.write);
const cleanup = () => {
if (typeable) setActiveChildInput(null);
launch.stop();
};

let child;
try { child = spawn(launch.cmd, launch.args, { stdio: "inherit", env }); }
try { child = spawn(launch.cmd, launch.args, { stdio: launch.stdio, env }); }
catch (e) { cleanup(); resolve({ ok: false, error: e }); return; }
child.on("error", (e) => { cleanup(); resolve({ ok: false, error: e }); });
child.on("exit", (code, signal) => { cleanup(); resolve({ ok: true, code, signal }); });
Expand Down
39 changes: 35 additions & 4 deletions src/mirror.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@
// every network call is swallowed, because a flaky link must never take down
// the terminal you're actually working in.
//
// What it can't see: once an engine takes the terminal (`/agents claude`), the
// child writes straight to the tty on its own fd — those bytes never pass
// through this process. The mirror shows the hand-off, not the engine's screen.
// A child that takes the terminal (`/agents claude`) writes straight to the tty
// on its own fd, so none of its bytes pass through this process on their own.
// Both directions are handled in src/pty.mjs instead: its output is copied out
// of a pty transcript, and its stdin is a fifo we hold, which is what lets a key
// pressed on the session page answer an engine's prompt rather than land in the
// pit behind it.
import os from "node:os";
import { loadCreds } from "./auth.mjs";

Expand All @@ -30,7 +33,7 @@ export function decodeKey(body) {

// What each key looks like to a program reading the tty in raw mode, and the
// keypress readline wants when it is the one holding the line.
const KEY_BYTES = { up: "\u001b[A", down: "\u001b[B", right: "\u001b[C", left: "\u001b[D", enter: "\r" };
export const KEY_BYTES = { up: "\u001b[A", down: "\u001b[B", right: "\u001b[C", left: "\u001b[D", enter: "\r" };
const KEY_PRESS = {
up: { name: "up" }, down: { name: "down" }, right: { name: "right" },
left: { name: "left" }, enter: { name: "return" },
Expand All @@ -43,6 +46,14 @@ const KEY_PRESS = {
export function pressKey(name, rl = null, stdin = process.stdin) {
const bytes = KEY_BYTES[name];
if (!bytes) return false;
// A child engine takes precedence over everything below, because when one is
// running it is the thing the person on the session page can see. It reads a
// real file descriptor rather than this process's stdin object, so the bytes
// have to be *written* — the synthesised event further down reaches readline
// and the pit's own raw-mode readers, and nothing that was spawned. This is
// the line that decides whether an arrow key lands on Claude's trust prompt.
const toChild = activeChildInput();
if (toChild && toChild(bytes)) return true;
// At the prompt readline owns the line editor, so hand it a keypress rather
// than bytes: ↑/↓ walk the history, ←/→ move within the line, enter runs it.
if (rl) {
Expand Down Expand Up @@ -78,6 +89,26 @@ export function activeChildSink() {
return activeSink;
}

// The other direction: where to put bytes so the program currently holding the
// terminal reads them.
//
// Null almost always, and set only while a child owns the tty under a pty we
// opened (src/pty.mjs captureWithInput). It has to be module-level for the same
// reason the sink does — pressKey is called from the mirror's poll loop, which
// has no idea which launcher is mid-flight — and it is what makes a key pressed
// on the session page land in an engine rather than in the pit behind it.
let activeInput = null;

/** Point web keystrokes at a running child (or null when it exits). */
export function setActiveChildInput(write) {
activeInput = typeof write === "function" ? write : null;
}

/** How to type into whatever child owns the terminal, or null for the pit. */
export function activeChildInput() {
return activeInput;
}

export function createMirror({
version = "",
cwd = process.cwd(),
Expand Down
248 changes: 239 additions & 9 deletions src/pty.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@
// `script` disagree on both flag names and argument order, and anything we
// cannot positively identify falls back to today's plain `inherit`.
import { spawnSync } from "node:child_process";
import { closeSync, existsSync, mkdtempSync, openSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
import {
closeSync, constants, existsSync, mkdtempSync, openSync,
readFileSync, readSync, rmSync, statSync, writeFileSync, writeSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { StringDecoder } from "node:string_decoder";
Expand Down Expand Up @@ -78,6 +81,18 @@ export function ptySpec(cmd, args = [], transcript, flavor) {
return null;
}

/**
* The same thing for a shell *line* rather than an argv, which the input path
* needs: it prefixes the child with `stty` and `tty` so the session sizes
* itself and says where it landed, and those only exist as shell.
*/
export function ptyShellSpec(command, transcript, flavor) {
if (!command || !transcript) return null;
if (flavor === "util-linux") return { cmd: "script", args: ["-q", "-e", "-f", "-c", command, transcript] };
if (flavor === "bsd") return { cmd: "script", args: ["-q", "-F", transcript, "sh", "-c", command] };
return null;
}

/**
* Follow a transcript as it is written, handing each new slice to `onChunk`.
*
Expand Down Expand Up @@ -197,16 +212,29 @@ export function ptyEnabled(sink, flavor = scriptFlavor()) {
* of how this started, where each launcher had to be taught separately and only
* two ever were. Pass `null` to opt a launch out.
*
* Returns `{ cmd, args, stop }`. With nothing watching, or on a box with no
* `script(1)` we can drive, `cmd`/`args` come back exactly as passed in and
* `stop` is a no-op — the caller spawns what it always spawned. `stop()` must
* be called once the child exits: it drains the tail of the transcript (the
* last lines of a command are usually the ones you were waiting for) and
* removes the temp dir.
* Returns `{ cmd, args, stdio, write, stop }`. With nothing watching, or on a
* box with no `script(1)` we can drive, `cmd`/`args` come back exactly as
* passed in, `stdio` is "inherit" and `write` returns false — the caller spawns
* what it always spawned. `stop()` must be called once the child exits: it
* drains the tail of the transcript (the last lines of a command are usually
* the ones you were waiting for) and removes the temp dir.
*
* `input: true` additionally makes the child's stdin something we can type
* into, so the session page can drive it — see captureWithInput.
*/
export function captureSpec({ cmd, args = [] }, onOutput = activeChildSink(), { flavor = scriptFlavor() } = {}) {
const plain = { cmd, args, stop: () => {} };
export function captureSpec(
{ cmd, args = [] },
onOutput = activeChildSink(),
{ flavor = scriptFlavor(), input = false, stdin = process.stdin, stdout = process.stdout } = {},
) {
const plain = { cmd, args, stdio: "inherit", write: () => false, stop: () => {} };
if (!ptyEnabled(onOutput, flavor)) return plain;
if (input) {
const withInput = captureWithInput({ cmd, args }, onOutput, { flavor, stdin, stdout });
if (withInput) return withInput;
// No fifo, no local tty, nothing we could drive — fall through to the
// output-only capture rather than dropping capture altogether.
}
let workDir = null;
try {
workDir = mkdtempSync(path.join(tmpdir(), "moshcode-pty-"));
Expand All @@ -224,6 +252,8 @@ export function captureSpec({ cmd, args = [] }, onOutput = activeChildSink(), {
return {
cmd: wrapped.cmd,
args: wrapped.args,
stdio: "inherit",
write: () => false,
stop() {
try { stopFollow(); } catch { /* nothing left to drain */ }
try { rmSync(dir, { recursive: true, force: true }); } catch { /* temp dir */ }
Expand All @@ -235,3 +265,203 @@ export function captureSpec({ cmd, args = [] }, onOutput = activeChildSink(), {
return plain;
}
}

// ---------------------------------------------------------------------------
// Typing into the child
// ---------------------------------------------------------------------------

/** A terminal geometry we can hand a child, with a sane floor. */
function geometry(stdout) {
return { cols: Number(stdout?.columns) || 80, rows: Number(stdout?.rows) || 24 };
}

// Application cursor keys (DECCKM). A program that turns this on is saying "send
// me ESC O B for down, not ESC [ B", and a terminal obliges — which is why the
// distinction never comes up for the person at the keyboard, and why it bites
// the moment we start synthesising keys ourselves. `less` is the plain
// demonstration: fed the CSI form while it has DECCKM set, it does not scroll,
// it prints "ESC[B" on its own prompt line as if you had typed the characters.
//
// The mode is not something we can ask about, but it is announced: the child
// writes the escape on its way into full-screen mode, and every byte it writes
// is already passing under our nose on the way to the mirror.
const DECCKM = /\u001b\[\?1([hl])/g;

/** Track a DECCKM change announced in `text`; returns the mode after it. */
export function cursorKeyMode(text, current = false) {
const seen = [...String(text).matchAll(DECCKM)].pop();
return seen ? seen[1] === "h" : current;
}

/**
* Rewrite CSI cursor keys as SS3, for a child that asked for application mode.
*
* Only the four cursor keys move: everything else, including a literal ESC and
* anything the person at the keyboard typed, is left exactly as it arrived.
*/
export function toApplicationCursor(buf) {
const out = Buffer.from(buf);
for (let i = 0; i + 2 < out.length; i += 1) {
// ESC [ A|B|C|D -> ESC O A|B|C|D
if (out[i] === 0x1b && out[i + 1] === 0x5b && out[i + 2] >= 0x41 && out[i + 2] <= 0x44) {
out[i + 1] = 0x4f;
}
}
return out;
}

/**
* The same capture, but with a stdin the mirror can write to.
*
* `inherit` hands the child the tty's own file descriptors, which is why a key
* pressed on the session page could never reach it: there is no fd in this
* process between the browser and the program, so the best the mirror could do
* was synthesise a `data` event on its own `process.stdin` — which the pit's
* readline hears and a child does not (see pressKey in src/mirror.mjs). To type
* into an engine we have to own its stdin, and a fifo is the one way to do that
* with nothing but the base system: `script(1)` reads it and copies it to the
* pty master, exactly as it would a terminal.
*
* Owning stdin costs two things back, and both are paid here rather than
* written off as limitations:
*
* - Size. `script` takes the pty's geometry from its own stdin, and a fifo has
* none, so the child would start on a 0x0 terminal — which full-screen
* engines do not survive. Nothing outside a pty can ioctl its master, but
* `stty` inside it can, so the session sizes itself on the way in.
* - Resize. For the same reason `script` can no longer forward SIGWINCH. The
* child records its pty path on the way in, which is enough to resize it
* from out here with `stty -F` when the real window changes, so dragging a
* window edge still reaches the engine.
*
* The person at the keyboard has to keep working throughout, so local stdin is
* relayed byte-for-byte into the same fifo. That means raw mode: this tty has
* to stop echoing and stop buffering lines, because the pty on the other end is
* now the one doing both.
*
* Returns null when this box can't do it (no `mkfifo`, no local tty), which
* leaves the caller on the output-only path it had before.
*/
export function captureWithInput({ cmd, args = [] }, onOutput, { flavor, stdin, stdout } = {}) {
// Without a local terminal there is nothing to relay and raw mode is
// meaningless, so capture alone is the honest thing to offer.
if (!stdin?.isTTY || typeof stdin.setRawMode !== "function") return null;

let workDir = null;
let fd = null;
try {
workDir = mkdtempSync(path.join(tmpdir(), "moshcode-pty-"));
const transcript = path.join(workDir, "transcript");
const fifo = path.join(workDir, "input");
const ptsFile = path.join(workDir, "pts");
writeFileSync(transcript, "");

// node has no mkfifo, so this is the one call out to the system — and a box
// without it simply does not get the input path.
const made = spawnSync("mkfifo", [fifo]);
if (made.error || made.status !== 0) throw new Error("no mkfifo on this box");

const { cols, rows } = geometry(stdout);
const command = [
`tty > ${shQuote(ptsFile)} 2>/dev/null`,
`stty rows ${rows} cols ${cols} 2>/dev/null`,
// exec, so the engine *is* the process script is waiting on: its signals
// and its exit status pass straight through rather than via a shell.
`exec ${[cmd, ...args].map(shQuote).join(" ")}`,
].join("; ");
const wrapped = ptyShellSpec(command, transcript, flavor);
if (!wrapped) throw new Error("no script(1) spec for this flavour");

// O_RDWR, not O_WRONLY: opening a fifo write-only blocks until a reader
// arrives, and the reader here is a child we have not spawned yet. Holding
// both ends also keeps the child from seeing EOF between writes.
fd = openSync(fifo, constants.O_RDWR);

let first = true;
// Which form of cursor key this child is asking for, learned from the same
// stream that goes to the mirror. Tracked on the raw chunk rather than the
// banner-stripped one: the mode switch is a control sequence, and nothing
// about the banner is in its way.
let appCursor = false;
const stopFollow = followFile(transcript, (chunk) => {
appCursor = cursorKeyMode(chunk, appCursor);
const clean = stripScriptBanner(chunk, first);
first = false;
if (clean) onOutput(clean);
});

let stopped = false;
/** Put bytes in front of the child, from the web or from the keyboard. */
const write = (data) => {
if (stopped || fd === null) return false;
const raw = typeof data === "string" ? Buffer.from(data, "latin1") : Buffer.from(data);
try { writeSync(fd, appCursor ? toApplicationCursor(raw) : raw); return true; }
catch { return false; }
};

// Raw, because the pty on the far end is now the one echoing and the one
// splitting lines. Leaving this tty cooked would double every character and
// hold Enter back until the child had already redrawn without it.
const wasRaw = Boolean(stdin.isRaw);
stdin.setRawMode(true);
stdin.resume();
const onData = (buf) => { write(buf); };
stdin.on("data", onData);

// The child's own tty, once its prelude has written it down. Read lazily:
// at the moment we spawn, that file does not exist yet.
let pts = null;
const childTty = () => {
if (pts) return pts;
try { pts = readFileSync(ptsFile, "utf8").trim() || null; } catch { pts = null; }
return pts;
};
let resizeTimer = null;
const onResize = () => {
clearTimeout(resizeTimer);
// Dragging an edge fires this continuously; settle for one ioctl per drag.
resizeTimer = setTimeout(() => {
resizeTimer = null;
const tty = childTty();
if (!tty || stopped) return;
const size = geometry(stdout);
// -F on util-linux, -f on BSD/macOS — the same disagreement as the
// script(1) flags above, and getting it wrong here is a usage error on
// every resize rather than anything visible.
const on = flavor === "bsd" ? "-f" : "-F";
try { spawnSync("stty", [on, tty, "rows", String(size.rows), "cols", String(size.cols)]); }
catch { /* the child owns it; a resize we lose is cosmetic */ }
}, 120);
resizeTimer.unref?.();
};
stdout?.on?.("resize", onResize);

const dir = workDir;
return {
cmd: wrapped.cmd,
args: wrapped.args,
// The fifo is the child's stdin; its output still goes straight to the
// real terminal, so the engine draws at full speed exactly as before.
stdio: [fd, "inherit", "inherit"],
write,
stop() {
if (stopped) return;
stopped = true;
clearTimeout(resizeTimer);
stdout?.off?.("resize", onResize);
stdin.off("data", onData);
// Hand the terminal back the way we found it. Getting this wrong leaves
// the pit with no echo, which reads as a hung shell.
try { stdin.setRawMode(wasRaw); } catch { /* not a tty any more */ }
stdin.pause();
try { stopFollow(); } catch { /* nothing left to drain */ }
if (fd !== null) { try { closeSync(fd); } catch { /* already gone */ } fd = null; }
try { rmSync(dir, { recursive: true, force: true }); } catch { /* temp dir */ }
},
};
} catch {
if (fd !== null) { try { closeSync(fd); } catch { /* already gone */ } }
if (workDir) { try { rmSync(workDir, { recursive: true, force: true }); } catch { /* temp dir */ } }
return null;
}
}
Loading
Loading