commons-proxy 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +757 -0
- package/bin/cli.js +146 -0
- package/package.json +97 -0
- package/public/Complaint Details.pdf +0 -0
- package/public/Cyber Crime Portal.pdf +0 -0
- package/public/app.js +229 -0
- package/public/css/src/input.css +523 -0
- package/public/css/style.css +1 -0
- package/public/favicon.png +0 -0
- package/public/index.html +549 -0
- package/public/js/components/account-manager.js +356 -0
- package/public/js/components/add-account-modal.js +414 -0
- package/public/js/components/claude-config.js +420 -0
- package/public/js/components/dashboard/charts.js +605 -0
- package/public/js/components/dashboard/filters.js +362 -0
- package/public/js/components/dashboard/stats.js +110 -0
- package/public/js/components/dashboard.js +236 -0
- package/public/js/components/logs-viewer.js +100 -0
- package/public/js/components/models.js +36 -0
- package/public/js/components/server-config.js +349 -0
- package/public/js/config/constants.js +102 -0
- package/public/js/data-store.js +375 -0
- package/public/js/settings-store.js +58 -0
- package/public/js/store.js +99 -0
- package/public/js/translations/en.js +367 -0
- package/public/js/translations/id.js +412 -0
- package/public/js/translations/pt.js +308 -0
- package/public/js/translations/tr.js +358 -0
- package/public/js/translations/zh.js +373 -0
- package/public/js/utils/account-actions.js +189 -0
- package/public/js/utils/error-handler.js +96 -0
- package/public/js/utils/model-config.js +42 -0
- package/public/js/utils/ui-logger.js +143 -0
- package/public/js/utils/validators.js +77 -0
- package/public/js/utils.js +69 -0
- package/public/proxy-server-64.png +0 -0
- package/public/views/accounts.html +361 -0
- package/public/views/dashboard.html +484 -0
- package/public/views/logs.html +97 -0
- package/public/views/models.html +331 -0
- package/public/views/settings.html +1327 -0
- package/src/account-manager/credentials.js +378 -0
- package/src/account-manager/index.js +462 -0
- package/src/account-manager/onboarding.js +112 -0
- package/src/account-manager/rate-limits.js +369 -0
- package/src/account-manager/storage.js +160 -0
- package/src/account-manager/strategies/base-strategy.js +109 -0
- package/src/account-manager/strategies/hybrid-strategy.js +339 -0
- package/src/account-manager/strategies/index.js +79 -0
- package/src/account-manager/strategies/round-robin-strategy.js +76 -0
- package/src/account-manager/strategies/sticky-strategy.js +138 -0
- package/src/account-manager/strategies/trackers/health-tracker.js +162 -0
- package/src/account-manager/strategies/trackers/index.js +9 -0
- package/src/account-manager/strategies/trackers/quota-tracker.js +120 -0
- package/src/account-manager/strategies/trackers/token-bucket-tracker.js +155 -0
- package/src/auth/database.js +169 -0
- package/src/auth/oauth.js +548 -0
- package/src/auth/token-extractor.js +117 -0
- package/src/cli/accounts.js +648 -0
- package/src/cloudcode/index.js +29 -0
- package/src/cloudcode/message-handler.js +510 -0
- package/src/cloudcode/model-api.js +248 -0
- package/src/cloudcode/rate-limit-parser.js +235 -0
- package/src/cloudcode/request-builder.js +93 -0
- package/src/cloudcode/session-manager.js +47 -0
- package/src/cloudcode/sse-parser.js +121 -0
- package/src/cloudcode/sse-streamer.js +293 -0
- package/src/cloudcode/streaming-handler.js +615 -0
- package/src/config.js +125 -0
- package/src/constants.js +407 -0
- package/src/errors.js +242 -0
- package/src/fallback-config.js +29 -0
- package/src/format/content-converter.js +193 -0
- package/src/format/index.js +20 -0
- package/src/format/request-converter.js +255 -0
- package/src/format/response-converter.js +120 -0
- package/src/format/schema-sanitizer.js +673 -0
- package/src/format/signature-cache.js +88 -0
- package/src/format/thinking-utils.js +648 -0
- package/src/index.js +148 -0
- package/src/modules/usage-stats.js +205 -0
- package/src/providers/anthropic-provider.js +258 -0
- package/src/providers/base-provider.js +157 -0
- package/src/providers/cloudcode.js +94 -0
- package/src/providers/copilot.js +399 -0
- package/src/providers/github-provider.js +287 -0
- package/src/providers/google-provider.js +192 -0
- package/src/providers/index.js +211 -0
- package/src/providers/openai-compatible.js +265 -0
- package/src/providers/openai-provider.js +271 -0
- package/src/providers/openrouter-provider.js +325 -0
- package/src/providers/setup.js +83 -0
- package/src/server.js +870 -0
- package/src/utils/claude-config.js +245 -0
- package/src/utils/helpers.js +51 -0
- package/src/utils/logger.js +142 -0
- package/src/utils/native-module-helper.js +162 -0
- package/src/webui/index.js +1134 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request Converter
|
|
3
|
+
* Converts Anthropic Messages API requests to Google Generative AI format
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
GEMINI_MAX_OUTPUT_TOKENS,
|
|
8
|
+
getModelFamily,
|
|
9
|
+
isThinkingModel
|
|
10
|
+
} from '../constants.js';
|
|
11
|
+
import { convertContentToParts, convertRole } from './content-converter.js';
|
|
12
|
+
import { sanitizeSchema, cleanSchema } from './schema-sanitizer.js';
|
|
13
|
+
import {
|
|
14
|
+
restoreThinkingSignatures,
|
|
15
|
+
removeTrailingThinkingBlocks,
|
|
16
|
+
reorderAssistantContent,
|
|
17
|
+
filterUnsignedThinkingBlocks,
|
|
18
|
+
hasGeminiHistory,
|
|
19
|
+
hasUnsignedThinkingBlocks,
|
|
20
|
+
needsThinkingRecovery,
|
|
21
|
+
closeToolLoopForThinking,
|
|
22
|
+
cleanCacheControl
|
|
23
|
+
} from './thinking-utils.js';
|
|
24
|
+
import { logger } from '../utils/logger.js';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Convert Anthropic Messages API request to the format expected by Cloud Code
|
|
28
|
+
*
|
|
29
|
+
* Uses Google Generative AI format, but for Claude models:
|
|
30
|
+
* - Keeps tool_result in Anthropic format (required by Claude API)
|
|
31
|
+
*
|
|
32
|
+
* @param {Object} anthropicRequest - Anthropic format request
|
|
33
|
+
* @returns {Object} Request body for Cloud Code API
|
|
34
|
+
*/
|
|
35
|
+
export function convertAnthropicToGoogle(anthropicRequest) {
|
|
36
|
+
// [CRITICAL FIX] Pre-clean all cache_control fields from messages (Issue #189)
|
|
37
|
+
// Claude Code CLI sends cache_control on various content blocks, but Cloud Code API
|
|
38
|
+
// rejects them with "Extra inputs are not permitted". Clean them proactively here
|
|
39
|
+
// before any other processing, following the pattern from Antigravity-Manager.
|
|
40
|
+
const messages = cleanCacheControl(anthropicRequest.messages || []);
|
|
41
|
+
|
|
42
|
+
const { system, max_tokens, temperature, top_p, top_k, stop_sequences, tools, tool_choice, thinking } = anthropicRequest;
|
|
43
|
+
const modelName = anthropicRequest.model || '';
|
|
44
|
+
const modelFamily = getModelFamily(modelName);
|
|
45
|
+
const isClaudeModel = modelFamily === 'claude';
|
|
46
|
+
const isGeminiModel = modelFamily === 'gemini';
|
|
47
|
+
const isThinking = isThinkingModel(modelName);
|
|
48
|
+
|
|
49
|
+
const googleRequest = {
|
|
50
|
+
contents: [],
|
|
51
|
+
generationConfig: {}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// Handle system instruction
|
|
55
|
+
if (system) {
|
|
56
|
+
let systemParts = [];
|
|
57
|
+
if (typeof system === 'string') {
|
|
58
|
+
systemParts = [{ text: system }];
|
|
59
|
+
} else if (Array.isArray(system)) {
|
|
60
|
+
// Filter for text blocks as system prompts are usually text
|
|
61
|
+
// Anthropic supports text blocks in system prompts
|
|
62
|
+
systemParts = system
|
|
63
|
+
.filter(block => block.type === 'text')
|
|
64
|
+
.map(block => ({ text: block.text }));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (systemParts.length > 0) {
|
|
68
|
+
googleRequest.systemInstruction = {
|
|
69
|
+
parts: systemParts
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Add interleaved thinking hint for Claude thinking models with tools
|
|
75
|
+
if (isClaudeModel && isThinking && tools && tools.length > 0) {
|
|
76
|
+
const hint = 'Interleaved thinking is enabled. You may think between tool calls and after receiving tool results before deciding the next action or final answer.';
|
|
77
|
+
if (!googleRequest.systemInstruction) {
|
|
78
|
+
googleRequest.systemInstruction = { parts: [{ text: hint }] };
|
|
79
|
+
} else {
|
|
80
|
+
const lastPart = googleRequest.systemInstruction.parts[googleRequest.systemInstruction.parts.length - 1];
|
|
81
|
+
if (lastPart && lastPart.text) {
|
|
82
|
+
lastPart.text = `${lastPart.text}\n\n${hint}`;
|
|
83
|
+
} else {
|
|
84
|
+
googleRequest.systemInstruction.parts.push({ text: hint });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Apply thinking recovery for Gemini thinking models when needed
|
|
90
|
+
// Gemini needs recovery for tool loops/interrupted tools (stripped thinking)
|
|
91
|
+
let processedMessages = messages;
|
|
92
|
+
|
|
93
|
+
if (isGeminiModel && isThinking && needsThinkingRecovery(messages)) {
|
|
94
|
+
logger.debug('[RequestConverter] Applying thinking recovery for Gemini');
|
|
95
|
+
processedMessages = closeToolLoopForThinking(messages, 'gemini');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// For Claude: apply recovery for cross-model (Gemini→Claude) or unsigned thinking blocks
|
|
99
|
+
// Unsigned thinking blocks occur when Claude Code strips signatures it doesn't understand
|
|
100
|
+
const needsClaudeRecovery = hasGeminiHistory(messages) || hasUnsignedThinkingBlocks(messages);
|
|
101
|
+
if (isClaudeModel && isThinking && needsClaudeRecovery && needsThinkingRecovery(messages)) {
|
|
102
|
+
logger.debug('[RequestConverter] Applying thinking recovery for Claude');
|
|
103
|
+
processedMessages = closeToolLoopForThinking(messages, 'claude');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Convert messages to contents, then filter unsigned thinking blocks
|
|
107
|
+
for (const msg of processedMessages) {
|
|
108
|
+
let msgContent = msg.content;
|
|
109
|
+
|
|
110
|
+
// For assistant messages, process thinking blocks and reorder content
|
|
111
|
+
if ((msg.role === 'assistant' || msg.role === 'model') && Array.isArray(msgContent)) {
|
|
112
|
+
// First, try to restore signatures for unsigned thinking blocks from cache
|
|
113
|
+
msgContent = restoreThinkingSignatures(msgContent);
|
|
114
|
+
// Remove trailing unsigned thinking blocks
|
|
115
|
+
msgContent = removeTrailingThinkingBlocks(msgContent);
|
|
116
|
+
// Reorder: thinking first, then text, then tool_use
|
|
117
|
+
msgContent = reorderAssistantContent(msgContent);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const parts = convertContentToParts(msgContent, isClaudeModel, isGeminiModel);
|
|
121
|
+
|
|
122
|
+
// SAFETY: Google API requires at least one part per content message
|
|
123
|
+
// This happens when all thinking blocks are filtered out (unsigned)
|
|
124
|
+
if (parts.length === 0) {
|
|
125
|
+
// Use '.' instead of '' because claude models reject empty text parts.
|
|
126
|
+
// A single period is invisible in practice but satisfies the API requirement.
|
|
127
|
+
logger.warn('[RequestConverter] WARNING: Empty parts array after filtering, adding placeholder');
|
|
128
|
+
parts.push({ text: '.' });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const content = {
|
|
132
|
+
role: convertRole(msg.role),
|
|
133
|
+
parts: parts
|
|
134
|
+
};
|
|
135
|
+
googleRequest.contents.push(content);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Filter unsigned thinking blocks for Claude models
|
|
139
|
+
if (isClaudeModel) {
|
|
140
|
+
googleRequest.contents = filterUnsignedThinkingBlocks(googleRequest.contents);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Generation config
|
|
144
|
+
if (max_tokens) {
|
|
145
|
+
googleRequest.generationConfig.maxOutputTokens = max_tokens;
|
|
146
|
+
}
|
|
147
|
+
if (temperature !== undefined) {
|
|
148
|
+
googleRequest.generationConfig.temperature = temperature;
|
|
149
|
+
}
|
|
150
|
+
if (top_p !== undefined) {
|
|
151
|
+
googleRequest.generationConfig.topP = top_p;
|
|
152
|
+
}
|
|
153
|
+
if (top_k !== undefined) {
|
|
154
|
+
googleRequest.generationConfig.topK = top_k;
|
|
155
|
+
}
|
|
156
|
+
if (stop_sequences && stop_sequences.length > 0) {
|
|
157
|
+
googleRequest.generationConfig.stopSequences = stop_sequences;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Enable thinking for thinking models (Claude and Gemini 3+)
|
|
161
|
+
if (isThinking) {
|
|
162
|
+
if (isClaudeModel) {
|
|
163
|
+
// Claude thinking config
|
|
164
|
+
const thinkingConfig = {
|
|
165
|
+
include_thoughts: true
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
// Only set thinking_budget if explicitly provided
|
|
169
|
+
const thinkingBudget = thinking?.budget_tokens;
|
|
170
|
+
if (thinkingBudget) {
|
|
171
|
+
thinkingConfig.thinking_budget = thinkingBudget;
|
|
172
|
+
logger.debug(`[RequestConverter] Claude thinking enabled with budget: ${thinkingBudget}`);
|
|
173
|
+
|
|
174
|
+
// Validate max_tokens > thinking_budget as required by the API
|
|
175
|
+
const currentMaxTokens = googleRequest.generationConfig.maxOutputTokens;
|
|
176
|
+
if (currentMaxTokens && currentMaxTokens <= thinkingBudget) {
|
|
177
|
+
// Bump max_tokens to allow for some response content
|
|
178
|
+
// Default to budget + 8192 (standard output buffer)
|
|
179
|
+
const adjustedMaxTokens = thinkingBudget + 8192;
|
|
180
|
+
logger.warn(`[RequestConverter] max_tokens (${currentMaxTokens}) <= thinking_budget (${thinkingBudget}). Adjusting to ${adjustedMaxTokens} to satisfy API requirements`);
|
|
181
|
+
googleRequest.generationConfig.maxOutputTokens = adjustedMaxTokens;
|
|
182
|
+
}
|
|
183
|
+
} else {
|
|
184
|
+
logger.debug('[RequestConverter] Claude thinking enabled (no budget specified)');
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
googleRequest.generationConfig.thinkingConfig = thinkingConfig;
|
|
188
|
+
} else if (isGeminiModel) {
|
|
189
|
+
// Gemini thinking config (uses camelCase)
|
|
190
|
+
const thinkingConfig = {
|
|
191
|
+
includeThoughts: true,
|
|
192
|
+
thinkingBudget: thinking?.budget_tokens || 16000
|
|
193
|
+
};
|
|
194
|
+
logger.debug(`[RequestConverter] Gemini thinking enabled with budget: ${thinkingConfig.thinkingBudget}`);
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
googleRequest.generationConfig.thinkingConfig = thinkingConfig;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Convert tools to Google format
|
|
202
|
+
if (tools && tools.length > 0) {
|
|
203
|
+
const functionDeclarations = tools.map((tool, idx) => {
|
|
204
|
+
// Extract name from various possible locations
|
|
205
|
+
const name = tool.name || tool.function?.name || tool.custom?.name || `tool-${idx}`;
|
|
206
|
+
|
|
207
|
+
// Extract description from various possible locations
|
|
208
|
+
const description = tool.description || tool.function?.description || tool.custom?.description || '';
|
|
209
|
+
|
|
210
|
+
// Extract schema from various possible locations
|
|
211
|
+
const schema = tool.input_schema
|
|
212
|
+
|| tool.function?.input_schema
|
|
213
|
+
|| tool.function?.parameters
|
|
214
|
+
|| tool.custom?.input_schema
|
|
215
|
+
|| tool.parameters
|
|
216
|
+
|| { type: 'object' };
|
|
217
|
+
|
|
218
|
+
// Sanitize schema for general compatibility
|
|
219
|
+
let parameters = sanitizeSchema(schema);
|
|
220
|
+
|
|
221
|
+
// Apply Google-format cleaning for ALL models since they all go through
|
|
222
|
+
// Cloud Code API which validates schemas using Google's protobuf format.
|
|
223
|
+
// This fixes issue #82: /compact command fails with schema transformation error
|
|
224
|
+
// "Proto field is not repeating, cannot start list" for Claude models.
|
|
225
|
+
parameters = cleanSchema(parameters);
|
|
226
|
+
|
|
227
|
+
return {
|
|
228
|
+
name: String(name).replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64),
|
|
229
|
+
description: description,
|
|
230
|
+
parameters
|
|
231
|
+
};
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
googleRequest.tools = [{ functionDeclarations }];
|
|
235
|
+
logger.debug(`[RequestConverter] Tools: ${JSON.stringify(googleRequest.tools).substring(0, 300)}`);
|
|
236
|
+
|
|
237
|
+
// For Claude models, set functionCallingConfig.mode = "VALIDATED"
|
|
238
|
+
// This ensures strict parameter validation (matches opencode-cloudcode-auth)
|
|
239
|
+
if (isClaudeModel) {
|
|
240
|
+
googleRequest.toolConfig = {
|
|
241
|
+
functionCallingConfig: {
|
|
242
|
+
mode: 'VALIDATED'
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Cap max tokens for Gemini models
|
|
249
|
+
if (isGeminiModel && googleRequest.generationConfig.maxOutputTokens > GEMINI_MAX_OUTPUT_TOKENS) {
|
|
250
|
+
logger.debug(`[RequestConverter] Capping Gemini max_tokens from ${googleRequest.generationConfig.maxOutputTokens} to ${GEMINI_MAX_OUTPUT_TOKENS}`);
|
|
251
|
+
googleRequest.generationConfig.maxOutputTokens = GEMINI_MAX_OUTPUT_TOKENS;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
return googleRequest;
|
|
255
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response Converter
|
|
3
|
+
* Converts Google Generative AI responses to Anthropic Messages API format
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import crypto from 'crypto';
|
|
7
|
+
import { MIN_SIGNATURE_LENGTH, getModelFamily } from '../constants.js';
|
|
8
|
+
import { cacheSignature, cacheThinkingSignature } from './signature-cache.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Convert Google Generative AI response to Anthropic Messages API format
|
|
12
|
+
*
|
|
13
|
+
* @param {Object} googleResponse - Google format response (the inner response object)
|
|
14
|
+
* @param {string} model - The model name used
|
|
15
|
+
* @returns {Object} Anthropic format response
|
|
16
|
+
*/
|
|
17
|
+
export function convertGoogleToAnthropic(googleResponse, model) {
|
|
18
|
+
// Handle the response wrapper
|
|
19
|
+
const response = googleResponse.response || googleResponse;
|
|
20
|
+
|
|
21
|
+
const candidates = response.candidates || [];
|
|
22
|
+
const firstCandidate = candidates[0] || {};
|
|
23
|
+
const content = firstCandidate.content || {};
|
|
24
|
+
const parts = content.parts || [];
|
|
25
|
+
|
|
26
|
+
// Convert parts to Anthropic content blocks
|
|
27
|
+
const anthropicContent = [];
|
|
28
|
+
let hasToolCalls = false;
|
|
29
|
+
|
|
30
|
+
for (const part of parts) {
|
|
31
|
+
if (part.text !== undefined) {
|
|
32
|
+
// Handle thinking blocks
|
|
33
|
+
if (part.thought === true) {
|
|
34
|
+
const signature = part.thoughtSignature || '';
|
|
35
|
+
|
|
36
|
+
// Cache thinking signature with model family for cross-model compatibility
|
|
37
|
+
if (signature && signature.length >= MIN_SIGNATURE_LENGTH) {
|
|
38
|
+
const modelFamily = getModelFamily(model);
|
|
39
|
+
cacheThinkingSignature(signature, modelFamily);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Include thinking blocks in the response for Claude Code
|
|
43
|
+
anthropicContent.push({
|
|
44
|
+
type: 'thinking',
|
|
45
|
+
thinking: part.text,
|
|
46
|
+
signature: signature
|
|
47
|
+
});
|
|
48
|
+
} else {
|
|
49
|
+
anthropicContent.push({
|
|
50
|
+
type: 'text',
|
|
51
|
+
text: part.text
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
} else if (part.functionCall) {
|
|
55
|
+
// Convert functionCall to tool_use
|
|
56
|
+
// Use the id from the response if available, otherwise generate one
|
|
57
|
+
const toolId = part.functionCall.id || `toolu_${crypto.randomBytes(12).toString('hex')}`;
|
|
58
|
+
const toolUseBlock = {
|
|
59
|
+
type: 'tool_use',
|
|
60
|
+
id: toolId,
|
|
61
|
+
name: part.functionCall.name,
|
|
62
|
+
input: part.functionCall.args || {}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// For Gemini 3+, include thoughtSignature from the part level
|
|
66
|
+
if (part.thoughtSignature && part.thoughtSignature.length >= MIN_SIGNATURE_LENGTH) {
|
|
67
|
+
toolUseBlock.thoughtSignature = part.thoughtSignature;
|
|
68
|
+
// Cache for future requests (Claude Code may strip this field)
|
|
69
|
+
cacheSignature(toolId, part.thoughtSignature);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
anthropicContent.push(toolUseBlock);
|
|
73
|
+
hasToolCalls = true;
|
|
74
|
+
} else if (part.inlineData) {
|
|
75
|
+
// Handle image content from Google format
|
|
76
|
+
anthropicContent.push({
|
|
77
|
+
type: 'image',
|
|
78
|
+
source: {
|
|
79
|
+
type: 'base64',
|
|
80
|
+
media_type: part.inlineData.mimeType,
|
|
81
|
+
data: part.inlineData.data
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Determine stop reason
|
|
88
|
+
const finishReason = firstCandidate.finishReason;
|
|
89
|
+
let stopReason = 'end_turn';
|
|
90
|
+
if (finishReason === 'STOP') {
|
|
91
|
+
stopReason = 'end_turn';
|
|
92
|
+
} else if (finishReason === 'MAX_TOKENS') {
|
|
93
|
+
stopReason = 'max_tokens';
|
|
94
|
+
} else if (finishReason === 'TOOL_USE' || hasToolCalls) {
|
|
95
|
+
stopReason = 'tool_use';
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Extract usage metadata
|
|
99
|
+
// Note: Antigravity's promptTokenCount is the TOTAL (includes cached),
|
|
100
|
+
// but Anthropic's input_tokens excludes cached. We subtract to match.
|
|
101
|
+
const usageMetadata = response.usageMetadata || {};
|
|
102
|
+
const promptTokens = usageMetadata.promptTokenCount || 0;
|
|
103
|
+
const cachedTokens = usageMetadata.cachedContentTokenCount || 0;
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
id: `msg_${crypto.randomBytes(16).toString('hex')}`,
|
|
107
|
+
type: 'message',
|
|
108
|
+
role: 'assistant',
|
|
109
|
+
content: anthropicContent.length > 0 ? anthropicContent : [{ type: 'text', text: '' }],
|
|
110
|
+
model: model,
|
|
111
|
+
stop_reason: stopReason,
|
|
112
|
+
stop_sequence: null,
|
|
113
|
+
usage: {
|
|
114
|
+
input_tokens: promptTokens - cachedTokens,
|
|
115
|
+
output_tokens: usageMetadata.candidatesTokenCount || 0,
|
|
116
|
+
cache_read_input_tokens: cachedTokens,
|
|
117
|
+
cache_creation_input_tokens: 0
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
}
|