forked from NoeFabris/opencode-antigravity-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest-helpers.ts
More file actions
2856 lines (2459 loc) · 89.8 KB
/
Copy pathrequest-helpers.ts
File metadata and controls
2856 lines (2459 loc) · 89.8 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 { getKeepThinking } from "./config";
import { createLogger } from "./logger";
import { cacheSignature } from "./cache";
import {
EMPTY_SCHEMA_PLACEHOLDER_NAME,
EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,
SKIP_THOUGHT_SIGNATURE,
} from "../constants";
import { processImageData } from "./image-saver";
import type { GoogleSearchConfig } from "./transform/types";
const log = createLogger("request-helpers");
const ANTIGRAVITY_PREVIEW_LINK = "https://goo.gle/enable-preview-features"; // TODO: Update to Antigravity link if available
// ============================================================================
// JSON SCHEMA CLEANING FOR ANTIGRAVITY API
// Ported from CLIProxyAPI's CleanJSONSchemaForAntigravity (gemini_schema.go)
// ============================================================================
/**
* Unsupported constraint keywords that should be moved to description hints.
* Claude/Gemini reject these in VALIDATED mode.
*/
const UNSUPPORTED_CONSTRAINTS = [
"minLength", "maxLength", "exclusiveMinimum", "exclusiveMaximum",
"pattern", "minItems", "maxItems", "format",
"default", "examples",
] as const;
/**
* Keywords that should be removed after hint extraction.
*/
const UNSUPPORTED_KEYWORDS = [
...UNSUPPORTED_CONSTRAINTS,
"$schema", "$defs", "definitions", "const", "$ref", "additionalProperties",
"propertyNames", "title", "$id", "$comment",
] as const;
/**
* Appends a hint to a schema's description field.
*/
function appendDescriptionHint(schema: any, hint: string): any {
if (!schema || typeof schema !== "object") {
return schema;
}
const existing = typeof schema.description === "string" ? schema.description : "";
const newDescription = existing ? `${existing} (${hint})` : hint;
return { ...schema, description: newDescription };
}
/**
* Phase 1a: Converts $ref to description hints.
* $ref: "#/$defs/Foo" → { type: "object", description: "See: Foo" }
*/
function convertRefsToHints(schema: any): any {
if (!schema || typeof schema !== "object") {
return schema;
}
if (Array.isArray(schema)) {
return schema.map(item => convertRefsToHints(item));
}
// If this object has $ref, replace it with a hint
if (typeof schema.$ref === "string") {
const refVal = schema.$ref;
const defName = refVal.includes("/") ? refVal.split("/").pop() : refVal;
const hint = `See: ${defName}`;
const existingDesc = typeof schema.description === "string" ? schema.description : "";
const newDescription = existingDesc ? `${existingDesc} (${hint})` : hint;
return { type: "object", description: newDescription };
}
// Recursively process all properties
const result: any = {};
for (const [key, value] of Object.entries(schema)) {
result[key] = convertRefsToHints(value);
}
return result;
}
/**
* Phase 1b: Converts const to enum.
* { const: "foo" } → { enum: ["foo"] }
*/
function convertConstToEnum(schema: any): any {
if (!schema || typeof schema !== "object") {
return schema;
}
if (Array.isArray(schema)) {
return schema.map(item => convertConstToEnum(item));
}
const result: any = {};
for (const [key, value] of Object.entries(schema)) {
if (key === "const" && !schema.enum) {
result.enum = [value];
} else {
result[key] = convertConstToEnum(value);
}
}
return result;
}
/**
* Phase 1c: Adds enum hints to description.
* { enum: ["a", "b", "c"] } → adds "(Allowed: a, b, c)" to description
*/
function addEnumHints(schema: any): any {
if (!schema || typeof schema !== "object") {
return schema;
}
if (Array.isArray(schema)) {
return schema.map(item => addEnumHints(item));
}
let result: any = { ...schema };
// Add enum hint if enum has 2-10 items
if (Array.isArray(result.enum) && result.enum.length > 1 && result.enum.length <= 10) {
const vals = result.enum.map((v: any) => String(v)).join(", ");
result = appendDescriptionHint(result, `Allowed: ${vals}`);
}
// Recursively process nested objects
for (const [key, value] of Object.entries(result)) {
if (key !== "enum" && typeof value === "object" && value !== null) {
result[key] = addEnumHints(value);
}
}
return result;
}
/**
* Phase 1d: Adds additionalProperties hints.
* { additionalProperties: false } → adds "(No extra properties allowed)" to description
*/
function addAdditionalPropertiesHints(schema: any): any {
if (!schema || typeof schema !== "object") {
return schema;
}
if (Array.isArray(schema)) {
return schema.map(item => addAdditionalPropertiesHints(item));
}
let result: any = { ...schema };
if (result.additionalProperties === false) {
result = appendDescriptionHint(result, "No extra properties allowed");
}
// Recursively process nested objects
for (const [key, value] of Object.entries(result)) {
if (key !== "additionalProperties" && typeof value === "object" && value !== null) {
result[key] = addAdditionalPropertiesHints(value);
}
}
return result;
}
/**
* Phase 1e: Moves unsupported constraints to description hints.
* { minLength: 1, maxLength: 100 } → adds "(minLength: 1) (maxLength: 100)" to description
*/
function moveConstraintsToDescription(schema: any): any {
if (!schema || typeof schema !== "object") {
return schema;
}
if (Array.isArray(schema)) {
return schema.map(item => moveConstraintsToDescription(item));
}
let result: any = { ...schema };
// Move constraint values to description
for (const constraint of UNSUPPORTED_CONSTRAINTS) {
if (result[constraint] !== undefined && typeof result[constraint] !== "object") {
result = appendDescriptionHint(result, `${constraint}: ${result[constraint]}`);
}
}
// Recursively process nested objects
for (const [key, value] of Object.entries(result)) {
if (typeof value === "object" && value !== null) {
result[key] = moveConstraintsToDescription(value);
}
}
return result;
}
/**
* Phase 2a: Merges allOf schemas into a single object.
* { allOf: [{ properties: { a: ... } }, { properties: { b: ... } }] }
* → { properties: { a: ..., b: ... } }
*/
function mergeAllOf(schema: any): any {
if (!schema || typeof schema !== "object") {
return schema;
}
if (Array.isArray(schema)) {
return schema.map(item => mergeAllOf(item));
}
let result: any = { ...schema };
// If this object has allOf, merge its contents
if (Array.isArray(result.allOf)) {
const merged: any = {};
const mergedRequired: string[] = [];
for (const item of result.allOf) {
if (!item || typeof item !== "object") continue;
// Merge properties
if (item.properties && typeof item.properties === "object") {
merged.properties = { ...merged.properties, ...item.properties };
}
// Merge required arrays
if (Array.isArray(item.required)) {
for (const req of item.required) {
if (!mergedRequired.includes(req)) {
mergedRequired.push(req);
}
}
}
// Copy other fields from allOf items
for (const [key, value] of Object.entries(item)) {
if (key !== "properties" && key !== "required" && merged[key] === undefined) {
merged[key] = value;
}
}
}
// Apply merged content to result
if (merged.properties) {
result.properties = { ...result.properties, ...merged.properties };
}
if (mergedRequired.length > 0) {
const existingRequired = Array.isArray(result.required) ? result.required : [];
result.required = Array.from(new Set([...existingRequired, ...mergedRequired]));
}
// Copy other merged fields
for (const [key, value] of Object.entries(merged)) {
if (key !== "properties" && key !== "required" && result[key] === undefined) {
result[key] = value;
}
}
delete result.allOf;
}
// Recursively process nested objects
for (const [key, value] of Object.entries(result)) {
if (typeof value === "object" && value !== null) {
result[key] = mergeAllOf(value);
}
}
return result;
}
/**
* Scores a schema option for selection in anyOf/oneOf flattening.
* Higher score = more preferred.
*/
function scoreSchemaOption(schema: any): { score: number; typeName: string } {
if (!schema || typeof schema !== "object") {
return { score: 0, typeName: "unknown" };
}
const type = schema.type;
// Object or has properties = highest priority
if (type === "object" || schema.properties) {
return { score: 3, typeName: "object" };
}
// Array or has items = second priority
if (type === "array" || schema.items) {
return { score: 2, typeName: "array" };
}
// Any other non-null type
if (type && type !== "null") {
return { score: 1, typeName: type };
}
// Null or no type
return { score: 0, typeName: type || "null" };
}
/**
* Checks if an anyOf/oneOf array represents enum choices.
* Returns the merged enum values if so, otherwise null.
*
* Handles patterns like:
* - anyOf: [{ const: "a" }, { const: "b" }]
* - anyOf: [{ enum: ["a"] }, { enum: ["b"] }]
* - anyOf: [{ type: "string", const: "a" }, { type: "string", const: "b" }]
*/
function tryMergeEnumFromUnion(options: any[]): string[] | null {
if (!Array.isArray(options) || options.length === 0) {
return null;
}
const enumValues: string[] = [];
for (const option of options) {
if (!option || typeof option !== "object") {
return null;
}
// Check for const value
if (option.const !== undefined) {
enumValues.push(String(option.const));
continue;
}
// Check for single-value enum
if (Array.isArray(option.enum) && option.enum.length === 1) {
enumValues.push(String(option.enum[0]));
continue;
}
// Check for multi-value enum (merge all values)
if (Array.isArray(option.enum) && option.enum.length > 0) {
for (const val of option.enum) {
enumValues.push(String(val));
}
continue;
}
// If option has complex structure (properties, items, etc.), it's not a simple enum
if (option.properties || option.items || option.anyOf || option.oneOf || option.allOf) {
return null;
}
// If option has only type (no const/enum), it's not an enum pattern
if (option.type && !option.const && !option.enum) {
return null;
}
}
// Only return if we found actual enum values
return enumValues.length > 0 ? enumValues : null;
}
/**
* Phase 2b: Flattens anyOf/oneOf to the best option with type hints.
* { anyOf: [{ type: "string" }, { type: "number" }] }
* → { type: "string", description: "(Accepts: string | number)" }
*
* Special handling for enum patterns:
* { anyOf: [{ const: "a" }, { const: "b" }] }
* → { type: "string", enum: ["a", "b"] }
*/
function flattenAnyOfOneOf(schema: any): any {
if (!schema || typeof schema !== "object") {
return schema;
}
if (Array.isArray(schema)) {
return schema.map(item => flattenAnyOfOneOf(item));
}
let result: any = { ...schema };
// Process anyOf or oneOf
for (const unionKey of ["anyOf", "oneOf"] as const) {
if (Array.isArray(result[unionKey]) && result[unionKey].length > 0) {
const options = result[unionKey];
const parentDesc = typeof result.description === "string" ? result.description : "";
// First, check if this is an enum pattern (anyOf with const/enum values)
// This is crucial for tools like WebFetch where format: anyOf[{const:"text"},{const:"markdown"},{const:"html"}]
const mergedEnum = tryMergeEnumFromUnion(options);
if (mergedEnum !== null) {
// This is an enum pattern - merge all values into a single enum
const { [unionKey]: _, ...rest } = result;
result = {
...rest,
type: "string",
enum: mergedEnum,
};
// Preserve parent description
if (parentDesc) {
result.description = parentDesc;
}
continue;
}
// Not an enum pattern - use standard flattening logic
// Score each option and find the best
let bestIdx = 0;
let bestScore = -1;
const allTypes: string[] = [];
for (let i = 0; i < options.length; i++) {
const { score, typeName } = scoreSchemaOption(options[i]);
if (typeName) {
allTypes.push(typeName);
}
if (score > bestScore) {
bestScore = score;
bestIdx = i;
}
}
// Select the best option and flatten it recursively
let selected = flattenAnyOfOneOf(options[bestIdx]) || { type: "string" };
// Preserve parent description
if (parentDesc) {
const childDesc = typeof selected.description === "string" ? selected.description : "";
if (childDesc && childDesc !== parentDesc) {
selected = { ...selected, description: `${parentDesc} (${childDesc})` };
} else if (!childDesc) {
selected = { ...selected, description: parentDesc };
}
}
if (allTypes.length > 1) {
const uniqueTypes = Array.from(new Set(allTypes));
const hint = `Accepts: ${uniqueTypes.join(" | ")}`;
selected = appendDescriptionHint(selected, hint);
}
// Replace result with selected schema, preserving other fields
const { [unionKey]: _, description: __, ...rest } = result;
result = { ...rest, ...selected };
}
}
// Recursively process nested objects
for (const [key, value] of Object.entries(result)) {
if (typeof value === "object" && value !== null) {
result[key] = flattenAnyOfOneOf(value);
}
}
return result;
}
/**
* Phase 2c: Flattens type arrays to single type with nullable hint.
* { type: ["string", "null"] } → { type: "string", description: "(nullable)" }
*/
function flattenTypeArrays(schema: any, nullableFields?: Map<string, string[]>, currentPath?: string): any {
if (!schema || typeof schema !== "object") {
return schema;
}
if (Array.isArray(schema)) {
return schema.map((item, idx) => flattenTypeArrays(item, nullableFields, `${currentPath || ""}[${idx}]`));
}
let result: any = { ...schema };
const localNullableFields = nullableFields || new Map<string, string[]>();
// Handle type array
if (Array.isArray(result.type)) {
const types = result.type as string[];
const hasNull = types.includes("null");
const nonNullTypes = types.filter(t => t !== "null" && t);
// Select first non-null type, or "string" as fallback
const firstType = nonNullTypes.length > 0 ? nonNullTypes[0] : "string";
result.type = firstType;
// Add hint for multiple types
if (nonNullTypes.length > 1) {
result = appendDescriptionHint(result, `Accepts: ${nonNullTypes.join(" | ")}`);
}
// Add nullable hint
if (hasNull) {
result = appendDescriptionHint(result, "nullable");
}
}
// Recursively process properties
if (result.properties && typeof result.properties === "object") {
const newProps: any = {};
for (const [propKey, propValue] of Object.entries(result.properties)) {
const propPath = currentPath ? `${currentPath}.properties.${propKey}` : `properties.${propKey}`;
const processed = flattenTypeArrays(propValue, localNullableFields, propPath);
newProps[propKey] = processed;
// Track nullable fields for required array cleanup
if (processed && typeof processed === "object" &&
typeof processed.description === "string" &&
processed.description.includes("nullable")) {
const objectPath = currentPath || "";
const existing = localNullableFields.get(objectPath) || [];
existing.push(propKey);
localNullableFields.set(objectPath, existing);
}
}
result.properties = newProps;
}
// Remove nullable fields from required array
if (Array.isArray(result.required) && !nullableFields) {
// Only at root level, filter out nullable fields
const nullableAtRoot = localNullableFields.get("") || [];
if (nullableAtRoot.length > 0) {
result.required = result.required.filter((r: string) => !nullableAtRoot.includes(r));
if (result.required.length === 0) {
delete result.required;
}
}
}
// Recursively process other nested objects
for (const [key, value] of Object.entries(result)) {
if (key !== "properties" && typeof value === "object" && value !== null) {
result[key] = flattenTypeArrays(value, localNullableFields, `${currentPath || ""}.${key}`);
}
}
return result;
}
/**
* Phase 3: Removes unsupported keywords after hints have been extracted.
* @param insideProperties - When true, keys are property NAMES (preserve); when false, keys are JSON Schema keywords (filter).
*/
function removeUnsupportedKeywords(schema: any, insideProperties: boolean = false): any {
if (!schema || typeof schema !== "object") {
return schema;
}
if (Array.isArray(schema)) {
return schema.map(item => removeUnsupportedKeywords(item, false));
}
const result: any = {};
for (const [key, value] of Object.entries(schema)) {
if (!insideProperties && (UNSUPPORTED_KEYWORDS as readonly string[]).includes(key)) {
continue;
}
if (typeof value === "object" && value !== null) {
if (key === "properties") {
const propertiesResult: any = {};
for (const [propName, propSchema] of Object.entries(value as object)) {
propertiesResult[propName] = removeUnsupportedKeywords(propSchema, false);
}
result[key] = propertiesResult;
} else {
result[key] = removeUnsupportedKeywords(value, false);
}
} else {
result[key] = value;
}
}
return result;
}
/**
* Phase 3b: Cleans up required fields - removes entries that don't exist in properties.
*/
function cleanupRequiredFields(schema: any): any {
if (!schema || typeof schema !== "object") {
return schema;
}
if (Array.isArray(schema)) {
return schema.map(item => cleanupRequiredFields(item));
}
let result: any = { ...schema };
// Clean up required array if properties exist
if (Array.isArray(result.required) && result.properties && typeof result.properties === "object") {
const validRequired = result.required.filter((req: string) =>
Object.prototype.hasOwnProperty.call(result.properties, req)
);
if (validRequired.length === 0) {
delete result.required;
} else if (validRequired.length !== result.required.length) {
result.required = validRequired;
}
}
// Recursively process nested objects
for (const [key, value] of Object.entries(result)) {
if (typeof value === "object" && value !== null) {
result[key] = cleanupRequiredFields(value);
}
}
return result;
}
/**
* Phase 4: Adds placeholder property for empty object schemas.
* Claude VALIDATED mode requires at least one property.
*/
function addEmptySchemaPlaceholder(schema: any): any {
if (!schema || typeof schema !== "object") {
return schema;
}
if (Array.isArray(schema)) {
return schema.map(item => addEmptySchemaPlaceholder(item));
}
let result: any = { ...schema };
// Check if this is an empty object schema
const isObjectType = result.type === "object";
if (isObjectType) {
const hasProperties =
result.properties &&
typeof result.properties === "object" &&
Object.keys(result.properties).length > 0;
if (!hasProperties) {
result.properties = {
[EMPTY_SCHEMA_PLACEHOLDER_NAME]: {
type: "boolean",
description: EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,
},
};
result.required = [EMPTY_SCHEMA_PLACEHOLDER_NAME];
}
}
// Recursively process nested objects
for (const [key, value] of Object.entries(result)) {
if (typeof value === "object" && value !== null) {
result[key] = addEmptySchemaPlaceholder(value);
}
}
return result;
}
/**
* Cleans a JSON schema for Antigravity API compatibility.
* Transforms unsupported features into description hints while preserving semantic information.
*
* Ported from CLIProxyAPI's CleanJSONSchemaForAntigravity (gemini_schema.go)
*/
export function cleanJSONSchemaForAntigravity(schema: any): any {
if (!schema || typeof schema !== "object") {
return schema;
}
let result = schema;
// Phase 1: Convert and add hints
result = convertRefsToHints(result);
result = convertConstToEnum(result);
result = addEnumHints(result);
result = addAdditionalPropertiesHints(result);
result = moveConstraintsToDescription(result);
// Phase 2: Flatten complex structures
result = mergeAllOf(result);
result = flattenAnyOfOneOf(result);
result = flattenTypeArrays(result);
// Phase 3: Cleanup
result = removeUnsupportedKeywords(result);
result = cleanupRequiredFields(result);
// Phase 4: Add placeholder for empty object schemas
result = addEmptySchemaPlaceholder(result);
return result;
}
// ============================================================================
// END JSON SCHEMA CLEANING
// ============================================================================
export interface AntigravityApiError {
code?: number;
message?: string;
status?: string;
[key: string]: unknown;
}
/**
* Minimal representation of Antigravity API responses we touch.
*/
export interface AntigravityApiBody {
response?: unknown;
error?: AntigravityApiError;
[key: string]: unknown;
}
/**
* Usage metadata exposed by Antigravity responses. Fields are optional to reflect partial payloads.
*/
export interface AntigravityUsageMetadata {
totalTokenCount?: number;
promptTokenCount?: number;
candidatesTokenCount?: number;
cachedContentTokenCount?: number;
thoughtsTokenCount?: number;
}
/**
* Normalized thinking configuration accepted by Antigravity.
*/
export interface ThinkingConfig {
thinkingBudget?: number;
includeThoughts?: boolean;
}
/**
* Default token budget for thinking/reasoning. 16000 tokens provides sufficient
* space for complex reasoning while staying within typical model limits.
*/
export const DEFAULT_THINKING_BUDGET = 16000;
/**
* Checks if a model name indicates thinking/reasoning capability.
* Models with "thinking", "gemini-3", or "opus" in their name support extended thinking.
*/
export function isThinkingCapableModel(modelName: string): boolean {
const lowerModel = modelName.toLowerCase();
return lowerModel.includes("thinking")
|| lowerModel.includes("gemini-3")
|| lowerModel.includes("opus");
}
/**
* Extracts thinking configuration from various possible request locations.
* Supports both Gemini-style thinkingConfig and Anthropic-style thinking options.
*/
export function extractThinkingConfig(
requestPayload: Record<string, unknown>,
rawGenerationConfig: Record<string, unknown> | undefined,
extraBody: Record<string, unknown> | undefined,
): ThinkingConfig | undefined {
const thinkingConfig = rawGenerationConfig?.thinkingConfig
?? extraBody?.thinkingConfig
?? requestPayload.thinkingConfig;
if (thinkingConfig && typeof thinkingConfig === "object") {
const config = thinkingConfig as Record<string, unknown>;
return {
includeThoughts: Boolean(config.includeThoughts),
thinkingBudget: typeof config.thinkingBudget === "number" ? config.thinkingBudget : DEFAULT_THINKING_BUDGET,
};
}
// Convert Anthropic-style "thinking" option: { type: "enabled", budgetTokens: N }
const anthropicThinking = extraBody?.thinking ?? requestPayload.thinking;
if (anthropicThinking && typeof anthropicThinking === "object") {
const thinking = anthropicThinking as Record<string, unknown>;
if (thinking.type === "enabled" || thinking.budgetTokens) {
return {
includeThoughts: true,
thinkingBudget: typeof thinking.budgetTokens === "number" ? thinking.budgetTokens : DEFAULT_THINKING_BUDGET,
};
}
}
return undefined;
}
/**
* Variant thinking config extracted from OpenCode's providerOptions.
*/
export interface VariantThinkingConfig {
/** Gemini 3 native thinking level (low/medium/high) */
thinkingLevel?: string;
/** Numeric thinking budget for Claude and Gemini 2.5 */
thinkingBudget?: number;
/** Whether to include thoughts in output */
includeThoughts?: boolean;
/** Google Search configuration */
googleSearch?: GoogleSearchConfig;
}
/**
* Extracts variant thinking config from OpenCode's providerOptions.
*
* All Antigravity models route through the Google provider, so we only check
* providerOptions.google. Supports two formats:
*
* 1. Gemini 3 native: { google: { thinkingLevel: "high", includeThoughts: true } }
* 2. Budget-based (Claude/Gemini 2.5): { google: { thinkingConfig: { thinkingBudget: 32000 } } }
*
* When providerOptions is missing or has no thinking config (common with OpenCode
* model variants), falls back to extracting from generationConfig directly:
* 3. generationConfig fallback: { thinkingConfig: { thinkingBudget: 8192 } }
*/
export function extractVariantThinkingConfig(
providerOptions: Record<string, unknown> | undefined,
generationConfig?: Record<string, unknown> | undefined
): VariantThinkingConfig | undefined {
const result: VariantThinkingConfig = {};
// Primary path: extract from providerOptions.google
const google = (providerOptions?.google) as Record<string, unknown> | undefined;
if (google) {
// Gemini 3 native format: { google: { thinkingLevel: "high", includeThoughts: true } }
// thinkingLevel takes priority over thinkingBudget - they are mutually exclusive
if (typeof google.thinkingLevel === "string") {
result.thinkingLevel = google.thinkingLevel;
result.includeThoughts = typeof google.includeThoughts === "boolean" ? google.includeThoughts : undefined;
} else if (google.thinkingConfig && typeof google.thinkingConfig === "object") {
// Budget-based format (Claude/Gemini 2.5): { google: { thinkingConfig: { thinkingBudget } } }
// Only used when thinkingLevel is not present
const tc = google.thinkingConfig as Record<string, unknown>;
if (typeof tc.thinkingBudget === "number") {
result.thinkingBudget = tc.thinkingBudget;
}
}
// Extract Google Search config
if (google.googleSearch && typeof google.googleSearch === "object") {
const search = google.googleSearch as Record<string, unknown>;
result.googleSearch = {
mode: search.mode === 'auto' || search.mode === 'off' ? search.mode : undefined,
threshold: typeof search.threshold === 'number' ? search.threshold : undefined,
};
}
}
// Fallback: OpenCode may pass thinking config in generationConfig
// instead of providerOptions (common when using model variants)
if (result.thinkingBudget === undefined && !result.thinkingLevel && generationConfig) {
if (generationConfig.thinkingConfig && typeof generationConfig.thinkingConfig === "object") {
const tc = generationConfig.thinkingConfig as Record<string, unknown>;
if (typeof tc.thinkingLevel === "string") {
// Gemini 3 native format sent via generationConfig
result.thinkingLevel = tc.thinkingLevel;
result.includeThoughts = typeof tc.includeThoughts === "boolean" ? tc.includeThoughts : undefined;
} else if (typeof tc.thinkingBudget === "number") {
result.thinkingBudget = tc.thinkingBudget;
}
}
}
return Object.keys(result).length > 0 ? result : undefined;
}
/**
* Determines the final thinking configuration based on model capabilities and user settings.
* For Claude thinking models, we keep thinking enabled even in multi-turn conversations.
* The filterUnsignedThinkingBlocks function will handle signature validation/restoration.
*/
export function resolveThinkingConfig(
userConfig: ThinkingConfig | undefined,
isThinkingModel: boolean,
_isClaudeModel: boolean,
_hasAssistantHistory: boolean,
): ThinkingConfig | undefined {
// For thinking-capable models (including Claude thinking models), enable thinking by default
// The signature validation/restoration is handled by filterUnsignedThinkingBlocks
if (isThinkingModel && !userConfig) {
return { includeThoughts: true, thinkingBudget: DEFAULT_THINKING_BUDGET };
}
return userConfig;
}
/**
* Checks if a part is a thinking/reasoning block (Anthropic or Gemini style).
*/
function isThinkingPart(part: Record<string, unknown>): boolean {
return part.type === "thinking"
|| part.type === "redacted_thinking"
|| part.type === "reasoning"
|| part.thinking !== undefined
|| part.thought === true;
}
/**
* Checks if a part has a signature field (thinking block signature).
* Used to detect foreign thinking blocks that might have unknown type values.
*/
function hasSignatureField(part: Record<string, unknown>): boolean {
return part.signature !== undefined || part.thoughtSignature !== undefined;
}
/**
* Checks if a part is a tool block (tool_use or tool_result).
* Tool blocks must never be filtered - they're required for tool call/result pairing.
* Handles multiple formats:
* - Anthropic: { type: "tool_use" }, { type: "tool_result", tool_use_id }
* - Nested: { tool_result: { tool_use_id } }, { tool_use: { id } }
* - Gemini: { functionCall }, { functionResponse }
*/
function isToolBlock(part: Record<string, unknown>): boolean {
return part.type === "tool_use"
|| part.type === "tool_result"
|| part.tool_use_id !== undefined
|| part.tool_call_id !== undefined
|| part.tool_result !== undefined
|| part.tool_use !== undefined
|| part.toolUse !== undefined
|| part.functionCall !== undefined
|| part.functionResponse !== undefined;
}
/**
* Unconditionally strips ALL thinking/reasoning blocks from a content array.
* Used for Claude models to avoid signature validation errors entirely.
* Claude will generate fresh thinking for each turn.
*/
function stripAllThinkingBlocks(contentArray: any[]): any[] {
return contentArray.filter(item => {
if (!item || typeof item !== "object") return true;
if (isToolBlock(item)) return true;
if (isThinkingPart(item)) return false;
if (hasSignatureField(item)) return false;
return true;
});
}
/**
* Removes trailing thinking blocks from a content array.
* Claude API requires that assistant messages don't end with thinking blocks.
* Only removes unsigned thinking blocks; preserves those with valid signatures.
*/
function removeTrailingThinkingBlocks(
contentArray: any[],
sessionId?: string,
getCachedSignatureFn?: (sessionId: string, text: string) => string | undefined,
): any[] {
const result = [...contentArray];
while (result.length > 0 && isThinkingPart(result[result.length - 1])) {
const part = result[result.length - 1];
const isValid = sessionId && getCachedSignatureFn
? isOurCachedSignature(part as Record<string, unknown>, sessionId, getCachedSignatureFn)
: hasValidSignature(part as Record<string, unknown>);
if (isValid) {
break;
}
result.pop();
}
return result;
}
/**
* Checks if a thinking part has a valid signature.
* A valid signature is a non-empty string with at least 50 characters.
*/
function hasValidSignature(part: Record<string, unknown>): boolean {
const signature = part.thought === true ? part.thoughtSignature : part.signature;
return typeof signature === "string" && signature.length >= 50;
}
/**
* Gets the signature from a thinking part, if present.
*/
function getSignature(part: Record<string, unknown>): string | undefined {
const signature = part.thought === true ? part.thoughtSignature : part.signature;
return typeof signature === "string" ? signature : undefined;
}
/**
* Checks if a thinking part's signature was generated by our plugin (exists in our cache).
* This prevents accepting signatures from other providers (e.g., direct Anthropic API, OpenAI)
* which would cause "Invalid signature" errors when sent to Antigravity Claude.
*/
function isOurCachedSignature(
part: Record<string, unknown>,
sessionId: string | undefined,
getCachedSignatureFn: ((sessionId: string, text: string) => string | undefined) | undefined,
): boolean {
if (!sessionId || !getCachedSignatureFn) {
return false;
}
const text = getThinkingText(part);
if (!text) {
return false;
}
const partSignature = getSignature(part);
if (!partSignature) {
return false;
}
const cachedSignature = getCachedSignatureFn(sessionId, text);
return cachedSignature === partSignature;