Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
A sign-in the app sees only in a status read ends the engine's signed-out hold
milind-soni00b04147c473
diff --git a/server/harness/registry.test.ts b/server/harness/registry.test.tsindex 872d8f0522..04a2bab429 100644--- a/server/harness/registry.test.ts+++ b/server/harness/registry.test.ts@@ -207,6 +207,30 @@ describe("ProviderRegistry", () => {}});+ it("tells its listeners when a status read finds a signed-out engine signed in, however that sign-in happened, and only then", async () => {+ let authenticated: boolean | undefined = false;+ const fake = makeFakeDriver({ get answer() { return { state: "available" as const, version: "1.0.0", ...(authenticated === undefined ? {} : { authenticated }) }; } });+ const registry = new ProviderRegistry([fake.driver]);+ await registry.load({ a: { driver: "fake" } });+ const heard: string[] = [];+ registry.onSignedIn((instanceId) => heard.push(instanceId));+ const read = async () => {+ registry.forgetSnapshots();+ await registry.describe();+ };+ await read();+ expect(heard).toEqual([]);+ authenticated = true;+ await read();+ expect(heard).toEqual(["a"]);+ await read();+ authenticated = undefined;+ await read();+ authenticated = true;+ await read();+ expect(heard, "signed in all along: nothing new to tell").toEqual(["a"]);+ });+it("describe() reports a snapshot() failure as unavailable rather than throwing", async () => {const fake = makeFakeDriver({ failSnapshot: "provider probe exploded" });const registry = new ProviderRegistry([fake.driver]);diff --git a/server/harness/registry.ts b/server/harness/registry.tsindex f689119b2a..38b33fe287 100644--- a/server/harness/registry.ts+++ b/server/harness/registry.ts@@ -111,6 +111,7 @@ export class ProviderRegistry {/** Engines the start-up read has not probed yet; null outside that read. */private unread: Set<InstanceId> | null = null;private snapshotGeneration = 0;+ private readonly signedInListeners = new Set<(instanceId: InstanceId) => void>();/** Per instance object: settings that reload an engine make a new one, so its status is read afresh. */private readsOf = new WeakMap<ProviderInstance, { snapshot: ProviderSnapshot; at: number; generation: number }>();private driversByKind: Map<string, AnyProviderDriver>;@@ -452,14 +453,24 @@ export class ProviderRegistry {}// Only while this is still the live instance: a reload may have replaced it during the read.if (this.byId.get(instance.instanceId)?.live === instance) {+ const before = this.lastSnapshots.get(instance.instanceId) ?? this.seeds.get(instance.instanceId);this.lastSnapshots.set(instance.instanceId, snapshot);this.unread?.delete(instance.instanceId);this.saveStatus();this.healWrongCli(instance.instanceId, snapshot);+ if (before?.authenticated === false && snapshot.state === "available" && snapshot.authenticated === true) {+ for (const listener of this.signedInListeners) listener(instance.instanceId);+ }}return snapshot;}+ /** `listener` hears of each engine whose status read turns from signed out to signed in, however the sign-in happened:+ * in the app, in the engine's own browser callback, or in a terminal. */+ onSignedIn(listener: (instanceId: InstanceId) => void): void {+ this.signedInListeners.add(listener);+ }+private saveStatus(): void {this.status?.save(this.instances().flatMap(({ instanceId, driverKind }) => {const snapshot = this.lastSnapshots.get(instanceId) ?? this.seeds.get(instanceId);diff --git a/server/index.ts b/server/index.tsindex 2ca4a5bad2..d166167b84 100644--- a/server/index.ts+++ b/server/index.ts@@ -8799,7 +8799,7 @@ async function stopBotForEmergencyApprovalDowngrade(botId: string): Promise<voidconst engineName = (engine: string) => engineLabel(engine, registry.get(engine) ?? undefined);const limitClock = new LimitResetClock({ file: join(DATA_DIR, "limit-holds.json"), accounts: () => planAccountsFromInstances(instanceConfigs(cfg)), onChange: () => routines?.retimeLimitResets(),- waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), holdsFile: join(DATA_DIR, "limit-takeover-holds.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine) => limitClock.blockedUntil(engine), resetAt: (engine) => limitClock.resetAt(engine), enabled: () => quotaSwitchEnabled(), where: CLOUD_HOME ? "on the Cloud" : "on this computer", signedOutNow: (id) => registry.knownSnapshot(id)?.authenticated === false, signedOutNoticed: () => registry.forgetSnapshots(), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => [...(store.bot(botId)?.fallback ?? []), ...(cfg.automaticRecovery?.backup ? [cfg.automaticRecovery.backup] : [])], signedOutChosen: (botId) => { const bot = store.bot(botId); return bot ? startupBackups(bot, cfg.automaticRecovery) : []; }, tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => limitFailovers.record(failover) });+ waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), holdsFile: join(DATA_DIR, "limit-takeover-holds.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine) => limitClock.blockedUntil(engine), resetAt: (engine) => limitClock.resetAt(engine), enabled: () => quotaSwitchEnabled(), where: CLOUD_HOME ? "on the Cloud" : "on this computer", signedOutNow: (id) => registry.knownSnapshot(id)?.authenticated === false, signedOutNoticed: () => registry.forgetSnapshots(), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => [...(store.bot(botId)?.fallback ?? []), ...(cfg.automaticRecovery?.backup ? [cfg.automaticRecovery.backup] : [])], signedOutChosen: (botId) => { const bot = store.bot(botId); return bot ? startupBackups(bot, cfg.automaticRecovery) : []; }, tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => limitFailovers.record(failover) }); registry.onSignedIn((instanceId) => limitTakeover.signedIn(instanceId));const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failovers.json"), blockedUntil: (engine) => limitClock.blockedUntil(engine), signedOut: (engine) => limitTakeover.stillSignedOut(engine), engineName,threadModel: (botId, threadId) => store.projectBotForTask(botId, threadId)?.modelSelection ?? null,note: (threadId, line, text) => store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${line}`, ok: true, ...(text ? { nameCode: text.key, nameParams: text.params } : {}) } }),diff --git a/server/limit-reset.e2e.test.ts b/server/limit-reset.e2e.test.tsindex a7cec84349..e9476d0a3a 100644--- a/server/limit-reset.e2e.test.ts+++ b/server/limit-reset.e2e.test.ts@@ -4,7 +4,7 @@// another sign-in to the same engine is never used. The limit clock hook shortens the minute after a reset to a// second, so each run is watched without waiting.import { spawn, type ChildProcess } from "node:child_process";-import { closeSync, existsSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { join } from "node:path";import { fileURLToPath } from "node:url";import { expect, it } from "vitest";@@ -30,7 +30,7 @@ interface Fixture {restart: () => Promise<void>;}-async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: boolean; codex?: false; signedOut?: boolean }, check: (fixture: Fixture) => Promise<void>) {+async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: boolean; codex?: false; signedOut?: boolean; claudeEnv?: Record<string, string> }, check: (fixture: Fixture) => Promise<void>) {const fixture = await launchVerificationServer({});const { dataDir, url, logPath } = fixture.info;const limitedFile = join(dataDir, "claude-limited.json");@@ -59,7 +59,7 @@ async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: boolconst configPath = join(dataDir, "config.json");const config = JSON.parse(readFileSync(configPath, "utf8"));config.instances.claude.environment = { ...config.instances.claude.environment, FAKE_CLAUDE_LIMITED_FILE: limitedFile, FAKE_CLAUDE_PROMPTS: promptsFile, FAKE_CLAUDE_TOOL_CALLS: "[]",- ...(setup.signedOut ? { FAKE_CLAUDE_MODE: "not-logged-in" } : {}) };+ ...(setup.signedOut ? { FAKE_CLAUDE_MODE: "not-logged-in" } : {}), ...setup.claudeEnv };if (setup.codex !== false) config.instances.codex = { driver: "codex", config: { cli: fileURLToPath(new URL("./testing/fake-codex-app-server.ts", import.meta.url)) } };if (setup.secondClaude) config.instances.claudeWork = { ...config.instances.claude, displayName: "Second Claude sign-in" };if (setup.recovery) config.automaticRecovery = setup.recovery;@@ -343,7 +343,7 @@ it("a signed-out Claude with Automatic recovery on: its turns go to the chosen bconst { task: other } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Another thing" });await control("send", "--bot", bot.id, "--task", other.threadId, "--text", "And the budget");expect((await control("wait", "--bot", bot.id, "--task", other.threadId, "--timeout", "30")).status).toBe("settled");- const next = await messagesOf(api, other.threadId);+ const next = await messagesOf(api, other.threadId); console.log("DEBUG", JSON.stringify(next.map((m) => [m.role, m.kind, m.text?.slice(0, 120), m.tool?.name?.slice(0, 200)])), JSON.stringify(await messagesOf(api, bot.activeTaskId).then((ms) => ms.map((m) => [m.role, m.kind, m.text?.slice(0, 80), m.tool?.name?.slice(0, 200)]))));expect(recoveryLines(next)).toEqual(["recovery: Verification fixture is signed out, so Codex took over."]);expect(next.some((message) => message.tool?.name?.startsWith("notice:")), "said once, not again").toBe(false);expect(await reply(other.threadId)).toBe("done from fake codex");@@ -354,6 +354,47 @@ it("a signed-out Claude with Automatic recovery on: its turns go to the chosen b});}, 180_000);+it("a Claude signed out and in again outside the app: once its status reads signed in, new conversations start on it again", async () => {+ // FAKE_CLAUDE_HOME_FILES: a turn is refused unless the CLI's own sign-in file exists; FAKE_CLAUDE_AUTH=file: `auth status`+ // says signed in while its file exists. Both are written and removed here as a terminal's `claude auth login`/`logout` would.+ await withLimitFixture({ claudeEnv: { FAKE_CLAUDE_HOME_FILES: "1", FAKE_CLAUDE_AUTH: "file" }, recovery: { enabled: true, backup: codex } }, async ({ api, control, dataDir, claudePrompts, evidence }) => {+ const claudeHome = join(dataDir, ".claude");+ const signIn = () => {+ mkdirSync(claudeHome, { recursive: true });+ writeFileSync(join(claudeHome, ".credentials.json"), JSON.stringify({ claudeAiOauth: { accessToken: "fixture-token-not-a-credential" } }));+ writeFileSync(join(claudeHome, "fake-auth.json"), JSON.stringify({ email: "[email protected]" }));+ };+ const signOut = () => {+ for (const file of [".credentials.json", "fake-auth.json"]) rmSync(join(claudeHome, file), { force: true });+ };+ const signedIn = async () => ((await api("GET", "/api/instances?fresh=1")).instances as any[]).find((instance) => instance.instanceId === "claude")?.snapshot.authenticated;+ const reply = async (id: string) => (await messagesOf(api, id)).findLast((message) => message.role === "bot" && message.kind === "text")?.text;++ signIn();+ await expect.poll(signedIn, { timeout: 20_000 }).toBe(true);+ const { bot } = await control("new-bot", "--name", "Kai");+ expect(bot.modelSelection.instanceId).toBe("claude");+ signOut();+ await expect.poll(signedIn, { timeout: 20_000 }).toBe(false);+ await control("send", "--bot", bot.id, "--task", bot.activeTaskId, "--text", "Draft the launch plan");+ expect((await control("wait", "--bot", bot.id, "--task", bot.activeTaskId, "--timeout", "30")).status).toBe("settled");+ expect(recoveryLines(await messagesOf(api, bot.activeTaskId))).toEqual(["recovery: Verification fixture is signed out, so Codex took over."]);+ expect(await reply(bot.activeTaskId)).toBe("done from fake codex");+ const asked = claudePrompts().length;++ signIn();+ await expect.poll(signedIn, { timeout: 20_000 }).toBe(true);+ const { task: other } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "After signing in" });+ await control("send", "--bot", bot.id, "--task", other.threadId, "--text", "And the budget");+ expect((await control("wait", "--bot", bot.id, "--task", other.threadId, "--timeout", "30")).status).toBe("settled");+ const next = await messagesOf(api, other.threadId);+ expect(recoveryLines(next), "no other AI took it").toEqual([]);+ expect(claudePrompts(), "the signed-in Claude answered").toHaveLength(asked + 1);+ expect(await reply(other.threadId)).not.toBe("done from fake codex");+ evidence.push({ next });+ });+}, 180_000);+it.each([["as its turns end", false],["as Automatic recovery stops its turns before they start, with no other AI to take them", true],