Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: reject malformed start_thread recipients before creating work
guanxing0619-collab40e7cf31539e
diff --git a/docs/verification/claude-tool-lifecycle.md b/docs/verification/claude-tool-lifecycle.mdindex c819300952..be68493b79 100644--- a/docs/verification/claude-tool-lifecycle.md+++ b/docs/verification/claude-tool-lifecycle.md@@ -108,6 +108,22 @@ These fixture checks do not prove that a customer's real provider account ornetwork is healthy. Ask for their app version, Claude CLI version, and aredacted diagnostic export if failures remain; do not request credentials.+`start_thread` refuses unknown arguments before opening work. A misspelled+recipient such as `bot` must not turn a teammate assignment into a task on the+sender. A valid legacy `bot_id` remains supported, but an empty or non-string+one is refused instead of defaulting to the sender.++```sh+pnpm exec vitest run server/drivers/agents-proxy.test.ts server/start-thread-routing.e2e.test.ts+```++The isolated fixture sends the malformed call through the real agents proxy,+checks that neither bot gained a task, then sends the corrected+`coordinate_bots` call and reads the recipient's completed conversation. It+retains the commands, waits, transcript and resulting task IDs beside the+server log as `.log.json`. It uses a scripted provider and does not establish+why a real model or relay produced the malformed arguments.+## Rebuilt conversationsEditing a message or rebuilding context must start a new Claude session,diff --git a/server/drivers/agents-proxy.test.ts b/server/drivers/agents-proxy.test.tsindex 05b9736d20..2a9010733c 100644--- a/server/drivers/agents-proxy.test.ts+++ b/server/drivers/agents-proxy.test.ts@@ -987,6 +987,30 @@ describe("agents-proxy MCP surface", () => {expect(start.description).not.toMatch(/\b(delegate_bot|ask_bot)\b/);});+ it.each(["bot", "botId", "toBotId", "bot_ids", "reportBack"])("start_thread refuses unknown %s before creating a task", async (key) => {+ const before = threadCalls;+ const res = await callTool("start_thread", { title: "Review", message: "Review the patch.", [key]: "Helper" });+ expect(res.result.isError).toBe(true);+ expect(res.result.content[0].text).toContain(`unknown arguments "${key}"`);+ expect(res.result.content[0].text).toContain("coordinate_bots with bot_ids from read_team");+ expect(threadCalls).toBe(before);+ });++ it.each([null, "", " ", 42, ["bot-helper"], { id: "bot-helper" }])("start_thread refuses an invalid legacy bot_id %j instead of falling back to itself", async (bot_id) => {+ const before = threadCalls;+ const res = await callTool("start_thread", { title: "Review", message: "Review the patch.", bot_id });+ expect(res.result.isError).toBe(true);+ expect(res.result.content[0].text).toContain("bot_id must be a non-empty bot ID");+ expect(threadCalls).toBe(before);+ });++ it("start_thread does not ignore a conflicting recipient alias beside a valid legacy bot_id", async () => {+ const before = threadCalls;+ const res = await callTool("start_thread", { title: "Review", message: "Review the patch.", bot_id: "bot-helper", bot: "Another helper" });+ expect(res.result.isError).toBe(true);+ expect(threadCalls).toBe(before);+ });+it("start_thread on a teammate is a hand-off into a fresh thread: the receipt's thread and assignment id, no deprecation line", async () => {const previous = threadResponse;threadResponse = { receipts: [{ botId: "bot-helper", botName: "Helper", outcome: "queued", detail: "handed to the coordinator; the teammate's turn has not started yet", requestId: "asg-peer-9", threadId: "thread-peer" }],diff --git a/server/drivers/agents-schema.ts b/server/drivers/agents-schema.tsindex 2bcdf43897..d2f0dbc7fb 100644--- a/server/drivers/agents-schema.ts+++ b/server/drivers/agents-schema.ts@@ -84,10 +84,25 @@ function check(node: unknown, value: unknown, where: string, problems: string[])}}+function startThreadArgumentProblem(schema: unknown, args: Json): string | undefined {+ const properties = record(schema) && record(schema.properties) ? schema.properties : {};+ const unknown = Object.keys(args).filter((key) => key !== "bot_id" && !Object.hasOwn(properties, key));+ if (unknown.length) {+ return `start_thread was not run: unknown arguments ${unknown.map((key) => JSON.stringify(key)).join(", ")}. It opens a task on yourself. To hand work to a teammate, use coordinate_bots with bot_ids from read_team and thread "new".`;+ }+ if (Object.hasOwn(args, "bot_id") && (typeof args.bot_id !== "string" || !args.bot_id.trim())) {+ return 'start_thread was not run: bot_id must be a non-empty bot ID. For a teammate, use coordinate_bots with bot_ids from read_team and thread "new"; for a task on yourself, omit bot_id.';+ }+ return undefined;+}+/** Why `args` falls outside the full schema's bounds, in words a model can act on; undefined when it fits. A null* stands for a field left out, as providers send unused optional fields. Types, enums and required fields are each- * tool's own to check: several accept a stringified object, a camelCase alias or a case variant on purpose. */+ * tool's own to check: several accept a stringified object, a camelCase alias or a case variant on purpose.+ * start_thread also rejects unknown fields and malformed legacy recipients so neither can silently select self. */export function outOfBounds(tool: string, schema: unknown, args: Json): string | undefined {+ const targetProblem = tool === "start_thread" ? startThreadArgumentProblem(schema, args) : undefined;+ if (targetProblem) return targetProblem;const problems: string[] = [];check(schema, args, "", problems);if (!problems.length) return undefined;diff --git a/server/start-thread-routing.e2e.test.ts b/server/start-thread-routing.e2e.test.tsnew file mode 100644index 0000000000..97a6d04ef2--- /dev/null+++ b/server/start-thread-routing.e2e.test.ts@@ -0,0 +1,69 @@+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { expect, it } from "vitest";+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";++it("rejects a misspelled start_thread recipient without creating work, then delivers the corrected handoff", async () => {+ const fixture = await launchVerificationServer({}, undefined, undefined, undefined, undefined, { scripted: true });+ const { url, dataDir, logPath } = fixture.info;+ const planPath = join(dataDir, "room-plan.json");+ const evidence: unknown[] = [];+ const cli = async (...args: string[]) => {+ const result = await runControlOmb([...args, "--url", url]) as any;+ evidence.push({ command: [...args, "--url", url], result });+ return result;+ };+ const api = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(url + path, { method, headers: { "content-type": "application/json", origin: url },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(10_000) });+ const result = await response.json() as any;+ expect(response.ok, JSON.stringify(result)).toBe(true);+ return result;+ };+ const turns = (): any[] => existsSync(`${planPath}.evidence.jsonl`)+ ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map(line => JSON.parse(line)) : [];+ try {+ const sender = (await cli("new-bot", "--name", "Coordinator", "--section", "Review")).bot;+ const recipient = (await cli("new-bot", "--name", "Reviewer", "--section", "Review")).bot;+ await api("PATCH", `/api/bots/${sender.id}`, { chiefOfStaff: true });+ const taskIds = async () => (await api("GET", "/api/bots")).bots+ .filter((bot: any) => [sender.id, recipient.id].includes(bot.id))+ .map((bot: any) => ({ id: bot.id, threads: bot.tasks.map((task: any) => task.threadId) }));+ const before = await taskIds();+ const title = "Review the fixture patch";+ const message = "Check the fixture patch and report the result.";+ const plans = {+ [sender.id]: { turns: [+ { steps: [{ tool: "start_thread", arguments: { bot: recipient.name, title, message }, expectError: true }], reply: "The recipient argument was refused." },+ { steps: [{ tool: "coordinate_bots", arguments: { bot_ids: [recipient.id], thread: "new", title, message, request_key: "fixture-review" } }], reply: "Sent the review." },+ { reply: "The reviewer finished." },+ ] },+ [recipient.id]: { reply: "Fixture patch reviewed." },+ };+ writeFileSync(planPath, JSON.stringify(plans));+ await cli("send", "--bot", sender.id, "--task", sender.activeTaskId, "--text", "Ask Reviewer to review the fixture patch.");+ expect((await cli("wait", "--bot", sender.id, "--task", sender.activeTaskId, "--timeout", "30")).status).toBe("settled");+ expect(await taskIds()).toEqual(before);+ const rejected = turns().find(turn => turn.botId === sender.id).evidence.find((entry: any) => entry.step?.tool === "start_thread");+ expect(rejected.response.result.isError).toBe(true);+ expect(rejected.response.result.content[0].text).toContain('unknown arguments "bot"');+ evidence.push({ rejected: rejected.response.result, tasksAfterRefusal: await taskIds() });++ await cli("send", "--bot", sender.id, "--task", sender.activeTaskId, "--text", "Use coordinate_bots to send the review.");+ await expect.poll(() => turns().find(turn => turn.botId === recipient.id), { timeout: 30_000 }).toBeTruthy();+ const recipientTurn = turns().find(turn => turn.botId === recipient.id);+ expect((await cli("wait", "--bot", recipient.id, "--task", recipientTurn.threadId, "--timeout", "30")).status).toBe("settled");+ expect((await cli("wait", "--bot", sender.id, "--task", sender.activeTaskId, "--timeout", "30")).status).toBe("settled");+ const transcript = await cli("messages", "--bot", recipient.id, "--task", recipientTurn.threadId, "--limit", "10");+ expect(JSON.stringify(transcript)).toContain(message);+ expect(JSON.stringify(transcript)).toContain("Fixture patch reviewed.");+ const after = await taskIds();+ expect(after.find((bot: any) => bot.id === sender.id)).toEqual(before.find((bot: any) => bot.id === sender.id));+ expect(after.find((bot: any) => bot.id === recipient.id).threads).toContain(recipientTurn.threadId);+ evidence.push({ tasksAfterHandoff: after });+ } finally {+ writeFileSync(`${logPath}.log.json`, JSON.stringify({ logPath, evidence }, null, 2));+ console.log(`Start-thread routing evidence: ${logPath}.log.json`);+ await fixture.close();+ }+}, 120_000);