tuxevil-rotator 4.4.8 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +3 -1
  3. package/package.json +1 -1
  4. package/plugins/opencode-discovery/index.mjs +50 -21
  5. package/src/access-probe.ts +1 -1
  6. package/src/account-store.ts +14 -2
  7. package/src/audio-transcription.ts +1 -0
  8. package/src/auto-model-access.ts +22 -0
  9. package/src/compat/model-specs.ts +7 -0
  10. package/src/compat/schema-sanitizer.ts +420 -287
  11. package/src/compat.ts +110 -66
  12. package/src/config-defaults.ts +7 -0
  13. package/src/fetch-with-retry.ts +294 -16
  14. package/src/idempotency.ts +3 -1
  15. package/src/model-access-api.ts +9 -1
  16. package/src/model-access.ts +2 -2
  17. package/src/notification-poller.ts +9 -1
  18. package/src/provider-catalog-evidence.ts +18 -1
  19. package/src/providers/adapter.ts +10 -0
  20. package/src/providers/credential-helpers.ts +34 -0
  21. package/src/providers/google-antigravity/aicode-eligibility.ts +256 -0
  22. package/src/providers/google-antigravity/aicode-forward.ts +381 -0
  23. package/src/providers/google-antigravity/aicode.ts +478 -0
  24. package/src/providers/google-antigravity/catalog.ts +6 -0
  25. package/src/providers/google-antigravity/code-assist.ts +53 -41
  26. package/src/providers/google-antigravity/dynamic-catalog.ts +72 -7
  27. package/src/providers/google-antigravity/forward.ts +309 -86
  28. package/src/providers/google-antigravity/index.ts +122 -4
  29. package/src/providers/google-antigravity/oauth.ts +22 -12
  30. package/src/providers/google-antigravity/quota.ts +781 -34
  31. package/src/providers/google-antigravity/translators.ts +55 -46
  32. package/src/providers/google-antigravity/twin-payload.ts +231 -0
  33. package/src/providers/ollama/quota.ts +6 -4
  34. package/src/providers/openai-codex/compat.ts +11 -2
  35. package/src/providers/openai-codex/quota.ts +2 -1
  36. package/src/providers/opencode-zen/catalog.ts +159 -13
  37. package/src/providers/opencode-zen/discovery.ts +50 -0
  38. package/src/providers/opencode-zen/index.ts +7 -2
  39. package/src/providers/opencode-zen/quota.ts +14 -1
  40. package/src/proxy.ts +570 -87
  41. package/src/quota-pools.ts +76 -1
  42. package/src/rate-limit-parser.ts +239 -19
  43. package/src/rotator.ts +848 -297
  44. package/src/stream-guards.ts +87 -1
  45. package/src/telemetry.ts +17 -3
  46. package/src/types.ts +184 -9
  47. package/src/validators.ts +3 -0
  48. package/src/web/lib/accounts.ts +2 -0
  49. package/src/web/lib/attention.ts +19 -0
  50. package/src/web/lib/models.ts +6 -1
  51. package/src/web/lib/status.ts +22 -4
  52. package/src/web/pages/AccountDetail.tsx +49 -2
  53. package/src/web/pages/Accounts.tsx +38 -3
  54. package/src/web/pages/ModelAccess.tsx +4 -0
  55. package/src/web/pages/Models.tsx +2 -1
  56. package/src/web/pages/Overview.tsx +15 -1
  57. package/src/web/styles/app.css +73 -3
  58. package/tools/telemetry-receiver/receiver.js +523 -266
@@ -1,292 +1,425 @@
1
- export function isRecord(value: unknown): value is Record<string, unknown> {
2
- return typeof value === "object" && value !== null && !Array.isArray(value);
3
- }
4
-
5
- /**
6
- * Gemini's function_declarations accept a restricted subset of JSON Schema.
7
- * Keywords like `const`, `$schema`, `$ref`, `$defs`, `if/then/else`, `not`,
8
- * `patternProperties`, etc. are not supported and will cause a 400.
9
- * This function recursively strips those unsupported keywords.
10
- */
11
- export function sanitizeGeminiSchema(schema: unknown): unknown {
12
- if (!isRecord(schema)) return schema;
13
-
14
- // Keywords Gemini does not support
15
- const UNSUPPORTED = new Set([
16
- "const", "$schema", "$id", "$ref", "$defs", "definitions",
17
- "if", "then", "else", "not",
18
- "patternProperties", "unevaluatedProperties", "unevaluatedItems",
19
- "contentEncoding", "contentMediaType", "examples",
20
- "exclusiveMinimum", "exclusiveMaximum", "minimum", "maximum",
21
- "multipleOf", "minLength", "maxLength", "pattern",
22
- "minItems", "maxItems", "uniqueItems",
23
- "minProperties", "maxProperties", "propertyNames", "title", "default",
24
- "deprecated",
25
- ]);
26
-
27
- const out: Record<string, unknown> = {};
28
- for (const [key, value] of Object.entries(schema)) {
29
- if (UNSUPPORTED.has(key)) continue;
30
- // Gemini's protobuf layer rejects vendor extensions such as
31
- // x-google-enum-descriptions and x-google-identifier.
32
- if (key.startsWith("x-")) continue;
33
-
34
- if (key === "anyOf" || key === "oneOf" || key === "allOf") {
35
- if (Array.isArray(value)) {
36
- // Special case: all items are pure {const: value} — this is the
37
- // JSON Schema way of writing an enum. Convert to Gemini's `enum` array.
38
- const allConst = value.every(
39
- (item) => isRecord(item) && Object.keys(item).length === 1 && "const" in item,
40
- );
41
- if (allConst) {
42
- out["enum"] = value.map((item) => (item as Record<string, unknown>)["const"]);
43
- // Infer type:string when all const values are strings (covers most tool params)
44
- if (value.every((item) => typeof (item as Record<string, unknown>)["const"] === "string")) {
45
- if (!out["type"]) out["type"] = "string";
46
- }
47
- } else {
48
- const cleaned = value.map(sanitizeGeminiSchema).filter(
49
- // Drop entries that become empty objects after sanitisation
50
- (v) => isRecord(v) && Object.keys(v).length > 0,
51
- );
52
- // If only one variant remains, unwrap it (Gemini prefers flat schemas)
53
- if (cleaned.length === 1) {
54
- Object.assign(out, cleaned[0]);
55
- } else if (cleaned.length > 1) {
56
- out[key] = cleaned;
57
- }
58
- // cleaned.length === 0: skip entirely
59
- }
60
- }
61
- continue;
62
- }
63
-
64
- // Inline union type: `type: ["number","null"]`. Gemini's proto `type`
65
- // field is a single enum, not repeating — collapse to the first non-null
66
- // type and lift nullability into the proto-supported `nullable` flag.
67
- if (key === "type" && Array.isArray(value)) {
68
- const nonNull = (value as unknown[]).filter((t) => t !== "null");
69
- if ((value as unknown[]).includes("null")) out["nullable"] = true;
70
- out["type"] = (nonNull[0] ?? "string");
71
- continue;
72
- }
73
-
74
- if (key === "properties" && isRecord(value)) {
75
- out[key] = Object.fromEntries(
76
- Object.entries(value).map(([k, v]) => [k, sanitizeGeminiSchema(v)]),
77
- );
78
- continue;
79
- }
80
-
81
- if (key === "items") {
82
- out[key] = sanitizeGeminiSchema(value);
83
- continue;
84
- }
85
-
86
- out[key] = isRecord(value) ? sanitizeGeminiSchema(value) : value;
87
- }
88
- return out;
89
- }
90
-
91
- /**
92
- * Lighter sanitization for Claude models routed through Gemini's API.
93
- * Gemini's outer API still validates schemas before routing to Claude, so
94
- * we must remove fields Gemini's protobuf doesn't know about (like `const`,
95
- * `$ref`, etc.). However, unlike the Gemini-native sanitizer, we KEEP
96
- * standard JSON Schema Draft 2020-12 keywords (minimum, maximum, pattern,
97
- * etc.) that Claude requires and that Gemini's API does pass through.
98
- */
99
- export function sanitizeClaudeViaGeminiSchema(schema: unknown): unknown {
100
- if (!isRecord(schema)) return schema;
101
-
102
- // Only remove fields that Gemini's API layer truly rejects at the network level.
103
- // We keep standard Draft 2020-12 keywords but must strip exclusiveMinimum/exclusiveMaximum
104
- // as boolean values (Draft 4) — the API layer rejects them even for Claude-bound requests.
105
- const UNSUPPORTED = new Set([
106
- "$schema", "$id", "$ref", "$defs", "definitions",
107
- "if", "then", "else", "not",
108
- "patternProperties", "unevaluatedProperties", "unevaluatedItems",
109
- "contentEncoding", "contentMediaType",
110
- // Gemini's protobuf layer rejects these regardless of target model
111
- "exclusiveMinimum", "exclusiveMaximum", "propertyNames", "uniqueItems", "deprecated",
112
- ]);
113
-
114
- const out: Record<string, unknown> = {};
115
- for (const [key, value] of Object.entries(schema)) {
116
- if (UNSUPPORTED.has(key)) continue;
117
- // Vendor extensions are not understood by Gemini's outer protobuf API,
118
- // even when the inner request targets Claude.
119
- if (key.startsWith("x-")) continue;
120
-
121
- // `const` is not supported by Gemini's API — convert to a single-value enum
122
- if (key === "const") {
123
- out["enum"] = [value];
124
- continue;
125
- }
126
-
127
- if (key === "anyOf" || key === "oneOf" || key === "allOf") {
128
- if (Array.isArray(value)) {
129
- // Case 1: all items are pure {const: value} — convert to flat enum.
130
- const allPureConst = value.every(
131
- (item) => isRecord(item) && Object.keys(item).length === 1 && "const" in item,
132
- );
133
- if (allPureConst) {
134
- out["enum"] = value.map((item) => (item as Record<string, unknown>)["const"]);
135
- if (value.every((item) => typeof (item as Record<string, unknown>)["const"] === "string")) {
136
- if (!out["type"]) out["type"] = "string";
137
- }
138
- continue;
139
- }
140
-
141
- // Case 2: all items are {type: T, const: V} (same type, each with a const).
142
- // e.g. [{type:"string",const:"fact"},{type:"string",const:"lesson"}]
143
- // Merge into a single flat {type: T, enum: [V1, V2, ...]} — avoids
144
- // the redundant anyOf-with-single-enum pattern that Claude rejects.
145
- const allTypeConst = value.every(
146
- (item) =>
147
- isRecord(item) &&
148
- Object.keys(item).length === 2 &&
149
- "type" in item &&
150
- "const" in item,
151
- );
152
- if (allTypeConst) {
153
- const firstType = (value[0] as Record<string, unknown>)["type"];
154
- const allSameType = value.every((item) => (item as Record<string, unknown>)["type"] === firstType);
155
- if (allSameType) {
156
- if (!out["type"]) out["type"] = firstType;
157
- out["enum"] = value.map((item) => (item as Record<string, unknown>)["const"]);
158
- continue;
159
- }
160
- }
161
-
162
- // Sanitize all variants first.
163
- const cleaned = value.map(sanitizeClaudeViaGeminiSchema).filter(
164
- (v) => isRecord(v) && Object.keys(v).length > 0,
165
- ) as Record<string, unknown>[];
166
-
167
- if (cleaned.length === 0) {
168
- // All variants collapsed to nothing — skip entirely.
169
- continue;
170
- }
171
-
172
- // Case 3: nullable pattern — anyOf/oneOf with exactly one {type:"null"}
173
- // variant and one or more real variants. Convert to the real variant
174
- // with nullable:true. This is lossless — Gemini's proto supports nullable.
175
- // e.g. anyOf:[{type:"string"},{type:"null"}] → {type:"string",nullable:true}
176
- if (key !== "allOf") {
177
- const nullIdx = cleaned.findIndex((v) => v.type === "null" && Object.keys(v).length === 1);
178
- if (nullIdx !== -1) {
179
- const nonNull = cleaned.filter((_, i) => i !== nullIdx);
180
- if (nonNull.length === 1) {
181
- Object.assign(out, nonNull[0], { nullable: true });
182
- continue;
183
- }
184
- if (nonNull.length > 1) {
185
- // Multiple non-null variants + null → collapse non-null variants,
186
- // then mark nullable. Still lossy but preserves nullability.
187
- Object.assign(out, nonNull[0], { nullable: true });
188
- continue;
189
- }
190
- }
191
- }
192
-
193
- // Case 4: allOf — deep merge all variants (allOf = intersection).
194
- // Merging properties from all variants is semantically correct.
195
- if (key === "allOf") {
196
- const merged: Record<string, unknown> = {};
197
- let mergedProperties: Record<string, unknown> = {};
198
- let mergedRequired: string[] = [];
199
- for (const variant of cleaned) {
200
- for (const [vk, vv] of Object.entries(variant)) {
201
- if (vk === "properties" && isRecord(vv)) {
202
- mergedProperties = { ...mergedProperties, ...vv };
203
- } else if (vk === "required" && Array.isArray(vv)) {
204
- mergedRequired = [...new Set([...mergedRequired, ...vv])];
205
- } else {
206
- merged[vk] = vv;
207
- }
208
- }
209
- }
210
- if (Object.keys(mergedProperties).length > 0) merged["properties"] = mergedProperties;
211
- if (mergedRequired.length > 0) merged["required"] = mergedRequired;
212
- Object.assign(out, merged);
213
- continue;
214
- }
215
-
216
- // Case 5: anyOf/oneOf where all variants are objects with properties —
217
- // merge all properties together, making all optional (union of shapes).
218
- // This is mildly lossy (accepts wider input) but doesn't reject valid inputs.
219
- const allObjects = cleaned.every(
220
- (v) => v.type === "object" && isRecord(v.properties),
221
- );
222
- if (allObjects && cleaned.length > 1) {
223
- const unionProperties: Record<string, unknown> = {};
224
- for (const variant of cleaned) {
225
- const props = variant.properties as Record<string, unknown>;
226
- for (const [pk, pv] of Object.entries(props)) {
227
- if (!(pk in unionProperties)) unionProperties[pk] = pv;
228
- }
229
- }
230
- // Only keep required fields that exist in ALL variants
231
- const allRequired = cleaned.map((v) =>
232
- Array.isArray(v.required) ? new Set(v.required as string[]) : new Set<string>(),
233
- );
234
- const commonRequired = [...allRequired[0]].filter((r) =>
235
- allRequired.every((s) => s.has(r)),
236
- );
237
- const base = { ...cleaned[0] };
238
- base["properties"] = unionProperties;
239
- if (commonRequired.length > 0) {
240
- base["required"] = commonRequired;
241
- } else {
242
- delete base["required"];
243
- }
244
- Object.assign(out, base);
245
- continue;
246
- }
247
-
248
- // Fallback: collapse to the first valid variant.
249
- // Gemini's Schema proto serialization corrupts complex anyOf/oneOf
250
- // during the round-trip to Claude, causing JSON Schema draft 2020-12
251
- // validation failures. Collapsing is lossy but functional — the tool
252
- // still works, just with a narrower accepted input type.
253
- Object.assign(out, cleaned[0]);
254
- }
255
- continue;
256
- }
257
-
258
- // Inline union type: `type: ["number","null"]`. Gemini's proto `type`
259
- // field is a single enum, not repeating — an array value triggers a 400
260
- // ('Proto field is not repeating'). Collapse to the first non-null type
261
- // and lift nullability into the proto-supported `nullable` flag.
262
- if (key === "type" && Array.isArray(value)) {
263
- const nonNull = (value as unknown[]).filter((t) => t !== "null");
264
- if ((value as unknown[]).includes("null")) out["nullable"] = true;
265
- out["type"] = (nonNull[0] ?? "string");
266
- continue;
267
- }
268
-
269
- if (key === "properties" && isRecord(value)) {
270
- out[key] = Object.fromEntries(
271
- Object.entries(value).map(([k, v]) => [k, sanitizeClaudeViaGeminiSchema(v)]),
272
- );
273
- continue;
274
- }
275
-
276
- if (key === "items") {
277
- out[key] = sanitizeClaudeViaGeminiSchema(value);
278
- continue;
279
- }
280
-
281
- out[key] = isRecord(value) ? sanitizeClaudeViaGeminiSchema(value) : value;
282
- }
283
- // Gemini's Schema proto accepts only strings in enum, even for Claude-bound
284
- // requests. Preserve the primitive type and drop unsupported enum values.
285
- if (Array.isArray(out.enum) && !out.enum.every((value) => typeof value === "string")) {
286
- if (!out.type && out.enum.length > 0 && out.enum.every((value) => typeof value === "boolean")) {
287
- out.type = "boolean";
1
+ export function isRecord(value: unknown): value is Record<string, unknown> {
2
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3
+ }
4
+
5
+ // Keywords Gemini does not support
6
+ const GEMINI_UNSUPPORTED = new Set([
7
+ "$schema", "$id", "$ref", "$defs", "definitions",
8
+ "if", "then", "else", "not",
9
+ "patternProperties", "unevaluatedProperties", "unevaluatedItems",
10
+ "contentEncoding", "contentMediaType", "examples",
11
+ "exclusiveMinimum", "exclusiveMaximum", "minimum", "maximum",
12
+ "multipleOf", "minLength", "maxLength", "pattern",
13
+ "minItems", "maxItems", "uniqueItems",
14
+ "minProperties", "maxProperties", "propertyNames", "title", "default",
15
+ "deprecated",
16
+ ]);
17
+
18
+ // Only remove fields that Gemini's API layer truly rejects at the network level.
19
+ // We keep standard Draft 2020-12 keywords but must strip exclusiveMinimum/exclusiveMaximum
20
+ // as boolean values (Draft 4) — the API layer rejects them even for Claude-bound requests.
21
+ const CLAUDE_VIA_GEMINI_UNSUPPORTED = new Set([
22
+ "$schema", "$id", "$ref", "$defs", "definitions",
23
+ "if", "then", "else", "not",
24
+ "patternProperties", "unevaluatedProperties", "unevaluatedItems",
25
+ "contentEncoding", "contentMediaType",
26
+ // Gemini's protobuf layer rejects these regardless of target model
27
+ "exclusiveMinimum", "exclusiveMaximum", "propertyNames", "uniqueItems", "deprecated",
28
+ ]);
29
+
30
+ /**
31
+ * Collapse JSON Schema const-literal unions (`[{const: V}, ...]` or
32
+ * `[{type: T, const: V}, ...]`) into a flat `enum` (+ `type` when typed).
33
+ */
34
+ function applyConstUnionToSchema(
35
+ variants: unknown[],
36
+ out: Record<string, unknown>,
37
+ ): boolean {
38
+ if (variants.length === 0) return false;
39
+
40
+ // Case 1: all items are pure {const: value} — JSON Schema way of writing an enum.
41
+ const allPureConst = variants.every(
42
+ (item) => isRecord(item) && Object.keys(item).length === 1 && "const" in item,
43
+ );
44
+ if (allPureConst) {
45
+ out["enum"] = variants.map((item) => (item as Record<string, unknown>)["const"]);
46
+ return true;
47
+ }
48
+
49
+ // Case 2: all items are {type: T, const: V} with the same type.
50
+ // Merge into a single flat {type: T, enum: [V1, V2, ...]} — avoids
51
+ // redundant anyOf wrappers that upstream schema validators reject.
52
+ const allTypeConst = variants.every(
53
+ (item) =>
54
+ isRecord(item) &&
55
+ Object.keys(item).length === 2 &&
56
+ "type" in item &&
57
+ "const" in item,
58
+ );
59
+ if (allTypeConst) {
60
+ const firstType = (variants[0] as Record<string, unknown>)["type"];
61
+ if (
62
+ typeof firstType === "string" &&
63
+ variants.every((item) => (item as Record<string, unknown>)["type"] === firstType)
64
+ ) {
65
+ if (!out["type"]) out["type"] = firstType;
66
+ out["enum"] = variants.map((item) => (item as Record<string, unknown>)["const"]);
67
+ return true;
68
+ }
69
+ }
70
+
71
+ return false;
72
+ }
73
+
74
+ /**
75
+ * Inline union type: `type: ["number","null"]`. Gemini's proto `type`
76
+ * field is a single enum, not repeating — an array value triggers a 400
77
+ * ('Proto field is not repeating'). Collapse to the first non-null type
78
+ * and lift nullability into the proto-supported `nullable` flag.
79
+ */
80
+ function collapseInlineUnionType(
81
+ value: unknown[],
82
+ out: Record<string, unknown>,
83
+ ): void {
84
+ const nonNull = value.filter((t) => t !== "null");
85
+ if (value.includes("null")) out["nullable"] = true;
86
+ out["type"] = nonNull[0] ?? "string";
87
+ }
88
+
89
+ function sanitizeSchemaProperties(
90
+ value: Record<string, unknown>,
91
+ sanitize: (schema: unknown) => unknown,
92
+ ): Record<string, unknown> {
93
+ const result: Record<string, unknown> = {};
94
+ for (const [k, v] of Object.entries(value)) {
95
+ Object.defineProperty(result, k, {
96
+ value: sanitize(v),
97
+ enumerable: true,
98
+ writable: true,
99
+ configurable: true,
100
+ });
101
+ }
102
+ return result;
103
+ }
104
+
105
+ function mergePropertyMaps(
106
+ base: Record<string, unknown> | undefined,
107
+ incoming: Record<string, unknown>,
108
+ overwrite = true,
109
+ ): Record<string, unknown> {
110
+ const merged: Record<string, unknown> = {};
111
+ if (base) {
112
+ for (const [k, v] of Object.entries(base)) {
113
+ Object.defineProperty(merged, k, {
114
+ value: v,
115
+ enumerable: true,
116
+ writable: true,
117
+ configurable: true,
118
+ });
119
+ }
120
+ }
121
+ for (const [k, v] of Object.entries(incoming)) {
122
+ if (!overwrite && Object.hasOwn(merged, k)) continue;
123
+ Object.defineProperty(merged, k, {
124
+ value: v,
125
+ enumerable: true,
126
+ writable: true,
127
+ configurable: true,
128
+ });
129
+ }
130
+ return merged;
131
+ }
132
+
133
+ function mergeSchemaFragment(
134
+ out: Record<string, unknown>,
135
+ fragment: Record<string, unknown>,
136
+ ): void {
137
+ for (const [k, v] of Object.entries(fragment)) {
138
+ if (k === "properties" && isRecord(v)) {
139
+ out["properties"] = mergePropertyMaps(
140
+ isRecord(out["properties"]) ? out["properties"] : undefined,
141
+ v,
142
+ );
143
+ continue;
144
+ }
145
+ if (k === "required" && Array.isArray(v)) {
146
+ const existing = Array.isArray(out["required"]) ? out["required"] : [];
147
+ out["required"] = [...new Set([...existing, ...v])];
148
+ continue;
288
149
  }
150
+ Object.defineProperty(out, k, {
151
+ value: v,
152
+ enumerable: true,
153
+ writable: true,
154
+ configurable: true,
155
+ });
156
+ }
157
+ }
158
+
159
+ function sanitizeSchemaItems(
160
+ value: unknown,
161
+ sanitize: (schema: unknown) => unknown,
162
+ ): unknown {
163
+ if (Array.isArray(value)) {
164
+ return value
165
+ .map(sanitize)
166
+ .find((item) => isRecord(item) && Object.keys(item).length > 0);
167
+ }
168
+ return sanitize(value);
169
+ }
170
+
171
+ /**
172
+ * Gemini's Schema proto accepts only string values in `enum` (for string
173
+ * schemas), even for Claude-bound requests. Preserve primitive type and
174
+ * nullability when possible, and strip incompatible `enum` entries.
175
+ */
176
+ function normalizeGeminiSchemaEnum(out: Record<string, unknown>): void {
177
+ if (!("enum" in out)) return;
178
+
179
+ if (!Array.isArray(out.enum) || out.enum.length === 0) {
180
+ delete out.enum;
181
+ return;
182
+ }
183
+
184
+ const hasNull = out.enum.some((value) => value === null);
185
+ const nonNull = out.enum.filter((value) => value !== null);
186
+ if (nonNull.length === 0) {
289
187
  delete out.enum;
188
+ return;
189
+ }
190
+
191
+ if (nonNull.every((value) => typeof value === "string")) {
192
+ if (hasNull) out.nullable = true;
193
+ if (!out.type) out.type = "string";
194
+ if (typeof out.type === "string" && out.type.toLowerCase() === "string") {
195
+ if (hasNull) out.enum = nonNull;
196
+ return;
197
+ }
198
+ delete out.enum;
199
+ return;
200
+ }
201
+
202
+ if (!out.type) {
203
+ if (nonNull.every((value) => typeof value === "boolean")) {
204
+ out.type = "boolean";
205
+ } else if (
206
+ nonNull.every((value) => typeof value === "number" && Number.isFinite(value))
207
+ ) {
208
+ out.type = nonNull.every((value) => Number.isInteger(value))
209
+ ? "integer"
210
+ : "number";
211
+ }
212
+ }
213
+ if (hasNull && out.type) {
214
+ out.nullable = true;
215
+ }
216
+ delete out.enum;
217
+ }
218
+
219
+ /**
220
+ * Gemini's function_declarations accept a restricted subset of JSON Schema.
221
+ * Keywords like `const`, `$schema`, `$ref`, `$defs`, `if/then/else`, `not`,
222
+ * `patternProperties`, etc. are not supported and will cause a 400.
223
+ * This function recursively strips those unsupported keywords.
224
+ */
225
+ export function sanitizeGeminiSchema(schema: unknown): unknown {
226
+ if (!isRecord(schema)) return schema;
227
+
228
+ const out: Record<string, unknown> = {};
229
+ for (const [key, value] of Object.entries(schema)) {
230
+ if (GEMINI_UNSUPPORTED.has(key)) continue;
231
+ // Gemini's protobuf layer rejects vendor extensions such as
232
+ // x-google-enum-descriptions and x-google-identifier.
233
+ if (key.startsWith("x-")) continue;
234
+
235
+ // `const` is not supported by Gemini's API — convert to a single-value enum
236
+ if (key === "const") {
237
+ out["enum"] = [value];
238
+ continue;
239
+ }
240
+
241
+ if (key === "anyOf" || key === "oneOf" || key === "allOf") {
242
+ if (Array.isArray(value) && !applyConstUnionToSchema(value, out)) {
243
+ const cleaned = value.map(sanitizeGeminiSchema).filter(
244
+ // Drop entries that become empty objects after sanitisation
245
+ (v) => isRecord(v) && Object.keys(v).length > 0,
246
+ );
247
+ // If only one variant remains, unwrap it (Gemini prefers flat schemas)
248
+ if (cleaned.length === 1) {
249
+ Object.assign(out, cleaned[0]);
250
+ } else if (cleaned.length > 1) {
251
+ out[key] = cleaned;
252
+ }
253
+ // cleaned.length === 0: skip entirely
254
+ }
255
+ continue;
256
+ }
257
+
258
+ if (key === "type" && Array.isArray(value)) {
259
+ collapseInlineUnionType(value, out);
260
+ continue;
261
+ }
262
+
263
+ if (key === "properties" && isRecord(value)) {
264
+ out[key] = sanitizeSchemaProperties(value, sanitizeGeminiSchema);
265
+ continue;
266
+ }
267
+
268
+ if (key === "items") {
269
+ const sanitizedItems = sanitizeSchemaItems(value, sanitizeGeminiSchema);
270
+ if (sanitizedItems !== undefined) out[key] = sanitizedItems;
271
+ continue;
272
+ }
273
+
274
+ out[key] = isRecord(value) ? sanitizeGeminiSchema(value) : value;
275
+ }
276
+ normalizeGeminiSchemaEnum(out);
277
+ return out;
278
+ }
279
+
280
+ /**
281
+ * Lighter sanitization for Claude models routed through Gemini's API.
282
+ * Gemini's outer API still validates schemas before routing to Claude, so
283
+ * we must remove fields Gemini's protobuf doesn't know about (like `const`,
284
+ * `$ref`, etc.). However, unlike the Gemini-native sanitizer, we KEEP
285
+ * standard JSON Schema Draft 2020-12 keywords (minimum, maximum, pattern,
286
+ * etc.) that Claude requires and that Gemini's API does pass through.
287
+ */
288
+ export function sanitizeClaudeViaGeminiSchema(schema: unknown): unknown {
289
+ if (!isRecord(schema)) return schema;
290
+
291
+ const out: Record<string, unknown> = {};
292
+ for (const [key, value] of Object.entries(schema)) {
293
+ if (CLAUDE_VIA_GEMINI_UNSUPPORTED.has(key)) continue;
294
+ // Vendor extensions are not understood by Gemini's outer protobuf API,
295
+ // even when the inner request targets Claude.
296
+ if (key.startsWith("x-")) continue;
297
+
298
+ // `const` is not supported by Gemini's API — convert to a single-value enum
299
+ if (key === "const") {
300
+ out["enum"] = [value];
301
+ continue;
302
+ }
303
+
304
+ if (key === "anyOf" || key === "oneOf" || key === "allOf") {
305
+ if (Array.isArray(value) && !applyConstUnionToSchema(value, out)) {
306
+ // Sanitize all variants first.
307
+ const cleaned = value.map(sanitizeClaudeViaGeminiSchema).filter(
308
+ (v) => isRecord(v) && Object.keys(v).length > 0,
309
+ ) as Record<string, unknown>[];
310
+
311
+ if (cleaned.length === 0) {
312
+ // All variants collapsed to nothing — skip entirely.
313
+ continue;
314
+ }
315
+
316
+ // Case 3: nullable pattern — anyOf/oneOf with exactly one {type:"null"}
317
+ // variant and one or more real variants. Convert to the real variant
318
+ // with nullable:true. This is lossless — Gemini's proto supports nullable.
319
+ // e.g. anyOf:[{type:"string"},{type:"null"}] → {type:"string",nullable:true}
320
+ if (key !== "allOf") {
321
+ const nullIdx = cleaned.findIndex((v) => v.type === "null" && Object.keys(v).length === 1);
322
+ if (nullIdx !== -1) {
323
+ const nonNull = cleaned.filter((_, i) => i !== nullIdx);
324
+ if (nonNull.length >= 1) {
325
+ mergeSchemaFragment(out, nonNull[0]);
326
+ out["nullable"] = true;
327
+ continue;
328
+ }
329
+ }
330
+ }
331
+
332
+ // Case 4: allOf — deep merge all variants (allOf = intersection).
333
+ // Merging properties from all variants is semantically correct.
334
+ if (key === "allOf") {
335
+ const merged: Record<string, unknown> = {};
336
+ let mergedProperties: Record<string, unknown> = {};
337
+ let mergedRequired: string[] = [];
338
+ for (const variant of cleaned) {
339
+ for (const [vk, vv] of Object.entries(variant)) {
340
+ if (vk === "properties" && isRecord(vv)) {
341
+ mergedProperties = mergePropertyMaps(mergedProperties, vv);
342
+ } else if (vk === "required" && Array.isArray(vv)) {
343
+ mergedRequired = [...new Set([...mergedRequired, ...vv])];
344
+ } else {
345
+ merged[vk] = vv;
346
+ }
347
+ }
348
+ }
349
+ if (Object.keys(mergedProperties).length > 0) merged["properties"] = mergedProperties;
350
+ if (mergedRequired.length > 0) merged["required"] = mergedRequired;
351
+ mergeSchemaFragment(out, merged);
352
+ continue;
353
+ }
354
+
355
+ // Case 5: anyOf/oneOf where all variants are objects with properties —
356
+ // merge all properties together, making all optional (union of shapes).
357
+ // This is mildly lossy (accepts wider input) but doesn't reject valid inputs.
358
+ const allObjects = cleaned.every(
359
+ (v) => v.type === "object" && isRecord(v.properties),
360
+ );
361
+ if (allObjects && cleaned.length > 1) {
362
+ let unionProperties: Record<string, unknown> = {};
363
+ for (const variant of cleaned) {
364
+ const props = variant.properties as Record<string, unknown>;
365
+ unionProperties = mergePropertyMaps(unionProperties, props, false);
366
+ }
367
+ // Only keep required fields that exist in ALL variants
368
+ const allRequired = cleaned.map((v) =>
369
+ Array.isArray(v.required) ? new Set(v.required as string[]) : new Set<string>(),
370
+ );
371
+ const commonRequired = [...allRequired[0]].filter((r) =>
372
+ allRequired.every((s) => s.has(r)),
373
+ );
374
+ const base = { ...cleaned[0] };
375
+ base["properties"] = unionProperties;
376
+ if (commonRequired.length > 0) {
377
+ base["required"] = commonRequired;
378
+ } else {
379
+ delete base["required"];
380
+ }
381
+ mergeSchemaFragment(out, base);
382
+ continue;
383
+ }
384
+
385
+ // Fallback: collapse to the first valid variant.
386
+ // Gemini's Schema proto serialization corrupts complex anyOf/oneOf
387
+ // during the round-trip to Claude, causing JSON Schema draft 2020-12
388
+ // validation failures. Collapsing is lossy but functional — the tool
389
+ // still works, just with a narrower accepted input type.
390
+ mergeSchemaFragment(out, cleaned[0]);
391
+ }
392
+ continue;
393
+ }
394
+
395
+ if (key === "type" && Array.isArray(value)) {
396
+ collapseInlineUnionType(value, out);
397
+ continue;
398
+ }
399
+
400
+ if (key === "properties" && isRecord(value)) {
401
+ const sanitizedProps = sanitizeSchemaProperties(value, sanitizeClaudeViaGeminiSchema);
402
+ out[key] = mergePropertyMaps(
403
+ isRecord(out[key]) ? (out[key] as Record<string, unknown>) : undefined,
404
+ sanitizedProps,
405
+ );
406
+ continue;
407
+ }
408
+
409
+ if (key === "required" && Array.isArray(value)) {
410
+ const existing = Array.isArray(out[key]) ? (out[key] as unknown[]) : [];
411
+ out[key] = [...new Set([...existing, ...value])];
412
+ continue;
413
+ }
414
+
415
+ if (key === "items") {
416
+ const sanitizedItems = sanitizeSchemaItems(value, sanitizeClaudeViaGeminiSchema);
417
+ if (sanitizedItems !== undefined) out[key] = sanitizedItems;
418
+ continue;
419
+ }
420
+
421
+ out[key] = isRecord(value) ? sanitizeClaudeViaGeminiSchema(value) : value;
290
422
  }
423
+ normalizeGeminiSchemaEnum(out);
291
424
  return out;
292
425
  }