File size: 8,410 Bytes
b88ce1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d02ec4
b88ce1b
 
 
 
 
 
 
 
 
 
2d02ec4
b88ce1b
 
3ed6209
 
 
 
 
 
 
 
 
 
 
 
 
2d02ec4
b88ce1b
 
 
 
 
 
 
 
 
2d02ec4
 
b88ce1b
2d02ec4
b88ce1b
2d02ec4
3ed6209
2d02ec4
 
 
 
 
 
 
 
 
 
 
 
 
b88ce1b
2d02ec4
b88ce1b
 
 
 
 
 
2d02ec4
b88ce1b
 
 
 
 
 
 
 
 
 
 
 
 
 
2d02ec4
b88ce1b
 
 
 
 
 
 
 
 
 
2d02ec4
b88ce1b
 
 
 
 
 
 
 
 
 
2d02ec4
b88ce1b
 
 
 
 
 
 
 
 
 
 
2d02ec4
b88ce1b
 
2d02ec4
b88ce1b
 
 
 
 
 
 
 
 
 
 
 
2d02ec4
b88ce1b
2d02ec4
 
 
 
 
 
 
 
 
b88ce1b
 
 
 
2d02ec4
b88ce1b
2d02ec4
b88ce1b
 
 
 
 
 
 
 
 
 
 
 
f783f84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d02ec4
 
 
b88ce1b
 
 
 
2d02ec4
f783f84
 
 
 
2d02ec4
f783f84
b88ce1b
 
 
 
 
 
 
 
 
 
 
 
 
 
f783f84
b88ce1b
 
 
 
 
2d02ec4
b88ce1b
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import { randomUUID } from 'crypto';
import config from '../config/config.js';

function generateRequestId() {
  return `agent-${randomUUID()}`;
}

function generateSessionId() {
  return String(-Math.floor(Math.random() * 9e18));
}

function generateProjectId() {
  const adjectives = ['useful', 'bright', 'swift', 'calm', 'bold'];
  const nouns = ['fuze', 'wave', 'spark', 'flow', 'core'];
  const randomAdj = adjectives[Math.floor(Math.random() * adjectives.length)];
  const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
  const randomNum = Math.random().toString(36).substring(2, 7);
  return `${randomAdj}-${randomNoun}-${randomNum}`;
}
function extractImagesFromContent(content) {
  const result = { text: '', images: [] };

  // 如果content是字符串,直接返回
  if (typeof content === 'string') {
    result.text = content;
    return result;
  }

  // 如果content是数组(multimodal格式)
  if (Array.isArray(content)) {
    for (const item of content) {
      if (item.type === 'text') {
        result.text += item.text;
      } else if (item.type === 'image_url') {
        // 提取base64图片数据
        const imageUrl = item.image_url?.url || '';

        // 匹配 data:image/{format};base64,{data} 格式
        const match = imageUrl.match(/^data:image\/(\w+);base64,(.+)$/);
        if (match) {
          const format = match[1]; // 例如 png, jpeg, jpg
          const base64Data = match[2];
          result.images.push({
            inlineData: {
              mimeType: `image/${format}`,
              data: base64Data
            }
          })
        }
      }
    }
  }

  return result;
}
function handleUserMessage(extracted, antigravityMessages) {
  antigravityMessages.push({
    role: "user",
    parts: [
      {
        text: extracted.text
      },
      ...extracted.images
    ]
  })
}
function handleAssistantMessage(message, antigravityMessages) {
  const lastMessage = antigravityMessages[antigravityMessages.length - 1];
  const hasToolCalls = message.tool_calls && message.tool_calls.length > 0;

  let contentText = '';
  if (typeof message.content === 'string') {
    contentText = message.content;
  } else if (Array.isArray(message.content)) {
    for (const item of message.content) {
      if (item.type === 'text') {
        contentText += item.text;
      }
    }
  }

  const hasContent = contentText && contentText.trim() !== '';

  const antigravityTools = hasToolCalls ? message.tool_calls.map(toolCall => ({
    functionCall: {
      id: toolCall.id,
      name: toolCall.function.name,
      args: {
        query: toolCall.function.arguments
      }
    }
  })) : [];

  if (lastMessage?.role === "model" && hasToolCalls && !hasContent) {
    lastMessage.parts.push(...antigravityTools)
  } else {
    const parts = [];
    if (hasContent) {
      let text = contentText;
      let thoughtSignature = null;
      const signatureMatch = text.match(/<!-- thought_signature: (.+?) -->/);
      if (signatureMatch) {
        thoughtSignature = signatureMatch[1];
        text = text.replace(signatureMatch[0], '').trim();
      }

      const part = { text };
      if (thoughtSignature) {
        part.thought_signature = thoughtSignature;
      }
      parts.push(part);
    }
    parts.push(...antigravityTools);

    antigravityMessages.push({
      role: "model",
      parts
    })
  }
}
function handleToolCall(message, antigravityMessages) {
  // 从之前的 model 消息中找到对应的 functionCall name
  let functionName = '';
  for (let i = antigravityMessages.length - 1; i >= 0; i--) {
    if (antigravityMessages[i].role === 'model') {
      const parts = antigravityMessages[i].parts;
      for (const part of parts) {
        if (part.functionCall && part.functionCall.id === message.tool_call_id) {
          functionName = part.functionCall.name;
          break;
        }
      }
      if (functionName) break;
    }
  }

  const lastMessage = antigravityMessages[antigravityMessages.length - 1];
  const functionResponse = {
    functionResponse: {
      id: message.tool_call_id,
      name: functionName,
      response: {
        output: message.content
      }
    }
  };

  // 如果上一条消息是 user 且包含 functionResponse,则合并
  if (lastMessage?.role === "user" && lastMessage.parts.some(p => p.functionResponse)) {
    lastMessage.parts.push(functionResponse);
  } else {
    antigravityMessages.push({
      role: "user",
      parts: [functionResponse]
    });
  }
}
function openaiMessageToAntigravity(openaiMessages) {
  const antigravityMessages = [];
  for (const message of openaiMessages) {
    if (message.role === "user" || message.role === "system") {
      const extracted = extractImagesFromContent(message.content);
      handleUserMessage(extracted, antigravityMessages);
    } else if (message.role === "assistant") {
      handleAssistantMessage(message, antigravityMessages);
    } else if (message.role === "tool") {
      handleToolCall(message, antigravityMessages);
    }
  }

  return antigravityMessages;
}
function generateGenerationConfig(parameters, enableThinking, actualModelName) {
  const generationConfig = {
    topP: parameters.top_p ?? config.defaults.top_p,
    topK: parameters.top_k ?? config.defaults.top_k,
    temperature: parameters.temperature ?? config.defaults.temperature,
    candidateCount: 1,
    maxOutputTokens: parameters.max_tokens ?? config.defaults.max_tokens,
    stopSequences: [
      "<|user|>",
      "<|bot|>",
      "<|context_request|>",
      "<|endoftext|>",
      "<|end_of_turn|>"
    ]
  }

  if (enableThinking) {
    generationConfig.thinkingConfig = {
      includeThoughts: true,
      thinkingBudget: 1024
    };
  }

  if (enableThinking && actualModelName.includes("claude")) {
    delete generationConfig.topP;
  }
  return generationConfig
}
function convertOpenAIToolsToAntigravity(openaiTools) {
  if (!openaiTools || openaiTools.length === 0) return [];
  return openaiTools.map((tool) => {
    delete tool.function.parameters.$schema;
    return {
      functionDeclarations: [
        {
          name: tool.function.name,
          description: tool.function.description,
          parameters: tool.function.parameters
        }
      ]
    }
  })
}
const idCache = new Map();
const SESSION_ID_DURATION = 60 * 60 * 1000; // 1 hour
const PROJECT_ID_DURATION = 12 * 60 * 60 * 1000; // 12 hours

function getCachedIds(apiKey) {
  const now = Date.now();
  let cache = idCache.get(apiKey);

  if (!cache) {
    cache = {
      projectId: generateProjectId(),
      projectExpiry: now + PROJECT_ID_DURATION,
      sessionId: generateSessionId(),
      sessionExpiry: now + SESSION_ID_DURATION
    };
    idCache.set(apiKey, cache);
    return cache;
  }

  if (now > cache.projectExpiry) {
    cache.projectId = generateProjectId();
    cache.projectExpiry = now + PROJECT_ID_DURATION;
  }

  if (now > cache.sessionExpiry) {
    cache.sessionId = generateSessionId();
    cache.sessionExpiry = now + SESSION_ID_DURATION;
  }

  return cache;
}

function generateRequestBody(openaiMessages, modelName, parameters, openaiTools, apiKey) {
  const enableThinking = modelName.endsWith('-thinking') ||
    modelName === 'gemini-2.5-pro' ||
    modelName === 'gemini-2.5-pro-image' ||
    modelName.startsWith('gemini-3-pro-') ||
    modelName === "rev19-uic3-1p" ||
    modelName === "gpt-oss-120b-medium"
  const actualModelName = modelName.endsWith('-thinking') ? modelName.slice(0, -9) : modelName;

  // Use a default key if none provided (though it should be provided by the server)
  const cacheKey = apiKey || 'default';
  const { projectId, sessionId } = getCachedIds(cacheKey);

  return {
    project: projectId,
    requestId: generateRequestId(),
    request: {
      contents: openaiMessageToAntigravity(openaiMessages),
      systemInstruction: {
        role: "user",
        parts: [{ text: config.systemInstruction }]
      },
      tools: convertOpenAIToolsToAntigravity(openaiTools),
      toolConfig: {
        functionCallingConfig: {
          mode: "VALIDATED"
        }
      },
      generationConfig: generateGenerationConfig(parameters, enableThinking, actualModelName),
      sessionId: sessionId
    },
    model: actualModelName,
    userAgent: "antigravity"
  }
}
export {
  generateRequestId,
  generateSessionId,
  generateProjectId,
  generateRequestBody
}