forked from diegosouzapw/OmniRoute
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeminiHelper.ts
More file actions
762 lines (675 loc) · 25.5 KB
/
Copy pathgeminiHelper.ts
File metadata and controls
762 lines (675 loc) · 25.5 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
// Gemini helper functions for translator
import { safeParseJSON } from "./jsonUtil.ts";
type JsonRecord = Record<string, unknown>;
// Unsupported JSON Schema constraints that should be removed for Antigravity.
// `additionalProperties` is handled separately so `true` can be preserved.
export const GEMINI_UNSUPPORTED_SCHEMA_KEYS = new Set([
// Basic constraints (not supported by Gemini API)
"minLength",
"maxLength",
"exclusiveMinimum",
"exclusiveMaximum",
// `multipleOf` is not part of the Gemini/antigravity OpenAPI 3.0 schema subset;
// leaving it in function_declarations triggers a hard upstream 400
// ("Unknown name \"multipleOf\""). `minimum`/`maximum` ARE accepted and kept.
"multipleOf",
// OpenAI "strict" tool-calling mode embeds `strict: true/false` directly inside
// a function's `parameters` schema (RubyLLM and other OpenAI-convention clients
// do this by default). Gemini's function_declarations schema doesn't recognize
// it and 400s the same way ("Unknown name \"strict\" ... Cannot find field").
"strict",
// Codex's multi-agent collaboration tools (spawn_agent / send_message /
// followup_task) mark their `message` parameter schema with a non-standard
// `encrypted: true` annotation (JsonSchema::with_encrypted). Gemini's
// function_declarations schema doesn't recognize it and 400s the same way
// ("Unknown name \"encrypted\" ... Cannot find field").
"encrypted",
// NOTE: `pattern` is intentionally NOT in this set. Antigravity (Gemini-derived
// surface) accepts `pattern` on string constraints, and glob/grep/file-search
// tools depend on it to express their argument regex. Removing it produced
// upstream 400s and wrong-tool semantics (decolua/9router#1368).
"minItems",
"maxItems",
"format",
// Claude rejects these in VALIDATED mode
"default",
"examples",
// JSON Schema meta keywords
"$schema",
"$id",
"$anchor",
"$dynamicRef",
"$dynamicAnchor",
"$vocabulary",
"$comment",
"$defs",
"definitions",
"const",
"$ref",
"ref",
// Object validation keywords (not supported)
"propertyNames",
"patternProperties",
"unevaluatedProperties",
"unevaluatedItems",
"contains",
"minContains",
"maxContains",
// #9617: array uniqueness keyword — agentic-CLI tool schemas (JSON-Schema
// generators) set this routinely and Gemini's schema parser has no field for
// it, rejecting the whole request with "Unknown name \"uniqueItems\"".
// Upstream 9router already strips it alongside `contains` for the same error.
"uniqueItems",
// Complex schema keywords (handled by flattenAnyOfOneOf/mergeAllOf)
"anyOf",
"oneOf",
"allOf",
"not",
// Dependency keywords (not supported)
"dependencies",
"dependentSchemas",
"dependentRequired",
// Other unsupported keywords
"title",
"if",
"then",
"else",
"contentMediaType",
"contentEncoding",
"contentSchema",
"readOnly",
"writeOnly",
// Non-standard schema fields (not recognized by Gemini API)
"deprecated",
"optional",
// VS Code / JSON Language Service extensions injected by GitHub Copilot tools (#1175)
"enumDescriptions",
"markdownDescription",
"markdownEnumDescriptions",
"enumItemLabels",
"tags",
// UI/Styling properties (from Cursor tools - NOT JSON Schema standard)
"cornerRadius",
"fillColor",
"fontFamily",
"fontSize",
"fontWeight",
"gap",
"padding",
"strokeColor",
"strokeThickness",
"textColor",
]);
export const UNSUPPORTED_SCHEMA_CONSTRAINTS = [...GEMINI_UNSUPPORTED_SCHEMA_KEYS];
// Default safety settings for the standard Gemini API surface.
//
// HARM_CATEGORY_CIVIC_INTEGRITY is intentionally NOT included here (#8231): the
// dynamic validation on some models/endpoints rejects it with a hard 400
// (`safety_settings[N]: element predicate failed`), taking down every request
// through that model. The Antigravity/Cloud Code surface already worked around
// this for #5003 (see ANTIGRAVITY_UNSUPPORTED_SAFETY_CATEGORIES in
// open-sse/executors/antigravity.ts) — this drops the same category from the
// standard-path default so behavior is consistent across Gemini surfaces. A
// caller that explicitly supplies safetySettings (including one that itself
// requests CIVIC_INTEGRITY) is still honored as-is — only this unconditional
// default is scoped down.
export const DEFAULT_SAFETY_SETTINGS = [
{ category: "HARM_CATEGORY_HATE_SPEECH", threshold: "OFF" },
{ category: "HARM_CATEGORY_DANGEROUS_CONTENT", threshold: "OFF" },
{ category: "HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold: "OFF" },
{ category: "HARM_CATEGORY_HARASSMENT", threshold: "OFF" },
];
function normalizeAudioMimeType(format: unknown): string {
const normalized =
typeof format === "string" && format.trim() ? format.trim().toLowerCase() : "wav";
if (normalized === "mp3") {
return "audio/mpeg";
}
return `audio/${normalized}`;
}
// Convert OpenAI content to Gemini parts
export function convertOpenAIContentToParts(content: unknown): JsonRecord[] {
const parts: JsonRecord[] = [];
if (typeof content === "string") {
parts.push({ text: content });
} else if (Array.isArray(content)) {
for (const item of content) {
const rec = toRecord(item);
if (rec.type === "text") {
parts.push({ text: rec.text });
} else if (rec.type === "input_audio" || rec.type === "audio") {
const audio = toRecord(rec.input_audio || rec.audio);
if (typeof audio.data === "string" && audio.data) {
parts.push({
inlineData: {
mimeType: normalizeAudioMimeType(audio.format),
data: audio.data.replace(/^data:[a-zA-Z0-9/+-]+;base64,/, ""),
},
});
}
} else if (rec.type === "audio_url") {
// OpenAI-style audio_url (data: URI). Mirrors the image_url data-URL
// parser below but produces an audio inlineData part (#913).
const audioUrl = toRecord(rec.audio_url);
const url = typeof audioUrl.url === "string" ? audioUrl.url : "";
if (url.startsWith("data:")) {
const commaIndex = url.indexOf(",");
if (commaIndex !== -1) {
const mimePart = url.substring(5, commaIndex); // skip "data:"
const data = url.substring(commaIndex + 1);
const mimeType = mimePart.split(";")[0] || "audio/wav";
parts.push({ inlineData: { mimeType, data } });
}
}
} else {
// 1. Handle Gemini native inline_data injected into OpenAI arrays (e.g. Cherry Studio)
const geminiInline = toRecord(rec.inline_data || rec.inlineData);
if (geminiInline?.data) {
parts.push({
inlineData: {
mimeType: String(
geminiInline.mime_type || geminiInline.mimeType || "application/pdf"
),
data: String(geminiInline.data).replace(/^data:[a-zA-Z0-9/+-]+;base64,/, ""),
},
});
continue;
}
// 2. Handle Claude-style source blocks commonly used by AI clients
const source = toRecord(rec.source);
if (source?.type === "base64" && source?.data) {
parts.push({
inlineData: {
mimeType: String(source.media_type || "application/pdf"),
data: String(source.data).replace(/^data:[a-zA-Z0-9/+-]+;base64,/, ""),
},
});
continue;
}
// 3. Handle raw data strings (e.g. {"type": "file", "data": "JVBER...", "mime_type": "..."}).
// Also accept the Responses-API shape {"type":"input_file","file_data":"JVBER...","filename":...}
// AND the OpenAI Chat Completions shape
// {"type":"file","file":{"filename":...,"file_data":"data:<mime>;base64,..."}} so PDFs and
// videos reach Gemini instead of being silently dropped (#2515). Gemini reads
// application/pdf and video/* natively via inlineData, exactly like images.
const file = toRecord(rec.file);
const doc = toRecord(rec.document);
const rawDataStr =
rec.data || rec.file_data || file?.data || file?.file_data || doc?.data || doc?.file_data;
if (typeof rawDataStr === "string" && !rawDataStr.startsWith("http")) {
// Prefer the mime embedded in the data: URI (e.g. application/pdf, video/mp4) so
// documents and videos are not mislabeled as the fallback; the fallback applies
// only to bare base64 that carries no data: prefix.
let mimeType =
rec.mime_type ||
rec.media_type ||
file?.mime_type ||
doc?.mime_type ||
"application/pdf";
if (rawDataStr.startsWith("data:")) {
const commaIndex = rawDataStr.indexOf(",");
if (commaIndex !== -1) {
const parsedMime = rawDataStr.substring(5, commaIndex).split(";")[0];
if (parsedMime) mimeType = parsedMime;
}
}
const rawData = rawDataStr.replace(/^data:[a-zA-Z0-9/+-]+;base64,/, "");
parts.push({
inlineData: {
mimeType: String(mimeType),
data: rawData,
},
});
continue;
}
// 4. Standard OpenAI Data URIs
const imageUrl = toRecord(rec.image_url);
const imageObj = toRecord(rec.image);
const fileUrl = toRecord(rec.file_url);
const fileObj = toRecord(rec.file);
const docObj = toRecord(rec.document);
// `file_url` is a top-level string on the Responses-API input_file shape (#2515).
// `rec.image` (with nested {url}) is emitted by some MCP tool wrappers and
// translation layers as an alternative to `rec.image_url` (#2807).
const fileData =
(typeof rec.file_url === "string" ? rec.file_url : undefined) ||
// AI SDK-style image part: { type: "image", image: "data:...;base64,..." } (#1330)
(typeof rec.image === "string" ? rec.image : undefined) ||
imageUrl?.url ||
imageObj?.url ||
fileUrl?.url ||
fileObj?.url ||
docObj?.url;
if (typeof fileData === "string" && fileData.startsWith("data:")) {
const commaIndex = fileData.indexOf(",");
if (commaIndex !== -1) {
const mimePart = fileData.substring(5, commaIndex); // skip "data:"
const data = fileData.substring(commaIndex + 1);
const mimeType = mimePart.split(";")[0];
parts.push({
inlineData: { mimeType, data },
});
}
} else if (typeof fileData === "string" && /^https?:\/\//i.test(fileData)) {
// Remote URLs cannot be embedded as inlineData (which requires base64),
// but Gemini's Part schema natively accepts `fileData: { fileUri }` for
// HTTP/HTTPS sources — the model fetches the asset itself. Pass the URL
// through instead of dropping it (#2807; ported from upstream PR #344).
// The MIME type is intentionally `image/*` because we do not block on
// a HEAD request to sniff it; Gemini infers the concrete type on fetch.
parts.push({
fileData: { fileUri: fileData, mimeType: "image/*" },
});
}
}
}
}
return parts;
}
// Extract text content from OpenAI content
export function extractTextContent(content: unknown): string {
if (typeof content === "string") return content;
if (Array.isArray(content)) {
return content
.map((item) => toRecord(item))
.filter((c) => c.type === "text")
.map((c) => (typeof c.text === "string" ? c.text : ""))
.join("");
}
return "";
}
// Try parse JSON safely (null fallback on parse error; re-export keeps legacy API).
export function tryParseJSON(str: unknown): unknown {
return safeParseJSON(str, null);
}
// Generate request ID
export function generateRequestId() {
return `agent-${crypto.randomUUID()}`;
}
// Generate session ID
export function generateSessionId() {
const arr = new BigUint64Array(1);
globalThis.crypto.getRandomValues(arr);
const num = arr[0] % 9000000000000000000n;
return `-${num.toString()}`;
}
function cloneSchemaValue(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map((item) => cloneSchemaValue(item));
}
if (value && typeof value === "object") {
return Object.fromEntries(
Object.entries(value).map(([key, nestedValue]) => [key, cloneSchemaValue(nestedValue)])
);
}
return value;
}
function toRecord(value: unknown): JsonRecord {
return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
}
function decodeJsonPointerSegment(segment: unknown): string {
return String(segment).replace(/~1/g, "/").replace(/~0/g, "~");
}
function resolveLocalReference(root: unknown, ref: unknown): unknown | null {
if (typeof ref !== "string" || !ref.startsWith("#/")) return null;
let current: unknown = root;
const segments = ref
.slice(2)
.split("/")
.filter(Boolean)
.map((segment) => decodeJsonPointerSegment(segment));
for (const segment of segments) {
const currentRecord = toRecord(current);
if (!(segment in currentRecord)) {
return null;
}
current = currentRecord[segment];
}
return current;
}
function inlineLocalSchemaRefs(
node: unknown,
root: unknown,
activeRefs: Set<string> = new Set<string>()
): unknown {
if (Array.isArray(node)) {
return node.map((item) => inlineLocalSchemaRefs(item, root, activeRefs));
}
if (!node || typeof node !== "object") {
return node;
}
const record: JsonRecord = { ...toRecord(node) };
const ref = typeof record.$ref === "string" ? record.$ref : "";
if (ref.startsWith("#/$defs/") || ref.startsWith("#/definitions/")) {
const rest = { ...record };
delete rest.$ref;
if (activeRefs.has(ref)) {
return inlineLocalSchemaRefs(rest, root, activeRefs);
}
const resolved = resolveLocalReference(root, ref);
if (!resolved || typeof resolved !== "object") {
return inlineLocalSchemaRefs(rest, root, activeRefs);
}
activeRefs.add(ref);
const merged = {
...toRecord(inlineLocalSchemaRefs(cloneSchemaValue(resolved), root, activeRefs)),
...rest,
};
activeRefs.delete(ref);
return inlineLocalSchemaRefs(merged, root, activeRefs);
}
return Object.fromEntries(
Object.entries(record).map(([key, value]) => [
key,
inlineLocalSchemaRefs(value, root, activeRefs),
])
);
}
// Helper: Remove unsupported keywords recursively from object/array
function removeUnsupportedKeywords(obj: unknown, keywords: Set<string>): void {
if (!obj || typeof obj !== "object") return;
if (Array.isArray(obj)) {
for (const item of obj) {
removeUnsupportedKeywords(item, keywords);
}
return;
}
const record = obj as JsonRecord;
// Delete unsupported *constraint* keywords at the current schema level.
for (const key of Object.keys(record)) {
if (keywords.has(key) || key.startsWith("x-")) {
delete record[key];
}
}
// Recurse into remaining values. `properties` is a map keyed by arbitrary,
// user-defined property NAMES — a tool may legitimately declare a property
// called `pattern`, `enum`, `minLength`, etc. Descend into each property's
// subschema, but never run keyword-deletion against the property names
// themselves, or glob/grep-style tools lose their `pattern` argument (#1368).
for (const [key, value] of Object.entries(record)) {
if (!value || typeof value !== "object") continue;
if (key === "properties" && !Array.isArray(value)) {
for (const subSchema of Object.values(value as JsonRecord)) {
removeUnsupportedKeywords(subSchema, keywords);
}
} else {
removeUnsupportedKeywords(value, keywords);
}
}
}
function normalizeAdditionalProperties(obj: unknown): void {
if (!obj || typeof obj !== "object") return;
if (Array.isArray(obj)) {
for (const item of obj) {
normalizeAdditionalProperties(item);
}
return;
}
const record = obj as JsonRecord;
// Gemini API function_declarations schemas reject `additionalProperties: false`
// with HTTP 400 "Unknown name". Strip only the `false` value (the default-permissive
// case Gemini already enforces). Preserve `additionalProperties: true` as a positive
// signal that the caller wants strict-by-default schema validation
// (Gemini rejects with 400 in that case too, so we keep the original error path
// rather than silently masking it). #12509
if (record.additionalProperties === false) {
delete record.additionalProperties;
}
for (const value of Object.values(record)) {
if (value && typeof value === "object") {
normalizeAdditionalProperties(value);
}
}
}
// Convert const to enum
function convertConstToEnum(obj: unknown): void {
if (!obj || typeof obj !== "object") return;
const record = obj as JsonRecord;
if (record.const !== undefined && !record.enum) {
record.enum = [record.const];
delete record.const;
}
for (const value of Object.values(record)) {
if (value && typeof value === "object") {
convertConstToEnum(value);
}
}
}
// Convert enum values to strings (Gemini requires string enum values)
// For integer types, remove enum entirely as Gemini doesn't support it
function convertEnumValuesToStrings(obj: unknown): void {
if (!obj || typeof obj !== "object") return;
const record = obj as JsonRecord;
if (record.enum && Array.isArray(record.enum)) {
// Gemini only supports enum for string types, not integer
if (record.type === "integer" || record.type === "number") {
delete record.enum;
} else {
record.enum = record.enum.map((v: unknown) => String(v));
if (!record.type) {
record.type = "string";
}
}
}
for (const value of Object.values(record)) {
if (value && typeof value === "object") {
convertEnumValuesToStrings(value);
}
}
}
// Merge allOf schemas
function mergeAllOf(obj: unknown): void {
if (!obj || typeof obj !== "object") return;
const record = obj as JsonRecord;
if (record.allOf && Array.isArray(record.allOf)) {
const merged: { properties?: JsonRecord; required?: string[] } = {};
for (const item of record.allOf) {
const itemRecord = toRecord(item);
const itemProperties = toRecord(itemRecord.properties);
if (Object.keys(itemProperties).length > 0) {
if (!merged.properties) merged.properties = {};
Object.assign(merged.properties, itemProperties);
}
if (itemRecord.required && Array.isArray(itemRecord.required)) {
if (!merged.required) merged.required = [];
for (const req of itemRecord.required) {
if (typeof req === "string" && !merged.required.includes(req)) {
merged.required.push(req);
}
}
}
}
delete record.allOf;
if (merged.properties)
record.properties = { ...toRecord(record.properties), ...merged.properties };
if (merged.required) {
const required = Array.isArray(record.required)
? record.required.filter((item): item is string => typeof item === "string")
: [];
record.required = [...required, ...merged.required];
}
}
for (const value of Object.values(record)) {
if (value && typeof value === "object") {
mergeAllOf(value);
}
}
}
// Select best schema from anyOf/oneOf
function selectBest(items: unknown[]): number {
let bestIdx = 0;
let bestScore = -1;
for (let i = 0; i < items.length; i++) {
const item = toRecord(items[i]);
let score = 0;
const type = item.type;
if (type === "object" || item.properties) {
score = 3;
} else if (type === "array" || item.items) {
score = 2;
} else if (type && type !== "null") {
score = 1;
}
if (score > bestScore) {
bestScore = score;
bestIdx = i;
}
}
return bestIdx;
}
// Flatten anyOf/oneOf
function flattenAnyOfOneOf(obj: unknown): void {
if (!obj || typeof obj !== "object") return;
const record = obj as JsonRecord;
if (record.anyOf && Array.isArray(record.anyOf) && record.anyOf.length > 0) {
const nonNullSchemas = record.anyOf.filter((s) => s && toRecord(s).type !== "null");
if (nonNullSchemas.length > 0) {
const bestIdx = selectBest(nonNullSchemas);
const selected = nonNullSchemas[bestIdx];
delete record.anyOf;
Object.assign(record, toRecord(selected));
}
}
if (record.oneOf && Array.isArray(record.oneOf) && record.oneOf.length > 0) {
const nonNullSchemas = record.oneOf.filter((s) => s && toRecord(s).type !== "null");
if (nonNullSchemas.length > 0) {
const bestIdx = selectBest(nonNullSchemas);
const selected = nonNullSchemas[bestIdx];
delete record.oneOf;
Object.assign(record, toRecord(selected));
}
}
for (const value of Object.values(record)) {
if (value && typeof value === "object") {
flattenAnyOfOneOf(value);
}
}
}
// Flatten type arrays
function flattenTypeArrays(obj: unknown): void {
if (!obj || typeof obj !== "object") return;
const record = obj as JsonRecord;
if (record.type && Array.isArray(record.type)) {
const nonNullTypes = record.type.filter((t) => t !== "null");
record.type = nonNullTypes.length > 0 ? nonNullTypes[0] : "string";
}
for (const value of Object.values(record)) {
if (value && typeof value === "object") {
flattenTypeArrays(value);
}
}
}
// Clean JSON Schema for Antigravity API compatibility - removes unsupported keywords recursively
// Reference: CLIProxyAPI/internal/util/gemini_schema.go
export function cleanJSONSchemaForAntigravity(schema: unknown): unknown {
if (!schema || typeof schema !== "object") return schema;
const root = cloneSchemaValue(schema);
let cleaned = inlineLocalSchemaRefs(root, root);
// Phase 1: Convert and prepare
convertConstToEnum(cleaned);
convertEnumValuesToStrings(cleaned);
// Phase 2: Flatten complex structures
mergeAllOf(cleaned);
flattenAnyOfOneOf(cleaned);
flattenTypeArrays(cleaned);
// Phase 3: Preserve the only supported additionalProperties shape before keyword cleanup.
normalizeAdditionalProperties(cleaned);
// Phase 4: Remove all unsupported keywords at ALL levels (including inside arrays).
removeUnsupportedKeywords(cleaned, GEMINI_UNSUPPORTED_SCHEMA_KEYS);
// Phase 5: Cleanup required fields recursively.
function cleanupRequired(obj: unknown): void {
if (!obj || typeof obj !== "object") return;
const record = obj as JsonRecord;
if (record.required && Array.isArray(record.required) && record.properties) {
const properties = toRecord(record.properties);
const validRequired = record.required.filter(
(field) =>
typeof field === "string" && Object.prototype.hasOwnProperty.call(properties, field)
);
if (validRequired.length === 0) {
delete record.required;
} else {
record.required = validRequired;
}
}
// Recurse into nested objects
for (const value of Object.values(record)) {
if (value && typeof value === "object") {
cleanupRequired(value);
}
}
}
cleanupRequired(cleaned);
// Phase 6: Add placeholder for empty object schemas (Antigravity requirement).
function addPlaceholders(obj: unknown): void {
if (!obj || typeof obj !== "object") return;
const record = obj as JsonRecord;
if (record.type === "object") {
if (!record.properties || Object.keys(toRecord(record.properties)).length === 0) {
record.properties = {
reason: {
type: "string",
description: "Brief explanation of why you are calling this tool",
},
};
record.required = ["reason"];
}
}
// Recurse into nested objects
for (const value of Object.values(record)) {
if (value && typeof value === "object") {
addPlaceholders(value);
}
}
}
addPlaceholders(cleaned);
// Phase 7: Recursive type:"object" injection for nested schemas (#9268).
// Gemini/Vertex requires every node with properties/required to have an explicit
// `type: "object"`. Some clients (e.g. Composio-exported tools) emit nested
// schemas with `properties` but no `type`, causing a Gemini 400. Follow the
// `removeUnsupportedKeywords()`/`addPlaceholders()` visitor pattern.
function injectObjectType(obj: unknown): void {
if (!obj || typeof obj !== "object") return;
if (Array.isArray(obj)) {
for (const item of obj) {
injectObjectType(item);
}
return;
}
const record = obj as JsonRecord;
if (!record.type && (record.properties !== undefined || record.required !== undefined)) {
record.type = "object";
}
// Recurse into remaining values.
for (const value of Object.values(record)) {
if (value && typeof value === "object") {
injectObjectType(value);
}
}
}
injectObjectType(cleaned);
// Phase 8: Ensure array types have an items schema (#10578).
// Gemini strictly requires array parameters to define their `items` schema.
// If an MCP tool defines an array but forgets the items, inject a safe default.
function ensureArrayItems(obj: unknown): void {
if (!obj || typeof obj !== "object") return;
if (Array.isArray(obj)) {
for (const item of obj) {
ensureArrayItems(item);
}
return;
}
const record = obj as JsonRecord;
if (record.type === "array" && !record.items) {
record.items = { type: "string" };
}
// Recurse into remaining values.
for (const value of Object.values(record)) {
if (value && typeof value === "object") {
ensureArrayItems(value);
}
}
}
ensureArrayItems(cleaned);
return cleaned;
}