Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
send --task new starts a new conversation, and says where the message went
milind-sonif3802edbc0d0
diff --git a/docs/headless-cli.md b/docs/headless-cli.mdindex e2f69b968f..39d09512c6 100644--- a/docs/headless-cli.md+++ b/docs/headless-cli.md@@ -72,7 +72,7 @@ one of its conversations.| `doctor [--wait 2m]` | Checks the server answers, is new enough, who you are to it (and when your session expires), that an engine is ready, and whether bots have a browser. || `bots`, `channels`, `models` | Your bots and what each is doing, your rooms, the engines and the models each offers. || `messages TARGET [--limit 30]` | The latest messages of a conversation. |-| `send TARGET TEXT` | Sends one message and returns at once. `--send-id ID` makes a retry safe: the same id never sends twice. |+| `send TARGET TEXT` | Sends one message and returns at once, to the conversation the bot or room has open. `--task new` starts a new conversation for it (`--title` names it, else the message's first line), and `--task ID` picks one. It says which conversation it went to. `--send-id ID` makes a retry safe: the same id never sends twice. || `run TARGET TEXT` | Gives a bot or room one job and waits until it is done (below). || `wait TARGET` | Waits on work already running. || `interrupt TARGET [--tree]` | Presses Stop. `--tree` also stops every teammate still working on its job, in that teammate's own conversation. |diff --git a/server/headless/args.ts b/server/headless/args.tsindex 0c9a396347..c1a93cf13e 100644--- a/server/headless/args.ts+++ b/server/headless/args.ts@@ -59,8 +59,8 @@ const VERBS: Record<string, { options: ParseArgsOptionsConfig; positionals: numbchannels: { options: {}, positionals: 0 },models: { options: {}, positionals: 0 },messages: { options: { ...TARGET, limit: { type: "string" } }, positionals: 1 },- send: { options: { ...TARGET, ...TEXT, "send-id": { type: "string" }, "dry-run": { type: "boolean" } }, positionals: 2 },- "send-channel": { options: { ...TARGET, ...TEXT, "send-id": { type: "string" }, "dry-run": { type: "boolean" } }, positionals: 2 },+ send: { options: { ...TARGET, ...TEXT, title: { type: "string" }, "send-id": { type: "string" }, "dry-run": { type: "boolean" } }, positionals: 2 },+ "send-channel": { options: { ...TARGET, ...TEXT, title: { type: "string" }, "send-id": { type: "string" }, "dry-run": { type: "boolean" } }, positionals: 2 },run: {options: { ...TARGET, ...TEXT, ...WAITING, title: { type: "string" }, wait: { type: "string" }, export: { type: "string" }, force: { type: "boolean" },"send-id": { type: "string" } },diff --git a/server/headless/commands.ts b/server/headless/commands.tsindex c4d803417d..da4a4f5087 100644--- a/server/headless/commands.ts+++ b/server/headless/commands.ts@@ -1,6 +1,6 @@// `--json` prints a tool's result unchanged; plain output is a line per item.import { EXIT, flag, parseCount, parseDuration, requiredFlag, usageError } from "./args.ts";-import { newSendId, readMessage, resolveTarget, type Target, type VerbContext, type VerbOutcome } from "./context.ts";+import { conversationFor, conversationTitle, newSendId, readMessage, resolveTarget, type Target, type VerbContext, type VerbOutcome } from "./context.ts";import { oneLine, shortId } from "./output.ts";import { stopConversation } from "./run.ts";@@ -9,7 +9,7 @@ type Rec = Record<string, any>;const dryRun = (ctx: VerbContext, tool: string, args: Rec, extra: Rec = {}): VerbOutcome | undefined =>ctx.flags["dry-run"] === true? { result: { ok: true, dryRun: true, command: ctx.verb, tool, arguments: args, ...extra }, exitCode: EXIT.done,- human: [`Would call ${tool} with ${JSON.stringify(args)}${extra.tree ? ", then stop every teammate still working on it" : ""}. Nothing was sent.`] }+ human: [`Would ${extra.newConversation ? `start a new conversation, "${extra.newConversation.title}", then ` : ""}call ${tool} with ${JSON.stringify(args)}${extra.tree ? ", then stop every teammate still working on it" : ""}. Nothing was sent.`] }: undefined;const targetArgs = (target: Target): Rec => ({ [`${target.type}_id`]: target.id, ...(target.taskId ? { task_id: target.taskId } : {}) });@@ -111,15 +111,21 @@ export async function send(ctx: VerbContext): Promise<VerbOutcome> {const named = Boolean(flag(ctx.flags, "bot") ?? flag(ctx.flags, "channel") ?? flag(ctx.flags, "thread"));const [first, second] = ctx.positionals;const text = await readMessage(ctx, named ? first : second);- const target = await resolveTarget(ctx, named ? undefined : first, channelOnly ? "channel" : "any");+ const task = flag(ctx.flags, "task")?.trim();+ const opened = task === "new" || task === "current" ? task : undefined;+ if (flag(ctx.flags, "title") !== undefined && opened !== "new") throw usageError("--title names a new conversation: add --task new");+ const target = await resolveTarget(opened ? { ...ctx, flags: { ...ctx.flags, task: undefined } } : ctx, named ? undefined : first, channelOnly ? "channel" : "any");const tool = target.type === "bot" ? "send_bot_message" : "send_channel_message";- const args = { ...targetArgs(target), text, send_id: flag(ctx.flags, "send-id") ?? newSendId() };- const preview = dryRun(ctx, tool, args);+ const title = opened === "new" && !target.taskId ? conversationTitle(ctx, text) : undefined;+ const current = opened === "current" && !target.taskId ? await conversationFor(await ctx.client(), target, "current") : undefined;+ const args = { ...targetArgs(current ? { ...target, taskId: current } : target), text, send_id: flag(ctx.flags, "send-id") ?? newSendId() };+ const preview = dryRun(ctx, tool, args, title !== undefined ? { newConversation: { title } } : {});if (preview) return preview;- const result = await (await ctx.client()).tool(tool, args);+ const client = await ctx.client();+ const result = await client.tool(tool, title !== undefined ? { ...args, task_id: await conversationFor(client, target, "new", title) } : args);return {- result, exitCode: EXIT.done,- human: [`Sent to ${target.name ?? target.id} (thread ${result.taskId})${result.queued ? "; it waits until the turn running there ends" : ""}.`,+ result: title !== undefined ? { ...result, newConversation: { title } } : result, exitCode: EXIT.done,+ human: [`Sent to ${target.name ?? target.id} ${title !== undefined ? `in a new conversation, "${title}", ` : ""}(thread ${result.taskId})${result.queued ? "; it waits until the turn running there ends" : ""}.`,`Follow it with: openmausbot wait --thread ${result.taskId}`],};}diff --git a/server/headless/context.ts b/server/headless/context.tsindex e9cd5f3345..ac459088f8 100644--- a/server/headless/context.ts+++ b/server/headless/context.ts@@ -82,6 +82,19 @@ export async function resolveTarget(ctx: VerbContext, positional: string | undefreturn withTask({ type, id: record.id, name: record.name });}+export async function conversationFor(client: HeadlessClient, target: Target, task: string, title = "Headless run"): Promise<string> {+ if (task === "new") return (await client.tool("create_task", { target_type: target.type, target_id: target.id, title })).task.taskId;+ if (task !== "current") return task;+ const fleet = await client.json<Fleet>("/api/bots?messages=0");+ const owner = (target.type === "bot" ? fleet.bots : fleet.groups)?.find((record) => record.id === target.id);+ if (!owner) throw usageError(`no ${target.type === "bot" ? "bot" : "room"} with id ${target.id}`);+ return owner.threadId;+}++/** --title, else the message's first line. */+export const conversationTitle = (ctx: VerbContext, text: string): string =>+ (flag(ctx.flags, "title") ?? text.split("\n")[0]!).trim().slice(0, 80) || "Headless run";+export async function readMessage(ctx: VerbContext, positional: string | undefined): Promise<string> {const text = flag(ctx.flags, "text");const file = flag(ctx.flags, "message-file");diff --git a/server/headless/main.ts b/server/headless/main.tsindex d3f9698581..4f4a1aed53 100644--- a/server/headless/main.ts+++ b/server/headless/main.ts@@ -23,10 +23,12 @@ export const VERB_HELP: Record<string, string> = {models: "openmausbot models\n The engines and the models each offers (use them as INSTANCE/MODEL).",messages: `openmausbot messages TARGET [--limit 30]\n The latest messages of a conversation (at most 200).${T}`,- send: `openmausbot send TARGET (TEXT | --text TEXT | --message-file FILE | -) [--send-id ID] [--dry-run]- Send one message and return at once. The same --send-id never sends twice.+ send: `openmausbot send TARGET (TEXT | --text TEXT | --message-file FILE | -) [--task new|current|ID] [--title T] [--send-id ID] [--dry-run]+ Send one message and return at once. It goes to the conversation the bot or room has open (--task current,+ the default), to a new one (--task new, titled by --title or the message's first line), or to --task ID.+ It says which conversation it went to. The same --send-id never sends twice.${T}`,- "send-channel": "openmausbot send-channel --channel ID (TEXT | --text TEXT) [--task ID] [--dry-run]\n The same as send, for a room named by id.",+ "send-channel": "openmausbot send-channel --channel ID (TEXT | --text TEXT) [--task new|current|ID] [--title T] [--dry-run]\n The same as send, for a room named by id.",run: `openmausbot run TARGET (TEXT | --message-file FILE | -) [--task new|current|ID] [--title T][--wait job|turn|none] [--timeout 30m] [--on-input exit|wait|stop] [--on-timeout leave|stop][--strict] [--export DIR [--force]]diff --git a/server/headless/run.ts b/server/headless/run.tsindex a948725633..d556c20635 100644--- a/server/headless/run.ts+++ b/server/headless/run.ts@@ -1,8 +1,9 @@// Exit codes: 0 done, 1 failed or stopped, 3 needs you, 4 timed out, 130 Ctrl-C (the work keeps running).import { messageFileTargets } from "../message-file.ts";-import { EXIT, flag, HeadlessError, oneOf, parseCount, usageError } from "./args.ts";+import { EXIT, flag, HeadlessError, oneOf, parseCount } from "./args.ts";import { readJob, type HeadlessClient } from "./client.ts";-import { newSendId, readMessage, resolveTarget, waitPolicy, type Target, type VerbContext, type VerbOutcome } from "./context.ts";+import { conversationFor, conversationTitle, newSendId, readMessage, resolveTarget, waitPolicy, type Target, type VerbContext,+ type VerbOutcome } from "./context.ts";import { exportFolder, exportJob } from "./export.ts";import { oneLine } from "./output.ts";@@ -172,17 +173,7 @@ export async function runVerb(ctx: VerbContext): Promise<VerbOutcome> {const task = flag(ctx.flags, "task")?.trim() || (flag(ctx.flags, "thread") ? undefined : "new");const target = await resolveTarget({ ...ctx, flags: { ...ctx.flags, task: undefined } }, named ? undefined : first);const client = await ctx.client();- let threadId: string;- if (target.taskId) threadId = target.taskId;- else if (task === "new") {- const title = (flag(ctx.flags, "title") ?? text.split("\n")[0]!).trim().slice(0, 80) || "Headless run";- threadId = (await client.tool("create_task", { target_type: target.type, target_id: target.id, title })).task.taskId;- } else if (task === "current") {- const fleet = await client.json<Rec>("/api/bots?messages=0");- const owner = (target.type === "bot" ? fleet.bots : fleet.groups)?.find((record: Rec) => record.id === target.id);- if (!owner) throw usageError(`no ${target.type === "bot" ? "bot" : "room"} with id ${target.id}`);- threadId = owner.threadId;- } else threadId = task!;+ const threadId = target.taskId ?? await conversationFor(client, target, task!, conversationTitle(ctx, text));const since = Number((await readJob(client, threadId)).now);const sendId = flag(ctx.flags, "send-id") ?? newSendId();const tool = target.type === "bot" ? "send_bot_message" : "send_channel_message";diff --git a/server/headless/send.test.ts b/server/headless/send.test.tsnew file mode 100644index 0000000000..dcca4d0722--- /dev/null+++ b/server/headless/send.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it, vi } from "vitest";++import type { HeadlessIo } from "./output.ts";+import { runHeadless } from "./main.ts";++type Rec = Record<string, any>;++function harness() {+ const calls: Array<{ name: string; args: Rec }> = [];+ const callTool = vi.fn(async (name: string, args: Rec) => {+ calls.push({ name, args });+ if (name === "create_task") return { success: true, task: { taskId: "fresh" } };+ if (name === "send_channel_message") return { success: true, channelId: args.channel_id, taskId: args.task_id ?? "r-active", messageId: "m1" };+ if (name === "send_bot_message") return { success: true, botId: args.bot_id, taskId: args.task_id ?? "b-active", messageId: "m1" };+ throw new Error(`unexpected tool ${name}`);+ });+ const request = vi.fn(async (path: string) => {+ if (path === "/api/bots?messages=0") {+ return { bots: [{ id: "lead", name: "Room Lead", threadId: "b-active", tasks: [{ threadId: "b-active" }] }],+ groups: [{ id: "room", name: "Launch Room", threadId: "r-active", tasks: [{ threadId: "r-active" }, { threadId: "r-old" }] }] };+ }+ throw new Error(`unexpected path ${path}`);+ });+ const out: string[] = [];+ const io: HeadlessIo = { out: (text) => out.push(text), err: () => undefined, readStdin: async () => "" };+ const run = async (argv: string[]) => {+ out.length = 0;+ const code = await runHeadless(argv, { env: { OPENMAUSBOT_URL: "http://127.0.0.1:19999" }, io, callTool: callTool as any, request: request as any });+ return { code, out: [...out] };+ };+ return { calls, run };+}++describe("send", () => {+ it("starts a new conversation in a room with --task new, titled by the message's first line, and names it", async () => {+ const h = harness();+ const { code, out } = await h.run(["send", "Launch Room", "Plan the launch\nwith everyone", "--task", "new"]);+ expect(code).toBe(0);+ expect(h.calls.map((call) => call.name)).toEqual(["create_task", "send_channel_message"]);+ expect(h.calls[0]!.args).toEqual({ target_type: "channel", target_id: "room", title: "Plan the launch" });+ expect(h.calls[1]!.args).toEqual({ channel_id: "room", task_id: "fresh", text: "Plan the launch\nwith everyone", send_id: expect.stringMatching(/^cli-/) });+ expect(out[0]).toBe('Sent to Launch Room in a new conversation, "Plan the launch", (thread fresh).');+ });++ it("takes --title for the new conversation, and reports it in --json", async () => {+ const h = harness();+ const { code, out } = await h.run(["send", "--bot", "lead", "hello", "--task", "new", "--title", "Daily check", "--json"]);+ expect(code).toBe(0);+ expect(h.calls[0]!.args).toEqual({ target_type: "bot", target_id: "lead", title: "Daily check" });+ expect(JSON.parse(out[0]!)).toMatchObject({ taskId: "fresh", newConversation: { title: "Daily check" } });+ });++ it("goes to the open conversation by default and with --task current, and to the one --task ID names", async () => {+ const h = harness();+ await h.run(["send", "Launch Room", "hello"]);+ await h.run(["send", "Launch Room", "hello", "--task", "current"]);+ await h.run(["send", "Launch Room", "hello", "--task", "r-old"]);+ expect(h.calls.map((call) => [call.name, call.args.task_id])).toEqual([+ ["send_channel_message", undefined], ["send_channel_message", "r-active"], ["send_channel_message", "r-old"]]);+ });++ it("starts nothing on --dry-run, and refuses --title without --task new", async () => {+ const h = harness();+ const preview = await h.run(["send", "Launch Room", "hello", "--task", "new", "--dry-run", "--json"]);+ expect(preview.code).toBe(0);+ expect(JSON.parse(preview.out[0]!)).toMatchObject({ dryRun: true, tool: "send_channel_message", newConversation: { title: "hello" } });+ expect(h.calls).toEqual([]);+ expect((await h.run(["send", "Launch Room", "hello", "--title", "T"])).code).toBe(2);+ expect(h.calls).toEqual([]);+ });+});