Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Only a person's own request opens threads on a bot itself, again
milind-soni3693dc28083f
diff --git a/server/host/self-threads.test.ts b/server/host/self-threads.test.tsnew file mode 100644index 0000000000..2e6ea0c1a8--- /dev/null+++ b/server/host/self-threads.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from "vitest";+import { SELF_THREAD_REFUSAL, selfThreadRefusal } from "./self-threads.ts";++describe("selfThreadRefusal", () => {+ it("lets a person's own request, or a routine's, open threads on the bot", () => {+ expect(selfThreadRefusal({ handoff: false, requestLine: {} })).toBeUndefined();+ expect(selfThreadRefusal({ handoff: false, requestLine: undefined })).toBeUndefined();+ });++ it("refuses a teammate's hand-off, and a thread the bot opened on itself", () => {+ expect(selfThreadRefusal({ handoff: true, requestLine: {} })).toBe(SELF_THREAD_REFUSAL);+ expect(selfThreadRefusal({ handoff: false, requestLine: { peerAsk: { botId: "post" } } })).toBe(SELF_THREAD_REFUSAL);+ });+});diff --git a/server/host/self-threads.ts b/server/host/self-threads.tsnew file mode 100644index 0000000000..6dbe92e66a--- /dev/null+++ b/server/host/self-threads.ts@@ -0,0 +1,12 @@+// Who may open a job on itself with start_thread: work a person, or their routine, asked for in this conversation. A+// teammate's hand-off, or a job the bot opened on itself, finishes its own work: a new thread is a new request, outside+// the depth, budget and stop of the one it would serve, so a chain could grow there without end. This was the rule until+// every hand-off moved onto the runtime (Oct 12), and the tool's description still says it.++export const SELF_THREAD_REFUSAL = "Only a person's own request can open separate threads on yourself, and this turn works on a teammate's hand-off or on a thread you opened yourself. Do the work here, and end with what is still left, so whoever asked can decide. Do not retry.";++/** `handoff`: this turn runs a teammate's hand-off. `requestLine`: the latest line from the user role in this conversation,+ * which a bot's own opening or a teammate's ask marks with `peerAsk`; a person's or a routine's line has none. */+export function selfThreadRefusal(input: { handoff: boolean; requestLine: { peerAsk?: unknown } | undefined }): string | undefined {+ return input.handoff || input.requestLine?.peerAsk ? SELF_THREAD_REFUSAL : undefined;+}diff --git a/server/index.ts b/server/index.tsindex 8d66da0e6f..8cf0b991e6 100644--- a/server/index.ts+++ b/server/index.ts@@ -629,7 +629,7 @@ import { createReactions, withReactionNotes, type Reactor } from "./reactions.tsimport { createPersonReplies } from "./person-replies.ts";import { personKey, relayedPersonKey } from "./person-key.ts";import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";-import { createDevsReports } from "./host/devs-reports.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";+import { createDevsReports } from "./host/devs-reports.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts"; import { selfThreadRefusal } from "./host/self-threads.ts";import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts";import { createThreadRoutes } from "./routes/threads.ts";import { createWebhookRoutes } from "./routes/webhooks.ts";@@ -14294,7 +14294,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}const sourceTitle = owner.group ? owner.group.name : (store.taskByThread(from.id, fromThreadId)?.title ?? "");const picked = body.modelSelection === undefined ? null : checkedModelSelection(body.modelSelection, undefined, true); const refused = !picked ? null : target.id !== from.id ? "model_selection is only for threads on yourself" : !picked.ok ? picked.error : validateModelProposal(picked.selection, from); if (refused) return json(res, 400, { error: refused });- if (target.id === from.id) {+ if (target.id === from.id) { const selfRefused = selfThreadRefusal({ handoff: Boolean(internalCapability.roomHandoffId), requestLine: store.activePath(fromThreadId).findLast((line) => line.role === "user" && line.kind === "text") }); if (selfRefused) return json(res, 409, { error: selfRefused });const inherited = picked?.ok ? { modelSelection: picked.selection, approvalMode: undefined } : parentThreadModel(from.id, fromThreadId);const task = store.createTask(from.id, title, false, projectId, { botId: from.id, name: from.name, at: Date.now() }, inherited.approvalMode, inherited.modelSelection);if (!task) return json(res, 500, { error: "couldn't create that thread" });diff --git a/server/self-threads.e2e.test.ts b/server/self-threads.e2e.test.tsnew file mode 100644index 0000000000..4c7b7bf121--- /dev/null+++ b/server/self-threads.e2e.test.ts@@ -0,0 +1,56 @@+// Who may open a job on itself (start_thread), end to end on the scripted engine. Only a person's own request may: a+// teammate's hand-off and a job the bot opened on itself finish their own work, so a chain can't grow outside the depth,+// budget and stop of the request it serves. The tool's description says so; the server enforces it again here.+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";+import { request } from "../scripts/mcp-server.ts";++const SETTLED = "Your downstream room requests have settled.";++it("opens threads on a bot only for a person's own request, never from a hand-off or a job it opened itself", async () => {+ const session = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });+ const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: session.info.url } }) as Promise<any>;+ const api = (path: string, body?: unknown, method = "POST") =>+ request(path, body === undefined ? {} : { method, body: JSON.stringify(body) }, session.info.url) as Promise<any>;+ try {+ const asker = (await cli("new-bot", "--name", "Asker")).bot;+ const books = (await cli("new-bot", "--name", "Books")).bot;+ const planPath = join(session.info.dataDir, "room-plan.json");+ const open = (title: string, message: string, expectError: boolean) => ({ tool: "start_thread", arguments: { title, message }, expectError });+ writeFileSync(planPath, JSON.stringify({+ [asker.id]: { script: [+ { key: "J1", match: ["J1-JOB"], steps: [{ arguments: { bot_ids: [books.id], message: "J1-ASK: check each ledger, one thread per ledger" } }], reply: "J1: asked Books." },+ { key: "J1-DONE", match: [SETTLED, "J1-JOB"], reply: "J1-DONE: Books checked the ledgers." },+ ] },+ [books.id]: { script: [+ { key: "J1-ASK", match: ["J1-ASK"], steps: [open("Ledger 1", "J1-SELF: check ledger 1", true)], reply: "J1-ASK: checked both ledgers here." },+ { key: "J2", match: ["J2-JOB"], steps: [open("Ledger A", "J2-SELF: check ledger A", false)], reply: "J2: opened Ledger A." },+ { key: "J2-SELF", match: ["J2-SELF"], steps: [open("Sub-ledger", "J2-DEEPER: check the sub-ledger", true)], reply: "J2-SELF: ledger A balances." },+ ] },+ }));+ const evidence = (): any[] => existsSync(`${planPath}.evidence.jsonl`)+ ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];+ const result = (key: string) => evidence().find((turn) => turn.planKey === key)?.evidence.find((entry: any) => entry.step?.tool === "start_thread")?.response.result;+ const titles = async () => ((await api("/api/bots")).bots.find((bot: any) => bot.id === books.id).tasks as any[]).map((task) => task.title);++ // A teammate's hand-off: the work is done in the hand-off's thread.+ await cli("send", "--bot", asker.id, "--task", asker.activeTaskId, "--text", "J1-JOB: have Books check the ledgers");+ await expect.poll(() => evidence().some((turn) => turn.planKey === "J1-DONE"), { timeout: 20_000 }).toBe(true);+ expect(result("J1-ASK").isError).toBe(true);+ expect(JSON.stringify(result("J1-ASK"))).toContain("Only a person's own request can open separate threads on yourself");++ // The person's own request opens a job; that job opens no more.+ await cli("send", "--bot", books.id, "--task", books.activeTaskId, "--text", "J2-JOB: open one thread per ledger");+ await expect.poll(() => evidence().some((turn) => turn.planKey === "J2-SELF"), { timeout: 20_000 }).toBe(true);+ expect(result("J2").isError).toBeFalsy();+ expect(result("J2-SELF").isError).toBe(true);+ expect(await titles()).toContain("Ledger A");+ expect(await titles()).not.toContain("Ledger 1");+ expect(await titles()).not.toContain("Sub-ledger");+ expect(evidence().some((turn) => turn.planKey === undefined)).toBe(false);+ } finally {+ await session.close();+ }+}, 90_000);