Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(skill-burger): retain native Pi writes in saved workflows
Afloatc5fdd905a77f
diff --git a/server/skill-burger/pi-writes.test.ts b/server/skill-burger/pi-writes.test.tsnew file mode 100644index 0000000000..94e4679b3e--- /dev/null+++ b/server/skill-burger/pi-writes.test.ts@@ -0,0 +1,138 @@+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, expect, it } from "vitest";++import { workflowSchema } from "../../shared/skill-burger/format.ts";+import type { RunMessage } from "../../shared/skill-burger/layers.ts";+import { ensureDirs } from "../config.ts";+import { PiDriver } from "../drivers/pi.ts";+import { json, readBody } from "../harness/http.ts";+import type { RequestAuth } from "../request-auth.ts";+import { dispatchRoutes } from "../routes/table.ts";+import { recordEvents } from "../testing/events.ts";+import { createSkillBurgerRoutes } from "./routes.ts";+import type { RunEnvelope } from "./runner.ts";+import { createSkillBurgerRuns, RESUME_PATH, RUN_PATH } from "./runs.ts";++const roots: string[] = [];+const servers: Server[] = [];+afterEach(async () => {+ await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))));+ roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true }));+});++async function replay(content: string, name = "write", path = "report.txt") {+ const home = mkdtempSync(join(tmpdir(), "burger-pi-write-"));+ roots.push(home);+ const original = join(home, "original");+ const root = join(home, "replay");+ mkdirSync(original);+ mkdirSync(root);+ ensureDirs();+ const cli = fileURLToPath(new URL("../testing/fake-pi-cli.ts", import.meta.url));+ chmodSync(cli, 0o755);+ const instance = await PiDriver.create({+ instanceId: "burger-pi-write", displayName: "Fixture", enabled: true, config: { cli, fullAuto: false },+ environment: { HOME: home, FAKE_PI_MODE: "tooluse", FAKE_PI_TOOLS: JSON.stringify([+ { name, args: { path, content } },+ { name: "bash", args: { command: `node -e "require('node:fs').copyFileSync('${path}','delivered.txt')"` } },+ { name: "bash", args: { command: "node -e \"require('node:fs').writeFileSync('complete.txt','complete')\"" } },+ ]) },+ });+ const recorder = recordEvents(instance.adapter);+ const messages: RunMessage[] = [{ id: "ask", role: "user", kind: "text", text: "Write the report and deliver a copy" }];+ try {+ await instance.adapter.sendTurn({ threadId: "write-report", text: messages[0]!.text!, cwd: original });+ expect(await recorder.until((event) => event.type === "turn.completed")).toMatchObject({ ok: true });+ for (const start of recorder.events) {+ if (start.type !== "item.started" || start.itemType !== "tool") continue;+ const end = recorder.events.find((event) => event.type === "item.completed" && event.itemId === start.itemId);+ if (end?.type !== "item.completed" || end.itemType !== "tool") throw new Error("missing tool completion");+ messages.push({ id: start.itemId!, role: "bot", kind: "activity", tool: { name: start.title!, itemId: start.itemId, summary: start.summary, input: start.input, output: end.output, ok: end.ok } });+ }+ expect(messages.map((message) => message.tool?.name).filter(Boolean)).toEqual([name, "bash", "bash"]);+ } finally {+ recorder.stop();+ await instance.dispose();+ }++ const routes = createSkillBurgerRoutes({ root, messages: () => messages, owns: () => true, sees: () => true, botIds: () => ["lead"] });+ let runs = createSkillBurgerRuns({ root, dataDir: root });+ const turn = { botId: "lead", threadId: "write-report", cwd: root, mayEditBurgers: true, publish() {}, internal: async () => { throw new Error("unexpected external call"); } };+ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ const auth = { kind: "loopback", scopes: ["admin"] } as RequestAuth;+ if (!await dispatchRoutes([routes, runs.internalRoutes(turn)], { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody })) json(res, 404, {});+ });+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ const api = async <T>(url: string, body?: unknown) => {+ const response = await fetch(`${base}${url}`, body === undefined ? undefined : { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });+ const result = await response.json() as T;+ expect(response.ok, JSON.stringify(result)).toBe(true);+ return result;+ };+ const saved = await api<{ skill: { name: string } }>("/api/skill-burgers", { botId: "lead", threadId: "write-report", summary: "Deliver the report" });+ const read = await api<{ workflow: unknown }>(`/api/skill-burgers/${saved.skill.name}`);+ const workflow = workflowSchema.parse(read.workflow);+ return {+ home, root, workflow, messages,+ run: () => api<RunEnvelope>(RUN_PATH, { name: saved.skill.name }),+ resume: (run: string) => {+ runs = createSkillBurgerRuns({ root, dataDir: root });+ return api<RunEnvelope>(RESUME_PATH, { run, response: "The complete report has been written." });+ },+ };+}++it("replays a native Pi write before the recorded shell command consumes its file", async () => {+ const content = "north,south\n12,34\n";+ const h = await replay(content);+ expect(existsSync(join(h.root, "report.txt"))).toBe(false);+ expect(await h.run()).toMatchObject({ ok: true, status: "ok" });+ expect(readFileSync(join(h.root, "delivered.txt"), "utf8")).toBe(content);+ expect(readFileSync(join(h.root, "complete.txt"), "utf8")).toBe("complete");+ expect(h.workflow.steps[0]).toMatchObject({ kind: "file", path: "report.txt", content });+});++it("preserves an empty Pi write instead of copying stale contents", async () => {+ const h = await replay("");+ writeFileSync(join(h.root, "report.txt"), "stale report");+ expect(await h.run()).toMatchObject({ ok: true, status: "ok" });+ expect(readFileSync(join(h.root, "report.txt"), "utf8")).toBe("");+ expect(readFileSync(join(h.root, "delivered.txt"), "utf8")).toBe("");+});++it("hands a shortened Pi write to AI before allowing its file consumer", async () => {+ const content = "report contents\n".repeat(600);+ const h = await replay(content);+ expect(h.messages[1]!.tool?.input).toContain("[… preview shortened]");+ const paused = await h.run();+ expect(paused).toMatchObject({ status: "needs_input", requiresInput: { step: "s1", type: "ai_step" } });+ expect(existsSync(join(h.root, "report.txt"))).toBe(false);+ expect(existsSync(join(h.root, "delivered.txt"))).toBe(false);+ writeFileSync(join(h.root, "report.txt"), content);+ expect(await h.resume(paused.run)).toMatchObject({ ok: true, status: "ok" });+ expect(readFileSync(join(h.root, "delivered.txt"), "utf8")).toBe(content);+});++it("keeps an added MCP server's write on its existing AI handoff", async () => {+ const h = await replay("external contents", "mcp__notes__write");+ const paused = await h.run();+ expect(paused).toMatchObject({ status: "needs_input", requiresInput: { step: "s1", type: "ai_step" } });+ expect(existsSync(join(h.root, "report.txt"))).toBe(false);+ expect(existsSync(join(h.root, "delivered.txt"))).toBe(false);+});++it("applies the existing workspace boundary to a retained Pi file target", async () => {+ const h = await replay("changed outside", "write", "../outside.txt");+ writeFileSync(join(h.home, "outside.txt"), "original outside");+ expect(await h.run()).toMatchObject({ ok: false, error: { type: "step_failed", step: "s1", message: expect.stringContaining("only inside") } });+ expect(readFileSync(join(h.home, "outside.txt"), "utf8")).toBe("original outside");+ expect(existsSync(join(h.root, "delivered.txt"))).toBe(false);+});diff --git a/server/testing/fake-pi-cli.ts b/server/testing/fake-pi-cli.tsindex 48f63513d8..d4a50ef591 100755--- a/server/testing/fake-pi-cli.ts+++ b/server/testing/fake-pi-cli.ts@@ -13,6 +13,7 @@// FAKE_PI_STEER_REFUSE answer a steer with an explicit success:false// FAKE_PI_STEER_OUT_OF_ORDER hold the first steer until a second arrives, then refuse the first and accept the second// FAKE_PI_CONTEXT_WINDOW positive token count attached to every listed model+// FAKE_PI_TOOLS JSON tool calls ({name, args, result?, isError?}) for tooluse modeimport { appendFileSync, readFileSync, writeFileSync } from "node:fs";import { join } from "node:path";@@ -229,8 +230,12 @@ const streamCompactionRecoveryUpstreamTurn = () => {const streamToolTurn = () => {send({ type: "agent_start" });send({ type: "turn_start" });- send({ type: "tool_execution_start", toolCallId: "call_1", toolName: "bash", args: { command: "echo hi", password: "pi-input-secret" } });- send({ type: "tool_execution_end", toolCallId: "call_1", toolName: "bash", isError: false, result: { content: [{ type: "text", text: "hi" }], api_key: "pi-output-secret" } });+ const calls = process.env.FAKE_PI_TOOLS ? JSON.parse(process.env.FAKE_PI_TOOLS) : [{ name: "bash", args: { command: "echo hi", password: "pi-input-secret" }, result: { content: [{ type: "text", text: "hi" }], api_key: "pi-output-secret" } }];+ for (const [index, call] of calls.entries()) {+ const toolCallId = `call_${index + 1}`;+ send({ type: "tool_execution_start", toolCallId, toolName: call.name, args: call.args });+ send({ type: "tool_execution_end", toolCallId, toolName: call.name, isError: call.isError ?? false, result: call.result ?? { content: [{ type: "text", text: "Tool completed" }] } });+ }send({ type: "turn_end", message: { stopReason: "toolUse", usage: { input: 5, output: 1 } }, usage: { input: 5, output: 1 } });send({ type: "turn_start" });send({ type: "message_update", usage: { input: 0, output: 0 }, assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "done" } });diff --git a/shared/skill-burger/layers.ts b/shared/skill-burger/layers.tsindex bba84a58e8..6c01a161a5 100644--- a/shared/skill-burger/layers.ts+++ b/shared/skill-burger/layers.ts@@ -88,7 +88,7 @@ const OWN_SERVERS = new Set(["agents", "phone", "device", "dweb", "ogb", "data",const COMPUTER_SERVERS: Record<string, LayerWhere> = { computer: "vm", localComputer: "yourComputer" };/** Looking at a desktop changes nothing: never a layer. */const COMPUTER_LOOK = /^(?:screenshot|get_screen_size|exec_status|move|wait|zoom|cursor_position|list_[a-z_]+|read_[a-z_]+|get_[a-z_]+)$/;-const FILE_WRITE = new Set(["Write", "write_file", "create_file"]);+const FILE_WRITE = new Set(["Write", "write", "write_file", "create_file"]);const FILE_EDIT = new Set(["Edit", "MultiEdit", "NotebookEdit", "edit", "apply_patch", "str_replace_based_edit_tool"]);const BROWSER_OPEN = /(?:^|_)(?:navigate|open|open_url|goto|tab_new)$/;const BROWSER_LOOK = /(?:^|_)(?:snapshot|screenshot|read|get_text|status|tabs|wait|check|console|network|close|evaluate_read)$/;