tuxevil-rotator 3.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.
Files changed (142) hide show
  1. package/CHANGELOG.md +773 -0
  2. package/LICENSE +21 -0
  3. package/README.md +341 -0
  4. package/bin/pi-antigravity-rotator.js +27 -0
  5. package/bin/tuxevil-rotator.js +5 -0
  6. package/package.json +63 -0
  7. package/src/account-store.ts +542 -0
  8. package/src/admin-auth.ts +126 -0
  9. package/src/body-limit.ts +52 -0
  10. package/src/cli.ts +293 -0
  11. package/src/compat/cache.ts +38 -0
  12. package/src/compat/model-specs.ts +82 -0
  13. package/src/compat/schema-sanitizer.ts +284 -0
  14. package/src/compat.ts +2357 -0
  15. package/src/compression/index.ts +92 -0
  16. package/src/compression/lite.ts +210 -0
  17. package/src/compression/preservation.ts +183 -0
  18. package/src/compression/rtk/command-detector.ts +170 -0
  19. package/src/compression/rtk/deduplicator.ts +39 -0
  20. package/src/compression/rtk/filter-loader.ts +84 -0
  21. package/src/compression/rtk/filter-types.ts +25 -0
  22. package/src/compression/rtk/filters/aws.json +34 -0
  23. package/src/compression/rtk/filters/biome.json +35 -0
  24. package/src/compression/rtk/filters/build-eslint.json +37 -0
  25. package/src/compression/rtk/filters/build-typescript.json +33 -0
  26. package/src/compression/rtk/filters/build-vite.json +41 -0
  27. package/src/compression/rtk/filters/build-webpack.json +34 -0
  28. package/src/compression/rtk/filters/bundle-install.json +35 -0
  29. package/src/compression/rtk/filters/composer.json +81 -0
  30. package/src/compression/rtk/filters/curl.json +34 -0
  31. package/src/compression/rtk/filters/df.json +34 -0
  32. package/src/compression/rtk/filters/docker-build.json +78 -0
  33. package/src/compression/rtk/filters/docker-logs.json +42 -0
  34. package/src/compression/rtk/filters/docker-ps.json +33 -0
  35. package/src/compression/rtk/filters/dotnet.json +47 -0
  36. package/src/compression/rtk/filters/du.json +33 -0
  37. package/src/compression/rtk/filters/error-stacktrace.json +41 -0
  38. package/src/compression/rtk/filters/gcloud.json +34 -0
  39. package/src/compression/rtk/filters/generic-output.json +32 -0
  40. package/src/compression/rtk/filters/gh.json +98 -0
  41. package/src/compression/rtk/filters/git-branch.json +45 -0
  42. package/src/compression/rtk/filters/git-diff.json +33 -0
  43. package/src/compression/rtk/filters/git-log.json +33 -0
  44. package/src/compression/rtk/filters/git-status.json +40 -0
  45. package/src/compression/rtk/filters/golangci-lint.json +34 -0
  46. package/src/compression/rtk/filters/gradle.json +47 -0
  47. package/src/compression/rtk/filters/json-output.json +40 -0
  48. package/src/compression/rtk/filters/kubectl.json +99 -0
  49. package/src/compression/rtk/filters/make.json +38 -0
  50. package/src/compression/rtk/filters/mypy.json +34 -0
  51. package/src/compression/rtk/filters/npm-audit.json +43 -0
  52. package/src/compression/rtk/filters/npm-install.json +41 -0
  53. package/src/compression/rtk/filters/nx.json +34 -0
  54. package/src/compression/rtk/filters/pip.json +41 -0
  55. package/src/compression/rtk/filters/playwright.json +42 -0
  56. package/src/compression/rtk/filters/poetry-install.json +35 -0
  57. package/src/compression/rtk/filters/prettier.json +40 -0
  58. package/src/compression/rtk/filters/ps.json +34 -0
  59. package/src/compression/rtk/filters/rsync.json +33 -0
  60. package/src/compression/rtk/filters/rubocop.json +34 -0
  61. package/src/compression/rtk/filters/ruff.json +40 -0
  62. package/src/compression/rtk/filters/shell-find.json +33 -0
  63. package/src/compression/rtk/filters/shell-grep.json +37 -0
  64. package/src/compression/rtk/filters/shell-ls.json +33 -0
  65. package/src/compression/rtk/filters/ssh.json +43 -0
  66. package/src/compression/rtk/filters/systemctl-status.json +43 -0
  67. package/src/compression/rtk/filters/terraform-plan.json +34 -0
  68. package/src/compression/rtk/filters/test-cargo.json +42 -0
  69. package/src/compression/rtk/filters/test-go.json +41 -0
  70. package/src/compression/rtk/filters/test-jest.json +43 -0
  71. package/src/compression/rtk/filters/test-pytest.json +41 -0
  72. package/src/compression/rtk/filters/test-vitest.json +43 -0
  73. package/src/compression/rtk/filters/tofu-plan.json +34 -0
  74. package/src/compression/rtk/filters/turbo.json +34 -0
  75. package/src/compression/rtk/filters/uv-sync.json +35 -0
  76. package/src/compression/rtk/filters/wget.json +34 -0
  77. package/src/compression/rtk/index.ts +103 -0
  78. package/src/compression/rtk/line-filter.ts +124 -0
  79. package/src/compression/rtk/smart-truncate.ts +71 -0
  80. package/src/config-defaults.ts +93 -0
  81. package/src/config-normalize.ts +48 -0
  82. package/src/config-storage.ts +21 -0
  83. package/src/dashboard.ts +1169 -0
  84. package/src/db-store.ts +188 -0
  85. package/src/doctor.ts +115 -0
  86. package/src/env.ts +15 -0
  87. package/src/exposure.ts +17 -0
  88. package/src/fetch-with-retry.ts +93 -0
  89. package/src/idempotency.ts +137 -0
  90. package/src/index.ts +267 -0
  91. package/src/key-auth.ts +159 -0
  92. package/src/key-migrations.ts +84 -0
  93. package/src/logger.ts +92 -0
  94. package/src/login.ts +48 -0
  95. package/src/notification-poller.ts +155 -0
  96. package/src/onboarding.ts +754 -0
  97. package/src/paths.ts +153 -0
  98. package/src/providers/adapter.ts +131 -0
  99. package/src/providers/credential-helpers.ts +72 -0
  100. package/src/providers/google-antigravity/code-assist.ts +161 -0
  101. package/src/providers/google-antigravity/credentials.ts +24 -0
  102. package/src/providers/google-antigravity/forward.ts +424 -0
  103. package/src/providers/google-antigravity/index.ts +168 -0
  104. package/src/providers/google-antigravity/login.ts +285 -0
  105. package/src/providers/google-antigravity/oauth.ts +314 -0
  106. package/src/providers/google-antigravity/quota.ts +152 -0
  107. package/src/providers/google-antigravity/translators.ts +1663 -0
  108. package/src/providers/ollama/api-key-validation.ts +59 -0
  109. package/src/providers/ollama/credentials.ts +28 -0
  110. package/src/providers/ollama/forward.ts +306 -0
  111. package/src/providers/ollama/index.ts +85 -0
  112. package/src/providers/ollama/login.ts +55 -0
  113. package/src/providers/ollama/prediction.ts +188 -0
  114. package/src/providers/ollama/quota-poll-store.ts +160 -0
  115. package/src/providers/ollama/quota.ts +189 -0
  116. package/src/providers/ollama/translators.ts +256 -0
  117. package/src/providers/ollama/usage-windows.ts +48 -0
  118. package/src/providers/proxy-dispatcher.ts +269 -0
  119. package/src/providers/registry.ts +70 -0
  120. package/src/proxy.ts +2446 -0
  121. package/src/rate-limit-parser.ts +126 -0
  122. package/src/response-headers.ts +98 -0
  123. package/src/responses-store.ts +159 -0
  124. package/src/rotator.ts +3614 -0
  125. package/src/settings-repository.ts +327 -0
  126. package/src/spend-logger.ts +696 -0
  127. package/src/static/dashboard-keys.js +384 -0
  128. package/src/static/dashboard-logs.js +797 -0
  129. package/src/static/dashboard.css +2740 -0
  130. package/src/static/dashboard.js +3177 -0
  131. package/src/storage.ts +105 -0
  132. package/src/systemd-env.ts +214 -0
  133. package/src/telemetry.ts +384 -0
  134. package/src/token-encryption.ts +199 -0
  135. package/src/types.ts +897 -0
  136. package/src/validators.ts +218 -0
  137. package/src/version-check.ts +225 -0
  138. package/src/virtual-keys.ts +312 -0
  139. package/tools/telemetry-receiver/README.md +147 -0
  140. package/tools/telemetry-receiver/package.json +13 -0
  141. package/tools/telemetry-receiver/receiver.js +2334 -0
  142. package/tuxevil-rotator_logo.png +0 -0
@@ -0,0 +1,1663 @@
1
+ import { logger, redactSensitive } from "../../logger.js";
2
+ import { applyModelAlias } from "../../types.js";
3
+ import type { RequestBody } from "../../proxy.js";
4
+ import {
5
+ isRecord,
6
+ sanitizeGeminiSchema,
7
+ sanitizeClaudeViaGeminiSchema,
8
+ } from "../../compat/schema-sanitizer.js";
9
+ import {
10
+ getModelFamily,
11
+ getModelSpec,
12
+ isThinkingModel,
13
+ } from "../../compat/model-specs.js";
14
+ import {
15
+ thoughtSignatureCache,
16
+ getStoredResponse,
17
+ setStoredResponse,
18
+ makeCompatId,
19
+ } from "../../compat/cache.js";
20
+
21
+ const compatLogger = logger.child("compat");
22
+
23
+ const VALIDATION_LOG_MAX_CHARS = 200;
24
+
25
+ export function logValidationFailure(scope: string, payload: unknown): void {
26
+ const truncated = redactSensitive(JSON.stringify(payload));
27
+ const clipped =
28
+ truncated.length > VALIDATION_LOG_MAX_CHARS
29
+ ? `${truncated.slice(0, VALIDATION_LOG_MAX_CHARS)}…[+${truncated.length - VALIDATION_LOG_MAX_CHARS} chars]`
30
+ : truncated;
31
+ compatLogger.warn(`${scope}: ${clipped}`);
32
+ }
33
+
34
+ export interface ResponseOutputText {
35
+ type: "output_text";
36
+ text: string;
37
+ annotations: unknown[];
38
+ }
39
+
40
+ export interface ResponseMessageOutputItem {
41
+ id: string;
42
+ type: "message";
43
+ status: "completed";
44
+ role: "assistant";
45
+ content: ResponseOutputText[];
46
+ }
47
+
48
+ export interface ResponseFunctionCallOutputItem {
49
+ id: string;
50
+ type: "function_call";
51
+ call_id: string;
52
+ name: string;
53
+ /** JSON-encoded function arguments (OpenAI Responses API format). */
54
+ arguments: unknown;
55
+ status: "completed";
56
+ }
57
+
58
+ export type ResponseOutputItem =
59
+ | ResponseMessageOutputItem
60
+ | ResponseFunctionCallOutputItem;
61
+
62
+ export interface ChatMessage {
63
+ role: "system" | "developer" | "user" | "assistant" | "model" | "tool";
64
+ content?:
65
+ | string
66
+ | Array<{ type: string; text?: string; [key: string]: unknown }>
67
+ | null;
68
+ tool_calls?: OpenAIToolCall[];
69
+ tool_call_id?: string;
70
+ name?: string;
71
+ }
72
+
73
+ export interface OpenAITool {
74
+ type: "function";
75
+ function: {
76
+ name: string;
77
+ description?: string;
78
+ parameters?: Record<string, unknown>;
79
+ };
80
+ }
81
+
82
+ export interface OpenAIToolCall {
83
+ id: string;
84
+ type: "function";
85
+ function: {
86
+ name: string;
87
+ /**
88
+ * Function arguments: the OpenAI standard encodes this as a
89
+ * JSON-stringified string, while Ollama expects an object. Callers
90
+ * (rotator/forward) deal with the right shape for each provider.
91
+ */
92
+ arguments: unknown;
93
+ };
94
+ }
95
+
96
+ export interface OpenAIToolChoice {
97
+ type: "function";
98
+ function: { name: string };
99
+ }
100
+
101
+ export interface OpenAIChatCompletionRequest {
102
+ model: string;
103
+ messages: ChatMessage[];
104
+ stream?: boolean;
105
+ temperature?: number;
106
+ max_tokens?: number;
107
+ prompt?: string | string[];
108
+ input?: unknown;
109
+ tools?: OpenAITool[];
110
+ tool_choice?: unknown;
111
+ /** OpenAI-style reasoning effort. Mapped to Gemini thinkingLevel. */
112
+ reasoning_effort?: string;
113
+ [key: string]: unknown;
114
+ }
115
+
116
+ export interface OpenAIResponsesRequest {
117
+ model: string;
118
+ input?: unknown;
119
+ instructions?:
120
+ | string
121
+ | Array<{ type: string; text?: string; [key: string]: unknown }>
122
+ | null;
123
+ stream?: boolean;
124
+ temperature?: number;
125
+ max_output_tokens?: number;
126
+ tools?: Array<Record<string, unknown>>;
127
+ tool_choice?: unknown;
128
+ reasoning?: { effort?: string | null; [key: string]: unknown } | null;
129
+ metadata?: Record<string, string>;
130
+ store?: boolean;
131
+ previous_response_id?: string | null;
132
+ conversation?: unknown;
133
+ parallel_tool_calls?: boolean;
134
+ [key: string]: unknown;
135
+ }
136
+
137
+ export interface AnthropicMessagesRequest {
138
+ model: string;
139
+ messages: ChatMessage[];
140
+ system?:
141
+ | string
142
+ | Array<{ type: string; text?: string; [key: string]: unknown }>;
143
+ stream?: boolean;
144
+ max_tokens?: number;
145
+ temperature?: number;
146
+ [key: string]: unknown;
147
+ }
148
+
149
+ export interface CompatCompletion {
150
+ text: string;
151
+ thinkingText?: string; // Gemini thought blocks (thought: true), emitted as reasoning_content
152
+ inputTokens: number;
153
+ outputTokens: number;
154
+ firstByteMs?: number;
155
+ responseId?: string;
156
+ toolCalls?: OpenAIToolCall[];
157
+ rawResponse?: unknown;
158
+ streamError?: string;
159
+ }
160
+
161
+ export type AntigravityPart =
162
+ | { text: string }
163
+ | { inlineData: { mimeType: string; data: string } };
164
+ export type GeminiContent = { role: "user" | "model"; parts: unknown[] };
165
+
166
+ interface GeminiFunctionDeclaration {
167
+ name: string;
168
+ description?: string;
169
+ parameters?: Record<string, unknown>;
170
+ }
171
+
172
+ interface GeminiToolConfig {
173
+ functionCallingConfig: {
174
+ mode: "AUTO" | "NONE" | "ANY";
175
+ allowedFunctionNames?: string[];
176
+ };
177
+ }
178
+
179
+ export type ResponsesConversionResult = {
180
+ chatRequest: OpenAIChatCompletionRequest;
181
+ inputItems: Array<Record<string, unknown>>;
182
+ conversationMessages: ChatMessage[];
183
+ previousResponseId: string | null;
184
+ };
185
+
186
+ export function isNonEmptyString(value: unknown): value is string {
187
+ return typeof value === "string" && value.trim().length > 0;
188
+ }
189
+
190
+ /**
191
+ * Normalize a tool-call `arguments` field into the JSON-encoded string
192
+ * shape that OpenAI-compat responses expect. The Ollama adapter feeds us
193
+ * a parsed object, while OpenAI/Antigravity already gives us a string.
194
+ */
195
+ export function toolArgumentsToString(args: unknown): string {
196
+ if (typeof args === "string") return args;
197
+ try {
198
+ return JSON.stringify(args ?? {});
199
+ } catch {
200
+ return "{}";
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Normalize a tool-call `arguments` field into a parsed object, falling
206
+ * back to an empty object when the payload is malformed. Used when
207
+ * forwarding an OpenAI-style request (where `arguments` is a string)
208
+ * into Ollama (which expects an object).
209
+ */
210
+ export function toolArgumentsToObject(args: unknown): Record<string, unknown> {
211
+ if (args && typeof args === "object") return args as Record<string, unknown>;
212
+ if (typeof args === "string") {
213
+ try {
214
+ const parsed = JSON.parse(args);
215
+ if (parsed && typeof parsed === "object") {
216
+ return parsed as Record<string, unknown>;
217
+ }
218
+ } catch {
219
+ // fall through
220
+ }
221
+ }
222
+ return {};
223
+ }
224
+
225
+ function cleanCacheControl<T>(content: T): T {
226
+ if (!Array.isArray(content)) return content;
227
+ return content.map((block: Record<string, unknown>) => {
228
+ if (!block || typeof block !== "object") return block;
229
+ if ("cache_control" in block) {
230
+ const { cache_control: _cc, ...rest } = block;
231
+ return rest;
232
+ }
233
+ return block;
234
+ }) as T;
235
+ }
236
+
237
+ export function extractText(content: ChatMessage["content"]): string {
238
+ if (typeof content === "string") return content;
239
+ if (!Array.isArray(content)) return "";
240
+ return cleanCacheControl(content)
241
+ .filter(
242
+ (p: { type?: string; text?: string; thinking?: string }) =>
243
+ (p.type === "text" && typeof p.text === "string") ||
244
+ (p.type === "thinking" && typeof p.thinking === "string"),
245
+ )
246
+ .map((p: { type?: string; text?: string; thinking?: string }) =>
247
+ p.type === "thinking"
248
+ ? `[Thinking]\n${p.thinking}\n[/Thinking]`
249
+ : (p.text as string),
250
+ )
251
+ .join("\n");
252
+ }
253
+
254
+ export function dataUrlToInlineData(url: string): AntigravityPart | null {
255
+ const match = url.match(/^data:([^;,]+);base64,(.+)$/s);
256
+ if (!match) return null;
257
+ return { inlineData: { mimeType: match[1], data: match[2] } };
258
+ }
259
+
260
+ export function extractParts(
261
+ content: ChatMessage["content"],
262
+ ): AntigravityPart[] {
263
+ if (content === null) return [];
264
+ if (typeof content === "string") return content ? [{ text: content }] : [];
265
+ if (!Array.isArray(content)) return [];
266
+ const parts: AntigravityPart[] = [];
267
+ for (const part of content) {
268
+ if (part.type === "text" && typeof part.text === "string" && part.text) {
269
+ parts.push({ text: part.text });
270
+ continue;
271
+ }
272
+ if (
273
+ part.type === "thinking" &&
274
+ typeof part.thinking === "string" &&
275
+ part.thinking
276
+ ) {
277
+ parts.push({ text: `[Thinking]\n${part.thinking}\n[/Thinking]` });
278
+ continue;
279
+ }
280
+ if (
281
+ part.type === "image_url" &&
282
+ isRecord(part.image_url) &&
283
+ typeof part.image_url.url === "string"
284
+ ) {
285
+ const inline = dataUrlToInlineData(part.image_url.url);
286
+ if (inline) parts.push(inline);
287
+ continue;
288
+ }
289
+ if (
290
+ part.type === "image" &&
291
+ isRecord(part.source) &&
292
+ part.source.type === "base64" &&
293
+ typeof part.source.media_type === "string" &&
294
+ typeof part.source.data === "string"
295
+ ) {
296
+ parts.push({
297
+ inlineData: {
298
+ mimeType: part.source.media_type,
299
+ data: part.source.data,
300
+ },
301
+ });
302
+ }
303
+ }
304
+ return parts;
305
+ }
306
+
307
+ export function convertOpenAIToolsToGemini(
308
+ tools: OpenAITool[],
309
+ isClaude: boolean = false,
310
+ ): { functionDeclarations: GeminiFunctionDeclaration[] }[] {
311
+ const decls: GeminiFunctionDeclaration[] = tools
312
+ .filter((t) => t.type === "function" && isNonEmptyString(t.function?.name))
313
+ .map((t) => {
314
+ const sanitized = t.function.parameters
315
+ ? ((isClaude
316
+ ? sanitizeClaudeViaGeminiSchema(t.function.parameters)
317
+ : sanitizeGeminiSchema(t.function.parameters)) as Record<
318
+ string,
319
+ unknown
320
+ >)
321
+ : undefined;
322
+ return {
323
+ name: t.function.name,
324
+ ...(t.function.description
325
+ ? { description: t.function.description }
326
+ : {}),
327
+ ...(sanitized ? { parameters: sanitized } : {}),
328
+ };
329
+ });
330
+ return decls.length > 0 ? [{ functionDeclarations: decls }] : [];
331
+ }
332
+
333
+ export function convertToolChoiceToGemini(
334
+ toolChoice: unknown,
335
+ ): GeminiToolConfig | undefined {
336
+ if (!toolChoice || toolChoice === "none")
337
+ return { functionCallingConfig: { mode: "NONE" } };
338
+ if (toolChoice === "auto" || toolChoice === "required")
339
+ return { functionCallingConfig: { mode: "AUTO" } };
340
+ if (
341
+ isRecord(toolChoice) &&
342
+ toolChoice.type === "function" &&
343
+ isRecord(toolChoice.function) &&
344
+ isNonEmptyString(toolChoice.function.name)
345
+ ) {
346
+ return {
347
+ functionCallingConfig: {
348
+ mode: "ANY",
349
+ allowedFunctionNames: [toolChoice.function.name],
350
+ },
351
+ };
352
+ }
353
+ return { functionCallingConfig: { mode: "AUTO" } };
354
+ }
355
+
356
+ export function validateMessages(value: unknown): value is ChatMessage[] {
357
+ return (
358
+ Array.isArray(value) &&
359
+ value.every((msg) => {
360
+ if (!isRecord(msg)) return false;
361
+ if (
362
+ !["system", "developer", "user", "assistant", "model", "tool"].includes(
363
+ String(msg.role),
364
+ )
365
+ )
366
+ return false;
367
+ // OpenAI clients may omit assistant content when the turn consists
368
+ // solely of valid tool calls. Other roles still require content.
369
+ if (msg.content === undefined) {
370
+ return msg.role === "assistant" && hasValidToolCalls(msg.tool_calls);
371
+ }
372
+ return (
373
+ typeof msg.content === "string" ||
374
+ msg.content === null ||
375
+ Array.isArray(msg.content)
376
+ );
377
+ })
378
+ );
379
+ }
380
+
381
+ function hasValidToolCalls(value: unknown): value is OpenAIToolCall[] {
382
+ return (
383
+ Array.isArray(value) &&
384
+ value.length > 0 &&
385
+ value.every(
386
+ (toolCall) =>
387
+ isRecord(toolCall) &&
388
+ isNonEmptyString(toolCall.id) &&
389
+ toolCall.type === "function" &&
390
+ isRecord(toolCall.function) &&
391
+ isNonEmptyString(toolCall.function.name) &&
392
+ "arguments" in toolCall.function,
393
+ )
394
+ );
395
+ }
396
+
397
+ export function extractTextFromUnknownContent(content: unknown): string {
398
+ if (typeof content === "string") return content;
399
+ if (!Array.isArray(content)) return "";
400
+ return content
401
+ .map((part) => {
402
+ if (typeof part === "string") return part;
403
+ if (!isRecord(part)) return "";
404
+ if (typeof part.text === "string") return part.text;
405
+ if (typeof part.input_text === "string") return part.input_text;
406
+ if (typeof part.output_text === "string") return part.output_text;
407
+ return "";
408
+ })
409
+ .filter(Boolean)
410
+ .join("\n");
411
+ }
412
+
413
+ export function normalizeContentBlocks(
414
+ content: unknown,
415
+ ): ChatMessage["content"] {
416
+ if (typeof content === "string" || content === null) return content;
417
+ if (!Array.isArray(content)) return extractTextFromUnknownContent(content);
418
+ const blocks = content.flatMap((part) => {
419
+ if (typeof part === "string") return [{ type: "text", text: part }];
420
+ if (!isRecord(part)) return [];
421
+ if (part.type === "input_text" && typeof part.text === "string")
422
+ return [{ type: "text", text: part.text }];
423
+ if (part.type === "output_text" && typeof part.text === "string")
424
+ return [{ type: "text", text: part.text }];
425
+ if (typeof part.text === "string")
426
+ return [
427
+ {
428
+ ...part,
429
+ type: typeof part.type === "string" ? part.type : "text",
430
+ text: part.text,
431
+ },
432
+ ];
433
+ if (typeof part.input_text === "string")
434
+ return [{ type: "text", text: part.input_text }];
435
+ if (typeof part.output_text === "string")
436
+ return [{ type: "text", text: part.output_text }];
437
+ if (part.type === "input_image" && typeof part.image_url === "string") {
438
+ return [{ type: "image_url", image_url: { url: part.image_url } }];
439
+ }
440
+ return [part as { type: string; text?: string; [key: string]: unknown }];
441
+ });
442
+ return blocks.length > 0 ? blocks : "";
443
+ }
444
+
445
+ export function normalizeInstructionsContent(
446
+ content: OpenAIResponsesRequest["instructions"],
447
+ ): ChatMessage["content"] {
448
+ if (typeof content === "string" || content === null || content === undefined)
449
+ return content ?? "";
450
+ return normalizeContentBlocks(content);
451
+ }
452
+
453
+ export function contentToResponseInputBlocks(
454
+ content: ChatMessage["content"],
455
+ role: string,
456
+ ): Array<Record<string, unknown>> {
457
+ if (typeof content === "string") {
458
+ if (!content) return [];
459
+ return [
460
+ {
461
+ type:
462
+ role === "assistant" || role === "model"
463
+ ? "output_text"
464
+ : "input_text",
465
+ text: content,
466
+ },
467
+ ];
468
+ }
469
+ if (!Array.isArray(content)) return [];
470
+ return cleanCacheControl(content).flatMap((part) => {
471
+ if (!isRecord(part)) return [];
472
+ if (typeof part.text === "string") {
473
+ return [
474
+ {
475
+ type:
476
+ role === "assistant" || role === "model"
477
+ ? "output_text"
478
+ : "input_text",
479
+ text: part.text,
480
+ },
481
+ ];
482
+ }
483
+ if (
484
+ part.type === "image_url" &&
485
+ isRecord(part.image_url) &&
486
+ typeof part.image_url.url === "string"
487
+ ) {
488
+ return [{ type: "input_image", image_url: part.image_url.url }];
489
+ }
490
+ return [part];
491
+ });
492
+ }
493
+
494
+ export function parseResponsesInput(
495
+ input: unknown,
496
+ callIdToName: Map<string, string> = new Map(),
497
+ ): ParsedResponsesInput {
498
+ if (typeof input === "string") {
499
+ return {
500
+ inputItems: [
501
+ {
502
+ id: makeCompatId("in"),
503
+ type: "message",
504
+ role: "user",
505
+ content: [{ type: "input_text", text: input }],
506
+ },
507
+ ],
508
+ messages: [{ role: "user", content: input }],
509
+ };
510
+ }
511
+ if (!Array.isArray(input)) return { inputItems: [], messages: [] };
512
+
513
+ const inputItems: Array<Record<string, unknown>> = [];
514
+ const messages: ChatMessage[] = [];
515
+
516
+ for (const rawItem of input) {
517
+ if (typeof rawItem === "string") {
518
+ inputItems.push({
519
+ id: makeCompatId("in"),
520
+ type: "message",
521
+ role: "user",
522
+ content: [{ type: "input_text", text: rawItem }],
523
+ });
524
+ messages.push({ role: "user", content: rawItem });
525
+ continue;
526
+ }
527
+ if (!isRecord(rawItem)) continue;
528
+
529
+ if (
530
+ rawItem.type === "function_call_output" &&
531
+ typeof rawItem.call_id === "string"
532
+ ) {
533
+ const outputText =
534
+ typeof rawItem.output === "string"
535
+ ? rawItem.output
536
+ : JSON.stringify(rawItem.output ?? "");
537
+ const toolName =
538
+ typeof rawItem.name === "string"
539
+ ? rawItem.name
540
+ : callIdToName.get(rawItem.call_id) || "unknown";
541
+ inputItems.push({
542
+ id: makeCompatId("in"),
543
+ type: "function_call_output",
544
+ call_id: rawItem.call_id,
545
+ output: outputText,
546
+ });
547
+ messages.push({
548
+ role: "tool",
549
+ content: outputText,
550
+ name: toolName,
551
+ tool_call_id: rawItem.call_id,
552
+ });
553
+ continue;
554
+ }
555
+
556
+ if (rawItem.type === "function_call" && typeof rawItem.name === "string") {
557
+ const callId =
558
+ typeof rawItem.call_id === "string"
559
+ ? rawItem.call_id
560
+ : makeCompatId("call");
561
+ const args =
562
+ typeof rawItem.arguments === "string"
563
+ ? rawItem.arguments
564
+ : JSON.stringify(rawItem.arguments ?? {});
565
+ inputItems.push({
566
+ id: makeCompatId("in"),
567
+ type: "function_call",
568
+ call_id: callId,
569
+ name: rawItem.name,
570
+ arguments: args,
571
+ });
572
+ const lastMsg = messages[messages.length - 1];
573
+ if (
574
+ lastMsg &&
575
+ lastMsg.role === "assistant" &&
576
+ Array.isArray(lastMsg.tool_calls)
577
+ ) {
578
+ lastMsg.tool_calls.push({
579
+ id: callId,
580
+ type: "function",
581
+ function: { name: rawItem.name, arguments: args },
582
+ });
583
+ } else {
584
+ messages.push({
585
+ role: "assistant",
586
+ content: null,
587
+ tool_calls: [
588
+ {
589
+ id: callId,
590
+ type: "function",
591
+ function: { name: rawItem.name, arguments: args },
592
+ },
593
+ ],
594
+ });
595
+ }
596
+ continue;
597
+ }
598
+
599
+ const isMessage =
600
+ rawItem.type === "message" ||
601
+ typeof rawItem.role === "string" ||
602
+ "content" in rawItem;
603
+ if (!isMessage) continue;
604
+ const rawRole = typeof rawItem.role === "string" ? rawItem.role : "user";
605
+ const role = rawRole === "developer" ? "system" : rawRole;
606
+ if (!["system", "user", "assistant", "model", "tool"].includes(role))
607
+ continue;
608
+ const content =
609
+ "content" in rawItem
610
+ ? normalizeContentBlocks(rawItem.content)
611
+ : extractTextFromUnknownContent(rawItem);
612
+ inputItems.push({
613
+ id: makeCompatId("in"),
614
+ type: "message",
615
+ role: rawRole,
616
+ content: contentToResponseInputBlocks(content, role),
617
+ });
618
+ messages.push({ role: role as ChatMessage["role"], content });
619
+ }
620
+
621
+ return { inputItems, messages };
622
+ }
623
+
624
+ type ParsedResponsesInput = {
625
+ inputItems: Array<Record<string, unknown>>;
626
+ messages: ChatMessage[];
627
+ };
628
+
629
+ export function messagesFromResponsesInput(
630
+ input: unknown,
631
+ ): ChatMessage[] | null {
632
+ if (typeof input === "string") return [{ role: "user", content: input }];
633
+ if (!Array.isArray(input)) return null;
634
+
635
+ const messages: ChatMessage[] = [];
636
+ for (const item of input) {
637
+ if (typeof item === "string") {
638
+ messages.push({ role: "user", content: item });
639
+ continue;
640
+ }
641
+ if (!isRecord(item)) continue;
642
+ const role = typeof item.role === "string" ? item.role : "user";
643
+ if (!["system", "user", "assistant", "model", "tool"].includes(role))
644
+ continue;
645
+ const content =
646
+ "content" in item
647
+ ? normalizeContentBlocks(item.content)
648
+ : extractTextFromUnknownContent(item);
649
+ messages.push({ role: role as ChatMessage["role"], content });
650
+ }
651
+ return messages.length > 0 ? messages : null;
652
+ }
653
+
654
+ export function messagesFromLooseMessages(
655
+ value: unknown,
656
+ ): ChatMessage[] | null {
657
+ if (typeof value === "string") return [{ role: "user", content: value }];
658
+ if (isRecord(value)) return messagesFromResponsesInput([value]);
659
+ return null;
660
+ }
661
+
662
+ export function messagesFromAntigravityRequest(
663
+ value: Record<string, unknown>,
664
+ ): ChatMessage[] | null {
665
+ const request = isRecord(value.request) ? value.request : null;
666
+ if (!request || !Array.isArray(request.contents)) return null;
667
+ const messages: ChatMessage[] = [];
668
+ if (
669
+ isRecord(request.systemInstruction) &&
670
+ Array.isArray(request.systemInstruction.parts)
671
+ ) {
672
+ const systemText = request.systemInstruction.parts
673
+ .map((part) =>
674
+ isRecord(part) && typeof part.text === "string" ? part.text : "",
675
+ )
676
+ .filter(Boolean)
677
+ .join("\n");
678
+ if (systemText) messages.push({ role: "system", content: systemText });
679
+ }
680
+ for (const turn of request.contents) {
681
+ if (!isRecord(turn) || !Array.isArray(turn.parts)) continue;
682
+ const role =
683
+ turn.role === "model" || turn.role === "assistant" ? "assistant" : "user";
684
+ const content = turn.parts
685
+ .map((part) =>
686
+ isRecord(part) && typeof part.text === "string" ? part.text : "",
687
+ )
688
+ .filter(Boolean)
689
+ .join("\n");
690
+ messages.push({ role, content });
691
+ }
692
+ return messages.length > 0 ? messages : null;
693
+ }
694
+
695
+ export function normalizeOpenAIChatCompletionRequest(value: unknown): unknown {
696
+ if (!isRecord(value) || Array.isArray(value.messages)) return value;
697
+ const messages = (() => {
698
+ if ("messages" in value) return messagesFromLooseMessages(value.messages);
699
+ if (typeof value.prompt === "string")
700
+ return [{ role: "user", content: value.prompt }];
701
+ if (Array.isArray(value.prompt))
702
+ return (
703
+ messagesFromResponsesInput(value.prompt) ??
704
+ value.prompt.map((prompt) => ({
705
+ role: "user",
706
+ content: String(prompt),
707
+ }))
708
+ );
709
+ if ("input" in value) return messagesFromResponsesInput(value.input);
710
+ return messagesFromAntigravityRequest(value);
711
+ })();
712
+ return messages ? { ...value, messages } : value;
713
+ }
714
+
715
+ export function normalizeOpenAIResponsesRequest(value: unknown): unknown {
716
+ if (!isRecord(value)) return value;
717
+
718
+ let normalized: Record<string, unknown> = { ...value };
719
+ if (Array.isArray(value.tools)) {
720
+ const before = value.tools.length;
721
+ const filtered: unknown[] = [];
722
+ for (const t of value.tools) {
723
+ if (!isRecord(t) || typeof t.type !== "string") continue;
724
+ if (t.type !== "function") continue;
725
+
726
+ if (isNonEmptyString(t.name) && !isRecord(t.function)) {
727
+ filtered.push({
728
+ type: "function",
729
+ function: {
730
+ name: t.name,
731
+ ...(typeof t.description === "string"
732
+ ? { description: t.description }
733
+ : {}),
734
+ ...(isRecord(t.parameters) ? { parameters: t.parameters } : {}),
735
+ },
736
+ });
737
+ continue;
738
+ }
739
+
740
+ if (isRecord(t.function) && isNonEmptyString(t.function.name)) {
741
+ filtered.push(t);
742
+ }
743
+ }
744
+ const dropped = before - filtered.length;
745
+ if (dropped > 0) {
746
+ compatLogger.warn(
747
+ `Filtered ${dropped} unsupported/unnamed tool(s) from Responses request (kept ${filtered.length} function tools)`,
748
+ );
749
+ }
750
+ normalized = {
751
+ ...normalized,
752
+ tools: filtered.length > 0 ? filtered : undefined,
753
+ };
754
+ }
755
+
756
+ if ("input" in normalized) return normalized;
757
+ if ("messages" in normalized)
758
+ return { ...normalized, input: normalized.messages };
759
+ if ("prompt" in normalized)
760
+ return { ...normalized, input: normalized.prompt };
761
+ return normalized;
762
+ }
763
+
764
+ export function normalizeAnthropicMessagesRequest(value: unknown): unknown {
765
+ if (!isRecord(value) || Array.isArray(value.messages)) return value;
766
+ const messages =
767
+ "messages" in value
768
+ ? messagesFromLooseMessages(value.messages)
769
+ : "input" in value
770
+ ? messagesFromResponsesInput(value.input)
771
+ : messagesFromAntigravityRequest(value);
772
+ return messages ? { ...value, messages } : value;
773
+ }
774
+
775
+ export function convertResponsesToChatRequest(
776
+ input: OpenAIResponsesRequest,
777
+ ): ResponsesConversionResult {
778
+ const previousResponseId = input.previous_response_id ?? null;
779
+ const previous = previousResponseId
780
+ ? getStoredResponse(previousResponseId)
781
+ : null;
782
+ if (previousResponseId && !previous) {
783
+ throw new Error(`previous_response_id not found: ${previousResponseId}`);
784
+ }
785
+
786
+ const previousCallIdToName = previous
787
+ ? new Map(Object.entries(previous.callIdToName))
788
+ : new Map<string, string>();
789
+ const previousConversationMessages: ChatMessage[] = previous
790
+ ? (previous.conversationMessages as unknown as ChatMessage[])
791
+ : [];
792
+
793
+ const parsed = parseResponsesInput(input.input, previousCallIdToName);
794
+ const conversationMessages = [
795
+ ...previousConversationMessages,
796
+ ...parsed.messages,
797
+ ];
798
+ const chatMessages = [
799
+ ...(input.instructions
800
+ ? [
801
+ {
802
+ role: "system" as const,
803
+ content: normalizeInstructionsContent(input.instructions),
804
+ },
805
+ ]
806
+ : []),
807
+ ...conversationMessages,
808
+ ];
809
+
810
+ return {
811
+ chatRequest: {
812
+ model: input.model,
813
+ messages: chatMessages,
814
+ stream: input.stream,
815
+ temperature: input.temperature,
816
+ max_tokens: input.max_output_tokens,
817
+ tools: input.tools as OpenAITool[] | undefined,
818
+ tool_choice: input.tool_choice,
819
+ reasoning_effort:
820
+ typeof input.reasoning?.effort === "string"
821
+ ? input.reasoning.effort
822
+ : undefined,
823
+ parallel_tool_calls: input.parallel_tool_calls,
824
+ },
825
+ inputItems: parsed.inputItems,
826
+ conversationMessages,
827
+ previousResponseId,
828
+ };
829
+ }
830
+
831
+ export function openAIToAntigravityBody(
832
+ input: OpenAIChatCompletionRequest,
833
+ ): RequestBody {
834
+ const systemParts: string[] = [];
835
+ const conversationMessages = input.messages.filter((msg) => {
836
+ if (msg.role === "system" || msg.role === "developer") {
837
+ const text =
838
+ typeof msg.content === "string"
839
+ ? msg.content
840
+ : extractText(msg.content);
841
+ if (text) systemParts.push(text);
842
+ return false;
843
+ }
844
+ return true;
845
+ });
846
+
847
+ const isClaude = /^claude-/i.test(input.model);
848
+ const isThinking = isThinkingModel(input.model);
849
+ const isGeminiThinking = !isClaude && isThinking;
850
+
851
+ const contents: GeminiContent[] = [];
852
+ // Claude requires every tool_result to immediately follow its tool_use turn.
853
+ let pendingClaudeToolCallIds = new Set<string>();
854
+ // OpenAI tool messages often omit `name`; resolve the function name from the
855
+ // preceding assistant tool_call (matched by tool_call_id) so the upstream
856
+ // functionResponse never carries the placeholder "unknown".
857
+ const toolCallIdToFunctionName = new Map<string, string>();
858
+ for (let i = 0; i < conversationMessages.length; i++) {
859
+ const msg = conversationMessages[i];
860
+ if (msg.role === "assistant" || msg.role === "model") {
861
+ let msgToolCalls = msg.tool_calls;
862
+ if (Array.isArray(msgToolCalls) && msgToolCalls.length > 0) {
863
+ const completedToolCallIds = new Set<string>();
864
+ let j = i + 1;
865
+ while (
866
+ j < conversationMessages.length &&
867
+ conversationMessages[j].role === "tool"
868
+ ) {
869
+ const toolCallId = conversationMessages[j].tool_call_id;
870
+ if (typeof toolCallId === "string") {
871
+ completedToolCallIds.add(toolCallId);
872
+ }
873
+ j++;
874
+ }
875
+ msgToolCalls = msgToolCalls.filter(
876
+ (tc) => tc.id && completedToolCallIds.has(tc.id),
877
+ );
878
+ if (msgToolCalls.length === 0) {
879
+ msgToolCalls = undefined;
880
+ }
881
+ }
882
+
883
+ const hasMissingSig =
884
+ isGeminiThinking &&
885
+ Array.isArray(msgToolCalls) &&
886
+ msgToolCalls.length > 0 &&
887
+ !thoughtSignatureCache.has(msgToolCalls[0].id);
888
+
889
+ if (hasMissingSig) {
890
+ const toolNames = msgToolCalls!
891
+ .map((tc) => tc.function.name)
892
+ .join(", ");
893
+ const resultParts: string[] = [];
894
+ while (
895
+ i + 1 < conversationMessages.length &&
896
+ conversationMessages[i + 1].role === "tool"
897
+ ) {
898
+ i++;
899
+ const toolMsg = conversationMessages[i];
900
+ const toolText =
901
+ typeof toolMsg.content === "string"
902
+ ? toolMsg.content
903
+ : extractText(toolMsg.content);
904
+ resultParts.push(
905
+ `${toolMsg.name || "tool"}: ${toolText.slice(0, 500)}`,
906
+ );
907
+ }
908
+ const summaryText = `[Context: The assistant used tools (${toolNames}) and received results:\n${resultParts.join("\n")}]`;
909
+ contents.push({ role: "user", parts: [{ text: summaryText }] });
910
+ contents.push({
911
+ role: "model",
912
+ parts: [{ text: "Understood, I have the tool results." }],
913
+ });
914
+ continue;
915
+ }
916
+
917
+ const parts: unknown[] = [];
918
+ if (msg.content) {
919
+ const textContent =
920
+ typeof msg.content === "string"
921
+ ? msg.content
922
+ : extractText(msg.content);
923
+ if (textContent) parts.push({ text: textContent });
924
+ }
925
+ if (Array.isArray(msgToolCalls) && msgToolCalls.length > 0) {
926
+ let isFirstInMessage = true;
927
+ for (const tc of msgToolCalls) {
928
+ if (typeof tc.id === "string" && typeof tc.function?.name === "string") {
929
+ toolCallIdToFunctionName.set(tc.id, tc.function.name);
930
+ }
931
+ let args: unknown;
932
+ try {
933
+ args =
934
+ typeof tc.function.arguments === "string"
935
+ ? JSON.parse(tc.function.arguments)
936
+ : tc.function.arguments;
937
+ } catch {
938
+ args = {};
939
+ }
940
+ const cachedSig = isFirstInMessage
941
+ ? thoughtSignatureCache.get(tc.id)
942
+ : undefined;
943
+ parts.push({
944
+ ...(cachedSig ? { thoughtSignature: cachedSig } : {}),
945
+ functionCall: {
946
+ ...(isClaude ? { id: tc.id } : {}),
947
+ name: tc.function.name,
948
+ args,
949
+ },
950
+ });
951
+ isFirstInMessage = false;
952
+ }
953
+ }
954
+ if (parts.length === 0) {
955
+ parts.push({ text: "..." });
956
+ }
957
+ if (parts.length > 0) {
958
+ const functionCallIds = new Set<string>();
959
+ for (const part of parts) {
960
+ if (!isRecord(part)) continue;
961
+ const functionCall = part.functionCall;
962
+ if (
963
+ isRecord(functionCall) &&
964
+ typeof functionCall.id === "string" &&
965
+ functionCall.id
966
+ ) {
967
+ functionCallIds.add(functionCall.id);
968
+ }
969
+ }
970
+ const hasFunctionCall = parts.some((p: any) => p.functionCall);
971
+ if (isClaude) {
972
+ const lastContent = contents[contents.length - 1];
973
+ const prevHasFunctionCall =
974
+ lastContent &&
975
+ lastContent.role === "model" &&
976
+ lastContent.parts.some((p: any) => p.functionCall);
977
+ if (prevHasFunctionCall && !hasFunctionCall) {
978
+ // Skip
979
+ } else if (hasFunctionCall) {
980
+ const fcOnly = parts.filter((p: any) => p.functionCall);
981
+ if (prevHasFunctionCall) {
982
+ lastContent.parts.push(...fcOnly);
983
+ for (const id of functionCallIds) pendingClaudeToolCallIds.add(id);
984
+ } else {
985
+ contents.push({ role: "model", parts: fcOnly });
986
+ pendingClaudeToolCallIds = new Set(functionCallIds);
987
+ }
988
+ } else {
989
+ contents.push({ role: "model", parts });
990
+ pendingClaudeToolCallIds.clear();
991
+ }
992
+ } else {
993
+ contents.push({ role: "model", parts });
994
+ }
995
+ }
996
+ } else if (msg.role === "tool") {
997
+ const responseText =
998
+ typeof msg.content === "string"
999
+ ? msg.content
1000
+ : extractText(msg.content);
1001
+ const toolCallId = msg.tool_call_id;
1002
+ const fnName =
1003
+ msg.name ||
1004
+ (typeof toolCallId === "string"
1005
+ ? toolCallIdToFunctionName.get(toolCallId)
1006
+ : undefined) ||
1007
+ "unknown";
1008
+ if (
1009
+ isClaude &&
1010
+ (!toolCallId || !pendingClaudeToolCallIds.has(toolCallId))
1011
+ ) {
1012
+ continue;
1013
+ }
1014
+ let responseData: unknown;
1015
+ try {
1016
+ const parsed = JSON.parse(responseText);
1017
+ responseData =
1018
+ parsed !== null &&
1019
+ typeof parsed === "object" &&
1020
+ !Array.isArray(parsed)
1021
+ ? parsed
1022
+ : { output: parsed };
1023
+ } catch {
1024
+ responseData = { output: responseText };
1025
+ }
1026
+ const toolImages: AntigravityPart[] = [];
1027
+ if (msg.content && Array.isArray(msg.content)) {
1028
+ for (const part of msg.content) {
1029
+ if (
1030
+ part.type === "image_url" &&
1031
+ isRecord(part.image_url) &&
1032
+ typeof part.image_url.url === "string"
1033
+ ) {
1034
+ const inlineData = dataUrlToInlineData(part.image_url.url);
1035
+ if (inlineData) toolImages.push(inlineData);
1036
+ } else if (
1037
+ part.type === "image" &&
1038
+ isRecord(part.source) &&
1039
+ typeof part.source.data === "string"
1040
+ ) {
1041
+ const mediaType =
1042
+ typeof part.source.media_type === "string"
1043
+ ? part.source.media_type
1044
+ : "image/png";
1045
+ toolImages.push({
1046
+ inlineData: { mimeType: mediaType, data: part.source.data },
1047
+ });
1048
+ }
1049
+ }
1050
+ }
1051
+
1052
+ const fnResponsePart = {
1053
+ functionResponse: {
1054
+ ...(isClaude && toolCallId ? { id: toolCallId } : {}),
1055
+ name: fnName,
1056
+ response: responseData,
1057
+ },
1058
+ };
1059
+ const lastContent = contents[contents.length - 1];
1060
+ if (
1061
+ lastContent &&
1062
+ lastContent.role === "user" &&
1063
+ Array.isArray(lastContent.parts) &&
1064
+ lastContent.parts.length > 0 &&
1065
+ isRecord(lastContent.parts[0] as any) &&
1066
+ (lastContent.parts[0] as any).functionResponse !== undefined
1067
+ ) {
1068
+ const firstNonFnIdx = lastContent.parts.findIndex(
1069
+ (p: any) => !isRecord(p) || p.functionResponse === undefined,
1070
+ );
1071
+ if (firstNonFnIdx === -1) {
1072
+ lastContent.parts.push(fnResponsePart);
1073
+ } else {
1074
+ lastContent.parts.splice(firstNonFnIdx, 0, fnResponsePart);
1075
+ }
1076
+ if (toolImages.length > 0) {
1077
+ lastContent.parts.push(...toolImages);
1078
+ }
1079
+ } else {
1080
+ contents.push({ role: "user", parts: [fnResponsePart, ...toolImages] });
1081
+ }
1082
+ if (isClaude && toolCallId) pendingClaudeToolCallIds.delete(toolCallId);
1083
+ } else {
1084
+ const msgParts = extractParts(msg.content);
1085
+ if (msgParts.length > 0) {
1086
+ if (isClaude) pendingClaudeToolCallIds.clear();
1087
+ contents.push({ role: "user", parts: msgParts });
1088
+ }
1089
+ }
1090
+ }
1091
+
1092
+ if (isClaude) {
1093
+ while (contents.at(-1)?.role === "model") {
1094
+ const lastContent = contents.at(-1);
1095
+ const hasFunctionCall =
1096
+ lastContent?.parts.some((p: any) => isRecord(p) && p.functionCall) ??
1097
+ false;
1098
+ if (hasFunctionCall) {
1099
+ contents.pop();
1100
+ continue;
1101
+ }
1102
+ contents.push({
1103
+ role: "user",
1104
+ parts: [
1105
+ {
1106
+ text: "Continue from the previous assistant message. Do not repeat completed tool calls unless new user input asks for them.",
1107
+ },
1108
+ ],
1109
+ });
1110
+ break;
1111
+ }
1112
+ }
1113
+
1114
+ if (contents.length === 0)
1115
+ contents.push({ role: "user", parts: [{ text: "Hello" }] });
1116
+
1117
+ const inputTools = Array.isArray(input.tools)
1118
+ ? (input.tools as OpenAITool[])
1119
+ : [];
1120
+ const geminiTools = convertOpenAIToolsToGemini(inputTools, isClaude);
1121
+ const geminiToolConfig =
1122
+ input.tool_choice !== undefined
1123
+ ? convertToolChoiceToGemini(input.tool_choice)
1124
+ : undefined;
1125
+
1126
+ const modelSpec = getModelSpec(input.model);
1127
+ const modelFamily = getModelFamily(input.model);
1128
+ let maxOutputTokens =
1129
+ typeof input.max_tokens === "number" ? input.max_tokens : undefined;
1130
+ if (maxOutputTokens && maxOutputTokens > modelSpec.maxOutputTokens) {
1131
+ compatLogger.debug(
1132
+ `Capping ${input.model} maxOutputTokens ${maxOutputTokens} → ${modelSpec.maxOutputTokens}`,
1133
+ );
1134
+ maxOutputTokens = modelSpec.maxOutputTokens;
1135
+ }
1136
+
1137
+ let thinkingConfigObj: Record<string, unknown> | undefined;
1138
+ if (modelFamily === "claude" && isThinking) {
1139
+ const tb = modelSpec.thinkingBudget;
1140
+ thinkingConfigObj = { include_thoughts: true, thinking_budget: tb };
1141
+ if (!maxOutputTokens || maxOutputTokens <= tb) {
1142
+ maxOutputTokens = Math.min(tb + 8192, modelSpec.maxOutputTokens);
1143
+ compatLogger.debug(
1144
+ `Adjusted Claude maxOutputTokens → ${maxOutputTokens}`,
1145
+ );
1146
+ }
1147
+ } else if (isThinking) {
1148
+ const tb = modelSpec.thinkingBudget;
1149
+ thinkingConfigObj =
1150
+ tb === -1
1151
+ ? { includeThoughts: true }
1152
+ : { includeThoughts: true, thinkingBudget: tb };
1153
+ if (tb !== -1 && (!maxOutputTokens || maxOutputTokens <= tb)) {
1154
+ maxOutputTokens = Math.min(tb + 8192, modelSpec.maxOutputTokens);
1155
+ compatLogger.debug(
1156
+ `Adjusted Gemini maxOutputTokens → ${maxOutputTokens}`,
1157
+ );
1158
+ }
1159
+ } else if (input.reasoning_effort) {
1160
+ const budgets: Record<string, number> = {
1161
+ low: Math.round(modelSpec.thinkingBudget / 4),
1162
+ medium: Math.round(modelSpec.thinkingBudget / 2),
1163
+ high: modelSpec.thinkingBudget,
1164
+ };
1165
+ const b = budgets[input.reasoning_effort.toLowerCase()];
1166
+ if (b) thinkingConfigObj = { includeThoughts: true, thinkingBudget: b };
1167
+ }
1168
+
1169
+ const generationConfig: Record<string, unknown> = {
1170
+ ...(typeof input.temperature === "number"
1171
+ ? { temperature: input.temperature }
1172
+ : {}),
1173
+ ...(maxOutputTokens ? { maxOutputTokens } : {}),
1174
+ ...(thinkingConfigObj ? { thinkingConfig: thinkingConfigObj } : {}),
1175
+ };
1176
+
1177
+ const request: Record<string, unknown> = {
1178
+ contents,
1179
+ generationConfig,
1180
+ };
1181
+
1182
+ if (systemParts.length > 0) {
1183
+ if (!isClaude && isThinking) {
1184
+ const firstTurn = contents[0];
1185
+ if (
1186
+ firstTurn &&
1187
+ firstTurn.role === "user" &&
1188
+ (firstTurn.parts[0] as any)?.text !== undefined
1189
+ ) {
1190
+ (firstTurn.parts[0] as any).text =
1191
+ systemParts.join("\n\n") + "\n\n" + (firstTurn.parts[0] as any).text;
1192
+ } else if (firstTurn && firstTurn.role === "user") {
1193
+ firstTurn.parts.unshift({ text: systemParts.join("\n\n") + "\n\n" });
1194
+ } else {
1195
+ contents.unshift({
1196
+ role: "user",
1197
+ parts: [{ text: systemParts.join("\n\n") }],
1198
+ });
1199
+ }
1200
+ } else {
1201
+ request.systemInstruction = {
1202
+ role: "system",
1203
+ parts: [{ text: systemParts.join("\n\n") }],
1204
+ };
1205
+ }
1206
+ }
1207
+
1208
+ if (geminiTools.length > 0) request.tools = geminiTools;
1209
+ if (geminiToolConfig) request.toolConfig = geminiToolConfig;
1210
+
1211
+ const mappedModel = applyModelAlias(input.model);
1212
+
1213
+ return {
1214
+ project: "compat-placeholder",
1215
+ model: mappedModel,
1216
+ displayModel: input.model,
1217
+ userAgent: "antigravity",
1218
+ requestType: "agent",
1219
+ request,
1220
+ };
1221
+ }
1222
+
1223
+ export function convertAnthropicToolsToOpenAI(
1224
+ tools: unknown,
1225
+ ): OpenAITool[] | undefined {
1226
+ if (!Array.isArray(tools) || tools.length === 0) return undefined;
1227
+ const result: OpenAITool[] = [];
1228
+ for (const t of tools) {
1229
+ if (!isRecord(t) || !isNonEmptyString(t.name)) continue;
1230
+ result.push({
1231
+ type: "function",
1232
+ function: {
1233
+ name: t.name as string,
1234
+ ...(typeof t.description === "string"
1235
+ ? { description: t.description }
1236
+ : {}),
1237
+ ...(isRecord(t.input_schema)
1238
+ ? { parameters: t.input_schema as Record<string, unknown> }
1239
+ : {}),
1240
+ },
1241
+ });
1242
+ }
1243
+ return result.length > 0 ? result : undefined;
1244
+ }
1245
+
1246
+ export function convertAnthropicToolChoice(toolChoice: unknown): unknown {
1247
+ if (!isRecord(toolChoice)) return toolChoice;
1248
+ if (toolChoice.type === "auto") return "auto";
1249
+ if (toolChoice.type === "any") return "required";
1250
+ if (toolChoice.type === "tool" && isNonEmptyString(toolChoice.name)) {
1251
+ return { type: "function", function: { name: toolChoice.name } };
1252
+ }
1253
+ return "auto";
1254
+ }
1255
+
1256
+ export function convertAnthropicMessagesToOpenAI(
1257
+ messages: ChatMessage[],
1258
+ ): ChatMessage[] {
1259
+ const result: ChatMessage[] = [];
1260
+ for (const msg of messages) {
1261
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
1262
+ const blocks = msg.content as Array<Record<string, unknown>>;
1263
+ const toolUseBlocks = blocks.filter(
1264
+ (b) => isRecord(b) && b.type === "tool_use" && isNonEmptyString(b.name),
1265
+ );
1266
+ if (toolUseBlocks.length > 0) {
1267
+ const textParts = blocks
1268
+ .filter(
1269
+ (b) =>
1270
+ isRecord(b) && b.type === "text" && typeof b.text === "string",
1271
+ )
1272
+ .map((b) => b.text as string)
1273
+ .join("");
1274
+ const toolCalls: OpenAIToolCall[] = toolUseBlocks.map((b) => ({
1275
+ id: (b.id as string) || `call_${Date.now().toString(36)}`,
1276
+ type: "function" as const,
1277
+ function: {
1278
+ name: b.name as string,
1279
+ arguments:
1280
+ typeof b.input === "string"
1281
+ ? b.input
1282
+ : JSON.stringify(b.input ?? {}),
1283
+ },
1284
+ }));
1285
+ result.push({
1286
+ role: "assistant",
1287
+ content: textParts || null,
1288
+ tool_calls: toolCalls,
1289
+ });
1290
+ continue;
1291
+ }
1292
+ }
1293
+ if (msg.role === "user" && Array.isArray(msg.content)) {
1294
+ const blocks = msg.content as Array<Record<string, unknown>>;
1295
+ const toolResults = blocks.filter(
1296
+ (b) => isRecord(b) && b.type === "tool_result",
1297
+ );
1298
+ if (toolResults.length > 0) {
1299
+ const otherBlocks = blocks.filter(
1300
+ (b) => !isRecord(b) || b.type !== "tool_result",
1301
+ );
1302
+ for (const tr of toolResults) {
1303
+ const content =
1304
+ typeof tr.content === "string"
1305
+ ? tr.content
1306
+ : Array.isArray(tr.content)
1307
+ ? extractTextFromUnknownContent(tr.content)
1308
+ : JSON.stringify(tr.content ?? "");
1309
+ result.push({
1310
+ role: "tool",
1311
+ content,
1312
+ tool_call_id: tr.tool_use_id as string,
1313
+ });
1314
+ }
1315
+ if (otherBlocks.length > 0) {
1316
+ result.push({
1317
+ role: "user",
1318
+ content: otherBlocks as ChatMessage["content"],
1319
+ });
1320
+ }
1321
+ continue;
1322
+ }
1323
+ }
1324
+ result.push(msg);
1325
+ }
1326
+ return result;
1327
+ }
1328
+
1329
+ export function anthropicToAntigravityBody(
1330
+ input: AnthropicMessagesRequest,
1331
+ ): RequestBody {
1332
+ const systemText =
1333
+ typeof input.system === "string"
1334
+ ? input.system
1335
+ : Array.isArray(input.system)
1336
+ ? extractText(input.system as ChatMessage["content"])
1337
+ : "";
1338
+ const tools = convertAnthropicToolsToOpenAI(input.tools);
1339
+ const toolChoice = convertAnthropicToolChoice(input.tool_choice);
1340
+ const convertedMessages = convertAnthropicMessagesToOpenAI(input.messages);
1341
+ return openAIToAntigravityBody({
1342
+ model: input.model,
1343
+ stream: input.stream,
1344
+ temperature: input.temperature,
1345
+ max_tokens: input.max_tokens,
1346
+ tools,
1347
+ tool_choice: toolChoice,
1348
+ messages: [
1349
+ ...(systemText ? [{ role: "system" as const, content: systemText }] : []),
1350
+ ...convertedMessages,
1351
+ ],
1352
+ });
1353
+ }
1354
+
1355
+ export function mapReasoningEffortToThinkingLevel(
1356
+ effort: string | undefined,
1357
+ modelId: string,
1358
+ ): number | undefined {
1359
+ const lowerModel = modelId.toLowerCase();
1360
+ const isGemini31Pro = /gemini-3\.1-pro/i.test(modelId);
1361
+ const isGemini3Flash =
1362
+ lowerModel.includes("gemini-3-flash") ||
1363
+ lowerModel.includes("gemini-3.5-flash");
1364
+
1365
+ let effectiveEffort = effort;
1366
+ if (!effectiveEffort) {
1367
+ if (lowerModel.endsWith("-high") || lowerModel.includes("gemini-pro-agent"))
1368
+ effectiveEffort = "high";
1369
+ else if (lowerModel.endsWith("-low")) effectiveEffort = "low";
1370
+ else if (isGemini3Flash) effectiveEffort = "high";
1371
+ }
1372
+
1373
+ if (!effectiveEffort) return undefined;
1374
+
1375
+ if (isGemini31Pro) {
1376
+ switch (effectiveEffort.toLowerCase()) {
1377
+ case "high":
1378
+ return 10001;
1379
+ case "medium":
1380
+ return 5000;
1381
+ case "low":
1382
+ return 1001;
1383
+ default:
1384
+ return undefined;
1385
+ }
1386
+ }
1387
+
1388
+ if (isGemini3Flash) {
1389
+ switch (effectiveEffort.toLowerCase()) {
1390
+ case "high":
1391
+ return -1;
1392
+ case "medium":
1393
+ return 4096;
1394
+ case "low":
1395
+ return 1024;
1396
+ default:
1397
+ return undefined;
1398
+ }
1399
+ }
1400
+
1401
+ return undefined;
1402
+ }
1403
+
1404
+ export function validateOpenAIChatCompletionRequest(
1405
+ value: unknown,
1406
+ ):
1407
+ | { ok: true; value: OpenAIChatCompletionRequest }
1408
+ | { ok: false; errors: string[] } {
1409
+ if (!isRecord(value))
1410
+ return { ok: false, errors: ["body must be a JSON object"] };
1411
+ const errors: string[] = [];
1412
+ if (!isNonEmptyString(value.model))
1413
+ errors.push("body.model must be a non-empty string");
1414
+ if (!validateMessages(value.messages)) {
1415
+ logValidationFailure("OpenAI messages validation failed", value.messages);
1416
+ errors.push("body.messages must be an array of chat messages");
1417
+ }
1418
+ if (value.stream !== undefined && typeof value.stream !== "boolean")
1419
+ errors.push("body.stream must be boolean when provided");
1420
+ if (value.temperature !== undefined && typeof value.temperature !== "number")
1421
+ errors.push("body.temperature must be number when provided");
1422
+ if (value.max_tokens !== undefined && typeof value.max_tokens !== "number")
1423
+ errors.push("body.max_tokens must be number when provided");
1424
+ return errors.length > 0
1425
+ ? { ok: false, errors }
1426
+ : { ok: true, value: value as unknown as OpenAIChatCompletionRequest };
1427
+ }
1428
+
1429
+ function validateResponsesTools(value: unknown): string[] {
1430
+ if (value === undefined) return [];
1431
+ if (!Array.isArray(value))
1432
+ return ["body.tools must be an array when provided"];
1433
+ const errors: string[] = [];
1434
+ for (const tool of value) {
1435
+ if (!isRecord(tool)) {
1436
+ errors.push("each tool must be an object");
1437
+ continue;
1438
+ }
1439
+ if (tool.type !== "function") {
1440
+ errors.push(`only function tools are supported (got: ${tool.type})`);
1441
+ }
1442
+ }
1443
+ return errors;
1444
+ }
1445
+
1446
+ export function validateOpenAIResponsesRequest(
1447
+ value: unknown,
1448
+ ):
1449
+ | { ok: true; value: OpenAIResponsesRequest }
1450
+ | { ok: false; errors: string[] } {
1451
+ if (!isRecord(value))
1452
+ return { ok: false, errors: ["body must be a JSON object"] };
1453
+ const errors: string[] = [];
1454
+ if (!isNonEmptyString(value.model))
1455
+ errors.push("body.model must be a non-empty string");
1456
+ if (value.stream !== undefined && typeof value.stream !== "boolean")
1457
+ errors.push("body.stream must be boolean when provided");
1458
+ if (value.temperature !== undefined && typeof value.temperature !== "number")
1459
+ errors.push("body.temperature must be number when provided");
1460
+ if (
1461
+ value.max_output_tokens !== undefined &&
1462
+ typeof value.max_output_tokens !== "number"
1463
+ )
1464
+ errors.push("body.max_output_tokens must be number when provided");
1465
+ if (value.store !== undefined && typeof value.store !== "boolean")
1466
+ errors.push("body.store must be boolean when provided");
1467
+ if (
1468
+ value.previous_response_id !== undefined &&
1469
+ value.previous_response_id !== null &&
1470
+ !isNonEmptyString(value.previous_response_id)
1471
+ ) {
1472
+ errors.push("body.previous_response_id must be a non-empty string or null");
1473
+ }
1474
+ if (value.conversation !== undefined && value.conversation !== null) {
1475
+ errors.push(
1476
+ "body.conversation is not supported; use previous_response_id instead",
1477
+ );
1478
+ }
1479
+ if (value.metadata !== undefined && !isRecord(value.metadata))
1480
+ errors.push("body.metadata must be an object when provided");
1481
+ if (
1482
+ value.reasoning !== undefined &&
1483
+ value.reasoning !== null &&
1484
+ !isRecord(value.reasoning)
1485
+ ) {
1486
+ errors.push("body.reasoning must be an object when provided");
1487
+ } else if (
1488
+ isRecord(value.reasoning) &&
1489
+ value.reasoning.effort !== undefined &&
1490
+ value.reasoning.effort !== null &&
1491
+ typeof value.reasoning.effort !== "string"
1492
+ ) {
1493
+ errors.push("body.reasoning.effort must be a string when provided");
1494
+ }
1495
+ if (
1496
+ value.instructions !== undefined &&
1497
+ value.instructions !== null &&
1498
+ typeof value.instructions !== "string" &&
1499
+ !Array.isArray(value.instructions)
1500
+ ) {
1501
+ errors.push(
1502
+ "body.instructions must be a string or content array when provided",
1503
+ );
1504
+ }
1505
+ errors.push(...validateResponsesTools(value.tools));
1506
+ return errors.length > 0
1507
+ ? { ok: false, errors }
1508
+ : { ok: true, value: value as unknown as OpenAIResponsesRequest };
1509
+ }
1510
+
1511
+ export function validateAnthropicMessagesRequest(
1512
+ value: unknown,
1513
+ ):
1514
+ | { ok: true; value: AnthropicMessagesRequest }
1515
+ | { ok: false; errors: string[] } {
1516
+ if (!isRecord(value))
1517
+ return { ok: false, errors: ["body must be a JSON object"] };
1518
+ const errors: string[] = [];
1519
+ if (!isNonEmptyString(value.model))
1520
+ errors.push("body.model must be a non-empty string");
1521
+ if (!validateMessages(value.messages))
1522
+ errors.push("body.messages must be an array of chat messages");
1523
+ if (
1524
+ value.system !== undefined &&
1525
+ typeof value.system !== "string" &&
1526
+ !Array.isArray(value.system)
1527
+ )
1528
+ errors.push("body.system must be string or content array when provided");
1529
+ if (value.stream !== undefined && typeof value.stream !== "boolean")
1530
+ errors.push("body.stream must be boolean when provided");
1531
+ if (value.temperature !== undefined && typeof value.temperature !== "number")
1532
+ errors.push("body.temperature must be number when provided");
1533
+ if (value.max_tokens !== undefined && typeof value.max_tokens !== "number")
1534
+ errors.push("body.max_tokens must be number when provided");
1535
+ return errors.length > 0
1536
+ ? { ok: false, errors }
1537
+ : { ok: true, value: value as unknown as AnthropicMessagesRequest };
1538
+ }
1539
+
1540
+ export function responseUsageFromCompletion(
1541
+ completion: CompatCompletion,
1542
+ ): Record<string, unknown> {
1543
+ return {
1544
+ input_tokens: completion.inputTokens,
1545
+ input_tokens_details: { cached_tokens: 0 },
1546
+ output_tokens: completion.outputTokens,
1547
+ output_tokens_details: { reasoning_tokens: 0 },
1548
+ total_tokens: completion.inputTokens + completion.outputTokens,
1549
+ };
1550
+ }
1551
+
1552
+ export function buildResponsesOutput(completion: CompatCompletion): {
1553
+ output: ResponseOutputItem[];
1554
+ outputText: string;
1555
+ callIdToName: Map<string, string>;
1556
+ } {
1557
+ const output: ResponseOutputItem[] = [];
1558
+ const callIdToName = new Map<string, string>();
1559
+ if (completion.thinkingText) {
1560
+ output.push({
1561
+ id: makeCompatId("rs"),
1562
+ type: "reasoning",
1563
+ status: "completed",
1564
+ summary: [{ type: "summary_text", text: completion.thinkingText }],
1565
+ } as unknown as ResponseOutputItem);
1566
+ }
1567
+ if (completion.text) {
1568
+ output.push({
1569
+ id: makeCompatId("msg"),
1570
+ type: "message",
1571
+ status: "completed",
1572
+ role: "assistant",
1573
+ content: [
1574
+ { type: "output_text", text: completion.text, annotations: [] },
1575
+ ],
1576
+ });
1577
+ }
1578
+ for (const toolCall of completion.toolCalls ?? []) {
1579
+ callIdToName.set(toolCall.id, toolCall.function.name);
1580
+ output.push({
1581
+ id: makeCompatId("fc"),
1582
+ type: "function_call",
1583
+ call_id: toolCall.id,
1584
+ name: toolCall.function.name,
1585
+ arguments: toolArgumentsToString(toolCall.function.arguments),
1586
+ status: "completed",
1587
+ });
1588
+ }
1589
+ return { output, outputText: completion.text, callIdToName };
1590
+ }
1591
+
1592
+ export function buildAssistantMessageFromCompletion(
1593
+ completion: CompatCompletion,
1594
+ ): ChatMessage {
1595
+ return completion.toolCalls && completion.toolCalls.length > 0
1596
+ ? {
1597
+ role: "assistant",
1598
+ content: completion.text || null,
1599
+ tool_calls: completion.toolCalls,
1600
+ }
1601
+ : { role: "assistant", content: completion.text };
1602
+ }
1603
+
1604
+ export function buildResponsesResponse(
1605
+ request: OpenAIResponsesRequest,
1606
+ responseId: string,
1607
+ createdAt: number,
1608
+ completion: CompatCompletion,
1609
+ status: "in_progress" | "completed" | "cancelled",
1610
+ previousResponseId: string | null,
1611
+ ): Record<string, unknown> {
1612
+ const { output, outputText } = buildResponsesOutput(completion);
1613
+ return {
1614
+ id: responseId,
1615
+ object: "response",
1616
+ created_at: createdAt,
1617
+ status,
1618
+ error: null,
1619
+ incomplete_details: null,
1620
+ instructions: request.instructions ?? null,
1621
+ max_output_tokens: request.max_output_tokens ?? null,
1622
+ model: request.model,
1623
+ output,
1624
+ output_text: outputText,
1625
+ parallel_tool_calls: request.parallel_tool_calls ?? true,
1626
+ previous_response_id: previousResponseId,
1627
+ reasoning: { effort: request.reasoning?.effort ?? null },
1628
+ store: request.store !== false,
1629
+ temperature: request.temperature ?? null,
1630
+ text: { format: { type: "text" } },
1631
+ tool_choice: request.tool_choice ?? "auto",
1632
+ tools: Array.isArray(request.tools) ? request.tools : [],
1633
+ top_p: null,
1634
+ truncation: "disabled",
1635
+ usage: responseUsageFromCompletion(completion),
1636
+ metadata: isRecord(request.metadata) ? request.metadata : {},
1637
+ };
1638
+ }
1639
+
1640
+ export function saveResponsesEntry(
1641
+ response: Record<string, unknown>,
1642
+ inputItems: Array<Record<string, unknown>>,
1643
+ conversationMessages: ChatMessage[],
1644
+ completion: CompatCompletion,
1645
+ ): void {
1646
+ const responseId = typeof response.id === "string" ? response.id : null;
1647
+ if (!responseId) return;
1648
+ const { callIdToName } = buildResponsesOutput(completion);
1649
+ const mergedConversation = [
1650
+ ...conversationMessages,
1651
+ buildAssistantMessageFromCompletion(completion),
1652
+ ];
1653
+ const expiresAt = Date.now() + 6 * 60 * 60 * 1000;
1654
+ setStoredResponse(responseId, {
1655
+ response,
1656
+ inputItems,
1657
+ conversationMessages: mergedConversation as unknown as Array<
1658
+ Record<string, unknown>
1659
+ >,
1660
+ callIdToName: Object.fromEntries(callIdToName),
1661
+ expiresAt,
1662
+ });
1663
+ }