Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Connect native Claude and Codex agents with API keys (typed model, HTTPS-only discovery) (#4887)

Milind Soni63712496df99
diff --git a/apps/docs/content/docs/providers/model-providers.mdx b/apps/docs/content/docs/providers/model-providers.mdx
index 2ed20f5322..990ff39027 100644
--- a/apps/docs/content/docs/providers/model-providers.mdx
+++ b/apps/docs/content/docs/providers/model-providers.mdx
@@ -15,7 +15,7 @@ differences with OpenCode 2.x.
| Fireworks AI | Yes | Yes | Custom endpoint, or Claude Code's own settings | Not yet |
| DeepSeek | Yes | Yes | Custom endpoint, or Claude Code's own settings | Not yet |
| Cline | Yes | Yes | No | No |
-| Your own OpenAI-compatible address | Yes, in OpenCode's config file | Yes | No | Not yet |
+| Your own OpenAI-compatible address | Yes, in OpenCode's config file | Yes | No | Direct API endpoint, if it supports Responses |
| Your own Anthropic-compatible address | Not tested | No | Custom endpoint, or Claude Code's own settings | No |
"Chat engine" is OpenMausBot's built-in engine for OpenAI-compatible services.
@@ -161,14 +161,17 @@ To run Claude bots on DeepSeek, GLM or another host that speaks Claude
Code's API, add a **custom endpoint** in Settings → Engines, in the Claude
card:
-- **Add endpoint** takes a name, the endpoint's base URL, its token and the
- model id the endpoint serves. Model mappings for Opus, Sonnet and Haiku
- are optional.
+- **Add endpoint** takes a name, the host's base URL, its API key and,
+ optionally, a model. Leave **Model** empty and OpenMausBot reads the host's
+ model list at `/v1/models`; type the model id (such as `deepseek-chat`)
+ when the host doesn't list its models.
- Each endpoint is its own engine with its own directory, so a bot chooses
it like any other AI. It never reads or writes this computer's
`~/.claude`, and the Claude Code on this computer keeps its own sign-in.
-- Its bots run the model the endpoint serves. A bot that still has a Claude
- model selected runs the endpoint's main model instead.
+- Each bot can choose a different model from the endpoint's catalog.
+- Another gateway must support streaming Messages (`POST /v1/messages`) with
+ tool use. Enter its root URL without `/v1/messages`, such as
+ `https://gateway.example.com`.
- The token is saved in OpenMausBot's own `config.json` and sent only to the
base URL you enter. Removing an endpoint removes only that entry.
@@ -197,7 +200,44 @@ DeepSeek, and your Claude bots follow it:
### Codex
-Not yet. Codex bots use your ChatGPT sign-in, or your organisation's models.
+Codex bots can also run on an API key instead of a ChatGPT sign-in:
+
+1. Open **Settings → Engines** and expand the Codex/ChatGPT card.
+2. Under **Codex direct API**, choose **Add endpoint**.
+3. Leave the base URL empty for OpenAI, or enter another gateway's URL, such
+ as `https://gateway.example.com/v1`.
+4. Enter a name and API key. **Model** is optional; then save.
+5. Choose the new engine and a model in a bot's settings.
+
+- Usage is billed by the provider behind the URL. Saving an endpoint doesn't
+ start a sign-in or replace an existing account.
+- Each endpoint has its own Codex home in OpenMausBot's data directory. The
+ key is saved in `config.json` and is never shown in the app or passed in
+ command arguments. Changing the URL asks for the key again.
+- A gateway must support streaming Responses (`POST /v1/responses`) with tool
+ calls. A gateway that only offers Chat Completions works with the chat
+ engine instead.
+- Each bot chooses its model. OpenAI uses the standard catalog; another
+ gateway's list is read from `/models` under its base URL, unless you typed
+ a model.
+- Remove an endpoint after moving its bots and the default model off it.
+
+### When an endpoint won't save
+
+Saving a custom gateway without a model reads its model list and says whether
+the network, the API key, the HTTP response or an empty model list failed.
+Saving with a typed model, or with the official Anthropic or OpenAI URL,
+doesn't check the key; a wrong key shows up on the bot's first turn.
+**Refresh models** reads a gateway's list again. The key is sent to read the
+list only over HTTPS or to this computer. Check that:
+
+- The URL is reachable from the computer or container running OpenMausBot,
+ not just from the one showing the app. Inside a container, `localhost`
+ means the container itself.
+- Codex endpoints use HTTPS. Plain HTTP is accepted only on `localhost` or
+ `127.0.0.1`.
+- The gateway serves the right protocol for the agent and lists models for
+ your key.
## Ollama's context window
diff --git a/docs/verification/claude-endpoint.md b/docs/verification/claude-endpoint.md
index fcf42dfcfd..f387b0ef08 100644
--- a/docs/verification/claude-endpoint.md
+++ b/docs/verification/claude-endpoint.md
@@ -22,21 +22,21 @@ spawn record to `<dataDir>/fake-claude-dump.json`; caller-supplied
Open `previewUrl` from the launch evidence, then Settings → Engines. Expand the
Claude card.
-1. **Add endpoint** opens a form inside the card: name, base URL, token, model,
- and an optional **Model mappings** disclosure for Opus, Sonnet and Haiku.
- Save stays disabled until name, URL, model and (for a new endpoint) token
- are filled. A rejected save shows an alert in the form and leaves the
- fields editable.
-2. Save a name, `https://api.deepseek.com/anthropic`, a fake token and
- `deepseek-chat`. A row appears with the address and models and its own
- **Edit** and **Remove** actions. The token is not shown anywhere.
-3. **Edit** shows the saved address and models, with the token field empty and
- labelled to keep the saved token. Change the model to `deepseek-reasoner`
- and save: the row and
- the bot's picker show only the new model. Leave the token empty; the saved
- token still runs the bot.
-4. Create a bot on the endpoint. Its model picker offers the endpoint's models
- only (here `deepseek-reasoner`), with the first as the default.
+1. **Add endpoint** opens an empty form inside the card: name, base URL
+ (placeholder `https://api.anthropic.com`), API key and an optional model.
+ There is no provider selector. Save stays disabled until name, URL and
+ (for a new endpoint) token are filled. A rejected save shows an alert and
+ leaves the fields editable. A plain-HTTP host off this computer with no
+ model is refused without sending the key; typing the model saves it.
+2. Enter a synthetic gateway URL with an authenticated `/v1/models` catalog
+ offering `deepseek-chat` and `deepseek-reasoner`. Save its name, base URL
+ and fake token. A row appears with its address and **Edit** and **Remove**
+ actions. The token is not shown anywhere.
+3. **Edit** shows the saved address with the token field empty. Rename it,
+ leave the token empty and save; both models remain available.
+4. Create two bots on the endpoint. Choose `deepseek-chat` for one and
+ `deepseek-reasoner` for the other in their agent settings. Each keeps its
+ own model selection. Official Anthropic uses the standard model catalog.
5. Try **Remove** while a bot still uses the endpoint: the button is disabled
and its tooltip says how many bots use it. Move the bot to another model,
then remove it: only the row disappears, and Claude's own sign-in stays.
diff --git a/docs/verification/engines.md b/docs/verification/engines.md
index 036c04cf5d..e58a100f3d 100644
--- a/docs/verification/engines.md
+++ b/docs/verification/engines.md
@@ -125,3 +125,24 @@ OMB_LIVE_MUSE=1 pnpm exec vitest run server/drivers/muse-code.live.test.ts
It lists the account's models (Muse Wonder 1.0), answers on Muse Wonder, runs
a shell command as a tool step, and resumes the session on a fresh instance
after the first one is gone, the way an app restart does.
+
+## Direct API endpoints for native agents
+
+```sh
+pnpm exec vitest run server/claude-account-api.test.ts server/claude-endpoints.test.ts server/codex-endpoints.test.ts server/drivers/codex.test.ts server/drivers/codex-background-text.test.ts src/components/AgentEndpoints.dom.test.ts src/components/ClaudeEndpoints.test.ts server/agent-endpoint-models.test.ts
+```
+
+The API fixture launches a disposable server and synthetic CLIs. It checks
+Codex endpoint creation, persistence, updates, removal guards, admin-only
+mutations and write-only keys. Driver fixtures check direct routing across
+native thread restarts, background calls, missing-key refusal, and exclusion
+of the key from shell environments and command arguments. Renderer tests
+check that both forms start empty (the official URL is only a placeholder;
+an empty Codex URL saves OpenAI), send a typed model, and save a custom
+gateway URL. Discovery tests check that the key never goes to a plain-HTTP
+host off this computer.
+
+These fixtures do not prove a real gateway's Responses or Messages protocol,
+streaming, tool execution, TLS, DNS, or account authentication. Verify those
+against a separately provisioned test gateway before marking the draft ready.
+Never use the person's live workspace or credentials for fixture verification.
diff --git a/server/agent-endpoint-models.test.ts b/server/agent-endpoint-models.test.ts
new file mode 100644
index 0000000000..689c06df20
--- /dev/null
+++ b/server/agent-endpoint-models.test.ts
@@ -0,0 +1,99 @@
+import { expect, it, vi } from "vitest";
+import type { InstanceConfig } from "./contracts.ts";
+import { discoverAgentEndpointModels, officialModels } from "./agent-endpoint-models.ts";
+
+function endpoint(codex: boolean, url = "https://gateway.example/v1"): InstanceConfig {
+ return codex
+ ? { driver: "codex", config: { endpoint: { url, models: ["old"] } }, environment: { OPENMAUSBOT_CODEX_API_KEY: "fixture-secret" } }
+ : { driver: "claudeAgent", config: { endpointModels: ["old"] }, environment: { ANTHROPIC_BASE_URL: url, ANTHROPIC_API_KEY: "fixture-secret" } };
+}
+it.each([true, false])("discovers valid, unique per-agent model choices (Codex=%s)", async codex => {
+ const entry = endpoint(codex);
+ const request = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ data: [{ id: "model-a" }, { id: "model-b" }, { id: "model-a" }, { id: "invalid model" }, {}] }));
+ await discoverAgentEndpointModels(entry, request);
+ expect(request).toHaveBeenCalledWith("https://gateway.example/v1/models", expect.objectContaining({ redirect: "manual", signal: expect.any(AbortSignal), headers: expect.objectContaining({ authorization: "Bearer fixture-secret", ...(codex ? {} : { "x-api-key": "fixture-secret", "anthropic-version": "2023-06-01" }) }) }));
+ expect(entry.config).toMatchObject(codex ? { endpoint: { models: ["model-a", "model-b"] } } : { endpointModels: ["model-a", "model-b"] });
+ expect(entry.environment).not.toHaveProperty("ANTHROPIC_MODEL");
+});
+it.each([
+ [new Response("fixture-secret", { status: 401 }), "rejected the API key (HTTP 401)"],
+ [new Response("fixture-secret", { status: 403 }), "rejected the API key (HTTP 403)"],
+ [new Response("fixture-secret", { status: 404 }), "model catalog was not found (HTTP 404)"],
+ [new Response("fixture-secret", { status: 302 }), "redirected the model request"],
+ [new Response("fixture-secret", { status: 500 }), "model request failed (HTTP 500)"],
+ [new Response("fixture-secret"), "did not return a JSON model catalog"],
+ [Response.json({ data: [] }), "returned no supported model IDs"],
+])("explains discovery failures without exposing gateway response bodies", async (response, detail) => {
+ const entry = endpoint(true);
+ const failure = await discoverAgentEndpointModels(entry, vi.fn<typeof fetch>().mockResolvedValue(response as Response)).catch(error => error);
+ expect(failure.message).toContain(detail);
+ expect(failure.message).not.toContain("fixture-secret");
+ expect(failure.status).toBe(400);
+ expect(entry.config).toMatchObject({ endpoint: { models: ["old"] } });
+});
+it.each([
+ ["http://localhost:8317/v1", "localhost refers to OpenMausBot's server or container"],
+ ["https://gateway.example/v1", "could not reach the gateway"],
+])("explains network failures for %s without exposing raw exceptions", async (url, detail) => {
+ const failure = await discoverAgentEndpointModels(endpoint(true, url), vi.fn<typeof fetch>().mockRejectedValue(new Error("fixture-secret"))).catch(error => error);
+ expect(failure.message).toContain(detail);
+ expect(failure.message).not.toContain("fixture-secret");
+});
+it("identifies a model discovery timeout", async () => {
+ await expect(discoverAgentEndpointModels(endpoint(true), vi.fn<typeof fetch>().mockRejectedValue(new DOMException("fixture-secret", "TimeoutError"))))
+ .rejects.toThrow("timed out");
+});
+it.each([true, false])("keeps the standard catalog for official connections (Codex=%s)", async codex => {
+ const entry = endpoint(codex, codex ? "https://api.openai.com/v1" : "https://api.anthropic.com");
+ const request = vi.fn<typeof fetch>();
+ await discoverAgentEndpointModels(entry, request);
+ expect(request).not.toHaveBeenCalled();
+});
+it.each([true, false])("restores the standard catalog when a gateway moves to the official URL (Codex=%s)", async codex => {
+ const entry = endpoint(codex, codex ? "https://api.openai.com/v1" : "https://api.anthropic.com");
+ await discoverAgentEndpointModels(entry, vi.fn<typeof fetch>());
+ const models = codex ? (entry.config as any).endpoint.models : (entry.config as any).endpointModels;
+ expect(models).toEqual(officialModels(codex));
+ expect(models).not.toContain("old");
+});
+it("refuses a catalog larger than 2 MB without parsing it", async () => {
+ const entry = endpoint(true);
+ const huge = new Response(`{"data":[${'{"id":"m"},'.repeat(300_000)}{"id":"m"}]}`);
+ await expect(discoverAgentEndpointModels(entry, vi.fn<typeof fetch>().mockResolvedValue(huge))).rejects.toThrow("larger than 2 MB");
+ expect(entry.config).toMatchObject({ endpoint: { models: ["old"] } });
+});
+it("keeps at most 1,000 models", async () => {
+ const entry = endpoint(true);
+ const data = Array.from({ length: 1500 }, (_, index) => ({ id: `model-${index}` }));
+ await discoverAgentEndpointModels(entry, vi.fn<typeof fetch>().mockResolvedValue(Response.json({ data })));
+ expect((entry.config as any).endpoint.models).toHaveLength(1000);
+});
+it("never offers Claude Code's reserved `default` as a gateway model", async () => {
+ const entry = endpoint(false);
+ await discoverAgentEndpointModels(entry, vi.fn<typeof fetch>().mockResolvedValue(Response.json({ data: [{ id: "default" }, { id: "model-a" }] })));
+ expect((entry.config as any).endpointModels).toEqual(["model-a"]);
+});
+it("explains a gateway that drops the connection mid-catalog without exposing the error", async () => {
+ const entry = endpoint(true);
+ const body = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode('{"data":[')); controller.error(new Error("fixture-secret")); } });
+ const failure = await discoverAgentEndpointModels(entry, vi.fn<typeof fetch>().mockResolvedValue(new Response(body))).catch(error => error);
+ expect(failure.message).toContain("closed the connection while sending its model catalog");
+ expect(failure.message).not.toContain("fixture-secret");
+ expect(failure.status).toBe(400);
+});
+it.each([true, false])("never sends the key to a plain-HTTP host off this computer (Codex=%s)", async codex => {
+ const entry = endpoint(codex, "http://gateway.example/v1");
+ const request = vi.fn<typeof fetch>();
+ const failure = await discoverAgentEndpointModels(entry, request).catch(error => error);
+ expect(request).not.toHaveBeenCalled();
+ expect(failure.message).toContain("only over HTTPS or from this computer");
+ expect(failure.message).toContain("type the model");
+ expect(failure.status).toBe(400);
+});
+it.each(["http://127.0.0.1:8317/v1", "http://[::1]:8317/v1"])("still reads a loopback catalog over plain HTTP (%s)", async url => {
+ const entry = endpoint(false, url);
+ const request = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ data: [{ id: "model-a" }] }));
+ await discoverAgentEndpointModels(entry, request);
+ expect(request).toHaveBeenCalledTimes(1);
+ expect((entry.config as any).endpointModels).toEqual(["model-a"]);
+});
diff --git a/server/agent-endpoint-models.ts b/server/agent-endpoint-models.ts
new file mode 100644
index 0000000000..2924b88c6a
--- /dev/null
+++ b/server/agent-endpoint-models.ts
@@ -0,0 +1,101 @@
+import type { InstanceConfig } from "./contracts.ts";
+import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS } from "./drivers/claude-model-extras.ts";
+import { STATIC_CODEX_MODELS } from "./drivers/codex-catalog.ts";
+import { isLoopback, providerModelsUrl } from "./provider-key-check.ts";
+
+const OFFICIAL_URL = { codex: "https://api.openai.com/v1", claude: "https://api.anthropic.com" } as const;
+const MAX_CATALOG_BYTES = 2 * 1024 * 1024;
+const MAX_MODELS = 1000;
+const TYPE_MODEL = " Or type the model the host serves in Model.";
+
+export function agentEndpointAddress(entry: InstanceConfig): string {
+ return entry.driver === "codex"
+ ? (entry.config as { endpoint: { url: string } }).endpoint.url
+ : entry.environment!.ANTHROPIC_BASE_URL;
+}
+
+export function isGatewayEndpoint(entry: InstanceConfig): boolean {
+ return agentEndpointAddress(entry) !== OFFICIAL_URL[entry.driver === "codex" ? "codex" : "claude"];
+}
+
+/** An endpoint saved with a fixed model keeps it; discovery never replaces it. */
+export function hasExplicitModel(entry: InstanceConfig): boolean {
+ return entry.driver === "codex"
+ ? Boolean((entry.config as { endpoint?: { model?: string } }).endpoint?.model)
+ : Boolean(entry.environment?.ANTHROPIC_MODEL);
+}
+
+export function officialModels(codex: boolean): string[] {
+ const catalog = codex ? STATIC_CODEX_MODELS : STATIC_CLAUDE_MODELS;
+ return [...new Set([catalog.default, ...catalog.options.map(option => option.id)])];
+}
+
+/** Reads at most `limit` bytes, so a gateway cannot make the server buffer an unbounded body. */
+async function readCatalog(response: Response, limit: number): Promise<string | null> {
+ const reader = response.body?.getReader();
+ if (!reader) return "";
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > limit) { await reader.cancel().catch(() => {}); return null; }
+ chunks.push(value);
+ }
+ return Buffer.concat(chunks).toString("utf8");
+}
+
+/** Resolves the catalog for per-agent selection without storing a provider-wide model choice. */
+export async function discoverAgentEndpointModels(entry: InstanceConfig, fetchImpl: typeof fetch = fetch): Promise<void> {
+ const codex = entry.driver === "codex";
+ const config = entry.config as { endpoint?: { url: string; models: string[] }; endpointModels?: string[] };
+ const setModels = (models: string[]) => { if (codex) config.endpoint!.models = models; else config.endpointModels = models; };
+ if (!isGatewayEndpoint(entry)) return setModels(officialModels(codex));
+ const env = entry.environment ?? {};
+ const token = codex ? env.OPENMAUSBOT_CODEX_API_KEY : env.ANTHROPIC_API_KEY;
+ const headers = codex ? { authorization: `Bearer ${token}` } : { authorization: `Bearer ${token}`, "x-api-key": token!, "anthropic-version": "2023-06-01" };
+ const modelsUrl = providerModelsUrl(codex ? "openai" : "anthropic", agentEndpointAddress(entry));
+ const failure = (detail: string) => Object.assign(new Error(`Could not discover gateway models: ${detail}`), { status: 400 });
+ // Same rule as checkProviderKey: the key goes out only over HTTPS, or over plain HTTP to this computer.
+ const target = new URL(modelsUrl);
+ if (target.protocol !== "https:" && !(target.protocol === "http:" && isLoopback(target.hostname))) {
+ throw failure(`OpenMausBot reads a model list only over HTTPS or from this computer, so your key is not sent in the clear.${TYPE_MODEL}`);
+ }
+ let response: Response;
+ try {
+ // A redirect must never replay the credential to another address.
+ response = await fetchImpl(modelsUrl, {
+ headers, redirect: "manual", signal: AbortSignal.timeout(10_000),
+ });
+ } catch (error) {
+ const timeout = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
+ const localHint = isLoopback(new URL(modelsUrl).hostname)
+ ? " localhost refers to OpenMausBot's server or container. If both apps run on this computer, try 127.0.0.1; otherwise use an address reachable from that server."
+ : " Check that the gateway address is reachable from OpenMausBot's server.";
+ throw failure((timeout ? "The request timed out." : "OpenMausBot's server could not reach the gateway.") + localHint);
+ }
+ if (!response.ok) await response.body?.cancel().catch(() => {});
+ if (response.status === 401 || response.status === 403) {
+ throw failure(`The gateway rejected the API key (HTTP ${response.status}). Use the gateway's client API key, not a ChatGPT or Claude login token.`);
+ }
+ if (response.status === 404) throw failure(`The model catalog was not found (HTTP 404). Check the base URL; Codex usually needs /v1 and requests /v1/models.${TYPE_MODEL}`);
+ if (response.status >= 300 && response.status < 400) throw failure("The gateway redirected the model request. Enter the final API base URL; credentials are never forwarded through redirects.");
+ if (!response.ok) throw failure(`The model request failed (HTTP ${response.status}). Check the gateway's status and model catalog support.`);
+ const text = await readCatalog(response, MAX_CATALOG_BYTES)
+ .catch(() => { throw failure("The gateway closed the connection while sending its model catalog. Try again, or check the gateway's logs."); });
+ if (text === null) throw failure("The model catalog is larger than 2 MB. Check that the base URL points to the gateway's API.");
+ let body: unknown;
+ try { body = JSON.parse(text); } catch { throw failure("The gateway did not return a JSON model catalog. Check that the base URL points to its API, not its dashboard."); }
+ const data = body && typeof body === "object" ? (body as { data?: unknown }).data : undefined;
+ const pattern = codex ? /^[\w][\w./+-]*$/ : CLAUDE_MODEL_ID;
+ const models = new Set<string>();
+ for (const item of Array.isArray(data) ? data : []) {
+ if (models.size >= MAX_MODELS) break;
+ const id = item && typeof item === "object" ? (item as { id?: unknown }).id : undefined;
+ // Claude Code reads `--model default` as its own default model, not a gateway model id.
+ if (typeof id === "string" && id.length <= 160 && pattern.test(id) && (codex || id !== "default")) models.add(id);
+ }
+ if (!models.size) throw failure(`The gateway returned no supported model IDs. Connect a provider account in the gateway and check its /models catalog.${TYPE_MODEL}`);
+ setModels([...models]);
+}
diff --git a/server/claude-account-api.test.ts b/server/claude-account-api.test.ts
index 73501a5f24..ed39ff0e2d 100644
--- a/server/claude-account-api.test.ts
+++ b/server/claude-account-api.test.ts
@@ -96,6 +96,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl
"broken-account": {
driver: "claudeAgent", displayName: "Repairable shadow", config: { cli, configDir: "relative/saved-directory" },
},
+ codex: { driver: "codex", config: { cli: join(SERVER_DIR, "testing", "fake-codex-app-server.ts") } },
claude: {
driver: "claudeAgent", displayName: "Default fixture", config: { cli },
environment: { ANTHROPIC_AUTH_TOKEN: "fixture-base-secret", BASE_ONLY_SENTINEL: "base-only" },
@@ -108,7 +109,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl
clientToken = paired.token;
const port = await freePortBlock([0, 1]);
base = `http://127.0.0.1:${port}`;
- const offlinePrelude = `data:text/javascript,${encodeURIComponent('globalThis.fetch = async () => new Response("offline fixture", { status: 503 });')}`;
+ const offlinePrelude = `data:text/javascript,${encodeURIComponent('let refreshes = 0; globalThis.fetch = async (url) => String(url).startsWith("https://catalog-fixture.example/") ? Response.json({ data: [{ id: "model-a" }, { id: "model-b" }] }) : String(url).startsWith("https://growing-fixture.example/") ? Response.json({ data: [{ id: "model-a" }, ...(refreshes++ ? [{ id: "model-new" }] : [])] }) : new Response("offline fixture", { status: 503 });')}`;
child = spawn(process.execPath, ["--import", offlinePrelude, join(SERVER_DIR, "index.ts")], {
cwd: join(SERVER_DIR, ".."),
env: {
@@ -138,6 +139,109 @@ afterAll(async () => {
});
describe("Claude account HTTP API", () => {
+ it.each(["claude", "codex"])("connects %s without a model and keeps independent bot choices", async engine => {
+ const created = await api("POST", `/api/instances/${engine}-endpoint`, { displayName: "Catalog fixture", baseUrl: "https://catalog-fixture.example/v1", token: "catalog-fixture-key" });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ const id = created.body.instanceId;
+ const instance = created.body.instances.find((row: any) => row.instanceId === id);
+ expect(instance.models.options).toEqual(expect.arrayContaining([expect.objectContaining({ id: "model-a", custom: true }), expect.objectContaining({ id: "model-b", custom: true })]));
+ const first = await addBotOn(id, "model-a");
+ const second = await addBotOn(id, "model-b");
+ expect((await bot(first.id)).modelSelection.model).toBe("model-a");
+ expect((await bot(second.id)).modelSelection.model).toBe("model-b");
+ if (engine === "claude") {
+ for (const [launched, model] of [[first, "model-a"], [second, "model-b"]] as const) {
+ expect((await api("POST", `/api/bots/${launched.id}/messages`, { text: "which model" })).status).toBe(202);
+ await idle(launched.id);
+ const spawn = JSON.parse(readFileSync(join(saved().instances[id].config.configDir, "spawn.json"), "utf8"));
+ expect(spawn.argv[spawn.argv.indexOf("--model") + 1]).toBe(model);
+ }
+ }
+ expect((await api("PATCH", `/api/instances/${id}/${engine}-endpoint`, { displayName: "Renamed", baseUrl: "https://catalog-fixture.example/v1" })).status).toBe(200);
+ const configs = saved().instances[id].config;
+ expect(engine === "codex" ? configs.endpoint.models : configs.endpointModels).toEqual(["model-a", "model-b"]);
+ });
+
+ it.each([
+ ["claude", "https://api.anthropic.com"],
+ ["codex", "https://api.openai.com/v1"],
+ ])("connects official %s without choosing a provider-wide model", async (engine, baseUrl) => {
+ const result = await api("POST", `/api/instances/${engine}-endpoint`, { displayName: "Official fixture", baseUrl, token: "official-fixture-key" });
+ expect(result.status, JSON.stringify(result.body)).toBe(201);
+ const instance = result.body.instances.find((row: any) => row.instanceId === result.body.instanceId);
+ expect(instance.models.options.length).toBeGreaterThan(1);
+ expect(instance.models.options.every((option: any) => option.custom)).toBe(true);
+ expect(saved().instances[result.body.instanceId].environment).not.toHaveProperty("ANTHROPIC_MODEL");
+ });
+
+ it("does not persist an endpoint when gateway model discovery fails", async () => {
+ const before = Object.keys(saved().instances);
+ const result = await api("POST", "/api/instances/codex-endpoint", { displayName: "Failed fixture", baseUrl: "https://offline.example/v1", token: "failed-fixture-secret" });
+ expect(result.status).toBe(400);
+ expect(result.body.error).toContain("Could not discover gateway models");
+ expect(JSON.stringify(result.body)).not.toContain("failed-fixture-secret");
+ expect(Object.keys(saved().instances)).toEqual(before);
+ });
+
+ it("reads a gateway's model list again on Refresh models", async () => {
+ const created = await api("POST", "/api/instances/codex-endpoint", { displayName: "Growing fixture", baseUrl: "https://growing-fixture.example/v1", token: "growing-fixture-key" });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ const id = created.body.instanceId;
+ expect(saved().instances[id].config.endpoint.models).toEqual(["model-a"]);
+ const refreshed = await api("POST", `/api/instances/${id}/refresh-models`, {});
+ expect(refreshed.status, JSON.stringify(refreshed.body)).toBe(200);
+ expect(saved().instances[id].config.endpoint.models).toEqual(["model-a", "model-new"]);
+ expect(refreshed.body.instances.find((row: any) => row.instanceId === id).models.options.map((option: any) => option.id)).toContain("model-new");
+ expect((await api("DELETE", `/api/instances/${id}`)).status).toBe(200);
+ });
+
+ it("keeps a Codex endpoint's fixed model when its key changes on the official URL", async () => {
+ const created = await api("POST", "/api/instances/codex-endpoint", { displayName: "Fixed fixture", baseUrl: "https://api.openai.com/v1", token: "fixed-fixture-key", model: "fixed-model" });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ const id = created.body.instanceId;
+ expect((await api("PATCH", `/api/instances/${id}/codex-endpoint`, { token: "fixed-rotated-key" })).status).toBe(200);
+ expect(saved().instances[id].config.endpoint.models).toEqual(["fixed-model"]);
+ expect((await api("DELETE", `/api/instances/${id}`)).status).toBe(200);
+ });
+
+ it("rotates a legacy Claude endpoint's key without a model catalog", async () => {
+ const created = await api("POST", "/api/instances/claude-endpoint", { displayName: "Legacy fixture", baseUrl: "https://offline.example", token: "legacy-fixture-key", model: "legacy-model" });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ const id = created.body.instanceId;
+ const rotated = await api("PATCH", `/api/instances/${id}/claude-endpoint`, { token: "legacy-rotated-key" });
+ expect(rotated.status, JSON.stringify(rotated.body)).toBe(200);
+ expect(saved().instances[id].environment).toMatchObject({ ANTHROPIC_API_KEY: "legacy-rotated-key", ANTHROPIC_MODEL: "legacy-model" });
+ expect((await api("DELETE", `/api/instances/${id}`)).status).toBe(200);
+ });
+
+ it("creates, edits and removes an isolated Codex API endpoint without OAuth or key disclosure", async () => {
+ const fields = { displayName: "CLIProxyAPI", baseUrl: "https://gateway.example/v1", token: "codex-api-fixture-secret", model: "gateway-model" };
+ const created = await api("POST", "/api/instances/codex-endpoint", fields);
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ const id = created.body.instanceId;
+ const instance = created.body.instances.find((row: any) => row.instanceId === id);
+ expect(instance.codexEndpoint).toEqual({ baseUrl: fields.baseUrl, models: ["gateway-model"], tokenSaved: true });
+ expect(instance.authentication).toBeUndefined();
+ expect(JSON.stringify(created.body)).not.toContain(fields.token);
+ expect(saved().instances[id].environment.CODEX_HOME).toContain(id);
+ expect(saved().instances[id].environment.OPENMAUSBOT_CODEX_API_KEY).toBe(fields.token);
+ expect((await api("POST", `/api/instances/${id}/auth/start`)).status).not.toBe(200);
+ expect((await api("PATCH", `/api/instances/${id}/codex-endpoint`, { baseUrl: "https://other.example/v1" })).status).toBe(400);
+ expect((await api("PATCH", `/api/instances/${id}/codex-endpoint`, { model: "another-model" })).status).toBe(200);
+ expect(saved().instances[id].config.endpoint.models).toEqual(["another-model"]);
+ expect((await api("PATCH", `/api/instances/${id}/codex-endpoint`, { token: "codex-api-rotated-secret" })).status).toBe(200);
+ expect(saved().instances[id].config.endpoint.models).toEqual(["another-model"]);
+ const bot = await addBotOn(id, "another-model");
+ expect((await api("DELETE", `/api/instances/${id}`)).status).toBe(409);
+ expect((await api("PATCH", `/api/bots/${bot.id}/model`, { instanceId: "claude", model: MODEL })).status).toBe(200);
+ expect((await api("DELETE", `/api/instances/${id}`)).status).toBe(200);
+ expect(saved().instances[id]).toBeUndefined();
+ for (const baseUrl of ["http://gateway.example/v1", "https://user:[email protected]/v1", "invalid"]) {
+ expect((await api("POST", "/api/instances/codex-endpoint", { ...fields, baseUrl })).status).toBe(400);
+ }
+ expect((await api("POST", "/api/instances/codex-endpoint", fields, { authorization: `Bearer ${clientToken}` })).status).toBe(403);
+ });
+
it("creates beside an invalid saved directory and repairs that unused shadow without accepting invalid replacements", async () => {
const initial = (await api("GET", "/api/instances")).body.instances.find((row: any) => row.instanceId === "broken-account");
expect(initial.snapshot.state).toBe("unavailable");
diff --git a/server/claude-endpoints.test.ts b/server/claude-endpoints.test.ts
index 9080bc533a..76c767926c 100644
--- a/server/claude-endpoints.test.ts
+++ b/server/claude-endpoints.test.ts
@@ -28,6 +28,12 @@ const cfg = () => ({
}) as never;
describe("custom Claude endpoint", () => {
+ it("uses the official Anthropic API key header without a bearer token", () => {
+ const { instanceId, instances } = newClaudeEndpoint(cfg(), { ...BASE, baseUrl: "https://api.anthropic.com", model: "claude-sonnet-5" });
+ expect(instances[instanceId].environment?.ANTHROPIC_API_KEY).toBe(BASE.token);
+ expect(instances[instanceId].environment?.ANTHROPIC_AUTH_TOKEN).toBeUndefined();
+ });
+
it("creates its own instance with the endpoint's routing, its own directory and no parent credentials", () => {
const source = cfg();
const { instanceId, instances } = newClaudeEndpoint(source, { ...BASE, opusModel: "deepseek-reasoner", sonnetModel: "" });
@@ -109,6 +115,15 @@ describe("custom Claude endpoint", () => {
expect(updated.instances.claude).toEqual(instances.claude);
});
+ it("keeps a discovered catalog when only a model mapping changes", () => {
+ const { instanceId, instances } = newClaudeEndpoint(cfg(), { ...BASE, model: undefined });
+ (instances[instanceId].config as { endpointModels: string[] }).endpointModels = ["model-a", "model-b"];
+ for (const opusModel of ["model-b", ""]) {
+ const entry = updateClaudeEndpoint({ instances }, instanceId, { opusModel }).instances[instanceId];
+ expect((entry.config as { endpointModels: string[] }).endpointModels).toEqual(["model-a", "model-b"]);
+ }
+ });
+
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" }))
@@ -140,6 +155,7 @@ describe("custom Claude endpoint", () => {
{ ...BASE, token: "has\nnewline" },
{ ...BASE, model: "has space" },
{ ...BASE, model: "" },
+ { ...BASE, model: "default" },
{ ...BASE, displayName: "Bad\nname" },
{ ...BASE, environment: { ANTHROPIC_BASE_URL: "https://x.test" } },
]) {
diff --git a/server/claude-endpoints.ts b/server/claude-endpoints.ts
index ee15d787e8..1cf7af8aeb 100644
--- a/server/claude-endpoints.ts
+++ b/server/claude-endpoints.ts
@@ -9,11 +9,13 @@ 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 { officialModels } from "./agent-endpoint-models.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 model = z.string().trim().max(160).regex(CLAUDE_MODEL_ID, "Use the model id the endpoint serves.")
+ .refine((value) => value !== "default", "Claude Code reserves `default`; 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) => endpointBaseUrl(value) !== null, "Enter an http(s) base URL.");
@@ -22,7 +24,7 @@ export const claudeEndpointSchema = z.object({
displayName,
baseUrl,
token,
- model,
+ model: model.optional(),
opusModel: optionalModel.optional(),
sonnetModel: optionalModel.optional(),
haikuModel: optionalModel.optional(),
@@ -93,10 +95,10 @@ function endpointEnvironment(url: string, secret: string, fields: EndpointFields
if (!address) throw Object.assign(new Error("Enter an http(s) base URL."), { status: 400 });
const environment: Record<string, string> = {
ANTHROPIC_BASE_URL: address,
- ANTHROPIC_AUTH_TOKEN: secret,
+ ...(address === "https://api.anthropic.com" ? {} : { ANTHROPIC_AUTH_TOKEN: secret }),
// Claude Code's own auth probe and a turn both need a key they recognize; the endpoint's token is that key.
ANTHROPIC_API_KEY: secret,
- ANTHROPIC_MODEL: (fields.model ?? "").trim(),
+ ...(fields.model ? { ANTHROPIC_MODEL: fields.model.trim() } : {}),
};
for (const [field, key] of TIERS) {
const value = fields[field]?.trim();
@@ -133,7 +135,7 @@ export function newClaudeEndpoint(cfg: AppConfig, body: z.infer<typeof claudeEnd
...(cli ? { cli } : {}),
configDir: join(DATA_DIR, "providers", instanceId),
requireApiKey: true,
- endpointModels: endpointModels(body),
+ endpointModels: body.model ? endpointModels(body) : officialModels(false),
},
environment: endpointEnvironment(body.baseUrl, body.token, body),
};
@@ -154,7 +156,7 @@ export function updateClaudeEndpoint(cfg: AppConfig, instanceId: string, body: E
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] };
+ const fields: EndpointFields = { baseUrl: address, model: body.model ?? entry.environment?.ANTHROPIC_MODEL };
if (body.displayName !== undefined) fields.displayName = body.displayName;
for (const [field, key] of TIERS) {
const value = body[field] !== undefined ? body[field] : entry.environment?.[key];
@@ -166,7 +168,7 @@ export function updateClaudeEndpoint(cfg: AppConfig, instanceId: string, body: E
...entry,
...(fields.displayName ? { displayName: fields.displayName } : {}),
environment: endpointEnvironment(address, secret, fields),
- config: { ...rawConfig(entry), endpointModels: endpointModels(fields) },
+ config: { ...rawConfig(entry), endpointModels: fields.model && (body.model !== undefined || TIERS.some(([field]) => body[field] !== undefined)) ? endpointModels(fields) : saved.models },
};
return { instances };
-}
\ No newline at end of file
+}
diff --git a/server/codex-endpoints.test.ts b/server/codex-endpoints.test.ts
new file mode 100644
index 0000000000..455de367cd
--- /dev/null
+++ b/server/codex-endpoints.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { codexEndpointSchema, newCodexEndpoint, updateCodexEndpoint, withCodexEndpointInfo } from "./codex-endpoints.ts";
+
+const fields = { displayName: "Gateway", baseUrl: "https://gateway.example/v1", token: "fixture-secret", model: "custom-model" };
+
+describe("Codex direct API endpoints", () => {
+ it("creates isolated instances without changing existing accounts or returning the key", () => {
+ const original = { driver: "codex", config: { cli: "/fixture/codex" } };
+ const { instanceId, instances } = newCodexEndpoint({ instances: { codex: original } } as never, fields);
+ expect(instances.codex).toEqual(original);
+ expect(instances[instanceId]).toMatchObject({ driver: "codex", access: "custom", config: { cli: "/fixture/codex", endpoint: { url: fields.baseUrl, models: ["custom-model"] } }, environment: { OPENMAUSBOT_CODEX_API_KEY: "fixture-secret" } });
+ expect(instances[instanceId].environment?.CODEX_HOME).toContain(instanceId);
+ const info = withCodexEndpointInfo([{ instanceId }], instances);
+ expect(info).toEqual([{ instanceId, url: fields.baseUrl, codexEndpoint: { baseUrl: fields.baseUrl, models: ["custom-model"], tokenSaved: true } }]);
+ expect(JSON.stringify(info)).not.toContain("fixture-secret");
+ });
+
+ it("requires a new key when changing hosts and preserves it on a model edit", () => {
+ const { instanceId, instances } = newCodexEndpoint({ instances: {} } as never, fields);
+ expect(() => updateCodexEndpoint({ instances } as never, instanceId, { baseUrl: "https://other.example/v1" })).toThrow(/token again/);
+ const updated = updateCodexEndpoint({ instances } as never, instanceId, { model: "another-model" }).instances[instanceId];
+ expect(updated.environment?.OPENMAUSBOT_CODEX_API_KEY).toBe("fixture-secret");
+ expect(updated.config).toMatchObject({ endpoint: { models: ["another-model"] } });
+ expect(() => updateCodexEndpoint({ instances: { codex: { driver: "codex" } } } as never, "codex", { model: "m" })).toThrow();
+ });
+
+ it.each(["http://gateway.example/v1", "https://user:[email protected]/v1", "https://gateway.example/v1?key=secret", "file:///tmp/socket"])("rejects unsafe URLs (%s)", baseUrl => {
+ expect(codexEndpointSchema.safeParse({ ...fields, baseUrl }).success).toBe(false);
+ });
+});
diff --git a/server/codex-endpoints.ts b/server/codex-endpoints.ts
new file mode 100644
index 0000000000..c3490f8893
--- /dev/null
+++ b/server/codex-endpoints.ts
@@ -0,0 +1,77 @@
+import { randomUUID } from "node:crypto";
+import { join } from "node:path";
+import { z } from "zod";
+
+import type { CodexEndpointInfo } from "../shared/claude-endpoint.ts";
+import { officialModels } from "./agent-endpoint-models.ts";
+import { claudeEndpointSchema } from "./claude-endpoints.ts";
+import { DATA_DIR, persistableInstanceConfigs, type AppConfig } from "./config.ts";
+import type { InstanceConfig, InstanceConfigMap } from "./contracts.ts";
+import { endpointBaseUrl } from "./openai-compat-endpoints.ts";
+
+export const codexEndpointSchema = claudeEndpointSchema.pick({ displayName: true, baseUrl: true, token: true, model: true })
+ .extend({ model: z.string().trim().min(1).max(160).regex(/^[\w][\w./+-]*$/, "Use the model id the Responses endpoint serves.").optional(), baseUrl: claudeEndpointSchema.shape.baseUrl.refine(value => {
+ const address = endpointBaseUrl(value);
+ if (!address) return false;
+ const url = new URL(address);
+ return url.protocol === "https:" || url.hostname === "localhost" || url.hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(url.hostname);
+ }, "Use HTTPS, or HTTP on localhost through a secure tunnel.") });
+export const codexEndpointUpdateSchema = codexEndpointSchema.partial().refine(value => Object.keys(value).length > 0, "No settings supplied");
+
+type Fields = Partial<z.infer<typeof codexEndpointSchema>>;
+
+function configOf(entry: InstanceConfig) {
+ return (entry.config ?? {}) as { cli?: string; endpoint?: { url: string; models: string[]; model?: string } };
+}
+
+export function isCodexEndpoint(entry: InstanceConfig | undefined): boolean {
+ if (entry?.driver !== "codex") return false;
+ const endpoint = configOf(entry).endpoint;
+ return Boolean(endpoint && typeof endpoint.url === "string" && endpointBaseUrl(endpoint.url)
+ && Array.isArray(endpoint.models) && endpoint.models.every(model => typeof model === "string"));
+}
+
+function infoOf(entry: InstanceConfig): CodexEndpointInfo {
+ const endpoint = configOf(entry).endpoint!;
+ return { baseUrl: endpoint.url, models: [...endpoint.models], tokenSaved: Boolean(entry.environment?.OPENMAUSBOT_CODEX_API_KEY) };
+}
+
+export function withCodexEndpointInfo(described: unknown, configs: InstanceConfigMap): unknown {
+ if (!Array.isArray(described)) return described;
+ return described.map((instance: { instanceId?: string }) => {
+ const entry = instance.instanceId ? configs[instance.instanceId] : undefined;
+ return entry && isCodexEndpoint(entry) ? { ...instance, url: infoOf(entry).baseUrl, codexEndpoint: infoOf(entry) } : instance;
+ });
+}
+
+export function newCodexEndpoint(cfg: AppConfig, body: z.infer<typeof codexEndpointSchema>) {
+ const instances = persistableInstanceConfigs(cfg);
+ const instanceId = `codex-endpoint-${randomUUID()}`;
+ const source = Object.values(instances).find(entry => entry.driver === "codex" && configOf(entry).cli);
+ const cli = source ? configOf(source).cli : undefined;
+ instances[instanceId] = {
+ driver: "codex", access: "custom", displayName: body.displayName,
+ config: { ...(cli ? { cli } : {}), endpoint: { url: endpointBaseUrl(body.baseUrl)!, ...(body.model ? { model: body.model, models: [body.model] } : { models: officialModels(true) }) } },
+ environment: { CODEX_HOME: join(DATA_DIR, "providers", instanceId), OPENMAUSBOT_CODEX_API_KEY: body.token },
+ };
+ return { instanceId, instances };
+}
+
+export function updateCodexEndpoint(cfg: AppConfig, instanceId: string, body: Fields) {
+ const instances = persistableInstanceConfigs(cfg);
+ const entry = instances[instanceId];
+ if (!entry) throw Object.assign(new Error("unknown instance"), { status: 404 });
+ if (!isCodexEndpoint(entry)) throw Object.assign(new Error("This Codex instance is not a direct API endpoint."), { status: 400 });
+ const saved = infoOf(entry);
+ const address = body.baseUrl === undefined ? saved.baseUrl : endpointBaseUrl(body.baseUrl)!;
+ // A saved credential belongs only to the address it was entered for.
+ if (body.token === undefined && address !== saved.baseUrl) throw Object.assign(new Error("Enter the endpoint's token again for the new address."), { status: 400 });
+ const token = body.token ?? entry.environment?.OPENMAUSBOT_CODEX_API_KEY;
+ if (!token) throw Object.assign(new Error("Enter the endpoint's token."), { status: 400 });
+ instances[instanceId] = {
+ ...entry, ...(body.displayName ? { displayName: body.displayName } : {}),
+ config: { ...configOf(entry), endpoint: { ...configOf(entry).endpoint!, url: address, ...(body.model ? { model: body.model, models: [body.model] } : {}) } },
+ environment: { ...entry.environment, OPENMAUSBOT_CODEX_API_KEY: token },
+ };
+ return { instances };
+}
diff --git a/server/drivers/claude-accounts.test.ts b/server/drivers/claude-accounts.test.ts
index 6197470a0a..fe1842eca1 100644
--- a/server/drivers/claude-accounts.test.ts
+++ b/server/drivers/claude-accounts.test.ts
@@ -49,12 +49,12 @@ function account(name: string, auth: unknown = { loggedIn: true, email: `${name}
return dir;
}
-async function create(configDir?: string, environment: Record<string, string> = {}) {
+async function create(configDir?: string, environment: Record<string, string> = {}, extra: Record<string, unknown> = {}) {
const instance = await ClaudeDriver.create({
instanceId: `claude-${instances.length}`,
displayName: "Fixture Claude",
enabled: true,
- config: { cli, configDir, permissionMode: "acceptEdits" },
+ config: { cli, configDir, permissionMode: "acceptEdits", ...extra },
environment,
});
instances.push(instance);
@@ -133,6 +133,14 @@ describe("Claude account configuration", () => {
expect(calls(dir)[0]?.env.ANTHROPIC_API_KEY).toBeUndefined();
});
+ it("gives an endpoint without its own directory none of the parent's credentials", async () => {
+ const dir = account("endpoint-no-dir");
+ vi.stubEnv("CLAUDE_CONFIG_DIR", dir);
+ const provider = await create(undefined, { ANTHROPIC_BASE_URL: "https://api.anthropic.com", ANTHROPIC_API_KEY: "fixture-endpoint-key" }, { endpointModels: ["claude-sonnet-5"] });
+ await provider.generateText?.("fixture review");
+ expect(calls(dir)[0]?.env).toEqual({ ANTHROPIC_BASE_URL: "https://api.anthropic.com", ANTHROPIC_API_KEY: "fixture-endpoint-key" });
+ });
+
it("preserves explicit custom endpoints and injected local models without inheriting subscription OAuth", async () => {
const dir = account("custom");
const provider = await create(dir, {
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index cd6e014fb6..9a35bfe89a 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -113,18 +113,18 @@ function claudeEnvironment(
source: NodeJS.ProcessEnv = process.env,
configDir?: string,
instanceEnvironment: NodeJS.ProcessEnv = {},
+ endpoint = false,
): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = { BASH_MAX_TIMEOUT_MS: "600000", ...source, PATH: augmentedPath(), NPM_CONFIG_LOGLEVEL: "error" };
- if (configDir?.trim()) {
- env.CLAUDE_CONFIG_DIR = resolveClaudeConfigDir(configDir, env);
+ if (configDir?.trim()) env.CLAUDE_CONFIG_DIR = resolveClaudeConfigDir(configDir, env);
+ else if (env.CLAUDE_CONFIG_DIR) env.CLAUDE_CONFIG_DIR = resolveClaudeConfigDir(undefined, env);
+ if (configDir?.trim() || endpoint) {
for (const key of CLAUDE_ACCOUNT_ENV_KEYS) {
// Subscription OAuth always comes from this account's own login, never the parent's.
if (key.startsWith("CLAUDE_CODE_OAUTH_") || key.endsWith("_FILE_DESCRIPTOR") || !Object.hasOwn(instanceEnvironment, key)) {
delete env[key];
}
}
- } else if (env.CLAUDE_CONFIG_DIR) {
- env.CLAUDE_CONFIG_DIR = resolveClaudeConfigDir(undefined, env);
}
delete env.CLAUDECODE;
delete env.CLAUDE_CODE_ENTRYPOINT;
@@ -775,7 +775,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
async create(input: DriverCreateInput<ClaudeConfig>): Promise<ProviderInstance> {
const { instanceId, config } = input;
const environment = (model?: string | null) =>
- claudeEnvironment(config.managed ? undefined : model, { ...process.env, ...input.environment }, config.configDir, input.environment);
+ claudeEnvironment(config.managed ? undefined : model, { ...process.env, ...input.environment }, config.configDir, input.environment, Boolean(config.endpointModels));
const catalogEnv = environment();
if (inheritsUserConfig(catalogEnv)) {
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`);
diff --git a/server/drivers/codex-background-text.test.ts b/server/drivers/codex-background-text.test.ts
index 32699fb9ae..e8f078d07d 100644
--- a/server/drivers/codex-background-text.test.ts
+++ b/server/drivers/codex-background-text.test.ts
@@ -108,7 +108,7 @@ describe("Codex generateMemoryText (fake CLI)", () => {
return { onRefused, fallback: { ...(model ? { model } : {}), refused: new Set(refused), onRefused } satisfies SmallModelFallback };
};
- const create = async (environment: Record<string, string> = {}, managed = false) => {
+ const create = async (environment: Record<string, string> = {}, managed = false, endpoint = false) => {
instance = await CodexDriver.create({
instanceId: `codex-background-${Math.random().toString(36).slice(2)}`,
displayName: "Codex",
@@ -117,12 +117,14 @@ describe("Codex generateMemoryText (fake CLI)", () => {
CODEX_HOME: join(scratch, ".codex"),
FAKE_CODEX_TEXT_LOG: log,
...(managed ? { OPENMAUSBOT_COMPANY_API_KEY: "synthetic-company-fixture" } : {}),
+ ...(endpoint ? { OPENMAUSBOT_CODEX_API_KEY: "synthetic-endpoint-key" } : {}),
...environment,
},
enabled: true,
config: {
cli: FAKE_CLI,
fullAuto: false,
+ ...(endpoint ? { endpoint: { url: "https://gateway.example/v1", models: ["gateway-model"] } } : {}),
...(managed ? { managed: { url: "https://company.example/v1", models: ["company-large", "gpt-6-luna"] } } : {}),
},
});
@@ -183,6 +185,20 @@ describe("Codex generateMemoryText (fake CLI)", () => {
expect(call!.argv[call!.argv.indexOf("--model") + 1]).toBe(codex.models.default);
});
+ it("uses only the direct endpoint for background calls and refuses a missing key", async () => {
+ const codex = await create({}, false, true);
+ await codex.generateMemoryText!("hello");
+ const [call] = calls();
+ expect(call!.argv).toContain('model_provider="openmaus_endpoint"');
+ expect(call!.argv).toContain('model_providers.openmaus_endpoint.base_url="https://gateway.example/v1"');
+ expect(modelsRun()).toEqual(["gateway-model"]);
+ expect(call!.env.OPENMAUSBOT_CODEX_API_KEY).toBe("synthetic-endpoint-key");
+ expect(JSON.stringify(call!.argv)).not.toContain("synthetic-endpoint-key");
+ await codex.dispose();
+ const keyless = await create({ OPENMAUSBOT_CODEX_API_KEY: "" }, false, true);
+ await expect(keyless.generateMemoryText!("hello")).rejects.toThrow(/Direct API key/);
+ });
+
it("keeps a Company's routing and approved models, and refuses without its key", async () => {
const codex = await create({}, true);
await codex.generateMemoryText!("hello");
diff --git a/server/drivers/codex-endpoint-config.ts b/server/drivers/codex-endpoint-config.ts
new file mode 100644
index 0000000000..ed68969215
--- /dev/null
+++ b/server/drivers/codex-endpoint-config.ts
@@ -0,0 +1,41 @@
+/** A Responses endpoint used by an isolated Codex instance. */
+export interface CodexEndpointConfig {
+ url: string;
+ models: string[];
+}
+
+export function decodeRoutedCodexConfig(raw: object, label = "Company"): CodexEndpointConfig {
+ const value = raw as { url?: unknown; models?: unknown };
+ if (typeof value.url !== "string" || !Array.isArray(value.models) || !value.models.length || value.models.some(model => typeof model !== "string" || !/^[\w][\w./+-]*$/.test(model))) {
+ throw new Error(`Invalid ${label} Codex configuration.`);
+ }
+ const url = new URL(value.url);
+ // Plain HTTP leaks the API key; allow it only on loopback.
+ const loopback = url.hostname === "localhost" || url.hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(url.hostname);
+ if (url.username || url.password || url.search || url.hash || (url.protocol !== "https:" && !(url.protocol === "http:" && loopback))) throw new Error(`Invalid ${label} Codex endpoint.`);
+ return { url: url.href.replace(/\/$/, ""), models: value.models as string[] };
+}
+
+export function managedCodexArgs(config: CodexEndpointConfig): string[] {
+ return providerCodexArgs(config.url, "openmaus_company", "Company", "OPENMAUSBOT_COMPANY_API_KEY");
+}
+
+export function endpointCodexArgs(config: CodexEndpointConfig): string[] {
+ return [...providerCodexArgs(config.url, "openmaus_endpoint", "Direct API", "OPENMAUSBOT_CODEX_API_KEY"),
+ "-c", "model_providers.openmaus_endpoint.supports_websockets=false",
+ "-c", "features.tool_search=false"];
+}
+
+function providerCodexArgs(url: string, provider: string, name: string, key: string): string[] {
+ return [
+ "-c", `model_provider=${JSON.stringify(provider)}`,
+ "-c", `model_providers.${provider}.name=${JSON.stringify(name)}`,
+ "-c", `model_providers.${provider}.base_url=${JSON.stringify(url)}`,
+ "-c", `model_providers.${provider}.env_key=${JSON.stringify(key)}`,
+ "-c", `model_providers.${provider}.wire_api="responses"`,
+ "-c", `model_providers.${provider}.requires_openai_auth=false`,
+ "-c", 'cli_auth_credentials_store="ephemeral"',
+ "-c", "shell_environment_policy.ignore_default_excludes=false",
+ ];
+}
+
diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.ts
index 4eb3f52ebd..697759811e 100644
--- a/server/drivers/codex.test.ts
+++ b/server/drivers/codex.test.ts
@@ -59,6 +59,13 @@ describe("CodexDriver.decodeConfig", () => {
expect(codexUserError(refusal, "own")).toBe(refusal);
expect(() => CodexDriver.decodeConfig({ authMode: "chatgpt-plan", managed: {} })).toThrow("cannot be combined");
});
+ it("keeps direct API configuration and refuses mixed authentication modes", () => {
+ expect(CodexDriver.decodeConfig({ endpoint: { url: "https://gateway.example/v1", models: ["gateway-model"] } }))
+ .toMatchObject({ endpoint: { url: "https://gateway.example/v1", models: ["gateway-model"] } });
+ expect(() => CodexDriver.decodeConfig({ endpoint: { url: "http://gateway.example/v1", models: ["m"] } })).toThrow();
+ expect(() => CodexDriver.decodeConfig({ authMode: "chatgpt-plan", endpoint: { url: "https://gateway.example", models: ["m"] } })).toThrow();
+ expect(() => CodexDriver.decodeConfig({ managed: {}, endpoint: {} })).toThrow();
+ });
it("defaults to the codex binary with fullAuto off", () => {
expect(CodexDriver.decodeConfig({})).toEqual({ cli: "codex", fullAuto: false });
expect(CodexDriver.decodeConfig(undefined)).toEqual({ cli: "codex", fullAuto: false });
@@ -133,7 +140,7 @@ describe("CodexDriver turns (fake app-server)", () => {
let scratch: string;
const create = async (
- opts: { mode?: string; fullAuto?: boolean; environment?: Record<string, string>; managed?: boolean; authMode?: "chatgpt-plan"; cli?: string } = {},
+ opts: { mode?: string; fullAuto?: boolean; environment?: Record<string, string>; managed?: boolean; endpoint?: boolean; authMode?: "chatgpt-plan"; cli?: string } = {},
) => {
if (opts.mode) process.env.FAKE_CODEX_MODE = opts.mode;
instance = await CodexDriver.create({
@@ -141,6 +148,7 @@ describe("CodexDriver turns (fake app-server)", () => {
displayName: "Codex Test",
environment: {
...(opts.managed ? { HOME: scratch, USERPROFILE: scratch, CODEX_HOME: join(scratch, ".codex"), OPENMAUSBOT_COMPANY_API_KEY: "synthetic-company-fixture" } : {}),
+ ...(opts.endpoint ? { CODEX_HOME: join(scratch, "endpoint"), OPENMAUSBOT_CODEX_API_KEY: "synthetic-endpoint-key" } : {}),
...opts.environment,
},
enabled: true,
@@ -148,6 +156,7 @@ describe("CodexDriver turns (fake app-server)", () => {
cli: opts.cli ?? FAKE_CLI,
fullAuto: opts.fullAuto ?? false,
...(opts.authMode ? { authMode: opts.authMode } : {}),
+ ...(opts.endpoint ? { endpoint: { url: "http://127.0.0.1:1/v1", models: ["gateway-model"] } } : {}),
...(opts.managed ? { managed: { url: "http://127.0.0.1:1/v1", models: ["company-codex-model"] } } : {}),
},
});
@@ -1943,6 +1952,10 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
["gpt-5.6-sol", "gpt-5.6-sol", "openai_chatgpt_plan"],
["gpt-6.1-sol", "gpt-6.1-sol", "openai_chatgpt_plan"],
] },
+ { name: "Direct API", opts: { endpoint: true }, selections: [
+ ["gateway-model", "gateway-model", "openmaus_endpoint"],
+ ["gateway-model", "gateway-model", "openmaus_endpoint"],
+ ] },
{ name: "Company", opts: { managed: true }, selections: [
["company-codex-model", "company-codex-model", "openmaus_company"],
["company-codex-model", "company-codex-model", "openmaus_company"],
@@ -1970,6 +1983,15 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
const seen = JSON.parse(readFileSync(dump, "utf8"));
pids.add(seen.pid);
const plan = "authMode" in opts;
+ if ("endpoint" in opts) {
+ expect(instance.startAuthentication).toBeUndefined();
+ expect(instance.signOut).toBeUndefined();
+ expect(seen.env.OPENMAUSBOT_CODEX_API_KEY).toBe("synthetic-endpoint-key");
+ expect(JSON.stringify({ argv: seen.argv, calls: seen.calls })).not.toContain("synthetic-endpoint-key");
+ expect(seen.argv).toContain("features.tool_search=false");
+ expect(seen.argv).toContain("model_providers.openmaus_endpoint.supports_websockets=false");
+ }
+
expect(seen.env.OPENAI_API_KEY).toBeUndefined();
expect(seen.env.OPENMAUSBOT_CHATGPT_TOKEN).toBe(plan ? "synthetic-chatgpt-token" : undefined);
expect(JSON.stringify({ argv: seen.argv, calls: seen.calls })).not.toContain("synthetic-chatgpt-token");
@@ -1981,6 +2003,7 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
const threadCalls = seen.calls.filter((call: { method: string }) => ["thread/start", "thread/resume"].includes(call.method));
expect(threadCalls).toHaveLength(1);
if (plan) expect(threadCalls[0].params.config["shell_environment_policy.exclude"]).toEqual(["OPENMAUSBOT_CHATGPT_TOKEN"]);
+ if ("endpoint" in opts) expect(threadCalls[0].params.config["shell_environment_policy.exclude"]).toContain("OPENMAUSBOT_CODEX_API_KEY");
expect(threadCalls[0]).toMatchObject({
method: index ? "thread/resume" : "thread/start",
params: { model: expectedModel, modelProvider, ...(index ? { threadId: "codex-thread-1" } : {}) },
diff --git a/server/drivers/codex.ts b/server/drivers/codex.ts
index 06c06f8054..9ab05d21a0 100644
--- a/server/drivers/codex.ts
+++ b/server/drivers/codex.ts
@@ -1,3 +1,5 @@
+import { decodeRoutedCodexConfig, managedCodexArgs, endpointCodexArgs, type CodexEndpointConfig } from "./codex-endpoint-config.ts";
+export { managedCodexArgs, endpointCodexArgs } from "./codex-endpoint-config.ts";
import { codexActionFailure } from "./codex-action-notice.ts";
import { codexToolSurfaceArgs } from "./codex-tool-surface.ts";
import { codexShellDisabled, GUEST_CONFINED_CODEX_ARGS } from "./codex-guest.ts";
@@ -75,18 +77,21 @@ export interface CodexConfig {
cli: string;
fullAuto: boolean;
authMode?: "chatgpt-plan";
- managed?: { url: string; models: string[] };
+ managed?: CodexEndpointConfig;
+ endpoint?: CodexEndpointConfig;
}
function decodeConfig(raw: unknown): CodexConfig {
const o = (raw ?? {}) as Record<string, unknown>;
if (o.authMode !== undefined && o.authMode !== "chatgpt-plan") throw new Error("Unknown Codex sign-in mode.");
if (o.authMode && o.managed) throw new Error("ChatGPT plan and Company billing cannot be combined.");
+ if (o.endpoint && (o.authMode || o.managed)) throw new Error("Direct API, ChatGPT plan and Company billing cannot be combined.");
return {
cli: typeof o.cli === "string" ? o.cli : "codex",
fullAuto: o.fullAuto === true,
...(o.authMode === "chatgpt-plan" ? { authMode: "chatgpt-plan" as const } : {}),
- ...(o.managed && typeof o.managed === "object" ? { managed: decodeManagedCodex(o.managed) } : {}),
+ ...(o.endpoint ? { endpoint: decodeRoutedCodexConfig(o.endpoint as object, "Direct API") } : {}),
+ ...(o.managed && typeof o.managed === "object" ? { managed: decodeRoutedCodexConfig(o.managed) } : {}),
};
}
@@ -108,33 +113,6 @@ export function chatgptPlanCodexArgs(): string[] {
];
}
-function decodeManagedCodex(raw: object): NonNullable<CodexConfig["managed"]> {
- const value = raw as { url?: unknown; models?: unknown };
- if (typeof value.url !== "string" || !Array.isArray(value.models) || !value.models.length || value.models.some(model => typeof model !== "string" || !/^[\w][\w./+-]*$/.test(model))) {
- throw new Error("Invalid Company Codex configuration.");
- }
- const url = new URL(value.url);
- // Plain HTTP leaks the Company API key; allow it only on loopback.
- const loopback = url.hostname === "localhost" || url.hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(url.hostname);
- if (url.username || url.password || url.search || url.hash || (url.protocol !== "https:" && !(url.protocol === "http:" && loopback))) throw new Error("Invalid Company Codex endpoint.");
- return { url: url.href.replace(/\/$/, ""), models: value.models as string[] };
-}
-
-export function managedCodexArgs(config: NonNullable<CodexConfig["managed"]>): string[] {
- // Credential stays in the instance environment, never argv or config.toml.
- // https://learn.chatgpt.com/docs/config-file/config-reference
- return [
- "-c", 'model_provider="openmaus_company"',
- "-c", 'model_providers.openmaus_company.name="Company"',
- "-c", `model_providers.openmaus_company.base_url=${JSON.stringify(config.url)}`,
- "-c", 'model_providers.openmaus_company.env_key="OPENMAUSBOT_COMPANY_API_KEY"',
- "-c", 'model_providers.openmaus_company.wire_api="responses"',
- "-c", "model_providers.openmaus_company.requires_openai_auth=false",
- "-c", 'cli_auth_credentials_store="ephemeral"',
- "-c", "shell_environment_policy.ignore_default_excludes=false",
- ];
-}
-
const PRIVATE_ENV_FAMILIES = ["OMB_GATE_CONFIG_", "OMB_REMOTE_MCP_CONFIG_"];
const PROXY_LITERAL_ENV = ["NODE_USE_ENV_PROXY", "NO_PROXY", "no_proxy"];
const SHELL_ESSENTIALS = new Set(["PATH", "HOME", "USER", "LOGNAME", "SHELL", "TMPDIR", "TERM", "LANG", "TZ"]);
@@ -365,6 +343,8 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
async create(input: DriverCreateInput<CodexConfig>): Promise<ProviderInstance> {
const { instanceId, config } = input;
+ const routed = config.endpoint ?? config.managed;
+ const routedProvider = config.endpoint ? "openmaus_endpoint" : "openmaus_company";
const plan = config.authMode === "chatgpt-plan";
const planUnavailable = plan && (hostedWorkspaceConfigured() || cloudHomeConfigured())
? "ChatGPT plan sign-in for hosted Pro requires OpenAI's hosted-app approval. Use a Company model or API key until that integration is approved; the local desktop flow cannot be used here."
@@ -381,6 +361,11 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
delete env.OPENAI_API_KEY;
stripWorkspaceCredentialEnv(env);
delete env.OPENMAUSBOT_CHATGPT_TOKEN;
+ delete env.OPENMAUSBOT_CODEX_API_KEY;
+ if (config.endpoint) {
+ env.OPENMAUSBOT_CODEX_API_KEY = input.environment.OPENMAUSBOT_CODEX_API_KEY;
+ env.CODEX_HOME = input.environment.CODEX_HOME;
+ }
if (plan) env.CODEX_HOME = join(planDirectory, "codex");
return env;
};
@@ -390,9 +375,9 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
let planSigningOut = false;
let disposed = false;
let planWarning: string | undefined;
- let models = plan ? { default: "", options: [] } : config.managed ? { default: config.managed.models[0], options: config.managed.models.map(id => ({ id, label: id })) } : STATIC_CODEX_MODELS;
+ let models = plan ? { default: "", options: [] } : routed ? { default: routed.models[0], options: routed.models.map(id => ({ id, label: id, ...(config.endpoint ? { custom: true } : {}) })) } : STATIC_CODEX_MODELS;
const refreshModels = async (preserveExisting = false) => {
- if (config.managed) return;
+ if (routed) return;
if (planAuth) {
const generation = planGeneration;
const kept = preserveExisting && models.options.length > 0 ? models : null;
@@ -423,7 +408,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
// Codex's model list ships with the CLI: updating 0.155.1 to 0.162.1 in place adds gpt-6.1-sol.
let modelsCliVersion: string | null = null;
let startupModelRefresh: Promise<void> | null = null;
- if (config.managed) {
+ if (routed) {
await refreshModels();
} else {
startupModelRefresh = (await openStartupModelCatalog({
@@ -439,7 +424,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
}
// OpenAI can refuse Codex's own ChatGPT login while `codex login status` still reports it. Only a
// stored ChatGPT login is marked: an API-key login cannot be fixed by a ChatGPT sign-in.
- const ownLogin = !plan && !config.managed;
+ const ownLogin = !plan && !routed;
const loginCheck = codexLoginCheck(config.cli);
const loginMark = (): [string, string] | null => {
const env = childEnv();
@@ -511,6 +496,11 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
}
mkdirSync(join(planDirectory, "codex"), { recursive: true, mode: 0o700 });
}
+ if (config.endpoint) {
+ if (!turn.model || !config.endpoint.models.includes(turn.model)) throw new Error("Select a model configured for this direct API endpoint.");
+ if (!input.environment.OPENMAUSBOT_CODEX_API_KEY || !input.environment.CODEX_HOME) throw new Error("Direct API key or isolated Codex home is missing. Edit the endpoint in Settings.");
+ mkdirSync(input.environment.CODEX_HOME, { recursive: true, mode: 0o700 });
+ }
if (config.managed) {
if (!turn.model) {
throw new Error("Company model access is unavailable: no model is selected. Reconnect your organization; personal billing will not be used.");
@@ -576,7 +566,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const env = childEnv();
const launchedLogin = chatgptTurn ? storedCodexLogin(env) : null;
if (planToken) env.OPENMAUSBOT_CHATGPT_TOKEN = planToken;
- const appServerArgs = ["app-server", ...(plan ? chatgptPlanCodexArgs() : config.managed ? managedCodexArgs(config.managed) : codexSelectedProviderArgs(env, turn.model)), ...codexToolSurfaceArgs(),
+ const appServerArgs = ["app-server", ...(plan ? chatgptPlanCodexArgs() : config.endpoint ? endpointCodexArgs(config.endpoint) : config.managed ? managedCodexArgs(config.managed) : codexSelectedProviderArgs(env, turn.model)), ...codexToolSurfaceArgs(),
// Native shell snapshots can restore variables the shell policy removed.
...(turn.toolScope === undefined ? [] : ["-c", "features.shell_snapshot=false"]),
// A guest-driven turn: no shell, no file reads (-c wins over config files).
@@ -668,6 +658,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const mountedEnv = [...mountedNames].filter((name) => env[name] !== undefined && !SHELL_ESSENTIALS.has(name) && !name.startsWith("LC_")
&& (name === "ELECTRON_RUN_AS_NODE" || baseEnv.get(name) !== env[name]));
const privateEnv = [...new Set([
+ ...(config.endpoint ? ["OPENMAUSBOT_CODEX_API_KEY"] : []),
...(turn.toolScope !== undefined ? ["OMB_GATE_CONFIG_*"] : []),
...PRIVATE_ENV_FAMILIES.filter((family) => mountedEnv.some((name) => name.startsWith(family))).map((family) => `${family}*`),
...mountedEnv.filter((name) => !PRIVATE_ENV_FAMILIES.some((family) => name.startsWith(family))).sort(),
@@ -1407,8 +1398,8 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
// Codex's `never` means "do not ask to escalate", not "grant every requested permission":
// only Full may synthesize approvals.
autoAcceptPermissions = approvalMode === "full";
- const selection = config.managed
- ? { model: turn.model, modelProvider: "openmaus_company" }
+ const selection = routed
+ ? { model: turn.model, modelProvider: routedProvider }
: config.authMode === "chatgpt-plan"
? { model: turn.model, modelProvider: "openai_chatgpt_plan" }
: decodeCodexSelection(turn.model);
@@ -1568,6 +1559,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const { version } = probe;
if (planAuth) return { state: "available", version, chatgptPlan: true, billing: "subscription", ...await planAuth.snapshot(), update: await codexReleaseUpdate(version, config.cli),
...(planWarning ? { warning: { title: "Check ChatGPT connection", message: planWarning } } : {}) };
+ if (config.endpoint) return { state: "available", version, authenticated: Boolean(input.environment.OPENMAUSBOT_CODEX_API_KEY && input.environment.CODEX_HOME), billing: "metered" };
if (config.managed) return { state: "available", version, authenticated: Boolean(input.environment.OPENMAUSBOT_COMPANY_API_KEY && input.environment.CODEX_HOME), billing: "metered" };
const previousCliVersion = modelsCliVersion;
modelsCliVersion = version;
@@ -1603,6 +1595,10 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
if (planSigningOut || disposed) throw new Error("This ChatGPT account is being disconnected.");
mkdirSync(join(planDirectory, "codex"), { recursive: true, mode: 0o700 });
providerArgs = chatgptPlanCodexArgs();
+ } else if (config.endpoint) {
+ if (!input.environment.OPENMAUSBOT_CODEX_API_KEY || !input.environment.CODEX_HOME) throw new Error("Direct API key or isolated Codex home is missing. Edit the endpoint in Settings.");
+ mkdirSync(input.environment.CODEX_HOME, { recursive: true, mode: 0o700 });
+ providerArgs = endpointCodexArgs(config.endpoint);
} else if (config.managed) {
if (!input.environment.OPENMAUSBOT_COMPANY_API_KEY || !input.environment.CODEX_HOME) {
throw new Error("Company model access is unavailable. Reconnect your organization; personal billing will not be used.");
@@ -1612,12 +1608,12 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const route = codexBackgroundRoute(models, smallModelsUsable(), options.fallback);
if (!route) throw new Error("Codex lists no model for background calls. Refresh models in Settings → Model providers → Codex.");
return runCodexBackgroundRoute(route, (id) => {
- const selection = planAuth || config.managed ? { model: id, modelProvider: null } : decodeCodexSelection(id);
+ const selection = planAuth || routed ? { model: id, modelProvider: null } : decodeCodexSelection(id);
return runCodexOneShot({
spawn: spawnCli, kill: killCliTree, cli: config.cli, env, prompt, options,
model: selection.model ?? id,
modelProvider: selection.modelProvider,
- providerArgs: planAuth || config.managed ? providerArgs : codexLocalProviderArgs(env, id),
+ providerArgs: planAuth || routed ? providerArgs : codexLocalProviderArgs(env, id),
describeError: (message) => {
const route: CodexRoute = planAuth ? "plan" : selection.modelProvider === OFFICIAL_CODEX_PROVIDER ? "own" : "other";
hidePlanRefusedModel(selection.model ?? id, message, route);
@@ -1640,38 +1636,40 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
...(startupModelRefresh ? { startupModelRefresh } : {}),
generateMemoryText,
...(plan ? { authenticationMethod: "browser-pkce" as const } : {}),
- startAuthentication: async () => {
- if (planUnavailable) throw new Error(planUnavailable);
- if (planSigningOut || disposed) throw new Error("This account is being disconnected. Wait before signing in again.");
- return (planAuth ?? authentication).start();
- },
- getAuthentication: async (flowId) => {
- const result = await (planAuth ?? authentication).get(flowId);
- if (planAuth && result.phase === "succeeded") planWarning = undefined;
- if (planAuth && result.phase === "succeeded" && !models.options.length) await refreshModels();
- return result;
- },
- cancelAuthentication: () => (planAuth ?? authentication).cancel(),
- signOut: async () => {
- if (!planAuth) {
- const mark = loginMark();
- await authentication.signOut();
- loginAccepted(mark);
- return;
- }
- planSigningOut = true;
- planGeneration++;
- try {
- const stopped = await Promise.all([...active.values()].map(({ stop }) => stop()));
- if (stopped.some(value => !value)) throw new Error("A ChatGPT task could not stop safely. Stop the task before signing out.");
- models = { default: "", options: [] };
- await planAuth.signOut();
- planWarning = undefined;
- } catch (error) {
- if ((error as { code?: string }).code !== "chatgpt_revocation_unconfirmed") throw error;
- planWarning = (error as Error).message;
- } finally { planSigningOut = false; }
- },
+ ...(!config.endpoint ? {
+ startAuthentication: async () => {
+ if (planUnavailable) throw new Error(planUnavailable);
+ if (planSigningOut || disposed) throw new Error("This account is being disconnected. Wait before signing in again.");
+ return (planAuth ?? authentication).start();
+ },
+ getAuthentication: async (flowId: string) => {
+ const result = await (planAuth ?? authentication).get(flowId);
+ if (planAuth && result.phase === "succeeded") planWarning = undefined;
+ if (planAuth && result.phase === "succeeded" && !models.options.length) await refreshModels();
+ return result;
+ },
+ cancelAuthentication: () => (planAuth ?? authentication).cancel(),
+ signOut: async () => {
+ if (!planAuth) {
+ const mark = loginMark();
+ await authentication.signOut();
+ loginAccepted(mark);
+ return;
+ }
+ planSigningOut = true;
+ planGeneration++;
+ try {
+ const stopped = await Promise.all([...active.values()].map(({ stop }) => stop()));
+ if (stopped.some(value => !value)) throw new Error("A ChatGPT task could not stop safely. Stop the task before signing out.");
+ models = { default: "", options: [] };
+ await planAuth.signOut();
+ planWarning = undefined;
+ } catch (error) {
+ if ((error as { code?: string }).code !== "chatgpt_revocation_unconfirmed") throw error;
+ planWarning = (error as Error).message;
+ } finally { planSigningOut = false; }
+ },
+ } : {}),
snapshot,
adapter: {
provider: DRIVER_KIND,
diff --git a/server/model-providers-docs.test.ts b/server/model-providers-docs.test.ts
index abcf96d544..12a8b4a711 100644
--- a/server/model-providers-docs.test.ts
+++ b/server/model-providers-docs.test.ts
@@ -118,7 +118,7 @@ describe("Claude Code section", () => {
const text = section("### Claude Code");
expect(text).toContain("add a **custom endpoint** in Settings → Engines, in the Claude card");
expect(text).toContain("It never reads or writes this computer's `~/.claude`, and the Claude Code on this computer keeps its own sign-in.");
- expect(text).toContain("Its bots run the model the endpoint serves. A bot that still has a Claude model selected runs the endpoint's main model instead.");
+ expect(text).toContain("Each bot can choose a different model from the endpoint's catalog.");
expect(text).toContain("The token is saved in OpenMausBot's own `config.json` and sent only to the base URL you enter. Removing an endpoint removes only that entry.");
});
});
diff --git a/server/routes/instances.ts b/server/routes/instances.ts
index 03e67b029b..655297f016 100644
--- a/server/routes/instances.ts
+++ b/server/routes/instances.ts
@@ -1,3 +1,5 @@
+import { agentEndpointAddress, discoverAgentEndpointModels, hasExplicitModel, isGatewayEndpoint } from "../agent-endpoint-models.ts";
+import { codexEndpointSchema, codexEndpointUpdateSchema, newCodexEndpoint, updateCodexEndpoint, withCodexEndpointInfo, isCodexEndpoint } from "../codex-endpoints.ts";
import { userError, userErrorFields } from "../user-errors.ts";
import { randomUUID } from "node:crypto";
import { providerIconError } from "../../shared/provider-icon.ts";
@@ -12,6 +14,7 @@ import {
claudeEndpointSchema,
claudeEndpointUpdateSchema,
newClaudeEndpoint,
+ isClaudeEndpoint,
updateClaudeEndpoint,
withClaudeEndpointInfo,
} from "../claude-endpoints.ts";
@@ -62,7 +65,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
botForThread, activeGroupTurnForBot,
} = deps;
const describeInstances = async () => hostedModels ? deps.describeInstances()
- : withEndpointUrls(withClaudeEndpointInfo(await deps.describeInstances(), cfg.instances ?? {}), cfg.instances ?? {});
+ : withEndpointUrls(withCodexEndpointInfo(withClaudeEndpointInfo(await deps.describeInstances(), cfg.instances ?? {}), cfg.instances ?? {}), cfg.instances ?? {});
/** Bots, their backups and threads, the new-bot default, or a turn running on it: a provider in use can't go away. */
const providerInUse = (instanceId: string): boolean => cfg.defaultModelSelection?.instanceId === instanceId || store.bots.some((bot) =>
bot.modelSelection.instanceId === instanceId || bot.fallback?.some(candidate => candidate.instanceId === instanceId) || store.tasks(bot.id).some((task) => task.modelSelection?.instanceId === instanceId)) ||
@@ -170,16 +173,18 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
} finally { providerConfigBusy.set(false); }
}
- if (method === "POST" && path === "/api/instances/claude-endpoint") {
+ if (method === "POST" && (path === "/api/instances/claude-endpoint" || path === "/api/instances/codex-endpoint")) {
if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {
return json(res, 415, { error: "content-type must be application/json" });
}
- const parsed = claudeEndpointSchema.safeParse(await readBody(req, 16384));
- if (!parsed.success) return json(res, 400, { error: "Enter a name, an http(s) base URL, a token and the model the endpoint serves." });
+ const codex = path.endsWith("/codex-endpoint");
+ const parsed = (codex ? codexEndpointSchema : claudeEndpointSchema).safeParse(await readBody(req, 16384));
+ if (!parsed.success) return json(res, 400, { error: codex ? parsed.error.issues[0]?.message ?? "Check the endpoint settings." : "Enter a name, an http(s) base URL, an API key." });
if (providerConfigBusy.get()) return json(res, 409, { error: "provider settings are already being updated" });
providerConfigBusy.set(true);
try {
- const { instanceId, instances } = newClaudeEndpoint(cfg, parsed.data);
+ const { instanceId, instances } = (codex ? newCodexEndpoint : newClaudeEndpoint)(cfg, parsed.data);
+ if (!parsed.data.model) await discoverAgentEndpointModels(instances[instanceId]);
await persistProviderInstance(instanceId, instances);
return json(res, 201, { instanceId, instances: await describeInstances() });
} catch (error) {
@@ -188,14 +193,15 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
} finally { providerConfigBusy.set(false); }
}
- const endpointPatch = /^\/api\/instances\/([\w.-]+)\/claude-endpoint$/.exec(path);
+ const endpointPatch = /^\/api\/instances\/([\w.-]+)\/(claude|codex)-endpoint$/.exec(path);
if (method === "PATCH" && endpointPatch) {
if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {
return json(res, 415, { error: "content-type must be application/json" });
}
const instanceId = endpointPatch[1];
- const parsed = claudeEndpointUpdateSchema.safeParse(await readBody(req, 16384));
- if (!parsed.success) return json(res, 400, { error: "Check the address, token and model ids." });
+ const codex = endpointPatch[2] === "codex";
+ const parsed = (codex ? codexEndpointUpdateSchema : claudeEndpointUpdateSchema).safeParse(await readBody(req, 16384));
+ if (!parsed.success) return json(res, 400, { error: "Check the address and API key." });
if (providerConfigBusy.get()) return json(res, 409, { error: "provider settings are already being updated" });
if (busyProviderSelections().some((selection) => selection.instanceId === instanceId)) {
return json(res, 409, { error: "Wait for bots using this endpoint to finish before changing its settings." });
@@ -203,7 +209,10 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
providerConfigBusy.set(true);
providerInstancesChanging.add(instanceId);
try {
- const { instances } = updateClaudeEndpoint(cfg, instanceId, parsed.data);
+ const { instances } = (codex ? updateCodexEndpoint : updateClaudeEndpoint)(cfg, instanceId, parsed.data);
+ const previous = persistableInstanceConfigs(cfg)[instanceId];
+ const addressChanged = agentEndpointAddress(previous) !== agentEndpointAddress(instances[instanceId]);
+ if (!parsed.data.model && !hasExplicitModel(previous) && (parsed.data.token !== undefined || addressChanged)) await discoverAgentEndpointModels(instances[instanceId]);
await persistProviderInstance(instanceId, instances);
return json(res, 200, { instances: await describeInstances() });
} catch (error) {
@@ -255,6 +264,16 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
return json(res, 200, await (deps.checkInstance ?? checkEngine)(instance));
}
if (action === "refresh-models") {
+ const endpoint = persistableInstanceConfigs(cfg)[instanceId];
+ if (endpoint && (isClaudeEndpoint(endpoint) || isCodexEndpoint(endpoint)) && isGatewayEndpoint(endpoint) && !hasExplicitModel(endpoint)) {
+ if (providerConfigBusy.get()) return json(res, 409, { error: "provider settings are already being updated" });
+ providerConfigBusy.set(true);
+ try {
+ const instances = persistableInstanceConfigs(cfg);
+ await discoverAgentEndpointModels(instances[instanceId]);
+ await persistProviderInstance(instanceId, instances);
+ } finally { providerConfigBusy.set(false); }
+ }
if (!(await registry.refreshModels(instanceId))) return json(res, 404, { error: "unknown instance" });
return json(res, 200, { instances: await describeInstances() });
}
@@ -434,8 +453,8 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
if (!Object.hasOwn(instances, instanceId)) return json(res, 404, { error: "unknown instance" });
const addedChatgpt = instances[instanceId].driver === "codex" && instanceId.startsWith("chatgpt-");
const addedAntigravity = instances[instanceId].driver === "antigravityAgent" && instanceId.startsWith("antigravity-");
- if (!addedChatgpt && !addedAntigravity && !isAddedEndpoint(instanceId, instances[instanceId]) && (instances[instanceId].driver !== "claudeAgent" || instanceId === "claude")) {
- return json(res, 400, { error: "Only added Claude, ChatGPT, and Antigravity accounts and OpenAI-compatible endpoints can be removed here." });
+ if (!addedChatgpt && !addedAntigravity && !isCodexEndpoint(instances[instanceId]) && !isAddedEndpoint(instanceId, instances[instanceId]) && (instances[instanceId].driver !== "claudeAgent" || instanceId === "claude")) {
+ return json(res, 400, { error: "Only added accounts and custom endpoints can be removed here." });
}
if (providerInUse(instanceId)) {
return json(res, 409, { error: "Choose another account for the bots and default model using this account before removing it." });
diff --git a/shared/claude-endpoint.ts b/shared/claude-endpoint.ts
index 95215c14fa..dd6180c10e 100644
--- a/shared/claude-endpoint.ts
+++ b/shared/claude-endpoint.ts
@@ -9,8 +9,16 @@ export interface ClaudeEndpointInfo {
smallFastModel: string;
}
+/** A direct Codex Responses API connection; the key is write-only. */
+export interface CodexEndpointInfo {
+ baseUrl: string;
+ models: string[];
+ tokenSaved: boolean;
+}
+
/** The instance fields only a custom endpoint has. */
export interface InstanceEndpointInfo {
claudeEndpoint?: ClaudeEndpointInfo;
+ codexEndpoint?: CodexEndpointInfo;
url?: string;
}
diff --git a/src/components/AgentEndpoints.dom.test.ts b/src/components/AgentEndpoints.dom.test.ts
new file mode 100644
index 0000000000..ac352decd0
--- /dev/null
+++ b/src/components/AgentEndpoints.dom.test.ts
@@ -0,0 +1,82 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+const fixture = vi.hoisted(() => ({ posts: [] as Array<{ path: string; body: Record<string, string> }> }));
+vi.mock("@/state/store", () => ({
+ useStore: () => ({ state: { instances: [], bots: [] }, dispatch: () => {} }),
+ api: async (path: string, init: { body: string }) => { fixture.posts.push({ path, body: JSON.parse(init.body) }); return {}; },
+}));
+import { ClaudeEndpoints, CodexEndpoints } from "./ClaudeEndpoints";
+
+let container: HTMLDivElement, root: Root;
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ fixture.posts = [];
+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);
+});
+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.unstubAllGlobals(); });
+async function click(label: string) {
+ const button = [...container.querySelectorAll("button")].find(button => button.textContent === label);
+ expect(button).toBeTruthy();
+ await act(async () => button!.click());
+}
+async function input(label: string, value: string) {
+ const field = container.querySelector<HTMLInputElement>(`input[aria-label="${label}"]`)!;
+ expect(field).toBeTruthy();
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(field, value);
+ field.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+it("starts the Claude form empty, with Anthropic's URL only as a placeholder", async () => {
+ await act(async () => root.render(createElement(ClaudeEndpoints)));
+ await click("Add endpoint");
+ expect(container.querySelector("select")).toBeNull();
+ const baseUrl = container.querySelector<HTMLInputElement>('input[aria-label="Base URL"]')!;
+ expect(baseUrl.value).toBe("");
+ expect(baseUrl.placeholder).toBe("https://api.anthropic.com");
+ expect(container.querySelector<HTMLInputElement>('input[aria-label="Name"]')!.value).toBe("");
+ await input("Name", "Fixture host");
+ await input("Token", "fixture-api-key");
+ const save = [...container.querySelectorAll("button")].find(button => button.textContent === "Save")!;
+ expect(save.disabled).toBe(true);
+ expect(fixture.posts).toHaveLength(0);
+});
+it("saves OpenAI for Codex when the URL is left empty, without an OAuth step", async () => {
+ await act(async () => root.render(createElement(CodexEndpoints)));
+ await click("Add endpoint");
+ const baseUrl = container.querySelector<HTMLInputElement>('input[aria-label="Base URL"]')!;
+ expect(baseUrl.value).toBe("");
+ expect(baseUrl.placeholder).toBe("https://api.openai.com/v1");
+ await input("Name", "OpenAI");
+ await input("Token", "fixture-api-key");
+ await click("Save");
+ expect(fixture.posts).toEqual([{ path: "/api/instances/codex-endpoint", body: { displayName: "OpenAI", baseUrl: "https://api.openai.com/v1", token: "fixture-api-key" } }]);
+});
+it.each([
+ { Component: ClaudeEndpoints, path: "/api/instances/claude-endpoint" },
+ { Component: CodexEndpoints, path: "/api/instances/codex-endpoint" },
+])("sends a typed model for a host without a model list ($path)", async ({ Component, path }) => {
+ await act(async () => root.render(createElement(Component)));
+ await click("Add endpoint");
+ await input("Name", "Fixture host");
+ await input("Base URL", "https://host.example/anthropic");
+ await input("Token", "fixture-api-key");
+ await input("Model", "fixture-model");
+ await click("Save");
+ expect(fixture.posts).toEqual([{ path, body: { displayName: "Fixture host", baseUrl: "https://host.example/anthropic", token: "fixture-api-key", model: "fixture-model" } }]);
+});
+it.each([
+ { Component: ClaudeEndpoints, path: "/api/instances/claude-endpoint" },
+ { Component: CodexEndpoints, path: "/api/instances/codex-endpoint" },
+])("saves a custom URL directly from $path", async ({ Component, path }) => {
+ await act(async () => root.render(createElement(Component)));
+ await click("Add endpoint");
+ await input("Name", "My CLIProxyAPI");
+ await input("Base URL", "https://gateway.example/v1");
+ await input("Token", "fixture-proxy-key");
+ await click("Save");
+ expect(fixture.posts).toEqual([{ path, body: { displayName: "My CLIProxyAPI", baseUrl: "https://gateway.example/v1", token: "fixture-proxy-key" } }]);
+});
diff --git a/src/components/ClaudeEndpoints.test.ts b/src/components/ClaudeEndpoints.test.ts
index 04a6ed52e1..a992b5bbd0 100644
--- a/src/components/ClaudeEndpoints.test.ts
+++ b/src/components/ClaudeEndpoints.test.ts
@@ -43,12 +43,12 @@ describe("Claude custom endpoints settings", () => {
expect(html).toContain("Add endpoint");
});
- it("lists each endpoint's address and models, and never its token", () => {
+ it("lists each endpoint's address, and never its token", () => {
const html = render([endpoint()]);
expect(html).toContain("DeepSeek");
expect(html).toContain("https://api.deepseek.test/anthropic");
- expect(html).toContain("deepseek-chat");
- expect(html).toContain("deepseek-reasoner");
+ expect(html).not.toContain("deepseek-chat");
+ expect(html).not.toContain("deepseek-reasoner");
expect(html).toContain("Edit");
expect(html).toContain("Remove DeepSeek");
// The API answer carries only whether a token is saved, so no field holds one.
diff --git a/src/components/ClaudeEndpoints.tsx b/src/components/ClaudeEndpoints.tsx
index d6db841a9e..c1616c5f78 100644
--- a/src/components/ClaudeEndpoints.tsx
+++ b/src/components/ClaudeEndpoints.tsx
@@ -7,37 +7,29 @@ import { cn } from "@/lib/cn";
import { ConfirmDialog } from "./ConfirmDialog";
import { KEY_FIELD } from "./keys/KeyRow";
+type Engine = "claude" | "codex";
+// Placeholders only: an Anthropic key already has its own engine in Settings → Keys. An empty Codex URL means OpenAI.
+const OFFICIAL = { claude: { url: "https://api.anthropic.com", model: "deepseek-chat" }, codex: { url: "https://api.openai.com/v1", model: "" } };
const INPUT = cn(KEY_FIELD, "font-sans");
-const MAPPINGS = [
- ["opusModel", "claudeEndpoints.opus"],
- ["sonnetModel", "claudeEndpoints.sonnet"],
- ["haikuModel", "claudeEndpoints.haiku"],
-] as const;
-
interface Draft {
name: string;
url: string;
token: string;
model: string;
- opusModel: string;
- sonnetModel: string;
- haikuModel: string;
}
-const EMPTY: Draft = { name: "", url: "", token: "", model: "", opusModel: "", sonnetModel: "", haikuModel: "" };
+const EMPTY: Draft = { name: "", url: "", token: "", model: "" };
const draftOf = (instance: InstanceInfo): Draft => ({
name: instance.displayName,
- url: instance.claudeEndpoint?.baseUrl ?? "",
+ url: (instance.claudeEndpoint ?? instance.codexEndpoint)?.baseUrl ?? "",
token: "",
- model: instance.claudeEndpoint?.models[0] ?? "",
- opusModel: instance.claudeEndpoint?.opusModel ?? "",
- sonnetModel: instance.claudeEndpoint?.sonnetModel ?? "",
- haikuModel: instance.claudeEndpoint?.haikuModel ?? "",
+ model: "",
});
-function EndpointForm({ instance, onDone }: { instance?: InstanceInfo; onDone: () => void }) {
+function EndpointForm({ instance, engine, onDone }: { instance?: InstanceInfo; engine: Engine; onDone: () => void }) {
const { dispatch } = useStore();
+ const official = OFFICIAL[engine];
const [draft, setDraft] = useState<Draft>(instance ? draftOf(instance) : EMPTY);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -47,7 +39,7 @@ function EndpointForm({ instance, onDone }: { instance?: InstanceInfo; onDone: (
spellCheck: false,
disabled: saving,
});
- const ready = Boolean(draft.name.trim() && draft.url.trim() && draft.model.trim() && (instance || draft.token.trim()));
+ const ready = Boolean(draft.name.trim() && (draft.url.trim() || engine === "codex") && (instance || draft.token.trim()));
const save = async () => {
if (saving || !ready) return;
@@ -55,17 +47,15 @@ function EndpointForm({ instance, onDone }: { instance?: InstanceInfo; onDone: (
setError(null);
const body = {
displayName: draft.name.trim(),
- baseUrl: draft.url.trim(),
- model: draft.model.trim(),
- opusModel: draft.opusModel.trim(),
- sonnetModel: draft.sonnetModel.trim(),
- haikuModel: draft.haikuModel.trim(),
+ baseUrl: draft.url.trim() || official.url,
...(draft.token.trim() ? { token: draft.token.trim() } : {}),
+ // Empty lets the server read the host's model list.
+ ...(draft.model.trim() ? { model: draft.model.trim() } : {}),
};
try {
const result = instance
- ? await api(`/api/instances/${encodeURIComponent(instance.instanceId)}/claude-endpoint`, { method: "PATCH", body: JSON.stringify(body) })
- : await api("/api/instances/claude-endpoint", { method: "POST", body: JSON.stringify(body) });
+ ? await api(`/api/instances/${encodeURIComponent(instance.instanceId)}/${engine}-endpoint`, { method: "PATCH", body: JSON.stringify(body) })
+ : await api(`/api/instances/${engine}-endpoint`, { method: "POST", body: JSON.stringify(body) });
if (Array.isArray(result.instances)) dispatch({ type: "instances", instances: result.instances });
onDone();
} catch (cause) {
@@ -76,15 +66,16 @@ function EndpointForm({ instance, onDone }: { instance?: InstanceInfo; onDone: (
};
return (
- <form data-claude-endpoint-form={instance?.instanceId ?? "new"} className="flex flex-col gap-2 rounded-xl border border-hairline/50 bg-inset p-3"
+ <form data-claude-endpoint-form={engine === "claude" ? instance?.instanceId ?? "new" : undefined} data-codex-endpoint-form={engine === "codex" ? instance?.instanceId ?? "new" : undefined} className="flex flex-col gap-2 rounded-xl border border-hairline/50 bg-inset p-3"
onSubmit={(event) => { event.preventDefault(); void save(); }}>
+ <p className="text-[12px] leading-4 text-ink-secondary">{t(engine === "codex" ? "agentEndpoints.responses" : "agentEndpoints.messages")}</p>
<label className="flex flex-col gap-1 text-[12px] font-medium text-ink">
{t("claudeEndpoints.name")}
<input {...field("name")} maxLength={80} autoFocus aria-label={t("claudeEndpoints.name")} className={INPUT} />
</label>
<label className="flex flex-col gap-1 text-[12px] font-medium text-ink">
{t("claudeEndpoints.baseUrl")}
- <input {...field("url")} type="url" maxLength={2048} placeholder="https://api.example.com/anthropic" aria-label={t("claudeEndpoints.baseUrl")} className={cn(INPUT, "font-mono")} />
+ <input {...field("url")} type="url" maxLength={2048} placeholder={official.url} aria-label={t("claudeEndpoints.baseUrl")} className={cn(INPUT, "font-mono")} />
</label>
<label className="flex flex-col gap-1 text-[12px] font-medium text-ink">
{t("claudeEndpoints.token")}
@@ -93,18 +84,9 @@ function EndpointForm({ instance, onDone }: { instance?: InstanceInfo; onDone: (
</label>
<label className="flex flex-col gap-1 text-[12px] font-medium text-ink">
{t("claudeEndpoints.model")}
- <input {...field("model")} maxLength={160} placeholder="deepseek-chat" aria-label={t("claudeEndpoints.model")} className={cn(INPUT, "font-mono")} />
+ <input {...field("model")} maxLength={160} placeholder={official.model} aria-label={t("claudeEndpoints.model")} className={cn(INPUT, "font-mono")} />
</label>
<p className="text-[12px] leading-4 text-ink-secondary">{t("claudeEndpoints.modelHint")}</p>
- <details className="text-[12px] text-ink-secondary">
- <summary className="cursor-pointer select-none hover:text-ink">{t("claudeEndpoints.mappings")}</summary>
- <div className="mt-2 flex flex-col gap-1.5">
- {MAPPINGS.map(([key, label]) => (
- <input key={key} {...field(key)} maxLength={160} aria-label={t(label)} placeholder={t(label)} className={cn(INPUT, "font-mono")} />
- ))}
- <p className="leading-relaxed">{t("claudeEndpoints.mappingsHint")}</p>
- </div>
- </details>
{error && <p role="alert" className="text-[12px] text-danger">{error}</p>}
<div className="flex justify-end gap-2">
<button type="button" onClick={onDone} disabled={saving} className="rounded-lg px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-control disabled:opacity-50">{t("common.cancel")}</button>
@@ -124,7 +106,7 @@ function EndpointRow({ instance, onEdit }: { instance: InstanceInfo; onEdit: ()
const usedBy = state.bots.filter((bot) => bot.modelSelection.instanceId === instance.instanceId
|| bot.fallback?.some((candidate) => candidate.instanceId === instance.instanceId)
|| bot.tasks?.some((task) => task.modelSelection?.instanceId === instance.instanceId)).length;
- const endpoint = instance.claudeEndpoint;
+ const endpoint = instance.claudeEndpoint ?? instance.codexEndpoint;
const remove = async () => {
setConfirming(false);
setRemoving(true);
@@ -139,12 +121,11 @@ function EndpointRow({ instance, onEdit }: { instance: InstanceInfo; onEdit: ()
}
};
return (
- <li data-claude-endpoint={instance.instanceId} className="px-3 py-2.5">
+ <li data-claude-endpoint={instance.claudeEndpoint ? instance.instanceId : undefined} data-codex-endpoint={instance.codexEndpoint ? instance.instanceId : undefined} className="px-3 py-2.5">
<div className="flex min-h-9 items-center gap-3">
<div className="min-w-0 flex-1">
<div className="truncate text-[13px] font-medium text-ink" title={instance.displayName}>{instance.displayName}</div>
<div className="truncate font-mono text-[11px] text-ink-secondary" title={endpoint?.baseUrl}>{endpoint?.baseUrl}</div>
- <div className="truncate text-[12px] text-ink-secondary">{endpoint?.models.join(" · ")}</div>
</div>
<button type="button" onClick={onEdit} disabled={removing} className="shrink-0 rounded-lg px-2.5 py-1.5 text-[12px] font-medium text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50">
{t("claudeEndpoints.edit")}
@@ -164,27 +145,28 @@ function EndpointRow({ instance, onEdit }: { instance: InstanceInfo; onEdit: ()
);
}
-/** Custom Claude endpoints: their own engines, so this computer's Claude Code and its sign-in stay as they are. */
-export function ClaudeEndpoints() {
+function AgentEndpoints({ engine }: { engine: Engine }) {
const { state } = useStore();
- const endpoints = state.instances.filter((instance) => instance.claudeEndpoint);
+ const endpoints = state.instances.filter((instance) => engine === "claude" ? instance.claudeEndpoint : instance.codexEndpoint);
const [open, setOpen] = useState<string | null>(null);
return (
- <div data-claude-endpoints className="mt-3 space-y-2">
- <div className="text-[13px] leading-[18px] text-ink">{t("claudeEndpoints.title")}</div>
- <p className="text-[12px] leading-4 text-ink-secondary">{t("claudeEndpoints.hint")}</p>
+ <div data-claude-endpoints={engine === "claude" ? "" : undefined} data-codex-endpoints={engine === "codex" ? "" : undefined} className="mt-3 space-y-2">
+ <div className="text-[13px] leading-[18px] text-ink">{t(engine === "claude" ? "claudeEndpoints.title" : "agentEndpoints.codexTitle")}</div>
+ <p className="text-[12px] leading-4 text-ink-secondary">{t(engine === "claude" ? "claudeEndpoints.hint" : "agentEndpoints.codexHint")}</p>
{endpoints.length === 0
? <p className="text-[12px] leading-4 text-ink-secondary">{t("claudeEndpoints.empty")}</p>
: <ul className="divide-y divide-hairline/40 rounded-xl border border-hairline/50 bg-panel/40">
{endpoints.map((instance) => open === instance.instanceId
- ? <li key={instance.instanceId} className="p-3"><EndpointForm instance={instance} onDone={() => setOpen(null)} /></li>
+ ? <li key={instance.instanceId} className="p-3"><EndpointForm engine={engine} instance={instance} onDone={() => setOpen(null)} /></li>
: <EndpointRow key={instance.instanceId} instance={instance} onEdit={() => setOpen(instance.instanceId)} />)}
</ul>}
{open === "new"
- ? <EndpointForm onDone={() => setOpen(null)} />
+ ? <EndpointForm engine={engine} onDone={() => setOpen(null)} />
: <button type="button" onClick={() => setOpen("new")} className="flex min-h-8 w-fit items-center gap-1.5 rounded-lg px-2 py-1.5 text-[13px] font-medium text-ink-secondary outline-none hover:bg-control hover:text-ink focus-visible:ring-2 focus-visible:ring-accent">
<Plus size={14} />{t("claudeEndpoints.add")}
</button>}
</div>
);
-}
\ No newline at end of file
+}
+export function ClaudeEndpoints() { return <AgentEndpoints engine="claude" />; }
+export function CodexEndpoints() { return <AgentEndpoints engine="codex" />; }
diff --git a/src/components/EnginesSettings.tsx b/src/components/EnginesSettings.tsx
index f866cab860..5508d0a41d 100644
--- a/src/components/EnginesSettings.tsx
+++ b/src/components/EnginesSettings.tsx
@@ -10,7 +10,7 @@ import { ApiKeyEngineManage, EngineSetup, EngineUpdateNotice, EngineWarningNotic
import { AppCopyNotice } from "./EngineAppCopy";
import { forgetAppCopySwitches } from "@/state/engine-install";
import { AccountsCard, AddAccount, accountGroupOf, accountsReady, type AccountGroup } from "./EngineAccounts";
-import { ClaudeEndpoints } from "./ClaudeEndpoints";
+import { ClaudeEndpoints, CodexEndpoints } from "./ClaudeEndpoints";
import { DEVICE_SIGN_IN_COPY, deviceSignInProvider } from "./DeviceSignIn";
import { AntigravityFreeSpace } from "./AntigravityFreeSpace";
import { CacheKeepWarmSettings } from "./CacheKeepWarmSettings";
@@ -387,7 +387,7 @@ function EngineRow({ instance, bare = false }: { instance: InstanceInfo; bare?:
return (
<EngineCard instance={instance} bare={bare}>
{policyNote}
- {!engineReady(instance) && <EngineSetup instance={instance} intent={instance.access === "custom" ? "inject" : "cloud"} unframed />}
+ {!engineReady(instance) && <EngineSetup instance={instance} intent={instance.access === "custom" ? "inject" : "cloud"} description={instance.codexEndpoint ? t("agentEndpoints.codexHint") : undefined} unframed />}
{engineReady(instance) && <ApiKeyEngineManage instance={instance} className="mt-3" />}
{/* The setup panel that first said so is gone once the engine is Ready. */}
{engineReady(instance) && <AppCopyNotice instance={instance} className="mt-3" />}
@@ -518,7 +518,7 @@ export function EnginesSettings({ simple = false, more }: { simple?: boolean; mo
const { state } = useStore();
// Leaving Settings ends the "now uses the copy OpenMausBot installed" lines.
useEffect(() => forgetAppCopySwitches, []);
- const listed = state.instances.filter((i) => i.readOnly || i.cli !== undefined || i.cliDefault !== undefined || i.snapshot.state === "unavailable" || isApiKeyEngine(i) || i.claudeEndpoint !== undefined);
+ const listed = state.instances.filter((i) => i.readOnly || i.cli !== undefined || i.cliDefault !== undefined || i.snapshot.state === "unavailable" || isApiKeyEngine(i) || i.claudeEndpoint !== undefined || i.codexEndpoint !== undefined);
// A provider's accounts share one card, which takes the place of its first account.
const groups = new Map<AccountGroup, InstanceInfo[]>();
for (const instance of listed) {
@@ -533,19 +533,21 @@ export function EnginesSettings({ simple = false, more }: { simple?: boolean; mo
// A hidden ordinary Claude instance takes its card, and the endpoint section inside it, away. A hosted
// workspace lists every engine read-only and refuses instance changes, so there the section has no Add.
const hostedWorkspace = rows.length > 0 && rows.every((instance) => instance.readOnly);
+ const orphanCodexEndpoints = !groups.has("chatgpt") && !hostedWorkspace;
const orphanEndpoints = !groups.has("claude") && !hostedWorkspace;
const isReady = (instance: InstanceInfo) => { const group = groupOf(instance); return group ? accountsReady(groups.get(group)!) : engineReady(instance); };
const renderEngine = (instance: InstanceInfo, bare = false) => {
const group = groupOf(instance);
return group
? <AccountsCard group={group} accounts={groups.get(group)!} bare={bare}
- advanced={<>{group === "claude" && <ClaudeEndpoints />}<EngineAdvanced instance={instance} /></>} />
+ advanced={<>{group === "claude" ? <ClaudeEndpoints /> : <CodexEndpoints />}<EngineAdvanced instance={instance} /></>} />
: <EngineRow instance={instance} bare={bare} />;
};
if (simple && more) return <>
<SimpleEngines rows={rows} isReady={isReady} renderEngine={renderEngine} more={more} />
{orphanEndpoints && <div className="px-4"><ClaudeEndpoints /></div>}
+ {orphanCodexEndpoints && <div className="px-4"><CodexEndpoints /></div>}
</>;
return (
@@ -559,6 +561,7 @@ export function EnginesSettings({ simple = false, more }: { simple?: boolean; mo
</div>
<EngineSections instances={rows} isReady={isReady} renderEngine={renderEngine} />
{orphanEndpoints && <div className="px-4"><ClaudeEndpoints /></div>}
+ {orphanCodexEndpoints && <div className="px-4"><CodexEndpoints /></div>}
<HiddenEngines />
<CacheKeepWarmSettings />
</div>
diff --git a/src/locales/en.json b/src/locales/en.json
index 775f073a84..d884595449 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -4435,7 +4435,7 @@
"claudeEndpoints.token": "Token",
"claudeEndpoints.tokenKeep": "Leave empty to keep the saved token",
"claudeEndpoints.model": "Model",
- "claudeEndpoints.modelHint": "The model id the endpoint serves, such as deepseek-chat. Bots on this endpoint use it unless you pick another of its models.",
+ "claudeEndpoints.modelHint": "Optional. Leave it empty and OpenMausBot reads the host's model list; OpenAI and Anthropic use the standard list. Type a model when the host doesn't list its models. Each bot then picks its own model.",
"claudeEndpoints.mappings": "Model mappings (optional)",
"claudeEndpoints.mappingsHint": "Which model the endpoint uses for Opus, Sonnet and Haiku work.",
"claudeEndpoints.opus": "Opus model",
@@ -9693,6 +9693,10 @@
"imageGen.key.openrouter": "OpenRouter API key",
"server.voice.noNoteNoVoice": "No voice note with this reply: this bot has no voice set up yet.",
"server.voice.noNoteFailed": "No voice note with this reply: the voice couldn't be made ({reason}).",
+ "agentEndpoints.responses": "Uses an API key without OAuth. The gateway must support streaming Responses (/v1/responses), including tool calls. Chat Completions alone is not enough. Use HTTPS or a secure tunnel to localhost.",
+ "agentEndpoints.messages": "Uses an API key without OAuth. The gateway must support Anthropic Messages (/v1/messages), including streaming and tool calls. HTTP sends your key unencrypted; prefer HTTPS or a secure tunnel.",
+ "agentEndpoints.codexTitle": "Codex direct API",
+ "agentEndpoints.codexHint": "Run the native Codex agent on an API key: OpenAI, or a gateway that speaks the Responses API. Each connection has its own key and Codex settings, and the provider behind the URL bills the usage.",
"server.voice.turnEnded": "I stopped before finishing: {reason}",
"phone.code.e2e.scan": "Open the {app} app on your phone and scan.",
"phone.code.e2e.wifi": "This Wi-Fi",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 821130470c..caf2bb5ffc 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -4185,7 +4185,7 @@
"claudeEndpoints.token": "Token",
"claudeEndpoints.tokenKeep": "Deixe em branco para manter o token salvo",
"claudeEndpoints.model": "Modelo",
- "claudeEndpoints.modelHint": "O ID do modelo que o endpoint oferece, como deepseek-chat. Os bots deste endpoint usam esse modelo, a menos que você escolha outro dos modelos dele.",
+ "claudeEndpoints.modelHint": "Opcional. Deixe em branco e o OpenMausBot lê a lista de modelos do host; OpenAI e Anthropic usam a lista padrão. Digite um modelo quando o host não listar os modelos dele. Depois, cada bot escolhe o próprio modelo.",
"claudeEndpoints.mappings": "Mapeamento de modelos (opcional)",
"claudeEndpoints.mappingsHint": "Qual modelo o endpoint usa para tarefas do Opus, do Sonnet e do Haiku.",
"claudeEndpoints.opus": "Modelo para Opus",
@@ -9683,6 +9683,10 @@
"connectedWorkspaces.forgetName": "Esquecer {name}",
"connectedWorkspaces.forgetError": "Não foi possível esquecer o ambiente. Tente novamente.",
"connectedWorkspaces.createError": "Não foi possível criar o ambiente. Confira a pasta de dados e tente novamente.",
+ "agentEndpoints.responses": "Usa uma chave de API sem OAuth. O gateway deve oferecer suporte à API Responses (/v1/responses) com streaming e chamadas de ferramentas. Apenas Chat Completions não é suficiente. Use HTTPS ou um túnel seguro para localhost.",
+ "agentEndpoints.messages": "Usa uma chave de API sem OAuth. O gateway deve oferecer suporte à API Messages da Anthropic (/v1/messages) com streaming e chamadas de ferramentas. HTTP envia sua chave sem criptografia; prefira HTTPS ou um túnel seguro.",
+ "agentEndpoints.codexTitle": "API direta do Codex",
+ "agentEndpoints.codexHint": "Rode o agente nativo do Codex com uma chave de API: OpenAI ou um gateway compatível com a API Responses. Cada conexão tem chave e configurações do Codex próprias, e o provedor por trás da URL cobra pelo uso.",
"phone.code.e2e.scan": "Abra o app {app} no celular e escaneie.",
"phone.code.e2e.wifi": "Este Wi-Fi",
"phone.code.e2e.tailscale": "Tailscale",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index e6cf75fefa..faa0250b3c 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -27741,7 +27741,7 @@
"claudeEndpoints.token": "d2089be672953d1136faa84079af1b6f3967fed8932dabffba3032d30e3c0618",
"claudeEndpoints.tokenKeep": "9ed9a81a29067877a6745d445b0af73c94f943474ba461ab6a8b2ea92fd0b121",
"claudeEndpoints.model": "5e2c614c23f02239bc03c6c04fcb681950f9e72bf8fdff6be79c79841cbb10c0",
- "claudeEndpoints.modelHint": "d9c4b5f7fe88cdbb0b21fdd08122a186287346b8a283e7b22258dc7b9695b2be",
+ "claudeEndpoints.modelHint": "251d0b60c5236ccedc827f1669235d088e41997fe6d0db572ca8622b1fe6a912",
"claudeEndpoints.mappings": "9ef9eba4097d66d36a5705cd4d51b7044b0e07da1829eb759c359ffcde40c7ec",
"claudeEndpoints.mappingsHint": "2a55beedc91b232870585095ee96868e2f878dc29b9cfcc6a78ce825c618b7ff",
"claudeEndpoints.opus": "c334b99f1817421f9371293c418140e85b28ec64c9992be616ea4efb8364c0a4",
@@ -33151,6 +33151,10 @@
"connectedWorkspaces.forgetName": "aa553b0835130001c7cafd2f2785cc46b858e78284db11b1a780e7d8580cfef4",
"connectedWorkspaces.forgetError": "6426192c4c32258117650b57029d6bb95102ab0eede1967d962a750817df5f85",
"connectedWorkspaces.createError": "d6393fe1d84bccf5308d15cec7b87cba70c84c7cc098403c58067ad540709763",
+ "agentEndpoints.responses": "a5b94e2daf77c066a9e04639acfc6e5469ff099f8740454b8e6aee015518ec3e",
+ "agentEndpoints.messages": "87c79df077f74c8cd652e38b38c31813de114c7a653af469098847ff0b83c784",
+ "agentEndpoints.codexTitle": "f538b4b1573cac1d66f8f11e7e528fbc71f20c2732df67ba81be89588522fb51",
+ "agentEndpoints.codexHint": "2b1afcbf7bc1ab8970583399c941b7234d04f4f67949149c2600537c85b991ce",
"remote.devices.paused": "112eb547befc47325095c5e306877b631e952dd3a6ac70053966d11699acef21",
"chat.notice.commandCodeAccountRefused": "36ca5c5fb8c40fc640ea71abdac2b30f885fb40abae34737163d55a43f015f15",
"phone.code.e2e.scan": "b8d6ef15cdf921ee0c8b59acfe031a46523f0de227e62161b9a401a5d6c4a974",
@@ -47440,7 +47444,6 @@
"claudeEndpoints.token": "d2089be672953d1136faa84079af1b6f3967fed8932dabffba3032d30e3c0618",
"claudeEndpoints.tokenKeep": "9ed9a81a29067877a6745d445b0af73c94f943474ba461ab6a8b2ea92fd0b121",
"claudeEndpoints.model": "5e2c614c23f02239bc03c6c04fcb681950f9e72bf8fdff6be79c79841cbb10c0",
- "claudeEndpoints.modelHint": "d9c4b5f7fe88cdbb0b21fdd08122a186287346b8a283e7b22258dc7b9695b2be",
"claudeEndpoints.mappings": "9ef9eba4097d66d36a5705cd4d51b7044b0e07da1829eb759c359ffcde40c7ec",
"claudeEndpoints.mappingsHint": "2a55beedc91b232870585095ee96868e2f878dc29b9cfcc6a78ce825c618b7ff",
"claudeEndpoints.opus": "c334b99f1817421f9371293c418140e85b28ec64c9992be616ea4efb8364c0a4",
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 36d04c73a0..b49b8c1be0 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -4434,7 +4434,6 @@
"claudeEndpoints.token": "權杖",
"claudeEndpoints.tokenKeep": "留空以保留已儲存的權杖",
"claudeEndpoints.model": "模型",
- "claudeEndpoints.modelHint": "端點提供的模型 ID,例如 deepseek-chat。除非你選擇它的其他模型,否則此端點上的機器人會使用這個模型。",
"claudeEndpoints.mappings": "模型對應(選填)",
"claudeEndpoints.mappingsHint": "端點在 Opus、Sonnet 和 Haiku 工作時分別使用哪個模型。",
"claudeEndpoints.opus": "Opus 模型",