Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Skill Burger: keep same-name files in other folders and appends as their own steps (#7483)
Milind Soni05c52ac54c69
diff --git a/server/skill-burger/executors.test.ts b/server/skill-burger/executors.test.tsindex 31d9ce3674..3896e49f85 100644--- a/server/skill-burger/executors.test.ts+++ b/server/skill-burger/executors.test.ts@@ -1,9 +1,12 @@-import { mkdtempSync, readFileSync, symlinkSync } from "node:fs";+import { mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it } from "vitest";import { appFrame, createExecutors, shellQuote } from "./executors.ts";+import { draftWorkflow } from "../../shared/skill-burger/draft.ts";+import type { RunMessage } from "../../shared/skill-burger/layers.ts";+import { startRun } from "./runner.ts";const folder = () => mkdtempSync(join(tmpdir(), "burger-exec-"));const signal = () => new AbortController().signal;@@ -44,4 +47,41 @@ describe("where a Skill Burger's steps run", () => {expect(await exec.shell({ command: "yes | head -c 5000", env: {}, where: "bot", tool: "shell", signal: signal(), maxBytes: 1_000 })).toMatchObject({ ok: false, tooLarge: true });expect(shellQuote(value)).toBe(`'it'\\''s $(rm -rf /) \`x\`'`);});++ it.skipIf(process.platform === "win32").each([+ {+ name: "the CSV header and every appended row",+ commands: [+ "printf 'name,score\\n' > report.csv", "printf 'Ada,10\\n' >> report.csv",+ "printf 'Bob,20\\n' >> report.csv", "cp report.csv backup.csv",+ ],+ expected: { "report.csv": "name,score\nAda,10\nBob,20\n", "backup.csv": "name,score\nAda,10\nBob,20\n" },+ },+ {+ name: "the last overwrite of a file",+ commands: ["printf draft > report.csv", "printf corrected > report.csv", "cp report.csv final.csv"],+ expected: { "report.csv": "corrected", "final.csv": "corrected" },+ },+ ])("replays $name", async ({ commands, expected }) => {+ const cwd = folder();+ try {+ const messages: RunMessage[] = [+ { id: "ask", role: "user", kind: "text", text: "Prepare the reports" },+ ...commands.map((command, index) => ({+ id: `m${index}`, role: "bot", kind: "activity", tool: { name: "Bash", ok: true, input: JSON.stringify({ command }) },+ })),+ ];+ const draft = draftWorkflow(messages)!;+ const result = await startRun({ name: "reports", botId: "b", threadId: "t", sha256: "test", workflow: draft.workflow }, {+ exec: createExecutors({ botId: "b", cwd, internal: async () => ({ ok: false, body: {} }) }),+ events: { started() {}, ended() {} }, save() {},+ });+ expect(result).toMatchObject({ ok: true, status: "ok" });+ for (const [name, content] of Object.entries(expected)) {+ expect(readFileSync(join(cwd, name), "utf8")).toBe(content);+ }+ } finally {+ rmSync(cwd, { recursive: true, force: true });+ }+ });});diff --git a/shared/skill-burger/file-writes.test.ts b/shared/skill-burger/file-writes.test.tsnew file mode 100644index 0000000000..4e6f38af79--- /dev/null+++ b/shared/skill-burger/file-writes.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from "vitest";++import { draftWorkflow } from "./draft.ts";+import { workflowSchema } from "./format.ts";+import { burgerLayers, type RunMessage } from "./layers.ts";++let sequence = 0;+const ask: RunMessage = { id: "ask", role: "user", kind: "text", text: "Prepare the reports" };+const tool = (name: string, input: Record<string, unknown>): RunMessage => ({+ id: `m${++sequence}`, role: "bot", kind: "activity", tool: { name, ok: true, input: JSON.stringify(input) },+});+const write = (path: string, content: string) => tool("Write", { file_path: path, content });+const shell = (command: string, cwd?: string) => tool("Bash", { command, ...(cwd ? { cwd } : {}) });+const runs = (commands: string[]) => draftWorkflow([ask, ...commands.map((command) => shell(command))])!.workflow.steps.map((step) => step.kind === "shell" && step.run);++describe("file writes in a saved workflow", () => {+ it.each([+ ["/reports/north/summary.md", "/reports/south/summary.md"],+ ["C:\\reports\\north\\summary.md", "C:\\reports\\south\\summary.md"],+ ])("keeps both files when %s and %s have the same basename", (north, south) => {+ const draft = draftWorkflow([ask, write(north, "North totals"), write(south, "South totals")]);+ expect(draft).not.toBeNull();+ expect(draft!.workflow.steps.map((step) => step.kind === "file" && step.path)).toEqual([north, south]);+ expect(workflowSchema.safeParse(draft!.workflow).success).toBe(true);+ });++ it("keeps redirects to different directories and quoted filenames", () => {+ const commands = [+ "printf north > north/report.csv",+ "printf south > south/report.csv",+ 'printf detail > "north detailed.csv"',+ 'printf summary > "north summary.csv"',+ ];+ expect(runs(commands)).toEqual(commands);+ });++ it("keeps relative output paths in different working directories", () => {+ const draft = draftWorkflow([+ ask,+ shell("printf north > report.csv", "/reports/north"),+ shell("printf south > report.csv", "/reports/south"),+ ]);+ expect(draft).not.toBeNull();+ expect(draft!.workflow.steps.map((step) => step.kind === "shell" && step.cwd)).toEqual(["/reports/north", "/reports/south"]);+ });++ it("keeps the same filename written after moving into different folders", () => {+ const commands = ["cd north && printf north > report.csv", "cd south && printf south > report.csv"];+ expect(runs(commands)).toEqual(commands);+ });++ it("keeps an output written on different computers", () => {+ const command = "python make_report.py > report.csv";+ const layers = burgerLayers([+ ask,+ shell(command),+ tool("mcp__computer__exec", { command }),+ tool("mcp__localComputer__exec", { command }),+ ]);+ expect(layers.map((layer) => layer.where)).toEqual(["bot", "vm", "yourComputer"]);+ expect(layers.every((layer) => layer.tries === undefined)).toBe(true);+ });++ it("keeps the CSV header and every append before copying the finished report", () => {+ const commands = [+ "printf 'name,score\\n' > report.csv",+ "printf 'Ada,10\\n' >> report.csv",+ "printf 'Bob,20\\n' >> report.csv",+ "cp report.csv backup.csv",+ ];+ const draft = draftWorkflow([ask, ...commands.map((command) => shell(command))]);+ expect(draft!.workflow.steps.map((step) => step.kind === "shell" && step.run)).toEqual(commands);+ expect(draft!.layers.every((layer) => layer.tries === undefined)).toBe(true);+ });++ it("keeps a write, an append and a later rewrite of one file in order", () => {+ const commands = ["printf header > log.txt", "printf row >> log.txt", "printf fresh > log.txt"];+ expect(runs(commands)).toEqual(commands);+ });++ it("still keeps only the last try when the same full path is written again", () => {+ const layers = burgerLayers([+ ask,+ write("/reports/summary.md", "Draft"),+ shell("printf draft > ./out/../report.csv", "/reports"),+ write("/reports/summary.md", "Finished"),+ shell("printf finished > /reports/report.csv"),+ ]);+ expect(layers.map((layer) => [layer.args, layer.tries])).toEqual([+ [{ path: "/reports/summary.md", content: "Finished" }, 1],+ [{ command: "printf finished > /reports/report.csv" }, 1],+ ]);+ });+});diff --git a/shared/skill-burger/layers.ts b/shared/skill-burger/layers.tsindex bba84a58e8..74523e5af6 100644--- a/shared/skill-burger/layers.ts+++ b/shared/skill-burger/layers.ts@@ -109,6 +109,10 @@ export function isServerRow(message: RunMessage): boolean {/** The unquoted output redirect of a command (`> notes.md`, `>> log.txt`, `cat > a.md <<EOF`), other than to /dev/…:* it writes a file, whatever program it runs. */export function redirectTarget(command: string): string | null {+ return redirectOf(command)?.path ?? null;+}++function redirectOf(command: string): { path: string; append: boolean } | null {let quote: string | null = null;for (let i = 0; i < command.length; i += 1) {const char = command[i]!;@@ -118,11 +122,13 @@ export function redirectTarget(command: string): string | null {const before = command[i - 1] ?? " ";if (/[0-9&>-]/.test(before) && before !== " ") continue;let j = i + 1;- if (command[j] === ">") j += 1;+ const append = command[j] === ">";+ if (append) j += 1;if (command[j] === "&" || command[j] === "(") continue;while (command[j] === " ") j += 1;- const target = /^["']?([^\s"';|&]+)/.exec(command.slice(j))?.[1];- if (target && !target.startsWith("/dev/")) return target;+ const target = /^(?:"([^"]+)"|'([^']+)'|["']?([^\s"';|&]+))/.exec(command.slice(j));+ const path = target?.[1] ?? target?.[2] ?? target?.[3];+ if (path && !path.startsWith("/dev/")) return { path, append };}return null;}@@ -384,11 +390,43 @@ function joinDesktop(layers: BurgerLayer[]): BurgerLayer[] {return out;}-/** The file a layer writes, when it writes one: a later write of the same file is the try that counts. */-function writesTo(layer: BurgerLayer): string | null {- if (layer.kind === "file" && typeof layer.args?.path === "string") return layer.args.path.split(/[\\/]/).pop() ?? null;- if (layer.kind === "shell" && typeof layer.args?.command === "string") return redirectTarget(layer.args.command)?.split(/[\\/]/).pop() ?? null;- return null;+/** The folders a command's leading `cd <dir> &&` steps move into, and the rest of it; null after any other `cd`. */+function afterCd(command: string): { folders: string[]; rest: string } | null {+ const folders: string[] = [];+ let rest = command;+ for (let found = LEADING_CD.exec(rest); found; found = LEADING_CD.exec(rest)) {+ folders.push(found[1] ?? found[2] ?? found[3]!);+ rest = rest.slice(found[0].length);+ }+ return /(?:^|[;&|(]\s*)cd(?:\s|$)/.test(rest) ? null : { folders, rest };+}+const LEADING_CD = /^\s*cd\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*&&\s*/;++/** A path as one key: the conversation folder as ".", either slash, and ".", ".." and repeated slashes resolved. */+function resolvePath(parts: readonly string[]): string {+ const out: string[] = [];+ let root = "";+ for (const part of parts) {+ const clean = part.replace(CONVERSATION_FOLDER, ".").replace(/\\/g, "/");+ const absolute = /^(?:[A-Za-z]:)?\//.exec(clean)?.[0];+ if (absolute) { root = absolute; out.length = 0; }+ for (const segment of clean.slice(absolute?.length ?? 0).split("/")) {+ if (segment === "" || segment === ".") continue;+ if (segment === ".." && out.length && out[out.length - 1] !== "..") out.pop();+ else if (segment !== ".." || !root) out.push(segment);+ }+ }+ return root + out.join("/");+}++/** The file a layer writes, by its full path on its computer, and whether it only adds to the end of it. */+function writesTo(layer: BurgerLayer): { file: string; append: boolean } | null {+ const cwd = typeof layer.args?.cwd === "string" ? layer.args.cwd : ".";+ if (layer.kind === "file" && typeof layer.args?.path === "string") return { file: `${layer.where}:${resolvePath([cwd, layer.args.path])}`, append: false };+ if (layer.kind !== "shell" || typeof layer.args?.command !== "string") return null;+ const moved = afterCd(layer.args.command);+ const redirect = moved && redirectOf(moved.rest);+ return redirect ? { file: `${layer.where}:${resolvePath([cwd, ...moved.folders, redirect.path])}`, append: redirect.append } : null;}/** A read the run made that leaves no layer: a page looked at, a file or listing read. */@@ -418,10 +456,17 @@ export function burgerLayers(messages: readonly RunMessage[], live: ReadonlySet<if (found.some((layer) => layer.read)) read = true;}const kept: BurgerLayer[] = [];- const replaced = (layer: BurgerLayer, later: BurgerLayer) => (later.status !== "failed" && sameStep(layer, later) && layer.status === "failed") || (writesTo(layer) !== null && writesTo(layer) === writesTo(later) && later.status !== "failed");+ const writes = layers.map(writesTo);+ const rewrites = (earlier: number, later: number) => {+ const [first, last] = [writes[earlier], writes[later]];+ return Boolean(first && last && !first.append && !last.append && first.file === last.file+ && !writes.slice(earlier + 1, later).some((between) => between?.append && between.file === first.file));+ };+ const replaced = (earlier: number, later: number) => layers[later]!.status !== "failed"+ && ((sameStep(layers[earlier]!, layers[later]!) && layers[earlier]!.status === "failed") || rewrites(earlier, later));layers.forEach((layer, index) => {- if (layers.slice(index + 1).some((later) => replaced(layer, later))) return;- const tries = layers.slice(0, index).filter((earlier) => replaced(earlier, layer)).length;+ if (layers.some((_, later) => later > index && replaced(index, later))) return;+ const tries = layers.filter((_, earlier) => earlier < index && replaced(earlier, index)).length;kept.push(tries && layer.status !== "failed" ? { ...layer, tries } : layer);});return withReview(joinDelegations(joinDesktop(kept), round, repliesIn(run)), run);