8000 feat(runner): fixture-only node-pty runner adapter, first slice (#153) by simon-inkie · Pull Request #231 · simon-inkie/inkie-deck · GitHub
[go: up one dir, main page]

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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ jobs:
# Installed explicitly rather than relied on: the runner image happens
# to carry PyYAML today, and a suite that is green because of what an
# image happens to include is measuring the image.
- name: Install ripgrep, jq and PyYAML
run: sudo apt-get update && sudo apt-get install -y ripgrep jq python3-yaml
- name: Install ripgrep, jq, PyYAML and tmux
run: sudo apt-get update && sudo apt-get install -y ripgrep jq python3-yaml tmux

- name: Typecheck with tsgo
run: pnpm typecheck
Expand Down
2 changes: 1 addition & 1 deletion .gitlab-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ stages:
# runs and not only for whatever follows it in one script.
LANG: C.UTF-8
before_script:
- apt-get update && apt-get install -y --no-install-recommends ripgrep xxd jq python3-yaml
- apt-get update && apt-get install -y --no-install-recommends ripgrep xxd jq python3-yaml tmux
- corepack enable
- corepack prepare --activate
script:
Expand Down
14 changes: 14 additions & 0 deletions .specs/153-tmux-to-node-pty/ISSUE-TEXT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!-- Copy of the published body of #153 (2026-11-18). The origin link to an internal tracker is omitted here. -->
## Goal

Move Deck's terminal-backed agent execution from bash/tmux to a cross-platform TypeScript runner using node-pty/ConPTY, preserving safe delivery and lifecycle behaviour.

## Scope and first slice

Define a runner adapter for launch, input, output, resize, cancellation and exit. Prove one supported agent in an isolated fixture while tmux remains available; select the adapter explicitly rather than switching every agent at once. Preserve the refusal to send into an ended agent's shell.

Test delayed output, failed launch, cancellation, process cleanup and input refusal after exit. Plan a drained cutover: stop new admission, settle in-flight work and confirm ownership before replacing the old runner. Inventory delivery, stuck detection, metrics and streaming changes before later slices.

## Origin and qualification

Migrated from an internal tracker, expanded by maintainer direction on 18 November 2026. The existing investigation is background, not an accepted implementation contract. Native Windows, Linux and macOS acceptance requires separate evidence.
490 changes: 490 additions & 0 deletions .specs/153-tmux-to-node-pty/SPEC.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions packages/deck/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,8 @@
"description": "Web control plane for a fleet of AI agents speaking the inkie-agents-base protocol: inboxes, decision cards, briefs, projects and tmux-backed agent sessions",
"engines": {
"node": "^22.13.0 || >=24.0.0"
},
"optionalDependencies": {
"node-pty": "1.1.0"
}
}
90 changes: 90 additions & 0 deletions packages/deck/test/runner/fixture-agent.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";

const scenario = process.argv[2];
if (scenario === "failed") process.exit(23);
if (scenario === "slow") await delay(150);

const write = (text) => process.stdout.write(text);
let input = "";
let task;
let confirming = false;

async function startDescendant() {
const child = spawn(process.execPath, ["-e", `
const { writeFileSync } = require("node:fs");
process.on("SIGHUP", () => {});
process.on("SIGTERM", () => {});
writeFileSync("descendant-" + process.pid, "ready");
setInterval(() => {}, 1000);
`], { stdio: "ignore" });
child.on("error", (error) => write(`DESCENDANT FAILED ${error.message}\n`));
child.unref();
if (child.pid === undefined) return;
const readyFile = `descendant-${child.pid}`;
while (child.exitCode === null && child.signalCode === null) {
if (existsSync(readyFile)) {
write(`DESCENDANT ${child.pid}\n`);
return;
}
await delay(10);
}
write(`DESCENDANT FAILED ${child.exitCode ?? child.signalCode}\n`);
}

function submit(text) {
if (text === "work") {
task = setTimeout(() => {
task = undefined;
write("TASK FINISHED\n");
}, 2000);
setTimeout(() => write("TASK DEADLINE\n"), 2000);
write("TASK STARTED\n");
} else if (text === "confirm") {
confirming = true;
write("CONFIRM? [Enter/Escape]\n");
} else if (text === "environment") {
write(`ENV ${Object.keys(process.env).sort().join(",")}\n`);
} else if (text === "descendant") {
void startDescendant();
} else if (text === "exit") {
write("fixture@terminal:~$\n");
process.stdin.pause();
process.stdout.write("FIXTURE END\n", () => process.exit(0));
} else if (text.length > 80) {
write("[long paste]\n");
} else {
write(`INPUT ${text}\n`);
}
}

process.stdout.on("resize", () => write(`SIZE ${process.stdout.columns}x${process.stdout.rows}\n`));
process.stdin.setRawMode(true);
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
for (const char of chunk) {
if (confirming) {
if (char !== "\r" && char !== "\x1b") continue;
confirming = false;
write(char === "\r" ? "CONFIRMED\n>\n" : "DECLINED\n>\n");
} else if (char === "\r") {
submit(input.replace(/^\x1b\[200~/, "").replace(/\x1b\[201~$/, ""));
input = "";
} else if (char === "\x03") {
if (task !== undefined) {
clearTimeout(task);
task = undefined;
write("TASK CANCELLED\n>\n");
}
} else {
input += char;
}
}
});

write("\x1b[?2004hFIXTURE READY\n>\n");
for (const text of ["FIRST \\ frame", "SECOND \u00a3 frame", "THIRD frame"]) {
await delay(30);
write(`${text}\n`);
}
15 changes: 15 additions & 0 deletions packages/deck/test/runner/fixture-command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import type { SessionSpec } from "./runner.js";

export function fixtureEnvironment(directory: string) {
return { HOME: directory, PATH: "/usr/bin:/bin", TERM: "xterm", LANG: "C" };
}

export function fixtureCommand(directory: string, spec: SessionSpec) {
return {
file: spec.scenario === "missing" ? join(directory, "missing-fixture") : process.execPath,
args: [fileURLToPath(new URL("./fixture-agent.mjs", import.meta.url)), spec.scenario ?? "normal"],
env: fixtureEnvironment(directory),
};
}
13 changes: 13 additions & 0 deletions packages/deck/test/runner/fixture-exit.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { spawn } from "node:child_process";
import { renameSync, writeFileSync } from "node:fs";
import { constants } from "node:os";

const [statusFile, ...command] = process.argv.slice(2);
const fixture = spawn("/usr/bin/env", command, { stdio: "inherit" });
fixture.once("exit", (code, signal) => {
const signalNumber = signal ? constants.signals[signal] : 0;
const pending = `${statusFile}.tmp`;
writeFileSync(pending, `${process.pid} ${code ?? 0} ${signalNumber}\n`);
renameSync(pending, statusFile);
process.exitCode = code ?? 128 + signalNumber;
});
19 changes: 19 additions & 0 deletions packages/deck/test/runner/fixture-registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { mkdtempSync, realpathSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { isAbsolute, join, relative, sep } from "node:path";
import { PtyRunner } from "./pty-runner.js";
import type { Runner } from "./runner.js";
import { TmuxRunner } from "./tmux-runner.js";

export function fixtureRegistry(directory: string): (kind: Runner["kind"]) => Runner {
const canonical = realpathSync(directory);
const fromTemp = relative(realpathSync(tmpdir()), canonical);
if (!fromTemp || fromTemp === ".." || fromTemp.startsWith(`..${sep}`) || isAbsolute(fromTemp) || !statSync(canonical).isDirectory()) {
throw new Error("Fixture registry requires a directory strictly inside the temporary directory.");
}
return (kind) => {
if (kind !== "pty" && kind !== "tmux") throw new Error("Unknown fixture runner.");
const home = mkdtempSync(join(canonical, "s-"));
return kind === "pty" ? new PtyRunner(home) : new TmuxRunner(home);
};
}
43 changes: 43 additions & 0 deletions packages/deck/test/runner/import-graph.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { readdirSync, readFileSync } from "node:fs";
import { join, relative, sep } from "node:path";
import { fileURLToPath } from "node:url";
import ts from "typescript";
import { expect, it } from "vitest";

const deck = fileURLToPath(new URL("../../", import.meta.url));
const fixtures = join("test", "runner") + sep;
const compilerOptions = ts.getParsedCommandLineOfConfigFile(join(deck, "tsconfig.json"), {}, {
...ts.sys,
onUnRecoverableConfigFileDiagnostic: (error) => { throw new Error(String(error.messageText)); },
})!.options;

it("keeps the fixture registry, runners and node-pty out of the production import graph", () => {
const app = join(deck, "app");
const server = join(deck, "server");
const roots = [
...readdirSync(app, { recursive: true, encoding: "utf8" }).filter((file) => /\.[cm]?[jt]sx?$/.test(file)).map((file) => join(app, file)),
...readdirSync(server).filter((file) => file.endsWith(".mjs")).map((file) => join(server, file)),
join(deck, "scripts/start-production.mjs"), join(deck, "vite.config.ts"), join(deck, "react-router.config.ts"),
];
const visited = new Set<string>();
const violations: string[] = [];
const cache = ts.createModuleResolutionCache(deck, (file) => file, compilerOptions);

function scan(file: string): void {
if (visited.has(file)) return;
visited.add(file);
const source = readFileSync(file, "utf8");
for (const { fileName } of ts.preProcessFile(source, true, true).importedFiles) {
const resolved = ts.resolveModuleName(fileName, file, compilerOptions, ts.sys, cache).resolvedModule;
const dependency = resolved?.resolvedFileName;
if (/^node-pty(?:\/|$)/.test(fileName) || (dependency && relative(deck, dependency).startsWith(fixtures))) {
violations.push(`${relative(deck, file)} -> ${fileName}`);
} else if (dependency && !resolved.isExternalLibraryImport && /\.[cm]?[jt]sx?$/.test(dependency)) {
scan(dependency);
}
}
}

roots.forEach(scan);
expect(violations).toEqual([]);
});
67 changes: 67 additions & 0 deletions packages/deck/test/runner/pty-runner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { createRequire } from "node:module";
import { fixtureCommand } from "./fixture-command.js";
import { FixtureRunner, LaunchFailure, type SessionSpec, type WriteResult } from "./runner.js";

const require = createRequire(import.meta.url);
const keys: Record<string, string> = {
Up: "\x1b[A", Down: "\x1b[B", Enter: "\r", Escape: "\x1b", Tab: "\t", BTab: "\x1b[Z",
};

interface NativeTerminal {
pid: number;
onData(callback: (chunk: Buffer) => void): { dispose(): void };
onExit(callback: (event: { exitCode: number; signal?: number }) => void): { dispose(): void };
write(text: string): void;
resize(cols: number, rows: number): void;
}

interface NativeBinding {
spawn(file: string, args: string[], options: {
cwd: string; env: Record<string, string>; cols: number; rows: number; encoding: null;
}): NativeTerminal;
}

export function loadNodePty(): NativeBinding {
try {
return require("node-pty");
} catch (error) {
throw new LaunchFailure("unavailable", `Could not load node-pty: ${String(error)}`, error);
}
}

export class PtyRunner extends FixtureRunner {
readonly kind = "pty";
private terminal?: NativeTerminal;

constructor(private readonly directory: string) { super(); }

protected async start(spec: SessionSpec): Promise<number> {
if (process.platform !== "linux") {
throw new LaunchFailure("unavailable", "The PTY fixture runner is verified only on Linux.");
}
const binding = loadNodePty();
const { file, args, env } = fixtureCommand(this.directory, spec);
const terminal = binding.spawn(file, args, {
cwd: this.directory, env, cols: spec.cols ?? 80, rows: spec.rows ?? 24, encoding: null,
});
this.terminal = terminal;
const output = terminal.onData((chunk) => this.data(chunk));
const exit = terminal.onExit(({ exitCode, signal }) => {
output.dispose();
exit.dispose();
void this.finish({ code: signal ? null : exitCode, signal: signal || null });
});
return terminal.pid;
}

protected async dispose(): Promise<void> { this.terminal = undefined; }

protected send(value: string, named: boolean): WriteResult {
this.terminal!.write(named ? keys[value]! : value);
return { status: "written" };
}

protected setSize(cols: number, rows: number): void { this.terminal!.resize(cols, rows); }

protected interrupt(): void { this.terminal!.write("\x03"); }
}
Loading
Loading
0