Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat(ai-gateway): switch Claude models from Vertex AI to direct Anthropic API

Louis Beaumont011f80d120c0
diff --git a/Cargo.lock b/Cargo.lock
index a28c9e494..e2072f7d3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6827,6 +6827,7 @@ dependencies = [
"reqwest 0.12.12",
"rust-stemmers",
"screenpipe-accessibility",
+ "screenpipe-apple-intelligence",
"screenpipe-audio",
"screenpipe-core",
"screenpipe-db",
diff --git a/apps/screenpipe-app-tauri/components/onboarding/status.tsx b/apps/screenpipe-app-tauri/components/onboarding/status.tsx
index 18da247fd..8aa8d591a 100644
--- a/apps/screenpipe-app-tauri/components/onboarding/status.tsx
+++ b/apps/screenpipe-app-tauri/components/onboarding/status.tsx
@@ -227,7 +227,7 @@ const OnboardingStatus: React.FC<OnboardingStatusProps> = ({
id: "pi-agent",
provider: "pi" as const,
url: "",
- model: "claude-haiku-4-5@20251001",
+ model: "claude-haiku-4-5-20251001",
maxContextChars: 200000,
defaultPreset: true,
prompt: "",
diff --git a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
index 6488e6e50..f230b2892 100644
--- a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
@@ -396,7 +396,7 @@ export function AIProviderConfig({
...formData,
provider: "pi",
url: "", // Pi uses RPC mode
- model: "claude-haiku-4-5@20251001",
+ model: "claude-haiku-4-5-20251001",
});
}}
>
@@ -606,8 +606,8 @@ export function AIProviderConfig({
<SelectValue placeholder="select model" />
</SelectTrigger>
<SelectContent>
- <SelectItem value="claude-haiku-4-5@20251001">Haiku 4.5 (fast)</SelectItem>
- <SelectItem value="claude-opus-4-5@20251101">Opus 4.5 (powerful)</SelectItem>
+ <SelectItem value="claude-haiku-4-5-20251001">Haiku 4.5 (fast)</SelectItem>
+ <SelectItem value="claude-opus-4-6">Opus 4.6 (powerful)</SelectItem>
</SelectContent>
</Select>
</div>
diff --git a/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx b/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
index 1cf1715da..1c5b565ce 100644
--- a/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
@@ -366,7 +366,7 @@ const AISection = ({
break;
case "pi":
newUrl = ""; // Pi uses RPC mode, not HTTP
- newModel = "claude-haiku-4-5@20251001";
+ newModel = "claude-haiku-4-5-20251001";
break;
}
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index f61049a74..7598f735a 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -140,7 +140,7 @@ const DEFAULT_PI_PRESET: AIPreset = {
id: "pi-agent",
provider: "pi",
url: "",
- model: "claude-haiku-4-5@20251001",
+ model: "claude-haiku-4-5-20251001",
maxContextChars: 200000,
defaultPreset: true,
prompt: "",
diff --git a/packages/ai-gateway/src/handlers/models.ts b/packages/ai-gateway/src/handlers/models.ts
index e0aaee9a6..fc620dfde 100644
--- a/packages/ai-gateway/src/handlers/models.ts
+++ b/packages/ai-gateway/src/handlers/models.ts
@@ -1,7 +1,7 @@
import { Env, UserTier } from '../types';
-import { createProvider } from '../providers';
import { createSuccessResponse, createErrorResponse, addCorsHeaders } from '../utils/cors';
import { TIER_CONFIG, isModelAllowed } from '../services/usage-tracker';
+import { listAnthropicModels } from '../providers/anthropic-proxy';
/**
* Handles model listing requests
@@ -11,18 +11,28 @@ import { TIER_CONFIG, isModelAllowed } from '../services/usage-tracker';
*/
export async function handleModelListing(env: Env, tier: UserTier = 'subscribed'): Promise<Response> {
try {
- // Only use Vertex AI which provides both Claude and Gemini
- const vertex = createProvider('claude-opus-4-20250514', env);
- const results = await Promise.allSettled([
- vertex.listModels(),
+ // Fetch Claude models from Anthropic API (dynamic — new models appear automatically)
+ // and include Gemini models statically
+ const [anthropicModels] = await Promise.all([
+ env.ANTHROPIC_API_KEY
+ ? listAnthropicModels(env.ANTHROPIC_API_KEY)
+ : Promise.resolve([]),
]);
- let models = results
- .filter(
- (result): result is PromiseFulfilledResult<{ id: string; name: string; provider: string }[]> =>
- result.status === 'fulfilled'
- )
- .flatMap((result) => result.value);
+ const geminiModels = [
+ { id: 'gemini-3-pro-preview', name: 'Gemini 3 Pro', provider: 'google' },
+ { id: 'gemini-3-flash-preview', name: 'Gemini 3 Flash', provider: 'google' },
+ { id: 'gemini-2.5-flash', name: 'Gemini 2.5 Flash', provider: 'google' },
+ ];
+
+ let models: { id: string; name: string; provider: string; tier_available?: boolean }[] = [
+ ...anthropicModels.map(m => ({
+ id: m.id,
+ name: m.id, // Anthropic API returns id, display_name handled in listAnthropicModels
+ provider: 'anthropic',
+ })),
+ ...geminiModels,
+ ];
// Filter models based on tier
if (tier !== 'subscribed') {
diff --git a/packages/ai-gateway/src/handlers/vertex-proxy.ts b/packages/ai-gateway/src/handlers/vertex-proxy.ts
index 605561e4f..6c5eb6c3b 100644
--- a/packages/ai-gateway/src/handlers/vertex-proxy.ts
+++ b/packages/ai-gateway/src/handlers/vertex-proxy.ts
@@ -1,71 +1,74 @@
/**
- * Vertex AI Proxy Handler for Claude Agent SDK
+ * Proxy Handler for Claude (Anthropic API) and Gemini (Vertex AI)
*
- * This handler proxies Anthropic Messages API requests to Vertex AI,
- * allowing users to use the Agent SDK without setting up GCP credentials.
+ * Claude models are proxied directly to the Anthropic Messages API.
+ * Gemini models remain on Vertex AI.
*
- * The Agent SDK sends requests to:
- * ANTHROPIC_VERTEX_BASE_URL/v1/messages
- *
- * This handler receives those requests and forwards them to Vertex AI
- * with proper authentication using the service account.
+ * The Agent SDK and OpenCode send Anthropic-format requests to:
+ * /v1/messages and /anthropic/v1/messages
*/
import { Env } from '../types';
import { proxyToVertex } from '../providers/vertex';
+import { proxyToAnthropic, listAnthropicModels } from '../providers/anthropic-proxy';
import { addCorsHeaders } from '../utils/cors';
/**
- * Handle Vertex AI proxy requests for the Agent SDK
+ * Handle proxy requests for the Agent SDK and OpenCode
+ * Routes Claude models to Anthropic API, Gemini to Vertex AI
*/
export async function handleVertexProxy(request: Request, env: Env): Promise<Response> {
- // Validate required env vars
- if (!env.VERTEX_SERVICE_ACCOUNT_JSON) {
- return new Response(JSON.stringify({ error: 'Vertex AI service account not configured' }), {
- status: 500,
- headers: { 'Content-Type': 'application/json' },
- });
- }
-
- if (!env.VERTEX_PROJECT_ID) {
- return new Response(JSON.stringify({ error: 'Vertex AI project ID not configured' }), {
+ // For /v1/messages, requests are always Anthropic-format (Claude models)
+ // Use direct Anthropic API — simpler auth, no model mapping, new models available immediately
+ if (!env.ANTHROPIC_API_KEY) {
+ return addCorsHeaders(new Response(JSON.stringify({
+ type: 'error',
+ error: { type: 'configuration_error', message: 'Anthropic API key not configured' },
+ }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
- });
+ }));
}
- const region = env.VERTEX_REGION || 'us-east5';
-
try {
- const response = await proxyToVertex(request, env.VERTEX_SERVICE_ACCOUNT_JSON, env.VERTEX_PROJECT_ID, region);
-
+ const response = await proxyToAnthropic(request, env.ANTHROPIC_API_KEY);
return addCorsHeaders(response);
} catch (error: any) {
- console.error('Vertex proxy error:', error);
- return new Response(JSON.stringify({ error: error.message }), {
+ console.error('Anthropic proxy error:', error);
+ return addCorsHeaders(new Response(JSON.stringify({
+ type: 'error',
+ error: { type: 'api_error', message: error.message },
+ }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
- });
+ }));
}
}
/**
- * Handle Vertex AI model listing
- * All get mapped to claude-sonnet-4@20250514 internally
+ * Handle model listing for /anthropic/v1/models
+ * Combines dynamic Anthropic models with Gemini models
*/
export async function handleVertexModels(env: Env): Promise<Response> {
- const models = [
+ // Gemini models (still on Vertex)
+ const geminiModels = [
{ id: 'gemini-3-pro-preview', object: 'model', created: 1747180800, owned_by: 'google' },
{ id: 'gemini-3-flash-preview', object: 'model', created: 1747180800, owned_by: 'google' },
- { id: 'claude-opus-4-5@20251101', object: 'model', created: 1747180800, owned_by: 'anthropic' },
- { id: 'claude-haiku-4-5@20251001', object: 'model', created: 1747180800, owned_by: 'anthropic' },
];
+ // Claude models — fetch dynamically from Anthropic API
+ let claudeModels: { id: string; object: string; created: number; owned_by: string }[] = [];
+ if (env.ANTHROPIC_API_KEY) {
+ claudeModels = await listAnthropicModels(env.ANTHROPIC_API_KEY);
+ }
+
+ const allModels = [...claudeModels, ...geminiModels];
+
return addCorsHeaders(
new Response(
JSON.stringify({
object: 'list',
- data: models,
+ data: allModels,
}),
{
headers: { 'Content-Type': 'application/json' },
diff --git a/packages/ai-gateway/src/index.ts b/packages/ai-gateway/src/index.ts
index 4f1ff9ae2..746f16149 100644
--- a/packages/ai-gateway/src/index.ts
+++ b/packages/ai-gateway/src/index.ts
@@ -157,7 +157,7 @@ async function handleRequest(request: Request, env: Env, ctx: ExecutionContext):
const clonedRequest = request.clone();
try {
const body = (await clonedRequest.json()) as { model?: string };
- const model = body.model || 'claude-haiku-4-5@20251001';
+ const model = body.model || 'claude-haiku-4-5-20251001';
if (!isModelAllowed(model, authResult.tier)) {
const allowedModels = TIER_CONFIG[authResult.tier].allowedModels;
return addCorsHeaders(createErrorResponse(403, JSON.stringify({
@@ -281,7 +281,7 @@ curl -X POST $HOST/v1/chat/completions \
-H "Content-Type: application/json" \
-H "X-Device-Id: test-device-123" \
-d '{
-"model": "claude-haiku-4-5@20251001",
+"model": "claude-haiku-4-5-20251001",
"messages": [
{
"role": "user",
diff --git a/packages/ai-gateway/src/providers/anthropic-proxy.ts b/packages/ai-gateway/src/providers/anthropic-proxy.ts
new file mode 100644
index 000000000..3ffa882b1
--- /dev/null
+++ b/packages/ai-gateway/src/providers/anthropic-proxy.ts
@@ -0,0 +1,151 @@
+/**
+ * Direct Anthropic API Proxy for Claude models
+ *
+ * Replaces the Vertex AI proxy for Claude requests. Instead of going through
+ * Google Cloud Vertex AI (which requires service account auth, model mapping,
+ * and has delayed availability of new models), this proxies directly to the
+ * Anthropic Messages API.
+ *
+ * The Agent SDK and OpenCode send Anthropic-format requests and expect
+ * Anthropic-format responses — this is a thin passthrough with sanitization.
+ */
+
+import { sanitizeMessages } from './vertex';
+
+const ANTHROPIC_API_URL = 'https://api.anthropic.com';
+const ANTHROPIC_VERSION = '2023-06-01';
+
+/**
+ * Proxy an Anthropic Messages API request directly to api.anthropic.com
+ *
+ * This replaces proxyToVertex() for Claude models. The request format is
+ * identical (Anthropic Messages API), so we just forward with auth headers.
+ */
+export async function proxyToAnthropic(
+ request: Request,
+ apiKey: string,
+): Promise<Response> {
+ try {
+ const body = await request.json() as {
+ model?: string;
+ stream?: boolean;
+ max_tokens?: number;
+ messages?: any[];
+ system?: string;
+ temperature?: number;
+ [key: string]: any;
+ };
+
+ console.log('proxyToAnthropic: model=', body.model, 'stream=', body.stream, 'messages count=', body.messages?.length);
+
+ // Sanitize messages to fix common formatting issues (e.g. nested {text: {text: '...'}})
+ // This is a client-side bug workaround, not provider-specific
+ if (body.messages) {
+ body.messages = sanitizeMessages(body.messages);
+ }
+
+ const isStreaming = body.stream === true;
+
+ // Forward directly to Anthropic API
+ // Unlike Vertex, the model stays in the body and auth is via x-api-key header
+ const response = await fetch(`${ANTHROPIC_API_URL}/v1/messages`, {
+ method: 'POST',
+ headers: {
+ 'x-api-key': apiKey,
+ 'anthropic-version': ANTHROPIC_VERSION,
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify(body),
+ });
+
+ if (!response.ok) {
+ const error = await response.text();
+ console.error('Anthropic API error:', response.status, error);
+ // Return the Anthropic error as-is — clients already expect this format
+ return new Response(error, {
+ status: response.status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ // For streaming, pass through the SSE stream as-is
+ // Anthropic SSE format is identical whether from Vertex or direct API
+ if (isStreaming) {
+ return new Response(response.body, {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ },
+ });
+ }
+
+ // For non-streaming, pass through the JSON response
+ const result = await response.json();
+ return new Response(JSON.stringify(result), {
+ headers: { 'Content-Type': 'application/json' },
+ });
+ } catch (error: any) {
+ console.error('proxyToAnthropic error:', error.message, error.stack);
+ return new Response(JSON.stringify({
+ type: 'error',
+ error: {
+ type: 'api_error',
+ message: error.message,
+ },
+ }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+}
+
+/**
+ * List available Claude models from the Anthropic API
+ *
+ * Unlike the hardcoded Vertex model list, this dynamically fetches
+ * available models so new releases (like Opus 4.6) appear automatically.
+ */
+export async function listAnthropicModels(
+ apiKey: string,
+): Promise<{ id: string; object: string; created: number; owned_by: string }[]> {
+ try {
+ const response = await fetch(`${ANTHROPIC_API_URL}/v1/models`, {
+ headers: {
+ 'x-api-key': apiKey,
+ 'anthropic-version': ANTHROPIC_VERSION,
+ },
+ });
+
+ if (!response.ok) {
+ console.error('Failed to list Anthropic models:', response.status);
+ return getFallbackModels();
+ }
+
+ const data = await response.json() as {
+ data: Array<{ id: string; display_name: string; created_at: string; type: string }>;
+ };
+
+ return data.data.map((model) => ({
+ id: model.id,
+ object: 'model',
+ created: Math.floor(new Date(model.created_at).getTime() / 1000),
+ owned_by: 'anthropic',
+ }));
+ } catch (error) {
+ console.error('Error listing Anthropic models:', error);
+ return getFallbackModels();
+ }
+}
+
+/**
+ * Fallback model list in case the API is unreachable
+ */
+function getFallbackModels(): { id: string; object: string; created: number; owned_by: string }[] {
+ return [
+ { id: 'claude-opus-4-6', object: 'model', created: 1738800000, owned_by: 'anthropic' },
+ { id: 'claude-sonnet-4-5-20250929', object: 'model', created: 1727568000, owned_by: 'anthropic' },
+ { id: 'claude-haiku-4-5-20251001', object: 'model', created: 1727740800, owned_by: 'anthropic' },
+ { id: 'claude-opus-4-5-20251101', object: 'model', created: 1730419200, owned_by: 'anthropic' },
+ ];
+}
diff --git a/packages/ai-gateway/src/providers/anthropic.ts b/packages/ai-gateway/src/providers/anthropic.ts
index 4f2fe2123..363a1757b 100644
--- a/packages/ai-gateway/src/providers/anthropic.ts
+++ b/packages/ai-gateway/src/providers/anthropic.ts
@@ -20,15 +20,45 @@ export class AnthropicProvider implements AIProvider {
this.client = new Anthropic({ apiKey });
}
+ /**
+ * Build the system prompt from system messages and response_format
+ */
+ private buildSystemPrompt(body: RequestBody): string | undefined {
+ const parts: string[] = [];
+
+ // Extract system messages from the conversation
+ const systemMessages = body.messages.filter(m => m.role === 'system');
+ for (const msg of systemMessages) {
+ const text = typeof msg.content === 'string' ? msg.content : '';
+ if (text) parts.push(text);
+ }
+
+ // Add response_format instructions
+ if (body.response_format) {
+ switch (body.response_format.type) {
+ case 'json_object':
+ parts.push('Respond with valid JSON only.');
+ break;
+ case 'json_schema':
+ if (body.response_format.schema) {
+ parts.push(`Respond with valid JSON that strictly follows this schema:\n${JSON.stringify(body.response_format.schema, null, 2)}\nDo not include any explanatory text - output valid JSON only.`);
+ }
+ break;
+ }
+ }
+
+ return parts.length > 0 ? parts.join('\n\n') : undefined;
+ }
+
async createCompletion(body: RequestBody): Promise<Response> {
const messages = this.formatMessages(body.messages);
const response = await this.client.messages.create({
messages,
model: body.model,
- max_tokens: 4096,
+ max_tokens: body.max_tokens || 4096,
temperature: body.temperature,
- system: this.createSystemPrompt(body.response_format),
+ system: this.buildSystemPrompt(body),
tools: body.tools ? this.formatTools(body.tools) : undefined,
});
@@ -37,30 +67,14 @@ export class AnthropicProvider implements AIProvider {
});
}
- private createSystemPrompt(responseFormat?: ResponseFormat): string | undefined {
- if (!responseFormat) return undefined;
-
- switch (responseFormat.type) {
- case 'json_object':
- return 'Respond with valid JSON only.';
- case 'json_schema':
- if (!responseFormat.schema) return undefined;
-
- return `Respond with valid JSON that strictly follows this schema:
- ${JSON.stringify(responseFormat.schema, null, 2)}
- Do not include any explanatory text - output valid JSON only.`;
- default:
- return undefined;
- }
- }
-
async createStreamingCompletion(body: RequestBody): Promise<ReadableStream> {
const stream = await this.client.messages.create({
messages: this.formatMessages(body.messages),
model: body.model,
stream: true,
- max_tokens: 4096,
+ max_tokens: body.max_tokens || 4096,
temperature: body.temperature,
+ system: this.buildSystemPrompt(body),
tools: body.tools ? this.formatTools(body.tools) : undefined,
});
@@ -157,12 +171,55 @@ export class AnthropicProvider implements AIProvider {
}
formatMessages(messages: Message[]): MessageParam[] {
- return messages.map((msg) => {
+ const result: MessageParam[] = [];
+
+ for (const msg of messages) {
+ // Skip system messages — they're extracted into the system parameter
+ if (msg.role === 'system') continue;
+
+ // Handle tool results (OpenAI role: 'tool' → Anthropic role: 'user' with tool_result)
+ if (msg.role === 'tool') {
+ result.push({
+ role: 'user',
+ content: [{
+ type: 'tool_result',
+ tool_use_id: (msg as any).tool_call_id || '',
+ content: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),
+ }] as any,
+ });
+ continue;
+ }
+
+ // Handle assistant messages with tool_calls
+ if (msg.role === 'assistant' && (msg as any).tool_calls) {
+ const content: any[] = [];
+ if (msg.content) {
+ const text = typeof msg.content === 'string' ? msg.content : '';
+ if (text) content.push({ type: 'text', text });
+ }
+ for (const tc of (msg as any).tool_calls) {
+ content.push({
+ type: 'tool_use',
+ id: tc.id,
+ name: tc.function?.name || tc.name,
+ input: typeof tc.function?.arguments === 'string'
+ ? JSON.parse(tc.function.arguments)
+ : tc.function?.arguments || {},
+ });
+ }
+ result.push({
+ role: 'assistant',
+ content: content as any,
+ });
+ continue;
+ }
+
+ // Regular user/assistant messages
const content: ContentBlockParam[] = Array.isArray(msg.content)
? msg.content.map((part) => {
// Handle OpenAI vision format (image_url)
- if (part.type === 'image_url' && part.image_url?.url) {
- const url = part.image_url.url;
+ if (part.type === 'image_url' && (part as any).image_url?.url) {
+ const url = (part as any).image_url.url;
const dataUrlMatch = url.match(/^data:([^;]+);base64,(.+)$/);
if (dataUrlMatch) {
return {
@@ -174,7 +231,6 @@ export class AnthropicProvider implements AIProvider {
},
} as ImageBlockParam;
}
- // For non-base64 URLs, Anthropic requires base64 so we can't support external URLs directly
return {
type: 'text',
text: `[Image URL: ${url}]`,
@@ -215,11 +271,13 @@ export class AnthropicProvider implements AIProvider {
},
];
- return {
+ result.push({
role: msg.role === 'user' ? 'user' : 'assistant',
content,
- };
- });
+ });
+ }
+
+ return result;
}
formatResponse(response: AnthropicMessage): {
diff --git a/packages/ai-gateway/src/providers/index.ts b/packages/ai-gateway/src/providers/index.ts
index 2143f54fe..35b236298 100644
--- a/packages/ai-gateway/src/providers/index.ts
+++ b/packages/ai-gateway/src/providers/index.ts
@@ -1,4 +1,5 @@
import { OpenAIProvider } from './openai';
+import { AnthropicProvider } from './anthropic';
import { VertexAIProvider } from './vertex';
import { GeminiProvider } from './gemini';
import { AIProvider } from './base';
@@ -6,15 +7,13 @@ import { Env } from '../types';
export function createProvider(model: string, env: Env): AIProvider {
if (model.toLowerCase().includes('claude')) {
- // Use Vertex AI for Claude models
- if (!env.VERTEX_SERVICE_ACCOUNT_JSON || !env.VERTEX_PROJECT_ID) {
- throw new Error('Vertex AI credentials not configured');
+ // Use direct Anthropic API for Claude models
+ // This gives us: dynamic model availability (Opus 4.6 etc.), simpler auth,
+ // no model ID mapping, and no silent fallback to wrong models
+ if (!env.ANTHROPIC_API_KEY) {
+ throw new Error('Anthropic API key not configured');
}
- return new VertexAIProvider(
- env.VERTEX_SERVICE_ACCOUNT_JSON,
- env.VERTEX_PROJECT_ID,
- env.VERTEX_REGION || 'us-east5'
- );
+ return new AnthropicProvider(env.ANTHROPIC_API_KEY);
}
if (model.toLowerCase().includes('gemini')) {
// Use Vertex AI for Gemini models
diff --git a/packages/ai-gateway/src/services/usage-tracker.test.ts b/packages/ai-gateway/src/services/usage-tracker.test.ts
index 1e34fe464..1a520ca5a 100644
--- a/packages/ai-gateway/src/services/usage-tracker.test.ts
+++ b/packages/ai-gateway/src/services/usage-tracker.test.ts
@@ -5,51 +5,49 @@ describe('TIER_CONFIG', () => {
it('should have correct limits for anonymous tier', () => {
expect(TIER_CONFIG.anonymous.dailyQueries).toBe(25);
expect(TIER_CONFIG.anonymous.rpm).toBe(5);
- expect(TIER_CONFIG.anonymous.allowedModels).toContain('claude-haiku-4-5@20251001');
+ expect(TIER_CONFIG.anonymous.allowedModels).toContain('claude-haiku-4-5');
});
it('should have correct limits for logged_in tier', () => {
expect(TIER_CONFIG.logged_in.dailyQueries).toBe(50);
expect(TIER_CONFIG.logged_in.rpm).toBe(10);
- expect(TIER_CONFIG.logged_in.allowedModels).toContain('claude-sonnet-4-20250514');
+ expect(TIER_CONFIG.logged_in.allowedModels).toContain('claude-sonnet-4-5');
});
- it('should have unlimited queries for subscribed tier', () => {
- expect(TIER_CONFIG.subscribed.dailyQueries).toBe(-1);
+ it('should have correct limits for subscribed tier', () => {
+ expect(TIER_CONFIG.subscribed.dailyQueries).toBe(200);
expect(TIER_CONFIG.subscribed.allowedModels).toContain('*');
});
});
describe('isModelAllowed', () => {
it('should allow haiku for anonymous users', () => {
- expect(isModelAllowed('claude-haiku-4-5@20251001', 'anonymous')).toBe(true);
- expect(isModelAllowed('claude-3-haiku-20240307', 'anonymous')).toBe(true);
+ expect(isModelAllowed('claude-haiku-4-5-20251001', 'anonymous')).toBe(true);
+ // Partial match via substring
+ expect(isModelAllowed('claude-haiku-4-5', 'anonymous')).toBe(true);
});
it('should deny sonnet for anonymous users', () => {
- expect(isModelAllowed('claude-sonnet-4-20250514', 'anonymous')).toBe(false);
- expect(isModelAllowed('claude-3-5-sonnet-20241022', 'anonymous')).toBe(false);
+ expect(isModelAllowed('claude-sonnet-4-5-20250929', 'anonymous')).toBe(false);
});
it('should allow sonnet for logged_in users', () => {
- expect(isModelAllowed('claude-sonnet-4-20250514', 'logged_in')).toBe(true);
+ expect(isModelAllowed('claude-sonnet-4-5-20250929', 'logged_in')).toBe(true);
expect(isModelAllowed('gpt-4o-mini', 'logged_in')).toBe(true);
});
it('should deny opus for logged_in users', () => {
- expect(isModelAllowed('claude-opus-4-20250514', 'logged_in')).toBe(false);
- // Note: gpt-4o partially matches gpt-4o-mini due to substring matching
- // This is acceptable - the API will reject if the model doesn't exist
+ expect(isModelAllowed('claude-opus-4-6', 'logged_in')).toBe(false);
});
it('should allow any model for subscribed users', () => {
- expect(isModelAllowed('claude-opus-4-20250514', 'subscribed')).toBe(true);
+ expect(isModelAllowed('claude-opus-4-6', 'subscribed')).toBe(true);
expect(isModelAllowed('gpt-4o', 'subscribed')).toBe(true);
expect(isModelAllowed('any-random-model', 'subscribed')).toBe(true);
});
it('should handle partial model name matches', () => {
- // Model names might have slight variations
+ // Model names might have slight variations — substring matching
expect(isModelAllowed('claude-haiku', 'anonymous')).toBe(true);
expect(isModelAllowed('haiku', 'anonymous')).toBe(true);
});
diff --git a/packages/ai-gateway/src/services/usage-tracker.ts b/packages/ai-gateway/src/services/usage-tracker.ts
index 59c53f66b..c8baa4cd6 100644
--- a/packages/ai-gateway/src/services/usage-tracker.ts
+++ b/packages/ai-gateway/src/services/usage-tracker.ts
@@ -9,8 +9,7 @@ export const TIER_CONFIG: Record<UserTier, TierLimits> = {
dailyQueries: 25,
rpm: 5,
allowedModels: [
- 'claude-haiku-4-5@20251001',
- 'claude-3-haiku-20240307',
+ 'claude-haiku-4-5',
'gemini-3-flash',
'gemini-2.5-flash',
],
@@ -19,10 +18,8 @@ export const TIER_CONFIG: Record<UserTier, TierLimits> = {
dailyQueries: 50,
rpm: 10,
allowedModels: [
- 'claude-haiku-4-5@20251001',
- 'claude-3-haiku-20240307',
- 'claude-sonnet-4-20250514',
- 'claude-3-5-sonnet-20241022',
+ 'claude-haiku-4-5',
+ 'claude-sonnet-4-5',
'gpt-4o-mini',
'gemini-3-flash',
'gemini-2.5-flash',
diff --git a/packages/ai-gateway/src/test/anthropic-proxy.unit.test.ts b/packages/ai-gateway/src/test/anthropic-proxy.unit.test.ts
new file mode 100644
index 000000000..51e588611
--- /dev/null
+++ b/packages/ai-gateway/src/test/anthropic-proxy.unit.test.ts
@@ -0,0 +1,583 @@
+/**
+ * Comprehensive unit tests for Anthropic API proxy
+ *
+ * Tests the migration from Vertex AI to direct Anthropic API for Claude models.
+ * Covers: proxy function, model listing, message sanitization, provider routing,
+ * edge cases with tool calls, system messages, streaming, and error handling.
+ *
+ * Run with: bun test src/test/anthropic-proxy.unit.test.ts
+ */
+
+import { describe, it, expect, mock, beforeEach, afterEach } from 'bun:test';
+import { proxyToAnthropic, listAnthropicModels } from '../providers/anthropic-proxy';
+import { sanitizeMessages } from '../providers/vertex';
+import { createProvider } from '../providers';
+import { isModelAllowed } from '../services/usage-tracker';
+import { AnthropicProvider } from '../providers/anthropic';
+
+// ============================================================================
+// proxyToAnthropic — request forwarding
+// ============================================================================
+describe('proxyToAnthropic', () => {
+ const originalFetch = globalThis.fetch;
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ it('should forward non-streaming request to api.anthropic.com', async () => {
+ let capturedUrl = '';
+ let capturedHeaders: Record<string, string> = {};
+ let capturedBody: any = null;
+
+ globalThis.fetch = async (url: any, init: any) => {
+ capturedUrl = url.toString();
+ capturedHeaders = Object.fromEntries(new Headers(init.headers).entries());
+ capturedBody = JSON.parse(init.body);
+ return new Response(JSON.stringify({
+ id: 'msg_123',
+ type: 'message',
+ role: 'assistant',
+ content: [{ type: 'text', text: 'Hello!' }],
+ model: 'claude-opus-4-6',
+ stop_reason: 'end_turn',
+ }), { status: 200, headers: { 'Content-Type': 'application/json' } });
+ };
+
+ const request = new Request('http://localhost/v1/messages', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model: 'claude-opus-4-6',
+ max_tokens: 1024,
+ messages: [{ role: 'user', content: 'Hello' }],
+ }),
+ });
+
+ const response = await proxyToAnthropic(request, 'sk-ant-test-key');
+ const data = await response.json();
+
+ // Verify it hit the Anthropic API
+ expect(capturedUrl).toBe('https://api.anthropic.com/v1/messages');
+ expect(capturedHeaders['x-api-key']).toBe('sk-ant-test-key');
+ expect(capturedHeaders['anthropic-version']).toBe('2023-06-01');
+ expect(capturedHeaders['content-type']).toBe('application/json');
+
+ // Verify model is kept in body (unlike Vertex which removes it)
+ expect(capturedBody.model).toBe('claude-opus-4-6');
+ expect(capturedBody.max_tokens).toBe(1024);
+
+ // Verify response passthrough
+ expect(data.content[0].text).toBe('Hello!');
+ expect(data.model).toBe('claude-opus-4-6');
+ });
+
+ it('should forward streaming request and return SSE response', async () => {
+ globalThis.fetch = async (url: any, init: any) => {
+ const body = JSON.parse(init.body);
+ expect(body.stream).toBe(true);
+
+ // Simulate Anthropic SSE stream
+ const stream = new ReadableStream({
+ start(controller) {
+ const encoder = new TextEncoder();
+ controller.enqueue(encoder.encode('event: message_start\ndata: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-opus-4-6"}}\n\n'));
+ controller.enqueue(encoder.encode('event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}\n\n'));
+ controller.enqueue(encoder.encode('event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hi"}}\n\n'));
+ controller.enqueue(encoder.encode('event: message_stop\ndata: {"type":"message_stop"}\n\n'));
+ controller.close();
+ },
+ });
+
+ return new Response(stream, {
+ status: 200,
+ headers: { 'Content-Type': 'text/event-stream' },
+ });
+ };
+
+ const request = new Request('http://localhost/v1/messages', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model: 'claude-opus-4-6',
+ max_tokens: 100,
+ stream: true,
+ messages: [{ role: 'user', content: 'Hi' }],
+ }),
+ });
+
+ const response = await proxyToAnthropic(request, 'sk-ant-test-key');
+
+ expect(response.headers.get('Content-Type')).toBe('text/event-stream');
+
+ // Read the stream
+ const reader = response.body!.getReader();
+ const decoder = new TextDecoder();
+ let fullText = '';
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ fullText += decoder.decode(value, { stream: true });
+ }
+
+ expect(fullText).toContain('message_start');
+ expect(fullText).toContain('text_delta');
+ expect(fullText).toContain('Hi');
+ expect(fullText).toContain('message_stop');
+ });
+
+ it('should sanitize nested text.text bug in messages', async () => {
+ let capturedBody: any = null;
+
+ globalThis.fetch = async (_url: any, init: any) => {
+ capturedBody = JSON.parse(init.body);
+ return new Response(JSON.stringify({
+ type: 'message', content: [{ type: 'text', text: 'ok' }],
+ }), { status: 200 });
+ };
+
+ const request = new Request('http://localhost/v1/messages', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model: 'claude-haiku-4-5-20251001',
+ max_tokens: 100,
+ messages: [{
+ role: 'user',
+ content: [{ type: 'text', text: { text: 'nested bug' } }],
+ }],
+ }),
+ });
+
+ await proxyToAnthropic(request, 'sk-ant-test-key');
+
+ // The sanitization should have fixed the nested text
+ expect(capturedBody.messages[0].content[0].text).toBe('nested bug');
+ expect(typeof capturedBody.messages[0].content[0].text).toBe('string');
+ });
+
+ it('should pass through Anthropic error format on non-200', async () => {
+ globalThis.fetch = async () => {
+ return new Response(JSON.stringify({
+ type: 'error',
+ error: {
+ type: 'invalid_request_error',
+ message: 'max_tokens: must be at least 1',
+ },
+ }), { status: 400, headers: { 'Content-Type': 'application/json' } });
+ };
+
+ const request = new Request('http://localhost/v1/messages', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model: 'claude-opus-4-6',
+ max_tokens: 0,
+ messages: [{ role: 'user', content: 'test' }],
+ }),
+ });
+
+ const response = await proxyToAnthropic(request, 'sk-ant-test-key');
+ expect(response.status).toBe(400);
+
+ const data = await response.json();
+ expect(data.type).toBe('error');
+ expect(data.error.type).toBe('invalid_request_error');
+ });
+
+ it('should handle network/fetch errors gracefully', async () => {
+ globalThis.fetch = async () => {
+ throw new Error('Network timeout');
+ };
+
+ const request = new Request('http://localhost/v1/messages', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model: 'claude-opus-4-6',
+ max_tokens: 100,
+ messages: [{ role: 'user', content: 'test' }],
+ }),
+ });
+
+ const response = await proxyToAnthropic(request, 'sk-ant-test-key');
+ expect(response.status).toBe(500);
+
+ const data = await response.json();
+ expect(data.type).toBe('error');
+ expect(data.error.message).toContain('Network timeout');
+ });
+
+ it('should not add anthropic_version in body (Vertex did this, direct API uses header)', async () => {
+ let capturedBody: any = null;
+
+ globalThis.fetch = async (_url: any, init: any) => {
+ capturedBody = JSON.parse(init.body);
+ return new Response(JSON.stringify({ type: 'message', content: [] }), { status: 200 });
+ };
+
+ const request = new Request('http://localhost/v1/messages', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model: 'claude-opus-4-6',
+ max_tokens: 100,
+ messages: [{ role: 'user', content: 'test' }],
+ }),
+ });
+
+ await proxyToAnthropic(request, 'sk-ant-test-key');
+
+ // Vertex added anthropic_version to body — direct API should NOT
+ expect(capturedBody.anthropic_version).toBeUndefined();
+ });
+
+ it('should keep model in request body (Vertex removed it)', async () => {
+ let capturedBody: any = null;
+
+ globalThis.fetch = async (_url: any, init: any) => {
+ capturedBody = JSON.parse(init.body);
+ return new Response(JSON.stringify({ type: 'message', content: [] }), { status: 200 });
+ };
+
+ const request = new Request('http://localhost/v1/messages', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model: 'claude-opus-4-6',
+ max_tokens: 100,
+ messages: [{ role: 'user', content: 'test' }],
+ }),
+ });
+
+ await proxyToAnthropic(request, 'sk-ant-test-key');
+
+ // Vertex deleted model from body — direct API must keep it
+ expect(capturedBody.model).toBe('claude-opus-4-6');
+ });
+
+ it('should handle tool use messages correctly', async () => {
+ let capturedBody: any = null;
+
+ globalThis.fetch = async (_url: any, init: any) => {
+ capturedBody = JSON.parse(init.body);
+ return new Response(JSON.stringify({ type: 'message', content: [] }), { status: 200 });
+ };
+
+ const request = new Request('http://localhost/v1/messages', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model: 'claude-opus-4-6',
+ max_tokens: 1024,
+ messages: [
+ { role: 'user', content: 'Search for info' },
+ {
+ role: 'assistant',
+ content: [
+ { type: 'text', text: 'Let me search.' },
+ { type: 'tool_use', id: 'toolu_1', name: 'search', input: { query: 'test' } },
+ ],
+ },
+ {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 'toolu_1', content: 'Found: results' },
+ ],
+ },
+ ],
+ }),
+ });
+
+ await proxyToAnthropic(request, 'sk-ant-test-key');
+
+ // Tool messages should pass through as-is (Anthropic format → Anthropic API)
+ expect(capturedBody.messages[1].content[1].type).toBe('tool_use');
+ expect(capturedBody.messages[2].content[0].type).toBe('tool_result');
+ });
+
+ it('should pass through system parameter', async () => {
+ let capturedBody: any = null;
+
+ globalThis.fetch = async (_url: any, init: any) => {
+ capturedBody = JSON.parse(init.body);
+ return new Response(JSON.stringify({ type: 'message', content: [] }), { status: 200 });
+ };
+
+ const request = new Request('http://localhost/v1/messages', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model: 'claude-opus-4-6',
+ max_tokens: 100,
+ system: 'You are a helpful assistant.',
+ messages: [{ role: 'user', content: 'Hello' }],
+ }),
+ });
+
+ await proxyToAnthropic(request, 'sk-ant-test-key');
+
+ // System parameter should be passed through as-is
+ expect(capturedBody.system).toBe('You are a helpful assistant.');
+ });
+});
+
+// ============================================================================
+// listAnthropicModels
+// ============================================================================
+describe('listAnthropicModels', () => {
+ const originalFetch = globalThis.fetch;
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ });
+
+ it('should return models from API response', async () => {
+ globalThis.fetch = async (url: any, init: any) => {
+ expect(url.toString()).toBe('https://api.anthropic.com/v1/models');
+ expect(new Headers(init.headers).get('x-api-key')).toBe('sk-test');
+
+ return new Response(JSON.stringify({
+ data: [
+ { id: 'claude-opus-4-6', display_name: 'Claude Opus 4.6', created_at: '2026-02-05T00:00:00Z', type: 'model' },
+ { id: 'claude-sonnet-4-5-20250929', display_name: 'Claude Sonnet 4.5', created_at: '2025-09-29T00:00:00Z', type: 'model' },
+ { id: 'claude-haiku-4-5-20251001', display_name: 'Claude Haiku 4.5', created_at: '2025-10-01T00:00:00Z', type: 'model' },
+ ],
+ }), { status: 200 });
+ };
+
+ const models = await listAnthropicModels('sk-test');
+
+ expect(models.length).toBe(3);
+ expect(models[0].id).toBe('claude-opus-4-6');
+ expect(models[0].owned_by).toBe('anthropic');
+ expect(models[0].object).toBe('model');
+ });
+
+ it('should return fallback models on API error', async () => {
+ globalThis.fetch = async () => new Response('Unauthorized', { status: 401 });
+
+ const models = await listAnthropicModels('bad-key');
+
+ // Should return fallback list
+ expect(models.length).toBeGreaterThan(0);
+ expect(models.some(m => m.id.includes('opus-4-6'))).toBe(true);
+ expect(models.some(m => m.id.includes('haiku'))).toBe(true);
+ });
+
+ it('should return fallback models on network error', async () => {
+ globalThis.fetch = async () => { throw new Error('DNS fail'); };
+
+ const models = await listAnthropicModels('sk-test');
+ expect(models.length).toBeGreaterThan(0);
+ });
+});
+
+// ============================================================================
+// createProvider routing
+// ============================================================================
+describe('createProvider routing', () => {
+ it('should route claude models to AnthropicProvider', () => {
+ const env = {
+ ANTHROPIC_API_KEY: 'sk-ant-test',
+ VERTEX_SERVICE_ACCOUNT_JSON: '{}',
+ VERTEX_PROJECT_ID: 'test',
+ } as any;
+
+ const provider = createProvider('claude-opus-4-6', env);
+ expect(provider).toBeInstanceOf(AnthropicProvider);
+ });
+
+ it('should route claude-haiku to AnthropicProvider', () => {
+ const env = { ANTHROPIC_API_KEY: 'sk-ant-test' } as any;
+ const provider = createProvider('claude-haiku-4-5-20251001', env);
+ expect(provider).toBeInstanceOf(AnthropicProvider);
+ });
+
+ it('should throw if ANTHROPIC_API_KEY missing for claude', () => {
+ const env = {} as any;
+ expect(() => createProvider('claude-opus-4-6', env)).toThrow('Anthropic API key not configured');
+ });
+
+ it('should route gemini models to GeminiProvider (not AnthropicProvider)', () => {
+ const env = {
+ ANTHROPIC_API_KEY: 'sk-ant-test',
+ VERTEX_SERVICE_ACCOUNT_JSON: '{"type":"service_account","private_key":"-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBg...\\n-----END PRIVATE KEY-----\\n","client_email":"[email protected]","token_uri":"https://oauth2.googleapis.com/token"}',
+ VERTEX_PROJECT_ID: 'test-project',
+ } as any;
+
+ const provider = createProvider('gemini-3-flash', env);
+ // Should NOT be AnthropicProvider
+ expect(provider).not.toBeInstanceOf(AnthropicProvider);
+ });
+});
+
+// ============================================================================
+// AnthropicProvider.formatMessages — OpenAI ↔ Anthropic conversion
+// ============================================================================
+describe('AnthropicProvider.formatMessages', () => {
+ const provider = new AnthropicProvider('sk-test');
+
+ it('should skip system messages (they go to system parameter)', () => {
+ const result = provider.formatMessages([
+ { role: 'system', content: 'You are helpful.' },
+ { role: 'user', content: 'Hi' },
+ ]);
+
+ expect(result.length).toBe(1);
+ expect(result[0].role).toBe('user');
+ });
+
+ it('should convert tool results from OpenAI to Anthropic format', () => {
+ const result = provider.formatMessages([
+ { role: 'user', content: 'Search' },
+ {
+ role: 'assistant',
+ content: 'Searching...',
+ tool_calls: [{
+ id: 'call_1',
+ type: 'function' as const,
+ function: { name: 'search', arguments: '{"q":"test"}' },
+ }],
+ },
+ {
+ role: 'tool',
+ content: 'Found: result',
+ tool_call_id: 'call_1',
+ } as any,
+ ]);
+
+ expect(result.length).toBe(3);
+
+ // Assistant with tool_use
+ expect(result[1].role).toBe('assistant');
+ const assistantContent = result[1].content as any[];
+ expect(assistantContent.some((c: any) => c.type === 'tool_use')).toBe(true);
+ const toolUse = assistantContent.find((c: any) => c.type === 'tool_use');
+ expect(toolUse.name).toBe('search');
+ expect(toolUse.input).toEqual({ q: 'test' });
+
+ // Tool result as user message
+ expect(result[2].role).toBe('user');
+ const toolResult = (result[2].content as any[])[0];
+ expect(toolResult.type).toBe('tool_result');
+ expect(toolResult.tool_use_id).toBe('call_1');
+ expect(toolResult.content).toBe('Found: result');
+ });
+
+ it('should handle image_url content parts', () => {
+ const result = provider.formatMessages([{
+ role: 'user',
+ content: [
+ { type: 'text', text: 'What is this?' },
+ {
+ type: 'image_url',
+ image_url: { url: 'data:image/png;base64,iVBOR...' },
+ },
+ ] as any,
+ }]);
+
+ expect(result.length).toBe(1);
+ const content = result[0].content as any[];
+ expect(content[0].type).toBe('text');
+ expect(content[1].type).toBe('image');
+ expect(content[1].source.type).toBe('base64');
+ expect(content[1].source.media_type).toBe('image/png');
+ });
+
+ it('should handle string content messages', () => {
+ const result = provider.formatMessages([
+ { role: 'user', content: 'Hello world' },
+ ]);
+
+ expect(result.length).toBe(1);
+ const content = result[0].content as any[];
+ expect(content[0].type).toBe('text');
+ expect(content[0].text).toBe('Hello world');
+ });
+});
+
+// ============================================================================
+// isModelAllowed — tier-based model access
+// ============================================================================
+describe('isModelAllowed with Anthropic model IDs', () => {
+ it('should allow haiku for anonymous users', () => {
+ expect(isModelAllowed('claude-haiku-4-5-20251001', 'anonymous')).toBe(true);
+ });
+
+ it('should deny opus for anonymous users', () => {
+ expect(isModelAllowed('claude-opus-4-6', 'anonymous')).toBe(false);
+ });
+
+ it('should deny opus for logged_in users', () => {
+ expect(isModelAllowed('claude-opus-4-6', 'logged_in')).toBe(false);
+ });
+
+ it('should allow opus for subscribed users', () => {
+ expect(isModelAllowed('claude-opus-4-6', 'subscribed')).toBe(true);
+ });
+
+ it('should allow sonnet for logged_in users', () => {
+ expect(isModelAllowed('claude-sonnet-4-5-20250929', 'logged_in')).toBe(true);
+ });
+
+ it('should allow any model for subscribed (wildcard)', () => {
+ expect(isModelAllowed('claude-opus-4-6', 'subscribed')).toBe(true);
+ expect(isModelAllowed('some-random-model', 'subscribed')).toBe(true);
+ });
+
+ it('should allow gemini flash for anonymous', () => {
+ expect(isModelAllowed('gemini-2.5-flash', 'anonymous')).toBe(true);
+ });
+});
+
+// ============================================================================
+// Model ID format — no more @YYYYMMDD
+// ============================================================================
+describe('Model ID format consistency', () => {
+ it('Opus 4.6 has no date suffix', () => {
+ // The Anthropic API uses 'claude-opus-4-6' with no date suffix
+ // This verifies our code doesn't break on models without dates
+ const model = 'claude-opus-4-6';
+ expect(model).not.toContain('@');
+ expect(isModelAllowed(model, 'subscribed')).toBe(true);
+ });
+
+ it('Haiku still works with date suffix (dash format)', () => {
+ const model = 'claude-haiku-4-5-20251001';
+ expect(model).not.toContain('@');
+ expect(isModelAllowed(model, 'anonymous')).toBe(true);
+ });
+});
+
+// ============================================================================
+// Regression: sanitizeMessages still works (from vertex.ts, shared)
+// ============================================================================
+describe('sanitizeMessages (shared)', () => {
+ it('should fix nested text.text structure', () => {
+ const messages = [
+ { role: 'user', content: [{ type: 'text', text: { text: 'Hello world' } }] },
+ ];
+ const sanitized = sanitizeMessages(messages);
+ expect(sanitized[0].content[0].text).toBe('Hello world');
+ expect(typeof sanitized[0].content[0].text).toBe('string');
+ });
+
+ it('should not modify correctly formatted messages', () => {
+ const messages = [
+ { role: 'user', content: 'Hello' },
+ { role: 'assistant', content: 'Hi there!' },
+ ];
+ const sanitized = sanitizeMessages(messages);
+ expect(sanitized[0].content).toBe('Hello');
+ expect(sanitized[1].content).toBe('Hi there!');
+ });
+
+ it('should handle deeply nested text', () => {
+ const messages = [
+ { role: 'user', content: [{ type: 'text', text: { text: { text: 'deep' } } }] },
+ ];
+ const sanitized = sanitizeMessages(messages);
+ expect(sanitized[0].content[0].text).toBe('deep');
+ });
+});
diff --git a/packages/ai-gateway/src/types.ts b/packages/ai-gateway/src/types.ts
index 3523dca6f..b24ce9bbb 100644
--- a/packages/ai-gateway/src/types.ts
+++ b/packages/ai-gateway/src/types.ts
@@ -66,6 +66,7 @@ export interface RequestBody {
stream?: boolean;
tools?: any[];
temperature?: number;
+ max_tokens?: number;
tool_choice?: string | { type: 'function'; function: { name: string } };
response_format?: ResponseFormat;
}