Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Drop the #4940 port from the train: the tool-name change is bundled into app-host.html, which then needs a rebuild
milind-soni658ee0755ae1
diff --git a/packages/phone-protocol/src/agents-tool-names.ts b/packages/phone-protocol/src/agents-tool-names.tsindex e226cc52df..46de64ad2a 100644--- a/packages/phone-protocol/src/agents-tool-names.ts+++ b/packages/phone-protocol/src/agents-tool-names.ts@@ -5,9 +5,7 @@// tool of its own.type Args = Record<string, unknown>;-/** 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() !== "");+const given = (args: Args, key: string) => args[key] !== undefined && args[key] !== null;function record(value: unknown): value is Args {return value !== null && typeof value === "object" && !Array.isArray(value);@@ -24,9 +22,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",@@ -41,9 +39,8 @@ export interface AgentsAlias {}const as = (name: string, args: Args) => ({ name, arguments: args });-/** 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 });+/** 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] ?? "" });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 94cc649bf0..7bc4f0d25e 100644--- a/packages/phone-protocol/src/app.ts+++ b/packages/phone-protocol/src/app.ts@@ -308,16 +308,13 @@ 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;- 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)) {+ 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 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 (carries(input.jsx)) {+ if (given(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.tsdeleted file mode 100644index 138b4693db..0000000000--- a/server/drivers/agents-blank-ids.test.ts+++ /dev/null@@ -1,108 +0,0 @@-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", 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 0b059c7dc0..bf9786a309 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 = typeof args.thread_id === "string" ? args.thread_id.trim() : "";- const messageId = typeof args.message_id === "string" ? args.message_id.trim() : "";+ const threadId = String(args.thread_id ?? "").trim();+ const messageId = 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 };}