@tarve/mcp 0.0.0-stage → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@tarve/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.12.0",
4
+ "description": "Model Context Protocol server for Tarve apps: lets AI agents inspect, screenshot, drive and reload a running app in development",
5
+ "license": "Apache-2.0",
6
+ "keywords": [
7
+ "tarve",
8
+ "mcp",
9
+ "model-context-protocol",
10
+ "devtools",
11
+ "ai",
12
+ "agent"
13
+ ],
14
+ "homepage": "https://github.com/omarcosr/tarve/tree/main/packages/mcp#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/omarcosr/tarve.git",
18
+ "directory": "packages/mcp"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/omarcosr/tarve/issues"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "provenance": true
26
+ },
27
+ "type": "module",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./src/index.ts",
31
+ "bun": "./src/index.ts",
32
+ "default": "./dist/index.js"
33
+ }
34
+ },
35
+ "bin": {
36
+ "tarve-mcp": "./dist/cli.js"
37
+ },
38
+ "files": [
39
+ "src",
40
+ "dist",
41
+ "!src/**/*.test.ts",
42
+ "!src/fixtures",
43
+ "README.md"
44
+ ],
45
+ "scripts": {
46
+ "test": "bun test",
47
+ "build": "bun build.ts",
48
+ "prepack": "bun build.ts"
49
+ },
50
+ "peerDependencies": {
51
+ "@tarve/core": "^0.12.0"
52
+ },
53
+ "engines": {
54
+ "bun": ">=1.4.0",
55
+ "node": ">=26.10.0"
56
+ }
57
+ }
@@ -0,0 +1,137 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { serveStdio } from "./server";
4
+ import { AppSession, type LaunchSpec } from "./session";
5
+ import { createTools } from "./tools";
6
+
7
+ export const VERSION = "0.10.0";
8
+
9
+ export const USAGE = `tarve-mcp: a Model Context Protocol server (stdio) that runs a Tarve app and lets an agent inspect, screenshot, drive and reload it.
10
+
11
+ Usage:
12
+ tarve-mcp [options] <app.tsx> start the app with \`tarve dev\` (hot reload)
13
+ tarve-mcp [options] <dist/App.exe> start a built app (\`tarve build\`, any runtime) as it is
14
+ tarve-mcp [options] --exec <command...> start the app with your own command (it must use @tarve/core)
15
+ (\`-- <command...>\` too, where the runtime keeps \`--\`: Bun drops it)
16
+
17
+ Options:
18
+ --run \`tarve run\` instead of \`tarve dev\` (no hot reload)
19
+ --runtime <name> bun or node, passed to the tarve CLI
20
+ --inspect also open the visual inspector window
21
+ --cwd <dir> working directory of the app (default: the current one)
22
+ --connect-timeout <ms> how long the app may take to connect (default 60000)
23
+
24
+ MCP client config (Claude Desktop, Cursor, VS Code…):
25
+ { "command": "bunx", "args": ["tarve-mcp", "src/app.tsx"] }`;
26
+
27
+ export interface McpArgs {
28
+ entry?: string;
29
+ command?: string[];
30
+ mode: "dev" | "run";
31
+ runtime?: string;
32
+ inspect: boolean;
33
+ cwd: string;
34
+ connectTimeoutMs?: number;
35
+ help: boolean;
36
+ }
37
+
38
+ export function parseArgs(argv: readonly string[], cwd = process.cwd()): McpArgs {
39
+ const args: McpArgs = { mode: "dev", inspect: false, cwd, help: false };
40
+ for (let index = 0; index < argv.length; index++) {
41
+ const arg = argv[index]!;
42
+ const value = (): string => {
43
+ const next = argv[++index];
44
+ if (next === undefined) throw new Error(`${arg} needs a value`);
45
+ return next;
46
+ };
47
+ if (arg === "--" || arg === "--exec") { args.command = argv.slice(index + 1); break; }
48
+ if (arg === "--help" || arg === "-h") args.help = true;
49
+ else if (arg === "--run") args.mode = "run";
50
+ else if (arg === "--dev") args.mode = "dev";
51
+ else if (arg === "--inspect") args.inspect = true;
52
+ else if (arg === "--runtime") args.runtime = value();
53
+ else if (arg === "--cwd") args.cwd = resolve(cwd, value());
54
+ else if (arg === "--connect-timeout") {
55
+ const ms = Number(value());
56
+ if (!Number.isFinite(ms) || ms <= 0) throw new Error("--connect-timeout needs a positive number of milliseconds");
57
+ args.connectTimeoutMs = ms;
58
+ } else if (arg.startsWith("-")) throw new Error(`Unknown option ${arg}`);
59
+ else if (args.entry) throw new Error(`Unexpected argument ${arg}: give one app entry, or a command after --`);
60
+ else args.entry = arg;
61
+ }
62
+ if (args.command && !args.command.length) throw new Error("Give the command after --exec");
63
+ if (args.command && args.entry) throw new Error("Give an app entry or a command after --exec, not both");
64
+ return args;
65
+ }
66
+
67
+ const readJson = (path: string): Record<string, unknown> | undefined => {
68
+ try { return JSON.parse(readFileSync(path, "utf8")); } catch { return undefined; }
69
+ };
70
+
71
+ /**
72
+ * How to run the tarve CLI the app's project uses, from `cwd` upwards: the installed
73
+ * `node_modules/@tarve/core` CLI with this runtime, or, in the Tarve repository itself, its
74
+ * source CLI, which runs on Bun like every repository script (`examples/node_modules/.bin/tarve`).
75
+ * The app's own runtime is `--runtime`, whatever runs the CLI.
76
+ */
77
+ export function findTarveCli(cwd: string): string[] | undefined {
78
+ const binOf = (root: string, manifest: Record<string, unknown>): string | undefined => {
79
+ const bin = manifest.bin;
80
+ const path = typeof bin === "string" ? bin : bin && typeof bin === "object" ? (bin as Record<string, unknown>).tarve : undefined;
81
+ return typeof path === "string" && existsSync(join(root, path)) ? join(root, path) : undefined;
82
+ };
83
+ for (let directory = resolve(cwd); ; directory = dirname(directory)) {
84
+ const own = readJson(join(directory, "package.json"));
85
+ if (own?.name === "@tarve/core") {
86
+ const source = join(directory, "packages", "core", "cli.ts");
87
+ if (existsSync(source)) return [process.versions.bun ? process.execPath : "bun", source];
88
+ const built = binOf(directory, own);
89
+ if (built) return [process.execPath, built];
90
+ }
91
+ const installed = join(directory, "node_modules", "@tarve", "core");
92
+ const manifest = readJson(join(installed, "package.json"));
93
+ const bin = manifest && binOf(installed, manifest);
94
+ if (bin) return [process.execPath, bin];
95
+ if (dirname(directory) === directory) return undefined;
96
+ }
97
+ }
98
+
99
+ const SOURCE = /\.(?:[cm]?[jt]sx?|svelte)$/i;
100
+
101
+ export function resolveLaunch(args: McpArgs): LaunchSpec {
102
+ const env: Record<string, string> = args.inspect ? { TARVE_INSPECTOR: "1" } : {};
103
+ if (args.command) return { command: args.command[0]!, args: args.command.slice(1), cwd: args.cwd, env };
104
+ if (!args.entry) throw new Error(`Give the app entry (tarve-mcp app.tsx) or a command after --exec\n\n${USAGE}`);
105
+ const entry = resolve(args.cwd, args.entry);
106
+ if (!existsSync(entry)) throw new Error(`${entry} does not exist`);
107
+ // Not source: an executable \`tarve build\` made, which runs as it is.
108
+ if (!SOURCE.test(entry)) return { command: entry, args: [], cwd: args.cwd, env };
109
+ const cli = findTarveCli(args.cwd);
110
+ if (!cli) throw new Error(`@tarve/core is not installed in ${args.cwd} or above: install it, or give the command after --exec`);
111
+ return { command: cli[0]!, args: [...cli.slice(1), args.mode, entry, ...(args.runtime ? ["--runtime", args.runtime] : [])], cwd: args.cwd, env };
112
+ }
113
+
114
+ export const INSTRUCTIONS = `Drives a running Tarve desktop app (native window, not a browser).
115
+ Start with inspect_tree (or screenshot) to see the UI; target nodes by visible text or by the ids it shows.
116
+ click, hover, type_text, press_key, scroll and drag go through native hit testing and wait for the next frame.
117
+ Coordinates are window logical px. get_logs shows console output and errors; get_events the app's native events; get_metrics performance.
118
+ Source edits hot-reload in dev mode; call reload after a crash or a closed window.`;
119
+
120
+ /** Starts the app and serves MCP on stdio until stdin closes. */
121
+ export async function startServer(argv: readonly string[]): Promise<number> {
122
+ const args = parseArgs(argv);
123
+ if (args.help) {
124
+ process.stderr.write(`${USAGE}\n`);
125
+ return 0;
126
+ }
127
+ const session = new AppSession(resolveLaunch(args), { ...(args.connectTimeoutMs ? { connectTimeoutMs: args.connectTimeoutMs } : {}) });
128
+ process.once("exit", () => session.killNow());
129
+ const shutdown = () => { void session.dispose().finally(() => process.exit(0)); };
130
+ process.once("SIGINT", shutdown);
131
+ process.once("SIGTERM", shutdown);
132
+ // The app opens while the client initializes; tools report a failed start.
133
+ session.start().catch(error => process.stderr.write(`[tarve-mcp] ${error instanceof Error ? error.message : String(error)}\n`));
134
+ await serveStdio(createTools(session), { name: "tarve", version: VERSION, instructions: INSTRUCTIONS });
135
+ await session.dispose();
136
+ return 0;
137
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { startServer } from "./cli-args";
3
+
4
+ try {
5
+ process.exitCode = await startServer(process.argv.slice(2));
6
+ } catch (error) {
7
+ process.stderr.write(`tarve-mcp: ${error instanceof Error ? error.message : String(error)}\n`);
8
+ process.exitCode = 1;
9
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { AppSession, type AppEvent, type LaunchSpec, type LogLine, type SessionOptions, type SessionStatus } from "./session";
2
+ export { createHandler, serveStdio, textResult, PROTOCOL_VERSIONS, type Content, type ServerInfo, type StdioStreams, type Tool, type ToolAnnotations, type ToolResult } from "./server";
3
+ export { createTools, findByText, keyName, outline, type ControlNode } from "./tools";
4
+ export { parseArgs, resolveLaunch, startServer, type McpArgs } from "./cli-args";
package/src/server.ts ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * A Model Context Protocol server (tools only) over newline-delimited JSON-RPC 2.0, the MCP
3
+ * stdio transport. No SDK: the same code runs on Bun, Node.js and txiki.js.
4
+ */
5
+
6
+ export type Content =
7
+ | { type: "text"; text: string }
8
+ | { type: "image"; data: string; mimeType: string };
9
+
10
+ export interface ToolResult {
11
+ content: Content[];
12
+ structuredContent?: Record<string, unknown>;
13
+ isError?: boolean;
14
+ }
15
+
16
+ export interface ToolAnnotations {
17
+ title?: string;
18
+ readOnlyHint?: boolean;
19
+ destructiveHint?: boolean;
20
+ idempotentHint?: boolean;
21
+ openWorldHint?: boolean;
22
+ }
23
+
24
+ export interface Tool {
25
+ name: string;
26
+ description: string;
27
+ inputSchema: { type: "object"; properties?: Record<string, unknown>; required?: string[]; additionalProperties?: boolean };
28
+ annotations?: ToolAnnotations;
29
+ run(args: Record<string, unknown>): Promise<ToolResult>;
30
+ }
31
+
32
+ export interface ServerInfo {
33
+ name: string;
34
+ version: string;
35
+ /** Shown to the model on initialize: what the server is for and how to use it. */
36
+ instructions?: string;
37
+ }
38
+
39
+ export const PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"] as const;
40
+
41
+ type Id = string | number | null;
42
+ interface JsonRpcResponse { jsonrpc: "2.0"; id: Id; result?: unknown; error?: { code: number; message: string } }
43
+
44
+ export const ErrorCode = { parse: -32700, invalidRequest: -32600, methodNotFound: -32601, invalidParams: -32602, internal: -32603 } as const;
45
+
46
+ class RpcError extends Error {
47
+ readonly code: number;
48
+ constructor(code: number, message: string) {
49
+ super(message);
50
+ this.code = code;
51
+ }
52
+ }
53
+
54
+ export const textResult = (text: string, isError = false): ToolResult => ({ content: [{ type: "text", text }], ...(isError ? { isError } : {}) });
55
+
56
+ /** Answers one JSON-RPC message (request or notification); `undefined` for notifications. */
57
+ export function createHandler(tools: readonly Tool[], info: ServerInfo): (message: unknown) => Promise<JsonRpcResponse | undefined> {
58
+ const byName = new Map(tools.map(tool => [tool.name, tool]));
59
+ async function dispatch(method: string, params: Record<string, unknown>): Promise<unknown> {
60
+ switch (method) {
61
+ case "initialize": {
62
+ const asked = typeof params.protocolVersion === "string" ? params.protocolVersion : "";
63
+ return {
64
+ protocolVersion: (PROTOCOL_VERSIONS as readonly string[]).includes(asked) ? asked : PROTOCOL_VERSIONS[0],
65
+ capabilities: { tools: { listChanged: false } },
66
+ serverInfo: { name: info.name, version: info.version },
67
+ ...(info.instructions ? { instructions: info.instructions } : {}),
68
+ };
69
+ }
70
+ case "ping": return {};
71
+ case "tools/list":
72
+ return { tools: tools.map(({ name, description, inputSchema, annotations }) => ({ name, description, inputSchema, ...(annotations ? { annotations } : {}) })) };
73
+ case "tools/call": {
74
+ const tool = typeof params.name === "string" ? byName.get(params.name) : undefined;
75
+ if (!tool) throw new RpcError(ErrorCode.invalidParams, `Unknown tool: ${String(params.name)}`);
76
+ const args = params.arguments && typeof params.arguments === "object" && !Array.isArray(params.arguments) ? params.arguments as Record<string, unknown> : {};
77
+ try {
78
+ return await tool.run(args);
79
+ } catch (error) {
80
+ // Tool failures go to the model as results it can act on, not as protocol errors.
81
+ return textResult(error instanceof Error ? error.message : String(error), true);
82
+ }
83
+ }
84
+ default: throw new RpcError(ErrorCode.methodNotFound, `Method not found: ${method}`);
85
+ }
86
+ }
87
+ return async message => {
88
+ if (!message || typeof message !== "object" || Array.isArray(message)) {
89
+ return { jsonrpc: "2.0", id: null, error: { code: ErrorCode.invalidRequest, message: "Invalid request" } };
90
+ }
91
+ const { id, method, params } = message as { id?: Id; method?: unknown; params?: unknown };
92
+ // A response or a notification (initialized, cancelled): nothing to answer.
93
+ if (typeof method !== "string") return undefined;
94
+ if (id === undefined) return undefined;
95
+ try {
96
+ const result = await dispatch(method, params && typeof params === "object" ? params as Record<string, unknown> : {});
97
+ return { jsonrpc: "2.0", id, result };
98
+ } catch (error) {
99
+ const code = error instanceof RpcError ? error.code : ErrorCode.internal;
100
+ return { jsonrpc: "2.0", id, error: { code, message: error instanceof Error ? error.message : String(error) } };
101
+ }
102
+ };
103
+ }
104
+
105
+ export interface StdioStreams {
106
+ input: { setEncoding?(encoding: "utf8"): unknown; on(event: "data", listener: (chunk: string | Uint8Array) => void): unknown; on(event: "end" | "close", listener: () => void): unknown };
107
+ output: { write(chunk: string): unknown };
108
+ }
109
+
110
+ /** Serves MCP on stdin/stdout until stdin ends. Only protocol messages go to stdout. */
111
+ export function serveStdio(tools: readonly Tool[], info: ServerInfo, streams: StdioStreams = { input: process.stdin, output: process.stdout }): Promise<void> {
112
+ const handle = createHandler(tools, info);
113
+ const send = (response: unknown) => { streams.output.write(JSON.stringify(response) + "\n"); };
114
+ const decoder = new TextDecoder();
115
+ let buffer = "";
116
+ const pending = new Set<Promise<void>>();
117
+ const receive = (line: string) => {
118
+ let message: unknown;
119
+ try { message = JSON.parse(line); } catch {
120
+ send({ jsonrpc: "2.0", id: null, error: { code: ErrorCode.parse, message: "Parse error" } });
121
+ return;
122
+ }
123
+ const task = (async () => {
124
+ if (Array.isArray(message)) {
125
+ const responses = (await Promise.all(message.map(handle))).filter(Boolean);
126
+ if (responses.length) send(responses);
127
+ } else {
128
+ const response = await handle(message);
129
+ if (response) send(response);
130
+ }
131
+ })();
132
+ pending.add(task);
133
+ void task.finally(() => pending.delete(task));
134
+ };
135
+ streams.input.setEncoding?.("utf8");
136
+ return new Promise(resolve => {
137
+ let done = false;
138
+ const finish = () => {
139
+ if (done) return;
140
+ done = true;
141
+ if (buffer.trim()) receive(buffer);
142
+ void Promise.allSettled([...pending]).then(() => resolve());
143
+ };
144
+ streams.input.on("data", chunk => {
145
+ buffer += typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
146
+ let end: number;
147
+ while ((end = buffer.indexOf("\n")) >= 0) {
148
+ const line = buffer.slice(0, end).replace(/\r$/, "");
149
+ buffer = buffer.slice(end + 1);
150
+ if (line.trim()) receive(line);
151
+ }
152
+ });
153
+ streams.input.on("end", finish);
154
+ streams.input.on("close", finish);
155
+ });
156
+ }
package/src/session.ts ADDED
@@ -0,0 +1,295 @@
1
+ import { spawn, spawnSync, type ChildProcess } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { createServer, type Server, type Socket } from "node:net";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+
8
+ /** How to start the app: a program and its arguments. */
9
+ export interface LaunchSpec {
10
+ command: string;
11
+ args: string[];
12
+ cwd?: string;
13
+ env?: Record<string, string>;
14
+ }
15
+
16
+ export interface SessionOptions {
17
+ /** How long the app may take to connect after it starts. Default 60 s (a first `bun --hot` compile). */
18
+ connectTimeoutMs?: number;
19
+ /** App events kept for `events()`. Default 500. */
20
+ eventLimit?: number;
21
+ /** Output lines kept for `logs()`. Default 1000. */
22
+ logLimit?: number;
23
+ }
24
+
25
+ export interface AppEvent { seq: number; time: number; event: Record<string, unknown> }
26
+ export interface LogLine { seq: number; time: number; stream: "stdout" | "stderr"; text: string }
27
+
28
+ export interface SessionStatus {
29
+ running: boolean;
30
+ connected: boolean;
31
+ pid?: number;
32
+ /** The app process's runtime, as it reported it. */
33
+ runtime?: string;
34
+ exitCode?: number | null;
35
+ starts: number;
36
+ command: string[];
37
+ }
38
+
39
+ /** A bounded log with increasing sequence numbers, so readers can ask for what is new. */
40
+ class Ring<T extends { seq: number }> {
41
+ private items: T[] = [];
42
+ private next = 1;
43
+ private readonly limit: number;
44
+ constructor(limit: number) { this.limit = limit; }
45
+ push(item: Omit<T, "seq">): void {
46
+ this.items.push({ ...item, seq: this.next++ } as T);
47
+ if (this.items.length > this.limit) this.items.splice(0, this.items.length - this.limit);
48
+ }
49
+ since(seq = 0, limit = 100): T[] {
50
+ const newer = this.items.filter(item => item.seq > seq);
51
+ return newer.slice(Math.max(0, newer.length - limit));
52
+ }
53
+ get last(): number { return this.next - 1; }
54
+ }
55
+
56
+ interface Pending { resolve(value: unknown): void; reject(error: Error): void; timer: ReturnType<typeof setTimeout> }
57
+
58
+ /** A private socket address: a named pipe on Windows, a Unix socket in a 0700 temporary directory elsewhere. */
59
+ function controlAddress(): { address: string; cleanup(): void } {
60
+ const key = randomBytes(16).toString("hex");
61
+ if (process.platform === "win32") return { address: `\\\\.\\pipe\\tarve-mcp-${key}`, cleanup() {} };
62
+ const directory = mkdtempSync(join(tmpdir(), "tarve-mcp-"));
63
+ return { address: join(directory, "control.sock"), cleanup() { rmSync(directory, { recursive: true, force: true }); } };
64
+ }
65
+
66
+ /**
67
+ * One app driven by the MCP server: it starts the app with `TARVE_CONTROL` pointing at a
68
+ * socket only this session knows (and a token the app must present), keeps its output and
69
+ * events, sends it requests and restarts it.
70
+ */
71
+ export class AppSession {
72
+ readonly launch: LaunchSpec;
73
+ readonly directory: string;
74
+ private readonly options: Required<SessionOptions>;
75
+ private readonly token = randomBytes(24).toString("hex");
76
+ private readonly addr: { address: string; cleanup(): void };
77
+ private server: Server | undefined;
78
+ private listening: Promise<void> | undefined;
79
+ private child: ChildProcess | undefined;
80
+ private socket: Socket | undefined;
81
+ private runtime: string | undefined;
82
+ private exitCode: number | null | undefined;
83
+ private starts = 0;
84
+ private nextId = 1;
85
+ private readonly pending = new Map<number, Pending>();
86
+ private connected: Promise<void> | undefined;
87
+ private connectWaiter: { resolve(): void; reject(error: Error): void } | undefined;
88
+ private readonly eventLog: Ring<AppEvent>;
89
+ private readonly logLog: Ring<LogLine>;
90
+
91
+ constructor(launch: LaunchSpec, options: SessionOptions = {}) {
92
+ this.launch = launch;
93
+ this.options = { connectTimeoutMs: options.connectTimeoutMs ?? 60_000, eventLimit: options.eventLimit ?? 500, logLimit: options.logLimit ?? 1000 };
94
+ this.eventLog = new Ring(this.options.eventLimit);
95
+ this.logLog = new Ring(this.options.logLimit);
96
+ this.addr = controlAddress();
97
+ this.directory = mkdtempSync(join(tmpdir(), "tarve-mcp-shots-"));
98
+ }
99
+
100
+ status(): SessionStatus {
101
+ return {
102
+ running: !!this.child && this.child.exitCode === null && this.child.signalCode === null,
103
+ connected: !!this.socket && !this.socket.destroyed,
104
+ ...(this.child?.pid ? { pid: this.child.pid } : {}),
105
+ ...(this.runtime ? { runtime: this.runtime } : {}),
106
+ ...(this.exitCode !== undefined ? { exitCode: this.exitCode } : {}),
107
+ starts: this.starts,
108
+ command: [this.launch.command, ...this.launch.args],
109
+ };
110
+ }
111
+
112
+ events(since?: number, limit?: number): { events: AppEvent[]; last: number } {
113
+ return { events: this.eventLog.since(since, limit), last: this.eventLog.last };
114
+ }
115
+
116
+ logs(since?: number, limit?: number): { lines: LogLine[]; last: number } {
117
+ return { lines: this.logLog.since(since, limit), last: this.logLog.last };
118
+ }
119
+
120
+ private listen(): Promise<void> {
121
+ return this.listening ??= new Promise((resolve, reject) => {
122
+ const server = createServer(socket => this.accept(socket));
123
+ server.on("error", reject);
124
+ server.listen(this.addr.address, () => { this.server = server; resolve(); });
125
+ });
126
+ }
127
+
128
+ private accept(socket: Socket): void {
129
+ socket.setEncoding("utf8");
130
+ socket.on("error", () => {});
131
+ let buffer = "";
132
+ let introduced = false;
133
+ socket.on("data", chunk => {
134
+ buffer += chunk;
135
+ let end: number;
136
+ while ((end = buffer.indexOf("\n")) >= 0) {
137
+ const line = buffer.slice(0, end);
138
+ buffer = buffer.slice(end + 1);
139
+ let message: Record<string, unknown>;
140
+ try { message = JSON.parse(line); } catch { continue; }
141
+ if (!introduced) {
142
+ // Only the app this session started knows the token.
143
+ if (message.type !== "hello" || message.token !== this.token) { socket.destroy(); return; }
144
+ introduced = true;
145
+ this.socket?.destroy();
146
+ this.socket = socket;
147
+ this.runtime = typeof message.runtime === "string" ? message.runtime : undefined;
148
+ this.connectWaiter?.resolve();
149
+ continue;
150
+ }
151
+ this.receive(message);
152
+ }
153
+ if (buffer.length > 1 << 26) socket.destroy();
154
+ });
155
+ socket.on("close", () => {
156
+ if (this.socket !== socket) return;
157
+ this.socket = undefined;
158
+ this.rejectPending(new Error("The app disconnected"));
159
+ });
160
+ }
161
+
162
+ private receive(message: Record<string, unknown>): void {
163
+ if (message.type === "event" && message.event && typeof message.event === "object") {
164
+ this.eventLog.push({ time: Date.now(), event: message.event as Record<string, unknown> });
165
+ return;
166
+ }
167
+ if (message.type === "closed") {
168
+ this.eventLog.push({ time: Date.now(), event: { type: "closed" } });
169
+ return;
170
+ }
171
+ const pending = typeof message.id === "number" ? this.pending.get(message.id) : undefined;
172
+ if (!pending) return;
173
+ this.pending.delete(message.id as number);
174
+ clearTimeout(pending.timer);
175
+ if (typeof message.error === "string") pending.reject(new Error(message.error));
176
+ else pending.resolve(message.result);
177
+ }
178
+
179
+ private rejectPending(error: Error): void {
180
+ for (const [id, pending] of this.pending) {
181
+ clearTimeout(pending.timer);
182
+ pending.reject(error);
183
+ this.pending.delete(id);
184
+ }
185
+ }
186
+
187
+ private recentErrors(): string {
188
+ const lines = this.logLog.since(0, 15).map(line => line.text);
189
+ return lines.length ? `\n${lines.join("\n")}` : "";
190
+ }
191
+
192
+ /** Starts the app (when it is not running) and resolves once it has connected. */
193
+ async start(): Promise<void> {
194
+ if (this.connected && this.status().running) return this.connected;
195
+ await this.listen();
196
+ this.starts++;
197
+ this.exitCode = undefined;
198
+ const { command, args, cwd, env } = this.launch;
199
+ const child = spawn(command, args, {
200
+ cwd,
201
+ env: { ...process.env, ...env, TARVE_CONTROL: this.addr.address, TARVE_CONTROL_TOKEN: this.token, TARVE_DEV: process.env.TARVE_DEV ?? "1" },
202
+ stdio: ["ignore", "pipe", "pipe"],
203
+ // Its own process group on Unix, so a stop reaches the runtime a CLI forwards to.
204
+ detached: process.platform !== "win32",
205
+ windowsHide: true,
206
+ // Windows runs `.cmd` shims (npx, bunx) through the shell only.
207
+ shell: process.platform === "win32" && /\.(cmd|bat)$/i.test(command),
208
+ });
209
+ this.child = child;
210
+ for (const stream of ["stdout", "stderr"] as const) {
211
+ let rest = "";
212
+ child[stream]?.setEncoding("utf8");
213
+ child[stream]?.on("data", (chunk: string) => {
214
+ const parts = (rest + chunk).split(/\r?\n/);
215
+ rest = parts.pop() ?? "";
216
+ for (const text of parts) this.logLog.push({ time: Date.now(), stream, text });
217
+ });
218
+ child[stream]?.on("end", () => { if (rest) this.logLog.push({ time: Date.now(), stream, text: rest }); rest = ""; });
219
+ }
220
+ const connected = new Promise<void>((resolve, reject) => {
221
+ const timer = setTimeout(() => fail(new Error(`The app did not connect within ${this.options.connectTimeoutMs} ms${this.recentErrors()}`)), this.options.connectTimeoutMs);
222
+ const fail = (error: Error) => { clearTimeout(timer); this.connectWaiter = undefined; reject(error); };
223
+ this.connectWaiter = { resolve: () => { clearTimeout(timer); this.connectWaiter = undefined; resolve(); }, reject: fail };
224
+ child.once("error", error => fail(new Error(`Could not start ${command}: ${error.message}`)));
225
+ child.once("exit", code => {
226
+ this.exitCode = code;
227
+ if (this.child === child) this.rejectPending(new Error(`The app exited (code ${code})`));
228
+ if (this.connectWaiter) fail(new Error(`The app exited (code ${code}) before it connected${this.recentErrors()}`));
229
+ });
230
+ });
231
+ this.connected = connected;
232
+ connected.catch(() => {});
233
+ return connected;
234
+ }
235
+
236
+ /** Sends a control request to the connected app. */
237
+ async request<T = unknown>(method: string, params: Record<string, unknown> = {}, timeoutMs = 15_000): Promise<T> {
238
+ // A tool called while the app is still starting waits for it to connect.
239
+ if (!this.socket && this.connectWaiter && this.connected) await this.connected;
240
+ const socket = this.socket;
241
+ if (!socket || socket.destroyed) {
242
+ const exited = this.exitCode !== undefined ? ` (it exited with code ${this.exitCode})` : "";
243
+ return Promise.reject(new Error(`The app is not connected${exited}: call reload to start it again`));
244
+ }
245
+ const id = this.nextId++;
246
+ return new Promise<T>((resolve, reject) => {
247
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`${method} timed out after ${timeoutMs} ms`)); }, timeoutMs);
248
+ this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject, timer });
249
+ socket.write(JSON.stringify({ id, method, params }) + "\n");
250
+ });
251
+ }
252
+
253
+ /** Stops the app: asks it to close, then ends its process tree. */
254
+ async stop(): Promise<void> {
255
+ const child = this.child;
256
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
257
+ const exited = new Promise<void>(resolve => child.once("exit", () => resolve()));
258
+ await this.request("close", {}, 1500).catch(() => {});
259
+ const closed = await Promise.race([exited.then(() => true), new Promise<boolean>(resolve => setTimeout(() => resolve(false), 3000))]);
260
+ if (!closed) {
261
+ this.kill(child);
262
+ await Promise.race([exited, new Promise(resolve => setTimeout(resolve, 3000))]);
263
+ }
264
+ }
265
+
266
+ private kill(child: ChildProcess): void {
267
+ if (!child.pid) return;
268
+ try {
269
+ if (process.platform === "win32") spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
270
+ else process.kill(-child.pid, "SIGKILL");
271
+ } catch {
272
+ child.kill("SIGKILL");
273
+ }
274
+ }
275
+
276
+ async restart(): Promise<void> {
277
+ await this.stop();
278
+ this.connected = undefined;
279
+ return this.start();
280
+ }
281
+
282
+ /** Stops the app and removes the socket and screenshots. */
283
+ async dispose(): Promise<void> {
284
+ await this.stop();
285
+ this.socket?.destroy();
286
+ await new Promise<void>(resolve => this.server ? this.server.close(() => resolve()) : resolve());
287
+ this.addr.cleanup();
288
+ rmSync(this.directory, { recursive: true, force: true });
289
+ }
290
+
291
+ /** Synchronous last resort when the server process exits. */
292
+ killNow(): void {
293
+ if (this.child && this.child.exitCode === null && this.child.signalCode === null) this.kill(this.child);
294
+ }
295
+ }