Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(pi): give the agents server the start time other engines give it
AdityaUmale696a3bfb6a77
diff --git a/server/drivers/pi-mcp-extension.test.ts b/server/drivers/pi-mcp-extension.test.tsindex 2ac77a7321..2e4c5ae2ed 100644--- a/server/drivers/pi-mcp-extension.test.ts+++ b/server/drivers/pi-mcp-extension.test.ts@@ -8,6 +8,7 @@ import { startFakeHttpMcp } from "../testing/fake-http-mcp-server.ts";import { whopLikeCatalog } from "../testing/whop-like-catalog.ts";import { buildMcpServers } from "./pi-mcp-servers.ts";import { mcpStdioServer } from "../mcp-gate-config.ts";+import { agentsStartupMs } from "./chat-mcp-tools.ts";import extension, {allocateToolName,@@ -268,6 +269,59 @@ describe("Pi MCP startup budgets", () => {await remote.close();}});++ /** A command server that answers initialize only once the test creates `<name>.answer` in `dir`. */+ function slowToStart(dir: string, name: string): string {+ const asked = JSON.stringify(join(dir, `${name}.asked`)), answer = JSON.stringify(join(dir, `${name}.answer`));+ return fakeMcpScript(`+ import { existsSync, writeFileSync } from "node:fs";+ let buffer = "";+ process.stdin.setEncoding("utf8");+ const send = (value) => process.stdout.write(JSON.stringify(value) + "\\n");+ process.stdin.on("data", (chunk) => {+ buffer += chunk;+ let newline;+ while ((newline = buffer.indexOf("\\n")) !== -1) {+ const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);+ if (!line.trim()) continue;+ const msg = JSON.parse(line);+ if (msg.method === "initialize") {+ writeFileSync(${asked}, "");+ const wait = setInterval(() => {+ if (!existsSync(${answer})) return;+ clearInterval(wait);+ send({ jsonrpc: "2.0", id: msg.id, result: { capabilities: { tools: {} } } });+ }, 10);+ } else if (msg.method === "tools/list") send({ jsonrpc: "2.0", id: msg.id, result: { tools: [{ name: "coordinate_bots", inputSchema: { type: "object" } }] } });+ }+ });+ `);+ }++ it("gives the agents server the start time other engines give it, a plain command server 8 seconds", async () => {+ const { startupMs } = buildMcpServers({ threadId: "t", text: "hi", integrations: { agents: { command: "node", args: ["agents"], env: {} } } })!.agents as { startupMs?: number };+ expect(startupMs).toBe(agentsStartupMs());+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ try {+ const dir = tempDir();+ const agents = new StdioMcp({ command: process.execPath, args: [slowToStart(dir, "agents")], startupMs });+ const plain = new StdioMcp({ command: process.execPath, args: [slowToStart(dir, "plain")] });+ clients.push(agents, plain);+ const mounting = watch(agents.init().then(() => agents.listTools()));+ const failing = watch(plain.init().then(() => plain.listTools()));+ await untilReal(() => existsSync(join(dir, "agents.asked")) && existsSync(join(dir, "plain.asked")));+ await vi.advanceTimersByTimeAsync(12_000);+ await untilReal(() => failing.done);+ expect(String(failing.error)).toMatch(/timed out/);+ expect(mounting.done).toBe(false);+ writeFileSync(join(dir, "agents.answer"), "");+ await untilReal(() => mounting.done);+ expect(mounting.error).toBeUndefined();+ expect(mounting.value!.map((tool) => tool.name)).toEqual(["coordinate_bots"]);+ } finally {+ vi.useRealTimers();+ }+ });});describe("Pi MCP extension registration", () => {diff --git a/server/drivers/pi-mcp-extension.ts b/server/drivers/pi-mcp-extension.tsindex 9afb2a0019..73badff9ac 100644--- a/server/drivers/pi-mcp-extension.ts+++ b/server/drivers/pi-mcp-extension.ts@@ -17,6 +17,8 @@ interface McpServerDef {/** "local-computer" marks the user's real desktop: every tool on it is gated behind a permission card. */scope?: string;directory?: boolean;+ /** How long a command server gets to start; MCP_STARTUP_TIMEOUT_MS when absent. */+ startupMs?: number;}interface McpConfig {@@ -97,10 +99,12 @@ export class StdioMcp {private disposed = false;private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();private readonly remote: boolean;+ private readonly startupMs: number;private listDeadline: number | undefined;constructor(def: McpServerDef) {this.remote = def.directory === true;+ this.startupMs = typeof def.startupMs === "number" && Number.isFinite(def.startupMs) && def.startupMs > 0 ? def.startupMs : MCP_STARTUP_TIMEOUT_MS;this.child = spawn(def.command, def.args ?? [], {stdio: ["pipe", "pipe", "pipe"],env: { ...process.env, ...def.env },@@ -222,7 +226,7 @@ export class StdioMcp {}async init(): Promise<void> {- const budget = this.remote ? REMOTE_MCP_STARTUP_MS : MCP_STARTUP_TIMEOUT_MS;+ const budget = this.remote ? REMOTE_MCP_STARTUP_MS : this.startupMs;this.listDeadline = this.remote ? Date.now() + budget : undefined;await this.call("initialize",@@ -239,7 +243,7 @@ export class StdioMcp {async listTools(): Promise<McpTool[]> {const tools: McpTool[] = [];const seenCursors = new Set<string>();- const deadline = this.listDeadline ?? Date.now() + MCP_STARTUP_TIMEOUT_MS;+ const deadline = this.listDeadline ?? Date.now() + this.startupMs;let cursor: string | undefined;for (let page = 0; page < MCP_MAX_LIST_PAGES; page += 1) {const remainingMs = Math.max(1, deadline - Date.now());diff --git a/server/drivers/pi-mcp-servers.ts b/server/drivers/pi-mcp-servers.tsindex a7eaba4ccf..6e2486f267 100644--- a/server/drivers/pi-mcp-servers.ts+++ b/server/drivers/pi-mcp-servers.ts@@ -5,6 +5,7 @@ import type { SendTurnInput } from "../contracts.ts";import { appMountFor, customServerGate, gateServer, mcpStdioServer } from "../mcp-gate-config.ts";import { remoteMcpSpec } from "../mcp-http.ts";import { SPAWNED_PROXIES } from "../proxy-paths.ts";+import { agentsStartupMs } from "./chat-mcp-tools.ts";const NODE_ENV_FLAG = { ELECTRON_RUN_AS_NODE: "1" };@@ -23,7 +24,8 @@ export function buildMcpServers(turn: SendTurnInput): Record<string, unknown> |...(local.scope ? { scope: local.scope } : {}),};}- if (turn.integrations?.agents) servers.agents = { ...turn.integrations.agents };+ // A turn can't run without the agents server: give it the start time every other engine gives it.+ if (turn.integrations?.agents) servers.agents = { ...turn.integrations.agents, startupMs: agentsStartupMs() };if (turn.integrations?.phone) servers.phone = { ...turn.integrations.phone };if (turn.integrations?.dweb) {servers.dweb = {@@ -42,8 +44,8 @@ export function buildMcpServers(turn: SendTurnInput): Record<string, unknown> |const gated = gateServer({ name, server, toolScope: parsed.scope, threadId: turn.threadId, nodeEnv: NODE_ENV_FLAG, directory, ...customServerGate(name, name in (turn.integrations?.custom ?? {}), turn.integrations?.customResultBudgets), apps: appMountFor(name, turn) });const stdio = gated ?? mcpStdioServer(server, { nodeEnv: NODE_ENV_FLAG, ...(directory ? { directory: { name } } : {}) });if (!stdio) throw new Error("Pi MCP server configuration is invalid");- const original = server as { scope?: string };- servers[name] = { ...stdio, ...(original.scope ? { scope: original.scope } : {}), ...(directory ? { directory: true } : {}) };+ const original = server as { scope?: string; startupMs?: number };+ servers[name] = { ...stdio, ...(original.scope ? { scope: original.scope } : {}), ...(original.startupMs ? { startupMs: original.startupMs } : {}), ...(directory ? { directory: true } : {}) };}return Object.keys(servers).length ? servers : null;}diff --git a/server/drivers/pi.test.ts b/server/drivers/pi.test.tsindex d602f5de21..d10041ff1e 100644--- a/server/drivers/pi.test.ts+++ b/server/drivers/pi.test.ts@@ -14,6 +14,7 @@ import { removeTempDir } from "../testing/cleanup.ts";import { encodeInjectId, localHost } from "./local-inject.ts";import { piSessionDir } from "./pi-session.ts";import { buildMcpServers } from "./pi-mcp-servers.ts";+import { agentsStartupMs } from "./chat-mcp-tools.ts";import {applyPiLocalCatalog,decodePiFrame,@@ -203,7 +204,7 @@ describe("buildMcpServers", () => {});expect(servers).toEqual({composio: { command: "node", args: ["c"], env: { A: "1" } },- agents: { command: "node", args: ["a"], env: { B: "2" } },+ agents: { command: "node", args: ["a"], env: { B: "2" }, startupMs: agentsStartupMs() },phone: { command: "node", args: ["p"], env: {} },});});