Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions proxy/models.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"_title_model": "gpt-oss-120b-medium",
"_fallback_model": "",
"_default_provider": "nvidia",
"_default_model": "stepfun-ai/step-3.7-flash",
"_default_model": "minimaxai/minimax-m3",
"_compaction_enabled": true,
"_compaction_threshold": 0.8,
"_compaction_model": "",
Expand All @@ -24,15 +24,18 @@
"deepseek-v4-flash-free": 128000,
"mimo-v2.5-free": 128000,
"north-mini-code-free": 64000,
"stepfun-ai/step-3.7-flash": 128000
"minimaxai/minimax-m3": 128000
},
"_provider_models": {
"gemini-3.5-flash": {
"zen": "mimo-v2.5-free"
},
"gemini-3.1-pro": {
"opencode-go": "deepseek-v4-pro",
"zen": ["deepseek-v4-flash-free", "mimo-v2.5-free"]
"zen": [
"deepseek-v4-flash-free",
"mimo-v2.5-free"
]
},
"claude-sonnet-4-6-thinking": {
"zen": "mimo-v2.5-free"
Expand All @@ -41,13 +44,16 @@
"zen": "mimo-v2.5-free"
},
"gpt-oss-120b-medium": {
"nvidia": ["stepfun-ai/step-3.7-flash", "deepseek-v4-pro"]
"nvidia": [
"minimaxai/minimax-m3",
"deepseek-v4-pro"
]
},
"gemini-3.5-flash-low": {
"zen": "deepseek-v4-flash-free"
},
"gemini-3.5-flash-extra-low": {
"nvidia": "stepfun-ai/step-3.7-flash"
"nvidia": "minimaxai/minimax-m3"
},
"gemini-3-flash-agent": {
"zen": "north-mini-code-free"
Expand All @@ -59,7 +65,8 @@
"zen": "north-mini-code-free"
},
"default": {
"nvidia": "stepfun-ai/step-3.7-flash"
"nvidia": "minimaxai/minimax-m3",
"zen": "muse-spark-1.3-contributor-free"
}
}
}
}
4 changes: 2 additions & 2 deletions proxy/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

93 changes: 58 additions & 35 deletions proxy/src/adapters/anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,49 @@ import { parseToolArgs } from '../utils/parse-tool-args.js';

export class AnthropicAdapter implements ModelAdapter {
provider = 'anthropic';
private baseUrl: string;
private apiKey: string;
protected baseUrl: string;
protected apiKey: string;

constructor(baseUrl: string, apiKey: string) {
this.baseUrl = baseUrl.replace(/\/+$/, '');
this.apiKey = apiKey;
}

/** Endpoint path — '/messages' for Anthropic and compatible gateways. */
protected endpointPath(): string {
return '/messages';
}

/** Request headers. Overridden by gateway adapters (Bearer + session). */
protected buildHeaders(_config?: Record<string, unknown>): Record<string, string> {
return {
'Content-Type': 'application/json',
'x-api-key': this.apiKey,
'anthropic-version': '2023-06-01',
};
}

/**
* Thinking budget for `thinking: { type: 'enabled', budget_tokens }`.
* Returns null when thinking should be off. Overridden by gateway adapters
* that always run maximum thinking.
*/
protected thinkingBudget(maxTokens: number, config?: Record<string, unknown>): number | null {
const providerOptions = (config as any)?.providerOptions;
const reasoningEffort: string | undefined = providerOptions?.openai?.reasoningEffort;
if (!reasoningEffort) return null;
// Approximate budget_tokens by effort level. Anthropic requires
// budget_tokens >= 1024, and <= max_tokens.
const budgetByLevel: Record<string, number> = {
low: Math.min(2048, maxTokens - 1),
medium: Math.min(8192, maxTokens - 1),
high: Math.min(16384, maxTokens - 1),
};
const budget = budgetByLevel[reasoningEffort] ?? Math.min(8192, maxTokens - 1);
// Ensure we respect Anthropic's minimum (1024) and stay below max_tokens.
return Math.max(1024, budget);
}

async *stream(
model: string,
messages: OpenAIMessage[],
Expand All @@ -27,7 +62,7 @@ export class AnthropicAdapter implements ModelAdapter {
? [{ role: 'system' as const, content: system }, ...messages]
: messages;
const body = this.buildRequest(model, finalMessages, tools, config);
const response = await this.fetchResponse(body, signal);
const response = await this.fetchResponse(body, signal, config);

const reader = response.body!.getReader();
const decoder = new TextDecoder();
Expand Down Expand Up @@ -100,7 +135,7 @@ export class AnthropicAdapter implements ModelAdapter {
}
}

private buildRequest(
protected buildRequest(
model: string,
messages: OpenAIMessage[],
tools?: Record<string, unknown>,
Expand All @@ -109,9 +144,10 @@ export class AnthropicAdapter implements ModelAdapter {
const systemMessages = messages.filter(m => m.role === 'system');
const nonSystemMessages = messages.filter(m => m.role !== 'system');

const maxTokens = (config?.maxTokens as number) || 4096;
const body: Record<string, unknown> = {
model,
max_tokens: (config?.maxTokens as number) || 4096,
max_tokens: maxTokens,
stream: true,
messages: this.convertMessages(nonSystemMessages),
};
Expand All @@ -125,38 +161,26 @@ export class AnthropicAdapter implements ModelAdapter {
input_schema: tool.parameters || { type: 'object', properties: {} },
}));
}
if (config?.temperature != null) body.temperature = config.temperature;
if (config?.topP != null) body.top_p = config.topP;
if ((config as any)?.stopSequences?.length) body.stop_sequences = (config as any).stopSequences;

// A3: translate OpenAI-style `reasoningEffort` to Anthropic's `thinking`.
// Antigravity sets providerOptions.openai.reasoningEffort = 'low'|'medium'|'high'
// when the user wants visible chain-of-thought. Anthropic uses a different
// shape: `thinking: { type: 'enabled', budget_tokens: N }`.
// We only set this when reasoning is requested (avoids changing behavior
// for non-reasoning requests).
const providerOptions = (config as any)?.providerOptions;
const reasoningEffort: string | undefined = providerOptions?.openai?.reasoningEffort;
if (reasoningEffort) {
// Approximate budget_tokens by effort level. Anthropic requires
// budget_tokens >= 1024, and <= max_tokens.
const maxTokens = (body.max_tokens as number) || 4096;
const budgetByLevel: Record<string, number> = {
low: Math.min(2048, maxTokens - 1),
medium: Math.min(8192, maxTokens - 1),
high: Math.min(16384, maxTokens - 1),
};
const budget = budgetByLevel[reasoningEffort]
?? Math.min(8192, maxTokens - 1);
// Ensure we respect Anthropic's minimum (1024) and stay below max_tokens.
const safeBudget = Math.max(1024, budget);
(body as any).thinking = { type: 'enabled', budget_tokens: safeBudget };
const budget = this.thinkingBudget(maxTokens, config);
if (budget != null) {
(body as any).thinking = { type: 'enabled', budget_tokens: budget };
} else {
// Anthropic rejects temperature/top_p alongside thinking — only send
// them for non-reasoning requests.
if (config?.temperature != null) body.temperature = config.temperature;
if (config?.topP != null) body.top_p = config.topP;
}
if ((config as any)?.stopSequences?.length) body.stop_sequences = (config as any).stopSequences;

return body;
}

private convertMessages(messages: OpenAIMessage[]): any[] {
protected convertMessages(messages: OpenAIMessage[]): any[] {
const result: any[] = [];
for (const m of messages) {
if (m.role === 'tool') {
Expand Down Expand Up @@ -202,20 +226,19 @@ export class AnthropicAdapter implements ModelAdapter {
return result;
}

private async fetchResponse(body: Record<string, unknown>, signal?: AbortSignal): Promise<Response> {
const response = await poolFetch(`${this.baseUrl}/messages`, {
protected async fetchResponse(body: Record<string, unknown>, signal?: AbortSignal, config?: Record<string, unknown>): Promise<Response> {
const response = await poolFetch(`${this.baseUrl}${this.endpointPath()}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': this.apiKey,
'anthropic-version': '2023-06-01',
},
headers: this.buildHeaders(config),
body: JSON.stringify(body),
signal,
});
if (!response.ok) {
const err = await response.text().catch(() => 'unknown');
throw new Error(`[anthropic] API error ${response.status}: ${err}`);
logger.debug(`[${this.provider}] rejected body`, {
body: JSON.stringify(body).substring(0, 4000),
});
throw new Error(`[${this.provider}] API error ${response.status}: ${err}`);
}
return response;
}
Expand Down
34 changes: 34 additions & 0 deletions proxy/src/adapters/gateway-messages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Anthropic Messages API over an OpenCode gateway base URL (Go /messages,
* Zen /messages). Same protocol as AnthropicAdapter, but authenticates like
* the gateway expects (Bearer + stable x-opencode-session + distinct UA)
* and always runs maximum thinking.
*/

import { randomUUID } from 'crypto';
import { AnthropicAdapter } from './anthropic.js';

export class GatewayMessagesAdapter extends AnthropicAdapter {
constructor(baseUrl: string, apiKey: string, gatewayProvider: string) {
super(baseUrl, apiKey);
this.provider = gatewayProvider;
}

protected override buildHeaders(config?: Record<string, unknown>): Record<string, string> {
const sessionId = (config as any)?.providerOptions?.sessionId || randomUUID();
return {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
'x-opencode-session': String(sessionId),
'User-Agent': 'antigravity-proxy/1.0.7',
};
}

/**
* Always maximum thinking: largest budget that still leaves headroom for
* output (budget must stay below max_tokens).
*/
protected override thinkingBudget(maxTokens: number): number | null {
return Math.max(1024, Math.min(16384, maxTokens - 1024));
}
}
Loading
Loading