Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Let a Chief of Staff change shared bots in its departments
AdityaUmale4a6da7d492fe
diff --git a/server/chief-shared-department-bot.e2e.test.ts b/server/chief-shared-department-bot.e2e.test.tsnew file mode 100644index 0000000000..b94159368a--- /dev/null+++ b/server/chief-shared-department-bot.e2e.test.ts@@ -0,0 +1,83 @@+// Real server, fake engine: a Chief of Staff changes the setup of a bot shared with different people when that bot is in+// a department the Chief is in charge of, and still may not for one outside its departments.+import { spawn, type ChildProcess } from "node:child_process";+import { closeSync, openSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchVerificationServer, verificationServerEnvironment, type VerificationServer } from "../scripts/control-omb.ts";+import { waitForExit } from "./testing/cleanup.ts";++const key = "chief-shared-department-bot-capability";+let fixture: VerificationServer;+let child: ChildProcess;++const api = async (method: string, path: string, body?: unknown, token?: string) => {+ const response = await fetch(fixture.info.url + path, {+ method, headers: { "content-type": "application/json", origin: fixture.info.url, ...(token ? { authorization: `Bearer ${token}` } : {}) },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(20_000),+ });+ return { status: response.status, body: await response.json() as any };+};+const bot = async (name: string) => (await api("GET", "/api/bots")).body.bots.find((candidate: any) => candidate.name === name);++beforeAll(async () => {+ fixture = await launchVerificationServer();+ const port = Number(new URL(fixture.info.url).port);+ for (const [name, section] of [["Dept Chief", "Work"], ["Editor", "Editing"], ["Payroll", "Private"]]) {+ const created = await api("POST", "/api/bots", { name, section });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ }+ const chief = await api("PATCH", `/api/bots/${(await bot("Dept Chief")).id}`, { chiefOfStaff: true, managedSections: ["Editing"], acknowledgePeerScope: true });+ expect(chief.status, JSON.stringify(chief.body)).toBe(200);+ for (const name of ["Editor", "Payroll"]) {+ const shared = await api("PATCH", `/api/bots/${(await bot(name)).id}`, { visibility: "admins" });+ expect(shared.status, JSON.stringify(shared.body)).toBe(200);+ }+ await waitForExit(fixture.child, { signal: "SIGTERM" });+ const log = openSync(fixture.info.logPath, "a", 0o600);+ child = spawn(process.execPath, ["--experimental-strip-types", fileURLToPath(new URL("./index.ts", import.meta.url))], {+ cwd: fileURLToPath(new URL("..", import.meta.url)),+ env: { ...verificationServerEnvironment({}, fixture.info.dataDir, port), OMB_TEST_INTERNAL_CAPABILITY_KEY: key },+ stdio: ["ignore", log, log],+ });+ closeSync(log);+ const deadline = Date.now() + 20_000;+ while (Date.now() < deadline) {+ try { if ((await fetch(fixture.info.url + "/api/health")).ok) return; } catch {}+ await new Promise((resolve) => setTimeout(resolve, 20));+ }+ throw new Error(`server did not start; see ${fixture.info.logPath}`);+}, 60_000);++afterAll(async () => {+ if (child) await waitForExit(child, { signal: "SIGTERM" });+ await fixture?.close();+});++it("lets the Chief list and change a shared bot in its department, and not one outside it", async () => {+ const chief = await bot("Dept Chief");+ const editor = await bot("Editor");+ const payroll = await bot("Payroll");+ expect(chief).toMatchObject({ chiefOfStaff: true, managedSections: ["Editing"] });+ expect([editor.visibility, payroll.visibility]).toEqual(["admins", "admins"]);+ const minted = await fetch(fixture.info.url + "/api/testing/internal-capability", {+ method: "POST", headers: { "content-type": "application/json", "x-openmausbot-test-capability": key },+ body: JSON.stringify({ botId: chief.id, threadId: chief.threadId, kind: "agents" }),+ });+ expect(minted.status).toBe(201);+ const token = (await minted.json() as any).token as string;++ const catalog = await api("GET", "/api/internal/team-setup-catalog", undefined, token);+ expect(catalog.status, JSON.stringify(catalog.body)).toBe(200);+ expect((catalog.body.bots as any[]).map((entry) => entry.name).sort()).toEqual(["Dept Chief", "Editor"]);++ const change = (target: any) => api("POST", "/api/internal/profile-requests", { fromBotId: chief.id, fromThreadId: chief.threadId,+ forBotId: target.id, changes: { title: "Proofreader" }, reason: "The person asked." }, token);+ const allowed = await change(editor);+ expect(allowed.body.state, JSON.stringify(allowed.body)).toBe("applied");+ expect((await bot("Editor")).title).toBe("Proofreader");+ const refused = await change(payroll);+ expect(refused.status, JSON.stringify(refused.body)).toBeGreaterThanOrEqual(400);+ expect(refused.body.error).toContain("not in a department this Chief manages");+ expect((await bot("Payroll")).title).toBe("");+}, 60_000);diff --git a/server/index.ts b/server/index.tsindex 2d5930c9d1..b2b1a0b037 100644--- a/server/index.ts+++ b/server/index.ts@@ -128,7 +128,7 @@ import { createSideJobs, helperSelection } from "./side-jobs.ts";import type { CaptureTurn, RoomLine } from "./memory-capture.ts";import { createAboutMe } from "./about-me.ts"; import { createPersonPreference } from "./host/person-preference.ts";import { botMemoryUpdate, ownersOwnAsk } from "./memory-forget.ts";-import { canManage, canReach, departmentRefusal, hasTeamAuthority, inChargeOfEvery, livePeerRoster, livePeerRosterBlock, peerName, peerRosterPrompt, peerRosterSystemPrompt, withElsewhere, peerStatus, peerStatusWords, reachablePeers, resolveTeammate, roomPeerRosterSystemPrompt, roomRosterLine } from "./peer-roster.ts"; import { createLinkedRoster } from "./host/linked-roster.ts"; import { roomPostRefusal, sharedNamesNote, unreachedMentionLines } from "./same-name-mentions.ts";+import { canManage, canManageSetup, canReach, departmentRefusal, hasTeamAuthority, inChargeOfEvery, livePeerRoster, livePeerRosterBlock, peerName, peerRosterPrompt, peerRosterSystemPrompt, withElsewhere, peerStatus, peerStatusWords, reachablePeers, resolveTeammate, roomPeerRosterSystemPrompt, roomRosterLine } from "./peer-roster.ts"; import { createLinkedRoster } from "./host/linked-roster.ts"; import { roomPostRefusal, sharedNamesNote, unreachedMentionLines } from "./same-name-mentions.ts";import {containerComputerAction,containerComputerFrame,@@ -9068,7 +9068,7 @@ const chiefPeerTargetRule = (noun: string) => (proposerBotId: string, targetBotIconst target = store.bot(targetBotId);if (!target) return "that bot no longer exists";if (!proposer || !chiefLevel(proposer)) return "only a section's Chief of Staff can change another bot's " + noun;- if (!canManage(proposer, target)) return departmentRefusal(proposer, target) ?? "that bot is not in a department this Chief manages";+ if (!canManageSetup(proposer, target)) return departmentRefusal(proposer, target) ?? "that bot is not in a department this Chief manages";return null;};const burst = createBurstHost({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), tier: () => cloudPlanTier.tier(), maxParallel: () => cfg.burst?.maxParallel, hasRoom: () => engineMemory.laneHasRoom(), store, language: (threadId) => threadLanguage(threadId), startTurn: (botId, text, opts) => startTurn(botId, text, opts), stop: (botId, threadId, cause) => { void interruptDirectThread(botId, threadId, cause).catch(() => {}); }, threadBusy, opened: (threadId, parent) => threadStarters.set(threadId, openerFrom(parent)), origin: (run) => withPerson({ kind: "user", request: quoteInNote(run.task, 400) }, threadPersonKey(run.threadId)), approval: ownThreads.approvalFor, defaultModel: (bot, threadId) => burstDefaultModel({ own: store.taskByThread(bot.id, threadId)?.modelSelection ?? bot.modelSelection, catalog: (id) => registry.get(id)?.models, refused: (id) => quickFallback.refused(id), usable: (selection) => ownThreads.refusal(selection, bot) === null }), modelName, route: (notification) => teamMessages.route(notification, { routine: true }), announce: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); } });diff --git a/server/peer-roster.test.ts b/server/peer-roster.test.tsindex 64a43cc78b..ef3f0457ab 100644--- a/server/peer-roster.test.ts+++ b/server/peer-roster.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import {canManage,+ canManageSetup,canReach,departmentRefusal,hasAuthority,@@ -140,6 +141,35 @@ describe("department refusals name the department and what unlocks it", () => {});});+describe("a Chief changes the setup of every bot in its departments", () => {+ const clive: RosterMember = { id: "chief", name: "Clive", section: "Work", chiefOfStaff: true, managedSections: ["Editing"] };+ const shared = { visibility: { people: ["[email protected]"] } };+ const editor: RosterMember = { id: "editor", name: "Editor", section: "Editing", ...shared };++ it("even one shared with different people, while reach between them stays closed", () => {+ expect(canManageSetup(clive, editor)).toBe(true);+ expect(canManageSetup(clive, { ...editor, section: "Work" })).toBe(true);+ expect(canReach(clive, editor)).toBe(false);+ expect(canManage(clive, editor)).toBe(false);+ });++ it("still refuses a shared bot outside its departments, a bot without the Chief role, and hidden, own or a person's bots", () => {+ expect(canManageSetup(clive, { ...editor, section: "Personal" })).toBe(false);+ expect(canManageSetup({ ...clive, chiefOfStaff: false }, { ...editor, section: "Work" })).toBe(false);+ expect(canManageSetup(clive, { ...editor, hidden: true })).toBe(false);+ expect(canManageSetup({ ...clive, ...shared }, { ...clive, ...shared })).toBe(false);+ expect(canManageSetup(clive, { ...editor, defaultBot: { person: "[email protected]" } })).toBe(false);+ expect(canManageSetup({ ...clive, createdBy: "[email protected]" }, editor)).toBe(false);+ expect(canManageSetup(clive, { ...editor, chiefOfStaff: true, createdBy: "[email protected]" })).toBe(false);+ });++ it("keeps every bot the department rule already allowed", () => {+ expect(canManageSetup(clive, fleet[1]!)).toBe(true);+ expect(canManageSetup(self, fleet[1]!)).toBe(true);+ expect(canManageSetup(self, fleet[4]!)).toBe(false);+ });+});+describe("reach across departments", () => {it("lets any bot reach any department while hidden bots and visibility still apply", () => {expect(canReach(self, fleet[4]!)).toBe(true);diff --git a/server/peer-roster.ts b/server/peer-roster.tsindex 6306cdc34a..79c8062414 100644--- a/server/peer-roster.ts+++ b/server/peer-roster.ts@@ -80,6 +80,14 @@ export function canManage(from: RosterMember, target: RosterMember): boolean {return canReach(from, target) && hasAuthority(from, target);}+/** May change `target`'s setup (profile, default model, skills): what canManage allows, and for a Chief of Staff also a+ * bot shared with different people in a department it is in charge of. Reach between the two stays as canReach says. */+export function canManageSetup(from: RosterMember, target: RosterMember): boolean {+ if (canManage(from, target)) return true;+ return from.chiefOfStaff === true && from.id !== target.id && !target.hidden && !target.defaultBot &&+ !ownedChief(from) && !ownedChief(target) && hasTeamAuthority(from, target.section);+}+/** Why `from` may not manage `target` when the department rule alone decided; otherwise null. */export function departmentRefusal(from: RosterMember, target: RosterMember): string | null {if (!canReach(from, target) || ownedChief(from) || ownedChief(target) || hasTeamAuthority(from, target.section)) return null;diff --git a/server/routes/internal-chief-team.test.ts b/server/routes/internal-chief-team.test.tsindex 54ce8cc893..96dcd1127f 100644--- a/server/routes/internal-chief-team.test.ts+++ b/server/routes/internal-chief-team.test.ts@@ -109,6 +109,19 @@ describe("what a Chief of Staff reads about its team", () => {});});+ it("lists a bot shared with different people only when it is in a department the Chief is in charge of", async () => {+ const chief = bot("chief", { chiefOfStaff: true, section: "Work", managedSections: ["Editing"] });+ const shared = { visibility: { people: ["[email protected]"] } } as Partial<BotRecord>;+ const { get } = await serve(chief, async () => TEAMS, {+ teams: ["", "Work", "Editing", "Private"],+ bots: [chief, bot("editor", { section: "Editing", ...shared }), bot("payroll", { section: "Private", ...shared }),+ bot("archived", { section: "Editing", hidden: true, ...shared })],+ });+ const { body } = await get("/api/internal/team-setup-catalog");+ expect(body.teams).toEqual(["Work", "Editing"]);+ expect((body.bots as { id: string }[]).map((entry) => entry.id)).toEqual(["chief", "editor"]);+ });+it("leaves every other route to the next handler", async () => {const { get } = await serve(bot("chief", { chiefOfStaff: true }), async () => TEAMS);expect(await get("/api/internal/team-setup-requests")).toEqual({ status: 404, body: { from: "next routes" } });diff --git a/server/routes/internal-chief-team.ts b/server/routes/internal-chief-team.tsindex 0b6b1074c8..da857cfdd3 100644--- a/server/routes/internal-chief-team.ts+++ b/server/routes/internal-chief-team.ts@@ -1,4 +1,4 @@-import { hasTeamAuthority, peerAllowed } from "../peer-roster.ts"; import { chiefLevel } from "../chief-level.ts";+import { canManageSetup, hasTeamAuthority, peerAllowed } from "../peer-roster.ts"; import { chiefLevel } from "../chief-level.ts";import type { BotRecord } from "../store.ts";import { libraryTeamRoles } from "../team-library.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -47,7 +47,7 @@ export function createInternalChiefTeamRoutes(deps: {if (!current) return json(res, 403, { error: NOT_CHIEF });return json(res, 200, {teams: deps.teams().filter((name) => hasTeamAuthority(current, name)),- bots: deps.bots().filter((bot) => !bot.hidden && hasTeamAuthority(current, bot.section) && (bot.id === current.id || peerAllowed(current, bot)))+ bots: deps.bots().filter((bot) => !bot.hidden && hasTeamAuthority(current, bot.section) && (bot.id === current.id || peerAllowed(current, bot) || canManageSetup(current, bot))).map((bot) => ({ id: bot.id, name: bot.name, title: bot.title, section: bot.section ?? "", modelSelection: bot.modelSelection, chiefOfStaff: Boolean(bot.chiefOfStaff) })),instances: instances.map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, displayName: instance.displayName,state: instance.snapshot.state, models: instance.models, effortLevels: instance.capabilities?.effortLevels ?? [] })),