Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Mark endpoint models custom, hold the token to its address
fanxing11dde1f52538dc
diff --git a/server/claude-endpoints.test.ts b/server/claude-endpoints.test.tsindex f83294a8ce..e6c2792c22 100644--- a/server/claude-endpoints.test.ts+++ b/server/claude-endpoints.test.ts@@ -93,11 +93,10 @@ describe("custom Claude endpoint", () => {const updated = updateClaudeEndpoint({ instances }, instanceId, {model: "deepseek-reasoner",opusModel: "",- baseUrl: "https://api.example.test/anthropic",});const entry = updated.instances[instanceId];expect(entry.environment).toMatchObject({- ANTHROPIC_BASE_URL: "https://api.example.test/anthropic",+ ANTHROPIC_BASE_URL: "https://api.deepseek.com/anthropic",ANTHROPIC_AUTH_TOKEN: "sk-fixture-secret",ANTHROPIC_MODEL: "deepseek-reasoner",});@@ -109,6 +108,20 @@ describe("custom Claude endpoint", () => {expect(updated.instances.claude).toEqual(instances.claude);});+ it("requires the token again when the address changes", () => {+ const { instanceId, instances } = newClaudeEndpoint(cfg(), BASE);+ expect(() => updateClaudeEndpoint({ instances }, instanceId, { baseUrl: "https://api.example.test/anthropic" }))+ .toThrow(/token again for the new address/);+ const moved = updateClaudeEndpoint({ instances }, instanceId, { baseUrl: "https://api.example.test/anthropic", token: "sk-moved" });+ expect(moved.instances[instanceId].environment).toMatchObject({+ ANTHROPIC_BASE_URL: "https://api.example.test/anthropic",+ ANTHROPIC_AUTH_TOKEN: "sk-moved",+ });+ // The saved address, however written, still needs no token.+ expect(updateClaudeEndpoint({ instances }, instanceId, { baseUrl: BASE.baseUrl }).instances[instanceId].environment)+ .toMatchObject({ ANTHROPIC_AUTH_TOKEN: "sk-fixture-secret" });+ });+it("rejects a non-endpoint Claude instance, an unknown id and an endpoint with no token", () => {const { instances } = newClaudeEndpoint(cfg(), BASE);expect(() => updateClaudeEndpoint({ instances }, "claude", { model: "deepseek-chat" })).toThrow(/not a custom endpoint/);@@ -158,7 +171,7 @@ describe("Claude endpoint catalog", () => {try {expect(instance.models).toEqual({default: "deepseek-chat",- options: [{ id: "deepseek-chat", label: "deepseek-chat" }, { id: "deepseek-reasoner", label: "deepseek-reasoner" }],+ options: [{ id: "deepseek-chat", label: "deepseek-chat", custom: true }, { id: "deepseek-reasoner", label: "deepseek-reasoner", custom: true }],});} finally {await instance.dispose();diff --git a/server/claude-endpoints.ts b/server/claude-endpoints.tsindex 43a7ffc7e7..ee15d787e8 100644--- a/server/claude-endpoints.ts+++ b/server/claude-endpoints.ts@@ -5,28 +5,18 @@ import { randomUUID } from "node:crypto";import { join } from "node:path";import { z } from "zod";+import type { ClaudeEndpointInfo } from "../shared/claude-endpoint.ts";import { assertSeparateClaudeAccount } from "./claude-accounts.ts";import { DATA_DIR, persistableInstanceConfigs, type AppConfig } from "./config.ts";import type { InstanceConfig, InstanceConfigMap } from "./contracts.ts";import { CLAUDE_MODEL_ID } from "./drivers/claude-model-extras.ts";+import { endpointBaseUrl } from "./openai-compat-endpoints.ts";const displayName = z.string().trim().min(1).max(80).refine((value) => !/\p{Cc}/u.test(value), "Name cannot contain control characters");const model = z.string().trim().max(160).regex(CLAUDE_MODEL_ID, "Use the model id the endpoint serves.");const optionalModel = z.union([model, z.literal("")]);const token = z.string().trim().min(1).max(4096).refine((value) => !/[\p{Cc}\p{Cf}]/u.test(value), "Token cannot contain control characters");-const baseUrl = z.string().trim().max(2048).refine((value) => endpointUrl(value) !== null, "Enter an http(s) base URL.");--/** A normalized endpoint address: http(s), no credentials, no trailing slash; null when unusable. */-function endpointUrl(value: string): string | null {- try {- const url = new URL(value);- if (url.protocol !== "http:" && url.protocol !== "https:") return null;- if (url.username || url.password) return null;- return value.replace(/\/+$/u, "");- } catch {- return null;- }-}+const baseUrl = z.string().trim().max(2048).refine((value) => endpointBaseUrl(value) !== null, "Enter an http(s) base URL.");export const claudeEndpointSchema = z.object({displayName,@@ -41,7 +31,7 @@ export const claudeEndpointSchema = z.object({export const claudeEndpointUpdateSchema = z.object({displayName: displayName.optional(),- /** An empty token keeps the saved one. */+ /** Omitted keeps the saved token, unless the address changes. */token: token.optional(),baseUrl: baseUrl.optional(),model: model.optional(),@@ -70,15 +60,7 @@ export function isClaudeEndpoint(entry: InstanceConfig | undefined): boolean {return entry?.driver === "claudeAgent" && Array.isArray(rawConfig(entry).endpointModels);}-export interface ClaudeEndpointInfo {- baseUrl: string;- models: string[];- tokenSaved: boolean;- opusModel: string;- sonnetModel: string;- haikuModel: string;- smallFastModel: string;-}+export type { ClaudeEndpointInfo };/** What the settings UI may know about an endpoint: where it points and which models, never the token. */export function claudeEndpointInfo(entry: InstanceConfig): ClaudeEndpointInfo {@@ -107,7 +89,7 @@ export function withClaudeEndpointInfo(described: unknown, configs: InstanceConf}function endpointEnvironment(url: string, secret: string, fields: EndpointFields): Record<string, string> {- const address = endpointUrl(url);+ const address = endpointBaseUrl(url);if (!address) throw Object.assign(new Error("Enter an http(s) base URL."), { status: 400 });const environment: Record<string, string> = {ANTHROPIC_BASE_URL: address,@@ -168,10 +150,11 @@ export function updateClaudeEndpoint(cfg: AppConfig, instanceId: string, body: Eif (!isClaudeEndpoint(entry)) throw Object.assign(new Error("This Claude instance is not a custom endpoint."), { status: 400 });const saved = claudeEndpointInfo(entry);if (!saved.baseUrl || !saved.models.length) throw Object.assign(new Error("This endpoint is missing its address or model. Remove it and add it again."), { status: 409 });- const fields: EndpointFields = {- baseUrl: body.baseUrl ?? saved.baseUrl,- model: body.model ?? saved.models[0],- };+ const address = body.baseUrl === undefined ? saved.baseUrl : endpointBaseUrl(body.baseUrl);+ if (!address) throw Object.assign(new Error("Enter an http(s) base URL."), { status: 400 });+ // A saved token belongs to the address it was entered for.+ if (body.token === undefined && address !== endpointBaseUrl(saved.baseUrl)) throw Object.assign(new Error("Enter the endpoint's token again for the new address."), { status: 400 });+ const fields: EndpointFields = { baseUrl: address, model: body.model ?? saved.models[0] };if (body.displayName !== undefined) fields.displayName = body.displayName;for (const [field, key] of TIERS) {const value = body[field] !== undefined ? body[field] : entry.environment?.[key];@@ -182,7 +165,7 @@ export function updateClaudeEndpoint(cfg: AppConfig, instanceId: string, body: Einstances[instanceId] = {...entry,...(fields.displayName ? { displayName: fields.displayName } : {}),- environment: endpointEnvironment(fields.baseUrl!, secret, fields),+ environment: endpointEnvironment(address, secret, fields),config: { ...rawConfig(entry), endpointModels: endpointModels(fields) },};return { instances };diff --git a/server/drivers/claude-model-extras.ts b/server/drivers/claude-model-extras.tsindex 97bebef6d4..90dedb48e4 100644--- a/server/drivers/claude-model-extras.ts+++ b/server/drivers/claude-model-extras.ts@@ -1,3 +1,5 @@+import type { ModelCatalog } from "../contracts.ts";+// Claude Code's `[1m]` suffix selects a model's 1M-token context.export const CLAUDE_MODEL_ID = /^[a-z0-9][a-z0-9._:/-]*(?:\[1m\])?$/i;const OFFICIAL_CLAUDE_ID = /^claude-[a-z0-9.-]+$/;@@ -50,3 +52,22 @@ export function claudeModelExtras(settings: Record<string, unknown>, env: Record}return { extras, envModel };}++export const STATIC_CLAUDE_MODELS: ModelCatalog = {+ default: "claude-sonnet-5",+ options: [+ { id: "claude-fable-5-1", label: "Claude Fable 5.1" },+ { id: "claude-fable-5", label: "Claude Fable 5" },+ { id: "claude-opus-5-5", label: "Claude Opus 5.5", contextWindow: 1_000_000 },+ { id: "claude-opus-5", label: "Claude Opus 5" },+ { id: "claude-sonnet-5-5", label: "Claude Sonnet 5.5", contextWindow: 1_000_000 },+ { id: "claude-sonnet-5", label: "Claude Sonnet 5" },+ { id: "claude-haiku-5-5", label: "Claude Haiku 5.5", contextWindow: 1_000_000 },+ { id: "claude-haiku-4-5", label: "Claude Haiku 4.5" },+ ],+};++/** An endpoint serves only its own models, each flagged `custom` so a `custom` instance's picker lists it. */+export function endpointModelCatalog(models: string[] | undefined): ModelCatalog | null {+ return models ? { default: models[0], options: models.map((id) => ({ id, label: id, custom: true })) } : null;+}diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex e4bc5ea682..fdcf373b40 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -16,7 +16,7 @@ import { projectMcpServers } from "./claude-project-mcp.ts";import { botSettingsFor, withBotSettings } from "./claude-bot-settings.ts";import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";import { claudeAuthFailure, claudeAuthRecovery } from "./claude-auth-recovery.ts";-import { CLAUDE_MODEL_ID, claudeModelExtras } from "./claude-model-extras.ts";+import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS, claudeModelExtras, endpointModelCatalog } from "./claude-model-extras.ts";import { claudeToolSearchSetting } from "./claude-tool-search.ts";import { claudeElicitations } from "./claude-elicitation.ts";import { readCostHistory, recordCostState } from "./claude-cost-history.ts";@@ -25,7 +25,6 @@ import { ClaudeLoginController } from "./claude-login-auth.ts";import type {DriverCreateInput,- ModelCatalog,ProviderDriver,ProviderInstance,ProviderSnapshot,@@ -275,38 +274,22 @@ export interface ClaudeConfig {requireApiKey?: boolean;}-export const STATIC_CLAUDE_MODELS: ModelCatalog = {- default: "claude-sonnet-5",- options: [- { id: "claude-fable-5-1", label: "Claude Fable 5.1" },- { id: "claude-fable-5", label: "Claude Fable 5" },- { id: "claude-opus-5-5", label: "Claude Opus 5.5", contextWindow: 1_000_000 },- { id: "claude-opus-5", label: "Claude Opus 5" },- { id: "claude-sonnet-5-5", label: "Claude Sonnet 5.5", contextWindow: 1_000_000 },- { id: "claude-sonnet-5", label: "Claude Sonnet 5" },- { id: "claude-haiku-5-5", label: "Claude Haiku 5.5", contextWindow: 1_000_000 },- { id: "claude-haiku-4-5", label: "Claude Haiku 4.5" },- ],-};+export { STATIC_CLAUDE_MODELS };/** Maps an API slug a local host serves to `host::model`, so the turn injects instead of asking* for /login. */async function resolveClaudeTurnModel(model: string | null | undefined,env: Record<string, string | undefined>,+ endpointModels?: string[],): Promise<string | null | undefined> {+ if (endpointModels) return model && endpointModels.includes(model) ? model : endpointModels[0];if (!model || decodeInjectId(model) || STATIC_CLAUDE_MODELS.options.some((option) => option.id === model)) {return model;}return resolveInjectId(model, await probeLocalInjects(env)) ?? model;}-/** A custom endpoint serves only its own models: a saved model it does not list runs on its main one. */-function endpointTurnModel(model: string | null | undefined, endpointModels: string[] | undefined): string | null | undefined {- if (!endpointModels) return model;- return model && endpointModels.includes(model) ? model : endpointModels[0];-}-/** Extra ids from ~/.claude/settings.json's extraModels. Its `model` is Claude Code's last-used* slug, not a catalog entry. */export function readClaudeModelCatalog(env: Record<string, string | undefined> = process.env) {@@ -796,8 +779,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {console.error(`claude (${instanceId}): OMB_CLAUDE_INHERIT_USER_CONFIG=1 — bots inherit this machine's Claude Code MCP servers, skills, hooks and CLAUDE.md on every turn; remove it unless a bot needs a user-scope server`);}let models = config.managedModels ? { default: config.managedModels[0], options: config.managedModels.map(id => ({ id, label: id })) }- : config.endpointModels ? { default: config.endpointModels[0], options: config.endpointModels.map(id => ({ id, label: id })) }- : STATIC_CLAUDE_MODELS;+ : endpointModelCatalog(config.endpointModels) ?? STATIC_CLAUDE_MODELS;const orgBlocks = createOrgModelBlocks(() => engineHomes.everyHome(catalogEnv), (blocked) => { models = withOrgBlocks(models, blocked); });const refreshModels = async () => {if (config.managed || config.endpointModels) return;@@ -1063,9 +1045,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {if (cliVersionChecked && claudeCliSupports(cliVersion, "--system-prompt-snapshot")) {args.push("--system-prompt-snapshot", "off");}- const turnModel = config.managed ? turn.model- : config.endpointModels ? endpointTurnModel(turn.model, config.endpointModels)- : await resolveClaudeTurnModel(turn.model, turnEnvironment);+ const turnModel = config.managed ? turn.model : await resolveClaudeTurnModel(turn.model, turnEnvironment, config.endpointModels);const injected = config.managed || config.endpointModels ? { model: turnModel ?? null, injected: false } : applyClaudeInject({ ...turnEnvironment }, turnModel);if (injected.model) args.push("--model", injected.model);if (turn.effort) args.push("--effort", turn.effort);diff --git a/shared/claude-endpoint.ts b/shared/claude-endpoint.tsnew file mode 100644index 0000000000..95215c14fa--- /dev/null+++ b/shared/claude-endpoint.ts@@ -0,0 +1,16 @@+/** A Claude custom endpoint as the engine list shows it: where it points and what it serves, never the token. */+export interface ClaudeEndpointInfo {+ baseUrl: string;+ models: string[];+ tokenSaved: boolean;+ opusModel: string;+ sonnetModel: string;+ haikuModel: string;+ smallFastModel: string;+}++/** The instance fields only a custom endpoint has. */+export interface InstanceEndpointInfo {+ claudeEndpoint?: ClaudeEndpointInfo;+ url?: string;+}diff --git a/src/lib/simple-model-menu.test.ts b/src/lib/simple-model-menu.test.tsindex 1465a94faa..07e3783561 100644--- a/src/lib/simple-model-menu.test.ts+++ b/src/lib/simple-model-menu.test.ts@@ -244,3 +244,15 @@ describe("a model the organization turned off", () => {expect(menuOn("sonnet-5").current?.blocked).toBeUndefined();});});++describe("custom Claude endpoint", () => {+ // The driver marks every endpoint catalog option `custom`; the picker keeps exactly those.+ const endpoint = claude({ access: "custom" }, [+ { id: "deepseek-chat", label: "deepseek-chat", custom: true },+ { id: "deepseek-reasoner", label: "deepseek-reasoner", custom: true },+ ]);++ it("lists the endpoint's own models and none of Claude's", () => {+ expect(rows(menu([endpoint]), 0)).toEqual(["deepseek-chat", "deepseek-reasoner"]);+ });+});diff --git a/src/state/store.tsx b/src/state/store.tsxindex a7d13a17bd..fe496fc5e4 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -11,7 +11,7 @@ import {type ReactNode,} from "react";import { flushSync } from "react-dom";-import type { BotMovedTo, BotVisibility, CardAnswerer, CloudBackend, ConnectorToolGrant, EffortLevel, InstalledPackageMetadata, LiveCallState, ServerFrame, GroupThreadUsage, SteerQueueReason, WireBot, WireGroup, WireTask, OptionCardData as WireOptionCard } from "../../shared/wire";+import type { BotMovedTo, BotVisibility, CardAnswerer, CloudBackend, ConnectorToolGrant, EffortLevel, InstalledPackageMetadata, LiveCallState, ServerFrame, GroupThreadUsage, SteerQueueReason, WireBot, WireGroup, WireTask, OptionCardData as WireOptionCard } from "../../shared/wire"; import type { InstanceEndpointInfo } from "../../shared/claude-endpoint";import { movesThreadToTop } from "../../shared/wire"; import type { DefaultBotFields } from "../../shared/default-bot";import { reorderStable } from "../../shared/bot-order";import { withOneChief } from "../../shared/bot-owner";@@ -454,7 +454,7 @@ export function configStatusFromFrame(frame: ConfigStatusFrame): ConfigStatus {export type { EngineInstall } from "./engine-install";-export interface InstanceInfo {+export interface InstanceInfo extends InstanceEndpointInfo {instanceId: string;driverKind: string;displayName: string;@@ -504,12 +504,6 @@ export interface InstanceInfo {cliDefault?: string;cliCandidates?: string[];claudeAccount?: { configDir: string; signInCommand: string; signInShell: "powershell" | "sh"; isDefault: boolean };- /** Where a Claude custom endpoint points and what it serves; its token stays on the server. */- claudeEndpoint?: {- baseUrl: string; models: string[]; tokenSaved: boolean;- opusModel: string; sonnetModel: string; haikuModel: string; smallFastModel: string;- };- url?: string;freeUpSpace?: boolean; replyWaitMinutes?: number;}