Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(cloud): bots know which lent computer the person is typing on
Bugfixer 292a70748fc92
diff --git a/server/index.ts b/server/index.tsindex 2785c558d7..c23718cc84 100644--- a/server/index.ts+++ b/server/index.ts@@ -385,7 +385,7 @@ import {undoSkillWrite,} from "./skills.ts";import { fetchSkillFromSource } from "./skill-fetch.ts";-import { ensureTaskWorkspaceWithSkills, harnessSkillLinks } from "./skill-task-links.ts"; import { changedWords, createLendingLifts, handedInSince } from "./host/lending-lifts.ts"; import { deviceWord } from "./lent-computers.ts";+import { ensureTaskWorkspaceWithSkills, harnessSkillLinks } from "./skill-task-links.ts"; import { changedWords, createLendingLifts, handedInSince } from "./host/lending-lifts.ts"; import { deviceWord } from "./lent-computers.ts"; import { sendingSession } from "./sending-sessions.ts";import { importedSkillRequest, parseSkillManageReferences, previousSkillVersion, skillCardCopy, skillRequestReferences } from "./skill-request-card.ts";import { skillReferencesSha256 } from "./skill-storage.ts";import { createSkillsLibraryHost } from "./host/skills-library.ts";@@ -7590,7 +7590,7 @@ async function beginTurn(});}const personLine = !opts?.coordination && !opts?.cardContinuation && !opts?.automationSource && !opts?.compactOnly- && !opts?.computerSelectionContinuation && !opts?.editedMessageId && !commsDepth && !opts?.peerAsk && !userMessage.peerAsk; if (personLine) cloudConnections.personTurn(bot, threadId);+ && !opts?.computerSelectionContinuation && !opts?.editedMessageId && !commsDepth && !opts?.peerAsk && !userMessage.peerAsk; if (personLine) cloudConnections.personTurn(bot, threadId); const typingSession = personLine && !userMessage.relayed ? sendingSession(threadId, userMessage.sendId) : undefined;if (personLine && !userMessage.relayed && (coordinator.answer(threadId, text) || signInSettle.answerInChat(bot.id, threadId, text))) {askCards.answeredInWords(threadId, text);store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: serverLine(threadLanguage(threadId), "server.teammates.answerPassed"), ok: true } });@@ -8276,8 +8276,8 @@ async function beginTurn({ id: "shell", label: "Long-running commands", text: worksInWorkspace ? longCommandsPrompt(computerPromptKind) : "" },{ id: "computer", label: "Computer", text: computerPrompt(computerPromptKind) },{ id: "team-computer", label: "Team computer", text: teamComputerPrompt(teamComputer) },- { id: "plan", label: "Surface", text: surfacePrompt({ computer: mountedComputer, browser: Boolean(integrations.browser) }, { pinned: plan.pinned, note: plan.note + vpsUnavailableNote + vmUpdateNote + (computerSkipped && plan.computer !== "off" ? computerSkippedNote(redactSecretsInText(computerSkipped)) : "") + (computerSelectionTurns.get(threadId)?.handoff && !integrations.browser ? HANDOFF_BROWSER_NOTE : ""), canSelect: computerSelectionTurns.has(threadId) && !computerSelectionTurns.get(threadId)?.handoff, selectionRules: !selectionRulesStable, cloudHome: Boolean(CLOUD_HOME), botOpened: plan.botOpened, ownComputer: CLOUD_HOME && integrations.agents && lendingEnabled() ? sharedComputers.known(CLOUD_HOME_LENDER) : undefined, thisComputer: !CLOUD_HOME && bot.computer !== "off" && !inheritedTeamComputer(bot) && shouldMountLocalComputer({ requested: "local", providerSupportsLocal: instance.adapter.capabilities.localComputerMcp === true }) ? { bot: bot.name, botId: bot.id, platform: process.platform } : undefined }) }, { id: "computer-selection", label: "Choosing a computer", text: selectionRulesStable ? computerSelectionPrompt({ cloudHome: Boolean(CLOUD_HOME) }) : "" },- { id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(Boolean(integrations.agents) && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER), CLOUD_PERSONAL) + firstHourHooks.prompt(bot.id, threadId) : "" }, phoneLinkPart(),+ { id: "plan", label: "Surface", text: surfacePrompt({ computer: mountedComputer, browser: Boolean(integrations.browser) }, { pinned: plan.pinned, note: plan.note + vpsUnavailableNote + vmUpdateNote + (computerSkipped && plan.computer !== "off" ? computerSkippedNote(redactSecretsInText(computerSkipped)) : "") + (computerSelectionTurns.get(threadId)?.handoff && !integrations.browser ? HANDOFF_BROWSER_NOTE : ""), canSelect: computerSelectionTurns.has(threadId) && !computerSelectionTurns.get(threadId)?.handoff, selectionRules: !selectionRulesStable, cloudHome: Boolean(CLOUD_HOME), botOpened: plan.botOpened, ownComputer: CLOUD_HOME && integrations.agents && lendingEnabled() ? sharedComputers.known(CLOUD_HOME_LENDER, typingSession) : undefined, thisComputer: !CLOUD_HOME && bot.computer !== "off" && !inheritedTeamComputer(bot) && shouldMountLocalComputer({ requested: "local", providerSupportsLocal: instance.adapter.capabilities.localComputerMcp === true }) ? { bot: bot.name, botId: bot.id, platform: process.platform } : undefined }) }, { id: "computer-selection", label: "Choosing a computer", text: selectionRulesStable ? computerSelectionPrompt({ cloudHome: Boolean(CLOUD_HOME) }) : "" },+ { id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(Boolean(integrations.agents) && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER, typingSession), CLOUD_PERSONAL) + firstHourHooks.prompt(bot.id, threadId) : "" }, phoneLinkPart(),{ id: "composio", label: "Connected apps", text: integrations.composio ? composioSystemPrompt(liveBot?.connectorTools ?? bot.connectorTools) + describeConnectorScopes((liveBot ?? bot).connectorScopes) : "" },{ id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) }, { id: "to-connect", label: "Connections to make", text: cloudConnections.prompt(liveBot ?? bot, lentMcp.lines(liveBot ?? bot, { botId: bot.id, threadId, generation: dispatchClaimId })) + teamConnections.prompt(threadId, dispatchClaimId, integrations) },{ id: "browser", label: "Browser", text: integrations.browser ? browserPromptFor(bot, Boolean(integrations.agents)) : "" },diff --git a/server/lent-computers.ts b/server/lent-computers.tsindex 18d4e81d3a..8a6a2f6985 100644--- a/server/lent-computers.ts+++ b/server/lent-computers.ts@@ -126,15 +126,18 @@ export const lendScreenSteps = (device: "PC" | "Mac" | "computer") => device ===const dateText = (at: number) => new Date(at).toISOString().slice(0, 16).replace("T", " ") + " UTC";/** Every computer the person lent, as this turn's prompt tells it: names are theirs and may hold anything, so controls go. */-export function lentComputersLine(known: ReadonlyArray<{ name: string; platform: LentPlatform | null; online?: boolean; lent?: boolean; lastSeenAt?: number }>): string {+export function lentComputersLine(known: ReadonlyArray<{ name: string; platform: LentPlatform | null; online?: boolean; lent?: boolean; lastSeenAt?: number; typing?: boolean }>): string {+ let typingOn: string | null = null;const statuses = known.flatMap((computer) => {if (computer.online === undefined) return [];// eslint-disable-next-line no-control-regexconst name = computer.name.replace(/[\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069]/g, " ").slice(0, 80);- const state = computer.online ? "online" : computer.lent === false ? "no longer lent" : `offline since ${dateText(computer.lastSeenAt ?? 0)}`;+ if (computer.online && computer.typing) typingOn = name;+ const state = computer.online ? (computer.typing ? "online, they are typing on it now" : "online") : computer.lent === false ? "no longer lent" : `offline since ${dateText(computer.lastSeenAt ?? 0)}`;return [`${name} (${deviceWord(computer.platform)}): ${state}`];});- return statuses.length ? ` Their computers right now: ${statuses.join("; ")}.` : "";+ if (!statuses.length) return "";+ return ` Their computers right now: ${statuses.join("; ")}.` + (typingOn ? ` When they say "my computer" or "this computer", they mean ${typingOn}.` : "");}/**diff --git a/server/routes/bot-messages.test.ts b/server/routes/bot-messages.test.tsindex bc449ff97d..3c553d45ec 100644--- a/server/routes/bot-messages.test.ts+++ b/server/routes/bot-messages.test.ts@@ -18,6 +18,7 @@ import type { RequestAuth } from "../request-auth.ts";import { acceptedSendMatch, sendFingerprint, SendSequencer } from "../send-idempotency.ts";import { _queuedCount, drainSteeredMessages, queuedSteeredMessage, queueSteeredMessage } from "../steer-queue.ts";import { Store, type Message } from "../store.ts";+import { sendingSession } from "../sending-sessions.ts";import { typedWords } from "../typed-sends.ts";import { USER_ERROR } from "../user-errors.ts";import { createBotMessageRoutes, type BotMessageRouteDeps } from "./bot-messages.ts";@@ -134,7 +135,8 @@ async function fixture(over: Partial<Record<keyof BotMessageRouteDeps, unknown>>const server = createServer(async (req, res) => {const url = new URL(req.url ?? "/", "http://localhost");try {- const auth = { kind: "loopback", scopes: ["admin"] } as RequestAuth;+ const session = req.headers["x-test-session"];+ const auth = (typeof session === "string" ? { kind: "session", session: { id: session }, scopes: ["admin"] } : { kind: "loopback", scopes: ["admin"] }) as RequestAuth;const handled = await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody });if (!handled) json(res, 404, { from: "inline routes" });} catch (error) {@@ -145,8 +147,8 @@ async function fixture(over: Partial<Record<keyof BotMessageRouteDeps, unknown>>await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;- const post = async (body: unknown, suffix = "") => {- const response = await fetch(`${base}/api/bots/${bot.id}/messages${suffix}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });+ const post = async (body: unknown, suffix = "", headers: Record<string, string> = {}) => {+ const response = await fetch(`${base}/api/bots/${bot.id}/messages${suffix}`, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) });return { status: response.status, body: await response.json() as Record<string, any> };};const edit = async (messageId: string, body: unknown) => {@@ -342,6 +344,14 @@ describe("POST /api/bots/:id/messages and who typed it", () => {expect(typedWords(threadId, [relayed.body.message])).toBe("");});+ it("notes the signed-in session that sent a line, so a Cloud's bot knows which lent computer they type on", async () => {+ const { threadId, post } = await fixture();+ expect((await post({ threadId, sendId: SEND, text: words }, "", { "x-test-session": "pc-session" })).status).toBe(202);+ expect(sendingSession(threadId, SEND)).toBe("pc-session");+ expect((await post({ threadId, sendId: OTHER_SEND, text: words })).status).toBe(202);+ expect(sendingSession(threadId, OTHER_SEND)).toBeUndefined();+ });+it("does not take a bare loopback send as a person's on a headless server, where it may be a bot's shell", async () => {const { threadId, post } = await fixture({}, false);const plain = await post({ threadId, sendId: SEND, text: words });diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 8d6311a1e6..473ad55c18 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -35,6 +35,7 @@ import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";import { extractSteerImages } from "../turn-images.ts";import { followupFacts, helperFollowup, helperFollowupBody, mayFollowUp } from "../helper-followup.ts";import type { UsageTrigger } from "../usage-ledger.ts";+import { noteSendingSession } from "../sending-sessions.ts";import { noteTypedSend } from "../typed-sends.ts";import { engineSessionOutdated, startFresh } from "../fresh-start.ts";import { parseMentionPicks } from "../../shared/room-mentions.ts";@@ -341,6 +342,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler// paired session or the desktop capability proves a person and lifts the webhook block.const personPresent = auth.kind === "session" || DESKTOP_MANAGED;if (personPresent && sendId && !guarded && !press && !appSent) noteTypedSend(threadId, sendId, text);+ if (auth.kind === "session" && sendId) noteSendingSession(threadId, sendId, auth.session.id);if (pressKey) pressesInFlight.set(pressKey, sendId);try {const receipt = await acceptDirectSend({diff --git a/server/sending-sessions.test.ts b/server/sending-sessions.test.tsnew file mode 100644index 0000000000..94cd245167--- /dev/null+++ b/server/sending-sessions.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";+import { noteSendingSession, sendingSession } from "./sending-sessions.ts";++describe("the session that sent a line", () => {+ it("is known only for the same thread and sendId", () => {+ noteSendingSession("thread-a", "send-1", "pc-session");+ expect(sendingSession("thread-a", "send-1")).toBe("pc-session");+ expect(sendingSession("thread-a", "send-2")).toBeUndefined();+ expect(sendingSession("thread-b", "send-1")).toBeUndefined();+ expect(sendingSession("thread-a", undefined)).toBeUndefined();+ });++ it("keeps the newest lines and forgets the oldest past its limit", () => {+ noteSendingSession("thread-old", "send-old", "old");+ for (let index = 0; index < 2_000; index++) noteSendingSession("thread-many", `send-${index}`, "pc");+ expect(sendingSession("thread-old", "send-old")).toBeUndefined();+ expect(sendingSession("thread-many", "send-1999")).toBe("pc");+ });+});diff --git a/server/sending-sessions.ts b/server/sending-sessions.tsnew file mode 100644index 0000000000..b38cc5066f--- /dev/null+++ b/server/sending-sessions.ts@@ -0,0 +1,19 @@+// Which signed-in session sent each line, noted at the send route. On a Cloud home the desktop app lends its computer+// with the same session as its window (one cookie jar), so a line from that session was typed on that computer: the+// person's "my computer" is that one. Bound to the thread and the sendId, so no other line can borrow it. In memory on+// purpose: after a restart a line only loses the hint, and the bot asks as before.+const LIMIT = 2_000;+const sessions = new Map<string, string>();+const key = (threadId: string, sendId: string): string => `${threadId}\n${sendId}`;++export function noteSendingSession(threadId: string, sendId: string, session: string): void {+ const at = key(threadId, sendId);+ sessions.delete(at);+ sessions.set(at, session);+ if (sessions.size > LIMIT) sessions.delete(sessions.keys().next().value!);+}++/** The session that sent this line, when the send route noted one. */+export function sendingSession(threadId: string, sendId: string | undefined): string | undefined {+ return sendId === undefined ? undefined : sessions.get(key(threadId, sendId));+}diff --git a/server/shared-computers.test.ts b/server/shared-computers.test.tsindex 78f971f3d6..3acf7b216c 100644--- a/server/shared-computers.test.ts+++ b/server/shared-computers.test.ts@@ -630,3 +630,26 @@ describe("MCP servers a lent computer runs for this server", () => {await closed;});});++describe("the computer the person types on", () => {+ it("is the online computer lent by the session that sent the line, put first; no other session or person sees it", async () => {+ vi.useFakeTimers({ now: Date.now() });+ const dir = mkdtempSync(join(tmpdir(), "omb-typing-on-"));+ const broker = new SharedComputers(() => true, new LentComputers(join(dir, "lent.json")));+ const pc = { ...registration(), name: "WIN-1", platform: "win32" as const };+ const laptop = { ...registration(), name: "UBUNTU-1", platform: "linux" as const };+ broker.register(pc, { session: "pc", person: alice.person }, secret);+ await vi.advanceTimersByTimeAsync(1_000);+ broker.register(laptop, { session: "laptop", person: alice.person }, other);+ const typing = (session?: string) => broker.known(alice.person, session).map(computer => [computer.name, computer.typing === true]);+ expect(typing()).toEqual([["UBUNTU-1", false], ["WIN-1", false]]);+ expect(typing("pc")).toEqual([["WIN-1", true], ["UBUNTU-1", false]]);+ expect(typing("laptop")).toEqual([["UBUNTU-1", true], ["WIN-1", false]]);+ expect(typing("phone")).toEqual([["UBUNTU-1", false], ["WIN-1", false]]);+ expect(broker.known(bob.person, "pc")).toEqual([]);+ await vi.advanceTimersByTimeAsync(40_001);+ expect(typing("pc")).toEqual([["UBUNTU-1", false], ["WIN-1", false]]);+ broker.close();+ rmSync(dir, { recursive: true, force: true });+ });+});diff --git a/server/shared-computers.ts b/server/shared-computers.tsindex 4e56edd61d..b1e75e67c7 100644--- a/server/shared-computers.ts+++ b/server/shared-computers.ts@@ -72,6 +72,8 @@ export type SharedComputerStatus = {export type KnownLentComputer = {id: string; name: string; platform: "darwin" | "win32" | "linux" | null; online: boolean; busy: boolean; lent: boolean;lastSeenAt: number; lastUsedAt: number | null; scopes: { folders: number; terminal: boolean; screen: boolean; internet: boolean; chrome: boolean };+ /** The person typed this turn's line on it: the session that sent the line lends it, online now. */+ typing?: true;};/** The bot an action is for, so the lent computer's menu can name it with its colour. */export type ActingBot = { name: string; color: string };@@ -281,15 +283,20 @@ export class SharedComputers {.map((entry) => ({ id: entry.registration.id, name: entry.registration.name, platform: entry.registration.platform ?? null, session: entry.owner.session, environmentId: entry.registration.environments![0]!, seen: entry.seen })).sort((a, b) => b.seen - a.seen);}- /** Every computer this person lent, now or before, newest first: online, offline since, or no longer lent. */- known(principal: string | null): KnownLentComputer[] {+ /** Every computer this person lent, now or before, newest first: online, offline since, or no longer lent.+ * `sending`: the session that sent this turn's line. The desktop lends its computer with its window's own session, so+ * an online computer lent by that session is the one they type on: marked, and put first. */+ known(principal: string | null, sending?: string): KnownLentComputer[] {if (!principal) return [];- return (this.lent?.list(principal) ?? []).map(record => {+ const typingOn = sending === undefined ? undefined+ : [...this.computers.values()].find(entry => entry.owner.person === principal && entry.owner.session === sending && this.online(entry))?.registration.id;+ const known = (this.lent?.list(principal) ?? []).map((record): KnownLentComputer => {const entry = this.chosen(principal, record.id);- return { id: record.id, name: record.name, platform: record.platform, online: entry ? this.online(entry) : false, busy: (entry?.jobs.size ?? 0) > 0,+ return { ...(record.id === typingOn ? { typing: true as const } : {}), id: record.id, name: record.name, platform: record.platform, online: entry ? this.online(entry) : false, busy: (entry?.jobs.size ?? 0) > 0,lent: record.stoppedAt === null, lastSeenAt: entry ? Math.max(entry.seen, record.lastSeenAt) : record.lastSeenAt, lastUsedAt: record.lastUsedAt,scopes: { folders: record.folders, terminal: record.terminal, screen: record.screen, internet: record.internet === true, chrome: record.chrome === true } };});+ return [...known.filter(computer => computer.typing), ...known.filter(computer => !computer.typing)];}/** For a bot: which known computer is offline and since when, and the sentence to say; nothing while one is online. */away(principal: string | null) {diff --git a/server/system-prompt.test.ts b/server/system-prompt.test.tsindex f6709b9d51..2639dbf71f 100644--- a/server/system-prompt.test.ts+++ b/server/system-prompt.test.ts@@ -422,6 +422,15 @@ describe("cloudHomePrompt", () => {expect(cloudHomePrompt(true, [], known)).toContain("Their computers right now: ASH-MBP (Mac): online; OFFICE-PC (PC): offline since 2026-10-01 08:00 UTC.");expect(cloudHomePrompt(false, [], known)).not.toContain("Their computers right now");});++ it("names the computer the person types on, so their \"my computer\" means that one", () => {+ const both = [{ name: "WIN-1", platform: "win32" as const, online: true, typing: true }, { name: "UBUNTU-1", platform: "linux" as const, online: true }];+ const text = cloudHomePrompt(true, [], both);+ expect(text).toContain("Their computers right now: WIN-1 (PC): online, they are typing on it now; UBUNTU-1 (computer): online.");+ expect(text).toContain("When they say \"my computer\" or \"this computer\", they mean WIN-1.");+ expect(text).toContain("If they ask for something on their PC (WIN-1)");+ expect(cloudHomePrompt(true, [], both.map(({ typing: _typing, ...computer }) => computer))).not.toContain("typing");+ });it("says the bot runs in the cloud, offers what works there, and never asks for a place that cannot exist", () => {for (const tools of [true, false]) {const text = cloudHomePrompt(tools);diff --git a/server/system-prompt.ts b/server/system-prompt.tsindex 0aa49f2791..cff5191ba3 100644--- a/server/system-prompt.ts+++ b/server/system-prompt.ts@@ -197,7 +197,7 @@ export const CLOUD_ENGINES_HERE = " The AIs bots run on (Claude, Codex, Cursor a/** `asks`: the person's own Cloud, whose bots ask them to turn on what their computer doesn't give now (ask_for_computer). */export function cloudHomePrompt(sharedComputerTools: boolean, synced: ReadonlyArray<{ computerName: string; pcPath: string; cloudPath: string }> = [],- lent: ReadonlyArray<{ name: string; platform: "darwin" | "win32" | "linux" | null; online?: boolean; lent?: boolean; lastSeenAt?: number }> = [], asks = false): string {+ lent: ReadonlyArray<{ name: string; platform: "darwin" | "win32" | "linux" | null; online?: boolean; lent?: boolean; lastSeenAt?: number; typing?: boolean }> = [], asks = false): string {const { theirs, device } = theirComputer(lent);const unavailable = asks? ` If it isn't online, or doesn't lend what you need (its apps and screen, its files, running commands), call ask_for_computer with what you want to do and why: it shows them one card with a one-tap Turn on, and you carry on once it's on. Don't explain the fix yourself, and never do it on their cloud computer or in the built-in browser instead unless they ask you to.`