Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { z } from "zod";
import type { WireGroup } from "../../shared/wire.ts";
import { writeFileAtomic } from "../atomic.ts";
import { isReply } from "../held-unread.ts";
import { personKey } from "../person-key.ts";
import type { RequestAuth } from "../request-auth.ts";
import type { GroupRecord } from "../store.ts";
const ROOM_READS_FILE = "room-reads.json";
const fileSchema = z.object({ version: z.literal(1), reads: z.record(z.string(), z.record(z.string(), z.string())) });
type PathMessage = { id: string; role: string; kind?: string; at?: number };
/** Unread for a person: a bot replied after where they read up to; with no line yet, the room's own mark. A line no
* longer on the path (an edit or a retry moved it) reads up to the last message at or before it; `atOf` gives its time. */
export function roomUnreadFor(path: readonly PathMessage[], readUpTo: string | undefined, roomUnread: boolean, atOf?: (id: string) => number | undefined): boolean {
if (readUpTo === undefined) return roomUnread;
let from = path.findIndex((message) => message.id === readUpTo) + 1;
if (from === 0) {
const readAt = atOf?.(readUpTo);
if (readAt === undefined) return false;
from = path.findLastIndex((message) => (message.at ?? 0) <= readAt) + 1;
}
return path.slice(from).some(isReply);
}
/** The message a mark holds from: of those on the path, the one written last, whatever its clock says; "" for an empty
* conversation. `written` is the conversation's messages in the order they were written. */
export function heldFrom(path: readonly PathMessage[], written: readonly PathMessage[] = path): string {
const onPath = new Set(path.map((message) => message.id));
return written.findLast((message) => onPath.has(message.id))?.id ?? "";
}
/** A conversation marked unread with `held` from {@link heldFrom} stays held until a reply written after it reaches the
* path, at any place on it and with any clock. A message no longer on the path (an edit or a retry moved it) ends the mark. */
export function stillHeldUnread(path: readonly PathMessage[], held: string | undefined, written: readonly PathMessage[] = path): boolean {
if (held === undefined || (held !== "" && !path.some((message) => message.id === held))) return false;
const order = new Map(written.map((message, index) => [message.id, index])), heldAt = held === "" ? -1 : order.get(held) ?? -1;
return !path.some((message) => isReply(message) && (order.get(message.id) ?? Infinity) > heldAt);
}
/** `alsoForget`: a person's other marks of their own (their bots' order, their notification reads), which go with
* their read lines when they leave the team. */
export function createRoomReads(dataDir: string, alsoForget?: (person: string) => void) {
const file = join(dataDir, ROOM_READS_FILE);
let reads: Record<string, Record<string, string>> = {};
try {
const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));
if (parsed.success) reads = parsed.data.reads;
else console.warn(`room reads: ${file} is not a room reads file; starting fresh`);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.warn(`room reads: ${file} is unreadable; starting fresh`);
}
const save = () => {
try {
writeFileAtomic(file, `${JSON.stringify({ version: 1, reads })}\n`, { mode: 0o600 });
} catch (error) {
console.warn(`room reads: could not save ${file}: ${error instanceof Error ? error.message : String(error)}`);
}
};
const key = (groupId: string, threadId?: string) => threadId ? `${groupId}/${threadId}` : groupId;
return {
readUpTo: (groupId: string, person: string, threadId?: string): string | undefined => reads[key(groupId, threadId)]?.[person],
read(groupId: string, person: string, messageId: string, threadId?: string): void {
const bucket = key(groupId, threadId);
if (reads[bucket]?.[person] === messageId) return;
(reads[bucket] ??= {})[person] = messageId;
save();
},
forget(groupId: string, person: string, threadId?: string): void {
const bucket = key(groupId, threadId);
if (reads[bucket]?.[person] === undefined) return;
delete reads[bucket]![person];
save();
},
forgetRoom(groupId: string): void {
const buckets = Object.keys(reads).filter((bucket) => bucket === groupId || bucket.startsWith(`${groupId}/`));
if (!buckets.length) return;
for (const bucket of buckets) delete reads[bucket];
save();
},
forgetPerson(person: string): void {
alsoForget?.(person);
const rooms = Object.values(reads).filter((room) => room[person] !== undefined);
if (!rooms.length) return;
for (const room of rooms) delete room[person];
save();
},
};
}
export type RoomReads = ReturnType<typeof createRoomReads>;
/** A bot's shared conversation's key in `room-reads.json`, apart from every room's id. */
export const threadReadKey = (threadId: string) => `thread:${threadId}`;
/** A person's "marked unread with it open" on a bot's shared conversation: the newest message then. */
const threadHoldKey = (threadId: string) => `held:${threadId}`;
/** One stream frame's `group` payload as a person's own room, built once per person for that frame; null: theirs is the
* room as it is. */
export type OwnGroupFrames = Map<string, Record<string, unknown> | null>;
export interface PersonRoomsDeps {
/** Each person's own read line in each room, on a Team Cloud; null anywhere else, where a room reads the same for all. */
reads: RoomReads | null;
store(): { activePath(threadId: string): readonly PathMessage[]; messagesFor(threadId: string): readonly PathMessage[]; botByThread(threadId: string): { id: string } | null | undefined };
/** A bot's conversation more than one person reads (the team's, not someone's private chat). */
shared(threadId: string): boolean;
/** A bot as its `bot` frame carries it. */
wireBot(botId: string): object | null;
/** The newest message on a conversation's path, the line a room is read up to. */
newestMessageId(threadId: string): string | undefined;
publicGroupState(room: GroupRecord): WireGroup;
broadcast(payload: Record<string, unknown>, options: { person: string }): void;
}
/** Each person's view of a room (server/index.ts): its unread mark and read line as they read it, on a Team Cloud. */
export function createPersonRooms(deps: PersonRoomsDeps) {
const { reads } = deps;
const atOf = (threadId: string) => (id: string) => deps.store().messagesFor(threadId).find((message) => message.id === id)?.at;
/** A room's unread mark and read line as this person has read it, on a Team Cloud; the room as it is anywhere else. */
function groupForPerson(group: WireGroup, person: string | null): WireGroup {
if (!reads || !person) return group;
const currentPath = deps.store().activePath(group.threadId);
const legacyRead = reads.readUpTo(group.id, person);
const currentRead = reads.readUpTo(group.id, person, group.threadId)
?? (legacyRead && currentPath.some((message) => message.id === legacyRead) ? legacyRead : undefined);
const tasks = group.tasks?.map((task) => {
const path = deps.store().activePath(task.threadId);
const readUpTo = task.threadId === group.threadId ? currentRead : reads.readUpTo(group.id, person, task.threadId);
const unread = roomUnreadFor(path, readUpTo, task.unread ?? false, atOf(task.threadId));
return { ...task, unread };
});
const unread = tasks ? tasks.some((task) => task.unread) : roomUnreadFor(currentPath, currentRead, group.unread, atOf(group.threadId));
if (unread === group.unread && currentRead === group.lastReadMessageId &&
(!tasks || tasks.every((task, index) => task.unread === group.tasks?.[index]?.unread))) return group;
const { lastReadMessageId: _shared, ...rest } = group;
return { ...rest, tasks, unread, ...(currentRead ? { lastReadMessageId: currentRead } : {}) };
}
/** A bot's shared conversation's unread mark and read line as this person read it, on a Team Cloud; the task as it is
* anywhere else and for a private chat. Nobody's read line but their own goes out. */
function taskForPerson<T extends { threadId: string; unread?: boolean; lastReadMessageId?: string; heldUnread?: string }>(task: T, person: string): T {
if (!reads || !deps.shared(task.threadId)) return task;
const path = deps.store().activePath(task.threadId), readUpTo = reads.readUpTo(threadReadKey(task.threadId), person);
const held = reads.readUpTo(threadHoldKey(task.threadId), person), heldUnread = stillHeldUnread(path, held, deps.store().messagesFor(task.threadId)) ? held : undefined;
const unread = heldUnread !== undefined || roomUnreadFor(path, readUpTo, task.unread === true, atOf(task.threadId));
if (unread === (task.unread === true) && readUpTo === task.lastReadMessageId && heldUnread === task.heldUnread) return task;
const { lastReadMessageId: _shared, heldUnread: _held, ...rest } = task;
return { ...rest, unread, ...(readUpTo ? { lastReadMessageId: readUpTo } : {}), ...(heldUnread !== undefined ? { heldUnread } : {}) } as T;
}
return {
reads,
groupForPerson,
taskForPerson,
/** A deleted room's or conversation's read lines go with it. */
forgetDeleted(change: { type: string; groupId?: string; threadId?: string }): void {
if (change.type === "group.deleted" && change.groupId) reads?.forgetRoom(change.groupId);
else if (change.type === "thread.deleted" && change.threadId) for (const key of [threadReadKey, threadHoldKey]) reads?.forgetRoom(key(change.threadId));
},
groupForAuth: (auth: RequestAuth, group: WireGroup): WireGroup => groupForPerson(group, auth.kind === "session" ? personKey(auth.session) : null),
ownGroupPayload(ownGroups: OwnGroupFrames, person: string, payload: Record<string, unknown>) {
if (!reads || payload.kind !== "group") return null;
if (!ownGroups.has(person)) {
const group = payload.group as WireGroup;
const own = groupForPerson(group, person);
ownGroups.set(person, own === group ? null : { ...payload, group: own });
}
return ownGroups.get(person) ?? null;
},
/** Marks a room read or unread for the person signed in (server/routes/channels.ts `personMarkRoom`), told to their
* streams alone; absent anywhere but a Team Cloud. */
...(reads ? { personMarkRoom: (auth: RequestAuth, room: GroupRecord, unread: boolean, threadId = room.threadId): WireGroup | null => {
if (auth.kind !== "session") return null;
const person = personKey(auth.session);
const newest = deps.newestMessageId(threadId);
if (unread) {
reads.forget(room.id, person, threadId);
if (threadId === room.threadId) reads.forget(room.id, person);
} else if (newest) reads.read(room.id, person, newest, threadId);
const group = deps.publicGroupState(room);
deps.broadcast({ kind: "group", group }, { person });
return groupForPerson(group, person);
},
/** Marks a bot's shared conversation read or unread for the person signed in, told to their streams alone; false for
* a private chat, which keeps its one mark. Unread reads up to just before the conversation's newest reply. */
personMarkThread: (auth: RequestAuth, threadId: string, unread: boolean): boolean => {
if (auth.kind !== "session" || !deps.shared(threadId)) return false;
const person = personKey(auth.session), key = threadReadKey(threadId), newest = deps.newestMessageId(threadId);
if (unread) {
const path = deps.store().activePath(threadId), reply = path.findLastIndex(isReply);
if (reply > 0) reads.read(key, person, path[reply - 1]!.id);
else reads.forget(key, person);
reads.read(threadHoldKey(threadId), person, heldFrom(path, deps.store().messagesFor(threadId)));
} else {
reads.forget(threadHoldKey(threadId), person);
if (newest) reads.read(key, person, newest);
}
const bot = deps.store().botByThread(threadId), frame = bot ? deps.wireBot(bot.id) : null;
if (frame) deps.broadcast({ kind: "bot", bot: frame }, { person });
return true;
},
/** Whether this person's mark on a bot's shared conversation still holds; null for a private chat, which keeps the
* conversation's own mark. */
personHeldUnread: (auth: RequestAuth, threadId: string): boolean | null => {
if (auth.kind !== "session" || !deps.shared(threadId)) return null;
return stillHeldUnread(deps.store().activePath(threadId), reads.readUpTo(threadHoldKey(threadId), personKey(auth.session)), deps.store().messagesFor(threadId));
} } : {}),
};
}