Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep server/index.ts at its size: share the turn file's source, fold the new room-turn helpers
milind-soni02df6d441619
diff --git a/server/index.ts b/server/index.tsindex dec40261c9..7ec8d469cf 100644--- a/server/index.ts+++ b/server/index.ts@@ -3910,8 +3910,7 @@ const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { storeconst bot = store.bot(child.botId);if (store.messagesFor(parent.threadId).some(m => m.roomRequest?.id === child.id && m.roomRequest.phase === "result")) return;const problem = roomHandoffProblem(child, parent);- const source = store.bot(parent.botId);- const owner = directRequestOwners.get(parent.threadId);+ const source = store.bot(parent.botId), owner = directRequestOwners.get(parent.threadId);const answer = problem || !source ? null: taggedAnswerRow(child, parent, bot, (botId) => taggedTeammates(parent.text, personalReach.peers(store.bots, source, parent.threadId)).some((one) => one.id === botId),owner && !owner.stopped && owner.generations.has(parent.id) ? owner.messageId : undefined);@@ -4148,8 +4147,7 @@ function groupMemberBotAvailability(botId: string, operation: GroupTurnOperation/** One bot's turns in different room threads run at once, within the same per-bot thread limit as its own chats. */function roomTurnBlocked(botId: string, threadId: string): boolean {- const others = new Set([...roomMemberLock.threads(botId), ...store.roomActivities.busyThreads(botId)]); others.delete(threadId);- return store.busyForRoomThread(botId, threadId) || others.size >= maxConcurrentBotThreads(cfg, botThreadsHost(cloudPlanTier.starter()));+ const others = new Set([...roomMemberLock.threads(botId), ...store.roomActivities.busyThreads(botId)]); others.delete(threadId); return store.busyForRoomThread(botId, threadId) || others.size >= maxConcurrentBotThreads(cfg, botThreadsHost(cloudPlanTier.starter()));}/** One synchronous step, so threads woken by the same release cannot all read the member as free. */@@ -4422,25 +4420,15 @@ function groupProviderHandshakeSettled(operation: GroupTurnOperation): void {function groupTurnsForBot(botId: string): { group: GroupRecord; threadId: string }[] {const turns = new Map<string, { group: GroupRecord; threadId: string }>();for (const group of store.groups) {- for (const operation of groupTurnOperations.get(group.id) ?? []) {- if (!operation.cancelled && operation.botIds.has(botId) && !turns.has(operation.threadId)) turns.set(operation.threadId, { group, threadId: operation.threadId });- }- for (const [threadId, speaker] of groupSpeakers) {- if (speaker.botId !== botId || turns.has(threadId)) continue;- const ownsThread = group.dm- ? group.threadId === threadId- : Boolean(store.groupTaskByThread(group.id, threadId));- if (ownsThread) turns.set(threadId, { group, threadId });- }+ for (const operation of groupTurnOperations.get(group.id) ?? []) if (!operation.cancelled && operation.botIds.has(botId) && !turns.has(operation.threadId)) turns.set(operation.threadId, { group, threadId: operation.threadId });+ // A speaker counts only in a thread of this room.+ for (const [threadId, speaker] of groupSpeakers) if (speaker.botId === botId && !turns.has(threadId) && (group.dm ? group.threadId === threadId : Boolean(store.groupTaskByThread(group.id, threadId)))) turns.set(threadId, { group, threadId });if (group.busyBotId === botId && ![...turns.values()].some((turn) => turn.group.id === group.id)) turns.set(group.threadId, { group, threadId: group.threadId });}return [...turns.values()];}-/** The bot's room turn in threadId when it has one there, else any of its room turns. */-function activeGroupTurnForBot(botId: string, threadId?: string): { group: GroupRecord; threadId: string } | null {- const turns = groupTurnsForBot(botId); return turns.find((turn) => turn.threadId === threadId) ?? turns[0] ?? null;-}+function activeGroupTurnForBot(botId: string, threadId?: string): { group: GroupRecord; threadId: string } | null { const turns = groupTurnsForBot(botId); return turns.find((turn) => turn.threadId === threadId) ?? turns[0] ?? null; }const groupWithThread = (group: GroupRecord) => {const state = publicGroupState(group);@@ -7407,10 +7395,8 @@ const titleRegenerations = new Set<string>();function startTurn(...args: Parameters<typeof beginTurn>): ReturnType<typeof beginTurn> { return batchSaves(() => beginTurn(...args)); }/** The teammates a person's "@Name" tags in `text`, never a bot that shares the name of the writer or a teammate. */function taggedTeammates<T extends { id?: string; name: string; hidden?: boolean }>(text: string, peers: T[], picked?: readonly string[]): T[] {- return mentionedBots(withoutPersonTags(text, [...personTagNames(cfg.profile?.name), ...teamMessages.people().flatMap((one) => one.tags)],- store.bots.filter((one) => !one.hidden).map((one) => one.name)), peers, picked);+ return mentionedBots(withoutPersonTags(text, [...personTagNames(cfg.profile?.name), ...teamMessages.people().flatMap((one) => one.tags)], store.bots.filter((one) => !one.hidden).map((one) => one.name)), peers, picked);}-async function beginTurn(botId: string,text: string,@@ -10951,20 +10937,14 @@ function messageFileRootsForThread(senderId: string, threadId: string): string[]});}-/** A bot's own file copied into the attachment store, for attach_file and coordinate_bots' files alike. The store is no source: only the+/** A bot's own file, for attach_file, coordinate_bots' files and email attachments alike (readBotFile). The attachment store is no source: only the* bot's own files are (its conversation's inbox of received files among them), or one saved outside them this turn, never from the data dir. */-function saveTurnFile(capability: InternalCapability, botId: string, vm: LocalVmTarget | undefined, path: string, name: string | undefined, byContent: boolean) {- return saveBotAttachment({ path, name, byContent, roots: messageFileRootsForThread(botId, capability.threadId).filter((root) => root !== ATTACHMENTS_DIR), inbox: inboxRead(botId, capability.threadId), attached: () => conversationAttachments(store.messagesFor(capability.threadId)),- ...(vm ? { guest: { root: VM_WORKSPACE_GUEST, host: vm.workspaceDir } } : {}),- ...(capability.deliversSavedFiles && capability.turnStartedAt !== undefined ? { savedThisTurn: { since: capability.turnStartedAt, refuse: [DATA_DIR] } } : {}) });-}--/** The same file saveTurnFile would take, read whole for an email attachment. */-function readTurnFile(capability: InternalCapability, botId: string, vm: LocalVmTarget | undefined, path: string) {- return readBotFile({ path, roots: messageFileRootsForThread(botId, capability.threadId).filter((root) => root !== ATTACHMENTS_DIR), inbox: inboxRead(botId, capability.threadId), attached: () => conversationAttachments(store.messagesFor(capability.threadId)),+function turnFile(capability: InternalCapability, botId: string, vm: LocalVmTarget | undefined, path: string) {+ return { path, roots: messageFileRootsForThread(botId, capability.threadId).filter((root) => root !== ATTACHMENTS_DIR), inbox: inboxRead(botId, capability.threadId), attached: () => conversationAttachments(store.messagesFor(capability.threadId)),...(vm ? { guest: { root: VM_WORKSPACE_GUEST, host: vm.workspaceDir } } : {}),- ...(capability.deliversSavedFiles && capability.turnStartedAt !== undefined ? { savedThisTurn: { since: capability.turnStartedAt, refuse: [DATA_DIR] } } : {}) });+ ...(capability.deliversSavedFiles && capability.turnStartedAt !== undefined ? { savedThisTurn: { since: capability.turnStartedAt, refuse: [DATA_DIR] } } : {}) };}+function saveTurnFile(capability: InternalCapability, botId: string, vm: LocalVmTarget | undefined, path: string, name: string | undefined, byContent: boolean) { return saveBotAttachment({ ...turnFile(capability, botId, vm, path), name, byContent }); }async function attachmentVmForTurn(capability: InternalCapability): Promise<LocalVmTarget | undefined> {const slot = autoVmClaims.get(capability.threadId);@@ -12975,7 +12955,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}) });}// The mail passwords stay here; the agent process holds only the turn's capability, and every call gets the live bot's verdict.- if (method === "POST" && path === EMAIL_INTERNAL_MCP_PATH) { return json(res, 200, { result: await emailHost.handle(await readInternalBody(), internalCapability, requireActiveInternalCapability, linkLimits.held(internalCapability.threadId) ? LINK_APP_WRITE_REFUSAL : undefined, async (path) => readTurnFile(internalCapability, internalSender.id, await attachmentVmForTurn(internalCapability), path)) }); }+ if (method === "POST" && path === EMAIL_INTERNAL_MCP_PATH) { return json(res, 200, { result: await emailHost.handle(await readInternalBody(), internalCapability, requireActiveInternalCapability, linkLimits.held(internalCapability.threadId) ? LINK_APP_WRITE_REFUSAL : undefined, async (path) => readBotFile(turnFile(internalCapability, internalSender.id, await attachmentVmForTurn(internalCapability), path))) }); }if (method === "POST" && path === PHONE_INTERNAL_MCP_PATH) {return json(res, 200, { result: await phones.handle(await readInternalBody(), internalCapability, requireActiveInternalCapability) });}