Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Move from Grok Bot: read a moved Bot's chat from the Grok Bot app
aivsomkar2f18599d84f4
diff --git a/server/grok-history.test.ts b/server/grok-history.test.tsnew file mode 100644index 0000000000..b45ed9c00e--- /dev/null+++ b/server/grok-history.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from "vitest";++import { grokChatMessages } from "./grok-history.ts";++const KEY = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz";+const at = (seq: number) => 1_754_000_000_000 + seq * 60_000;+const person = (seq: number, content: string, extra: Record<string, unknown> = {}) =>+ ({ kind: "message", seq, id: `t${seq}u`, role: "user", content, richText: `<p>${content}</p>`, isStreaming: false, timestampMs: at(seq), ...extra });+const sent = (seq: number, message: Record<string, unknown>, extra: Record<string, unknown> = {}) =>+ ({ kind: "send-message", seq, id: `t${seq}s1`, message, timestampMs: at(seq), ...extra });+const shown = (entries: unknown[]) => grokChatMessages(entries).map(({ role, text }) => [role, text]);++describe("a Grok Bot chat as a MausBot conversation", () => {+ it("is one linear thread in Grok Bot's order, with Grok Bot's times, even when entries come shuffled or skip numbers", () => {+ const messages = grokChatMessages([+ sent(7, { type: "text", content: "Booked for Friday." }),+ person(1, "Find me a table for two"),+ sent(4, { type: "text", content: "Which night?" }),+ person(5, "Friday"),+ ]);+ expect(messages).toEqual([+ { id: "grok-1", kind: "text", role: "user", text: "Find me a table for two", at: at(1), parentId: null },+ { id: "grok-4", kind: "text", role: "bot", text: "Which night?", at: at(4), parentId: "grok-1" },+ { id: "grok-5", kind: "text", role: "user", text: "Friday", at: at(5), parentId: "grok-4" },+ { id: "grok-7", kind: "text", role: "bot", text: "Booked for Friday.", at: at(7), parentId: "grok-5" },+ ]);+ });++ it("turns each card into a line that says what it was", () => {+ expect(shown([+ sent(1, { type: "text", content: "Here are the two options.", images: [{ url: "a" }, { url: "b" }] }),+ sent(2, { type: "text", content: "", images: [{ url: "c" }] }),+ sent(3, { type: "widget", widget: { prompt: "Which plan?", options: [{ label: "Basic", value: "basic" }, { label: "Pro", value: "pro" }] } }, { respondedValue: "pro" }),+ sent(4, { type: "widget", widget: { prompt: "Pick days", options: [{ label: "Mon" }, { label: "Tue" }], allowCustom: true } }, { respondedValue: "Wed" }),+ sent(5, { type: "widget", widget: { prompt: "Want a reminder?", options: [{ label: "Yes", value: "y" }] } }, { widgetSkipped: true }),+ sent(6, { type: "bot-template-share", name: "Scout", body: "Finds leads", shareUrl: "https://x.ai/bot/abc123", published: true }),+ sent(7, { type: "connector", connector: "Google-calendar", serverId: "gcal", variant: "connect" }),+ { kind: "event", seq: 8, id: "e8", timestampMs: at(8), event: { type: "automation-changed", action: "created", automationId: "a1", automationName: "Morning brief" } },+ ])).toEqual([+ ["bot", "Here are the two options.\nSent 2 images"],+ ["bot", "Sent 1 image"],+ ["bot", "Which plan?\nChoices: Basic, Pro\nAnswer: Pro"],+ ["bot", "Pick days\nChoices: Mon, Tue\nAnswer: Wed"],+ ["bot", "Want a reminder?\nChoices: Yes\nSkipped"],+ ["bot", "Shared the Bot template \"Scout\": https://x.ai/bot/abc123"],+ ["bot", "Asked to connect Google-calendar"],+ ["bot", "Routine \"Morning brief\" created"],+ ]);+ });++ it("says which Bot wrote to it, or which Bot it wrote to", () => {+ expect(shown([+ person(1, "Can you check the invoice?", { fromAgent: { id: "b2", name: "Luna" } }),+ { kind: "message", seq: 2, id: "t2", role: "assistant", content: "Checked: it's paid.", toAgent: { id: "b2", name: "Luna", kind: "agent" }, timestampMs: at(2) },+ ])).toEqual([["user", "Luna:\nCan you check the invoice?"], ["bot", "To Luna:\nChecked: it's paid."]]);+ });++ it("leaves out what it doesn't know, what has no words, and an entry without its number or time", () => {+ expect(shown([+ person(1, "Kept"),+ { kind: "thinking", seq: 2, timestampMs: at(2), text: "hidden" },+ sent(3, { type: "voice-note", url: "x" }),+ { kind: "message", seq: 4, role: "system", content: "rules", timestampMs: at(4) },+ { kind: "event", seq: 5, timestampMs: at(5), event: { type: "session-started" } },+ person(6, " "),+ sent(7, { type: "connector" }),+ { ...person(8, "no time"), timestampMs: undefined },+ { ...person(9, "no number"), seq: "9" },+ person(1, "A second copy of seq 1"),+ null, "text", 42,+ ])).toEqual([["user", "Kept"]]);+ expect(grokChatMessages([])).toEqual([]);+ });++ it("takes keys out of every line", () => {+ const text = shown([+ person(1, `My key is ${KEY}`),+ sent(2, { type: "widget", widget: { prompt: `Use ${KEY}?`, options: [{ label: KEY, value: "k" }] } }, { respondedValue: "k" }),+ sent(3, { type: "bot-template-share", name: "Keys", shareUrl: `https://x.ai/bot/a?token=${KEY}` }),+ ]).map(([, line]) => line).join("\n");+ expect(text).not.toContain(KEY);+ expect(text).toContain("My key is");+ });+});diff --git a/server/grok-history.ts b/server/grok-history.tsnew file mode 100644index 0000000000..a3fa659bbd--- /dev/null+++ b/server/grok-history.ts@@ -0,0 +1,87 @@+import type { GrokHistoryAnswer } from "../shared/grok-import.ts";+import { redactSecretsInText } from "../shared/redact.ts";+import { readGrokChat } from "./grok-local.ts";+import type { SetupMachine } from "./setup-import.ts";+import type { Message, Store } from "./store.ts";++export const GROK_HISTORY_TITLE = "Chat from Grok Bot";+export type GrokHistoryStore = Pick<Store, "bot" | "createTask" | "importTranscript" | "messagesFor">;++type Entry = Record<string, unknown>;+type Line = { role: Message["role"]; text: string };++const words = (value: unknown) => (typeof value === "string" ? value.trim() : "");+const record = (value: unknown): Entry => (value && typeof value === "object" && !Array.isArray(value) ? value as Entry : {});+const list = (value: unknown) => (Array.isArray(value) ? value.map(record) : []);+const lines = (...parts: string[]) => parts.filter(Boolean).join("\n");++function widget(message: Entry, entry: Entry): string {+ const { prompt, options } = record(message.widget);+ const choices = list(options);+ const picked = choices.find((option) => option.value === entry.respondedValue)?.label ?? entry.respondedValue;+ return lines(words(prompt), choices.length ? `Choices: ${choices.map((option) => words(option.label)).filter(Boolean).join(", ")}` : "",+ words(picked) ? `Answer: ${words(picked)}` : entry.widgetSkipped === true ? "Skipped" : "");+}++/** What the Bot sent, by the type Grok Bot gives it. A card becomes a line saying what it was. */+const BOT_SENT = new Map<string, (message: Entry, entry: Entry) => string>([+ ["text", (message) => {+ const images = list(message.images).length;+ return lines(words(message.content), images === 1 ? "Sent 1 image" : images > 1 ? `Sent ${images} images` : "");+ }],+ ["widget", widget],+ ["bot-template-share", (message) => words(message.name) && [`Shared the Bot template "${words(message.name)}"`, words(message.shareUrl)].filter(Boolean).join(": ")],+ ["connector", (message) => words(message.connector) && `Asked to connect ${words(message.connector)}`],+]);++/** Each kind of entry in a Grok Bot chat; a kind or type not here is left out. */+const ENTRY = new Map<string, (entry: Entry) => Line | null>([+ ["message", (entry) => {+ if (entry.role !== "user" && entry.role !== "assistant") return null;+ const from = words(record(entry.fromAgent).name), to = words(record(entry.toAgent).name), text = words(entry.content);+ return { role: entry.role === "user" ? "user" : "bot", text: text && (from ? `${from}:\n${text}` : to ? `To ${to}:\n${text}` : text) };+ }],+ ["send-message", (entry) => {+ const message = record(entry.message);+ const sent = BOT_SENT.get(words(message.type));+ return sent ? { role: "bot", text: sent(message, entry) } : null;+ }],+ ["event", (entry) => {+ const { type, automationName, action } = record(entry.event);+ return type === "automation-changed" && words(automationName) ? { role: "bot", text: `Routine "${words(automationName)}" ${words(action)}`.trim() } : null;+ }],+]);++/** A Grok Bot chat slice's entries, read as untrusted, as one linear conversation in Grok Bot's order and times. */+export function grokChatMessages(entries: readonly unknown[]): Message[] {+ const ordered = entries.map(record)+ .filter((entry) => Number.isSafeInteger(entry.seq) && Number.isFinite(entry.timestampMs))+ .sort((a, b) => (a.seq as number) - (b.seq as number));+ const messages: Message[] = [];+ for (const [index, entry] of ordered.entries()) {+ if (index > 0 && entry.seq === ordered[index - 1]!.seq) continue;+ const line = ENTRY.get(words(entry.kind))?.(entry);+ const text = line && redactSecretsInText(line.text);+ if (!line || !text) continue;+ messages.push({ id: `grok-${entry.seq as number}`, kind: "text", role: line.role, text, at: entry.timestampMs as number, parentId: messages.at(-1)?.id ?? null });+ }+ return messages;+}++/** Brings a moved Bot's chat into one new thread on `botId`, as a record only: nothing runs, replies or notifies. Asked+ * again, it finds that thread and adds nothing. Null when there is no such bot. */+export function importGrokHistory(store: GrokHistoryStore, machine: SetupMachine, botId: string, grokName: string): GrokHistoryAnswer | null {+ const bot = store.bot(botId);+ if (!bot) return null;+ const earlier = bot.tasks?.find((task) => task.title === GROK_HISTORY_TITLE);+ const kept = earlier ? store.messagesFor(earlier.threadId).length : 0;+ if (kept) return { messages: kept };+ const chat = readGrokChat(machine, grokName);+ if ("reason" in chat) return chat;+ const messages = grokChatMessages(chat.entries);+ if (!messages.length) return { reason: "empty" };+ const task = earlier ?? store.createTask(botId, GROK_HISTORY_TITLE);+ if (!task) return null;+ store.importTranscript(task.threadId, messages, messages.at(-1)!.id);+ return { messages: messages.length };+}diff --git a/server/grok-local.test.ts b/server/grok-local.test.tsindex efb81c408a..1df12d0772 100644--- a/server/grok-local.test.ts+++ b/server/grok-local.test.ts@@ -3,8 +3,9 @@ import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { lookForGrokBot, removeOldCursorSignIn } from "./grok-local.ts";+import { lookForGrokBot, readGrokChat, removeOldCursorSignIn } from "./grok-local.ts";import { thisMachine, type SetupFs, type SetupMachine } from "./setup-import.ts";+import { base32, GROK_CACHE as CACHE, grokSlice as slice } from "./testing/grok-cache.ts";const homes: string[] = [];afterEach(() => {@@ -33,22 +34,6 @@ function machineAt(home: string, platform: NodeJS.Platform = "darwin"): SetupMacreturn { ...real, home, platform, env: {}, fs, opened };}-const base32 = (text: string) => {- const alphabet = "abcdefghijklmnopqrstuvwxyz234567";- let bits = 0, value = 0, out = "";- for (const byte of Buffer.from(text)) {- value = (value << 8) | byte;- bits += 8;- while (bits >= 5) {- out += alphabet[(value >>> (bits - 5)) & 31];- bits -= 5;- }- value &= (1 << bits) - 1;- }- return bits ? out + alphabet[(value << (5 - bits)) & 31] : out;-};-const CACHE = "Library/Application Support/Grok Bot/sand-client-persistence";-const slice = (kind: string) => `${CACHE}/${base32(`sand.client.slice.account.user%2E1.${kind}`)}.blob`;const SECRET = "the-secret-chat-text-and-login";function appCache(put: (path: string, text: string) => string) {@@ -119,3 +104,56 @@ describe("what the desktop app finds about Grok Bot", () => {expect(() => removeOldCursorSignIn(join(home, "data"))).not.toThrow();});});++describe("one moved Bot's chat", () => {+ const NEW_A = "1731b8e0-0000-4000-8000-000000000001", NEW_B = "28ae2014-0000-4000-8000-000000000002";+ const DREW = "d0bdfa13-0000-4000-8000-000000000003", QUIET = "e1e1e1e1-0000-4000-8000-000000000004";+ const chat = (text: string) => JSON.stringify({ schemaVersion: 1, value: { entries: [{ kind: "message", seq: 1, role: "user", content: text, timestampMs: 1 }], persistedAt: 2 } });+ function cache() {+ const { home, put } = fixtureHome();+ // appCache writes a roster that the one below replaces; everything else it writes must stay unopened.+ const never = [...appCache(put), put(`${CACHE}/${base32("sand.client.slice.account.user%2E1.transcript.replicas")}.blob`, SECRET)];+ put(slice("roster.last-roster"), JSON.stringify({ schemaVersion: 1, value: { rows: [+ { id: NEW_A, name: "New Bot" }, { id: NEW_B, name: "New Bot" }, { id: DREW, name: "Drew" }, { id: QUIET, name: "Quiet" },+ { id: "g1", name: "Team room", isGroup: true },+ ] } }));+ const chats = Object.fromEntries([NEW_A, NEW_B, DREW, "g1"].map((id) => [id, put(slice(`transcript.replicas.${id}`), chat(`chat of ${id}`))]));+ return { home, put, chats, never, roster: join(home, slice("roster.last-roster")) };+ }++ it("matches the Bot by its name, whatever the case or spaces, and opens only the roster and that Bot's chat", () => {+ const { home, chats, never, roster } = cache();+ const machine = machineAt(home);+ expect(readGrokChat(machine, " drew ")).toEqual({ entries: [{ kind: "message", seq: 1, role: "user", content: `chat of ${DREW}`, timestampMs: 1 }] });+ expect(machine.opened).toEqual([roster, chats[DREW]]);+ for (const path of [...never, chats[NEW_A], chats[NEW_B], chats.g1]) expect(machine.opened).not.toContain(path);+ });++ it("tells Bots that share a name apart by the start of the id in the name, and otherwise picks none", () => {+ const { home, chats, roster } = cache();+ const machine = machineAt(home);+ expect(readGrokChat(machine, "New Bot 28ae2014")).toMatchObject({ entries: [{ content: `chat of ${NEW_B}` }] });+ expect(readGrokChat(machine, "New Bot (1731B8E0)")).toMatchObject({ entries: [{ content: `chat of ${NEW_A}` }] });+ expect(machine.opened).toEqual([roster, chats[NEW_B], roster, chats[NEW_A]]);+ machine.opened.length = 0;+ expect(readGrokChat(machine, "New Bot")).toEqual({ reason: "ambiguous" });+ expect(readGrokChat(machine, "New Bot ffffffff")).toEqual({ reason: "noMatch" });+ expect(readGrokChat(machine, "Drew 28ae2014")).toEqual({ reason: "noMatch" });+ expect(readGrokChat(machine, "Team room")).toEqual({ reason: "noMatch" });+ expect(machine.opened).toEqual([roster, roster, roster, roster]);+ });++ it("says when the app isn't here, or has no chat saved for the Bot", () => {+ const empty = machineAt(fixtureHome().home);+ expect(readGrokChat(empty, "Drew")).toEqual({ reason: "noApp" });+ expect(empty.opened).toEqual([]);+ const { home, put } = cache();+ expect(readGrokChat(machineAt(home), "Quiet")).toEqual({ reason: "empty" });+ put(slice(`transcript.replicas.${DREW}`), JSON.stringify({ schemaVersion: 1, value: { entries: [] } }));+ expect(readGrokChat(machineAt(home), "Drew")).toEqual({ reason: "empty" });+ put(slice(`transcript.replicas.${DREW}`), "not json");+ expect(readGrokChat(machineAt(home), "Drew")).toEqual({ reason: "empty" });+ put(slice("roster.last-roster"), "not json");+ expect(readGrokChat(machineAt(home), "Drew")).toEqual({ reason: "noMatch" });+ });+});diff --git a/server/grok-local.ts b/server/grok-local.tsindex 250aa01b49..7cb206aeb4 100644--- a/server/grok-local.ts+++ b/server/grok-local.ts@@ -1,15 +1,15 @@// What the desktop app may find about Grok Bot on this computer. The Bot writes its own export (shared/grok-import.ts);-// the only things read here are those files in Downloads and the roster slice of the UI cache the Grok Bot app keeps, for-// the names of the Bots on this computer. Security: login material lives beside that cache (sand-secrets.json, cookies,-// ~/.grokbot) and is never opened, nor is any other slice, chats included; no path here is built from anything but the two-// names below or a file's own listing.+// the only things read here are those files in Downloads, the roster slice of the UI cache the Grok Bot app keeps, for+// the names of the Bots on this computer, and one Bot's chat slice, only while that Bot is being moved. Security: login+// material lives beside that cache (sand-secrets.json, cookies, ~/.grokbot) and is never opened, nor is any other slice or+// any other Bot's chat; no path here is built from anything but the two names below or a file's own listing.//// The cache's layout (Grok Bot desktop, recorded from a Windows install) and this reading of it adapt an MIT-licensed// importer; see NOTICE.import { rmSync } from "node:fs";import { join } from "node:path";-import { GROK_EXPORT_FILE, GROK_EXPORT_MAX_CHARS } from "../shared/grok-import.ts";+import { GROK_EXPORT_FILE, GROK_EXPORT_MAX_CHARS, type GrokHistoryReason } from "../shared/grok-import.ts";import { redactSecretsInText } from "../shared/redact.ts";import type { SetupMachine } from "./setup-import.ts";@@ -17,6 +17,7 @@ const USER_DATA_FOLDERS = [["Library", "Application Support", "Grok Bot"], ["Appconst CACHE_FOLDER = "sand-client-persistence";const SLICE_PREFIX = "sand.client.slice.account.";const ROSTER_SLICE = "roster.last-roster";+const CHAT_SLICE = "transcript.replicas.";const MAX_SLICE_BYTES = 32 * 1024 * 1024;const MAX_EXPORT_FILES = 20;const MAX_EXPORT_BYTES = 16 * 1024 * 1024;@@ -80,19 +81,53 @@ const shown = (value: unknown) => (typeof value === "string" ? redactSecretsInTeconst rows = (value: unknown): Array<Record<string, unknown>> =>Array.isArray(value) ? value.filter((row): row is Record<string, unknown> => Boolean(row) && typeof row === "object") : [];-/** A hint only: a missing or unreadable cache, or a layout this does not know, answers nothing. */-function rosterBots(machine: SetupMachine): string[] {+/** The Grok Bot app's cache here, or null when the app isn't. `bots` is empty when its roster is missing or unreadable. */+function appCache(machine: SetupMachine) {const folder = USER_DATA_FOLDERS.map((parts) => join(machine.home, ...parts, CACHE_FOLDER)).find((path) => machine.fs.lstat(path)?.isDirectory());const listing = folder ? machine.fs.readdir(folder) : null;- const slice = listing?.find((name) => sliceKind(sliceId(name)) === ROSTER_SLICE);- if (!folder || !slice) return [];- return rows(sliceValue(machine, join(folder, slice))?.rows).flatMap((row) => {+ if (!folder || !listing) return null;+ const read = (kind: string) => {+ const slice = listing.find((name) => sliceKind(sliceId(name)) === kind);+ return slice ? sliceValue(machine, join(folder, slice)) : null;+ };+ return { bots: rows(read(ROSTER_SLICE)?.rows).filter((row) => !row.isGroup), read };+}++/** A hint only: a missing or unreadable cache, or a layout this does not know, answers nothing. */+function rosterBots(machine: SetupMachine): string[] {+ return (appCache(machine)?.bots ?? []).flatMap((row) => {const name = shown(row.name);- return name && !row.isGroup ? [name] : [];+ return name ? [name] : [];});}+const key = (text: string) => text.trim().toLowerCase();++/** The roster row of the Bot an export names. Grok Bot lets names repeat, so the MausBot bot there adds the first 8+ * characters of the Bot's id to a repeated name; a name that still fits several rows, or none, picks nothing. */+function rosterRow(bots: Array<Record<string, unknown>>, exportName: string): Record<string, unknown> | "noMatch" | "ambiguous" {+ const name = key(exportName);+ const tokens = name.match(/\b[0-9a-f]{8}\b/g) ?? [];+ const tagged = (row: Record<string, unknown>) => tokens.some((token) => String(row.id).toLowerCase().startsWith(token));+ const named = bots.filter((row) => typeof row.id === "string" && row.id && typeof row.name === "string" &&+ (key(row.name) === name || (tagged(row) && name.includes(key(row.name)))));+ const picked = named.length > 1 ? named.filter(tagged) : named;+ return picked.length === 1 ? picked[0]! : named.length ? "ambiguous" : "noMatch";+}++export type GrokChat = { entries: unknown[] } | { reason: GrokHistoryReason };++/** One Bot's chat, as the entries of its slice; only the roster and that one slice are opened. */+export function readGrokChat(machine: SetupMachine, exportName: string): GrokChat {+ const cache = appCache(machine);+ if (!cache) return { reason: "noApp" };+ const row = rosterRow(cache.bots, exportName);+ if (typeof row === "string") return { reason: row };+ const entries = cache.read(`${CHAT_SLICE}${row.id as string}`)?.entries;+ return Array.isArray(entries) && entries.length ? { entries } : { reason: "empty" };+}+/** The exports in Downloads, newest first. A symlink is refused: only a real file with that name counts. */function readExportFiles(machine: SetupMachine): GrokFoundFile[] {const folder = join(machine.home, "Downloads");diff --git a/server/testing/grok-cache.ts b/server/testing/grok-cache.tsnew file mode 100644index 0000000000..6c578d64de--- /dev/null+++ b/server/testing/grok-cache.ts@@ -0,0 +1,19 @@+/** A file of the Grok Bot app's cache, at the path the app gives it: its slice id as unpadded lowercase base32. */+export const GROK_CACHE = "Library/Application Support/Grok Bot/sand-client-persistence";++export function base32(text: string): string {+ const alphabet = "abcdefghijklmnopqrstuvwxyz234567";+ let bits = 0, value = 0, out = "";+ for (const byte of Buffer.from(text)) {+ value = (value << 8) | byte;+ bits += 8;+ while (bits >= 5) {+ out += alphabet[(value >>> (bits - 5)) & 31];+ bits -= 5;+ }+ value &= (1 << bits) - 1;+ }+ return bits ? out + alphabet[(value << (5 - bits)) & 31] : out;+}++export const grokSlice = (kind: string) => `${GROK_CACHE}/${base32(`sand.client.slice.account.user%2E1.${kind}`)}.blob`;diff --git a/shared/grok-import.ts b/shared/grok-import.tsindex 2b5e15ee78..6cdeb169ed 100644--- a/shared/grok-import.ts+++ b/shared/grok-import.ts@@ -64,6 +64,13 @@ If it is too long for one message or file, split it: send several documents, eacexport type GrokImportErrorCode = "notExport" | "cutOff" | "tooLarge" | "credentials" | "newerVersion" | "unusable";+/** Why a moved Bot's chat didn't come over from the Grok Bot app on this computer: the app isn't here, no Bot or several+ * Bots there have its name, or it has no chat saved. */+export const GROK_HISTORY_REASONS = ["noApp", "noMatch", "ambiguous", "empty"] as const;+export type GrokHistoryReason = typeof GROK_HISTORY_REASONS[number];+/** The answer to POST /api/setup-import/grok/history: how many messages of the Bot's chat are in its thread here. */+export type GrokHistoryAnswer = { messages: number } | { reason: GrokHistoryReason };+export class GrokImportError extends Error {readonly code: GrokImportErrorCode;/** The credential-looking keys, for "credentials". */