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
1881 lines (1621 loc) · 71.4 KB
/
Copy pathrequest.ts
File metadata and controls
1881 lines (1621 loc) · 71.4 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_ENDPOINT,
GEMINI_CLI_ENDPOINT,
GEMINI_CLI_HEADERS,
EMPTY_SCHEMA_PLACEHOLDER_NAME,
EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,
SKIP_THOUGHT_SIGNATURE,
getRandomizedHeaders,
type HeaderStyle,
} from "../constants";
import { cacheSignature, getCachedSignature } from "./cache";
import { getKeepThinking } from "./config";
import {
createStreamingTransformer,
transformSseLine,
transformStreamingPayload,
} from "./core/streaming";
import { defaultSignatureStore } from "./stores/signature-store";
import {
DEBUG_MESSAGE_PREFIX,
isDebugEnabled,
isDebugTuiEnabled,
logAntigravityDebugResponse,
logCacheStats,
type AntigravityDebugContext,
} from "./debug";
import { createLogger } from "./logger";
import {
cleanJSONSchemaForAntigravity,
DEFAULT_THINKING_BUDGET,
deepFilterThinkingBlocks,
extractThinkingConfig,
extractVariantThinkingConfig,
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,
ANTIGRAVITY_SYSTEM_INSTRUCTION,
} from "../constants";
import {
analyzeConversationState,
closeToolLoopForThinking,
needsThinkingRecovery,
} from "./thinking-recovery";
import { sanitizeCrossModelPayloadInPlace } from "./transform/cross-model-sanitizer";
import { isGemini3Model, isImageGenerationModel, buildImageGenerationConfig, applyGeminiTransforms } from "./transform";
import {
resolveModelWithTier,
resolveModelWithVariant,
resolveModelForHeaderStyle,
isClaudeModel,
isClaudeThinkingModel,
CLAUDE_THINKING_MAX_OUTPUT_TOKENS,
type ThinkingTier,
} from "./transform";
import { detectErrorType } from "./recovery";
import { getSessionFingerprint, buildFingerprintHeaders, type Fingerprint } from "./fingerprint";
import type { GoogleSearchConfig } from "./transform/types";
const log = createLogger("request");
const PLUGIN_SESSION_ID = `-${crypto.randomUUID()}`;
const sessionDisplayedThinkingHashes = new Set<string>();
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);
const prelude = `[ThinkingResolution] source=debug_tui lines=${cleaned.length}`;
return `${DEBUG_MESSAGE_PREFIX}\n- ${prelude}\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;
}
/**
* Synthetic thinking placeholder text used when keep_thinking=true but debug mode is off.
* Injected via the same path as debug text (injectDebugThinking) to ensure consistent
* signature caching and multi-turn handling.
*/
const SYNTHETIC_THINKING_PLACEHOLDER = "[Thinking preserved]\n";
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;
// Strip debug blocks and synthetic thinking placeholders
if (text && (text.startsWith(DEBUG_MESSAGE_PREFIX) || text.startsWith(SYNTHETIC_THINKING_PLACEHOLDER.trim()))) {
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 isValidRequestPart(part: unknown): boolean {
if (!part || typeof part !== "object") {
return false;
}
const record = part as Record<string, unknown>;
return (
Object.prototype.hasOwnProperty.call(record, "text") ||
Object.prototype.hasOwnProperty.call(record, "functionCall") ||
Object.prototype.hasOwnProperty.call(record, "functionResponse") ||
Object.prototype.hasOwnProperty.call(record, "inlineData") ||
Object.prototype.hasOwnProperty.call(record, "fileData") ||
Object.prototype.hasOwnProperty.call(record, "executableCode") ||
Object.prototype.hasOwnProperty.call(record, "codeExecutionResult") ||
Object.prototype.hasOwnProperty.call(record, "thought")
);
}
function sanitizeRequestPayloadForAntigravity(payload: Record<string, unknown>): void {
const anyPayload = payload as any;
if (Array.isArray(anyPayload.contents)) {
anyPayload.contents = anyPayload.contents
.map((content: unknown) => {
if (!content || typeof content !== "object") {
return null;
}
const contentRecord = content as Record<string, unknown>;
const rawParts = Array.isArray(contentRecord.parts) ? contentRecord.parts : [];
let foundFirstFunctionCall = false;
const sanitizedParts = rawParts.filter(isValidRequestPart).map((part: any) => {
if (part && typeof part === "object" && part.functionCall) {
let sig = part.thoughtSignature || part.thought_signature;
// Only the first functionCall part in a block should have the signature.
// If it's the first one and missing a valid signature, inject the sentinel
// to prevent the API from rejecting the request with a 400 error.
if (!foundFirstFunctionCall) {
foundFirstFunctionCall = true;
if (!sig || sig.length < MIN_SIGNATURE_LENGTH) {
sig = SKIP_THOUGHT_SIGNATURE;
}
} else {
// Parallel function calls MUST NOT have a signature
sig = undefined;
}
if (sig) {
return { ...part, thought_signature: sig, thoughtSignature: sig };
}
// If not the first part, just return the part without adding any signature keys
const newPart = { ...part };
delete newPart.thoughtSignature;
delete newPart.thought_signature;
return newPart;
}
return part;
});
if (sanitizedParts.length === 0) {
return null;
}
return {
...contentRecord,
parts: sanitizedParts,
};
})
.filter((content: unknown): content is Record<string, unknown> => content !== null);
}
const systemInstruction = anyPayload.systemInstruction;
if (systemInstruction && typeof systemInstruction === "object" && !Array.isArray(systemInstruction)) {
const sys = systemInstruction as Record<string, unknown>;
if (Array.isArray(sys.parts)) {
const sanitizedSystemParts = sys.parts.filter(isValidRequestPart);
if (sanitizedSystemParts.length > 0) {
sys.parts = sanitizedSystemParts;
} else {
delete anyPayload.systemInstruction;
}
}
}
}
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")
);
}
// Sentinel value used when signature recovery fails - allows Claude to handle gracefully
// by redacting the thinking block instead of rejecting the request entirely.
// Reference: LLM-API-Key-Proxy uses this pattern for Gemini 3 tool calls.
const SENTINEL_SIGNATURE = "skip_thought_signature_validator";
function getThinkingPartText(part: any): string {
if (!part || typeof part !== "object") {
return "";
}
if (typeof part.text === "string") {
return part.text;
}
if (typeof part.thinking === "string") {
return part.thinking;
}
return "";
}
function hasCachedMatchingSignature(part: any, sessionId: string): boolean {
if (!part || typeof part !== "object") {
return false;
}
const text = getThinkingPartText(part);
if (!text) {
return false;
}
const expectedSignature = getCachedSignature(sessionId, text);
if (!expectedSignature) {
return false;
}
if (part.thought === true) {
return part.thoughtSignature === expectedSignature;
}
return part.signature === expectedSignature;
}
function ensureThoughtSignature(part: any, sessionId: string): any {
if (!part || typeof part !== "object") {
return part;
}
if (!sessionId) {
return part;
}
const text = getThinkingPartText(part);
if (!text) {
return part;
}
if (part.thought === true) {
return { ...part, thoughtSignature: SENTINEL_SIGNATURE };
}
if (part.type === "thinking" || part.type === "reasoning" || part.type === "redacted_thinking") {
return { ...part, signature: SENTINEL_SIGNATURE };
}
return part;
}
function hasSignedThinkingPart(part: any, sessionId?: string): boolean {
if (!part || typeof part !== "object") {
return false;
}
if (part.thought === true) {
if (part.thoughtSignature === SENTINEL_SIGNATURE || part.thoughtSignature === SKIP_THOUGHT_SIGNATURE) {
return true;
}
if (typeof part.thoughtSignature !== "string" || part.thoughtSignature.length < MIN_SIGNATURE_LENGTH) {
return false;
}
if (!sessionId) {
return true;
}
return hasCachedMatchingSignature(part, sessionId);
}
if (part.type === "thinking" || part.type === "reasoning" || part.type === "redacted_thinking") {
if (part.signature === SENTINEL_SIGNATURE || part.signature === SKIP_THOUGHT_SIGNATURE) {
return true;
}
if (typeof part.signature !== "string" || part.signature.length < MIN_SIGNATURE_LENGTH) {
return false;
}
if (!sessionId) {
return true;
}
return hasCachedMatchingSignature(part, sessionId);
}
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((part) => hasSignedThinkingPart(part, signatureSessionKey));
if (hasSignedThinking) {
return { ...content, parts: [...thinkingParts, ...otherParts] };
}
const lastThinking = defaultSignatureStore.get(signatureSessionKey);
if (!lastThinking) {
// No cached signature available - strip thinking blocks entirely
// Claude requires valid signatures, and we can't fake them
// Return only tool_use parts without any thinking to avoid signature validation errors
log.debug("Stripping thinking from tool_use content (no valid cached signature)", { signatureSessionKey });
return { ...content, parts: otherParts };
}
const injected = {
thought: true,
text: lastThinking.text,
thoughtSignature: SENTINEL_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;
}
const text = getThinkingPartText(block);
if (!text) {
return block;
}
if (!sessionId) {
return block;
}
return { ...block, signature: SKIP_THOUGHT_SIGNATURE };
}
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[], sessionId?: string): boolean {
return contents.some((content: any) => {
if (!content || typeof content !== "object" || !Array.isArray(content.parts)) {
return false;
}
return (content.parts as any[]).some((part) => hasSignedThinkingPart(part, sessionId));
});
}
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[], sessionId?: string): boolean {
return messages.some((message: any) => {
if (!message || typeof message !== "object" || !Array.isArray(message.content)) {
return false;
}
return (message.content as any[]).some((block) => hasSignedThinkingPart(block, sessionId));
});
}
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((block) => hasSignedThinkingPart(block, signatureSessionKey));
if (hasSignedThinking) {
return { ...message, content: [...thinkingBlocks, ...otherBlocks] };
}
const lastThinking = defaultSignatureStore.get(signatureSessionKey);
if (!lastThinking) {
// No cached signature available - use sentinel to bypass validation
// This handles cache miss scenarios (restart, session mismatch, expiry)
const existingThinking = thinkingBlocks[0];
const thinkingText = existingThinking?.thinking || existingThinking?.text || "";
log.debug("Injecting sentinel signature (cache miss)", { signatureSessionKey });
const sentinelBlock = {
type: "thinking",
thinking: thinkingText,
signature: SKIP_THOUGHT_SIGNATURE,
};
return { ...message, content: [sentinelBlock, ...otherBlocks] };
}
const injected = {
type: "thinking",
thinking: lastThinking.text,
signature: SKIP_THOUGHT_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;
/** Enable top-level Claude prompt auto-caching (`cache_control`). Default: false */
claudePromptAutoCaching?: boolean;
/** Google Search configuration (global default) */
googleSearch?: GoogleSearchConfig;
/** Per-account fingerprint for rate limit mitigation. Falls back to session fingerprint if not provided. */
fingerprint?: Fingerprint;
}
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");
// Strip x-goog-user-project header to prevent 403 auth/license conflicts.
// This header is added by OpenCode/AI SDK and can force project-level checks
// that are not required for Antigravity/Gemini CLI OAuth requests.
headers.delete("x-goog-user-project");
const match = input.match(/\/models\/([^:]+):(\w+)/);
if (!match) {
return {
request: input,
init: { ...baseInit, headers },
streaming: false,
headerStyle,
};
}
const [, rawModel = "", rawAction = ""] = match;
const requestedModel = rawModel;
const resolved = resolveModelForHeaderStyle(rawModel, headerStyle);
let 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);
const keepThinkingEnabled = getKeepThinking();
const enableClaudePromptAutoCaching = options?.claudePromptAutoCaching ?? false;
// Tier-based thinking configuration from model resolver (can be overridden by variant config)
let tierThinkingBudget = resolved.thinkingBudget;
let 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-6-thinking-high" -> "claude-opus-4-6-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);
if (enableClaudePromptAutoCaching && (req as any).cache_control === undefined) {
(req as any).cache_control = { type: "ephemeral" };
}
// Step 2: THEN inject signed thinking from cache (after stripping)
if (isClaudeThinking && keepThinkingEnabled && Array.isArray((req as any).contents)) {
(req as any).contents = ensureThinkingBeforeToolUseInContents((req as any).contents, signatureSessionKey);
}
if (isClaudeThinking && keepThinkingEnabled && 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 && keepThinkingEnabled && 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, signatureSessionKey)) ||
(Array.isArray((req as any).messages) && hasSignedThinkingInMessages((req as any).messages, signatureSessionKey)),
);
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;
const variantConfig = extractVariantThinkingConfig(
requestPayload.providerOptions as Record<string, unknown> | undefined,
rawGenerationConfig
);
const isGemini3 = effectiveModel.toLowerCase().includes("gemini-3");
log.debug(`[ThinkingResolution] rawModel=${rawModel} resolvedModel=${effectiveModel} resolvedTier=${tierThinkingLevel ?? "none"} variantLevel=${variantConfig?.thinkingLevel ?? "none"} variantBudget=${variantConfig?.thinkingBudget ?? "none"} providerOptions.google=${JSON.stringify((requestPayload.providerOptions as any)?.google ?? null)} generationConfig.thinkingConfig=${JSON.stringify((rawGenerationConfig as any)?.thinkingConfig ?? null)}`);
if (variantConfig?.thinkingLevel && isGemini3) {
// Gemini 3 native format - use thinkingLevel directly
tierThinkingLevel = variantConfig.thinkingLevel;
tierThinkingBudget = undefined;
} else if (variantConfig?.thinkingBudget) {
if (isGemini3) {
// Legacy format for Gemini 3 - convert with deprecation warning
log.warn("[Deprecated] Using thinkingBudget for Gemini 3 model. Use thinkingLevel instead.");
tierThinkingLevel = variantConfig.thinkingBudget <= 8192 ? "low"
: variantConfig.thinkingBudget <= 16384 ? "medium" : "high";
tierThinkingBudget = undefined;
} else {
// Claude / Gemini 2.5 - use budget directly
tierThinkingBudget = variantConfig.thinkingBudget;
tierThinkingLevel = 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
// Image generation models don't support thinking - skip thinking config entirely
const isImageModel = isImageGenerationModel(effectiveModel);
const userThinkingConfig = isImageModel ? undefined : extractThinkingConfig(requestPayload, rawGenerationConfig, extraBody);
const hasAssistantHistory = Array.isArray(requestPayload.contents) &&
requestPayload.contents.some((c: any) => c?.role === "model" || c?.role === "assistant");
// Claude Sonnet 4.6 is non-thinking only.
// Ignore any client-provided thinkingConfig for this model.
const lowerEffective = effectiveModel.toLowerCase();
const isClaudeSonnetNonThinking = lowerEffective === "claude-sonnet-4-6";
const effectiveUserThinkingConfig = (isClaudeSonnetNonThinking || isImageModel) ? undefined : userThinkingConfig;
// For image models, add imageConfig instead of thinkingConfig
if (isImageModel) {
const imageConfig = buildImageGenerationConfig();
const generationConfig = (rawGenerationConfig ?? {}) as Record<string, unknown>;
generationConfig.imageConfig = imageConfig;
// Remove any thinkingConfig that might have been set
delete generationConfig.thinkingConfig;
// Set reasonable defaults for image generation
if (!generationConfig.candidateCount) {
generationConfig.candidateCount = 1;
}
requestPayload.generationConfig = generationConfig;
// Add safety settings for image generation (permissive to allow creative content)
if (!requestPayload.safetySettings) {
requestPayload.safetySettings = [
{ category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_ONLY_HIGH" },
{ category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_ONLY_HIGH" },
{ category: "HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold: "BLOCK_ONLY_HIGH" },
{ category: "HARM_CATEGORY_DANGEROUS_CONTENT", threshold: "BLOCK_ONLY_HIGH" },
{ category: "HARM_CATEGORY_CIVIC_INTEGRITY", threshold: "BLOCK_ONLY_HIGH" },
];
}
// Image models don't support tools - remove them entirely
delete requestPayload.tools;
delete requestPayload.toolConfig;
// Replace system instruction with a simple image generation prompt
// Image models should not receive agentic coding assistant instructions