Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bind skill switch approval to the full SKILL.md
AdityaUmale07223a499908
diff --git a/server/host/skill-switch-host.test.ts b/server/host/skill-switch-host.test.tsnew file mode 100644index 0000000000..b7cdd7c885--- /dev/null+++ b/server/host/skill-switch-host.test.ts@@ -0,0 +1,85 @@+import { mkdtempSync, readdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { SkillRequestCardData, SkillSwitchAction } from "../../shared/skill-request.ts";+import type { OptionCardData } from "../../shared/wire.ts";+import type { BotRecord } from "../store.ts";++const mocks = vi.hoisted(() => ({ setImportedSkillEnabled: vi.fn() }));+vi.mock("../imported-skills.ts", () => ({ setImportedSkillEnabled: mocks.setImportedSkillEnabled }));+vi.mock("../skills.ts", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../skills.ts")>()),+ listSkills: () => [],+ readSkillFile: () => null,+}));++import { createSkillSwitchHost } from "./skill-switch-host.ts";++const skillMd = (key: string) => `---\nname: lookup\ndescription: Looks things up\n---\nkey: sk-ant-api03-${key.repeat(40)}\n`;+const dirs: string[] = [];++function setup() {+ const dataDir = mkdtempSync(join(tmpdir(), "skill-switch-host-"));+ dirs.push(dataDir);+ const bot = { id: "b1", name: "Bot", color: "blue" } as BotRecord;+ const messages: Array<{ id: string; card: OptionCardData }> = [];+ let file = skillMd("A");+ const host = createSkillSwitchHost({+ store: {+ bot: () => bot,+ appendMessage: ((_threadId: string, message: { card: OptionCardData }) => { messages.push({ id: `m${messages.length}`, card: message.card }); }) as never,+ patchMessage: ((_threadId: string, id: string, patch: { card: OptionCardData }) => { messages.find((message) => message.id === id)!.card = patch.card; }) as never,+ },+ dataDir,+ persistence: () => ({ ok: true }),+ listBotSkills: () => [{ name: "lookup", enabled: true, source: "imported", description: "Looks things up", origin: "imported" } as never],+ readBotSkillFile: () => file,+ noteSkillChange: vi.fn(),+ });+ const card = () => messages.at(-1)!.card;+ const approve = () => {+ const { id, card: shown } = messages.at(-1)!;+ const request = shown.skillRequest as SkillRequestCardData & { action: SkillSwitchAction };+ return host.resolve({ botId: bot.id, threadId: "t1", requestId: request.requestId, behavior: "allow", reviewedSha256: request.sha256 }, id, shown, request);+ };+ const pins = () => readdirSync(join(dataDir, "skill-switch"));+ return { bot, host, card, approve, pins, edit: (next: string) => { file = next; } };+}++beforeEach(() => {+ mocks.setImportedSkillEnabled.mockReset().mockReturnValue({ name: "lookup", enabled: false });+});+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe("skill switch cards", () => {+ it("turns off an imported skill only after the person approves", () => {+ const { bot, host, card, approve, pins } = setup();+ expect(host.stage(bot, "t1", "disable", { skill_name: "lookup" })).toMatchObject({ status: 201, body: { state: "pending" } });+ expect(card()).toMatchObject({ title: "Turn off skill \"lookup\"?", options: ["Turn off", "Deny"] });+ expect(card().skillRequest?.preview).not.toContain("AAAA");+ expect(mocks.setImportedSkillEnabled).not.toHaveBeenCalled();+ expect(pins()).toHaveLength(1);++ expect(approve()).toEqual({ claimed: true, outcome: "allowed-once" });+ expect(mocks.setImportedSkillEnabled).toHaveBeenCalledWith("b1", "lookup", false);+ expect(card()).toMatchObject({ answered: "allow", title: "Skill \"lookup\" turned off" });+ expect(pins()).toHaveLength(0);+ });++ it("refuses approval when a hidden secret changed after the card opened", () => {+ const { bot, host, card, approve, edit } = setup();+ expect(host.stage(bot, "t1", "disable", { skill_name: "lookup" }).status).toBe(201);+ const shown = card().skillRequest?.sha256;+ // Same length, so the redacted preview and the card's sha256 stay the same.+ edit(skillMd("B"));+ expect(approve()).toEqual({ claimed: true, status: 422, error: expect.stringContaining("changed after this card was shown") });+ expect(card().skillRequest?.sha256).toBe(shown);+ expect(card().held).toContain("changed after this card was shown");+ expect(mocks.setImportedSkillEnabled).not.toHaveBeenCalled();+ });+});diff --git a/server/host/skill-switch-host.ts b/server/host/skill-switch-host.tsindex f9a871a321..827bc80a99 100644--- a/server/host/skill-switch-host.ts+++ b/server/host/skill-switch-host.ts@@ -1,8 +1,12 @@// A bot asks to turn one of its skills on or off, or to delete it. That always waits for the person on a card, even with-// Full Access, and approval applies only if the skill is still the one the card showed (its SKILL.md sha256).+// Full Access, and approval applies only if the skill is still the one the card showed: the digest of its full SKILL.md,+// secrets included, is pinned on the server when the card opens, since the card's own sha256 covers only the redacted preview.import { randomUUID } from "node:crypto";+import { mkdirSync, readFileSync, rmSync } from "node:fs";+import { dirname, join } from "node:path";import type { SkillRequestCardData, SkillSwitchAction } from "../../shared/skill-request.ts";import type { OptionCardData } from "../../shared/wire.ts";+import { writeFileAtomic } from "../atomic.ts";import { appendDecision } from "../decision-log.ts";import { setImportedSkillEnabled } from "../imported-skills.ts";import { listSkills, readSkillFile, removeSkill, setSkillEnabled } from "../skills.ts";@@ -34,6 +38,11 @@ export type SkillSwitchResolution =export function createSkillSwitchHost(deps: SkillSwitchHostDeps) {const { store } = deps;+ const pinPath = (requestId: string) => join(deps.dataDir, "skill-switch", `${requestId}.sha256`);+ const readPin = (requestId: string) => {+ try { return readFileSync(pinPath(requestId), "utf8"); } catch { return ""; }+ };+ const dropPin = (requestId: string) => rmSync(pinPath(requestId), { force: true });/** The skill a bot asked to turn on, turn off or delete, as it is now. */function switchableSkill(bot: BotRecord, name: string): SwitchableSkill | undefined {@@ -46,15 +55,15 @@ export function createSkillSwitchHost(deps: SkillSwitchHostDeps) {return { kind: imported ? "imported" : "fixed", enabled: seen.enabled, text: imported ? deps.readBotSkillFile(bot, name) : null, source: seen.source, description: seen.description };}- function appendCard(args: { botId: string; threadId: string; action: SkillSwitchAction; name: string; target: SkillSwitchTarget }): { requestId: string; summary: string } {- const requestId = randomUUID();+ function appendCard(args: { requestId: string; botId: string; threadId: string; action: SkillSwitchAction; name: string; target: SkillSwitchTarget }): string {+ const { requestId } = args;const copy = skillSwitchCardCopy(args.action, args.name, args.target.gist);const payload: SkillRequestCardData = {version: 1,requestId,botId: args.botId,threadId: args.threadId,- // Nothing is staged: approval binds to the current SKILL.md through sha256.+ // Nothing is staged: approval binds to the SKILL.md digest pinned on the server.stagedId: `switch-${requestId}`,action: args.action,name: args.name,@@ -72,7 +81,7 @@ export function createSkillSwitchHost(deps: SkillSwitchHostDeps) {from: from ? { botId: from.id, name: from.name, color: from.color } : undefined,card: { title: copy.title, subtitle: copy.subtitle, options: [copy.option, "Deny"], requestId, tool: "stage_skill", skillRequest: payload },});- return { requestId, summary: copy.title };+ return copy.title;}function apply(botId: string, name: string, action: SkillSwitchAction, kind: SwitchableSkill["kind"] | undefined) {@@ -88,10 +97,13 @@ export function createSkillSwitchHost(deps: SkillSwitchHostDeps) {if (!persistence.ok) return { status: persistence.status, body: { error: persistence.error } };const target = skillSwitchTarget(name, action, switchableSkill(from, name));if ("error" in target) return { status: 422, body: { error: target.error } };- const card = appendCard({ botId: from.id, threadId, action, name, target });- appendDecision(deps.dataDir, { threadId, requestId: card.requestId, botId: from.id, botName: from.name,- tool: "stage_skill", summary: card.summary, decision: "card-shown", source: "skill" });- return { status: 201, body: { state: "pending", name, action, gist: target.gist, warnings: [], summary: card.summary } };+ const requestId = randomUUID();+ mkdirSync(dirname(pinPath(requestId)), { recursive: true, mode: 0o700 });+ writeFileAtomic(pinPath(requestId), target.contentSha256, { mode: 0o600 });+ const summary = appendCard({ requestId, botId: from.id, threadId, action, name, target });+ appendDecision(deps.dataDir, { threadId, requestId, botId: from.id, botName: from.name,+ tool: "stage_skill", summary, decision: "card-shown", source: "skill" });+ return { status: 201, body: { state: "pending", name, action, gist: target.gist, warnings: [], summary } };}function resolve(@@ -107,6 +119,7 @@ export function createSkillSwitchHost(deps: SkillSwitchHostDeps) {requestId: args.requestId, botId: args.botId, botName: args.botName, tool: card.tool, summary: card.subtitle, decision, source: "user" });if (args.behavior !== "allow") {store.patchMessage(args.threadId, messageId, { card: { ...card, answered: "deny", dismissed: true, held: undefined } });+ dropPin(request.requestId);decided("user-denied");return { claimed: true, outcome: "rejected" };}@@ -118,7 +131,7 @@ export function createSkillSwitchHost(deps: SkillSwitchHostDeps) {}const bot = store.bot(args.botId);const current = bot ? switchableSkill(bot, request.name) : undefined;- const still = skillSwitchStillMatches(request.name, request.action, current, request.sha256);+ const still = skillSwitchStillMatches(request.name, request.action, current, readPin(request.requestId));const applied = "error" in still ? still : apply(args.botId, request.name, request.action, current?.kind);if ("error" in applied) {store.patchMessage(args.threadId, messageId, { card: { ...card, held: applied.error } });@@ -127,6 +140,7 @@ export function createSkillSwitchHost(deps: SkillSwitchHostDeps) {store.patchMessage(args.threadId, messageId, {card: { ...card, answered: "allow", held: undefined, title: skillSwitchCardCopy(request.action, request.name, "").done },});+ dropPin(request.requestId);deps.noteSkillChange(args.botId, args.threadId);decided("user-approved");return { claimed: true, outcome: "allowed-once" };diff --git a/server/skill-switch.test.ts b/server/skill-switch.test.tsindex 6877912bdf..85046c2e46 100644--- a/server/skill-switch.test.ts+++ b/server/skill-switch.test.ts@@ -10,7 +10,7 @@ const hash = (value: string) => createHash("sha256").update(value).digest("hex")describe("skillSwitchTarget", () => {it("shows the current SKILL.md and binds the card to its hash", () => {- expect(skillSwitchTarget("notes", "disable", own(true))).toEqual({ preview: text, sha256: hash(text), gist: "Keeps notes" });+ expect(skillSwitchTarget("notes", "disable", own(true))).toEqual({ preview: text, sha256: hash(text), contentSha256: hash(text), gist: "Keeps notes" });expect(skillSwitchTarget("notes", "enable", own(false))).toMatchObject({ sha256: hash(text) });expect(skillSwitchTarget("notes", "delete", own(false))).toMatchObject({ sha256: hash(text) });});@@ -40,6 +40,14 @@ describe("skillSwitchStillMatches", () => {expect(skillSwitchStillMatches("notes", "disable", own(false), hash(text))).toEqual({ error: "skill \"notes\" is already off" });expect(skillSwitchStillMatches("notes", "delete", undefined, hash(text))).toHaveProperty("error");});++ it("binds to the full SKILL.md, not only its redacted preview", () => {+ const withKey = (key: string): SwitchableSkill => ({ ...own(true), text: `${text}key: sk-ant-api03-${key.repeat(40)}\n` });+ const shown = skillSwitchTarget("notes", "disable", withKey("A")) as { sha256: string; contentSha256: string };+ expect(skillSwitchTarget("notes", "disable", withKey("B"))).toMatchObject({ sha256: shown.sha256 });+ expect(skillSwitchStillMatches("notes", "disable", withKey("A"), shown.contentSha256)).toEqual({ ok: true });+ expect(skillSwitchStillMatches("notes", "disable", withKey("B"), shown.contentSha256)).toEqual({ error: expect.stringContaining("changed after this card was shown") });+ });});describe("skillSwitchCardCopy", () => {diff --git a/server/skill-switch.ts b/server/skill-switch.tsindex 0c4cfe707c..5509b6594d 100644--- a/server/skill-switch.ts+++ b/server/skill-switch.ts@@ -21,6 +21,8 @@ export interface SkillSwitchTarget {/** The current SKILL.md as the card shows it; approval binds to its hash. */preview: string;sha256: string;+ /** Digest of the full SKILL.md, secrets included. Approval binds to this one; it stays on the server, never on the card. */+ contentSha256: string;source?: string;gist: string;}@@ -51,6 +53,7 @@ export function skillSwitchTarget(return {preview,sha256: createHash("sha256").update(preview).digest("hex"),+ contentSha256: createHash("sha256").update(skill.text).digest("hex"),...(skill.source ? { source: redactSecretsInText(skill.source) } : {}),gist: redactSecretsInText(skill.description ?? "").replace(/\s+/g, " ").trim().slice(0, STAGED_GIST_MAX),};@@ -61,11 +64,11 @@ export function skillSwitchStillMatches(name: string,action: SkillSwitchAction,skill: SwitchableSkill | undefined,- sha256: string,+ contentSha256: string,): { ok: true } | { error: string } {const target = skillSwitchTarget(name, action, skill);if ("error" in target) return target;- return target.sha256 === sha256+ return target.contentSha256 === contentSha256? { ok: true }: { error: `skill "${name}" changed after this card was shown; ask the bot to propose it again` };}