Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Drop blank arguments only where blank means left out, and hand off without a folder instead of refusing
milind-soni045327e91cb0
diff --git a/server/bot-cwd.test.ts b/server/bot-cwd.test.tsindex e75fca3a97..a358782f6c 100644--- a/server/bot-cwd.test.ts+++ b/server/bot-cwd.test.ts@@ -101,11 +101,11 @@ describe("inMyFolderCwd", () => {expect(inMyFolderCwd(false, true, project, data)).toEqual({});});- it("stays silent when left out, and refuses an explicit true, where there is nothing to share", () => {+ it("hands off without a folder where there is nothing to share, even when asked for one", () => {expect(inMyFolderCwd(undefined, false, project, data)).toEqual({});expect(inMyFolderCwd(undefined, true, privateFolder, data)).toEqual({});- expect(inMyFolderCwd(true, false, project, data)).toEqual({ error: expect.stringMatching(/room/) });- expect(inMyFolderCwd(true, true, privateFolder, data)).toEqual({ error: expect.stringMatching(/no project folder/) });+ expect(inMyFolderCwd(true, false, project, data)).toEqual({});+ expect(inMyFolderCwd(true, true, privateFolder, data)).toEqual({});});});diff --git a/server/bot-cwd.ts b/server/bot-cwd.tsindex 98b3a53f62..bfca901c5a 100644--- a/server/bot-cwd.ts+++ b/server/bot-cwd.ts@@ -53,11 +53,10 @@ export function sharedProjectFolder(cwd: string | null | undefined, dataDir: strreturn lstatSync(checked.cwd).isSymbolicLink() ? real : checked.cwd;}-/** coordinate_bots' in_my_folder: the sender's project folder for the teammate threads it opens outside a room, or why an explicit true cannot be honoured. Omitted means on whenever there is a folder to share. */-export function inMyFolderCwd(wanted: boolean | undefined, outsideRoom: boolean, senderCwd: string | null | undefined, dataDir: string): { cwd?: string; error?: string } {- if (wanted === false) return {};- if (!outsideRoom) return wanted ? { error: "in_my_folder does not apply in a room: the room's folder governs there. Leave it out." } : {};+/** coordinate_bots' in_my_folder: the sender's project folder for the teammate threads it opens outside a room. On unless+ * false; with no folder to share, or in a room (whose folder governs there), the hand-off goes ahead without one. */+export function inMyFolderCwd(wanted: boolean | undefined, outsideRoom: boolean, senderCwd: string | null | undefined, dataDir: string): { cwd?: string } {+ if (wanted === false || !outsideRoom) return {};const cwd = sharedProjectFolder(senderCwd, dataDir);- if (cwd) return { cwd };- return wanted ? { error: "This conversation has no project folder to share (it works in its own private folder), so in_my_folder cannot be used. Leave it out; do not retry it." } : {};+ return cwd ? { cwd } : {};}diff --git a/server/drivers/agents-call.test.ts b/server/drivers/agents-call.test.tsindex bb1e9ae774..a2ae07defb 100644--- a/server/drivers/agents-call.test.ts+++ b/server/drivers/agents-call.test.ts@@ -375,3 +375,53 @@ describe("page tools", () => {{ path: "/api/internal/pages/unpublish", body: { page_id: "abcdefghijklmnopqrstuvwxyz" } }]);});});++describe("blank optional arguments", () => {+ it("drops blank session_search ids, so a blank-filled search stays a search", async () => {+ const paths: string[] = [];+ const result = await callTool("session_search", { query: "launch post", thread_id: "", message_id: " " }, context({+ client: {+ api: async (path) => {+ paths.push(path);+ return { hits: [] };+ },+ apiResponse: async () => ({ ok: true, status: 200, body: {} }),+ },+ }));+ expect(result.isError).toBeFalsy();+ expect(result.text).toContain('Nothing of yours matches "launch post"');+ expect(paths).toEqual(["/api/internal/session-search?fromBotId=bot-voice&fromThreadId=thread-voice&q=launch+post"]);+ });++ it("drops a blank jsx from show_html, so the html page is shown", async () => {+ const calls: Array<{ path: string; body: unknown }> = [];+ const result = await callTool("show_html", { html: "<p>hi</p>", jsx: "", title: "Hi" }, context({+ client: {+ api: async () => ({}),+ apiResponse: async (path, init) => {+ calls.push({ path, body: JSON.parse(String(init?.body)) });+ return { ok: true, status: 201, body: { messageId: "m9" } };+ },+ },+ }));+ expect(result).toEqual({ text: "Shown as app m9. To change it, call show_html again with app_id \"m9\"." });+ expect(calls).toEqual([{ path: "/api/internal/options-card", body: { tool: "show_html", html: "<p>hi</p>", title: "Hi" } }]);+ });++ it("keeps a blank manage_room bulletin, which clears the bulletin", async () => {+ const calls: Array<{ path: string; body: any }> = [];+ const result = await callTool("manage_room", { action: "set_bulletin", room_id: "room-1", bulletin: "" }, context({+ client: {+ api: async (path, init) => {+ calls.push({ path, body: JSON.parse(String(init?.body)) });+ return { message: "Cleared the bulletin." };+ },+ apiResponse: async () => ({ ok: true, status: 200, body: {} }),+ },+ }));+ expect(result).toEqual({ text: "Cleared the bulletin." });+ expect(calls).toEqual([+ { path: "/api/internal/manage-room", body: { fromBotId: "bot-voice", fromThreadId: "thread-voice", roomId: "room-1", action: "set_bulletin", bulletin: "" } },+ ]);+ });+});diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.tsindex e84d5cdb6f..002df4c10f 100644--- a/server/drivers/agents-call.ts+++ b/server/drivers/agents-call.ts@@ -187,22 +187,29 @@ function recallWhen(at: unknown, dateOnly: boolean): string {return dateOnly ? day : `${day} ${pad(said.getHours())}:${pad(said.getMinutes())}`;}-/** A model that fills every optional argument with `""` meant to leave it out. Dropped once here, so no tool reads- * a blank id, path or body as a value it then has to reject. */-function dropBlankStrings(input: Json): Json {- if (!input || typeof input !== "object" || Array.isArray(input)) return input;- const out: Json = {};- for (const [key, value] of Object.entries(input)) {- if (typeof value === "string" && !value.trim()) continue;- out[key] = value && typeof value === "object" && !Array.isArray(value) ? dropBlankStrings(value as Json) : value;+/** The top-level arguments a model may fill with `""` (or spaces) when it means to leave them out, per tool. Only these:+ * elsewhere a blank can be the value itself, such as a cleared room bulletin or a bot's private folder. */+const BLANK_MEANS_LEFT_OUT: Readonly<Record<string, readonly string[]>> = {+ coordinate_bots: ["group_id", "reason", "thread", "title", "reply", "done_when", "answers"],+ session_search: ["thread_id", "message_id", "query", "since", "until", "scope"],+ show_html: ["html", "jsx", "path"],+ memory_update: ["old_text", "text", "until"],+};++function dropBlankArguments(name: string, input: Json): Json {+ const keys = Object.hasOwn(BLANK_MEANS_LEFT_OUT, name) ? BLANK_MEANS_LEFT_OUT[name] : undefined;+ if (!keys || !input || typeof input !== "object" || Array.isArray(input)) return input;+ const out: Json = { ...input };+ for (const key of keys) {+ const value = out[key];+ if (typeof value === "string" && !value.trim()) delete out[key];}return out;}export async function callTool(called: string, input: Json, context: ToolCallContext): Promise<ToolCallResult> {- const resolved = resolveAgentsCall(called, input);- const name = resolved.name;- const args = dropBlankStrings(resolved.arguments);+ const { name, arguments: given } = resolveAgentsCall(called, input);+ const args = dropBlankArguments(name, given);const refused = outOfBounds(name, fullInputSchema(name), args);if (refused) return { text: refused, isError: true };const member = agentsCallMember(name, args);@@ -294,20 +301,15 @@ export async function callTool(called: string, input: Json, context: ToolCallConisError: true,};}- const send = (withMyFolder: boolean) => api("/api/internal/coordinate-bots", { method: "POST", body: JSON.stringify({- ...(withMyFolder ? { inMyFolder: canonical.in_my_folder } : {}),+ const r = await api("/api/internal/coordinate-bots", { method: "POST", body: JSON.stringify({groupId: canonical.group_id, botIds: ids, message: canonical.message,reason: typeof canonical.reason === "string" && canonical.reason.trim() ? canonical.reason.trim() : undefined,rework: canonical.rework,thread: canonical.thread, reply: canonical.reply,- title: typeof canonical.title === "string" && canonical.title.trim() ? canonical.title.trim() : undefined, consult: canonical.consult,+ title: typeof canonical.title === "string" && canonical.title.trim() ? canonical.title.trim() : undefined, consult: canonical.consult, inMyFolder: canonical.in_my_folder,done_when: typeof canonical.done_when === "string" && canonical.done_when.trim() ? canonical.done_when.trim() : undefined,answers: typeof canonical.answers === "string" && canonical.answers.trim() ? canonical.answers.trim() : undefined,}) });- let r = await send(true);- // A conversation with no project folder has nothing to share, and the whole hand-off fails for the flag. Send it- // again without; the bot keeps its work instead of reporting a step it cannot explain.- if (!r.ok && /in_my_folder cannot be used/i.test(String(r.result ?? ""))) r = await send(false);return { text: JSON.stringify(r), ...(r.error ? { isError: true } : {}) };}if (name === "assignment_status") {diff --git a/server/handoff-in-my-folder.e2e.test.ts b/server/handoff-in-my-folder.e2e.test.tsindex 97c625174b..5d473ff4b6 100644--- a/server/handoff-in-my-folder.e2e.test.ts+++ b/server/handoff-in-my-folder.e2e.test.ts@@ -5,7 +5,7 @@ import { join } from "node:path";import { expect, it } from "vitest";import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";-it("starts a teammate's thread in the delegating bot's project folder by default, and refuses an explicit in_my_folder when there is none", async () => {+it("starts a teammate's thread in the delegating bot's project folder by default, and hands off without one when there is none, even when asked", async () => {const session = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });const { url, dataDir } = session.info;const cli = (...args: string[]) => runControlOmb([...args, "--url", url]) as Promise<any>;@@ -34,12 +34,12 @@ it("starts a teammate's thread in the delegating bot's project folder by defaultawait api("PATCH", `/api/bots/${sam.id}`, { cwd: site });await api("PATCH", `/api/bots/${cliff.id}`, { cwd: own });- const ask = (thread: string, inMyFolder?: boolean, expectError = false) =>- ({ arguments: { bot_ids: [cliff.id], message: "Draft the launch post.", thread, ...(inMyFolder === undefined ? {} : { in_my_folder: inMyFolder }) }, ...(expectError ? { expectError } : {}) });+ const ask = (thread: string, inMyFolder?: boolean) =>+ ({ arguments: { bot_ids: [cliff.id], message: "Draft the launch post.", thread, ...(inMyFolder === undefined ? {} : { in_my_folder: inMyFolder }) } });writeFileSync(join(dataDir, "room-plan.json"), JSON.stringify({[sam.id]: { steps: [ask("standing")], reply: "Assigned", resumeReply: "Done" },- // Pip has no folder of its own: its conversation runs in a private task folder.- [pip.id]: { steps: [ask("standing", true, true), ask("new", true, true), ask("standing")], reply: "Could not hand it over" },+ // Pip has no folder of its own: its conversation runs in a private task folder, so in_my_folder has nothing to share.+ [pip.id]: { steps: [ask("standing", true)], reply: "Handed over" },[cliff.id]: { reply: "Drafted", writeFiles: { "cliff-was-here.txt": "yes" } },}));@@ -54,9 +54,8 @@ it("starts a teammate's thread in the delegating bot's project folder by defaultawait expect.poll(() => evidence().some((turn) => turn.botId === pip.id && Array.isArray(turn.evidence)), { timeout: 40_000 }).toBe(true);const replies = evidence().find((turn) => turn.botId === pip.id).evidence.filter((entry: any) => entry?.step).map((entry: any) => String(entry.response.result?.content?.[0]?.text ?? JSON.stringify(entry.response)));- expect(replies).toHaveLength(3);- expect(replies[0]).toMatch(/no project folder/);- expect(replies[1]).toMatch(/no project folder/);+ expect(replies).toHaveLength(1);+ expect(replies[0]).not.toMatch(/in_my_folder|no project folder/);await expect.poll(() => existsSync(join(own, "cliff-was-here.txt")), { timeout: 40_000 }).toBe(true);} finally {await session.close();diff --git a/server/index.ts b/server/index.tsindex 33ca6c1391..32abaf1516 100644--- a/server/index.ts+++ b/server/index.ts@@ -13752,7 +13752,6 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const targets = botIds.map(botId => roomHandoffTarget({ groupId: destination?.id, threadId: roomThreadId ?? store.bot(botId)?.threadId ?? "", botId }, address));const direct = targets.some(target => !target.groupId), fresh = direct && call.thread === "new";const folder = inMyFolderCwd(call.inMyFolder, direct, store.taskByThread(internalSender.id, address.threadId)?.cwd, DATA_DIR);- if (folder.error) return refuse(400, folder.error);if (fresh && !EXTERNAL && internalCapability.openedThreads >= MAX_THREADS_OPENED_PER_TURN) {return refuse(429, `You have already opened ${MAX_THREADS_OPENED_PER_TURN} threads this turn, which is the limit. Do not retry — finish your turn and tell the person which threads you still wanted to open, so they can open them or ask you again.`);}