pi-antigravity-rotator 2.2.1 → 2.2.2

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.
package/CHANGELOG.md CHANGED
@@ -2,13 +2,21 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [2.2.2] - 2026-06-21
6
+
7
+ ### Fixed
8
+ - **Telemetry HTTPS Error**: Reverted the default telemetry endpoint from `https://` back to `http://` because the backend server does not support SSL, which was causing silent "packet length too long" errors and preventing telemetry and broadcast notifications from working.
9
+
10
+ ### Refactored
11
+ - **Compatibility Layer**: Massively refactored the 2,400-line `src/compat.ts` into smaller, single-responsibility modules under `src/compat/` for easier maintenance. (PR [#11](https://github.com/tuxevil/pi-antigravity-rotator/pull/11) by [@josenicomaia](https://github.com/josenicomaia))
12
+
5
13
  ## [2.2.1] - 2026-06-20
6
14
 
7
15
  ### Fixed
8
- - **Support tool response images**: Extracted any image content (`image_url` or `image` formats) from OpenAI tool response content and mapped them to Antigravity `inlineData` parts.
9
- - **Ordered tool results**: Guaranteed all tool results remain clustered at the top of the parts array, complying with Claude's strict layout requirements.
10
- - **Dangling tool call filtering**: Filtered out any `tool_calls` that do not have a matching `tool_result` in the subsequent message to prevent `400 Bad Request`.
11
- - **Inline JSON-Schema union types**: Collapsed Draft-2020-12 inline union type arrays (e.g. `type: ["number", "null"]`) to the first non-null type and lifted nullability into the proto-supported `nullable` flag to fix 400 errors.
16
+ - **Support tool response images**: Extracted any image content (`image_url` or `image` formats) from OpenAI tool response content and mapped them to Antigravity `inlineData` parts. (PR [#9](https://github.com/tuxevil/pi-antigravity-rotator/pull/9) by [@josenicomaia](https://github.com/josenicomaia))
17
+ - **Ordered tool results**: Guaranteed all tool results remain clustered at the top of the parts array, complying with Claude's strict layout requirements. (PR [#9](https://github.com/tuxevil/pi-antigravity-rotator/pull/9) by [@josenicomaia](https://github.com/josenicomaia))
18
+ - **Dangling tool call filtering**: Filtered out any `tool_calls` that do not have a matching `tool_result` in the subsequent message to prevent `400 Bad Request`. (PR [#9](https://github.com/tuxevil/pi-antigravity-rotator/pull/9) by [@josenicomaia](https://github.com/josenicomaia))
19
+ - **Inline JSON-Schema union types**: Collapsed Draft-2020-12 inline union type arrays (e.g. `type: ["number", "null"]`) to the first non-null type and lifted nullability into the proto-supported `nullable` flag to fix 400 errors. (PR [#10](https://github.com/tuxevil/pi-antigravity-rotator/pull/10) by [@yashyadav711](https://github.com/yashyadav711))
12
20
 
13
21
  ## [2.2.0] - 2026-06-16
14
22
 
package/README.md CHANGED
@@ -153,7 +153,7 @@ If login fails at project discovery:
153
153
 
154
154
  After starting the proxy, open `http://localhost:51200/dashboard` or `http://<your-server-ip>:51200/dashboard` from any machine on the same network (the proxy binds to `0.0.0.0`).
155
155
 
156
- If `PI_ROTATOR_ADMIN_TOKEN` is unset, dashboard and `/api/*` access remains open for backwards compatibility. v2.0 now surfaces loud warnings about that state in startup logs, `/api/status`, and the dashboard itself.
156
+ If `PI_ROTATOR_ADMIN_TOKEN` is unset, the proxy automatically generates a cryptographically secure token on first run and saves it to a `.admin-token` file in the root directory. This token will be printed to the console on first startup. You must append `?token=<your-token>` to the dashboard URL to access it, or set `PI_ROTATOR_ADMIN_TOKEN` in your environment to override it.
157
157
 
158
158
  The dashboard shows:
159
159
 
@@ -285,7 +285,7 @@ Config files (`accounts.json`, `state.json`) are stored in `~/.pi-antigravity-ro
285
285
  # Environment variables
286
286
  export PI_ROTATOR_DIR=/path/to/config
287
287
  export PI_ROTATOR_QUOTA_USER_AGENT="antigravity/1.107.0 darwin/arm64"
288
- # Optional: require this token for dashboard/API access. If unset, legacy open access is preserved.
288
+ # Optional: require this token for dashboard/API access. If unset, a secure token is auto-generated.
289
289
  export PI_ROTATOR_ADMIN_TOKEN="change-me"
290
290
  # Optional: bind the proxy to a safer local-only interface.
291
291
  export PI_ROTATOR_BIND_HOST="127.0.0.1"
@@ -410,7 +410,7 @@ Login now fails if Google does not return a project ID. No shared fallback.
410
410
  | `POST` | `/v1/chat/completions` | OpenAI-compatible non-streaming chat adapter |
411
411
  | `POST` | `/v1/messages` | Anthropic-compatible non-streaming messages adapter |
412
412
 
413
- If `PI_ROTATOR_ADMIN_TOKEN` is set, dashboard/API requests must include either `Authorization: Bearer <token>`, `X-Rotator-Admin-Token: <token>`, or `?token=<token>` for browser dashboard access. The native pi proxy endpoint and compatibility adapters remain unauthenticated so existing clients keep working. Put this service behind a trusted local boundary if exposing beyond localhost/LAN.
413
+ Dashboard and internal `/api/*` requests must include either `Authorization: Bearer <token>`, `X-Rotator-Admin-Token: <token>`, or `?token=<token>` for browser dashboard access. The native pi proxy endpoint and compatibility adapters (`/v1/*`) remain unauthenticated by design, so your AI agents and existing clients will keep working without requiring a token. Put this service behind a trusted local boundary if exposing beyond localhost/LAN.
414
414
 
415
415
  ### Compatibility Adapters
416
416
 
@@ -471,7 +471,8 @@ Current adapter scope:
471
471
 
472
472
  Thanks to these amazing people who have contributed to the project:
473
473
 
474
- - **[@josenicomaia](https://github.com/josenicomaia)** (José Nicodemos Maia Neto) — Fixed streaming pass-through to emit correct `finish_reason` for tool calls, fixing tool execution on ZED editor. ([PR #8](https://github.com/tuxevil/pi-antigravity-rotator/pull/8))
474
+ - **[@josenicomaia](https://github.com/josenicomaia)** (José Nicodemos Maia Neto) — Modularized the compatibility layer architecture, added multimodal tool response support, and fixed streaming pass-through for tool executions. ([PR #8](https://github.com/tuxevil/pi-antigravity-rotator/pull/8), [PR #9](https://github.com/tuxevil/pi-antigravity-rotator/pull/9), [PR #11](https://github.com/tuxevil/pi-antigravity-rotator/pull/11))
475
+ - **[@yashyadav711](https://github.com/yashyadav711)** (Yash) — Fixed Draft-2020-12 inline JSON-Schema union type mapping for Gemini tools support. ([PR #10](https://github.com/tuxevil/pi-antigravity-rotator/pull/10))
475
476
  - **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, and compat test suite expansion. ([PR #3](https://github.com/tuxevil/pi-antigravity-rotator/pull/3), [PR #7](https://github.com/tuxevil/pi-antigravity-rotator/pull/7))
476
477
 
477
478
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-antigravity-rotator",
3
- "version": "2.2.1",
3
+ "version": "2.2.2",
4
4
  "description": "Multi-account rotation proxy for Google Antigravity with per-model routing, real-time quota tracking, and infringement detection",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -42,11 +42,13 @@
42
42
  },
43
43
  "author": "Sebastián Real (tuxevil)",
44
44
  "dependencies": {
45
+ "pg": "^8.22.0",
45
46
  "tsx": "^4.19.0"
46
47
  },
47
48
  "devDependencies": {
48
49
  "@eslint/js": "^10.0.1",
49
50
  "@types/node": "^22.0.0",
51
+ "@types/pg": "^8.20.0",
50
52
  "c8": "^11.0.0",
51
53
  "eslint": "^10.5.0",
52
54
  "typescript": "^5.7.0",
@@ -0,0 +1,42 @@
1
+ import { ResponsesStore, type StoredResponseEntry } from "../responses-store.js";
2
+
3
+ export const thoughtSignatureCache = new Map<string, string>();
4
+ const THOUGHT_SIGNATURE_CACHE_MAX = 500;
5
+ export const responsesStore = new ResponsesStore();
6
+
7
+ export function makeCompatId(prefix: string): string {
8
+ return `${prefix}_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
9
+ }
10
+
11
+ export function getStoredResponse(id: string): StoredResponseEntry | null {
12
+ return responsesStore.get(id);
13
+ }
14
+
15
+ export function setStoredResponse(id: string, entry: StoredResponseEntry): void {
16
+ responsesStore.set(id, entry);
17
+ }
18
+
19
+ export function resetResponsesStoreForTests(): void {
20
+ responsesStore.clear();
21
+ }
22
+
23
+ export async function loadResponsesStore(): Promise<void> {
24
+ await responsesStore.load();
25
+ }
26
+
27
+ export async function flushResponsesStore(): Promise<void> {
28
+ await responsesStore.flush();
29
+ }
30
+
31
+ export function flushResponsesStoreSync(): void {
32
+ responsesStore.flushSync();
33
+ }
34
+
35
+ export function cacheThoughtSignature(callId: string, signature: string): void {
36
+ if (thoughtSignatureCache.size >= THOUGHT_SIGNATURE_CACHE_MAX) {
37
+ // Evict the oldest entry
38
+ const firstKey = thoughtSignatureCache.keys().next().value;
39
+ if (firstKey !== undefined) thoughtSignatureCache.delete(firstKey);
40
+ }
41
+ thoughtSignatureCache.set(callId, signature);
42
+ }
@@ -0,0 +1,78 @@
1
+ export interface ModelSpec {
2
+ maxOutputTokens: number;
3
+ thinkingBudget: number; // -1 = adaptive (model decides), >=0 = fixed
4
+ isThinking: boolean;
5
+ }
6
+
7
+ export const DEFAULT_MODEL_SPECS: Record<string, ModelSpec> = {
8
+ "gemini-pro-agent": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true },
9
+ "gemini-3-flash-agent": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true },
10
+ "gemini-3-pro-high": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true },
11
+ "gemini-3-pro-low": { maxOutputTokens: 65535, thinkingBudget: 1001, isThinking: true },
12
+ "gemini-3.1-pro": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true },
13
+ "gemini-3.1-pro-high": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true },
14
+ "gemini-3.1-pro-low": { maxOutputTokens: 65535, thinkingBudget: 1001, isThinking: true },
15
+ "gemini-3.1-pro-preview": { maxOutputTokens: 65535, thinkingBudget: 10001, isThinking: true },
16
+ "gemini-3.5-flash": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true },
17
+ "gemini-3.5-flash-medium": { maxOutputTokens: 65536, thinkingBudget: 4000, isThinking: true },
18
+ "gemini-3.5-flash-low": { maxOutputTokens: 65536, thinkingBudget: 4000, isThinking: true },
19
+ "gemini-3.5-flash-high": { maxOutputTokens: 65536, thinkingBudget: 10000, isThinking: true },
20
+ "gemini-3-flash": { maxOutputTokens: 65536, thinkingBudget: 4000, isThinking: true },
21
+ "gemini-2.5-flash": { maxOutputTokens: 65535, thinkingBudget: 24576, isThinking: true },
22
+ "gemini-2.5-pro": { maxOutputTokens: 65535, thinkingBudget: 1024, isThinking: true },
23
+ "claude-sonnet-4-6": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true },
24
+ "claude-sonnet-4-6-thinking":{ maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true },
25
+ "claude-opus-4-6-thinking": { maxOutputTokens: 64000, thinkingBudget: 32768, isThinking: true },
26
+ "gpt-oss-120b-medium": { maxOutputTokens: 32768, thinkingBudget: 8192, isThinking: true },
27
+ "gpt-oss-120b": { maxOutputTokens: 32768, thinkingBudget: 8192, isThinking: true },
28
+ };
29
+
30
+ let modelSpecsOverride: Record<string, ModelSpec> | null = null;
31
+
32
+ /**
33
+ * Replace the bundled model spec table with operator-provided overrides.
34
+ * Pass `null` to restore defaults. Called once at startup from index.ts.
35
+ */
36
+ export function setModelSpecsOverride(specs: Record<string, ModelSpec> | null): void {
37
+ modelSpecsOverride = specs && Object.keys(specs).length > 0 ? specs : null;
38
+ }
39
+
40
+ export function getActiveModelSpecs(): Record<string, ModelSpec> {
41
+ return modelSpecsOverride ?? DEFAULT_MODEL_SPECS;
42
+ }
43
+
44
+ const GEMINI_MAX_OUTPUT_TOKENS = 65536;
45
+ const CLAUDE_MAX_OUTPUT_TOKENS = 64000;
46
+ const FALLBACK_THINKING_BUDGET = 24576;
47
+ const CLAUDE_DEFAULT_THINKING_BUDGET = 32768;
48
+
49
+ export function getModelFamily(model: string): "claude" | "gemini" | "unknown" {
50
+ const l = model.toLowerCase();
51
+ if (l.includes("claude")) return "claude";
52
+ if (l.includes("gemini")) return "gemini";
53
+ return "unknown";
54
+ }
55
+
56
+ export function getModelSpec(model: string): ModelSpec {
57
+ const specs = getActiveModelSpecs();
58
+ const lower = model.toLowerCase();
59
+ if (specs[lower]) return specs[lower];
60
+ for (const [key, spec] of Object.entries(specs)) {
61
+ if (lower.includes(key)) return spec;
62
+ }
63
+ const family = getModelFamily(model);
64
+ if (family === "claude") return { maxOutputTokens: CLAUDE_MAX_OUTPUT_TOKENS, thinkingBudget: CLAUDE_DEFAULT_THINKING_BUDGET, isThinking: true };
65
+ if (family === "gemini") return { maxOutputTokens: GEMINI_MAX_OUTPUT_TOKENS, thinkingBudget: FALLBACK_THINKING_BUDGET, isThinking: true };
66
+ return { maxOutputTokens: 65536, thinkingBudget: FALLBACK_THINKING_BUDGET, isThinking: false };
67
+ }
68
+
69
+ export function isThinkingModel(model: string): boolean {
70
+ const spec = getModelSpec(model);
71
+ if (spec.isThinking) return true;
72
+ const l = model.toLowerCase();
73
+ if (l.includes("gemini")) {
74
+ const m = l.match(/gemini-(\d+)/);
75
+ if (m && parseInt(m[1], 10) >= 3) return true;
76
+ }
77
+ return false;
78
+ }
@@ -0,0 +1,277 @@
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", "title", "default",
24
+ ]);
25
+
26
+ const out: Record<string, unknown> = {};
27
+ for (const [key, value] of Object.entries(schema)) {
28
+ if (UNSUPPORTED.has(key)) continue;
29
+
30
+ if (key === "anyOf" || key === "oneOf" || key === "allOf") {
31
+ if (Array.isArray(value)) {
32
+ // Special case: all items are pure {const: value} — this is the
33
+ // JSON Schema way of writing an enum. Convert to Gemini's `enum` array.
34
+ const allConst = value.every(
35
+ (item) => isRecord(item) && Object.keys(item).length === 1 && "const" in item,
36
+ );
37
+ if (allConst) {
38
+ out["enum"] = value.map((item) => (item as Record<string, unknown>)["const"]);
39
+ // Infer type:string when all const values are strings (covers most tool params)
40
+ if (value.every((item) => typeof (item as Record<string, unknown>)["const"] === "string")) {
41
+ if (!out["type"]) out["type"] = "string";
42
+ }
43
+ } else {
44
+ const cleaned = value.map(sanitizeGeminiSchema).filter(
45
+ // Drop entries that become empty objects after sanitisation
46
+ (v) => isRecord(v) && Object.keys(v).length > 0,
47
+ );
48
+ // If only one variant remains, unwrap it (Gemini prefers flat schemas)
49
+ if (cleaned.length === 1) {
50
+ Object.assign(out, cleaned[0]);
51
+ } else if (cleaned.length > 1) {
52
+ out[key] = cleaned;
53
+ }
54
+ // cleaned.length === 0: skip entirely
55
+ }
56
+ }
57
+ continue;
58
+ }
59
+
60
+ // Inline union type: `type: ["number","null"]`. Gemini's proto `type`
61
+ // field is a single enum, not repeating — collapse to the first non-null
62
+ // type and lift nullability into the proto-supported `nullable` flag.
63
+ if (key === "type" && Array.isArray(value)) {
64
+ const nonNull = (value as unknown[]).filter((t) => t !== "null");
65
+ if ((value as unknown[]).includes("null")) out["nullable"] = true;
66
+ out["type"] = (nonNull[0] ?? "string");
67
+ continue;
68
+ }
69
+
70
+ if (key === "properties" && isRecord(value)) {
71
+ out[key] = Object.fromEntries(
72
+ Object.entries(value).map(([k, v]) => [k, sanitizeGeminiSchema(v)]),
73
+ );
74
+ continue;
75
+ }
76
+
77
+ if (key === "items") {
78
+ out[key] = sanitizeGeminiSchema(value);
79
+ continue;
80
+ }
81
+
82
+ out[key] = isRecord(value) ? sanitizeGeminiSchema(value) : value;
83
+ }
84
+ return out;
85
+ }
86
+
87
+ /**
88
+ * Lighter sanitization for Claude models routed through Gemini's API.
89
+ * Gemini's outer API still validates schemas before routing to Claude, so
90
+ * we must remove fields Gemini's protobuf doesn't know about (like `const`,
91
+ * `$ref`, etc.). However, unlike the Gemini-native sanitizer, we KEEP
92
+ * standard JSON Schema Draft 2020-12 keywords (minimum, maximum, pattern,
93
+ * etc.) that Claude requires and that Gemini's API does pass through.
94
+ */
95
+ export function sanitizeClaudeViaGeminiSchema(schema: unknown): unknown {
96
+ if (!isRecord(schema)) return schema;
97
+
98
+ // Only remove fields that Gemini's API layer truly rejects at the network level.
99
+ // We keep standard Draft 2020-12 keywords but must strip exclusiveMinimum/exclusiveMaximum
100
+ // as boolean values (Draft 4) — the API layer rejects them even for Claude-bound requests.
101
+ const UNSUPPORTED = new Set([
102
+ "$schema", "$id", "$ref", "$defs", "definitions",
103
+ "if", "then", "else", "not",
104
+ "patternProperties", "unevaluatedProperties", "unevaluatedItems",
105
+ "contentEncoding", "contentMediaType",
106
+ // Gemini's protobuf layer rejects these regardless of target model
107
+ "exclusiveMinimum", "exclusiveMaximum",
108
+ ]);
109
+
110
+ const out: Record<string, unknown> = {};
111
+ for (const [key, value] of Object.entries(schema)) {
112
+ if (UNSUPPORTED.has(key)) continue;
113
+
114
+ // `const` is not supported by Gemini's API — convert to a single-value enum
115
+ if (key === "const") {
116
+ out["enum"] = [value];
117
+ continue;
118
+ }
119
+
120
+ if (key === "anyOf" || key === "oneOf" || key === "allOf") {
121
+ if (Array.isArray(value)) {
122
+ // Case 1: all items are pure {const: value} — convert to flat enum.
123
+ const allPureConst = value.every(
124
+ (item) => isRecord(item) && Object.keys(item).length === 1 && "const" in item,
125
+ );
126
+ if (allPureConst) {
127
+ out["enum"] = value.map((item) => (item as Record<string, unknown>)["const"]);
128
+ if (value.every((item) => typeof (item as Record<string, unknown>)["const"] === "string")) {
129
+ if (!out["type"]) out["type"] = "string";
130
+ }
131
+ continue;
132
+ }
133
+
134
+ // Case 2: all items are {type: T, const: V} (same type, each with a const).
135
+ // e.g. [{type:"string",const:"fact"},{type:"string",const:"lesson"}]
136
+ // Merge into a single flat {type: T, enum: [V1, V2, ...]} — avoids
137
+ // the redundant anyOf-with-single-enum pattern that Claude rejects.
138
+ const allTypeConst = value.every(
139
+ (item) =>
140
+ isRecord(item) &&
141
+ Object.keys(item).length === 2 &&
142
+ "type" in item &&
143
+ "const" in item,
144
+ );
145
+ if (allTypeConst) {
146
+ const firstType = (value[0] as Record<string, unknown>)["type"];
147
+ const allSameType = value.every((item) => (item as Record<string, unknown>)["type"] === firstType);
148
+ if (allSameType) {
149
+ if (!out["type"]) out["type"] = firstType;
150
+ out["enum"] = value.map((item) => (item as Record<string, unknown>)["const"]);
151
+ continue;
152
+ }
153
+ }
154
+
155
+ // Sanitize all variants first.
156
+ const cleaned = value.map(sanitizeClaudeViaGeminiSchema).filter(
157
+ (v) => isRecord(v) && Object.keys(v).length > 0,
158
+ ) as Record<string, unknown>[];
159
+
160
+ if (cleaned.length === 0) {
161
+ // All variants collapsed to nothing — skip entirely.
162
+ continue;
163
+ }
164
+
165
+ // Case 3: nullable pattern — anyOf/oneOf with exactly one {type:"null"}
166
+ // variant and one or more real variants. Convert to the real variant
167
+ // with nullable:true. This is lossless — Gemini's proto supports nullable.
168
+ // e.g. anyOf:[{type:"string"},{type:"null"}] → {type:"string",nullable:true}
169
+ if (key !== "allOf") {
170
+ const nullIdx = cleaned.findIndex((v) => v.type === "null" && Object.keys(v).length === 1);
171
+ if (nullIdx !== -1) {
172
+ const nonNull = cleaned.filter((_, i) => i !== nullIdx);
173
+ if (nonNull.length === 1) {
174
+ Object.assign(out, nonNull[0], { nullable: true });
175
+ continue;
176
+ }
177
+ if (nonNull.length > 1) {
178
+ // Multiple non-null variants + null → collapse non-null variants,
179
+ // then mark nullable. Still lossy but preserves nullability.
180
+ Object.assign(out, nonNull[0], { nullable: true });
181
+ continue;
182
+ }
183
+ }
184
+ }
185
+
186
+ // Case 4: allOf — deep merge all variants (allOf = intersection).
187
+ // Merging properties from all variants is semantically correct.
188
+ if (key === "allOf") {
189
+ const merged: Record<string, unknown> = {};
190
+ let mergedProperties: Record<string, unknown> = {};
191
+ let mergedRequired: string[] = [];
192
+ for (const variant of cleaned) {
193
+ for (const [vk, vv] of Object.entries(variant)) {
194
+ if (vk === "properties" && isRecord(vv)) {
195
+ mergedProperties = { ...mergedProperties, ...vv };
196
+ } else if (vk === "required" && Array.isArray(vv)) {
197
+ mergedRequired = [...new Set([...mergedRequired, ...vv])];
198
+ } else {
199
+ merged[vk] = vv;
200
+ }
201
+ }
202
+ }
203
+ if (Object.keys(mergedProperties).length > 0) merged["properties"] = mergedProperties;
204
+ if (mergedRequired.length > 0) merged["required"] = mergedRequired;
205
+ Object.assign(out, merged);
206
+ continue;
207
+ }
208
+
209
+ // Case 5: anyOf/oneOf where all variants are objects with properties —
210
+ // merge all properties together, making all optional (union of shapes).
211
+ // This is mildly lossy (accepts wider input) but doesn't reject valid inputs.
212
+ const allObjects = cleaned.every(
213
+ (v) => v.type === "object" && isRecord(v.properties),
214
+ );
215
+ if (allObjects && cleaned.length > 1) {
216
+ const unionProperties: Record<string, unknown> = {};
217
+ for (const variant of cleaned) {
218
+ const props = variant.properties as Record<string, unknown>;
219
+ for (const [pk, pv] of Object.entries(props)) {
220
+ if (!(pk in unionProperties)) unionProperties[pk] = pv;
221
+ }
222
+ }
223
+ // Only keep required fields that exist in ALL variants
224
+ const allRequired = cleaned.map((v) =>
225
+ Array.isArray(v.required) ? new Set(v.required as string[]) : new Set<string>(),
226
+ );
227
+ const commonRequired = [...allRequired[0]].filter((r) =>
228
+ allRequired.every((s) => s.has(r)),
229
+ );
230
+ const base = { ...cleaned[0] };
231
+ base["properties"] = unionProperties;
232
+ if (commonRequired.length > 0) {
233
+ base["required"] = commonRequired;
234
+ } else {
235
+ delete base["required"];
236
+ }
237
+ Object.assign(out, base);
238
+ continue;
239
+ }
240
+
241
+ // Fallback: collapse to the first valid variant.
242
+ // Gemini's Schema proto serialization corrupts complex anyOf/oneOf
243
+ // during the round-trip to Claude, causing JSON Schema draft 2020-12
244
+ // validation failures. Collapsing is lossy but functional — the tool
245
+ // still works, just with a narrower accepted input type.
246
+ Object.assign(out, cleaned[0]);
247
+ }
248
+ continue;
249
+ }
250
+
251
+ // Inline union type: `type: ["number","null"]`. Gemini's proto `type`
252
+ // field is a single enum, not repeating — an array value triggers a 400
253
+ // ('Proto field is not repeating'). Collapse to the first non-null type
254
+ // and lift nullability into the proto-supported `nullable` flag.
255
+ if (key === "type" && Array.isArray(value)) {
256
+ const nonNull = (value as unknown[]).filter((t) => t !== "null");
257
+ if ((value as unknown[]).includes("null")) out["nullable"] = true;
258
+ out["type"] = (nonNull[0] ?? "string");
259
+ continue;
260
+ }
261
+
262
+ if (key === "properties" && isRecord(value)) {
263
+ out[key] = Object.fromEntries(
264
+ Object.entries(value).map(([k, v]) => [k, sanitizeClaudeViaGeminiSchema(v)]),
265
+ );
266
+ continue;
267
+ }
268
+
269
+ if (key === "items") {
270
+ out[key] = sanitizeClaudeViaGeminiSchema(value);
271
+ continue;
272
+ }
273
+
274
+ out[key] = isRecord(value) ? sanitizeClaudeViaGeminiSchema(value) : value;
275
+ }
276
+ return out;
277
+ }