Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Move from Grok Bot: the desktop app serves a move MCP over a quick tunnel
aivsomkar186fae705095
diff --git a/electron/managed-companion-guardian.d.mts b/electron/managed-companion-guardian.d.mtsnew file mode 100644index 0000000000..98bfa1ba1d--- /dev/null+++ b/electron/managed-companion-guardian.d.mts@@ -0,0 +1,2 @@+/** PATH and, on Windows, the OS plumbing variables: nothing else of the given environment. */+export function minimalCloudflaredEnvironment(environment?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): NodeJS.ProcessEnv;diff --git a/server/grok-move-mcp.test.ts b/server/grok-move-mcp.test.tsnew file mode 100644index 0000000000..d3fce95fb8--- /dev/null+++ b/server/grok-move-mcp.test.ts@@ -0,0 +1,103 @@+import { describe, expect, it } from "vitest";++import { GROK_EXPORT_FORMAT, GROK_EXPORT_MAX_CHARS, parseGrokExport } from "../shared/grok-import.ts";+import { createMoveInbox, MOVE_MAX_BYTES, MOVE_MAX_DOCUMENTS, moveMcp, type MoveLink } from "./grok-move-mcp.ts";++const TOKEN = "sk-abcdefghijklmnopqrstuvwx";+const EXPIRES = Date.UTC(2030, 0, 1);+const link = (): MoveLink => {+ let seq = 0;+ return { inbox: createMoveInbox(() => ++seq), expiresAt: EXPIRES };+};+const document = (name: string, extra: Record<string, unknown> = {}) => ({ format: GROK_EXPORT_FORMAT, version: 1, bots: [{ name, ...extra }] });+const rpc = (method: string, params?: unknown, id: number | null = 1) => ({ jsonrpc: "2.0", ...(id === null ? {} : { id }), method, ...(params ? { params } : {}) });+const call = (to: MoveLink, name: string, args: unknown = {}) => {+ const answer = moveMcp(rpc("tools/call", { name, arguments: args }), to, 7);+ expect(answer.status).toBe(200);+ const result = (answer.body as { result: { content: Array<{ text: string }>; isError?: true } }).result;+ return { text: result.content[0]!.text, refused: result.isError === true };+};++describe("the move MCP a Bot in Grok Bot talks to", () => {+ it("shakes hands on a version it knows, answers a ping and takes a notification without a reply", () => {+ const to = link();+ for (const [asked, given] of [["2025-06-18", "2025-06-18"], ["2025-03-26", "2025-03-26"], ["2024-11-05", "2024-11-05"], ["1999-01-01", "2025-06-18"], [undefined, "2025-06-18"]]) {+ expect(moveMcp(rpc("initialize", { protocolVersion: asked, capabilities: {} }), to)).toMatchObject({+ status: 200,+ body: { jsonrpc: "2.0", id: 1, result: { protocolVersion: given, capabilities: { tools: {} }, serverInfo: { name: "MausBot" } } },+ });+ }+ expect(moveMcp(rpc("notifications/initialized", undefined, null), to)).toEqual({ status: 202 });+ expect(moveMcp(rpc("ping"), to)).toEqual({ status: 200, body: { jsonrpc: "2.0", id: 1, result: {} } });+ });++ it("lists the two tools the published bot calls, with `document` as the one input", () => {+ const tools = (moveMcp(rpc("tools/list"), link()).body as { result: { tools: Array<{ name: string; inputSchema: { required?: string[] } }> } }).result.tools;+ expect(tools.map((tool) => tool.name)).toEqual(["move_status", "send_export"]);+ expect(tools[1]!.inputSchema.required).toEqual(["document"]);+ });++ it("keeps a sent Bot as the importer reads it, whether it came as an object or as JSON text, and counts it in the status", () => {+ const to = link();+ expect(call(to, "move_status").text).toBe("Connected to MausBot. 0 Bots received so far. This link works until 2030-01-01T00:00:00.000Z, while MausBot stays open. Send each Bot with send_export, one Bot per call.");+ const sent = call(to, "send_export", { document: {+ ...document("Tango", { memories: ["likes cheese", `the key is ${TOKEN}`], skills: [{ name: "Greet", instructions: "Say hello." }, { name: "Empty" }], extra: { anything: 1 } }),+ stray: "x",+ } });+ expect(sent).toEqual({ refused: false, text: "Arrived in MausBot. Tango: 1 skill, 0 routines, 2 memories. Left out: 1 skill without instructions. Send those again with their full text if the Bot has it. The person can now import it in MausBot, under Move from Grok Bot." });+ expect(call(to, "send_export", { document: JSON.stringify(document("Maus")) }).refused).toBe(false);+ expect(call(to, "send_export", { document: document("tango", { memories: ["more"] }) }).refused).toBe(false);++ expect(to.inbox.arrivals.map(({ seq, at, botNames }) => ({ seq, at, botNames }))).toEqual([+ { seq: 1, at: 7, botNames: ["Tango"] }, { seq: 2, at: 7, botNames: ["Maus"] }, { seq: 3, at: 7, botNames: ["tango"] },+ ]);+ const kept = to.inbox.arrivals[0]!.text;+ expect(kept).not.toMatch(/stray|anything|sk-abcdefghij/);+ expect(parseGrokExport(kept)).toMatchObject([{ name: "Tango", memories: ["likes cheese", expect.stringContaining("the key is")] }]);+ expect(call(to, "move_status").text).toContain("2 Bots received so far");+ });++ it("refuses what the importer refuses, with a fix the Bot can act on, and keeps none of it", () => {+ const to = link();+ const refusals: Array<[unknown, string]> = [+ [{ document: document("Tango", { api_key: "real-secret-value" }) }, "passwords or keys in these fields"],+ [{ document: { ...document("Tango"), version: 2 } }, "Send the document with \"version\": 1"],+ [{ document: `{"format":"${GROK_EXPORT_FORMAT}","bots":[{"name":"Tango"` }, "cut off"],+ [{ document: { hello: "there" } }, `that is not a ${GROK_EXPORT_FORMAT} document`],+ [{ document: "x".repeat(GROK_EXPORT_MAX_CHARS + 1) }, "larger than 4 MB"],+ [{ document: 5 }, "as `document`"],+ [{}, "as `document`"],+ [undefined, "as `document`"],+ ];+ for (const [args, says] of refusals) {+ const answer = call(to, "send_export", args);+ expect(answer.refused, says).toBe(true);+ expect(answer.text).toContain("Nothing was saved");+ expect(answer.text).toContain(says);+ }+ expect(to.inbox.arrivals).toEqual([]);+ });++ it("stops taking Bots at a hundred documents, and at sixteen megabytes", () => {+ const full = link();+ for (let count = 0; count < MOVE_MAX_DOCUMENTS; count += 1) expect(call(full, "send_export", { document: document(`Bot ${count}`) }).refused).toBe(false);+ expect(call(full, "send_export", { document: document("One more") })).toMatchObject({ refused: true, text: expect.stringContaining("taken all it can hold") });+ expect(full.inbox.arrivals).toHaveLength(MOVE_MAX_DOCUMENTS);++ const heavy = link();+ const big = "word ".repeat(700_000);+ const fits = Math.floor(MOVE_MAX_BYTES / Buffer.byteLength(JSON.stringify(document("Big", { instructions: big }))));+ for (let count = 0; count < fits; count += 1) expect(call(heavy, "send_export", { document: document("Big", { instructions: big }) }).refused, String(count)).toBe(false);+ expect(call(heavy, "send_export", { document: document("Big", { instructions: big }) }).refused).toBe(true);+ expect(heavy.inbox.arrivals).toHaveLength(fits);+ });++ it("answers anything that is not one known request with a JSON-RPC error", () => {+ const to = link();+ expect(moveMcp(rpc("tools/call", { name: "read_exports" }), to)).toMatchObject({ status: 200, body: { id: 1, error: { code: -32602 } } });+ expect(moveMcp(rpc("resources/list"), to)).toMatchObject({ status: 200, body: { id: 1, error: { code: -32601 } } });+ for (const junk of [null, 5, "hi", [], [rpc("ping")], { jsonrpc: "1.0", id: 1, method: "ping" }, { jsonrpc: "2.0", id: 1, result: {} }, { jsonrpc: "2.0", id: {}, method: "ping" }]) {+ expect(moveMcp(junk, to), JSON.stringify(junk)).toMatchObject({ status: 400, body: { id: null, error: { code: -32600 } } });+ }+ });+});diff --git a/server/grok-move-mcp.ts b/server/grok-move-mcp.tsnew file mode 100644index 0000000000..47c0bff8f2--- /dev/null+++ b/server/grok-move-mcp.ts@@ -0,0 +1,152 @@+// Moving from Grok Bot over a connector: the MCP a Bot in Grok Bot talks to. Grok Bot calls it from its own cloud+// computer, so every message here is untrusted internet input, and holding the link's key is all a caller has.+// Security: a caller can add exports and read a count, never read an export back. An export is kept as the importer+// reads it: refused whole when it holds credential-looking fields, token-shaped text redacted, anything the importer+// does not read dropped. Nothing is written to disk, and nothing is imported until the person chooses to.+import { z } from "zod";++import { GROK_EXPORT_FORMAT, GrokImportError, grokExportDocument, parseGrokExport, type GrokBot } from "../shared/grok-import.ts";++export const MOVE_MAX_DOCUMENTS = 100;+export const MOVE_MAX_BYTES = 16 * 1024 * 1024;+const PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];+const SPLIT = "Split the Bot into several documents with the same bot name, each complete and valid on its own and holding the part the others do not, and send each one with send_export.";++export interface MoveArrival { seq: number; at: number; text: string; botNames: string[] }++/** What one link has taken in. `seq` numbers its arrivals; the caller owns the counter so numbers never repeat across links. */+export interface MoveInbox {+ readonly arrivals: readonly MoveArrival[];+ /** False when the link has taken all it may hold. */+ add(text: string, botNames: string[], at: number): boolean;+}++export function createMoveInbox(seq: () => number): MoveInbox {+ const arrivals: MoveArrival[] = [];+ let bytes = 0;+ return {+ arrivals,+ add(text, botNames, at) {+ const size = Buffer.byteLength(text);+ if (arrivals.length >= MOVE_MAX_DOCUMENTS || bytes + size > MOVE_MAX_BYTES) return false;+ bytes += size;+ arrivals.push({ seq: seq(), at, text, botNames });+ return true;+ },+ };+}++// The names and the `document` input are fixed: the published MausBot bot in Grok Bot calls them.+const TOOLS = [+ {+ name: "move_status",+ description: "Check the link to MausBot: whether it works, how many Bots have arrived so far, and when it stops working. Call this first.",+ inputSchema: { type: "object", properties: {}, additionalProperties: false },+ },+ {+ name: "send_export",+ description: `Send one Bot's setup to MausBot. \`document\` is a ${GROK_EXPORT_FORMAT} document: {"format": "${GROK_EXPORT_FORMAT}", "version": 1, "bots": [{name, title, instructions, memories, user_facts, skills, routines, apps}]}. Send one Bot per call, with every skill and routine in full. Never include passwords, API keys, tokens or cookies: a document that has them is refused. A document over 4 MB is refused: split it into several documents with the same bot name. The person sees what arrived in MausBot and chooses what to import; nothing changes in Grok Bot.`,+ inputSchema: {+ type: "object",+ properties: { document: { type: "object", description: `The ${GROK_EXPORT_FORMAT} document.` } },+ required: ["document"],+ },+ },+];++type ToolResult = { content: Array<{ type: "text"; text: string }>; isError?: true };+const said = (text: string): ToolResult => ({ content: [{ type: "text", text }] });+const refused = (text: string): ToolResult => ({ content: [{ type: "text", text }], isError: true });+const plural = (count: number, one: string, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;++function refusal(error: GrokImportError): string {+ switch (error.code) {+ case "credentials":+ return `Nothing was saved: the document has passwords or keys in these fields: ${error.keys.join(", ")}. Take those fields out and send it again.`;+ case "tooLarge":+ return `Nothing was saved: the document is larger than 4 MB. ${SPLIT}`;+ case "cutOff":+ return `Nothing was saved: the document is cut off. Send it again whole. If it is too long, do this: ${SPLIT}`;+ case "newerVersion":+ return `Nothing was saved: MausBot reads version 1 of ${GROK_EXPORT_FORMAT}. Send the document with "version": 1.`;+ case "notExport":+ case "unusable":+ return `Nothing was saved: that is not a ${GROK_EXPORT_FORMAT} document. Send {"format": "${GROK_EXPORT_FORMAT}", "version": 1, "bots": [{"name": ..., "instructions": ..., "memories": [...], "skills": [...], "routines": [...]}]} as \`document\`, with a name for each Bot.`;+ }+}++/** What MausBot can use of one Bot, and what it cannot: a skill or routine without its text creates nothing. */+function received(bot: GrokBot): string {+ const skills = bot.skills.filter((skill) => skill.instructions).length;+ const routines = bot.routines.filter((routine) => routine.instruction).length;+ const left = [+ skills < bot.skills.length ? `${plural(bot.skills.length - skills, "skill")} without instructions` : "",+ routines < bot.routines.length ? `${plural(bot.routines.length - routines, "routine")} without an instruction` : "",+ ].filter(Boolean);+ return `${bot.name}: ${plural(skills, "skill")}, ${plural(routines, "routine")}, ${plural(bot.memories.length + bot.userFacts.length, "memory", "memories")}.`+ + (left.length ? ` Left out: ${left.join(" and ")}. Send those again with their full text if the Bot has it.` : "");+}++function sendExport(args: unknown, inbox: MoveInbox, now: number): ToolResult {+ const document = (args as { document?: unknown } | null | undefined)?.document;+ // A model often sends an object argument as JSON text; the parser reads both.+ const text = typeof document === "string" ? document : document && typeof document === "object" ? JSON.stringify(document) : "";+ if (!text) return refused(`Nothing was saved: send the ${GROK_EXPORT_FORMAT} document as \`document\`.`);+ let bots: GrokBot[];+ try {+ bots = parseGrokExport(text);+ } catch (error) {+ if (error instanceof GrokImportError) return refused(refusal(error));+ throw error;+ }+ if (!inbox.add(JSON.stringify(grokExportDocument(bots)), bots.map((bot) => bot.name), now)) {+ return refused("Nothing was saved: this link has taken all it can hold. Tell the person to import what has arrived in MausBot, then to make a new link there for the rest.");+ }+ return said(`Arrived in MausBot. ${bots.map(received).join(" ")} The person can now import ${bots.length === 1 ? "it" : "them"} in MausBot, under Move from Grok Bot.`);+}++function moveStatus(link: MoveLink): ToolResult {+ const names = new Set(link.inbox.arrivals.flatMap((arrival) => arrival.botNames).map((name) => name.toLowerCase()));+ return said(`Connected to MausBot. ${plural(names.size, "Bot")} received so far. This link works until ${new Date(link.expiresAt).toISOString()}, while MausBot stays open. Send each Bot with send_export, one Bot per call.`);+}++const rpcSchema = z.object({+ jsonrpc: z.literal("2.0"),+ id: z.union([z.string(), z.number()]).optional(),+ method: z.string().max(128),+ params: z.record(z.string(), z.unknown()).optional(),+});++export interface MoveLink { inbox: MoveInbox; expiresAt: number }+/** An HTTP answer: `body` is JSON, and no body means an empty reply. */+export interface MoveMcpAnswer { status: number; body?: unknown }++export const moveRpcError = (id: string | number | null, code: number, message: string, status = 200): MoveMcpAnswer =>+ ({ status, body: { jsonrpc: "2.0", id, error: { code, message } } });++/** One parsed JSON message of MCP over Streamable HTTP: one JSON answer per request, no session and no stream. */+export function moveMcp(message: unknown, link: MoveLink, now = Date.now()): MoveMcpAnswer {+ const parsed = rpcSchema.safeParse(message);+ // A response, a batch, or anything else that is not one request: nothing to answer.+ if (!parsed.success) return moveRpcError(null, -32600, "Send one JSON-RPC 2.0 request", 400);+ const { id, method, params } = parsed.data;+ if (id === undefined) return { status: 202 };+ const result = (value: unknown): MoveMcpAnswer => ({ status: 200, body: { jsonrpc: "2.0", id, result: value } });+ if (method === "initialize") {+ const asked = params?.protocolVersion;+ return result({+ protocolVersion: typeof asked === "string" && PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],+ capabilities: { tools: {} },+ serverInfo: { name: "MausBot", version: "1.0.0" },+ instructions: "Moves Bots from Grok Bot to MausBot. Call move_status, then send_export once per Bot.",+ });+ }+ if (method === "ping") return result({});+ if (method === "tools/list") return result({ tools: TOOLS });+ if (method === "tools/call") {+ if (params?.name === "move_status") return result(moveStatus(link));+ if (params?.name === "send_export") return result(sendExport(params.arguments, link.inbox, now));+ return moveRpcError(id, -32602, "Unknown tool. The tools are move_status and send_export.");+ }+ return moveRpcError(id, -32601, "Method not found");+}diff --git a/server/grok-move-tunnel.test.ts b/server/grok-move-tunnel.test.tsnew file mode 100644index 0000000000..bbfc69ce0d--- /dev/null+++ b/server/grok-move-tunnel.test.ts@@ -0,0 +1,143 @@+import { spawn, type ChildProcess } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { GROK_EXPORT_FORMAT, GROK_EXPORT_MAX_CHARS } from "../shared/grok-import.ts";+import { createGrokMove, grokMoveCloudflared, type GrokMove } from "./grok-move-tunnel.ts";++const ADDRESS = "https://quiet-test-words.trycloudflare.com";+const moves: GrokMove[] = [];+afterEach(() => {+ for (const move of moves.splice(0)) move.end();+});++/** A stand-in cloudflared: a real child process that prints what cloudflared prints and then stays up. */+function harness(options: { says?: string; ttlMs?: number; startTimeoutMs?: number; now?: () => number } = {}) {+ const children: ChildProcess[] = [];+ const started: string[][] = [];+ const says = options.says ?? `INF | ${ADDRESS} |\\nINF Registered tunnel connection connIndex=0`;+ const move = createGrokMove({+ binary: () => "/fake/cloudflared",+ spawn: ((_binary: string, args: string[], spawnOptions: object) => {+ started.push(args);+ const child = spawn(process.execPath, ["-e", `process.stderr.write("${says}\\n"); setInterval(() => {}, 1000);`], spawnOptions);+ children.push(child);+ return child;+ }) as unknown as typeof spawn,+ ...options,+ });+ moves.push(move);+ /** The listener cloudflared was pointed at, reached the way cloudflared reaches it. */+ const post = (connectorUrl: string, body: unknown, init: { method?: string; type?: string; path?: string } = {}) =>+ fetch(`${started.at(-1)!.at(-1)}${init.path ?? new URL(connectorUrl).pathname}`, {+ method: init.method ?? "POST",+ ...(init.method === "GET" ? {} : { headers: { "content-type": init.type ?? "application/json" }, body: typeof body === "string" ? body : JSON.stringify(body) }),+ });+ return { move, children, started, post };+}+const send = (name: string) => ({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "send_export", arguments: { document: { format: GROK_EXPORT_FORMAT, version: 1, bots: [{ name, memories: ["likes cheese"] }] } } } });+const gone = (child: ChildProcess) => new Promise<void>((done) => (child.exitCode !== null || child.signalCode !== null ? done() : child.once("exit", () => done())));++describe("the Grok Bot link", () => {+ it("opens one quick tunnel to a listener of its own, hands over what a Bot sent, and closes both when ended", async () => {+ const { move, children, started, post } = harness();+ expect(move.look(0)).toEqual({ available: true, arrived: [] });+ const [made, again] = await Promise.all([move.connect(), move.connect()]);+ expect(made.connectorUrl).toMatch(new RegExp(`^${ADDRESS}/mcp/move/[\\w-]{43}$`));+ expect(made.expiresAt).toBeGreaterThan(Date.now() + 59 * 60_000);+ expect(again).toEqual(made);+ expect(await move.connect()).toEqual(made);+ expect(started).toHaveLength(1);+ expect(started[0]).toEqual(["--config", expect.stringMatching(/config\.yml$/), "tunnel", "--no-autoupdate", "--url", expect.stringMatching(/^http:\/\/127\.0\.0\.1:\d+$/)]);++ const sent = await post(made.connectorUrl!, send("Tango"));+ expect(sent.status).toBe(200);+ expect(sent.headers.get("content-type")).toBe("application/json");+ expect(await sent.json()).toMatchObject({ result: { content: [{ text: expect.stringContaining("Arrived in MausBot. Tango") }] } });+ expect((await post(made.connectorUrl!, { jsonrpc: "2.0", method: "notifications/initialized" })).status).toBe(202);+ const looked = move.look(0);+ expect(looked).toMatchObject({ connectorUrl: made.connectorUrl, arrived: [{ seq: 1 }] });+ expect(JSON.parse(looked.arrived[0]!.text)).toMatchObject({ bots: [{ name: "Tango", memories: ["likes cheese"] }] });+ expect(move.look(1).arrived).toEqual([]);++ expect(move.end()).toEqual({ available: true, arrived: [] });+ await gone(children[0]!);+ await expect(post(made.connectorUrl!, send("Late"))).rejects.toThrow();+ });++ it("answers the public address only at the keyed path, only to a JSON POST, and only up to the size cap", async () => {+ const { move, post } = harness();+ const { connectorUrl } = await move.connect();+ const path = new URL(connectorUrl!).pathname;+ for (const wrong of ["/", "/mcp/move/", `/mcp/move/${"A".repeat(43)}`, `${path}/`, `${path}x`, path.slice(0, -1), "/api/status", "/api/setup-import/grok/connector", `/x${path}`]) {+ const answer = await post(connectorUrl!, send("Tango"), { path: wrong });+ expect(answer.status, wrong).toBe(404);+ expect(await answer.json()).toEqual({ error: "not found" });+ }+ expect((await post(connectorUrl!, "", { method: "GET", path: "/" })).status).toBe(404);+ for (const method of ["GET", "DELETE", "PUT"]) {+ const answer = await post(connectorUrl!, send("Tango"), { method });+ expect(answer.status, method).toBe(405);+ expect(answer.headers.get("allow")).toBe("POST");+ }+ expect((await post(connectorUrl!, send("Tango"), { type: "text/plain" })).status).toBe(415);+ expect(await (await post(connectorUrl!, "{not json")).json()).toMatchObject({ error: { code: -32700 } });+ const huge = await post(connectorUrl!, JSON.stringify(send("x".repeat(GROK_EXPORT_MAX_CHARS + 70_000))));+ expect(huge.status).toBe(413);+ expect(move.look(0).arrived).toEqual([]);+ // The query is no part of the key.+ expect((await post(connectorUrl!, send("Tango"), { path: `${path}?x=1` })).status).toBe(200);+ });++ it("says the link stopped when cloudflared exits or the hour runs out, keeps what arrived, and numbers a new link's arrivals after the old", async () => {+ const { move, children, post } = harness();+ const first = await move.connect();+ await post(first.connectorUrl!, send("Tango"));+ children[0]!.kill();+ await gone(children[0]!);+ await new Promise((done) => setTimeout(done, 20));+ expect(move.look(0)).toMatchObject({ available: true, stopped: true, arrived: [{ seq: 1 }] });+ expect(move.look(0).connectorUrl).toBeUndefined();+ await expect(post(first.connectorUrl!, send("Late"))).rejects.toThrow();++ const second = await move.connect();+ expect(second.connectorUrl).not.toBe(first.connectorUrl);+ expect(second).toMatchObject({ available: true, arrived: [] });+ expect(second.stopped).toBeUndefined();+ await post(second.connectorUrl!, send("Maus"));+ expect(move.look(1).arrived.map((arrival) => arrival.seq)).toEqual([2]);++ const brief = harness({ ttlMs: 60 });+ const short = await brief.move.connect();+ await gone(brief.children[0]!);+ expect(brief.move.look(0)).toEqual({ available: true, stopped: true, arrived: [] });+ await expect(brief.post(short.connectorUrl!, send("Late"))).rejects.toThrow();+ });++ it("makes no link without cloudflared, and fails plainly, with nothing left running, when the tunnel never opens", async () => {+ const none = createGrokMove({ binary: () => null });+ expect(await none.connect()).toEqual({ available: false, arrived: [] });+ // Packaged, only the copy shipped in Resources counts.+ const resources = mkdtempSync(join(tmpdir(), "omb-grok-move-test-"));+ const shipped = join(resources, "cloudflared", process.platform === "win32" ? "cloudflared.exe" : "cloudflared");+ expect(grokMoveCloudflared({ PATH: dirname(process.execPath), OMB_CLOUDFLARED_PATH: process.execPath, OMB_RESOURCES_PATH: resources }, false)).toBeNull();+ mkdirSync(dirname(shipped));+ writeFileSync(shipped, "");+ expect(grokMoveCloudflared({ OMB_RESOURCES_PATH: resources }, false)).toBe(shipped);+ rmSync(resources, { recursive: true, force: true });+ expect(grokMoveCloudflared({ PATH: "/nonexistent", OMB_CLOUDFLARED_PATH: process.execPath }, true)).toBe(process.execPath);++ const silent = harness({ says: "INF Requesting new quick Tunnel", startTimeoutMs: 300 });+ await expect(silent.move.connect()).rejects.toThrow("The link could not be made: cloudflared did not open a tunnel in time.");+ await gone(silent.children[0]!);+ expect(silent.move.look(0)).toEqual({ available: true, arrived: [] });++ const ended = harness();+ const opening = ended.move.connect();+ ended.move.end();+ expect(await opening).toEqual({ available: true, arrived: [] });+ await gone(ended.children[0]!);+ });+});diff --git a/server/grok-move-tunnel.ts b/server/grok-move-tunnel.tsnew file mode 100644index 0000000000..a58f71a7c5--- /dev/null+++ b/server/grok-move-tunnel.ts@@ -0,0 +1,195 @@+// Moving from Grok Bot over a connector: the link. Grok Bot runs a connector from its own cloud computer, which cannot+// reach this one, so while the person asks for it this opens a second listener on loopback that serves the move MCP+// (grok-move-mcp.ts) and nothing else, and a Cloudflare quick tunnel from the bundled cloudflared to that listener.+// Security: the main API is never tunnelled. The public address answers only POST /mcp/move/<256-bit key>, and the+// key lives in this process's memory and in the address shown to the app's own window. The link ends when the person+// ends it, after an hour, when the app quits or when cloudflared exits; what arrived stays in memory until then.+import { spawn, type ChildProcess } from "node:child_process";+import { randomBytes, timingSafeEqual } from "node:crypto";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";+import type { AddressInfo } from "node:net";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import { minimalCloudflaredEnvironment } from "../electron/managed-companion-guardian.mjs";+import { resolveCloudflaredBinary } from "../electron/managed-companion-tunnel.mjs";+import { GROK_EXPORT_MAX_CHARS } from "../shared/grok-import.ts";+import { createMoveInbox, moveMcp, moveRpcError, type MoveInbox, type MoveMcpAnswer } from "./grok-move-mcp.ts";+import { readBody } from "./harness/http.ts";++export const MOVE_TTL_MS = 60 * 60 * 1000;+export const MOVE_PATH_PREFIX = "/mcp/move/";+/** A document at the importer's cap inside a JSON-RPC envelope. */+const BODY_MAX = GROK_EXPORT_MAX_CHARS + 64 * 1024;+const START_TIMEOUT_MS = 45_000;++export interface GrokConnector {+ /** False where there is no cloudflared to open a link with. */+ available: boolean;+ connectorUrl?: string;+ expiresAt?: number;+ /** The link was made and has stopped working: its hour ran out, or cloudflared exited. */+ stopped?: true;+ /** What arrived after the asked-for `seq`, oldest first, each as the text of one export. */+ arrived: Array<{ seq: number; at: number; text: string }>;+}++export interface GrokMove {+ /** The link to paste into Grok Bot: the one already made while it still works, so pasting it once is enough. */+ connect(): Promise<GrokConnector>;+ look(after: number): GrokConnector;+ end(): GrokConnector;+}++/** The desktop app's own cloudflared: the one shipped in Resources when packaged; from source, the staged copy or PATH. */+export function grokMoveCloudflared(env: NodeJS.ProcessEnv = process.env, fromSource = import.meta.url.endsWith(".ts")): string | null {+ return resolveCloudflaredBinary(fromSource+ ? { isPackaged: false, appPath: resolve(dirname(fileURLToPath(import.meta.url)), ".."), environment: env }+ : { isPackaged: true, resourcesPath: env.OMB_RESOURCES_PATH });+}++interface Link { connectorUrl: string; expiresAt: number; inbox: MoveInbox; live: boolean; close(): void }++function send(res: ServerResponse, answer: MoveMcpAnswer, headers: Record<string, string> = {}) {+ const data = answer.body === undefined ? "" : JSON.stringify(answer.body);+ res.writeHead(answer.status, { ...(data ? { "content-type": "application/json" } : {}), "cache-control": "no-store", ...headers });+ res.end(data);+}++/** The whole public surface. Anything but the exact keyed path is a 404 that says nothing about what is here. */+export function moveListener(path: string, link: () => { inbox: MoveInbox; expiresAt: number } | null, now: () => number) {+ const expected = Buffer.from(path);+ return async (req: IncomingMessage, res: ServerResponse) => {+ try {+ const asked = Buffer.from((req.url ?? "").split("?")[0]!);+ const current = link();+ if (asked.length !== expected.length || !timingSafeEqual(asked, expected) || !current || current.expiresAt <= now()) {+ return send(res, { status: 404, body: { error: "not found" } });+ }+ if (req.method !== "POST") return send(res, { status: 405, body: { error: "method not allowed" } }, { allow: "POST" });+ if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {+ return send(res, { status: 415, body: { error: "content-type must be application/json" } });+ }+ let message: unknown;+ try {+ message = await readBody(req, BODY_MAX);+ } catch (error) {+ return send(res, (error as { status?: number }).status === 413+ ? moveRpcError(null, -32600, "The request is larger than 4 MB. Split the Bot into several documents with the same bot name and send each one with send_export.", 413)+ : moveRpcError(null, -32700, "Parse error", 400));+ }+ send(res, moveMcp(message, current, now()));+ } catch {+ if (!res.headersSent) send(res, { status: 500, body: { error: "internal error" } });+ else res.destroy();+ }+ };+}++/** Resolves with the public address once cloudflared has it and has a connection to Cloudflare's edge. */+function tunnelAddress(child: ChildProcess, timeoutMs: number): Promise<string> {+ return new Promise((done, fail) => {+ let log = "";+ const timer = setTimeout(() => fail(new Error("cloudflared did not open a tunnel in time")), timeoutMs);+ const settle = (run: () => void) => { clearTimeout(timer); run(); };+ child.stderr?.setEncoding("utf8").on("data", (chunk: string) => {+ // Kept draining after the address is found so cloudflared never blocks on a full pipe.+ if (log.length > 64_000) return;+ log += chunk;+ const address = log.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/)?.[0];+ if (address && log.includes("Registered tunnel connection")) settle(() => done(address));+ });+ child.once("error", (error) => settle(() => fail(new Error(`cloudflared could not start: ${error.message}`))));+ child.once("exit", (code) => settle(() => {+ const why = log.trim().split("\n").at(-1)?.replace(/^\S+ (ERR|INF|WRN) /, "").slice(0, 300);+ fail(new Error(`cloudflared exited before the tunnel opened (exit ${code ?? "signal"}${why ? `: ${why}` : ""})`));+ }));+ });+}++export function createGrokMove(options: {+ binary?: () => string | null;+ spawn?: typeof spawn;+ now?: () => number;+ ttlMs?: number;+ startTimeoutMs?: number;+} = {}): GrokMove {+ const now = options.now ?? Date.now;+ const binary = options.binary ?? grokMoveCloudflared;+ let link: Link | null = null;+ let starting: Promise<Link> | null = null;+ /** Bumped by end(), so a link still opening when the person ends it is closed as soon as it opens. */+ let ended = 0;+ let seq = 0;++ const state = (after = 0): GrokConnector => ({+ available: Boolean(binary()),+ ...(link?.live ? { connectorUrl: link.connectorUrl, expiresAt: link.expiresAt } : {}),+ ...(link && !link.live ? { stopped: true as const } : {}),+ arrived: (link?.inbox.arrivals ?? []).filter((arrival) => arrival.seq > after).map(({ seq, at, text }) => ({ seq, at, text })),+ });++ async function open(binaryPath: string): Promise<Link> {+ const path = `${MOVE_PATH_PREFIX}${randomBytes(32).toString("base64url")}`;+ const expiresAt = now() + (options.ttlMs ?? MOVE_TTL_MS);+ const inbox = createMoveInbox(() => ++seq);+ let made: Link | null = null;+ let child: ChildProcess | undefined;+ let timer: NodeJS.Timeout | undefined;+ // A config of its own, so a ~/.cloudflared/config.yml or /etc/cloudflared one with ingress rules is never read.+ const runtime = mkdtempSync(join(tmpdir(), "omb-grok-move-"));+ const server: Server = createServer(moveListener(path, () => ({ inbox, expiresAt }), now));+ const close = () => {+ if (made) made.live = false;+ clearTimeout(timer);+ process.off("exit", close);+ child?.kill();+ server.close();+ server.closeAllConnections();+ rmSync(runtime, { recursive: true, force: true });+ };+ process.once("exit", close);+ try {+ await new Promise<void>((ready, fail) => server.once("error", fail).listen(0, "127.0.0.1", ready));+ const config = join(runtime, "config.yml");+ writeFileSync(config, "no-autoupdate: true\n");+ child = (options.spawn ?? spawn)(+ binaryPath,+ ["--config", config, "tunnel", "--no-autoupdate", "--url", `http://127.0.0.1:${(server.address() as AddressInfo).port}`],+ { stdio: ["ignore", "ignore", "pipe"], env: minimalCloudflaredEnvironment(), windowsHide: true },+ );+ const address = await tunnelAddress(child, options.startTimeoutMs ?? START_TIMEOUT_MS);+ made = { connectorUrl: `${address}${path}`, expiresAt, inbox, live: true, close };+ child.once("exit", close);+ timer = setTimeout(close, Math.max(0, expiresAt - now()));+ timer.unref();+ return made;+ } catch (error) {+ close();+ throw new Error(`The link could not be made: ${error instanceof Error ? error.message : String(error)}.`);+ }+ }++ return {+ async connect() {+ const binaryPath = binary();+ if (!binaryPath) return state();+ if (link?.live) return state();+ const round = ended;+ starting ??= open(binaryPath).finally(() => { starting = null; });+ const opened = await starting;+ if (round !== ended) opened.close();+ else if (!link?.live) link = opened;+ return state();+ },+ look: (after) => state(after),+ end() {+ ended += 1;+ link?.close();+ link = null;+ return state();+ },+ };+}diff --git a/server/routes/setup-import.test.ts b/server/routes/setup-import.test.tsindex 509f8a8138..8b92593fee 100644--- a/server/routes/setup-import.test.ts+++ b/server/routes/setup-import.test.ts@@ -7,6 +7,7 @@ import { dirname, join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { DATA_DIR, type AppConfig } from "../config.ts";+import type { GrokConnector, GrokMove } from "../grok-move-tunnel.ts";import { json, readBody } from "../harness/http.ts";import { IMPORTED_SKILLS_DIR, importedSkillsFor } from "../imported-skills.ts";import type { RequestAuth } from "../request-auth.ts";@@ -43,7 +44,20 @@ function fixtureHome() {return home;}-async function serve({ local = true, home = fixtureHome(), dataDir }: { local?: boolean; home?: string; dataDir?: string } = {}) {+/** A link that needs no cloudflared: the routes only pass along what it answers. */+function fakeGrokMove(available = true) {+ const calls: string[] = [];+ let open = false;+ const state = (arrived: GrokConnector["arrived"] = []): GrokConnector => ({ available, ...(open ? { connectorUrl: "https://words.trycloudflare.com/mcp/move/key", expiresAt: 9 } : {}), arrived });+ const move: GrokMove = {+ connect: async () => { calls.push("connect"); open = available; return state(); },+ look: (after) => { calls.push(`look ${after}`); return state(open && after < 1 ? [{ seq: 1, at: 5, text: "{}" }] : []); },+ end: () => { calls.push("end"); open = false; return state(); },+ };+ return { move, calls };+}++async function serve({ local = true, home = fixtureHome(), dataDir, grokMove = fakeGrokMove(false).move }: { local?: boolean; home?: string; dataDir?: string; grokMove?: GrokMove } = {}) {const cfg = { mcpServers: {} } as Pick<AppConfig, "mcpServers" | "features">;const bot = { id: `bot-${randomUUID().slice(0, 8)}` };let busy = false;@@ -55,6 +69,7 @@ async function serve({ local = true, home = fixtureHome(), dataDir }: { local?:persistMcpServers: (next) => { cfg.mcpServers = next; },machine: () => ({ ...thisMachine(), home, platform: "darwin", env: {} }),...(dataDir ? { dataDir } : {}),+ grokMove,})];const server = createServer(async (req, res) => {const url = new URL(req.url ?? "/", "http://localhost");@@ -88,6 +103,42 @@ describe("the setup import routes", () => {expect(await found.json()).toMatchObject({ files: [{ name: "grok-bot-export-drew.json", text: "reply" }], bots: [] });});+ it("opens one link for Grok Bot, hands over what arrived through it, and ends it", async () => {+ const { move, calls } = fakeGrokMove();+ const local = await serve({ grokMove: move });+ const connector = "/api/setup-import/grok/connector";+ const looked = await local.call("GET", connector);+ expect(looked.headers.get("cache-control")).toBe("no-store");+ expect(await looked.json()).toEqual({ available: true, arrived: [] });+ expect((await local.call("POST", connector, { body: "", type: "text/plain" })).status).toBe(415);+ expect(calls).toEqual(["look 0"]);+ const made = await (await local.call("POST", connector, { body: {} })).json() as GrokConnector;+ expect(made).toEqual({ available: true, connectorUrl: "https://words.trycloudflare.com/mcp/move/key", expiresAt: 9, arrived: [] });+ expect(await (await local.call("GET", connector)).json()).toMatchObject({ connectorUrl: made.connectorUrl, arrived: [{ seq: 1, at: 5, text: "{}" }] });+ expect(await (await local.call("GET", `${connector}?after=1`)).json()).toMatchObject({ arrived: [] });+ for (const after of ["x", "-1", "1.5"]) expect((await local.call("GET", `${connector}?after=${after}`)).status, after).toBe(400);+ expect(await (await local.call("DELETE", connector)).json()).toEqual({ available: true, arrived: [] });+ expect(calls).toEqual(["look 0", "connect", "look 0", "look 1", "end"]);+ });++ it("keeps the Grok Bot link to the owner's own loopback, and says plainly when no link can be made", async () => {+ const { move, calls } = fakeGrokMove();+ const local = await serve({ grokMove: move });+ const connector = "/api/setup-import/grok/connector";+ for (const auth of ["paired", "service"]) {+ for (const method of ["GET", "POST", "DELETE"]) expect((await local.call(method, connector, { auth, ...(method === "POST" ? { body: {} } : {}) })).status, `${auth} ${method}`).toBe(403);+ }+ for (const method of ["GET", "POST", "DELETE"]) expect((await (await serve({ local: false, grokMove: move })).call(method, connector, method === "POST" ? { body: {} } : {})).status, method).toBe(403);+ expect((await local.call("PUT", connector, { body: {} })).status).toBe(405);+ expect(calls).toEqual([]);++ expect(await (await (await serve()).call("POST", connector, { body: {} })).json()).toEqual({ available: false, arrived: [] });+ const failing = await serve({ grokMove: { ...move, connect: async () => { throw new Error("The link could not be made: cloudflared did not open a tunnel in time."); } } });+ const failed = await failing.call("POST", connector, { body: {} });+ expect(failed.status).toBe(502);+ expect(await failed.json()).toEqual({ error: "The link could not be made: cloudflared did not open a tunnel in time." });+ });+it("deletes an old Cursor sign-in as the routes start, on any server", async () => {const home = fixtureHome();writeFileSync(join(home, "cursor-session.json"), "{\"accessToken\":\"x\"}");diff --git a/server/routes/setup-import.ts b/server/routes/setup-import.tsindex 1d4a6722bb..d603759195 100644--- a/server/routes/setup-import.ts+++ b/server/routes/setup-import.ts@@ -2,6 +2,7 @@ import { z } from "zod";import { claudeUserMcpEnabled, DATA_DIR, type AppConfig } from "../config.ts";import { lookForGrokBot, removeOldCursorSignIn } from "../grok-local.ts";+import { createGrokMove, type GrokMove } from "../grok-move-tunnel.ts";import { applySetupImport, detectSetup, thisMachine, type SetupHost, type SetupMachine } from "../setup-import.ts";import type { BusyFlag } from "./config.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -18,18 +19,22 @@ export interface SetupImportRouteDeps {/** The computer whose files are read; tests point it at a fixture home. */machine?: () => SetupMachine;dataDir?: string;+ grokMove?: GrokMove;}export const SETUP_IMPORT_PATH = "/api/setup-import";export const GROK_LOOK_PATH = "/api/setup-import/grok";+export const GROK_CONNECTOR_PATH = "/api/setup-import/grok/connector";const LOCAL_ONLY = "Only the desktop app on the computer running OpenMausBot can bring in that computer's skills and tools.";const requestSchema = z.object({ skills: z.boolean().optional(), tools: z.boolean().optional() }).strict();-/** GET finds what is new here; POST brings in the chosen kinds. Only the owner's own loopback, never a paired device,- * a browser elsewhere, a bot's shell on a service server, a Cloud home or a hosted server. */+/** GET finds what is new here; POST brings in the chosen kinds. The Grok Bot connector: POST opens the link (a quick+ * tunnel to a listener that serves only the move MCP), GET reads what arrived, DELETE ends it. Only the owner's own+ * loopback, never a paired device, a browser elsewhere, a bot's shell on a service server, a Cloud home or a hosted server. */export function createSetupImportRoutes(deps: SetupImportRouteDeps): RouteHandler {removeOldCursorSignIn(deps.dataDir ?? DATA_DIR);const machine = deps.machine ?? thisMachine;+ const grokMove = deps.grokMove ?? createGrokMove();const host: SetupHost = {mcpServers: () => deps.cfg.mcpServers ?? {},mcpPolicyRefusal: deps.mcpPolicyRefusal,@@ -37,13 +42,29 @@ export function createSetupImportRoutes(deps: SetupImportRouteDeps): RouteHandlemcpConfigBusy: deps.mcpConfigBusy,claudeUserMcp: () => claudeUserMcpEnabled(deps.cfg),};- return async ({ req, res, path, method, auth, json, readBody }) => {+ return async ({ req, res, url, path, method, auth, json, readBody }) => {if (path === GROK_LOOK_PATH) {if (method !== "GET") return json(res, 405, { error: "method not allowed" });if (!deps.local || auth.kind !== "loopback" || auth.trust === "service") return json(res, 403, { error: LOCAL_ONLY });res.setHeader("Cache-Control", "no-store");return json(res, 200, lookForGrokBot(machine()));}+ if (path === GROK_CONNECTOR_PATH) {+ if (method !== "GET" && method !== "POST" && method !== "DELETE") return json(res, 405, { error: "method not allowed" });+ if (!deps.local || auth.kind !== "loopback" || auth.trust === "service") return json(res, 403, { error: LOCAL_ONLY });+ res.setHeader("Cache-Control", "no-store");+ // As for POST below: a page in a browser cannot send this type across origins.+ if (method === "POST" && !String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {+ return json(res, 415, { error: "content-type must be application/json" });+ }+ const after = Number(url.searchParams.get("after") ?? "0");+ if (!Number.isSafeInteger(after) || after < 0) return json(res, 400, { error: "after must be a number" });+ try {+ return json(res, 200, await (method === "POST" ? grokMove.connect() : method === "DELETE" ? grokMove.end() : grokMove.look(after)));+ } catch (error) {+ return json(res, 502, { error: error instanceof Error ? error.message : String(error) });+ }+ }if (path !== SETUP_IMPORT_PATH) return PASS;if (method !== "GET" && method !== "POST") return json(res, 405, { error: "method not allowed" });if (!deps.local || auth.kind !== "loopback" || auth.trust === "service") return json(res, 403, { error: LOCAL_ONLY });