Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Agents tools: a blank optional id asks for the make, not the update
milind-soni42287c2cb638
diff --git a/packages/phone-protocol/src/agents-tool-names.ts b/packages/phone-protocol/src/agents-tool-names.tsindex 46de64ad2a..e226cc52df 100644--- a/packages/phone-protocol/src/agents-tool-names.ts+++ b/packages/phone-protocol/src/agents-tool-names.ts@@ -5,7 +5,9 @@// tool of its own.type Args = Record<string, unknown>;-const given = (args: Args, key: string) => args[key] !== undefined && args[key] !== null;+/** Whether the call carries this argument. A blank string is how a model leaves an optional one out, so it must not+ * route the call to the member that needs it: a page sent with `app_id: ""` makes a page, it does not update one. */+const given = (value: unknown) => value !== undefined && value !== null && (typeof value !== "string" || value.trim() !== "");function record(value: unknown): value is Args {return value !== null && typeof value === "object" && !Array.isArray(value);@@ -22,9 +24,9 @@ export const AGENTS_ACTION_TOOLS: Readonly<Record<string, AgentsActionTool>> = {trigger: { members: ["create_trigger", "manage_trigger"], member: (args) => args.action === "create" ? "create_trigger" : "manage_trigger" },delete_trigger: { members: ["manage_trigger"], member: () => "manage_trigger" },manage_room: { members: ["manage_room", "create_room"], member: (args) => args.action === "create" ? "create_room" : "manage_room" },- session_search: { members: ["session_search", "session_read"], member: (args) => given(args, "thread_id") || given(args, "message_id") ? "session_read" : "session_search" },- show_widget: { members: ["show_widget", "update_widget"], member: (args) => given(args, "widget_id") ? "update_widget" : "show_widget" },- show_html: { members: ["show_html", "update_html"], member: (args) => given(args, "app_id") ? "update_html" : "show_html" },+ session_search: { members: ["session_search", "session_read"], member: (args) => given(args.thread_id) || given(args.message_id) ? "session_read" : "session_search" },+ show_widget: { members: ["show_widget", "update_widget"], member: (args) => given(args.widget_id) ? "update_widget" : "show_widget" },+ show_html: { members: ["show_html", "update_html"], member: (args) => given(args.app_id) ? "update_html" : "show_html" },x_search: {members: ["x_search", "x_user_posts", "x_post", "x_profile"],member: (args) => args.action === "user_posts" ? "x_user_posts" : args.action === "post" ? "x_post" : args.action === "profile" ? "x_profile" : "x_search",@@ -39,8 +41,9 @@ export interface AgentsAlias {}const as = (name: string, args: Args) => ({ name, arguments: args });-/** An id the call must carry to mean an update: empty when it was left out, so the tool refuses rather than creates. */-const required = (args: Args, key: string): Args => ({ ...args, [key]: args[key] ?? "" });+/** An id the call must carry to mean an update. One left out or blank becomes `false`, which still reads as given, so+ * the update is refused for its type rather than quietly creating a page or widget instead. */+const required = (args: Args, key: string): Args => ({ ...args, [key]: given(args[key]) ? args[key] : false });export const AGENTS_TOOL_ALIASES: Readonly<Record<string, AgentsAlias>> = {list_triggers: { tools: ["trigger_info"], resolve: (args) => as("trigger_info", { ...args, action: "list" }) },diff --git a/packages/phone-protocol/src/app.ts b/packages/phone-protocol/src/app.tsindex 7bc4f0d25e..94cc649bf0 100644--- a/packages/phone-protocol/src/app.ts+++ b/packages/phone-protocol/src/app.ts@@ -308,13 +308,16 @@ function checkJsx(value: unknown): AppInputResult<string> {function checkPage(input: Record<string, unknown>): AppInputResult<{ html: string } | { jsx: string } | { path: string }> {const given = (value: unknown) => value !== undefined && value !== null;- if ([input.html, input.jsx, input.path].filter(given).length > 1) return { ok: false, error: "Send one of html, jsx or path." };- if (given(input.path)) {+ const filled = (value: unknown) => given(value) && (typeof value !== "string" || value.trim() !== "");+ // A model that means one of these leaves the others as "", so a blank one must not compete with the one it filled in.+ const carries = [input.html, input.jsx, input.path].some(filled) ? filled : given;+ if ([input.html, input.jsx, input.path].filter(carries).length > 1) return { ok: false, error: "Send one of html, jsx or path." };+ if (carries(input.path)) {const path = typeof input.path === "string" ? input.path.trim() : "";if (!path || path.length > 4_096) return { ok: false, error: "path: the folder with index.html, or the .html file, in your working folder." };return { ok: true, value: { path } };}- if (given(input.jsx)) {+ if (carries(input.jsx)) {const jsx = checkJsx(input.jsx);return jsx.ok ? { ok: true, value: { jsx: jsx.value } } : jsx;}diff --git a/server/drivers/agents-blank-ids.test.ts b/server/drivers/agents-blank-ids.test.tsnew file mode 100644index 0000000000..eca99ad4e2--- /dev/null+++ b/server/drivers/agents-blank-ids.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from "vitest";++import { agentsCallIdentities, agentsCallMember, resolveAgentsCall } from "../../shared/agents-tool-names.ts";+import { parseShowHtmlInput, parseUpdateHtmlInput } from "../../shared/app.ts";+import { allowsTool } from "../../shared/tool-scope.ts";+import { WIDGET_SAMPLES } from "../../shared/widget-samples.ts";++import { callTool, type ToolCallContext } from "./agents-call.ts";+import type { Json } from "./agents-client.ts";++async function run(name: string, args: Json, answer: Json = { ok: true, messageId: "m1" }) {+ const sent: Array<{ path: string; body?: Json }> = [];+ const client: ToolCallContext["client"] = {+ api: async (path, init) => {+ sent.push({ path, ...(init?.body === undefined ? {} : { body: JSON.parse(init.body) as Json }) });+ return answer;+ },+ apiResponse: async (path, init) => ({ ok: true, status: 200, body: await client.api(path, init) }),+ };+ const result = await callTool(name, args, {+ botId: "bot-blank", threadId: "thread-blank", depth: 0, externalRuntime: false, sharedComputers: true, client,+ });+ return { result, sent };+}++/** Each tool that does two things, the id that decides which, and a call that carries no id at all. */+const ROUTES = [+ { name: "session_search", update: "session_read", key: "thread_id", args: { query: "site audit" } },+ { name: "show_html", update: "update_html", key: "app_id", args: { html: "<h1>test</h1>", title: "Test" } },+ { name: "show_widget", update: "update_widget", key: "widget_id", args: { widget: WIDGET_SAMPLES.buildStatus } },+];++describe("a blank id asks for the plain operation", () => {+ it.each(ROUTES)("$name with a blank $key makes instead of updating", async ({ name, update, key, args }) => {+ for (const blank of ["", " \t "]) {+ const input = { ...args, [key]: blank };+ expect(agentsCallMember(name, input)).toBe(name);+ const resolved = resolveAgentsCall(name, input);+ expect(resolved.name).toBe(name);+ expect(agentsCallMember(resolved.name, resolved.arguments)).toBe(name);+ expect(agentsCallIdentities(name, input)).toEqual([[name]]);+ // An "always allow" saved for the plain tool must cover this call; one saved for the update must not.+ const tool = { kind: "mcp" as const, server: "agents", name };+ expect(allowsTool({ allow: [`mcp:agents:${name}`] }, tool, input)).toBe(true);+ expect(allowsTool({ allow: [`mcp:agents:${update}`] }, tool, input)).toBe(false);++ const { result, sent } = await run(name, input);+ expect(result.isError).toBeFalsy();+ expect(sent).toHaveLength(1);+ if (name === "session_search") expect(sent[0]!.path).toMatch(/^\/api\/internal\/session-search\?/);+ else expect(sent[0]!.body).not.toHaveProperty(key);+ }+ });++ it.each(ROUTES)("$update without an id still refuses before any request", async ({ update, key, args }) => {+ for (const input of [args, { ...args, [key]: "" }, { ...args, [key]: " " }]) {+ const { result, sent } = await run(update, input);+ expect(result.isError).toBe(true);+ expect(sent).toEqual([]);+ }+ });+});++describe("a non-text id is not read as a name", () => {+ it.each([false, 0, ["thread-1"], { id: "thread-1" }])("refuses %j rather than reading a message from it", async (thread_id) => {+ const { result, sent } = await run("session_read", { thread_id, message_id: "m1" });+ expect(result).toMatchObject({ isError: true, text: expect.stringContaining("needs both thread_id and message_id") });+ expect(sent).toEqual([]);+ });++ it("keeps a half-filled read a refusal", async () => {+ const { result, sent } = await run("session_search", { query: "audit", thread_id: "thread-old", message_id: "" });+ expect(result).toMatchObject({ isError: true, text: expect.stringContaining("needs both thread_id and message_id") });+ expect(sent).toEqual([]);+ });+});++describe("a blank page source does not compete with the one that carries content", () => {+ const sources = [+ { html: "<h1>test</h1>", jsx: "", path: "" },+ { html: "", jsx: "export default function Test() { return <h1>test</h1>; }", path: " \t" },+ { html: " ", jsx: "", path: "page.html" },+ ];++ it.each(sources)("accepts %j for both a new page and a replaced one", async (source) => {+ expect(parseShowHtmlInput({ ...source, title: "Test" })).toMatchObject({ ok: true });+ expect(parseUpdateHtmlInput({ ...source, app_id: "m1" })).toMatchObject({ ok: true });+ const { result, sent } = await run("show_html", { ...source, title: "Test" });+ expect(result.isError).toBeFalsy();+ expect(sent).toHaveLength(1);+ expect(sent[0]!.body).not.toHaveProperty("app_id");+ });++ it("still refuses missing content and two sources that both carry some", () => {+ for (const source of [+ { html: "", jsx: "", path: "" },+ { html: " ", jsx: " \t", path: "" },+ { html: "<p>one</p>", jsx: "export default 1" },+ { html: "<p>one</p>", path: 0 },+ ]) {+ expect(parseShowHtmlInput({ ...source, title: "Test" }).ok).toBe(false);+ }+ expect(parseUpdateHtmlInput({ html: "<p>one</p>", jsx: "", path: "" })).toMatchObject({+ ok: false,+ error: expect.stringMatching(/^app_id:/),+ });+ });+});diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.tsindex 87023d7de2..24ca34b498 100644--- a/server/drivers/agents-call.ts+++ b/server/drivers/agents-call.ts@@ -853,8 +853,8 @@ export async function callTool(called: string, input: Json, context: ToolCallCon}if (member === "session_read") {if (args.scope === "threads" && typeof args.thread_id === "string") return { text: threadReadText(await api(`/api/internal/session-search?${new URLSearchParams({ fromBotId: BOT_ID, fromThreadId: THREAD_ID, scope: "threads", threadId: args.thread_id.trim(), ...(typeof args.message_id === "string" && args.message_id.trim() ? { before: args.message_id.trim() } : {}), ...(typeof args.limit === "number" && Number.isFinite(args.limit) ? { limit: String(Math.trunc(args.limit)) } : {}) }).toString()}`)) };- const threadId = String(args.thread_id ?? "").trim();- const messageId = String(args.message_id ?? "").trim();+ const threadId = typeof args.thread_id === "string" ? args.thread_id.trim() : "";+ const messageId = typeof args.message_id === "string" ? args.message_id.trim() : "";if (!threadId || !messageId) {return { text: "Reading a message needs both thread_id and message_id, copied from a session_search hit.", isError: true };}