Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
refactor(routes): move calendar-calls out of index.ts
TuanNancy72ca081d0178
diff --git a/server/index.ts b/server/index.tsindex 6062126e74..c49d2d77c8 100644--- a/server/index.ts+++ b/server/index.ts@@ -576,6 +576,7 @@ import { createNoAiNotice } from "./host/no-ai-notice.ts"; import { PASS, ROUTESimport { createHostedSlackRoutes } from "./routes/hosted-slack.ts";import { createBotPresetRoutes } from "./routes/bot-presets.ts"; import { createWorkspaceBannerRoutes, workspaceBannerStore, workspaceBannerSummary } from "./routes/workspace-banner.ts";import { createBotMemoryRoutes } from "./routes/bot-memory.ts"; import { createBotLibraryRoutes } from "./routes/bot-library.ts";+import { createCalendarCallRoutes } from "./routes/calendar-calls.ts";import { createBotCreateRoutes } from "./routes/bots-create.ts"; import { privateUntilShared } from "./new-bot-sharing.ts"; import { createShareNotice } from "./host/share-notice.ts"; import { memberDeleteRefusal } from "./host/member-bots.ts";import { createTeamOwnerRoutes } from "./routes/team-owners.ts";import { createBotSettingsRoutes } from "./routes/bot-settings.ts";@@ -8809,6 +8810,13 @@ calendarCalls = new CalendarCallManager({botExists: (botId) => Boolean(store.bot(botId)),onDue: deliverCalendarCall,});+ROUTES.push(createCalendarCallRoutes({+ calls: calendarCalls,+ audienceConflict: calendarAudienceConflict,+ ensureRoom: ensureCalendarCallRoom,+ roomView: (auth, group) => personRooms.groupForAuth(auth, publicGroupState(group)),+ messages: (threadId) => store.messagesFor(threadId),+}));const checkBacks = createCheckBacks({ dataDir: DATA_DIR, alive: (botId, threadId) => directChatOf(botId, threadId), busy: (botId, threadId) => threadBusy(botId, threadId), line: (record, line, messageId) => writeCheckBackLine(store, record, line, messageId, threadLanguage(record.threadId)), start: async (record, prompt) => { await startTurn(record.botId, prompt, { threadId: record.threadId, cardContinuation: true, origin: record.origin }); }, paused: (error) => [BOT_HELD_CODE, BOT_PAUSED_CODE].includes(String((error as { code?: unknown } | null)?.code)) }); const botWaits = new WaitManager(createWaitHost({ store, directChat: directChatOf, threadBusy, wrote: markTaskContextExternallyUpdated, notify, enqueue: (input) => routines!.enqueueWebhook(input), cloudHome: Boolean(CLOUD_HOME) })); store.onChange((change) => { if (change.type === "bot" && store.bot(change.botId)?.busy) botWaits.noteBotBusy(change.botId); });const recoveryOwners = routines.routineRequestReceiptOwners();if (recoveryOwners.length > 0) {@@ -14430,47 +14438,6 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return run ? json(res, 200, { run }) : json(res, 404, { error: "no such active run" });}- if (path === "/api/calendar-calls" && method === "GET") {- return json(res, 200, { calls: calendarCalls!.list() });- }- if (path === "/api/calendar-calls" && method === "POST") {- try {- const body = await readBody(req);- const conflict = calendarAudienceConflict(body);- if (conflict) return json(res, 400, { error: conflict });- return json(res, 201, { call: calendarCalls!.create(body) });- } catch (error) {- throw Object.assign(error instanceof Error ? error : new Error(String(error)), { status: 400 });- }- }- const calendarCallRoomMatch = path.match(/^\/api\/calendar-calls\/([\w-]+)\/room$/);- if (calendarCallRoomMatch && method === "POST") {- const call = calendarCalls!.get(calendarCallRoomMatch[1]);- if (!call) return json(res, 404, { error: "no such scheduled call" });- if (call.botIds.length < 2) {- return json(res, 400, { error: "single-bot events open that bot's chat directly" });- }- const group = ensureCalendarCallRoom(call);- return json(res, 200, { group: { ...personRooms.groupForAuth(auth, publicGroupState(group)), messages: store.messagesFor(group.threadId) } });- }- const calendarCallMatch = path.match(/^\/api\/calendar-calls\/([\w-]+)$/);- if (calendarCallMatch && method === "PATCH") {- if (!calendarCalls!.get(calendarCallMatch[1])) return json(res, 404, { error: "no such scheduled call" });- try {- const body = await readBody(req);- const conflict = calendarAudienceConflict(body);- if (conflict) return json(res, 400, { error: conflict });- return json(res, 200, { call: calendarCalls!.update(calendarCallMatch[1], body) });- } catch (error) {- throw Object.assign(error instanceof Error ? error : new Error(String(error)), { status: 400 });- }- }- if (calendarCallMatch && method === "DELETE") {- return calendarCalls!.remove(calendarCallMatch[1])- ? json(res, 200, { ok: true })- : json(res, 404, { error: "no such scheduled call" });- }-if (method === "GET" && path === "/api/events") {const pushKey = phoneKey(auth);const client: SseClient = {diff --git a/server/routes/calendar-calls.test.ts b/server/routes/calendar-calls.test.tsnew file mode 100644index 0000000000..adb3686f95--- /dev/null+++ b/server/routes/calendar-calls.test.ts@@ -0,0 +1,159 @@+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { afterEach, describe, expect, it, vi } from "vitest";++import type { CalendarCall } from "../calendar-calls.ts";+import { json, readBody } from "../harness/http.ts";+import { requiredScope } from "../request-auth.ts";+import type { GroupRecord } from "../store.ts";+import { createCalendarCallRoutes, type CalendarCallRouteDeps } from "./calendar-calls.ts";+import { dispatchRoutes } from "./table.ts";++const call: CalendarCall = {+ id: "c1", name: "Standup", description: "", botIds: ["a", "b"],+ schedule: { type: "once", at: 1 }, durationMinutes: 30, attachments: [],+ nextRunAt: 1, createdAt: 1, updatedAt: 1,+};+const room = { id: "room", threadId: "thread" } as unknown as GroupRecord;+const servers: Server[] = [];+afterEach(async () => {+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));+});++async function serve(deps: Partial<CalendarCallRouteDeps> = {}, state: { exists?: boolean; conflict?: string } = {}): Promise<{ base: string; create: ReturnType<typeof vi.fn>; update: ReturnType<typeof vi.fn>; remove: ReturnType<typeof vi.fn>; ensureRoom: ReturnType<typeof vi.fn> }> {+ const calls = {+ list: vi.fn(() => [call]),+ get: vi.fn(() => state.exists === false ? null : call),+ create: vi.fn((input: unknown) => ({ ...call, ...input as object })),+ update: vi.fn((id: string, patch: object) => ({ ...call, id, ...patch })),+ remove: vi.fn(() => state.exists !== false),+ };+ const ensureRoom = vi.fn(() => room);+ const routes = [createCalendarCallRoutes({+ calls,+ audienceConflict: () => state.conflict ?? null,+ ensureRoom,+ roomView: () => ({ id: "room" }),+ messages: () => [{ id: "m1" }],+ ...deps,+ })];+ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ try {+ const handled = await dispatchRoutes(routes, {+ req, res, url, path: url.pathname, method: req.method ?? "GET",+ auth: { kind: "loopback", scopes: ["admin"] }, json, readBody,+ });+ if (!handled) json(res, 404, { from: "inline routes" });+ } catch (error) {+ const status = (error as { status?: unknown }).status;+ json(res, typeof status === "number" ? status : 500, { error: error instanceof Error ? error.message : String(error) });+ }+ });+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ return { base: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, create: calls.create, update: calls.update, remove: calls.remove, ensureRoom };+}++const post = (base: string, path: string, body: unknown = { name: "Standup", botIds: ["a", "b"], schedule: { type: "once", at: 1 } }) =>+ fetch(`${base}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });++describe("the calendar-calls module through the route table", () => {+ it("lists calls and creates one with the audience check", async () => {+ const { base, create } = await serve();+ const listed = await fetch(`${base}/api/calendar-calls`);+ expect(listed.status).toBe(200);+ expect(await listed.json()).toEqual({ calls: [call] });++ const body = { name: "Standup", botIds: ["a", "b"], schedule: { type: "once", at: 1 } };+ const created = await post(base, "/api/calendar-calls", body);+ expect(created.status).toBe(201);+ expect((await created.json() as { call: CalendarCall }).call).toMatchObject(body);+ expect(create).toHaveBeenCalledWith(body);+ });++ it("refuses a conflicting audience and maps a create failure to 400", async () => {+ const conflicted = await serve({}, { conflict: "not the same audience" });+ const refused = await post(conflicted.base, "/api/calendar-calls");+ expect(refused.status).toBe(400);+ expect(await refused.json()).toEqual({ error: "not the same audience" });++ const failing = await serve({ calls: {+ list: () => [], get: () => call, create: () => { throw new Error("bad input"); },+ update: () => call, remove: () => true,+ } });+ const failed = await post(failing.base, "/api/calendar-calls");+ expect(failed.status).toBe(400);+ expect(await failed.json()).toEqual({ error: "bad input" });+ });++ it("opens a room only for a multi-bot call that exists", async () => {+ const { base, ensureRoom } = await serve();+ const opened = await post(base, "/api/calendar-calls/c1/room");+ expect(opened.status).toBe(200);+ expect(await opened.json()).toEqual({ group: { id: "room", messages: [{ id: "m1" }] } });+ expect(ensureRoom).toHaveBeenCalledWith(call);+ await serve({}, { exists: false }).then(async ({ base: missing }) => {+ const none = await post(missing, "/api/calendar-calls/c1/room");+ expect(none.status).toBe(404);+ expect(await none.json()).toEqual({ error: "no such scheduled call" });+ });+ const single = await serve({ calls: {+ list: () => [], get: () => ({ ...call, botIds: ["a"] }),+ create: () => call, update: () => call, remove: () => true,+ } });+ const refused = await post(single.base, "/api/calendar-calls/c1/room");+ expect(refused.status).toBe(400);+ expect(await refused.json()).toEqual({ error: "single-bot events open that bot's chat directly" });+ });++ it("patches and deletes existing calls, with 404 for a missing one", async () => {+ const { base, update, remove } = await serve();+ const patch = await fetch(`${base}/api/calendar-calls/c1`, { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "Sync" }) });+ expect(patch.status).toBe(200);+ expect((await patch.json() as { call: CalendarCall }).call).toMatchObject({ id: "c1", name: "Sync" });+ expect(update).toHaveBeenCalledWith("c1", { name: "Sync" });++ const deleted = await fetch(`${base}/api/calendar-calls/c1`, { method: "DELETE" });+ expect(deleted.status).toBe(200);+ expect(await deleted.json()).toEqual({ ok: true });+ expect(remove).toHaveBeenCalledWith("c1");++ const missing = await serve({}, { exists: false });+ for (const method of ["PATCH", "DELETE"]) {+ const response = await fetch(`${missing.base}/api/calendar-calls/c1`, { method, headers: { "content-type": "application/json" }, body: "{}" });+ expect(response.status, method).toBe(404);+ expect(await response.json()).toEqual({ error: "no such scheduled call" });+ }+ });++ it("refuses a conflicting patch and maps an update failure to 400", async () => {+ const conflicted = await serve({}, { conflict: "not the same audience" });+ const refused = await fetch(`${conflicted.base}/api/calendar-calls/c1`, { method: "PATCH", headers: { "content-type": "application/json" }, body: "{}" });+ expect(refused.status).toBe(400);+ expect(await refused.json()).toEqual({ error: "not the same audience" });++ const failing = await serve({ calls: {+ list: () => [], get: () => call, create: () => call,+ update: () => { throw new Error("bad patch"); }, remove: () => true,+ } });+ const failed = await fetch(`${failing.base}/api/calendar-calls/c1`, { method: "PATCH", headers: { "content-type": "application/json" }, body: "{}" });+ expect(failed.status).toBe(400);+ expect(await failed.json()).toEqual({ error: "bad patch" });+ });++ it("passes on paths and methods it does not own", async () => {+ const { base } = await serve();+ for (const [method, path] of [["GET", "/api/calendar-calls/c1"], ["PUT", "/api/calendar-calls"], ["POST", "/api/calendar-calls/nope"], ["GET", "/api/calendar-calls/nope/room"]]) {+ const response = await fetch(`${base}${path}`, { method, ...(method === "GET" ? {} : { headers: { "content-type": "application/json" }, body: "{}" }) });+ expect(response.status, `${method} ${path}`).toBe(404);+ expect(await response.json(), `${method} ${path}`).toEqual({ from: "inline routes" });+ }+ });++ it("stays behind the admin scope gate", () => {+ for (const method of ["GET", "POST", "PATCH", "DELETE"]) {+ expect(requiredScope(method, "/api/calendar-calls"), method).toBe("admin");+ }+ });+});diff --git a/server/routes/calendar-calls.ts b/server/routes/calendar-calls.tsnew file mode 100644index 0000000000..fc6630e861--- /dev/null+++ b/server/routes/calendar-calls.ts@@ -0,0 +1,61 @@+import type { CalendarCall, CalendarCallInput, CalendarCallManager, CalendarCallPatch } from "../calendar-calls.ts";+import type { RequestAuth } from "../request-auth.ts";+import type { GroupRecord } from "../store.ts";+import { PASS, type RouteHandler } from "./table.ts";++export interface CalendarCallRouteDeps {+ calls: Pick<CalendarCallManager, "list" | "get" | "create" | "update" | "remove">;+ /** The audience refusal for a roster, worded once in index.ts and shared with room creation. */+ audienceConflict(body: unknown): string | null;+ /** The room a multi-bot call opens. index.ts also uses it when a call is delivered. */+ ensureRoom(call: CalendarCall): GroupRecord;+ /** The room as this caller may see it. */+ roomView(auth: RequestAuth, group: GroupRecord): object;+ messages(threadId: string): unknown[];+}++export function createCalendarCallRoutes(deps: CalendarCallRouteDeps): RouteHandler {+ return async ({ req, res, path, method, auth, json, readBody }) => {+ if (path === "/api/calendar-calls" && method === "GET") {+ return json(res, 200, { calls: deps.calls.list() });+ }+ if (path === "/api/calendar-calls" && method === "POST") {+ try {+ const body = await readBody(req);+ const conflict = deps.audienceConflict(body);+ if (conflict) return json(res, 400, { error: conflict });+ return json(res, 201, { call: deps.calls.create(body as CalendarCallInput) });+ } catch (error) {+ throw Object.assign(error instanceof Error ? error : new Error(String(error)), { status: 400 });+ }+ }+ const calendarCallRoomMatch = path.match(/^\/api\/calendar-calls\/([\w-]+)\/room$/);+ if (calendarCallRoomMatch && method === "POST") {+ const call = deps.calls.get(calendarCallRoomMatch[1]!);+ if (!call) return json(res, 404, { error: "no such scheduled call" });+ if (call.botIds.length < 2) {+ return json(res, 400, { error: "single-bot events open that bot's chat directly" });+ }+ const group = deps.ensureRoom(call);+ return json(res, 200, { group: { ...deps.roomView(auth, group), messages: deps.messages(group.threadId) } });+ }+ const calendarCallMatch = path.match(/^\/api\/calendar-calls\/([\w-]+)$/);+ if (calendarCallMatch && method === "PATCH") {+ if (!deps.calls.get(calendarCallMatch[1]!)) return json(res, 404, { error: "no such scheduled call" });+ try {+ const body = await readBody(req);+ const conflict = deps.audienceConflict(body);+ if (conflict) return json(res, 400, { error: conflict });+ return json(res, 200, { call: deps.calls.update(calendarCallMatch[1]!, body as CalendarCallPatch) });+ } catch (error) {+ throw Object.assign(error instanceof Error ? error : new Error(String(error)), { status: 400 });+ }+ }+ if (calendarCallMatch && method === "DELETE") {+ return deps.calls.remove(calendarCallMatch[1]!)+ ? json(res, 200, { ok: true })+ : json(res, 404, { error: "no such scheduled call" });+ }+ return PASS;+ };+}