Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Skills on all bots: owner-only tool turns on a team, updates keep files
milind-soni5e1507f0edfa
diff --git a/server/cloud-team-skills-all-bots.e2e.test.ts b/server/cloud-team-skills-all-bots.e2e.test.tsindex b0b5ceebd7..9b1fa38c80 100644--- a/server/cloud-team-skills-all-bots.e2e.test.ts+++ b/server/cloud-team-skills-all-bots.e2e.test.ts@@ -58,6 +58,14 @@ it("reaches only the person's own bots, and only that person can put it on or ta}expect(await skillsOf(olivesBot)).toEqual([]);+ // A bot with a different copy of its own keeps it, and cannot silently replace the one on all of Ada's bots.+ const different = SKILL.replace("Make the folder", "Ask first, then make the folder");+ expect((await team.as(ada, "POST", `/api/bots/${later.id}/skill-template`, { name: "client-onboarding", description: "", source: "test", text: different, enabled: true })).status).toBe(201);+ expect(await skillsOf(later)).toEqual([expect.not.objectContaining({ allBots: true })]);+ expect((await allBots(ada, later)).status).toBe(409);+ expect((await team.as(ada, "DELETE", `/api/bots/${later.id}/skills/client-onboarding`)).status).toBe(200);+ expect(await skillsOf(later)).toEqual([expect.objectContaining({ allBots: true })]);+expect((await team.as(olive, "DELETE", `/api/bots/${adasResearcher.id}/skills/client-onboarding`)).status).toBe(403);expect(await skillsOf(adasResearcher)).toHaveLength(1);diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.tsindex f589287943..17a3327d1d 100644--- a/server/drivers/agents-call.ts+++ b/server/drivers/agents-call.ts@@ -888,8 +888,8 @@ export async function callTool(called: string, input: Json, context: ToolCallCon// Unreviewed imports: a hostile description is still prompt content, so only names and status.const revision = typeof row.revision === "string" ? `, shared with your team, revision ${row.revision}` : "";const unlisted = row.enabled && row.listed === false ? ", not in your prompt: search to read it" : "";- const everywhere = row.allBots === true ? ", on all your bots" : "";- return `- ${row.name} (${row.enabled ? "enabled" : "disabled"}, ${row.editable === true ? "learned/editable" : "imported"}${everywhere}${revision}${unlisted})`;+ const kind = row.allBots === true ? "on all your bots, update or delete changes every one" : row.editable === true ? "learned/editable" : "imported";+ return `- ${row.name} (${row.enabled ? "enabled" : "disabled"}, ${kind}${revision}${unlisted})`;}).join("\n"): "(none)";const pending = staged.lengthdiff --git a/server/host/skills-for-all-bots-host.ts b/server/host/skills-for-all-bots-host.tsindex d6754599f1..38dc6acfcb 100644--- a/server/host/skills-for-all-bots-host.ts+++ b/server/host/skills-for-all-bots-host.ts@@ -13,12 +13,14 @@ import type { OptionCardData } from "../../shared/wire.ts";import { writeFileAtomic } from "../atomic.ts";import { appendDecision } from "../decision-log.ts";import { UNDO_STALE, type DirectApply } from "../direct-apply.ts";+import { botOwner } from "../../shared/bot-owner.ts";+import { personKey } from "../person-key.ts";import { redactSecretsInText } from "../redact.ts";import { conversationLanguage, serverLine, type ServerLineKey } from "../server-lines.ts";import { learnSource } from "../skill-learn.ts";import { parseSkillManageReferences } from "../skill-request-card.ts";import { listSkills, preparedLearnedSkill, STAGED_GIST_MAX, STAGED_SKILL_FILE_MAX_BYTES } from "../skills.ts";-import { allBotsScopeOfBot, allBotsSkills, SKILLS_FOR_ALL_BOTS_DIR } from "../skills-for-all-bots.ts";+import { allBotsScopeOfBot, allBotsSkills, SKILLS_FOR_ALL_BOTS_DIR, skillsForAllBotsOnTeam } from "../skills-for-all-bots.ts";import { copyDigest, putOnAllBots, removeFromAllBots, restoreOwnCopies, sharedCopy, type RetiredCopy, type SkillCopy } from "../skills-for-all-bots-ops.ts";import type { BotRecord, Message, Store } from "../store.ts";@@ -82,8 +84,9 @@ export function createSkillsForAllBotsHost(deps: SkillsForAllBotsHostDeps) {};const dropRecord = (requestId: string) => rmSync(recordPath(requestId), { force: true });- /** The new files a create or update brings, checked as a bot's own learned skill is. */- function proposed(body: Record<string, unknown>, action: "create" | "update", name: string): { copy: SkillCopy; name: string; gist: string; warnings: string[] } | { error: string } {+ /** The new files a create or update brings, checked as a bot's own learned skill is. An update keeps the files beside+ * SKILL.md it does not mention, and a reference sent empty removes that one, as a bot's own update does. */+ function proposed(body: Record<string, unknown>, action: "create" | "update", name: string, current: SkillCopy | null): { copy: SkillCopy; name: string; gist: string; warnings: string[] } | { error: string } {const skillMd = redactSecretsInText(typeof body.skill_md === "string" ? body.skill_md : "");if (!skillMd.trim()) return { error: "skill_manage needs skill_md: the full SKILL.md including YAML frontmatter" };if (Buffer.byteLength(skillMd, "utf8") > STAGED_SKILL_FILE_MAX_BYTES) return { error: `SKILL.md files must be at most ${STAGED_SKILL_FILE_MAX_BYTES / 1024}KB` };@@ -91,11 +94,17 @@ export function createSkillsForAllBotsHost(deps: SkillsForAllBotsHostDeps) {if (!source) return { error: 'source must be a URL, folder, or "conversation"' };const references = parseSkillManageReferences(body.references);if ("error" in references) return references;- const prepared = preparedLearnedSkill([{ path: "SKILL.md", content: skillMd }, ...references.map((file) => ({ path: file.path, content: redactSecretsInText(file.content) }))]);+ const removals = new Set(references.filter((file) => !file.content.trim()).map((file) => file.path));+ if (removals.size && action !== "update") return { error: `empty reference content removes a file only on update; give ${[...removals][0]} its content` };+ const prepared = preparedLearnedSkill([{ path: "SKILL.md", content: skillMd }, ...references.filter((file) => !removals.has(file.path)).map((file) => ({ path: file.path, content: redactSecretsInText(file.content) }))]);if ("error" in prepared) return prepared;if (action === "update" && prepared.parsed.name !== name) return { error: `updated SKILL.md name must remain "${name}"` };+ const files = new Map((action === "update" ? current?.files ?? [] : []).map((file) => [file.path, file] as const));+ for (const path of removals) if (!files.delete(path)) return { error: `cannot remove ${path}: the skill has no such reference file` };+ for (const file of prepared.files.slice(1)) files.set(file.path, file);const gist = redactSecretsInText(typeof body.gist === "string" ? body.gist : "").replace(/\s+/g, " ").trim().slice(0, STAGED_GIST_MAX) || prepared.parsed.description.slice(0, STAGED_GIST_MAX);- return { copy: { skillMd: prepared.files[0]!.content, files: prepared.files.slice(1), source: learnSource(source) }, name: prepared.parsed.name, gist, warnings: prepared.warnings };+ const kept = [...files.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+ return { copy: { skillMd: prepared.files[0]!.content, files: kept, source: learnSource(source) }, name: prepared.parsed.name, gist, warnings: prepared.warnings };}function appendCard(args: { requestId: string; bot: BotRecord; threadId: string; action: Action; name: string; gist: string; preview: string; source: string; warnings: string[]; applied?: { previous?: SkillRequestCardData["previous"] } }): string {@@ -142,13 +151,20 @@ export function createSkillsForAllBotsHost(deps: SkillsForAllBotsHostDeps) {return names.length ? ` Kept their own different copy: ${names.join(", ")}.` : "";};- /** Null when the call is about the bot's own skill; then the usual paths take it. */+ /** Null when the call is about the bot's own skill; then the usual paths take it. `actsFor`: on a Team Cloud, the person+ * key the turn acts for (host/acting-person.ts); only the bot's own person's turn may change all of their bots, so a+ * teammate chatting with a shared bot cannot reach its owner's private bots through it. */async function stage(from: BotRecord, threadId: string, received: Record<string, unknown>, direct: () => DirectApply | null,- withImport: (body: Record<string, unknown>) => Promise<Record<string, unknown> | { importError: string }>, active: () => boolean): Promise<Result | null> {+ withImport: (body: Record<string, unknown>) => Promise<Record<string, unknown> | { importError: string }>, active: () => boolean,+ actsFor: () => string | null = () => null): Promise<Result | null> {const claim = claimed(from, received);if (!claim) return null;- const scope = allBotsScopeOfBot(store.bot(from.id));+ const live = store.bot(from.id), scope = allBotsScopeOfBot(live);if (!scope) return { status: 422, body: { error: "This bot belongs to no one on this team, so it has no \"all my bots\". Ask the person to have their own Chief of Staff do it, or add the skill to this bot alone without all_bots." } };+ const owner = live ? botOwner(live) : null;+ if (skillsForAllBotsOnTeam() && (!owner || actsFor() !== personKey({ id: "", email: owner }))) {+ return { status: 403, body: { error: "Only the person this bot reports to can change the skills on all of their bots, in their own conversation with it." } };+ }const body = claim.action === "create" ? await withImport(received) : received;if ("importError" in body) return { status: 422, body: { error: body.importError } };if (!active()) return { status: 401, body: { error: "This turn has ended." } };@@ -162,7 +178,7 @@ export function createSkillsForAllBotsHost(deps: SkillsForAllBotsHostDeps) {record = { scope, action: "delete", name: claim.name, digest: copyDigest(current) };gist = ""; preview = current.skillMd; source = current.source;} else {- const change = proposed(body, claim.action, claim.name);+ const change = proposed(body, claim.action, claim.name, claim.action === "update" ? sharedCopy(scope, claim.name) : null);if ("error" in change) return { status: 422, body: { error: change.error } };const current = sharedCopy(scope, change.name);if (claim.action === "create" && current) return { status: 422, body: { error: `"${change.name}" is already on all your bots; update it instead (action "update")` } };diff --git a/server/index.ts b/server/index.tsindex a81b51bb2e..951551ac0c 100644--- a/server/index.ts+++ b/server/index.ts@@ -13415,7 +13415,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (!connectorThread(from.id, fromThreadId)) {return json(res, 403, { error: "source conversation does not belong to sender" });}- const everywhere = await allBotsSkills.stage(from, fromThreadId, received, () => appliesDirectly(from.id, fromThreadId), (asked) => importedSkillRequest(asked, fetch, callSignal), () => internalCapabilityIsActive(internalCapability) && skillAuthoringEnabled(cfg)); if (everywhere) return json(res, everywhere.status, everywhere.body); if (isSkillSwitchAction(received.action)) { const staged = skillSwitch.stage(from, fromThreadId, received.action, received, appliesDirectly(from.id, fromThreadId)); return json(res, staged.status, staged.body); }+ const everywhere = await allBotsSkills.stage(from, fromThreadId, received, () => appliesDirectly(from.id, fromThreadId), (asked) => importedSkillRequest(asked, fetch, callSignal), () => internalCapabilityIsActive(internalCapability) && skillAuthoringEnabled(cfg), () => (CLOUD_TEAM ? actingPeople.requester(fromThreadId, internalCapability.generation) : null)); if (everywhere) return json(res, everywhere.status, everywhere.body); if (isSkillSwitchAction(received.action)) { const staged = skillSwitch.stage(from, fromThreadId, received.action, received, appliesDirectly(from.id, fromThreadId)); return json(res, staged.status, staged.body); }const body = await importedSkillRequest(received, fetch, callSignal); if ("importError" in body) return json(res, 422, { error: body.importError }); if (!internalCapabilityIsActive(internalCapability)) return json(res, 401, { error: TURN_ENDED_REFUSAL }); if (!skillAuthoringEnabled(cfg)) return json(res, 403, { error: "skill authoring is not enabled in Settings" });const direct = appliesDirectly(from.id, fromThreadId);const persistence = skillProposalPersistence(from.id, fromThreadId, !direct);diff --git a/server/routes/skills-for-all-bots.ts b/server/routes/skills-for-all-bots.tsindex 1807447a91..4a71d11afe 100644--- a/server/routes/skills-for-all-bots.ts+++ b/server/routes/skills-for-all-bots.ts@@ -7,7 +7,7 @@ import { ownerEmail } from "../../shared/bot-owner.ts";import type { RequestAuth } from "../request-auth.ts";import { listSkills } from "../skills.ts";import { allBotsScopeOfBot, allBotsScopeOfPerson, allBotsSkills, setAllBotsSkillOff, skillsForAllBotsOnTeam } from "../skills-for-all-bots.ts";-import { ownCopy, putOnAllBots, removeFromAllBots } from "../skills-for-all-bots-ops.ts";+import { copyDigest, ownCopy, putOnAllBots, removeFromAllBots, sharedCopy } from "../skills-for-all-bots-ops.ts";import type { BotRecord, Store } from "../store.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -45,7 +45,12 @@ export function createSkillsForAllBotsRoutes(deps: SkillsForAllBotsRouteDeps): Rif (!own.enabled) return json(res, 409, { error: `Turn "${name}" on for this bot first, after reading it.` });const copy = ownCopy(bot.id, name);if (!copy) return json(res, 409, { error: `"${name}" changed outside OpenMausBot; remove it and add it again.` });- const put = putOnAllBots(allowed.scope, name, copy, { fresh: true });+ // A different copy already on all of their bots stays: this bot keeps its own until one of the two is removed.+ const existing = sharedCopy(allowed.scope, name);+ if (existing && copyDigest(existing) !== copyDigest(copy)) {+ return json(res, 409, { error: `A different "${name}" is already on all your bots. Remove this bot's own copy to use that one, or remove that one from all your bots first.` });+ }+ const put = putOnAllBots(allowed.scope, name, copy, { fresh: !existing });if ("error" in put) return json(res, 409, { error: put.error });return json(res, 200, { name, kept: put.kept.map((id) => deps.store.bot(id)?.name ?? id), retired: put.retired.length });}diff --git a/server/skills-for-all-bots.e2e.test.ts b/server/skills-for-all-bots.e2e.test.tsindex 9cfa9ae962..f1f2cafa1f 100644--- a/server/skills-for-all-bots.e2e.test.ts+++ b/server/skills-for-all-bots.e2e.test.ts@@ -47,7 +47,7 @@ it("puts a skill on every bot of the person's with one tool call, and takes it oexpect(receipt.card).toMatchObject({ autoApplied: true, skillRequest: { allBots: true, action: "create", name: "client-onboarding" } });const listed = await run(writer, "Which skills do you have?", [{ tool: "skills_list", arguments: {}, expectError: false }]);- expect(listed[0]).toContain("client-onboarding (enabled, imported, on all your bots)");+ expect(listed[0]).toContain("client-onboarding (enabled, on all your bots, update or delete changes every one)");const [deleted] = await run(writer, "Remove client-onboarding from all my bots.", [{ tool: "skill_manage", arguments: { action: "delete", skill_name: "client-onboarding" }, expectError: false },diff --git a/server/skills-for-all-bots.test.ts b/server/skills-for-all-bots.test.tsindex c8b7373e40..3fe6e51a0c 100644--- a/server/skills-for-all-bots.test.ts+++ b/server/skills-for-all-bots.test.ts@@ -16,12 +16,15 @@ const { createSkillSwitchHost } = await import("./host/skill-switch-host.ts");const { requesterScope } = await import("./routes/skills-for-all-bots.ts");const { learnSource } = await import("./skill-learn.ts");const { flushDecisionLog } = await import("./decision-log.ts");+const { personKey } = await import("./person-key.ts");const { DATA_DIR } = await import("./config.ts");type Bot = { id: string; name: string; color: string; createdBy?: string; reportsTo?: string; home?: unknown };const SKILL = (name: string, body = "Do the thing.", description = "Sets up a new client the way this person does.") =>`---\nname: ${name}\ndescription: ${description}\n---\n\n# ${name}\n\n${body}\n`;+/** A path as the index line writes it: inside JSON quotes, so Windows backslashes come doubled. */+const quoted = (path: string) => JSON.stringify(path).slice(1, -1);const unique = (prefix: string) => `${prefix}-${Math.random().toString(36).slice(2, 10)}`;let bots: Bot[] = [];@@ -71,11 +74,11 @@ describe("a skill on all of the person's bots", () => {expect(names(one.id)).toEqual(["client-onboarding"]);const lines = indexLines(one.id, "client-onboarding");expect(lines).toHaveLength(1);- expect(lines[0]).toContain(join(DATA_DIR, "skills-for-all-bots", "mine", "skills", "client-onboarding", "SKILL.md"));+ expect(lines[0]).toContain(quoted(join(DATA_DIR, "skills-for-all-bots", "mine", "skills", "client-onboarding", "SKILL.md")));}// The bot with its own different copy keeps it: its own skill wins the name.expect(skills.resolveBotSkills(keeper.id, undefined).filter((skill) => skill.name === "client-onboarding")).toHaveLength(1);- expect(indexLines(keeper.id, "client-onboarding")[0]).toContain(join("workspaces", keeper.id));+ expect(indexLines(keeper.id, "client-onboarding")[0]).toContain(quoted(join("workspaces", keeper.id)));expect(skills.enabledSkillFile(writer.id, "client-onboarding")).toBe(everywhere.allBotsSkillFile(writer.id, "client-onboarding"));const removed = ops.removeFromAllBots("mine", "client-onboarding");@@ -115,7 +118,7 @@ describe("a skill on all of the person's bots", () => {expect(skills.listBotSkillsWithOrigin(chief.id, []).skills.map((skill) => [skill.name, skill.origin])).toEqual([["release-notes", "all-bots"]]);expect(skills.enabledSkillFile(chief.id, "release-notes", [])).toBe(everywhere.allBotsSkillFile(chief.id, "release-notes"));expect(skills.skillsSystemPrompt(chief.id, []).split("\n").filter((line) => line.startsWith("- release-notes:"))).toEqual([- expect.stringContaining(join("skills-for-all-bots", "mine")),+ expect.stringContaining(quoted(join("skills-for-all-bots", "mine"))),]);ops.removeFromAllBots("mine", "release-notes");expect(skills.resolveBotSkills(chief.id, [])[0]).not.toHaveProperty("allBots");@@ -167,8 +170,8 @@ describe("skill_manage for all the person's bots", () => {persistence: () => ({ ok: true }),noteSkillChange: vi.fn(),});- const call = (from: Bot, body: Record<string, unknown>) =>- made.stage(from as never, "t1", body, () => (direct ? "full-access" : null), async (asked) => asked, () => true);+ const call = (from: Bot, body: Record<string, unknown>, actsFor: string | null = null) =>+ made.stage(from as never, "t1", body, () => (direct ? "full-access" : null), async (asked) => asked, () => true, () => actsFor);const last = () => messages.at(-1)!;const undo = (from: Bot) => made.undo(from.id, "t1", last() as never, last().card.skillRequest);const answer = (from: Bot, behavior: "allow" | "deny") =>@@ -239,6 +242,32 @@ describe("skill_manage for all the person's bots", () => {expect(await call(nobodys, { action: "create", all_bots: true, skill_md: SKILL("x-skill"), source: "conversation" })).toMatchObject({ status: 422 });});+ it("on a Team Cloud, changes a member's bots only in a turn that acts for that member", async () => {+ wire(true);+ const alicesChief = bot("Alice's Chief", { createdBy: "[email protected]" });+ const alicesWriter = bot("Alice's Writer", { createdBy: "[email protected]" });+ const { call } = host(true);+ const create = { action: "create", all_bots: true, skill_md: SKILL("team-thing"), source: "conversation" };+ // A teammate chatting with Alice's shared bot, and a routine acting for nobody, cannot reach all of Alice's bots.+ expect(await call(alicesChief, create, personKey({ id: "", email: "[email protected]" }))).toMatchObject({ status: 403 });+ expect(await call(alicesChief, create, null)).toMatchObject({ status: 403 });+ expect(names(alicesWriter.id)).toEqual([]);+ expect(await call(alicesChief, create, personKey({ id: "", email: "[email protected]" }))).toMatchObject({ status: 201, body: { state: "applied" } });+ expect(names(alicesWriter.id)).toEqual(["team-thing"]);+ });++ it("an update keeps the reference files it does not mention, and an empty one removes that file", async () => {+ const chief = bot("Chief");+ const { call } = host(true);+ const references = [{ path: "references/steps.md", content: "# Steps\n\nOne, two.\n" }, { path: "references/tone.md", content: "# Tone\n\nPlain.\n" }];+ await call(chief, { action: "create", all_bots: true, skill_md: SKILL("with-notes"), references, source: "conversation" });+ await call(chief, { action: "update", skill_name: "with-notes", skill_md: SKILL("with-notes", "New way."), source: "conversation" });+ expect(ops.sharedCopy("mine", "with-notes")?.files.map((file) => file.path)).toEqual(["references/steps.md", "references/tone.md"]);+ await call(chief, { action: "update", skill_name: "with-notes", skill_md: SKILL("with-notes", "Newer way."), references: [{ path: "references/tone.md", content: "" }], source: "conversation" });+ expect(ops.sharedCopy("mine", "with-notes")).toMatchObject({ files: [{ path: "references/steps.md" }] });+ expect(ops.sharedCopy("mine", "with-notes")?.skillMd).toContain("Newer way.");+ });+it("switches a shared skill on or off for the asking bot only", () => {const chief = bot("Chief"), writer = bot("Writer");learn(chief.id, "tidy-inbox");diff --git a/server/skills-for-all-bots.ts b/server/skills-for-all-bots.tsindex 267c366303..59b934373a 100644--- a/server/skills-for-all-bots.ts+++ b/server/skills-for-all-bots.ts@@ -14,7 +14,7 @@ import { writeFileAtomic } from "./atomic.ts";import { DATA_DIR } from "./config.ts";import { botOwner, type OwnedBot } from "../shared/bot-owner.ts";import { isSkillName } from "../shared/skill-md.ts";-import { librarySkillFilePath, listLibrarySkills, readLibrarySkillFile, type LibrarySkillListing } from "./skill-library.ts";+import { librarySkillFilePath, listLibrarySkills, readLibrarySkillFile, readSkillLibraryIndex, type LibrarySkillListing } from "./skill-library.ts";export const SKILLS_FOR_ALL_BOTS_DIR = "skills-for-all-bots";@@ -100,7 +100,7 @@ export function allBotsSkills(botId: string): AllBotsSkillListing[] {/** The SKILL.md path the bot's index points at, when the person has a skill of this name on all their bots. */export function allBotsSkillFile(botId: string, name: string): string | null {const root = allBotsRootOfBot(botId);- return root && isSkillName(name) && listLibrarySkills(root).some((skill) => skill.name === name) ? librarySkillFilePath(name, root) : null;+ return root && isSkillName(name) && Object.hasOwn(readSkillLibraryIndex(root), name) ? librarySkillFilePath(name, root) : null;}/** Its SKILL.md while it still hashes as stored; null when there is none or it changed outside OpenMausBot. */