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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix ai gateway sentry regressions (#3379)
Louis Beaumontb4563754cf43
diff --git a/packages/ai-gateway/src/handlers/models.ts b/packages/ai-gateway/src/handlers/models.tsindex 1a837e50d..aa2034f78 100644--- a/packages/ai-gateway/src/handlers/models.ts+++ b/packages/ai-gateway/src/handlers/models.ts@@ -42,6 +42,14 @@ interface ModelEntry {query_weight?: number;}+function hasConfiguredSecret(value: unknown): boolean {+ if (typeof value !== 'string') return false;+ const trimmed = value.trim();+ if (!trimmed) return false;+ const lower = trimmed.toLowerCase();+ return !['placeholder', 'changeme', 'change-me', 'todo', 'none', 'null', 'undefined'].includes(lower);+}+/** Curated model catalog — single source of truth */const CURATED_MODELS: ModelEntry[] = [// ── Auto — smart routing with fallback ──@@ -585,7 +593,7 @@ export async function handleModelListing(env: Env, tier: UserTier = 'subscribed'// Avoid advertising models that would immediately fail because their// provider secret is not configured in the Worker environment yet.- models = models.filter(model => !model.requires_env || Boolean(env[model.requires_env]));+ models = models.filter(model => !model.requires_env || hasConfiguredSecret(env[model.requires_env]));// Filter models based on tier allowlistif (tier !== 'subscribed') {diff --git a/packages/ai-gateway/src/index.ts b/packages/ai-gateway/src/index.tsindex 7595643b4..aca05a7c4 100644--- a/packages/ai-gateway/src/index.ts+++ b/packages/ai-gateway/src/index.ts@@ -88,7 +88,15 @@ async function handleRequest(request: Request, env: Env, ctx: ExecutionContext):// Chat completions - main AI endpointif (path === '/v1/chat/completions' && request.method === 'POST') {- const body = (await request.json()) as RequestBody;+ let body: RequestBody;+ try {+ body = (await request.json()) as RequestBody;+ } catch {+ return addCorsHeaders(createErrorResponse(400, JSON.stringify({+ error: 'invalid_json',+ message: 'Request body must be valid JSON.',+ })));+ }// Check if model is allowed for this tierif (!isModelAllowed(body.model, authResult.tier, env)) {diff --git a/packages/ai-gateway/src/providers/anthropic.ts b/packages/ai-gateway/src/providers/anthropic.tsindex 1673606b0..ef64ed6d2 100644--- a/packages/ai-gateway/src/providers/anthropic.ts+++ b/packages/ai-gateway/src/providers/anthropic.ts@@ -14,6 +14,31 @@ import type {ContentBlockParam,} from '@anthropic-ai/sdk/resources';+function nonEmptyText(value: unknown): string | null {+ if (typeof value !== 'string') return null;+ return value.trim().length > 0 ? value : null;+}++function safeJson(value: unknown): string {+ if (typeof value === 'string') return value;+ try {+ return JSON.stringify(value ?? {});+ } catch {+ return '{}';+ }+}++function safeToolInput(value: unknown): Record<string, any> {+ if (typeof value === 'string') {+ try {+ return JSON.parse(value);+ } catch {+ return {};+ }+ }+ return (value && typeof value === 'object') ? value as Record<string, any> : {};+}+export class AnthropicProvider implements AIProvider {supportsTools = true;supportsVision = true;@@ -265,7 +290,7 @@ export class AnthropicProvider implements AIProvider {content: [{type: 'tool_result',tool_use_id: sanitizeToolUseId((msg as any).tool_call_id),- content: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),+ content: nonEmptyText(typeof msg.content === 'string' ? msg.content : safeJson(msg.content)) ?? '[empty tool result]',}] as any,});continue;@@ -279,15 +304,16 @@ export class AnthropicProvider implements AIProvider {if (text) content.push({ type: 'text', text });}for (const tc of (msg as any).tool_calls) {+ const name = tc.function?.name || tc.name;+ if (!name) continue;content.push({type: 'tool_use',id: sanitizeToolUseId(tc.id),- name: tc.function?.name || tc.name,- input: typeof tc.function?.arguments === 'string'- ? JSON.parse(tc.function.arguments)- : tc.function?.arguments || {},+ name,+ input: safeToolInput(tc.function?.arguments ?? tc.input),});}+ if (content.length === 0) continue;result.push({role: 'assistant',content: content as any,@@ -297,83 +323,84 @@ export class AnthropicProvider implements AIProvider {// Regular user/assistant messagesconst content: ContentBlockParam[] = Array.isArray(msg.content)- ? msg.content.map((part) => {+ ? msg.content.flatMap((part): ContentBlockParam[] => {+ if (part.type === 'text') {+ const text = nonEmptyText(part.text);+ return text ? [{ type: 'text', text } as TextBlock] : [];+ }// Handle OpenAI vision format (image_url)if (part.type === 'image_url' && part.image_url?.url) {const url = part.image_url.url;const dataUrlMatch = url.match(/^data:([^;]+);base64,(.+)$/);if (dataUrlMatch) {- return {+ return [{type: 'image',source: {type: 'base64',media_type: dataUrlMatch[1] as 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp',data: dataUrlMatch[2],},- } as ImageBlockParam;+ } as ImageBlockParam];}- return {+ return [{type: 'text',text: `[Image URL: ${url}]`,- } as TextBlock;+ } as TextBlock];}// Handle Pi native format: { type: "image", data: "base64...", mimeType: "image/png" }if (part.type === 'image' && part.data && part.mimeType) {- return {+ return [{type: 'image',source: {type: 'base64',media_type: part.mimeType as 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp',data: part.data as string,},- } as ImageBlockParam;+ } as ImageBlockParam];}// Handle Anthropic native format (from Pi agent)// Normalize mediaType (camelCase) to media_type (snake_case)if (part.type === 'image' && part.source?.type === 'base64') {- return {+ return [{type: 'image',source: {type: 'base64',media_type: part.source.media_type || part.source.mediaType || 'image/png',data: part.source.data,},- } as ImageBlockParam;+ } as ImageBlockParam];}// Legacy format supportif (part.type === 'image' && part.image?.url) {const url = part.image.url;const dataUrlMatch = url.match(/^data:([^;]+);base64,(.+)$/);if (dataUrlMatch) {- return {+ return [{type: 'image',source: {type: 'base64',media_type: dataUrlMatch[1] as 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp',data: dataUrlMatch[2],},- } as ImageBlockParam;+ } as ImageBlockParam];}- return {+ return [{type: 'image',source: {type: 'base64',media_type: 'image/jpeg',data: url,},- } as ImageBlockParam;+ } as ImageBlockParam];}- return {- type: 'text',- text: part.text || '',- } as TextBlock;+ return [];})- : [- {- type: 'text',- text: msg.content as string,- },- ];+ : (() => {+ const text = nonEmptyText(msg.content);+ return text ? [{ type: 'text', text } as TextBlock] : [];+ })();++ if (content.length === 0) continue;result.push({role: msg.role === 'user' ? 'user' : 'assistant',diff --git a/packages/ai-gateway/src/providers/gemini.ts b/packages/ai-gateway/src/providers/gemini.tsindex f09a11c42..77f8dd217 100644--- a/packages/ai-gateway/src/providers/gemini.ts+++ b/packages/ai-gateway/src/providers/gemini.ts@@ -12,6 +12,30 @@ export interface VertexGeminiConfig {region?: string;}+function nonEmptyText(value: unknown): string | null {+ if (typeof value !== 'string') return null;+ return value.trim().length > 0 ? value : null;+}++function safeToolArgs(value: unknown): Record<string, any> {+ if (typeof value === 'string') {+ try {+ return JSON.parse(value);+ } catch {+ return {};+ }+ }+ return (value && typeof value === 'object') ? value as Record<string, any> : {};+}++function safeJson(value: unknown): string {+ try {+ return JSON.stringify(value ?? {});+ } catch {+ return '{}';+ }+}+export class GeminiProvider implements AIProvider {supportsTools = true;supportsVision = true;@@ -688,11 +712,13 @@ export class GeminiProvider implements AIProvider {const parts: any[] = [];if (typeof msg.content === 'string') {- parts.push({ text: msg.content });+ const text = nonEmptyText(msg.content);+ if (text) parts.push({ text });} else if (Array.isArray(msg.content)) {for (const part of msg.content) {if (part.type === 'text') {- parts.push({ text: part.text || '' });+ const text = nonEmptyText(part.text);+ if (text) parts.push({ text });} else if (part.type === 'image_url' && part.image_url?.url) {const url = part.image_url.url;const dataUrlMatch = url.match(/^data:([^;]+);base64,(.+)$/);@@ -738,27 +764,32 @@ export class GeminiProvider implements AIProvider {},});}+ } else if ((part as any).type === 'tool_use' && msg.role === 'assistant') {+ const toolPart = this.formatFunctionCallPart(+ (part as any).name,+ (part as any).input ?? {},+ (part as any).id,+ );+ if (toolPart) parts.push(toolPart);+ } else if ((part as any).type === 'tool_result') {+ const text = nonEmptyText(+ typeof (part as any).content === 'string'+ ? (part as any).content+ : safeJson((part as any).content),+ );+ if (text) parts.push({ text });}}}if (msg.role === 'assistant' && (msg as any).tool_calls) {for (const toolCall of (msg as any).tool_calls) {- const callPart: any = {- functionCall: {- name: toolCall.function?.name || toolCall.name,- args: typeof toolCall.function?.arguments === 'string'- ? JSON.parse(toolCall.function.arguments)- : toolCall.function?.arguments || {},- },- };- const tsMatch = (toolCall.id || '').match(/_ts_(.+)$/);- if (tsMatch) {- try {- callPart.thoughtSignature = atob(tsMatch[1]);- } catch {}- }- parts.push(callPart);+ const callPart = this.formatFunctionCallPart(+ toolCall.function?.name || toolCall.name,+ toolCall.function?.arguments ?? toolCall.input,+ toolCall.id,+ );+ if (callPart) parts.push(callPart);}}@@ -772,6 +803,24 @@ export class GeminiProvider implements AIProvider {return formatted;}+ private formatFunctionCallPart(name: unknown, argsInput: unknown, id: unknown): any | null {+ if (typeof name !== 'string' || name.length === 0) return null;+ const args = safeToolArgs(argsInput);+ const tsMatch = typeof id === 'string' ? id.match(/_ts_(.+)$/) : null;+ if (!tsMatch) {+ return { text: `[function call: ${name}] ${safeJson(args)}` };+ }+ const callPart: any = {+ functionCall: { name, args },+ };+ try {+ callPart.thoughtSignature = atob(tsMatch[1]);+ } catch {+ return { text: `[function call: ${name}] ${safeJson(args)}` };+ }+ return callPart;+ }+private formatGroundingSources(groundingMetadata: any): string {if (!groundingMetadata?.groundingChunks?.length) return '';diff --git a/packages/ai-gateway/src/providers/index.ts b/packages/ai-gateway/src/providers/index.tsindex 8f2bc1c3b..bbc6e8fd7 100644--- a/packages/ai-gateway/src/providers/index.ts+++ b/packages/ai-gateway/src/providers/index.ts@@ -42,6 +42,29 @@ function isOpenRouterModel(model: string): boolean {OPENROUTER_MODELS.some(m => lower.includes(m));}+class ProviderConfigurationError extends Error {+ status = 503;+ constructor(message: string) {+ super(message);+ this.name = 'ProviderConfigurationError';+ }+}++function isConfiguredSecret(value: unknown): value is string {+ if (typeof value !== 'string') return false;+ const trimmed = value.trim();+ if (!trimmed) return false;+ const lower = trimmed.toLowerCase();+ return !['placeholder', 'changeme', 'change-me', 'todo', 'none', 'null', 'undefined'].includes(lower);+}++function requireSecret(value: unknown, message: string): string {+ if (!isConfiguredSecret(value)) {+ throw new ProviderConfigurationError(message);+ }+ return value.trim();+}+export function createProvider(model: string, env: Env): AIProvider {model = resolveModelAlias(model);@@ -51,10 +74,7 @@ export function createProvider(model: string, env: Env): AIProvider {return new OpenAIProvider('none', vllmUrl);}if (model.toLowerCase().includes('claude')) {- if (!env.ANTHROPIC_API_KEY) {- throw new Error('Anthropic API key not configured');- }- return new AnthropicProvider(env.ANTHROPIC_API_KEY);+ return new AnthropicProvider(requireSecret(env.ANTHROPIC_API_KEY, 'Anthropic API key not configured'));}if (model.toLowerCase().includes('gemini')) {// Prefer Vertex AI for Gemini (shorter data retention, enterprise ToS)@@ -66,43 +86,32 @@ export function createProvider(model: string, env: Env): AIProvider {});}// Fallback to API key if Vertex credentials unavailable- if (!env.GEMINI_API_KEY) {- throw new Error('Gemini API key not configured');- }- return new GeminiProvider(env.GEMINI_API_KEY);+ return new GeminiProvider(requireSecret(env.GEMINI_API_KEY, 'Gemini API key not configured'));}// Vertex AI MaaS — GLM-4.7, GLM-5, Kimi K2.5, DeepSeek, Llama, Qwen (burns GCP credits, free for users)if (isVertexMaasModel(model)) {- if (!env.VERTEX_SERVICE_ACCOUNT_JSON || !env.VERTEX_PROJECT_ID) {- throw new Error('Vertex AI credentials not configured');- }- return new VertexMaasProvider(env.VERTEX_SERVICE_ACCOUNT_JSON, env.VERTEX_PROJECT_ID);+ const serviceAccountJson = requireSecret(env.VERTEX_SERVICE_ACCOUNT_JSON, 'Vertex AI credentials not configured');+ const projectId = requireSecret(env.VERTEX_PROJECT_ID, 'Vertex AI credentials not configured');+ return new VertexMaasProvider(serviceAccountJson, projectId);}// Tinfoil — confidential inference in secure enclaves (TEE)if (isTinfoilModel(model)) {- if (!env.TINFOIL_API_KEY) {- throw new Error('Tinfoil API key not configured');- }- return new TinfoilProvider(env.TINFOIL_API_KEY);+ return new TinfoilProvider(requireSecret(env.TINFOIL_API_KEY, 'Tinfoil API key not configured'));}// Screenpipe enclave — our own Tinfoil-hosted CVM serving Gemma 4 E4B// (audio + vision + chat) alongside the privacy-filter. Tinfoil tokens// are org-scoped so TINFOIL_API_KEY works against this shim too; we// only require a dedicated SCREENPIPE_ENCLAVE_API_KEY if it's set.if (isScreenpipeEnclaveModel(model)) {- const key = env.SCREENPIPE_ENCLAVE_API_KEY || env.TINFOIL_API_KEY;- if (!key) {- throw new Error('No Tinfoil API key configured (need SCREENPIPE_ENCLAVE_API_KEY or TINFOIL_API_KEY)');- }- return new ScreenpipeEnclaveProvider(key);+ const key = isConfiguredSecret(env.SCREENPIPE_ENCLAVE_API_KEY)+ ? env.SCREENPIPE_ENCLAVE_API_KEY+ : env.TINFOIL_API_KEY;+ return new ScreenpipeEnclaveProvider(requireSecret(key, 'No Tinfoil API key configured (need SCREENPIPE_ENCLAVE_API_KEY or TINFOIL_API_KEY)'));}if (isOpenRouterModel(model)) {- if (!env.OPENROUTER_API_KEY) {- throw new Error('OpenRouter API key not configured');- }- return new OpenRouterProvider(env.OPENROUTER_API_KEY);+ return new OpenRouterProvider(requireSecret(env.OPENROUTER_API_KEY, 'OpenRouter API key not configured'));}- return new OpenAIProvider(env.OPENAI_API_KEY);+ return new OpenAIProvider(requireSecret(env.OPENAI_API_KEY, 'OpenAI API key not configured'));}export type { AIProvider };diff --git a/packages/ai-gateway/src/providers/vertex-maas.ts b/packages/ai-gateway/src/providers/vertex-maas.tsindex bb7ed4d18..8934b957d 100644--- a/packages/ai-gateway/src/providers/vertex-maas.ts+++ b/packages/ai-gateway/src/providers/vertex-maas.ts@@ -36,6 +36,33 @@ export class UpstreamError extends Error {}}+function nonEmptyText(value: unknown): string | null {+ if (typeof value !== 'string') return null;+ return value.trim().length > 0 ? value : null;+}++function safeJson(value: unknown): string {+ if (typeof value === 'string') return value;+ try {+ return JSON.stringify(value ?? {});+ } catch {+ return '{}';+ }+}++export async function parseVertexMaasJsonResponse(response: Response, model: string): Promise<any> {+ const text = await response.text();+ if (!text.trim()) {+ throw new UpstreamError(`Vertex MaaS returned an empty response body (${model})`, 502);+ }+ try {+ return JSON.parse(text);+ } catch (error: any) {+ const msg = error?.message ? `: ${error.message}` : '';+ throw new UpstreamError(`Vertex MaaS returned invalid JSON (${model})${msg}`, 502);+ }+}+async function fetchWithRetry(url: string, init: RequestInit, label: string): Promise<Response> {for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {const response = await fetch(url, init);@@ -251,7 +278,7 @@ export class VertexMaasProvider implements AIProvider {);}- const result = await response.json();+ const result = await parseVertexMaasJsonResponse(response, resolved.vertexId);promoteReasoningToContent(result);return new Response(JSON.stringify(result), {headers: { 'Content-Type': 'application/json' },@@ -305,45 +332,64 @@ export class VertexMaasProvider implements AIProvider {formatMessages(messages: Message[]): any[] {return messages.map((msg) => ({role: msg.role,- content: Array.isArray(msg.content)- ? msg.content- // Vertex MaaS rejects `type: 'thinking'` / `'redacted_thinking'`- // content blocks with `400 INVALID_ARGUMENT: Unrecognized 'type'- // field in an object element of an array 'content' field`- // (SCREENPIPE-AI-PROXY-C). Clients echoing prior assistant- // turns can include them; strip before sending. The actual- // answer text travels in a sibling `{type:'text'}` block, so- // dropping the thinking block doesn't lose the response.- // Cast to any: our `MessagePart` union doesn't list these- // types (they're Anthropic-specific) but clients send them.- .filter((part) => {- const t = (part as any)?.type;- return t !== 'thinking' && t !== 'redacted_thinking';- })- .map((part) => {- if (part.type === 'text') return { type: 'text', text: part.text || '' };- // OpenAI image_url format passthrough- if (part.type === 'image_url' && part.image_url?.url) {- return { type: 'image_url', image_url: { url: part.image_url.url } };- }- // Pi native format: { type: "image", data, mimeType }- if (part.type === 'image' && part.data && part.mimeType) {- return { type: 'image_url', image_url: { url: `data:${part.mimeType};base64,${part.data}` } };- }- // Anthropic base64 format- if (part.type === 'image' && part.source?.type === 'base64') {- const mt = part.source.media_type || part.source.mediaType || 'image/png';- return { type: 'image_url', image_url: { url: `data:${mt};base64,${part.source.data}` } };- }- return part;- })- : msg.content,- ...(msg.tool_calls && { tool_calls: msg.tool_calls }),+ ...this.formatMessageContent(msg),...(msg.tool_call_id && { tool_call_id: msg.tool_call_id }),...(msg.name && { name: msg.name }),}));}+ private formatMessageContent(msg: Message): { content: any; tool_calls?: any[] } {+ if (!Array.isArray(msg.content)) {+ return { content: nonEmptyText(msg.content) ?? '' };+ }++ const content: any[] = [];+ const toolCalls: any[] = [...((msg as any).tool_calls ?? [])];++ for (const part of msg.content as any[]) {+ const type = part?.type;+ if (type === 'text') {+ const text = nonEmptyText(part.text);+ if (text) content.push({ type: 'text', text });+ continue;+ }+ if (type === 'image_url' && part.image_url?.url) {+ content.push({ type: 'image_url', image_url: { url: part.image_url.url } });+ continue;+ }+ if (type === 'image' && part.data && part.mimeType) {+ content.push({ type: 'image_url', image_url: { url: `data:${part.mimeType};base64,${part.data}` } });+ continue;+ }+ if (type === 'image' && part.source?.type === 'base64') {+ const mt = part.source.media_type || part.source.mediaType || 'image/png';+ content.push({ type: 'image_url', image_url: { url: `data:${mt};base64,${part.source.data}` } });+ continue;+ }+ if (type === 'tool_use' && msg.role === 'assistant' && part.name) {+ toolCalls.push({+ id: part.id || `call_${toolCalls.length + 1}`,+ type: 'function',+ function: {+ name: part.name,+ arguments: safeJson(part.input ?? {}),+ },+ });+ continue;+ }+ if (type === 'tool_result') {+ const text = nonEmptyText(typeof part.content === 'string' ? part.content : safeJson(part.content));+ if (text) content.push({ type: 'text', text });+ }+ }++ const formatted: { content: any; tool_calls?: any[] } = {+ content: content.length > 0 ? content : toolCalls.length > 0 ? null : '',+ };+ if (toolCalls.length > 0) formatted.tool_calls = toolCalls;+ return formatted;+ }+formatResponse(response: any): any {return response;}diff --git a/packages/ai-gateway/src/services/usage-tracker.ts b/packages/ai-gateway/src/services/usage-tracker.tsindex e7971dc70..dc5ec6d41 100644--- a/packages/ai-gateway/src/services/usage-tracker.ts+++ b/packages/ai-gateway/src/services/usage-tracker.ts@@ -185,6 +185,7 @@ const DEFAULT_TIER_CONFIG: Record<UserTier, TierLimits> = {allowedModels: ['auto','claude-haiku-4-5',+ 'gemini-2.5-flash','gemini-3-flash','gemini-3.1-flash-lite','glm-4.7',@@ -202,6 +203,7 @@ const DEFAULT_TIER_CONFIG: Record<UserTier, TierLimits> = {'auto','claude-haiku-4-5','claude-sonnet-4-5',+ 'gemini-2.5-flash','gemini-3-flash','gemini-3.1-flash-lite','gemini-3-pro',diff --git a/packages/ai-gateway/src/test/anthropic-proxy.unit.test.ts b/packages/ai-gateway/src/test/anthropic-proxy.unit.test.tsindex edb5c2b76..00369e9bb 100644--- a/packages/ai-gateway/src/test/anthropic-proxy.unit.test.ts+++ b/packages/ai-gateway/src/test/anthropic-proxy.unit.test.ts@@ -554,6 +554,24 @@ describe('AnthropicProvider.formatMessages', () => {expect(content[0].type).toBe('text');expect(content[0].text).toBe('Hello world');});++ it('filters empty text blocks before sending to Anthropic', () => {+ const result = provider.formatMessages([+ {+ role: 'user',+ content: [+ { type: 'text', text: '' },+ { type: 'text', text: ' ' },+ { type: 'text', text: 'Hello' },+ ] as any,+ },+ { role: 'assistant', content: '' },+ ]);++ expect(result.length).toBe(1);+ const content = result[0].content as any[];+ expect(content).toEqual([{ type: 'text', text: 'Hello' }]);+ });});// ============================================================================diff --git a/packages/ai-gateway/src/test/gemini.unit.test.ts b/packages/ai-gateway/src/test/gemini.unit.test.tsindex 9465694d2..436f5b1ea 100644--- a/packages/ai-gateway/src/test/gemini.unit.test.ts+++ b/packages/ai-gateway/src/test/gemini.unit.test.ts@@ -174,3 +174,56 @@ describe('GeminiProvider tool schema conversion (Sentry SCREENPIPE-AI-PROXY-9)',expect(out.properties.name.items).toBeUndefined();});});++describe('GeminiProvider.formatMessages history sanitization', () => {+ const provider = new GeminiProvider('fake-api-key') as any;++ it('drops empty text parts', () => {+ const result = provider.formatMessages([{+ role: 'user',+ content: [+ { type: 'text', text: '' },+ { type: 'text', text: ' ' },+ { type: 'text', text: 'hello' },+ ] as any,+ }]);++ expect(result).toEqual([{ role: 'user', parts: [{ text: 'hello' }] }]);+ });++ it('does not replay Gemini function calls without thought signatures', () => {+ const result = provider.formatMessages([{+ role: 'assistant',+ content: '',+ tool_calls: [{+ id: 'call_read_without_signature',+ type: 'function',+ function: { name: 'read', arguments: '{"path":"/tmp/a"}' },+ }],+ }]);++ expect(result[0].parts[0]).toEqual({+ text: '[function call: read] {"path":"/tmp/a"}',+ });+ expect(result[0].parts[0].functionCall).toBeUndefined();+ });++ it('replays Gemini function calls when the encoded thought signature is present', () => {+ const signature = btoa('sig');+ const result = provider.formatMessages([{+ role: 'assistant',+ content: '',+ tool_calls: [{+ id: `call_read_ts_${signature}`,+ type: 'function',+ function: { name: 'read', arguments: '{"path":"/tmp/a"}' },+ }],+ }]);++ expect(result[0].parts[0].functionCall).toEqual({+ name: 'read',+ args: { path: '/tmp/a' },+ });+ expect(result[0].parts[0].thoughtSignature).toBe('sig');+ });+});diff --git a/packages/ai-gateway/src/test/openai-models.unit.test.ts b/packages/ai-gateway/src/test/openai-models.unit.test.tsindex 16e9294e7..3c92123cd 100644--- a/packages/ai-gateway/src/test/openai-models.unit.test.ts+++ b/packages/ai-gateway/src/test/openai-models.unit.test.ts@@ -64,6 +64,13 @@ describe('OpenAI API model catalog', () => {expect(ids).not.toContain('gpt-5.4-nano');});+ it('hides OpenAI models when OPENAI_API_KEY is a placeholder', async () => {+ const ids = await listedModelIds({ OPENAI_API_KEY: 'placeholder' });++ expect(ids).not.toContain('gpt-5.5');+ expect(ids).not.toContain('gpt-5.4-mini');+ });+it('keeps OpenAI models subscribed-only in the tier allowlist', () => {expect(isModelAllowed('gpt-5.4-mini', 'anonymous')).toBe(false);expect(isModelAllowed('gpt-5.4-mini', 'logged_in')).toBe(false);@@ -87,6 +94,16 @@ describe('OpenAI API accounting and routing', () => {expect(inferProvider('o4-mini')).toBe('openai');});+ it('rejects placeholder OpenAI keys before making upstream calls', () => {+ try {+ createProvider('gpt-5.5', env({ OPENAI_API_KEY: 'placeholder' }));+ throw new Error('expected provider creation to fail');+ } catch (error: any) {+ expect(error.message).toBe('OpenAI API key not configured');+ expect(error.status).toBe(503);+ }+ });+it('uses exact OpenAI prices instead of the unknown-model fallback', () => {expect(getModelCost('gpt-5.5', null, null)).toBeCloseTo(0.025, 6);expect(getModelCost('gpt-5.3-codex', null, null)).toBeCloseTo(0.0105, 6);diff --git a/packages/ai-gateway/src/test/vertex-maas.unit.test.ts b/packages/ai-gateway/src/test/vertex-maas.unit.test.tsindex 3de97c3e7..606d32198 100644--- a/packages/ai-gateway/src/test/vertex-maas.unit.test.ts+++ b/packages/ai-gateway/src/test/vertex-maas.unit.test.ts@@ -5,11 +5,24 @@import { describe, it, expect } from 'bun:test';import {isVertexMaasModel,+ parseVertexMaasJsonResponse,promoteReasoningStream,promoteReasoningToContent,resolveVertexMaasModel,+ UpstreamError,+ VertexMaasProvider,} from '../providers/vertex-maas';+const FAKE_SA_JSON = JSON.stringify({+ type: 'service_account',+ project_id: 'test-project',+ private_key_id: 'fake',+ private_key: '-----BEGIN PRIVATE KEY-----\nfake\n-----END PRIVATE KEY-----\n',+ client_email: '[email protected]',+ client_id: '0',+ token_uri: 'https://oauth2.googleapis.com/token',+});+describe('isVertexMaasModel', () => {it('should match GLM-4.7 variants', () => {expect(isVertexMaasModel('glm-4.7')).toBe(true);@@ -107,6 +120,62 @@ describe('promoteReasoningToContent', () => {});});+describe('parseVertexMaasJsonResponse', () => {+ it('turns empty 200 bodies into retryable upstream errors', async () => {+ try {+ await parseVertexMaasJsonResponse(new Response('', { status: 200 }), 'glm-5');+ throw new Error('expected parse to fail');+ } catch (error) {+ expect(error).toBeInstanceOf(UpstreamError);+ expect((error as UpstreamError).status).toBe(502);+ }+ });++ it('parses valid JSON bodies', async () => {+ const result = await parseVertexMaasJsonResponse(+ new Response(JSON.stringify({ choices: [] }), { status: 200 }),+ 'glm-5',+ );+ expect(result).toEqual({ choices: [] });+ });+});++describe('VertexMaasProvider.formatMessages', () => {+ const provider = new VertexMaasProvider(FAKE_SA_JSON, 'test-project');++ it('converts Anthropic tool_use blocks to OpenAI tool_calls for MaaS', () => {+ const result = provider.formatMessages([{+ role: 'assistant',+ content: [+ { type: 'thinking', thinking: 'hidden' },+ { type: 'text', text: '' },+ { type: 'tool_use', id: 'toolu_1', name: 'read', input: { path: '/tmp/a' } },+ ] as any,+ }]);++ expect(result[0].content).toBeNull();+ expect(result[0].tool_calls).toEqual([{+ id: 'toolu_1',+ type: 'function',+ function: { name: 'read', arguments: '{"path":"/tmp/a"}' },+ }]);+ });++ it('drops unsupported thinking blocks and empty text blocks', () => {+ const result = provider.formatMessages([{+ role: 'user',+ content: [+ { type: 'thinking', thinking: 'hidden' },+ { type: 'redacted_thinking', data: 'hidden' },+ { type: 'text', text: ' ' },+ { type: 'text', text: 'hello' },+ ] as any,+ }]);++ expect(result[0].content).toEqual([{ type: 'text', text: 'hello' }]);+ });+});+describe('promoteReasoningStream', () => {const encoder = new TextEncoder();const decoder = new TextDecoder();