Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): point the built-in agent at an Anthropic-compatible gateway

esengine4dfde00bdf31
diff --git a/desktop/electron/agent/anthropic.ts b/desktop/electron/agent/anthropic.ts
index 8a3c3d8a5..c176a7b1c 100644
--- a/desktop/electron/agent/anthropic.ts
+++ b/desktop/electron/agent/anthropic.ts
@@ -10,27 +10,105 @@
* on the same model, and the cached prefix is a BYTE match — a history
* normalised into a neutral shape and rebuilt would break both, which is why
* this class exists instead of a translation layer in the kernel.
+ *
+ * It speaks two DIALECTS of one wire format. The Messages API shape is
+ * implemented by other vendors, but the things this provider leans on —
+ * adaptive thinking, effort, top-level cache_control, server-side fallbacks,
+ * mid-conversation system messages — are Anthropic's extensions, not the
+ * format's. A gateway handed one either ignores it (so the code claims a
+ * behaviour that is not happening, and the bill says otherwise) or rejects the
+ * request outright. So `baseURL` selects the dialect, and the compatible one
+ * sends the core format and nothing else.
*/
import Anthropic from '@anthropic-ai/sdk';
import type { AgentProvider, AgentSession, CatalogTool, StepEvent, ToolOutcome } from './types';
-
-/** The default. Opus-tier because this drives a real project: a wrong edit costs
- * the user their scene, and the checkpoint only helps if the plan was sane. */
-export const DEFAULT_MODEL = 'claude-opus-5';
+import { DEFAULT_MODEL } from '../../src/settings/agentIds';
/** Agentic work is what `xhigh` is for; it is also the depth Claude Code runs at. */
export const DEFAULT_EFFORT = 'xhigh';
+/**
+ * Which extensions a session may use.
+ *
+ * Named after what it is rather than after a vendor: the second one is "the
+ * Messages API as published", and any gateway implementing it qualifies.
+ */
+export type Dialect = 'anthropic' | 'compatible';
+
export interface AnthropicOptions {
apiKey: string;
model?: string;
effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
- /** Point at an Anthropic-compatible gateway; omit for the API. */
+ /** Point at an Anthropic-compatible gateway; omit for the API. Its presence
+ * is what drops the request to the core wire format — see the file header. */
baseURL?: string;
}
type Message = Anthropic.Beta.BetaMessageParam;
+/** Streaming, so the ceiling can be generous: a turn that plans and edits a
+ * whole panel needs room, and a truncated turn wastes the work before it. */
+const MAX_TOKENS = 64000;
+
+interface StepRequest {
+ model: string;
+ max_tokens: number;
+ system: string;
+ tools: { name: string; description: string; input_schema: unknown }[];
+ messages: readonly Message[];
+ output_config: { effort: string };
+ [extension: string]: unknown;
+}
+
+/**
+ * The body for one step. Pure and exported because the dialect split is the one
+ * thing in this file that is not a passthrough to the SDK, and shipping an
+ * Anthropic-only field to a gateway fails in the two ways that are hardest to
+ * notice: silently ignored, or billed differently than the code says.
+ */
+export function buildStepRequest(opts: {
+ dialect: Dialect;
+ model: string;
+ effort: string;
+ system: string;
+ tools: readonly CatalogTool[];
+ messages: readonly Message[];
+}): StepRequest {
+ const request: StepRequest = {
+ model: opts.model,
+ max_tokens: MAX_TOKENS,
+ system: opts.system,
+ // The whole point of the catalog being stable and ordered: tools render
+ // first in the prefix, so an unchanging list is what makes caching work at
+ // all — where there is caching.
+ tools: opts.tools.map((t) => ({
+ name: t.name,
+ description: t.description,
+ input_schema: t.schema,
+ })),
+ messages: opts.messages,
+ // Effort is the one control that survives the trip: it is a request-level
+ // hint a gateway can honour or ignore without changing what comes back.
+ output_config: { effort: opts.effort },
+ };
+ if (opts.dialect === 'compatible') return request;
+
+ // Adaptive is on by default on this model; say it anyway so the summary
+ // opt-in has something to attach to. `display` matters because the editor
+ // renders reasoning — the default returns empty thinking blocks, which reads
+ // to a user as a long silence before anything happens.
+ request.thinking = { type: 'adaptive', display: 'summarized' };
+ // Top-level auto-caching keeps the growing conversation warm.
+ request.cache_control = { type: 'ephemeral' };
+ // A safety classifier can decline a request that is perfectly ordinary for a
+ // game editor (a "spawn an enemy attack" prompt reads differently out of
+ // context). Let the API re-run it on the recommended fallback instead of
+ // handing the user a dead turn.
+ request.betas = ['server-side-fallback-2026-07-01'];
+ request.fallbacks = 'default';
+ return request;
+}
+
class AnthropicSession implements AgentSession {
private readonly messages: Message[] = [];
/** Context waiting for a legal spot — see {@link flushContext}. */
@@ -38,7 +116,7 @@ class AnthropicSession implements AgentSession {
constructor(
private readonly client: Anthropic,
- private readonly opts: Required<Omit<AnthropicOptions, 'baseURL'>>,
+ private readonly opts: { model: string; effort: string; dialect: Dialect },
private readonly system: string,
private readonly tools: readonly CatalogTool[],
) {}
@@ -66,56 +144,59 @@ class AnthropicSession implements AgentSession {
}
/**
- * Land buffered context as a `role: "system"` message rather than by rewriting
- * the system prompt. The prompt sits at the FRONT of the cached prefix, so
- * editing it per turn re-bills the whole conversation; a system message sits
- * after the history and leaves the cache intact.
+ * Land buffered context after the history rather than by rewriting the system
+ * prompt. The prompt sits at the FRONT of the cached prefix, so editing it per
+ * turn re-bills the whole conversation.
+ *
+ * Which shape depends on the dialect. Anthropic takes a `role: "system"`
+ * message, which is the operator channel and cannot be spoofed by anything
+ * that writes user content. A gateway implements two roles and no more, so
+ * the same text rides along as an extra block on the user turn — legal in the
+ * core format, still after the cached prefix, but it IS user-role text and
+ * carries no more authority than the rest of that turn.
*
- * Placement is constrained: it may not be the first message, and it must
- * follow a user turn. Both hold here — the kernel always appends the user turn
- * or a tool-result turn before stepping — but hold the text rather than
- * emitting an invalid message if that ever stops being true.
+ * Placement is constrained either way: it must follow a user turn. That holds
+ * here — the kernel always appends the user turn or a tool-result turn before
+ * stepping — but hold the text rather than emitting an invalid message if
+ * that ever stops being true.
*/
private flushContext(): void {
if (this.pending.length === 0) return;
const last = this.messages[this.messages.length - 1];
if (!last || last.role !== 'user') return;
- this.messages.push({ role: 'system', content: this.pending.join('\n\n') });
+ const text = this.pending.join('\n\n');
+
+ if (this.opts.dialect === 'anthropic') {
+ this.messages.push({ role: 'system', content: text });
+ } else {
+ const blocks = typeof last.content === 'string'
+ ? [{ type: 'text' as const, text: last.content }]
+ : [...last.content];
+ last.content = [...blocks, { type: 'text' as const, text }];
+ }
this.pending.length = 0;
}
async *step(signal: AbortSignal): AsyncIterable<StepEvent> {
this.flushContext();
- const stream = this.client.beta.messages.stream({
+ const request = buildStepRequest({
+ dialect: this.opts.dialect,
model: this.opts.model,
- // Streaming, so the ceiling can be generous: a turn that plans and edits a
- // whole panel needs room, and a truncated turn wastes the work before it.
- max_tokens: 64000,
- // Adaptive is on by default on this model; say it anyway so the summary
- // opt-in has something to attach to. `display` matters because the editor
- // renders reasoning — the default returns empty thinking blocks, which
- // reads to a user as a long silence before anything happens.
- thinking: { type: 'adaptive', display: 'summarized' },
- output_config: { effort: this.opts.effort },
- // The whole point of the catalog being stable and ordered: tools render
- // first in the prefix, so an unchanging list is what makes the cache work
- // at all. Top-level auto-caching then keeps the growing conversation warm.
- cache_control: { type: 'ephemeral' },
+ effort: this.opts.effort,
system: this.system,
- tools: this.tools.map((t) => ({
- name: t.name,
- description: t.description,
- input_schema: t.schema as Anthropic.Beta.BetaTool['input_schema'],
- })),
+ tools: this.tools,
messages: this.messages,
- // A safety classifier can decline a request that is perfectly ordinary for
- // a game editor (a "spawn an enemy attack" prompt reads differently out of
- // context). Let the API re-run it on the recommended fallback instead of
- // handing the user a dead turn.
- betas: ['server-side-fallback-2026-07-01'],
- fallbacks: 'default',
- }, { signal });
+ });
+
+ // The beta surface only for the dialect that has beta features in the
+ // request: it posts to `/v1/messages?beta=true`, and a query string a
+ // gateway never advertised is not worth spending on a request that carries
+ // no betas anyway. The cast is sound in this branch — a `role: "system"`
+ // message is only ever appended in the Anthropic dialect.
+ const stream = this.opts.dialect === 'anthropic'
+ ? this.client.beta.messages.stream(request as never, { signal })
+ : this.client.messages.stream(request as never, { signal });
for await (const event of stream) {
if (event.type !== 'content_block_delta') continue;
@@ -125,7 +206,7 @@ class AnthropicSession implements AgentSession {
const message = await stream.finalMessage();
// Verbatim — thinking blocks and all. See the file header.
- this.messages.push({ role: 'assistant', content: message.content });
+ this.messages.push({ role: 'assistant', content: message.content as Message['content'] });
if (message.usage) {
yield {
@@ -163,13 +244,15 @@ function stopReason(raw: string | null): Extract<StepEvent, { type: 'stop' }>['r
}
export function createAnthropicProvider(options: AnthropicOptions): AgentProvider {
- const model = options.model ?? DEFAULT_MODEL;
+ const model = options.model || DEFAULT_MODEL;
const effort = options.effort ?? DEFAULT_EFFORT;
- const client = new Anthropic({ apiKey: options.apiKey, baseURL: options.baseURL });
+ const baseURL = options.baseURL || undefined;
+ const dialect: Dialect = baseURL ? 'compatible' : 'anthropic';
+ const client = new Anthropic({ apiKey: options.apiKey, baseURL });
return {
- id: 'anthropic',
+ id: dialect === 'anthropic' ? 'anthropic' : `compatible:${baseURL ?? ''}`,
model,
createSession: ({ system, tools }) =>
- new AnthropicSession(client, { apiKey: options.apiKey, model, effort }, system, tools),
+ new AnthropicSession(client, { model, effort, dialect }, system, tools),
};
}
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index be462d95f..56953686f 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -48,7 +48,7 @@ import { secretStatus, setSecret, clearSecret, readSecret } from './secrets';
import { createSurfaceDriver } from './surfaceDriver';
import { createAgentHost } from './agent/host';
import { createAnthropicProvider } from './agent/anthropic';
-import { AGENT_API_KEY } from '../src/settings/secretIds';
+import { AGENT_API_KEY } from '../src/settings/agentIds';
import {
discoverPlugins, compilePlugin, isTrusted, trustPlugin, revokeTrust, isDisabled, setPluginEnabled,
PROJECT_PLUGIN_DIR, USER_PLUGIN_DIR,
@@ -656,6 +656,12 @@ ipcMain.handle('secret:clear', (_e, id: string) => clearSecret(id));
// Main owns the conversation because it owns the key, and because a renderer
// reload mid-turn must not take the turn with it. It drives the editor through
// the SAME surface driver the MCP endpoint uses; the window keeps a mirror.
+// Which endpoint the next session talks to. Pushed from the renderer (the
+// settings live in its localStorage) and merged, since the two rows fire
+// separately; read at session creation, so a change lands on the next
+// conversation rather than under the one being read.
+let agentEndpoint: { baseUrl?: string; model?: string } = {};
+
const agentHost = createAgentHost({
driver: createSurfaceDriver(() => win),
push: (message) => win?.webContents.send('agent:message', message),
@@ -665,7 +671,11 @@ const agentHost = createAgentHost({
// Phrased for the person who will read it in the transcript, and it names
// where to fix it — a bare "401" or "missing apiKey" does neither.
if (!apiKey) throw new Error('No API key is configured. Add one in Settings › AI Agents.');
- return createAnthropicProvider({ apiKey });
+ return createAnthropicProvider({
+ apiKey,
+ baseURL: agentEndpoint.baseUrl,
+ model: agentEndpoint.model,
+ });
},
});
ipcMain.handle('agent:status', () => agentHost.status());
@@ -673,6 +683,9 @@ ipcMain.handle('agent:send', (_e, text: string) => agentHost.send(text));
ipcMain.handle('agent:stop', () => agentHost.stop());
ipcMain.handle('agent:confirm', (_e, callId: string, allow: boolean) => agentHost.confirm(callId, allow));
ipcMain.handle('agent:reset', () => agentHost.reset());
+ipcMain.handle('agent:setEndpoint', (_e, patch: { baseUrl?: string; model?: string }) => {
+ agentEndpoint = { ...agentEndpoint, ...patch };
+});
// — Custom window controls (frameless Windows/Linux; macOS uses native traffic lights) —
ipcMain.handle('window:minimize', () => win?.minimize());
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 5fa5b98a4..14af544eb 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -119,6 +119,10 @@ const api = {
ipcRenderer.invoke('agent:confirm', callId, allow),
/** Drop the conversation and start a new one. */
reset: (): Promise<AgentStatus> => ipcRenderer.invoke('agent:reset'),
+ /** Point the NEXT session at an endpoint/model. Merged, so each settings row
+ * can push its own field. */
+ setEndpoint: (patch: { baseUrl?: string; model?: string }): Promise<void> =>
+ ipcRenderer.invoke('agent:setEndpoint', patch),
/** Transcript events + status changes, in the order they happened; returns
* an unsubscribe. One channel because the two must not be reordered. */
onMessage: (cb: (message: AgentMessage) => void): (() => void) => {
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index 0b8fc8c8c..51a263d60 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -119,6 +119,16 @@ export const settingsMessages = defineMessages({
en: 'What the built-in agent authenticates with. Held by the system keychain — never written to the project or the settings file, and never handed back to this window.',
zh: '内置 Agent 用它调用模型。密钥存在系统钥匙串里——不写进项目、不写进设置文件,也不会交回给这个窗口。',
},
+ 'set.agents.baseUrl': { en: 'API endpoint', zh: 'API 地址' },
+ 'set.agents.baseUrl.desc': {
+ en: 'Leave empty for the Anthropic API. Point it at an Anthropic-compatible gateway (for example https://api.deepseek.com/anthropic) to run another vendor’s models — the agent then sends only the core Messages format, without extended thinking, prompt caching or automatic fallbacks.',
+ zh: '留空则使用 Anthropic API。填入兼容 Anthropic 的网关地址(例如 https://api.deepseek.com/anthropic)即可换用其他厂商的模型——此时 Agent 只发送基础 Messages 格式,不带扩展思考、提示缓存和自动回退。',
+ },
+ 'set.agents.model': { en: 'Model', zh: '模型' },
+ 'set.agents.model.desc': {
+ en: 'Leave empty to use the default. Name the model when using a gateway — some map an unrecognised name to their smallest model instead of refusing it.',
+ zh: '留空则使用默认模型。使用网关时请写明模型名——有些网关遇到无法识别的名字不会报错,而是改用它们最小的模型。',
+ },
'set.agents.mcpEnabled': { en: 'Allow AI agents to connect', zh: '允许 AI 代理连接' },
'set.agents.mcpEnabled.desc': {
en: 'Serve this editor over MCP on a local-only port, so an agent set up with --attach can drive the project you have open. Off means nothing is listening.',
diff --git a/desktop/src/settings/agentIds.ts b/desktop/src/settings/agentIds.ts
new file mode 100644
index 000000000..b72a74755
--- /dev/null
+++ b/desktop/src/settings/agentIds.ts
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file agentIds.ts — the built-in agent's constants, shared by both processes.
+ *
+ * Shared on purpose: the settings row registers under an id and main reads back
+ * under the same one, and a secret written under an id nobody reads is
+ * indistinguishable from a machine that lost its keychain. Likewise the default
+ * model — main falls back to it and the settings row shows it as the
+ * placeholder, so a second copy would eventually tell the user something untrue.
+ *
+ * A leaf module with no imports, so main can take it without pulling the editor
+ * in (the same reason plugins/paths.ts exists).
+ */
+
+/** The built-in agent's model credential. Also its settings-row id. */
+export const AGENT_API_KEY = 'agents.apiKey';
+
+/** What runs when the model setting is blank. Opus-tier because this drives a
+ * real project: a wrong edit costs the user their scene, and the turn's
+ * checkpoint only helps if the plan was sane. */
+export const DEFAULT_MODEL = 'claude-opus-5';
diff --git a/desktop/src/settings/editorSettings.ts b/desktop/src/settings/editorSettings.ts
index 5c69e8850..d278eb612 100644
--- a/desktop/src/settings/editorSettings.ts
+++ b/desktop/src/settings/editorSettings.ts
@@ -19,7 +19,8 @@ import { EngineHost } from '@/engine/EngineHost';
import { Toasts } from '@/store/Toasts';
import { mcpStatus, setMcpEnabled, subscribeMcp } from '@/store/McpStore';
import { secretStatusLine, subscribeSecrets } from '@/store/SecretStore';
-import { AGENT_API_KEY } from './secretIds';
+import { setAgentEndpoint } from '@/store/AgentStore';
+import { AGENT_API_KEY, DEFAULT_MODEL } from './agentIds';
import { t, editorLocale, systemDefaultLocale, EDITOR_LOCALES, LANGUAGE_SETTING_ID } from '@/i18n';
const root = () => document.documentElement.style;
@@ -254,6 +255,40 @@ settingsRegistry.register({
status: { read: () => secretStatusLine(AGENT_API_KEY), subscribe: subscribeSecrets },
});
+// The endpoint and model are pushed to main rather than read by it: settings
+// live in this window's localStorage, and main owns the session. Same path as
+// the MCP toggle — one setter, replayed at boot by applySettings(), so the two
+// processes cannot hold different answers.
+//
+// They take effect on the NEXT conversation. Rebuilding a live session on a
+// keystroke would throw away the transcript the user is reading, and a string
+// field commits on every keystroke.
+settingsRegistry.register({
+ id: 'agents.baseUrl',
+ type: 'string',
+ scope: 'editor',
+ section: 'agents',
+ group: t('set.group.builtinAgent'),
+ label: t('set.agents.baseUrl'),
+ description: t('set.agents.baseUrl.desc'),
+ placeholder: 'https://api.anthropic.com',
+ default: '',
+ effect: (v) => setAgentEndpoint({ baseUrl: v }),
+});
+
+settingsRegistry.register({
+ id: 'agents.model',
+ type: 'string',
+ scope: 'editor',
+ section: 'agents',
+ group: t('set.group.builtinAgent'),
+ label: t('set.agents.model'),
+ description: t('set.agents.model.desc'),
+ placeholder: DEFAULT_MODEL,
+ default: '',
+ effect: (v) => setAgentEndpoint({ model: v }),
+});
+
// ── External agents (main-owned endpoint, driven from here) ─────────────────
// An external agent reaches this editor through the MCP endpoint main can expose,
// and `--attach` finds it through the discovery file the endpoint writes. An
diff --git a/desktop/src/settings/secretIds.ts b/desktop/src/settings/secretIds.ts
deleted file mode 100644
index edf5b7a93..000000000
--- a/desktop/src/settings/secretIds.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file secretIds.ts — the ids a secret is stored under.
- *
- * Shared by both sides on purpose: the settings row registers under one of these
- * and main reads back under the same one, and a secret written under an id
- * nobody reads is indistinguishable from a machine that lost its keychain. A
- * leaf module with no imports, so main can take it without pulling the editor in
- * (the same reason plugins/paths.ts exists).
- */
-
-/** The built-in agent's model credential. Also its settings-row id. */
-export const AGENT_API_KEY = 'agents.apiKey';
diff --git a/desktop/src/store/AgentStore.ts b/desktop/src/store/AgentStore.ts
index 456b7c2ab..208a21f98 100644
--- a/desktop/src/store/AgentStore.ts
+++ b/desktop/src/store/AgentStore.ts
@@ -248,6 +248,19 @@ export function stopAgentTurn(): void {
void window.estella?.agent?.stop();
}
+/**
+ * Tell main which endpoint and model to build the next session against.
+ *
+ * Pushed rather than read: settings live in this window's localStorage and main
+ * owns the session, so this is the same one-way path the MCP toggle uses. The
+ * settings' `effect` calls it — including the boot replay — and a partial patch
+ * is merged in main, because the two rows are separate settings that each fire
+ * on their own.
+ */
+export function setAgentEndpoint(patch: { baseUrl?: string; model?: string }): void {
+ void window.estella?.agent?.setEndpoint(patch);
+}
+
/**
* Answer a pending confirmation. The row moves on the click rather than on
* main's echo — the person just decided, and a row that sits on "waiting for
diff --git a/desktop/src/theme/settings.css b/desktop/src/theme/settings.css
index 78252a640..30532e093 100644
--- a/desktop/src/theme/settings.css
+++ b/desktop/src/theme/settings.css
@@ -161,6 +161,9 @@
.set-str { width: 200px; height: 24px; background: var(--inset); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 0 7px; color: var(--text); font-size: var(--fs-xs); font-family: var(--mono); outline: none; }
.set-str:focus { border-color: var(--acc); box-shadow: 0 0 0 2px var(--acc-soft); }
.set-str::placeholder { color: var(--text-mute); font-family: var(--sans, inherit); }
+/* A plain string row fills its column rather than sitting 30px short of it: the
+ values are URLs and identifiers, where the truncated end is the telling one. */
+.set-ctrl > .set-str { width: 100%; }
/* A path row is wider than a plain string: an absolute program path is long, and
truncating the interesting end of it (the executable's name) is what makes the
Cocos-style field hard to read at a glance. */
diff --git a/desktop/tests/agent-dialect.test.ts b/desktop/tests/agent-dialect.test.ts
new file mode 100644
index 000000000..bfc0075e7
--- /dev/null
+++ b/desktop/tests/agent-dialect.test.ts
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The provider speaks two dialects of one wire format. The Messages API
+ * shape is implemented by other vendors; the extensions this provider
+ * leans on are Anthropic's, not the format's.
+ *
+ * This is worth a test because both failure modes are quiet. A gateway
+ * handed `cache_control` ignores it, so the code claims caching that is
+ * not happening and the bill disagrees. One handed `thinking` may 400 —
+ * loud, but only at the first real turn, which is the worst place to find
+ * out. And a `role: "system"` message sent to a two-role API is either
+ * rejected or silently dropped, taking the editor's context with it.
+ */
+import { describe, it, expect } from 'vitest';
+import { buildStepRequest, createAnthropicProvider } from '../electron/agent/anthropic';
+import { DEFAULT_MODEL } from '../src/settings/agentIds';
+import type { CatalogTool } from '../electron/agent/types';
+
+const TOOLS: CatalogTool[] = [
+ { name: 'get_scene_tree', description: 'Read the scene.', schema: { type: 'object' }, effect: 'read' },
+];
+
+const request = (dialect: 'anthropic' | 'compatible') => buildStepRequest({
+ dialect,
+ model: 'a-model',
+ effort: 'xhigh',
+ system: 'be useful',
+ tools: TOOLS,
+ messages: [{ role: 'user', content: 'hi' }],
+});
+
+/** Everything that exists because Anthropic added it, not because the Messages
+ * format has it. Adding one to the request means adding it here. */
+const EXTENSIONS = ['thinking', 'cache_control', 'betas', 'fallbacks'];
+
+describe('the request each dialect sends', () => {
+ it('carries the same core in both', () => {
+ for (const dialect of ['anthropic', 'compatible'] as const) {
+ expect(request(dialect)).toMatchObject({
+ model: 'a-model',
+ system: 'be useful',
+ max_tokens: expect.any(Number),
+ output_config: { effort: 'xhigh' },
+ tools: [{ name: 'get_scene_tree', input_schema: { type: 'object' } }],
+ messages: [{ role: 'user', content: 'hi' }],
+ });
+ }
+ });
+
+ it('uses the extensions when talking to Anthropic', () => {
+ const req = request('anthropic');
+ for (const key of EXTENSIONS) expect(req).toHaveProperty(key);
+ expect(req.thinking).toMatchObject({ display: 'summarized' });
+ });
+
+ it('sends none of them to a gateway', () => {
+ const req = request('compatible');
+ for (const key of EXTENSIONS) expect(req).not.toHaveProperty(key);
+ });
+
+ // The catalog is what a gateway is told the agent can do; dropping tools on
+ // the compatible path would leave a model that can only talk.
+ it('sends the tool catalog either way', () => {
+ expect(request('compatible').tools).toHaveLength(TOOLS.length);
+ });
+});
+
+describe('choosing the dialect', () => {
+ it('talks to Anthropic when no endpoint is set', () => {
+ const provider = createAnthropicProvider({ apiKey: 'k' });
+ expect(provider.id).toBe('anthropic');
+ expect(provider.model).toBe(DEFAULT_MODEL);
+ });
+
+ // An empty string is what a cleared settings field produces, and reading it as
+ // "a gateway at nowhere" would silently strip the extensions on the API.
+ it('reads a blank endpoint as no endpoint', () => {
+ expect(createAnthropicProvider({ apiKey: 'k', baseURL: '', model: '' }).id).toBe('anthropic');
+ expect(createAnthropicProvider({ apiKey: 'k', model: '' }).model).toBe(DEFAULT_MODEL);
+ });
+
+ it('drops to the core format for a gateway, and takes its model verbatim', () => {
+ const provider = createAnthropicProvider({
+ apiKey: 'k',
+ baseURL: 'https://api.deepseek.com/anthropic',
+ model: 'deepseek-v4-pro',
+ });
+ expect(provider.id).toContain('compatible');
+ expect(provider.model).toBe('deepseek-v4-pro');
+ });
+});
+
+describe('where per-turn editor context lands', () => {
+ const contextAfter = (dialect: 'anthropic' | 'compatible') => {
+ const session = createAnthropicProvider(
+ dialect === 'anthropic' ? { apiKey: 'k' } : { apiKey: 'k', baseURL: 'https://gateway.test' },
+ ).createSession({ system: 's', tools: TOOLS });
+ session.pushUser('build me a menu');
+ session.pushContext('The editor is editing the scene /scenes/main.esscene.');
+ // step() would call the network; the placement is decided before that, so
+ // reach for what it would send instead of standing up an HTTP fake.
+ (session as unknown as { flushContext(): void }).flushContext();
+ return (session as unknown as { messages: { role: string; content: unknown }[] }).messages;
+ };
+
+ it('uses the operator channel on Anthropic', () => {
+ const messages = contextAfter('anthropic');
+ expect(messages.at(-1)).toMatchObject({ role: 'system' });
+ });
+
+ // A gateway implements two roles. The same text rides the user turn as an
+ // extra block — legal in the core format, still after the cached prefix.
+ it('folds it into the user turn on a gateway', () => {
+ const messages = contextAfter('compatible');
+ expect(messages).toHaveLength(1);
+ expect(messages[0]).toMatchObject({ role: 'user' });
+ expect(messages[0].content).toEqual([
+ { type: 'text', text: 'build me a menu' },
+ { type: 'text', text: 'The editor is editing the scene /scenes/main.esscene.' },
+ ]);
+ });
+
+ it('holds the text rather than emitting a message with nothing to attach to', () => {
+ const session = createAnthropicProvider({ apiKey: 'k' }).createSession({ system: 's', tools: TOOLS });
+ session.pushContext('orphan');
+ (session as unknown as { flushContext(): void }).flushContext();
+ expect((session as unknown as { messages: unknown[] }).messages).toHaveLength(0);
+ });
+});
diff --git a/desktop/tests/secrets.test.ts b/desktop/tests/secrets.test.ts
index 06cf2e3c9..5d10f458e 100644
--- a/desktop/tests/secrets.test.ts
+++ b/desktop/tests/secrets.test.ts
@@ -14,7 +14,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, existsSync, readFileSync, writeFileSync, statSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
-import { AGENT_API_KEY } from '../src/settings/secretIds';
+import { AGENT_API_KEY } from '../src/settings/agentIds';
let userData: string;
let available = true;