Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(pi): bound native shell tool timeouts
yuhe66de394c0e3f
diff --git a/docs/verification/README.md b/docs/verification/README.mdindex 0e3222533e..4ae759f900 100644--- a/docs/verification/README.md+++ b/docs/verification/README.md@@ -77,6 +77,7 @@ Use only mapped, tested commands:- [Question cards: a teammate's question, in its chat and the person's inbox](question-cards.md)- [Chief authority over additional departments](team-access.md)- [Engines and Doctor](engines.md)+- [Pi shell timeout bounds and recovery after tool errors](pi-shell-timeouts.md)- [Cline engine and native loopback qualification](cline.md)- [Claude coordination and turn-scoped tools](claude-tool-lifecycle.md)- [Codex bot instructions](codex-instructions.md)diff --git a/docs/verification/pi-shell-timeouts.md b/docs/verification/pi-shell-timeouts.mdnew file mode 100644index 0000000000..4f1651b8ae--- /dev/null+++ b/docs/verification/pi-shell-timeouts.md@@ -0,0 +1,42 @@+# Pi shell timeouts++Pi 1.5.0's native `bash` and `powershell` tools take `timeout` in seconds and+have no default. OpenMausBot supplies 120 seconds when omitted and refuses+values outside `(0, 900]` with a tool error explaining the unit. A refused+command never starts, and Pi can continue the conversation after the error.+Services that must outlive a command should run in the background and be+checked with bounded commands.++Run the extension and driver regressions:++```sh+pnpm exec vitest run server/drivers/pi-mcp-extension.test.ts server/drivers/pi.test.ts server/drivers/pi-lifecycle.test.ts+```++For the native CLI contract, pass an installed Pi executable explicitly:++```sh+node --experimental-strip-types scripts/verify-pi-shell-timeouts.ts /absolute/path/to/pi+```++This launches the verification server from `control-omb` with a disposable+home and data directory, then selects the supplied Pi CLI through the engine+settings route. Pi uses a synthetic model hosted on loopback with a fixture+key. No user data, provider credentials or remote SSH hosts are involved.++The fixture sends a conversation through `control-omb` and checks that:++- `timeout: 90000` returns a seconds/limit error without creating its marker;+- a valid seconds timeout and an omitted timeout allow successful commands;+- a hanging local process with `timeout: 0.5` stops and leaves no running child;+- Pi receives the tool errors, replies again and the conversation settles.++The unit tests also check the actual default argument, fractional seconds,+PowerShell, invalid values and tool-selection enforcement. The native fixture+does not wait for the full default deadline or execute PowerShell.++Evidence is written to `.omb-scratch/verify-evidence/pi-shell-timeouts.json`,+including the server log path, wait result and bounded transcript. The fixture+server, temporary home and model endpoint are closed afterwards. This check+does not interrupt or recover an already-running user conversation; an+existing Pi process keeps the extension it loaded when it started.diff --git a/scripts/verify-pi-shell-timeouts.ts b/scripts/verify-pi-shell-timeouts.tsnew file mode 100644index 0000000000..e56bede750--- /dev/null+++ b/scripts/verify-pi-shell-timeouts.ts@@ -0,0 +1,103 @@+import assert from "node:assert/strict";+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { createServer } from "node:http";+import { join, resolve } from "node:path";+import type { Message } from "../shared/wire.ts";+import { launchVerificationServer, runControlOmb, type VerificationServer } from "./control-omb.ts";++const cliPath = process.argv[2];+assert(cliPath, "Pass the installed Pi CLI path explicitly");+const cli = resolve(cliPath);+assert(existsSync(cli), "Pi CLI must exist");+let fixture: VerificationServer | undefined;+let round = 0;+const payloads: Array<{ messages: Array<{ role: string; content?: unknown }> }> = [];+const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;+const provider = createServer(async (req, res) => {+ if (req.url !== "/v1/chat/completions" || !fixture) { res.writeHead(404).end(); return; }+ let body = "";+ for await (const chunk of req) body += chunk;+ payloads.push(JSON.parse(body));+ const { dataDir } = fixture.info;+ const calls = [+ { name: "bash", arguments: JSON.stringify({ command: `touch ${quote(join(dataDir, "must-not-run"))}`, timeout: 90_000 }) },+ { name: "bash", arguments: JSON.stringify({ command: "echo valid-seconds", timeout: 90 }) },+ { name: "bash", arguments: JSON.stringify({ command: "echo default-timeout" }) },+ { name: "bash", arguments: JSON.stringify({+ command: `${quote(process.execPath)} -e ${quote(`require('node:fs').writeFileSync(${JSON.stringify(join(dataDir, "shell-child.pid"))}, String(process.pid)); setInterval(() => {}, 1000);`)}`,+ timeout: 0.5,+ }) },+ ];+ const toolCalls = round++ === 0;+ const delta = toolCalls+ ? { role: "assistant", tool_calls: calls.map((fn, index) => ({ index, id: `shell-fixture-${index}`, type: "function", function: fn })) }+ : { role: "assistant", content: "Shell timeout fixture finished." };+ const frame = (change: unknown, finishReason: string | null) => `data: ${JSON.stringify({+ id: "fixture", object: "chat.completion.chunk", created: 0, model: "fixture",+ choices: [{ index: 0, delta: change, finish_reason: finishReason }],+ })}\n\n`;+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.end(frame(delta, null) + frame({}, toolCalls ? "tool_calls" : "stop") + "data: [DONE]\n\n");+});+await new Promise<void>((done) => provider.listen(0, "127.0.0.1", done));++try {+ fixture = await launchVerificationServer({});+ const { url, dataDir } = fixture.info;+ const api = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(url + path, {+ method, headers: { "content-type": "application/json", origin: url },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(30_000),+ });+ const result = await response.json() as any;+ assert.equal(response.status, 200, `${method} ${path}: ${JSON.stringify(result)}`);+ return result;+ };+ const control = (...args: string[]) => runControlOmb([...args, "--url", url]) as Promise<any>;+ const agentDir = join(dataDir, ".pi", "agent");+ mkdirSync(agentDir, { recursive: true });+ writeFileSync(join(agentDir, "models.json"), JSON.stringify({ providers: { fixture: {+ baseUrl: `http://127.0.0.1:${(provider.address() as { port: number }).port}/v1`,+ api: "openai-completions", apiKey: "synthetic-fixture-key",+ models: [{ id: "fixture", name: "Shell timeout fixture", reasoning: false, input: ["text"], contextWindow: 131072, maxTokens: 1024,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],+ } } }));+ writeFileSync(join(agentDir, "settings.json"), JSON.stringify({ defaultProvider: "fixture", defaultModel: "fixture", defaultThinkingLevel: "off" }));+ await api("PATCH", "/api/instances/pi", { cli });+ await api("POST", "/api/instances/pi/refresh-models", {});+ const bot = (await control("new-bot", "--name", "Shell timeout probe")).bot;+ const threadId = bot.activeTaskId ?? bot.threadId;+ await control("set-model", "--bot", bot.id, "--task", threadId, "--instance", "pi", "--model", "fixture/fixture");+ await control("send", "--bot", bot.id, "--task", threadId, "--text", "Run the disposable shell timeout fixture.");+ const wait = await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30");+ assert.equal(wait.status, "settled", JSON.stringify(wait));+ const messages = await control("messages", "--bot", bot.id, "--task", threadId, "--limit", "20");+ const transcript = (await api("GET", `/api/threads/${threadId}/messages?limit=20`)).messages as Message[];+ const tools = transcript.flatMap((message) => message.tool ? [{ ...message.tool, args: JSON.parse(message.tool.input ?? "{}") }] : []);+ assert.equal(tools.length, 4, JSON.stringify(transcript));+ const blocked = tools.find((tool) => tool.args.timeout === 90_000);+ assert.equal(blocked?.ok, false, JSON.stringify(tools));+ assert.match(blocked.output!, /seconds.*900/);+ assert.equal(existsSync(join(dataDir, "must-not-run")), false);+ assert(tools.some((tool) => tool.ok && /valid-seconds/.test(tool.output!)));+ assert(tools.some((tool) => tool.ok && /default-timeout/.test(tool.output!)));+ const expired = tools.find((tool) => tool.args.timeout === 0.5);+ assert.equal(expired?.ok, false);+ assert.match(expired.output!, /timed out after 0.5 seconds/);+ const childPid = Number(readFileSync(join(dataDir, "shell-child.pid"), "utf8"));+ assert.throws(() => process.kill(childPid, 0), { code: "ESRCH" });+ assert(transcript.some((message) => message.text === "Shell timeout fixture finished."));+ const toolResults = payloads.slice(1).flatMap((payload) => payload.messages+ .filter((message) => message.role === "tool").map((message) => JSON.stringify(message.content)));+ assert(toolResults.some((result) => /seconds.*900/.test(result)), "Pi must receive the rejected timeout");+ assert(toolResults.some((result) => /timed out after 0.5 seconds/.test(result)), "Pi must receive the expired command result");+ const evidence = { fixture: fixture.info, cli, wait, messages, rejectedBeforeExecution: true, timedOutChildStopped: true };+ const evidenceDir = resolve(".omb-scratch/verify-evidence");+ mkdirSync(evidenceDir, { recursive: true });+ writeFileSync(join(evidenceDir, "pi-shell-timeouts.json"), JSON.stringify(evidence, null, 2));+ console.log(JSON.stringify(evidence));+} finally {+ await fixture?.close();+ provider.closeAllConnections();+ await new Promise<void>((done) => provider.close(() => done()));+}diff --git a/server/drivers/pi-mcp-extension.test.ts b/server/drivers/pi-mcp-extension.test.tsindex ec66cf6a02..2ac77a7321 100644--- a/server/drivers/pi-mcp-extension.test.ts+++ b/server/drivers/pi-mcp-extension.test.ts@@ -288,6 +288,50 @@ describe("Pi MCP extension registration", () => {return dir;};+ it.each([undefined, { allow: ["native:bash", "native:powershell"] }])(+ "rejects shell timeouts mistaken for milliseconds with scope %j",+ async (toolScope) => {+ scopeConfig(toolScope);+ const f = scopedApi(["bash", "powershell"]);+ await extension(f.api);+ for (const toolName of ["bash", "powershell"]) {+ const input = { command: "echo should-not-run", timeout: 90_000 };+ expect(await f.handlers.get("tool_call")?.({ toolName, input })).toMatchObject({+ block: true,+ reason: expect.stringMatching(/seconds.*900/),+ });+ expect(input.timeout).toBe(90_000);+ }+ },+ );++ it("bounds shell calls without a timeout and preserves valid seconds", async () => {+ scopeConfig(undefined);+ const f = scopedApi(["bash", "powershell", "read"]);+ await extension(f.api);+ for (const toolName of ["bash", "powershell"]) {+ const input: { command: string; timeout?: number } = { command: "echo bounded" };+ expect(await f.handlers.get("tool_call")?.({ toolName, input })).toBeUndefined();+ expect(input.timeout).toBe(120);+ for (const timeout of [0.1, 90, 900]) {+ const explicit = { command: "echo valid", timeout };+ expect(await f.handlers.get("tool_call")?.({ toolName, input: explicit })).toBeUndefined();+ expect(explicit.timeout).toBe(timeout);+ }+ }+ const input = { path: "fixture.txt" };+ expect(await f.handlers.get("tool_call")?.({ toolName: "read", input })).toBeUndefined();+ expect(input).toEqual({ path: "fixture.txt" });+ });++ it.each([0, -1, NaN, Infinity, null, "90"])("rejects invalid shell timeout %s", async (timeout) => {+ scopeConfig(undefined);+ const f = scopedApi(["bash"]);+ await extension(f.api);+ expect(await f.handlers.get("tool_call")?.({ toolName: "bash", input: { command: "echo invalid", timeout } }))+ .toMatchObject({ block: true, reason: expect.stringMatching(/seconds/) });+ });+it("intersects native and package tools before the first turn and after restoration", async () => {scopeConfig({ allow: ["native:read", "native:edit", "native:write"] });const f = scopedApi(["read", "write", "bash", "package_tool"]);diff --git a/server/drivers/pi-mcp-extension.ts b/server/drivers/pi-mcp-extension.tsindex 7cc1e54217..9afb2a0019 100644--- a/server/drivers/pi-mcp-extension.ts+++ b/server/drivers/pi-mcp-extension.ts@@ -87,6 +87,8 @@ const MCP_MAX_FRAME_BYTES = 32 * 1024 * 1024;const TOOL_OUTPUT_MAX_BYTES = 50 * 1024;const TOOL_OUTPUT_MAX_LINES = 2_000;const TOOL_NAME_MAX_LENGTH = 64;+const SHELL_DEFAULT_TIMEOUT_SECONDS = 120;+const SHELL_MAX_TIMEOUT_SECONDS = 900;export class StdioMcp {private child: ChildProcessWithoutNullStreams;@@ -593,11 +595,26 @@ export default async function (pi: PiExtensionApi): Promise<void> {let enforcementFailed = false;const clients: StdioMcp[] = [];const serverEntries = Object.entries(config.mcpServers ?? {}).filter(([name]) => scope === undefined || canUseMcpServer(scope, name));+ const allowed = (name: string) => scope === undefined || (directoryTools.has(name)+ ? canUseMcpServer(scope, directoryTools.get(name)!)+ : allowsTool(scope, identities.get(name) ?? { kind: "native", name }));++ pi.on("tool_call", (event) => {+ if (scope !== undefined && (enforcementFailed || typeof event?.toolName !== "string" || !allowed(event.toolName))) {+ return { block: true, reason: "Tool selection excludes this tool" };+ }+ if (event?.toolName !== "bash" && event?.toolName !== "powershell") return;+ const input = event.input;+ if (!input || typeof input !== "object" || Array.isArray(input)) return;+ const args = input as Record<string, unknown>;+ // Pi 1.5 runs the mutated tool_call.input; its native shell timeout is seconds and has no default.+ if (args.timeout === undefined) args.timeout = SHELL_DEFAULT_TIMEOUT_SECONDS;+ if (typeof args.timeout !== "number" || !Number.isFinite(args.timeout) || args.timeout <= 0 || args.timeout > SHELL_MAX_TIMEOUT_SECONDS) {+ return { block: true, reason: `Shell timeout must be in seconds, greater than 0 and at most ${SHELL_MAX_TIMEOUT_SECONDS}. Use 90 for 90 seconds, not 90000. Run longer services in the background and check them with bounded commands.` };+ }+ });if (scope !== undefined) {- const allowed = (name: string) => directoryTools.has(name)- ? canUseMcpServer(scope, directoryTools.get(name)!)- : allowsTool(scope, identities.get(name) ?? { kind: "native", name });const intersect = () => {if (enforcementFailed) throw new Error("Pi tool selection enforcement is unavailable");try {@@ -618,7 +635,6 @@ export default async function (pi: PiExtensionApi): Promise<void> {}};for (const event of ["session_start", "session_switch", "model_select", "before_agent_start", "context"]) pi.on(event, () => { intersect(); });- pi.on("tool_call", (event) => !enforcementFailed && typeof event?.toolName === "string" && allowed(event.toolName) ? undefined : { block: true, reason: "Tool selection excludes this tool" });// Providers serialize tools before this hook, so the final payload is filtered too.pi.on("before_provider_request", (event, context) => {let selected = new Set<string>();