Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Merge origin/main (trains X1–X4) into train/nov20b-y1
milind-sonid45a798c4d33
diff --cc server/host/limit-takeover.tsindex d232433d7a,b5abe90873..ca993599f1--- a/server/host/limit-takeover.ts+++ b/server/host/limit-takeover.ts@@@ -166,66 -162,39 +168,68 @@@ export function createLimitTakeover(depnotices.endedEverywhere(signedOutKey(instanceId));};- const usable = (engines: TakeoverEngine[], current: TakeoverEngine, selection: ModelSelection, scope: TakeoverScope, approval?: ApprovalMode): boolean => {+ const notReady = (engine: TakeoverEngine): string => engine.enabled === false ? "switched off"+ : engine.snapshot.state !== "available" ? engine.snapshot.reason ?? "unavailable"+ : engine.snapshot.authenticated === false ? "signed out" : deps.context.refusal?.(engine) ?? "not ready";++ const skipped = (engines: TakeoverEngine[], current: TakeoverEngine, selection: ModelSelection, scope: TakeoverScope, approval?: ApprovalMode): Omit<SkippedBackup, "selection"> | null => {const engine = engines.find((candidate) => candidate.instanceId === selection.instanceId);- if (!engine || !readyToRun(engine, deps.context) || deps.blockedUntil(engine.instanceId, selection.model) !== null || modelHeld(selection) !== null) return false;+ if (!engine) return { why: "not-configured" };+ if (!readyToRun(engine, deps.context)) return { why: "not-ready", detail: notReady(engine) };+ if (deps.blockedUntil(engine.instanceId, selection.model) !== null) return { why: "limited" };+ if (modelHeld(selection) !== null) return { why: "model-held" };if (engine.instanceId !== current.instanceId) {- if (signedOutHeld(engine.instanceId)) return false;+ if (signedOutHeld(engine.instanceId)) return { why: "signed-out" };// Another sign-in to the same plan never carries a limit (that rotates accounts); it may stand in for one signed out.- if (scope !== "signed-out" && !limitBackupAllowed(current, engine, deps.configs()[engine.instanceId])) return false;+ if (scope !== "signed-out" && !limitBackupAllowed(current, engine, deps.configs()[engine.instanceId])) return { why: "same-plan" };// The same rule as switching by hand: a level the other AI has no such mode for needs the person first.- if (approval && modelSwitchNeedsAsk(approval, current.driverKind, engine.driverKind)) return false;+ if (approval && modelSwitchNeedsAsk(approval, current.driverKind, engine.driverKind)) return { why: "needs-approval" };}- if (recoveryCapabilityError(current, engine)) return false;- return engine.models.default === selection.model || engine.models.options.some((model) => model.id === selection.model);+ const missing = recoveryCapabilityError(current, engine);+ if (missing) return { why: "missing-capability", detail: missing };+ return engine.models.default === selection.model || engine.models.options.some((model) => model.id === selection.model) ? null : { why: "unknown-model" };};- /** The AIs that may carry on while `from` is limited or signed out, best first: for one model's limit the same AI's own- * default model, then the backups the person chose. No other AI is picked for them: with none of those usable the bot- * waits for the reset or a sign-in. `approval`: the thread's level, when known. `chosen`: the backups to weigh instead of- * the bot's and the installation's. `skipped`: each backup left out, and why. */+ /** The AIs that may carry on while `from` is limited or signed out, best first: for one model's limit, when the person chose+ * any backup, the same AI's own default model first, then the backups the person chose. A bot with no backup chosen gets- * none, and no other AI is picked for it: with none usable the bot waits for the reset or a sign-in. `approval`: the thread's level, when known. */- function backups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode): ModelSelection[] {++ * none, and no other AI is picked for it: with none usable the bot waits for the reset or a sign-in. `approval`: the thread's++ * level, when known. `chosen`: the backups to weigh instead of the bot's and the installation's. `skipped`: each backup++ * left out, and why. */+ function weighBackups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode, chosen?: readonly ModelSelection[]): { backups: ModelSelection[]; skipped: SkippedBackup[] } {const engines = deps.engines();const current = engines.find((engine) => engine.instanceId === from.instanceId);- if (!current) return [];+ if (!current) return { backups: [], skipped: [] };const out: ModelSelection[] = [];+ const left: SkippedBackup[] = [];const add = (selection: ModelSelection) => {- if (selection.instanceId === from.instanceId && (scope === "engine" || scope === "signed-out" || selection.model === from.model)) return;- if (out.some((known) => known.instanceId === selection.instanceId && known.model === selection.model)) return;- if (usable(engines, current, selection, scope, approval)) out.push({ instanceId: selection.instanceId, model: selection.model });+ const pick = { instanceId: selection.instanceId, model: selection.model };+ if (pick.instanceId === from.instanceId && pick.model === from.model) return;+ if ([...out, ...left.map((one) => one.selection)].some((known) => known.instanceId === pick.instanceId && known.model === pick.model)) return;+ if (pick.instanceId === from.instanceId && (scope === "engine" || scope === "signed-out")) {+ left.push({ selection: pick, why: scope === "signed-out" ? "signed-out" : "limited" });+ return;+ }+ const why = skipped(engines, current, pick, scope, approval);+ if (why) left.push({ selection: pick, ...why });+ else out.push(pick);};- if (scope === "model" || scope === "credits") add({ instanceId: current.instanceId, model: current.models.default });- for (const selection of chosen ?? (scope === "signed-out" ? deps.signedOutChosen?.(botId) ?? deps.chosen(botId) : deps.chosen(botId))) add(selection);- const chosen = deps.chosen(botId);- if ((scope === "model" || scope === "credits") && chosen.length) add({ instanceId: current.instanceId, model: current.models.default });- for (const selection of scope === "signed-out" ? deps.signedOutChosen?.(botId) ?? deps.chosen(botId) : chosen) add(selection);- return out;++ const picked = chosen ?? deps.chosen(botId);++ if ((scope === "model" || scope === "credits") && picked.length) add({ instanceId: current.instanceId, model: current.models.default });++ for (const selection of chosen ?? (scope === "signed-out" ? deps.signedOutChosen?.(botId) ?? picked : picked)) add(selection);+ return { backups: out, skipped: left };}+ function backups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode, chosen?: readonly ModelSelection[]): ModelSelection[] {+ return weighBackups(botId, from, scope, approval, chosen).backups;+ }++ const passedOver = (bot: Bot, from: ModelSelection, scope: TakeoverScope, left: readonly SkippedBackup[]): void => {+ for (const { selection, why, detail } of left) {+ // A status reason or a refusal may carry an engine's address with its credential in it.+ (deps.log ?? console.warn)(redactSecretsInText(`limit takeover: ${bot.name} (${bot.id}) on ${from.instanceId}/${from.model} (${scope}) passed over backup ${selection.instanceId}/${selection.model}: ${why}${detail ? ` (${detail})` : ""}`));+ }+ };+const label = (selection: ModelSelection, from: ModelSelection) => (selection.instanceId === from.instanceId? `${deps.engineName(selection.instanceId)} ${selection.model}` : deps.engineName(selection.instanceId));/** What refused, as the person knows it: the AI, or for one model's own limit that AI's model. */diff --cc server/index.tsindex b9a6388566,67c47ab029..2785c558d7--- a/server/index.ts+++ b/server/index.ts@@@ -210,8 -210,8 +210,8 @@@ importnewId,} from "./contracts.ts";import { RETRY_MAX_ATTEMPTS } from "./drivers/retry.ts";- import { recoveryCapabilityError, startupBackups } from "./automatic-recovery.ts"; import { outOfProcesses } from "./process-shortage.ts";+ import { chosenBackups, recoveryCapabilityError, startupBackups } from "./automatic-recovery.ts"; import { outOfProcesses } from "./process-shortage.ts";-import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { quotaSwitchEnabled } from "./quota-switch.ts"; import { createPeerLimitResend } from "./host/peer-limit-resend.ts";+import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { quotaSwitchEnabled } from "./quota-switch.ts"; import { createPeerLimitResend } from "./host/peer-limit-resend.ts"; import { createRoomLimitTakeover } from "./host/room-limit-takeover.ts";import { decodeGeneratedImage } from "./generated-image.ts";import { createMcpServersHost } from "./host/mcp-servers-host.ts"; import { createMcpKeys } from "./vault/mcp-keys.ts"; import { createLimitTakeover, signedOutStop } from "./host/limit-takeover.ts";import {@@@ -10204,8 -10206,8 +10204,8 @@@ async function runClaimedGroupMemberTurconst roomToolScope = toolScopeForTurn(readyBot.id), roomUserMcp = claudeUserMcpEnabled(cfg) && !managedPolicy.restrictsMcp();const roomSession = roomSessions.dispatch({threadId, botId: readyBot.id, claimId: internalGeneration, instance, guestConfined: roomGuestConfined, reset: Boolean(roomReset), hooks: Boolean(integrations.hooks),- context: () => ({ ...roomMemberContexts.forThread(threadId)?.[readyBot.id], compactAt: nativeCompactTokens(instance) }),- context: () => ({ ...roomMemberContexts.forThread(threadId)?.[readyBot.id], compactAt: nativeCompactTokens(instance, readyBot.modelSelection.model) }),- config: [roomSystem.stable, cwd, readyBot.modelSelection, turnApprovalMode, roomToolScope, roomUserMcp, integrations],++ context: () => ({ ...roomMemberContexts.forThread(threadId)?.[readyBot.id], compactAt: nativeCompactTokens(instance, roomSelection.model) }),+ config: [roomSystem.stable, cwd, roomSelection, turnApprovalMode, roomToolScope, roomUserMcp, integrations],window: roomWindow, tail: roomTail, wrap: (body) => withTurnClock(clock, withRecalled(roomRecalled, roomPick + attachmentsForBox(body, cwd) + roomShareNote.text + devsReports.note(threadId, Boolean(integrations.agents)))),});guardTurnDispatch(roomShareNote.after(instance.adapter.sendTurn({diff --cc server/limit-resets.tsindex c2b7eec634,2e2e3aa661..8406d821ce--- a/server/limit-resets.ts+++ b/server/limit-resets.ts@@@ -41,8 -38,8 +42,8 @@@ export function engineLimitFromUsage(roconst full = windows.filter((line) => line.used >= 100);if (full.length) {const latest = full.reduce((left, right) => (right.resetsAt ?? 0) > (left.resetsAt ?? 0) ? right : left);- // Claude goes on past a full window on its paid extra usage while that has room; its own refusal still holds it.- return { ...base, window: latest.window, usedPercent: 100, resetsAt: full.some((line) => line.resetsAt === null) ? null : latest.resetsAt, blocked: meterHoldsEngine(row.driver) && !claudeHasExtraUsageRoom(row) };- // A full window is the meter only: the engine's own refusal still holds it.- return { ...base, window: latest.window, usedPercent: 100, resetsAt: full.some((line) => line.resetsAt === null) ? null : latest.resetsAt, blocked: !claudeHasExtraUsageRoom(row) && !codexHasCreditRoom(row) };++ // A full window is the meter only: the engine's own refusal still holds it. A shown-only meter never holds the engine.++ return { ...base, window: latest.window, usedPercent: 100, resetsAt: full.some((line) => line.resetsAt === null) ? null : latest.resetsAt, blocked: meterHoldsEngine(row.driver) && !claudeHasExtraUsageRoom(row) && !codexHasCreditRoom(row) };}const fullest = [...windows].sort((left, right) => right.used - left.used || (left.resetsAt ?? Infinity) - (right.resetsAt ?? Infinity))[0]!;return { ...base, window: fullest.window, usedPercent: fullest.used, resetsAt: fullest.resetsAt, blocked: false };diff --cc server/plan-usage.tsindex b828cf433c,fd6aa67147..6aa63e9448--- a/server/plan-usage.ts+++ b/server/plan-usage.ts@@@ -7,7 -7,8 +7,8 @@@ import { join } from "node:path"import type { InstanceConfigMap } from "./contracts.ts";import { resolveClaudeConfigDir } from "./drivers/claude.ts";import { codexHome } from "./drivers/codex-identity.ts";+ import { codexHasCredits } from "./codex-credits.ts";-import { antigravityPlanUsage } from "./drivers/antigravity-usage-limits.ts";+import { antigravityPlanUsage, antigravityProxied } from "./drivers/antigravity-usage-limits.ts";import { harnessHome, sealedFixture } from "./env-path.ts";export type PlanDriver = "claude" | "codex" | "grok" | "opencode" | "antigravity";