File size: 8,995 Bytes
97ec0e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 axios from 'axios';
import tokenManager from '../auth/token_manager.js';
import config from '../config/config.js';
import { generateToolCallId } from '../utils/idGenerator.js';
import AntigravityRequester from '../AntigravityRequester.js';
import { saveBase64Image } from '../utils/imageStorage.js';

// 请求客户端:优先使用 AntigravityRequester,失败则降级到 axios
let requester = null;
let useAxios = false;

if (config.useNativeAxios === true) {
  useAxios = true;
} else {
  try {
    requester = new AntigravityRequester();
  } catch (error) {
    console.warn('AntigravityRequester 初始化失败,降级使用 axios:', error.message);
    useAxios = true;
  }
}

// ==================== 辅助函数 ====================

function buildHeaders(token) {
  return {
    'Host': config.api.host,
    'User-Agent': config.api.userAgent,
    'Authorization': `Bearer ${token.access_token}`,
    'Content-Type': 'application/json',
    'Accept-Encoding': 'gzip'
  };
}

function buildAxiosConfig(url, headers, body = null) {
  const axiosConfig = {
    method: 'POST',
    url,
    headers,
    timeout: config.timeout,
    proxy: config.proxy ? (() => {
      const proxyUrl = new URL(config.proxy);
      return { protocol: proxyUrl.protocol.replace(':', ''), host: proxyUrl.hostname, port: parseInt(proxyUrl.port) };
    })() : false
  };
  if (body !== null) axiosConfig.data = body;
  return axiosConfig;
}

function buildRequesterConfig(headers, body = null) {
  const reqConfig = {
    method: 'POST',
    headers,
    timeout_ms: config.timeout,
    proxy: config.proxy
  };
  if (body !== null) reqConfig.body = JSON.stringify(body);
  return reqConfig;
}

// 统一错误处理
async function handleApiError(error, token) {
  const status = error.response?.status || error.status || 'Unknown';
  let errorBody = error.message;
  
  if (error.response?.data?.readable) {
    const chunks = [];
    for await (const chunk of error.response.data) {
      chunks.push(chunk);
    }
    errorBody = Buffer.concat(chunks).toString();
  } else if (typeof error.response?.data === 'object') {
    errorBody = JSON.stringify(error.response.data, null, 2);
  } else if (error.response?.data) {
    errorBody = error.response.data;
  }
  
  if (status === 403) {
    tokenManager.disableCurrentToken(token);
    throw new Error(`该账号没有使用权限,已自动禁用。错误详情: ${errorBody}`);
  }
  
  throw new Error(`API请求失败 (${status}): ${errorBody}`);
}

// 转换 functionCall 为 OpenAI 格式
function convertToToolCall(functionCall) {
  return {
    id: functionCall.id || generateToolCallId(),
    type: 'function',
    function: {
      name: functionCall.name,
      arguments: JSON.stringify(functionCall.args)
    }
  };
}

// 解析并发送流式响应片段(会修改 state 并触发 callback)
function parseAndEmitStreamChunk(line, state, callback) {
  if (!line.startsWith('data: ')) return;
  
  try {
    const data = JSON.parse(line.slice(6));
    const parts = data.response?.candidates?.[0]?.content?.parts;
    
    if (parts) {
      for (const part of parts) {
        if (part.thought === true) {
          // 思维链内容
          if (!state.thinkingStarted) {
            callback({ type: 'thinking', content: '<think>\n' });
            state.thinkingStarted = true;
          }
          callback({ type: 'thinking', content: part.text || '' });
        } else if (part.text !== undefined) {
          // 普通文本内容
          if (state.thinkingStarted) {
            callback({ type: 'thinking', content: '\n</think>\n' });
            state.thinkingStarted = false;
          }
          callback({ type: 'text', content: part.text });
        } else if (part.functionCall) {
          // 工具调用
          state.toolCalls.push(convertToToolCall(part.functionCall));
        }
      }
    }
    
    // 响应结束时发送工具调用
    if (data.response?.candidates?.[0]?.finishReason && state.toolCalls.length > 0) {
      if (state.thinkingStarted) {
        callback({ type: 'thinking', content: '\n</think>\n' });
        state.thinkingStarted = false;
      }
      callback({ type: 'tool_calls', tool_calls: state.toolCalls });
      state.toolCalls = [];
    }
  } catch (e) {
    // 忽略 JSON 解析错误
  }
}

// ==================== 导出函数 ====================

export async function generateAssistantResponse(requestBody, token, callback) {
  
  const headers = buildHeaders(token);
  const state = { thinkingStarted: false, toolCalls: [] };
  let buffer = ''; // 缓冲区:处理跨 chunk 的不完整行
  
  const processChunk = (chunk) => {
    buffer += chunk;
    const lines = buffer.split('\n');
    buffer = lines.pop(); // 保留最后一行(可能不完整)
    lines.forEach(line => parseAndEmitStreamChunk(line, state, callback));
  };
  
  if (useAxios) {
    try {
      const axiosConfig = { ...buildAxiosConfig(config.api.url, headers, requestBody), responseType: 'stream' };
      const response = await axios(axiosConfig);
      
      response.data.on('data', chunk => processChunk(chunk.toString()));
      await new Promise((resolve, reject) => {
        response.data.on('end', resolve);
        response.data.on('error', reject);
      });
    } catch (error) {
      await handleApiError(error, token);
    }
  } else {
    try {
      const streamResponse = requester.antigravity_fetchStream(config.api.url, buildRequesterConfig(headers, requestBody));
      let errorBody = '';
      let statusCode = null;

      await new Promise((resolve, reject) => {
        streamResponse
          .onStart(({ status }) => { statusCode = status; })
          .onData((chunk) => statusCode !== 200 ? errorBody += chunk : processChunk(chunk))
          .onEnd(() => statusCode !== 200 ? reject({ status: statusCode, message: errorBody }) : resolve())
          .onError(reject);
      });
    } catch (error) {
      await handleApiError(error, token);
    }
  }
}

export async function getAvailableModels() {
  const token = await tokenManager.getToken();
  if (!token) throw new Error('没有可用的token,请运行 npm run login 获取token');
  
  const headers = buildHeaders(token);
  
  try {
    let data;
    if (useAxios) {
      data = (await axios(buildAxiosConfig(config.api.modelsUrl, headers, {}))).data;
    } else {
      const response = await requester.antigravity_fetch(config.api.modelsUrl, buildRequesterConfig(headers, {}));
      if (response.status !== 200) {
        const errorBody = await response.text();
        throw { status: response.status, message: errorBody };
      }
      data = await response.json();
    }
    const modelList = Object.keys(data.models).map(id => ({
        id,
        object: 'model',
        created: Math.floor(Date.now() / 1000),
        owned_by: 'google'
      }));
    modelList.push({
      id: "claude-opus-4-5",
      object: 'model',
      created: Math.floor(Date.now() / 1000),
      owned_by: 'google'
    })
    
    return {
      object: 'list',
      data: modelList
    };
  } catch (error) {
    await handleApiError(error, token);
  }
}

export async function generateAssistantResponseNoStream(requestBody, token) {
  
  const headers = buildHeaders(token);
  let data;
  
  try {
    if (useAxios) {
      data = (await axios(buildAxiosConfig(config.api.noStreamUrl, headers, requestBody))).data;
    } else {
      const response = await requester.antigravity_fetch(config.api.noStreamUrl, buildRequesterConfig(headers, requestBody));
      if (response.status !== 200) {
        const errorBody = await response.text();
        throw { status: response.status, message: errorBody };
      }
      data = await response.json();
    }
  } catch (error) {
    await handleApiError(error, token);
  }
  
  // 解析响应内容
  const parts = data.response?.candidates?.[0]?.content?.parts || [];
  let content = '';
  let thinkingContent = '';
  const toolCalls = [];
  const imageUrls = [];
  
  for (const part of parts) {
    if (part.thought === true) {
      thinkingContent += part.text || '';
    } else if (part.text !== undefined) {
      content += part.text;
    } else if (part.functionCall) {
      toolCalls.push(convertToToolCall(part.functionCall));
    } else if (part.inlineData) {
      // 保存图片到本地并获取 URL
      const imageUrl = saveBase64Image(part.inlineData.data, part.inlineData.mimeType);
      imageUrls.push(imageUrl);
    }
  }
  
  // 拼接思维链标签
  if (thinkingContent) {
    content = `<think>\n${thinkingContent}\n</think>\n${content}`;
  }
  
  // 生图模型:转换为 markdown 格式
  if (imageUrls.length > 0) {
    let markdown = content ? content + '\n\n' : '';
    markdown += imageUrls.map(url => `![image](${url})`).join('\n\n');
    return { content: markdown, toolCalls };
  }
  
  return { content, toolCalls };
}

export function closeRequester() {
  if (requester) requester.close();
}