Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(mcp): keep JSON-RPC frames with U+2028/U+2029 whole on stdio
AdityaUmaled0d95ebe9dbf
diff --git a/scripts/mcp-server.ts b/scripts/mcp-server.tsindex df8d6adbb6..5074ca7e58 100644--- a/scripts/mcp-server.ts+++ b/scripts/mcp-server.ts@@ -1,9 +1,9 @@#!/usr/bin/env node// Model Context Protocol (MCP) server for OpenMausBot over JSON-RPC 2.0 stdio,// for external agents (Hermes, Claude Desktop, Cursor, etc.).-import readline from "node:readline";import { allowedServerOrigin, EXAMPLE_ADDRESS } from "../electron/server-address.mjs";import { isRecord, projectMessage } from "./mcp-message-projection.ts";+import { readStdioLines } from "../server/stdio-lines.ts";/** A server's base URL: https anywhere, http only on loopback or a private network (LAN, Tailscale). */export function validateBaseUrl(url: string): string {@@ -1368,15 +1368,9 @@ export async function processMcpMessage(* resolves): what `pnpm mcp`, dist-server/mcp-server.js and `openmausbot mcp` run. */export function runStdio(): Promise<void> {log("OpenMausBot MCP server running on stdio");- const rl = readline.createInterface({- input: process.stdin,- output: process.stdout,- terminal: false,- });-const activeRequests = new Set<Promise<void>>();- rl.on("line", (line) => {+ return new Promise((closed) => readStdioLines(process.stdin, (line) => {const task = (async () => {try {const response = await processMcpMessage(line);@@ -1391,9 +1385,7 @@ export function runStdio(): Promise<void> {task.finally(() => {activeRequests.delete(task);});- });-- return new Promise((closed) => rl.on("close", async () => {+ }, async () => {for (const controller of activeMcpControllers) {controller.abort(new DOMException("Request cancelled", "AbortError"));}@@ -1401,7 +1393,7 @@ export function runStdio(): Promise<void> {await Promise.allSettled(Array.from(activeRequests));}// Do not force an exit here: stdout may still be flushing the final- // JSON-RPC frame. With stdin and readline closed, Node exits naturally+ // JSON-RPC frame. With stdin closed, Node exits naturally// once that buffered write has drained.process.exitCode = 0;closed();diff --git a/server/connector-proxy.ts b/server/connector-proxy.tsindex d82d9e6ac5..0ae1b2d176 100644--- a/server/connector-proxy.ts+++ b/server/connector-proxy.ts@@ -1,6 +1,5 @@// Connection requests become OpenMausBot chat cards: the agent never authors an auth URL and credentials never pass// through its transcript. stdout is the MCP transport: never log there.-import readline from "node:readline";import { randomUUID } from "node:crypto";import { setTimeout as delay } from "node:timers/promises";import {@@ -20,6 +19,7 @@ import { AUTH_CONFIG_ID } from "../shared/connector-availability.ts";import { fitToolListResult } from "./mcp-tool-schema.ts";import { toolSchemaProfileFromEnv } from "./tool-schema-profile.ts";import { capToolListResult, toolLimitFromEnv } from "./tool-count-limit.ts";+import { readStdioLines } from "./stdio-lines.ts";type Json = Record<string, unknown>;@@ -394,8 +394,7 @@ async function handle(received: Json): Promise<void> {}}-const input = readline.createInterface({ input: process.stdin, terminal: false });-input.on("line", (line) => {+readStdioLines(process.stdin, (line) => {const trimmed = line.trim();if (!trimmed) return;let message: Json;@@ -430,5 +429,4 @@ input.on("line", (line) => {if (method === "tools/call") send(textResult(message.id, messageText, true));else send(jsonRpcError(message.id, messageText));});-});-input.on("close", () => process.exit(0));+}, () => process.exit(0));diff --git a/server/drivers/agents-proxy.test.ts b/server/drivers/agents-proxy.test.tsindex 1f8f0b00e3..68ee6cbabf 100644--- a/server/drivers/agents-proxy.test.ts+++ b/server/drivers/agents-proxy.test.ts@@ -953,6 +953,13 @@ describe("agents-proxy MCP surface", () => {execResponse = { exitCode: 0, stdout: "PDF_OK\n", stderr: "", timedOut: false };});+ it("answers a call whose arguments hold a raw U+2028 or U+2029, which JSON.stringify leaves unescaped", async () => {+ const command = "printf 'a\u2028b\u2029c'";+ const reply = await callTool("vm_exec", { command });+ expect(reply.result.content[0].text).toBe("exit code 0\n--- stdout ---\nPDF_OK");+ expect(lastExecBody).toEqual({ command });+ });+it("attach_file sends only the path and name, and tells the model the file is in the chat", async () => {const res = await callTool("attach_file", { path: "/home/cua/workspace/report.pdf", name: "Q3 report.pdf" });expect(res.result.isError).toBeFalsy();diff --git a/server/drivers/agents-proxy.ts b/server/drivers/agents-proxy.tsindex 48956db550..9483956577 100644--- a/server/drivers/agents-proxy.ts+++ b/server/drivers/agents-proxy.ts@@ -8,16 +8,15 @@// OMB_MAUSBOT "1" for the person's MausBot, the only bot shown its notification tools// OMB_AGENTS_TOOL_BRIDGE "1" lists a few tools and puts the rest behind find_tool and use_tool// scripts/bundle-server.mjs inlines agents-mcp and agents-catalog/-call/-client/-bridge into this file, which the harness spawns.-import readline from "node:readline";import { agentsMcp } from "./agents-mcp.ts";import type { Json } from "./agents-client.ts";+import { readStdioLines } from "../stdio-lines.ts";const handle = agentsMcp(process.env);const send = (msg: Json) => process.stdout.write(JSON.stringify(msg) + "\n");-const rl = readline.createInterface({ input: process.stdin, terminal: false });-rl.on("line", (line) => {+readStdioLines(process.stdin, (line) => {const t = line.trim();if (!t) return;let msg: Json;@@ -29,5 +28,4 @@ rl.on("line", (line) => {void handle(msg).then((reply) => { if (reply) send(reply); }, (e) => {if (msg.id !== undefined) send({ jsonrpc: "2.0", id: msg.id, error: { code: -32603, message: (e as Error).message } } as Json);});-});-rl.on("close", () => process.exit(0));+}, () => process.exit(0));diff --git a/server/drivers/dweb-proxy.ts b/server/drivers/dweb-proxy.tsindex e7d6e22afb..a80e4f6bcc 100644--- a/server/drivers/dweb-proxy.ts+++ b/server/drivers/dweb-proxy.ts@@ -1,7 +1,7 @@// dweb's HTTP API (the local OpenMaus network daemon) as MCP tools over stdio JSON-RPC 2.0: dweb_status,// dweb_repo_status, dweb_opencode_models, dweb_opencode_run (waits up to 5 min). Env:// DWEB_URL base URL of the local dweb daemon (http://127.0.0.1:49737)-import readline from "node:readline";+import { readStdioLines } from "../stdio-lines.ts";const DWEB = (process.env.DWEB_URL ?? "http://127.0.0.1:49737").replace(/\/+$/, "");const DWEB_DISPLAY = (() => {@@ -170,8 +170,7 @@ async function handle(msg: Json) {}}-const rl = readline.createInterface({ input: process.stdin, terminal: false });-rl.on("line", (line) => {+readStdioLines(process.stdin, (line) => {const t = line.trim();if (!t) return;let msg: Json;@@ -183,5 +182,4 @@ rl.on("line", (line) => {void handle(msg).catch((e) => {if (msg.id !== undefined) rpcErr(msg.id, -32603, (e as Error).message);});-});-rl.on("close", () => process.exit(0));+}, () => process.exit(0));diff --git a/server/drivers/phone-proxy.ts b/server/drivers/phone-proxy.tsindex 3f7d98981c..ddec20572a 100644--- a/server/drivers/phone-proxy.ts+++ b/server/drivers/phone-proxy.ts@@ -1,12 +1,12 @@// First-party Android phone MCP server: physical USB devices only (no emulators, wireless or network ADB).import { spawn } from "node:child_process";import { accessSync, constants, existsSync } from "node:fs";-import { createInterface } from "node:readline";import { delimiter, join } from "node:path";import { homedir } from "node:os";import { PHONE_STEP_TOOLS, type PhoneStepTool } from "../../shared/phone-steps.ts";import { CONTROL_ACT_WITHIN_MS, CONTROL_WAIT_MS } from "../control-client.ts";+import { readStdioLines } from "../stdio-lines.ts";type Json = Record<string, unknown>;type Device = { serial: string; state: string; model: string; connection: "usb" | "network" | "emulator" };@@ -735,8 +735,7 @@ async function handle(message: Json, ensureClaim: EnsureClaim) {if (process.argv[1] && existsSync(process.argv[1]) && /phone-proxy\.(?:ts|js)$/.test(process.argv[1])) {const ensureClaim = createPhoneClaim();- const lines = createInterface({ input: process.stdin, terminal: false });- lines.on("line", (line) => {+ readStdioLines(process.stdin, (line) => {try {const message = JSON.parse(line) as Json;void handle(message, ensureClaim).catch((error) => rpcError(message.id, -32603, error instanceof Error ? error.message : String(error)));diff --git a/server/mcp-gate.ts b/server/mcp-gate.tsindex abde8aedaa..ce36d0fb93 100644--- a/server/mcp-gate.ts+++ b/server/mcp-gate.ts@@ -2,7 +2,6 @@import { spawn } from "node:child_process";import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";import { join } from "node:path";-import { createInterface } from "node:readline";import { allowsTool, parseToolScope, type ToolScope } from "../shared/tool-scope.ts";import { bridgedCallTarget } from "./drivers/agents-bridge.ts";@@ -14,6 +13,7 @@ import { fitToolList } from "./mcp-tool-schema.ts";import { DEFAULT_RESULT_BUDGET, type HeldResult, trimResultText, trimStructured } from "./mcp-trim.ts";import { descendantsOf, signalTree, stopTree, type TreeProcess } from "./proc-descendants.ts";import { killCliTree } from "./procs.ts";+import { readStdioLines } from "./stdio-lines.ts";import { toolSchemaProfileFromEnv } from "./tool-schema-profile.ts";import { capToolListResult, toolLimitFromEnv } from "./tool-count-limit.ts";@@ -288,7 +288,7 @@ function callTarget(name: string, args: unknown): string | undefined {/** JSON-RPC string and numeric IDs are separate, even when their text is equal. */const pending = new Map<string, Pending>();-createInterface({ input: process.stdin }).on("line", (line) => {+readStdioLines(process.stdin, (line) => {let message: Json | undefined;if (line.trim()) {try {@@ -353,7 +353,7 @@ process.stdin.on("end", () => {setTimeout(() => leave(0), END_OF_INPUT_GRACE_MS);});-createInterface({ input: child.stdout }).on("line", (line) => {+readStdioLines(child.stdout, (line) => {if (!line.trim()) return;let message: Json | undefined;try {diff --git a/server/mcp-remote-proxy.ts b/server/mcp-remote-proxy.tsindex cfef61df33..f55806ff63 100644--- a/server/mcp-remote-proxy.ts+++ b/server/mcp-remote-proxy.ts@@ -1,6 +1,5 @@// The upstream handshake is OMB's own, never the engine's: an engine's client adds capability fields a strict server// refuses. stdout carries only protocol frames.-import { createInterface } from "node:readline";import { redactSecretsInText } from "../shared/redact.ts";import { allowsTool, parseToolScope, type ToolScope } from "../shared/tool-scope.ts";@@ -31,6 +30,7 @@ import { lenientToolValidator, schemaProblems } from "./mcp-schema-validator.ts"import { fitToolListResult } from "./mcp-tool-schema.ts";import { toolSchemaProfileFromEnv } from "./tool-schema-profile.ts";import { capToolListResult, toolLimitFromEnv } from "./tool-count-limit.ts";+import { readStdioLines } from "./stdio-lines.ts";import { APP_EXTENSION_KEY } from "../shared/app.ts";type Json = Record<string, unknown>;@@ -358,8 +358,7 @@ async function handle(message: Json): Promise<void> {} finally { pending.delete(id); }}-const input = createInterface({ input: process.stdin });-input.on("line", (line) => {+const input = readStdioLines(process.stdin, (line) => {if (closing || !line.trim()) return;let value: unknown;try { value = JSON.parse(line); } catch { error(null, -32700, "Invalid JSON-RPC frame"); return; }@@ -367,7 +366,7 @@ input.on("line", (line) => {const task = handle(value);tasks.add(task);void task.finally(() => tasks.delete(task));-});+}, () => { void shutdown(); });async function shutdown(): Promise<void> {if (closing) return;closing = true;@@ -378,6 +377,5 @@ async function shutdown(): Promise<void> {await client.close();process.exit(0);}-input.on("close", () => { void shutdown(); });process.on("SIGTERM", () => { void shutdown(); });process.on("SIGINT", () => { void shutdown(); });diff --git a/server/stdio-lines.test.ts b/server/stdio-lines.test.tsnew file mode 100644index 0000000000..26a95c3c31--- /dev/null+++ b/server/stdio-lines.test.ts@@ -0,0 +1,58 @@+import { PassThrough } from "node:stream";+import { describe, expect, it } from "vitest";+import { readStdioLines } from "./stdio-lines.ts";++function collect() {+ const input = new PassThrough();+ const lines: string[] = [];+ let closed = 0;+ const reader = readStdioLines(input, (line) => lines.push(line), () => { closed++; });+ return { input, lines, reader, closed: () => closed };+}++describe("readStdioLines", () => {+ it("keeps a frame whole when a string in it holds a raw U+2028 or U+2029", () => {+ const { input, lines } = collect();+ const frame = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { arguments: { command: "a b c" } } });+ input.write(`${frame}\n`);+ expect(lines).toEqual([frame]);+ expect(JSON.parse(lines[0]).params.arguments.command).toBe("a b c");+ });++ it("splits on \\n only, drops a trailing \\r, and joins a frame or character cut across chunks", () => {+ const { input, lines } = collect();+ const bytes = Buffer.from("{\"a\":\"é\"}\r\n{\"b\":1}\n\n");+ input.write(bytes.subarray(0, 7));+ input.write(bytes.subarray(7));+ expect(lines).toEqual(["{\"a\":\"é\"}", "{\"b\":1}", ""]);+ });++ it("delivers an unterminated last frame at end of input, then reports the close once", async () => {+ const { input, lines, closed } = collect();+ input.end("{\"last\":true}");+ await new Promise((resolve) => setImmediate(resolve));+ expect(lines).toEqual(["{\"last\":true}"]);+ expect(closed()).toBe(1);+ });++ it("delivers nothing more after close", () => {+ const { input, lines, reader, closed } = collect();+ input.write("one\n");+ reader.close();+ input.write("two\n");+ expect(lines).toEqual(["one"]);+ expect(closed()).toBe(1);+ });++ it("never delivers a line twice when a handler throws", () => {+ const input = new PassThrough();+ const lines: string[] = [];+ readStdioLines(input, (line) => {+ lines.push(line);+ if (line === "bad") throw new Error("handler failed");+ });+ expect(() => input.emit("data", Buffer.from("one\nbad\nthree"))).toThrow("handler failed");+ input.emit("data", Buffer.from("\n"));+ expect(lines).toEqual(["one", "bad", "three"]);+ });+});diff --git a/server/stdio-lines.ts b/server/stdio-lines.tsnew file mode 100644index 0000000000..bc7c8d5e7c--- /dev/null+++ b/server/stdio-lines.ts@@ -0,0 +1,39 @@+// Reads newline-delimited JSON-RPC, the MCP stdio framing, splitting only on "\n". node:readline also ends a line at+// U+2028 and U+2029, which JSON.stringify leaves unescaped inside strings, so it cuts such a frame into two halves+// that both fail JSON.parse.+import type { Readable } from "node:stream";+import { StringDecoder } from "node:string_decoder";++export function readStdioLines(input: Readable, onLine: (line: string) => void, onClose?: () => void): { close(): void } {+ const decoder = new StringDecoder("utf8");+ let rest = "";+ let open = true;+ const deliver = (line: string) => onLine(line.endsWith("\r") ? line.slice(0, -1) : line);+ const take = (text: string) => {+ const from = rest.length;+ rest += text;+ for (let newline = rest.indexOf("\n", from); open && newline !== -1; newline = rest.indexOf("\n")) {+ const line = rest.slice(0, newline);+ rest = rest.slice(newline + 1);+ deliver(line);+ }+ };+ const onData = (chunk: Buffer | string) => take(typeof chunk === "string" ? chunk : decoder.write(chunk));+ const onEnd = () => {+ take(decoder.end());+ if (open && rest) deliver(rest);+ close();+ };+ function close() {+ if (!open) return;+ open = false;+ rest = "";+ input.off("data", onData);+ input.off("end", onEnd);+ input.pause();+ onClose?.();+ }+ input.on("data", onData);+ input.on("end", onEnd);+ return { close };+}