forked from NoeFabris/opencode-antigravity-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.ts
More file actions
1592 lines (1373 loc) · 58.2 KB
/
Copy pathrequest.ts
File metadata and controls
1592 lines (1373 loc) · 58.2 KB
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import crypto from "node:crypto";
import {
ANTIGRAVITY_HEADERS,
GEMINI_CLI_HEADERS,
ANTIGRAVITY_ENDPOINT,
GEMINI_CLI_ENDPOINT,
EMPTY_SCHEMA_PLACEHOLDER_NAME,
EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,
type HeaderStyle,
} from "../constants";
import { cacheSignature, getCachedSignature } from "./cache";
import {
createStreamingTransformer,
transformSseLine,
transformStreamingPayload,
} from "./core/streaming";
import { defaultSignatureStore } from "./stores/signature-store";
import {
DEBUG_MESSAGE_PREFIX,
isDebugEnabled,
logAntigravityDebugResponse,
type AntigravityDebugContext,
} from "./debug";
import { createLogger } from "./logger";
import {
cleanJSONSchemaForAntigravity,
DEFAULT_THINKING_BUDGET,
deepFilterThinkingBlocks,
extractThinkingConfig,
extractUsageFromSsePayload,
extractUsageMetadata,
fixToolResponseGrouping,
validateAndFixClaudeToolPairing,
applyToolPairingFixes,
injectParameterSignatures,
injectToolHardeningInstruction,
isThinkingCapableModel,
normalizeThinkingConfig,
parseAntigravityApiBody,
resolveThinkingConfig,
rewriteAntigravityPreviewAccessError,
transformThinkingParts,
type AntigravityApiBody,
} from "./request-helpers";
import {
CLAUDE_TOOL_SYSTEM_INSTRUCTION,
CLAUDE_DESCRIPTION_PROMPT,
} from "../constants";
import {
analyzeConversationState,
closeToolLoopForThinking,
needsThinkingRecovery,
} from "./thinking-recovery";
import { sanitizeCrossModelPayloadInPlace } from "./transform/cross-model-sanitizer";
import {
resolveModelWithTier,
isClaudeModel,
isClaudeThinkingModel,
CLAUDE_THINKING_MAX_OUTPUT_TOKENS,
} from "./transform";
import { detectErrorType } from "./recovery";
const log = createLogger("request");
const PLUGIN_SESSION_ID = `-${crypto.randomUUID()}`;
const MIN_SIGNATURE_LENGTH = 50;
function buildSignatureSessionKey(
sessionId: string,
model?: string,
conversationKey?: string,
projectKey?: string,
): string {
const modelKey = typeof model === "string" && model.trim() ? model.toLowerCase() : "unknown";
const projectPart = typeof projectKey === "string" && projectKey.trim()
? projectKey.trim()
: "default";
const conversationPart = typeof conversationKey === "string" && conversationKey.trim()
? conversationKey.trim()
: "default";
return `${sessionId}:${modelKey}:${projectPart}:${conversationPart}`;
}
function shouldCacheThinkingSignatures(model?: string): boolean {
if (typeof model !== "string") return false;
const lower = model.toLowerCase();
// Both Claude and Gemini 3 models require thought signature caching
// for multi-turn conversations with function calling
return lower.includes("claude") || lower.includes("gemini-3");
}
function hashConversationSeed(seed: string): string {
return crypto.createHash("sha256").update(seed, "utf8").digest("hex").slice(0, 16);
}
function extractTextFromContent(content: unknown): string {
if (typeof content === "string") {
return content;
}
if (!Array.isArray(content)) {
return "";
}
for (const block of content) {
if (!block || typeof block !== "object") {
continue;
}
const anyBlock = block as any;
if (typeof anyBlock.text === "string") {
return anyBlock.text;
}
if (anyBlock.text && typeof anyBlock.text === "object" && typeof anyBlock.text.text === "string") {
return anyBlock.text.text;
}
}
return "";
}
function extractConversationSeedFromMessages(messages: any[]): string {
const system = messages.find((message) => message?.role === "system");
const users = messages.filter((message) => message?.role === "user");
const firstUser = users[0];
const lastUser = users.length > 0 ? users[users.length - 1] : undefined;
const systemText = system ? extractTextFromContent(system.content) : "";
const userText = firstUser ? extractTextFromContent(firstUser.content) : "";
const fallbackUserText = !userText && lastUser ? extractTextFromContent(lastUser.content) : "";
return [systemText, userText || fallbackUserText].filter(Boolean).join("|");
}
function extractConversationSeedFromContents(contents: any[]): string {
const users = contents.filter((content) => content?.role === "user");
const firstUser = users[0];
const lastUser = users.length > 0 ? users[users.length - 1] : undefined;
const primaryUser = firstUser && Array.isArray(firstUser.parts) ? extractTextFromContent(firstUser.parts) : "";
if (primaryUser) {
return primaryUser;
}
if (lastUser && Array.isArray(lastUser.parts)) {
return extractTextFromContent(lastUser.parts);
}
return "";
}
function resolveConversationKey(requestPayload: Record<string, unknown>): string | undefined {
const anyPayload = requestPayload as any;
const candidates = [
anyPayload.conversationId,
anyPayload.conversation_id,
anyPayload.thread_id,
anyPayload.threadId,
anyPayload.chat_id,
anyPayload.chatId,
anyPayload.sessionId,
anyPayload.session_id,
anyPayload.metadata?.conversation_id,
anyPayload.metadata?.conversationId,
anyPayload.metadata?.thread_id,
anyPayload.metadata?.threadId,
];
for (const candidate of candidates) {
if (typeof candidate === "string" && candidate.trim()) {
return candidate.trim();
}
}
const systemSeed = extractTextFromContent(
(anyPayload.systemInstruction as any)?.parts
?? anyPayload.systemInstruction
?? anyPayload.system
?? anyPayload.system_instruction,
);
const messageSeed = Array.isArray(anyPayload.messages)
? extractConversationSeedFromMessages(anyPayload.messages)
: Array.isArray(anyPayload.contents)
? extractConversationSeedFromContents(anyPayload.contents)
: "";
const seed = [systemSeed, messageSeed].filter(Boolean).join("|");
if (!seed) {
return undefined;
}
return `seed-${hashConversationSeed(seed)}`;
}
function resolveConversationKeyFromRequests(requestObjects: Array<Record<string, unknown>>): string | undefined {
for (const req of requestObjects) {
const key = resolveConversationKey(req);
if (key) {
return key;
}
}
return undefined;
}
function resolveProjectKey(candidate?: unknown, fallback?: string): string | undefined {
if (typeof candidate === "string" && candidate.trim()) {
return candidate.trim();
}
if (typeof fallback === "string" && fallback.trim()) {
return fallback.trim();
}
return undefined;
}
function formatDebugLinesForThinking(lines: string[]): string {
const cleaned = lines
.map((line) => line.trim())
.filter((line) => line.length > 0)
.slice(-50);
return `${DEBUG_MESSAGE_PREFIX}\n${cleaned.map((line) => `- ${line}`).join("\n")}`;
}
function injectDebugThinking(response: unknown, debugText: string): unknown {
if (!response || typeof response !== "object") {
return response;
}
const resp = response as any;
if (Array.isArray(resp.candidates) && resp.candidates.length > 0) {
const candidates = resp.candidates.slice();
const first = candidates[0];
if (
first &&
typeof first === "object" &&
first.content &&
typeof first.content === "object" &&
Array.isArray(first.content.parts)
) {
const parts = [{ thought: true, text: debugText }, ...first.content.parts];
candidates[0] = { ...first, content: { ...first.content, parts } };
return { ...resp, candidates };
}
return resp;
}
if (Array.isArray(resp.content)) {
const content = [{ type: "thinking", thinking: debugText }, ...resp.content];
return { ...resp, content };
}
if (!resp.reasoning_content) {
return { ...resp, reasoning_content: debugText };
}
return resp;
}
function stripInjectedDebugFromParts(parts: unknown): unknown {
if (!Array.isArray(parts)) {
return parts;
}
return parts.filter((part) => {
if (!part || typeof part !== "object") {
return true;
}
const record = part as any;
const text =
typeof record.text === "string"
? record.text
: typeof record.thinking === "string"
? record.thinking
: undefined;
if (text && text.startsWith(DEBUG_MESSAGE_PREFIX)) {
return false;
}
return true;
});
}
function stripInjectedDebugFromRequestPayload(payload: Record<string, unknown>): void {
const anyPayload = payload as any;
if (Array.isArray(anyPayload.contents)) {
anyPayload.contents = anyPayload.contents.map((content: any) => {
if (!content || typeof content !== "object") {
return content;
}
if (Array.isArray(content.parts)) {
return { ...content, parts: stripInjectedDebugFromParts(content.parts) };
}
if (Array.isArray(content.content)) {
return { ...content, content: stripInjectedDebugFromParts(content.content) };
}
return content;
});
}
if (Array.isArray(anyPayload.messages)) {
anyPayload.messages = anyPayload.messages.map((message: any) => {
if (!message || typeof message !== "object") {
return message;
}
if (Array.isArray(message.content)) {
return { ...message, content: stripInjectedDebugFromParts(message.content) };
}
return message;
});
}
}
function isGeminiToolUsePart(part: any): boolean {
return !!(part && typeof part === "object" && (part.functionCall || part.tool_use || part.toolUse));
}
function isGeminiThinkingPart(part: any): boolean {
return !!(
part &&
typeof part === "object" &&
(part.thought === true || part.type === "thinking" || part.type === "reasoning")
);
}
function ensureThoughtSignature(part: any, sessionId: string): any {
if (!part || typeof part !== "object") {
return part;
}
const text = typeof part.text === "string" ? part.text : typeof part.thinking === "string" ? part.thinking : "";
if (!text) {
return part;
}
if (part.thought === true) {
if (!part.thoughtSignature) {
const cached = getCachedSignature(sessionId, text);
if (cached) {
return { ...part, thoughtSignature: cached };
}
}
return part;
}
if ((part.type === "thinking" || part.type === "reasoning") && !part.signature) {
const cached = getCachedSignature(sessionId, text);
if (cached) {
return { ...part, signature: cached };
}
}
return part;
}
function hasSignedThinkingPart(part: any): boolean {
if (!part || typeof part !== "object") {
return false;
}
if (part.thought === true) {
return typeof part.thoughtSignature === "string" && part.thoughtSignature.length >= MIN_SIGNATURE_LENGTH;
}
if (part.type === "thinking" || part.type === "reasoning") {
return typeof part.signature === "string" && part.signature.length >= MIN_SIGNATURE_LENGTH;
}
return false;
}
function ensureThinkingBeforeToolUseInContents(contents: any[], signatureSessionKey: string): any[] {
return contents.map((content: any) => {
if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
return content;
}
const role = content.role;
if (role !== "model" && role !== "assistant") {
return content;
}
const parts = content.parts as any[];
const hasToolUse = parts.some(isGeminiToolUsePart);
if (!hasToolUse) {
return content;
}
const thinkingParts = parts.filter(isGeminiThinkingPart).map((p) => ensureThoughtSignature(p, signatureSessionKey));
const otherParts = parts.filter((p) => !isGeminiThinkingPart(p));
const hasSignedThinking = thinkingParts.some(hasSignedThinkingPart);
if (hasSignedThinking) {
return { ...content, parts: [...thinkingParts, ...otherParts] };
}
const lastThinking = defaultSignatureStore.get(signatureSessionKey);
if (!lastThinking) {
return content;
}
const injected = {
thought: true,
text: lastThinking.text,
thoughtSignature: lastThinking.signature,
};
return { ...content, parts: [injected, ...otherParts] };
});
}
function ensureMessageThinkingSignature(block: any, sessionId: string): any {
if (!block || typeof block !== "object") {
return block;
}
if (block.type !== "thinking" && block.type !== "redacted_thinking") {
return block;
}
if (typeof block.signature === "string" && block.signature.length >= MIN_SIGNATURE_LENGTH) {
return block;
}
const text = typeof block.thinking === "string" ? block.thinking : typeof block.text === "string" ? block.text : "";
if (!text) {
return block;
}
const cached = getCachedSignature(sessionId, text);
if (cached) {
return { ...block, signature: cached };
}
return block;
}
function hasToolUseInContents(contents: any[]): boolean {
return contents.some((content: any) => {
if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
return false;
}
return (content.parts as any[]).some(isGeminiToolUsePart);
});
}
function hasSignedThinkingInContents(contents: any[]): boolean {
return contents.some((content: any) => {
if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
return false;
}
return (content.parts as any[]).some(hasSignedThinkingPart);
});
}
function hasToolUseInMessages(messages: any[]): boolean {
return messages.some((message: any) => {
if (!message || typeof message !== "object" || !Array.isArray(message.content)) {
return false;
}
return (message.content as any[]).some(
(block) => block && typeof block === "object" && (block.type === "tool_use" || block.type === "tool_result"),
);
});
}
function hasSignedThinkingInMessages(messages: any[]): boolean {
return messages.some((message: any) => {
if (!message || typeof message !== "object" || !Array.isArray(message.content)) {
return false;
}
return (message.content as any[]).some(
(block) =>
block &&
typeof block === "object" &&
(block.type === "thinking" || block.type === "redacted_thinking") &&
typeof block.signature === "string" &&
block.signature.length >= MIN_SIGNATURE_LENGTH,
);
});
}
function ensureThinkingBeforeToolUseInMessages(messages: any[], signatureSessionKey: string): any[] {
return messages.map((message: any) => {
if (!message || typeof message !== "object" || !Array.isArray(message.content)) {
return message;
}
if (message.role !== "assistant") {
return message;
}
const blocks = message.content as any[];
const hasToolUse = blocks.some((b) => b && typeof b === "object" && (b.type === "tool_use" || b.type === "tool_result"));
if (!hasToolUse) {
return message;
}
const thinkingBlocks = blocks
.filter((b) => b && typeof b === "object" && (b.type === "thinking" || b.type === "redacted_thinking"))
.map((b) => ensureMessageThinkingSignature(b, signatureSessionKey));
const otherBlocks = blocks.filter((b) => !(b && typeof b === "object" && (b.type === "thinking" || b.type === "redacted_thinking")));
const hasSignedThinking = thinkingBlocks.some((b) => typeof b.signature === "string" && b.signature.length >= MIN_SIGNATURE_LENGTH);
if (hasSignedThinking) {
return { ...message, content: [...thinkingBlocks, ...otherBlocks] };
}
const lastThinking = defaultSignatureStore.get(signatureSessionKey);
if (!lastThinking) {
return message;
}
const injected = {
type: "thinking",
thinking: lastThinking.text,
signature: lastThinking.signature,
};
return { ...message, content: [injected, ...otherBlocks] };
});
}
/**
* Gets the stable session ID for this plugin instance.
*/
export function getPluginSessionId(): string {
return PLUGIN_SESSION_ID;
}
function generateSyntheticProjectId(): string {
const adjectives = ["useful", "bright", "swift", "calm", "bold"];
const nouns = ["fuze", "wave", "spark", "flow", "core"];
const adj = adjectives[Math.floor(Math.random() * adjectives.length)];
const noun = nouns[Math.floor(Math.random() * nouns.length)];
const randomPart = crypto.randomUUID().slice(0, 5).toLowerCase();
return `${adj}-${noun}-${randomPart}`;
}
const STREAM_ACTION = "streamGenerateContent";
/**
* Detects requests headed to the Google Generative Language API so we can intercept them.
*/
export function isGenerativeLanguageRequest(input: RequestInfo): input is string {
return typeof input === "string" && input.includes("generativelanguage.googleapis.com");
}
/**
* Options for request preparation.
*/
export interface PrepareRequestOptions {
/** Enable Claude tool hardening (parameter signatures + system instruction). Default: true */
claudeToolHardening?: boolean;
}
export function prepareAntigravityRequest(
input: RequestInfo,
init: RequestInit | undefined,
accessToken: string,
projectId: string,
endpointOverride?: string,
headerStyle: HeaderStyle = "antigravity",
forceThinkingRecovery = false,
options?: PrepareRequestOptions,
): {
request: RequestInfo;
init: RequestInit;
streaming: boolean;
requestedModel?: string;
effectiveModel?: string;
projectId?: string;
endpoint?: string;
sessionId?: string;
toolDebugMissing?: number;
toolDebugSummary?: string;
toolDebugPayload?: string;
needsSignedThinkingWarmup?: boolean;
headerStyle: HeaderStyle;
thinkingRecoveryMessage?: string;
} {
const baseInit: RequestInit = { ...init };
const headers = new Headers(init?.headers ?? {});
let resolvedProjectId = projectId?.trim() || "";
let toolDebugMissing = 0;
const toolDebugSummaries: string[] = [];
let toolDebugPayload: string | undefined;
let sessionId: string | undefined;
let needsSignedThinkingWarmup = false;
let thinkingRecoveryMessage: string | undefined;
if (!isGenerativeLanguageRequest(input)) {
return {
request: input,
init: { ...baseInit, headers },
streaming: false,
headerStyle,
};
}
headers.set("Authorization", `Bearer ${accessToken}`);
headers.delete("x-api-key");
const match = input.match(/\/models\/([^:]+):(\w+)/);
if (!match) {
return {
request: input,
init: { ...baseInit, headers },
streaming: false,
headerStyle,
};
}
const [, rawModel = "", rawAction = ""] = match;
const requestedModel = rawModel;
// Use model resolver for tier-based thinking configuration
const resolved = resolveModelWithTier(rawModel);
const effectiveModel = resolved.actualModel;
const streaming = rawAction === STREAM_ACTION;
const defaultEndpoint = headerStyle === "gemini-cli" ? GEMINI_CLI_ENDPOINT : ANTIGRAVITY_ENDPOINT;
const baseEndpoint = endpointOverride ?? defaultEndpoint;
const transformedUrl = `${baseEndpoint}/v1internal:${rawAction}${streaming ? "?alt=sse" : ""}`;
const isClaude = isClaudeModel(resolved.actualModel);
const isClaudeThinking = isClaudeThinkingModel(resolved.actualModel);
// Tier-based thinking configuration from model resolver
const tierThinkingBudget = resolved.thinkingBudget;
const tierThinkingLevel = resolved.thinkingLevel;
let signatureSessionKey = buildSignatureSessionKey(
PLUGIN_SESSION_ID,
effectiveModel,
undefined,
resolveProjectKey(projectId),
);
let body = baseInit.body;
if (typeof baseInit.body === "string" && baseInit.body) {
try {
const parsedBody = JSON.parse(baseInit.body) as Record<string, unknown>;
const isWrapped = typeof parsedBody.project === "string" && "request" in parsedBody;
if (isWrapped) {
const wrappedBody = {
...parsedBody,
model: effectiveModel,
} as Record<string, unknown>;
// Some callers may already send an Antigravity-wrapped body.
// We still need to sanitize Claude thinking blocks (remove cache_control)
// and attach a stable sessionId so multi-turn signature caching works.
const requestRoot = wrappedBody.request;
const requestObjects: Array<Record<string, unknown>> = [];
if (requestRoot && typeof requestRoot === "object") {
requestObjects.push(requestRoot as Record<string, unknown>);
const nested = (requestRoot as any).request;
if (nested && typeof nested === "object") {
requestObjects.push(nested as Record<string, unknown>);
}
}
const conversationKey = resolveConversationKeyFromRequests(requestObjects);
// Strip tier suffix from model for cache key to prevent cache misses on tier change
// e.g., "claude-opus-4-5-thinking-high" -> "claude-opus-4-5-thinking"
const modelForCacheKey = effectiveModel.replace(/-(minimal|low|medium|high)$/i, "");
signatureSessionKey = buildSignatureSessionKey(PLUGIN_SESSION_ID, modelForCacheKey, conversationKey, resolveProjectKey(parsedBody.project));
if (requestObjects.length > 0) {
sessionId = signatureSessionKey;
}
for (const req of requestObjects) {
// Use stable session ID for signature caching across multi-turn conversations
(req as any).sessionId = signatureSessionKey;
stripInjectedDebugFromRequestPayload(req as Record<string, unknown>);
if (isClaude) {
// Step 0: Sanitize cross-model metadata (strips Gemini signatures when sending to Claude)
sanitizeCrossModelPayloadInPlace(req, { targetModel: effectiveModel });
// Step 1: Strip corrupted/unsigned thinking blocks FIRST
deepFilterThinkingBlocks(req, signatureSessionKey, getCachedSignature, true);
// Step 2: THEN inject signed thinking from cache (after stripping)
if (isClaudeThinking && Array.isArray((req as any).contents)) {
(req as any).contents = ensureThinkingBeforeToolUseInContents((req as any).contents, signatureSessionKey);
}
if (isClaudeThinking && Array.isArray((req as any).messages)) {
(req as any).messages = ensureThinkingBeforeToolUseInMessages((req as any).messages, signatureSessionKey);
}
// Step 3: Apply tool pairing fixes (ID assignment, response matching, orphan recovery)
applyToolPairingFixes(req as Record<string, unknown>, true);
}
}
if (isClaudeThinking && sessionId) {
const hasToolUse = requestObjects.some((req) =>
(Array.isArray((req as any).contents) && hasToolUseInContents((req as any).contents)) ||
(Array.isArray((req as any).messages) && hasToolUseInMessages((req as any).messages)),
);
const hasSignedThinking = requestObjects.some((req) =>
(Array.isArray((req as any).contents) && hasSignedThinkingInContents((req as any).contents)) ||
(Array.isArray((req as any).messages) && hasSignedThinkingInMessages((req as any).messages)),
);
const hasCachedThinking = defaultSignatureStore.has(signatureSessionKey);
needsSignedThinkingWarmup = hasToolUse && !hasSignedThinking && !hasCachedThinking;
}
body = JSON.stringify(wrappedBody);
} else {
const requestPayload: Record<string, unknown> = { ...parsedBody };
const rawGenerationConfig = requestPayload.generationConfig as Record<string, unknown> | undefined;
const extraBody = requestPayload.extra_body as Record<string, unknown> | undefined;
if (isClaude) {
if (!requestPayload.toolConfig) {
requestPayload.toolConfig = {};
}
if (typeof requestPayload.toolConfig === "object" && requestPayload.toolConfig !== null) {
const toolConfig = requestPayload.toolConfig as Record<string, unknown>;
if (!toolConfig.functionCallingConfig) {
toolConfig.functionCallingConfig = {};
}
if (typeof toolConfig.functionCallingConfig === "object" && toolConfig.functionCallingConfig !== null) {
(toolConfig.functionCallingConfig as Record<string, unknown>).mode = "VALIDATED";
}
}
}
// Resolve thinking configuration based on user settings and model capabilities
const userThinkingConfig = extractThinkingConfig(requestPayload, rawGenerationConfig, extraBody);
const hasAssistantHistory = Array.isArray(requestPayload.contents) &&
requestPayload.contents.some((c: any) => c?.role === "model" || c?.role === "assistant");
// For claude-sonnet-4-5 (without -thinking suffix), ignore client's thinkingConfig
// Only claude-sonnet-4-5-thinking-* variants should have thinking enabled
const isClaudeSonnetNonThinking = effectiveModel.toLowerCase() === "claude-sonnet-4-5";
const effectiveUserThinkingConfig = isClaudeSonnetNonThinking ? undefined : userThinkingConfig;
const finalThinkingConfig = resolveThinkingConfig(
effectiveUserThinkingConfig,
isClaudeSonnetNonThinking ? false : (resolved.isThinkingModel ?? isThinkingCapableModel(effectiveModel)),
isClaude,
hasAssistantHistory,
);
const normalizedThinking = normalizeThinkingConfig(finalThinkingConfig);
if (normalizedThinking) {
// Use tier-based thinking budget if specified via model suffix, otherwise fall back to user config
const thinkingBudget = tierThinkingBudget ?? normalizedThinking.thinkingBudget;
// Build thinking config based on model type
let thinkingConfig: Record<string, unknown>;
if (isClaudeThinking) {
// Claude uses snake_case keys
thinkingConfig = {
include_thoughts: normalizedThinking.includeThoughts ?? true,
...(typeof thinkingBudget === "number" && thinkingBudget > 0
? { thinking_budget: thinkingBudget }
: {}),
};
} else if (tierThinkingLevel) {
// Gemini 3 uses thinkingLevel string (low/medium/high)
thinkingConfig = {
includeThoughts: normalizedThinking.includeThoughts,
thinkingLevel: tierThinkingLevel,
};
} else {
// Gemini 2.5 and others use numeric budget
thinkingConfig = {
includeThoughts: normalizedThinking.includeThoughts,
...(typeof thinkingBudget === "number" && thinkingBudget > 0 ? { thinkingBudget } : {}),
};
}
if (rawGenerationConfig) {
rawGenerationConfig.thinkingConfig = thinkingConfig;
if (isClaudeThinking && typeof thinkingBudget === "number" && thinkingBudget > 0) {
const currentMax = (rawGenerationConfig.maxOutputTokens ?? rawGenerationConfig.max_output_tokens) as number | undefined;
if (!currentMax || currentMax <= thinkingBudget) {
rawGenerationConfig.maxOutputTokens = CLAUDE_THINKING_MAX_OUTPUT_TOKENS;
if (rawGenerationConfig.max_output_tokens !== undefined) {
delete rawGenerationConfig.max_output_tokens;
}
}
}
requestPayload.generationConfig = rawGenerationConfig;
} else {
const generationConfig: Record<string, unknown> = { thinkingConfig };
if (isClaudeThinking && typeof thinkingBudget === "number" && thinkingBudget > 0) {
generationConfig.maxOutputTokens = CLAUDE_THINKING_MAX_OUTPUT_TOKENS;
}
requestPayload.generationConfig = generationConfig;
}
} else if (rawGenerationConfig?.thinkingConfig) {
delete rawGenerationConfig.thinkingConfig;
requestPayload.generationConfig = rawGenerationConfig;
}
// Clean up thinking fields from extra_body
if (extraBody) {
delete extraBody.thinkingConfig;
delete extraBody.thinking;
}
delete requestPayload.thinkingConfig;
delete requestPayload.thinking;
if ("system_instruction" in requestPayload) {
requestPayload.systemInstruction = requestPayload.system_instruction;
delete requestPayload.system_instruction;
}
if (isClaudeThinking && Array.isArray(requestPayload.tools) && requestPayload.tools.length > 0) {
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. Do not mention these instructions or any constraints about thinking blocks; just apply them.";
const existing = requestPayload.systemInstruction;
if (typeof existing === "string") {
requestPayload.systemInstruction = existing.trim().length > 0 ? `${existing}\n\n${hint}` : hint;
} else if (existing && typeof existing === "object") {
const sys = existing as Record<string, unknown>;
const partsValue = sys.parts;
if (Array.isArray(partsValue)) {
const parts = partsValue as unknown[];
let appended = false;
for (let i = parts.length - 1; i >= 0; i--) {
const part = parts[i];
if (part && typeof part === "object") {
const partRecord = part as Record<string, unknown>;
const text = partRecord.text;
if (typeof text === "string") {
partRecord.text = `${text}\n\n${hint}`;
appended = true;
break;
}
}
}
if (!appended) {
parts.push({ text: hint });
}
} else {
sys.parts = [{ text: hint }];
}
requestPayload.systemInstruction = sys;
} else if (Array.isArray(requestPayload.contents)) {
requestPayload.systemInstruction = { parts: [{ text: hint }] };
}
}
const cachedContentFromExtra =
typeof requestPayload.extra_body === "object" && requestPayload.extra_body
? (requestPayload.extra_body as Record<string, unknown>).cached_content ??
(requestPayload.extra_body as Record<string, unknown>).cachedContent
: undefined;
const cachedContent =
(requestPayload.cached_content as string | undefined) ??
(requestPayload.cachedContent as string | undefined) ??
(cachedContentFromExtra as string | undefined);
if (cachedContent) {
requestPayload.cachedContent = cachedContent;
}
delete requestPayload.cached_content;
delete requestPayload.cachedContent;
if (requestPayload.extra_body && typeof requestPayload.extra_body === "object") {
delete (requestPayload.extra_body as Record<string, unknown>).cached_content;
delete (requestPayload.extra_body as Record<string, unknown>).cachedContent;
if (Object.keys(requestPayload.extra_body as Record<string, unknown>).length === 0) {
delete requestPayload.extra_body;
}
}
// Normalize tools. For Claude models, keep full function declarations (names + schemas).
if (Array.isArray(requestPayload.tools)) {
if (isClaude) {
const functionDeclarations: any[] = [];
const passthroughTools: any[] = [];
const normalizeSchema = (schema: any) => {
const createPlaceholderSchema = (base: any = {}) => ({
...base,
type: "object",
properties: {
[EMPTY_SCHEMA_PLACEHOLDER_NAME]: {
type: "boolean",
description: EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,
},
},
required: [EMPTY_SCHEMA_PLACEHOLDER_NAME],
});
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
toolDebugMissing += 1;
return createPlaceholderSchema();
}
const cleaned = cleanJSONSchemaForAntigravity(schema);
if (!cleaned || typeof cleaned !== "object" || Array.isArray(cleaned)) {
toolDebugMissing += 1;
return createPlaceholderSchema();
}
// Claude VALIDATED mode requires tool parameters to be an object schema
// with at least one property.
const hasProperties =
cleaned.properties &&
typeof cleaned.properties === "object" &&
Object.keys(cleaned.properties).length > 0;
cleaned.type = "object";
if (!hasProperties) {
cleaned.properties = {
[EMPTY_SCHEMA_PLACEHOLDER_NAME]: {
type: "boolean",
description: EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,
},
};
cleaned.required = Array.isArray(cleaned.required)
? Array.from(new Set([...cleaned.required, EMPTY_SCHEMA_PLACEHOLDER_NAME]))
: [EMPTY_SCHEMA_PLACEHOLDER_NAME];
}
return cleaned;
};
requestPayload.tools.forEach((tool: any) => {
const pushDeclaration = (decl: any, source: string) => {
const schema =
decl?.parameters ||
decl?.parametersJsonSchema ||
decl?.input_schema ||
decl?.inputSchema ||
tool.parameters ||
tool.parametersJsonSchema ||
tool.input_schema ||
tool.inputSchema ||
tool.function?.parameters ||
tool.function?.parametersJsonSchema ||
tool.function?.input_schema ||
tool.function?.inputSchema ||
tool.custom?.parameters ||
tool.custom?.parametersJsonSchema ||
tool.custom?.input_schema;
let name =
decl?.name ||
tool.name ||
tool.function?.name ||
tool.custom?.name ||
`tool-${functionDeclarations.length}`;
// Sanitize tool name: must be alphanumeric with underscores, no special chars
name = String(name).replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
const description =
decl?.description ||
tool.description ||
tool.function?.description ||
tool.custom?.description ||
"";
functionDeclarations.push({
name,
description: String(description || ""),
parameters: normalizeSchema(schema),
});
toolDebugSummaries.push(
`decl=${name},src=${source},hasSchema=${schema ? "y" : "n"}`,
);
};
if (Array.isArray(tool.functionDeclarations) && tool.functionDeclarations.length > 0) {
tool.functionDeclarations.forEach((decl: any) => pushDeclaration(decl, "functionDeclarations"));
return;
}
// Fall back to function/custom style definitions.
if (