pi-antigravity-rotator 2.1.5 → 2.2.1

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,6 +2,52 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [2.2.1] - 2026-06-20
6
+
7
+ ### 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.
12
+
13
+ ## [2.2.0] - 2026-06-16
14
+
15
+ ### Security
16
+
17
+ ### Security
18
+ - **Admin token autogeneration**: On first run with no `PI_ROTATOR_ADMIN_TOKEN` env var, a cryptographically secure token is generated, persisted to `.admin-token` (mode 0600), and printed once to the operator. Dashboard and `/api/*` routes are now protected by default on fresh installs. Override the generated token by setting `PI_ROTATOR_ADMIN_TOKEN` in the env. `.admin-token` added to `.gitignore`.
19
+ - **Querystring secret redaction**: `redactSensitive()` now also redacts `access_token`, `token`, `api_key`, `apikey`, `key`, `refresh_token` when they appear in querystring (`?key=val&...`) or URL fragment.
20
+ - **OAuth fallback warning**: New `warnIfUsingFallbackOAuthCreds()` detects when `ANTIGRAVITY_CLIENT_ID` and/or `ANTIGRAVITY_CLIENT_SECRET` are missing and emits a one-time warning that the rotator is using the public Antigravity IDE client.
21
+ - **Removed open CORS**: `Access-Control-Allow-Origin: *` removed from `/api/status` and `/api/config`. Replaced with `Cache-Control: no-store`. Dashboard still works same-origin.
22
+ - **Truncated/redacted validation logs**: New `logValidationFailure()` truncates payloads to 200 chars and runs them through `redactSensitive` before logging. Applied to OpenAI messages validation and stream error logs in `compat.ts`.
23
+
24
+ ### Added
25
+ - **`Config.modelSpecs`**: Operators can now override the per-model thinking/output spec table used by the compat layer without recompiling. Add a `modelSpecs` field to `accounts.json` and call `setModelSpecsOverride()` at boot (done automatically by `index.ts`).
26
+ - **`warnIfInsecureTelemetryEndpoint()`**: Detects plain `http://` telemetry endpoints and emits a one-time warning. Default endpoint switched to `https://`. Override via `PI_ROTATOR_TELEMETRY_URL`. Silence via `PI_ROTATOR_TELEMETRY_INSECURE_OK=1`.
27
+ - **Persistent `responsesStore`**: The OpenAI Responses API store (used by Codex via `previous_response_id`) is now persisted to `<configDir>/responses.json` with atomic writes and a 1.5s debounce. Restart-safe: in-flight Codex conversations continue across rotator restarts. New `src/responses-store.ts` with `load()`, `flush()`, `flushSync()`. Corrupt files are moved aside to `.corrupt-<ts>.bak` on startup.
28
+ - **Debounced state writes**: Hot paths (`recordRequest`, `markExhausted`, `markError`, `markFlagged`) now call `scheduleStateSave()` instead of `saveState()`, coalescing multiple writes within a 1s window into a single disk write. New `flushPendingStateSaveSync()` in the SIGTERM/SIGINT shutdown handler drains the queue synchronously to minimise data loss.
29
+ - **GitHub Actions CI**: New `.github/workflows/ci.yml` runs `npm ci` + `npm run check` (typecheck + 191 tests) on push and PR to `main`. Node 22 with npm cache. PRs without green checks cannot be merged.
30
+ - **8 e2e proxy tests** (`test/proxy-e2e.test.ts`): Cover the full proxy flow with a local HTTP server as mock Antigravity — 200 happy path, 429 rate-limited (Retry-After and RESOURCE_EXHAUSTED), 401 unauthorized, 403 flagged and non-flagged, 500 server error, endpoint cascade (daily→prod).
31
+ - **7 dashboard tests** (`test/dashboard.test.ts`): Verify utf-8/viewport meta tags, all 12 admin API endpoints are referenced, the `escapeHtml`/`jsString`/`maskText`/`maskEmail` helpers are present and `escapeHtml` correctly escapes the 5 HTML-sensitive characters, no hardcoded OAuth secrets or refresh tokens leak into the HTML.
32
+
33
+ ### Changed
34
+ - **Refactored `proxy.ts`**: Extracted `classifyUpstreamResponse()` that returns a discriminated `UpstreamAction`. Both `withRotation()` and `handleProxyRequest()` dispatch against the helper instead of duplicating the 401/403/404/400/429/5xx branches. ~150 lines of parallel code removed. New `UpstreamAction` type with 9 action kinds.
35
+
36
+ ### Cleanup
37
+ - **Removed `src/antigravity-prompt.ts`**: 80-line `ANTIGRAVITY_IDENTITY_PROMPT` export with 0 references in the repo.
38
+ - **Consolidated agent docs**: `CLAUDE.md` now points to `AGENTS.md` as the single source of truth. The duplicated BEADS INTEGRATION block is gone.
39
+ - **Moved scripts to `scripts/`**: 10 one-off utility scripts (`mitm.js`, `mock_google.js`, `query_models.{js,ts}`, `test-compat.ts`, `test-direct.js`, `test_generate.js`, `test_loop.js`, `test-http.cjs`, `test-openai.cjs`) moved from the repo root. `query_models.ts` and `test-compat.ts` updated to use `../src/...` relative imports after the move.
40
+
41
+ ## [2.2.1] - 2026-06-16
42
+
43
+ ### Fixed
44
+ - **SSE usage extraction cross-event matching**: The old `extractTokenUsage()` ran a regex on the last 32KB of the upstream body, which could match across SSE event boundaries and return incorrect `(input, output)` pairs. Replaced with `SseEventAccumulator` + `extractUsageFromSseEvent()` that buffer complete SSE events (split on `\n\n`), parse each `data:` payload as JSON, and recursively search for `usageMetadata` (Gemini) or `usage` (OpenAI/Anthropic). Regex remains as a last-resort fallback for malformed JSON. Real-time streaming is preserved — the `res.write(chunk)` in `onData` is unchanged. Resolves ROADMAP §2.
45
+
46
+ ## [2.1.6] - 2026-06-12
47
+
48
+ ### Fixed
49
+ - **Streaming tool calls finish reason**: Fixed an issue where `streamCompatSse` emitted `finish_reason: "stop"` instead of `"tool_calls"` when function calls were streamed to the client via OpenAI compatibility layer. This resolves compatibility issues with clients like ZED editor that discard pending tool executions as canceled when receiving "stop".
50
+
5
51
  ## [2.1.5] - 2026-05-27
6
52
 
7
53
  ### Fixed
@@ -11,6 +57,8 @@
11
57
  - **Consecutive tool result merging**: Multiple `functionResponse` parts are now merged into a single `user` Gemini turn, ensuring all `tool_result` blocks appear in one message directly after the `tool_use` assistant message.
12
58
 
13
59
 
60
+ ## [2.1.4] - 2026-05-27
61
+
14
62
  ### Improved
15
63
  - **Less Lossy Schema Collapsing for Claude**: The `sanitizeClaudeViaGeminiSchema` function now handles complex `anyOf`/`oneOf`/`allOf` schemas with significantly less information loss:
16
64
  - **Nullable detection (lossless)**: `anyOf: [{type: X}, {type: "null"}]` patterns are now converted to `{type: X, nullable: true}` instead of losing the null variant.
package/README.md CHANGED
@@ -471,6 +471,7 @@ 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
475
  - **[@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))
475
476
 
476
477
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-antigravity-rotator",
3
- "version": "2.1.5",
3
+ "version": "2.2.1",
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",
@@ -12,7 +12,9 @@
12
12
  "login": "tsx src/cli.ts login",
13
13
  "typecheck": "tsc --noEmit",
14
14
  "test": "node --import tsx/esm --test \"test/**/*.test.ts\"",
15
- "check": "npm run typecheck && npm test"
15
+ "lint": "eslint src test",
16
+ "coverage": "c8 --reporter=text --reporter=html npm test",
17
+ "check": "npm run typecheck && npm test && npm run lint"
16
18
  },
17
19
  "files": [
18
20
  "bin/",
@@ -43,7 +45,11 @@
43
45
  "tsx": "^4.19.0"
44
46
  },
45
47
  "devDependencies": {
48
+ "@eslint/js": "^10.0.1",
46
49
  "@types/node": "^22.0.0",
47
- "typescript": "^5.7.0"
50
+ "c8": "^11.0.0",
51
+ "eslint": "^10.5.0",
52
+ "typescript": "^5.7.0",
53
+ "typescript-eslint": "^8.61.1"
48
54
  }
49
55
  }
@@ -102,7 +102,37 @@ export function saveAccountsConfig(config: Config): void {
102
102
  writeJsonFileAtomic(ACCOUNTS_FILE, applyConfigDefaults(config));
103
103
  }
104
104
 
105
+ // Reasonable upper bounds on per-account fields. These are defensive
106
+ // limits to prevent a malicious or buggy caller from growing
107
+ // accounts.json without bound, which would slow every subsequent
108
+ // saveState. The numbers are well above any realistic real value.
109
+ export const MAX_EMAIL_LENGTH = 254; // RFC 5321
110
+ export const MAX_LABEL_LENGTH = 100;
111
+ export const MAX_PROJECT_ID_LENGTH = 100;
112
+ export const MAX_REFRESH_TOKEN_LENGTH = 4096;
113
+
114
+ function validateAccountConfigLengths(entry: AccountConfig): void {
115
+ const checks: Array<[string, number]> = [
116
+ ["email", MAX_EMAIL_LENGTH],
117
+ ["label", MAX_LABEL_LENGTH],
118
+ ["projectId", MAX_PROJECT_ID_LENGTH],
119
+ ["refreshToken", MAX_REFRESH_TOKEN_LENGTH],
120
+ ];
121
+ for (const [field, max] of checks) {
122
+ const value = entry[field as keyof AccountConfig];
123
+ if (typeof value === "string" && value.length > max) {
124
+ throw new Error(
125
+ `Account ${field} exceeds maximum length ${max} (got ${value.length}). ` +
126
+ `This usually indicates a malformed input — refusing to write to accounts.json.`,
127
+ );
128
+ }
129
+ }
130
+ }
131
+
132
+ export { validateAccountConfigLengths };
133
+
105
134
  export function addAccountToConfig(entry: AccountConfig): { isNew: boolean } {
135
+ validateAccountConfigLengths(entry);
106
136
  const config = loadOrCreateAccountsConfig();
107
137
  const existing = config.accounts.findIndex((a) => a.email === entry.email);
108
138
 
package/src/admin-auth.ts CHANGED
@@ -1,13 +1,96 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { randomBytes } from "node:crypto";
3
+ import { existsSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
4
+ import { join } from "node:path";
2
5
 
3
6
  interface AdminAuthRequest {
4
7
  url?: string;
5
8
  headers: IncomingMessage["headers"];
6
9
  }
7
10
 
11
+ const ADMIN_TOKEN_FILENAME = ".admin-token";
12
+
13
+ let persistedToken: string | null = null;
14
+
15
+ /**
16
+ * Set the persisted admin token at runtime. Called by index.ts after
17
+ * ensureAdminToken resolves the effective token. Subsequent calls to
18
+ * getConfiguredAdminToken() will return this token if no env var is set.
19
+ */
20
+ export function setPersistedAdminToken(token: string | null): void {
21
+ persistedToken = token && token.length > 0 ? token : null;
22
+ }
23
+
8
24
  export function getConfiguredAdminToken(env: NodeJS.ProcessEnv = process.env): string | null {
9
25
  const token = env.PI_ROTATOR_ADMIN_TOKEN?.trim();
10
- return token ? token : null;
26
+ if (token) return token;
27
+ return persistedToken;
28
+ }
29
+
30
+ /**
31
+ * Generate a cryptographically secure admin token (32 random bytes, hex).
32
+ * 64 hex characters = 256 bits of entropy.
33
+ */
34
+ export function generateAdminToken(): string {
35
+ return randomBytes(32).toString("hex");
36
+ }
37
+
38
+ export function readPersistedAdminToken(configDir: string): string | null {
39
+ const tokenPath = join(configDir, ADMIN_TOKEN_FILENAME);
40
+ if (!existsSync(tokenPath)) return null;
41
+ try {
42
+ const raw = readFileSync(tokenPath, "utf-8").trim();
43
+ return raw ? raw : null;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ export function writePersistedAdminToken(configDir: string, token: string): void {
50
+ const tokenPath = join(configDir, ADMIN_TOKEN_FILENAME);
51
+ writeFileSync(tokenPath, token, { mode: 0o600, encoding: "utf-8" });
52
+ try {
53
+ chmodSync(tokenPath, 0o600);
54
+ } catch {
55
+ // Best effort: some filesystems (e.g. Windows) don't support POSIX perms.
56
+ }
57
+ }
58
+
59
+ export interface ResolvedAdminToken {
60
+ token: string;
61
+ source: "env" | "file" | "generated";
62
+ generated: boolean;
63
+ }
64
+
65
+ /**
66
+ * Resolve the effective admin token, generating and persisting one if needed.
67
+ * Priority: PI_ROTATOR_ADMIN_TOKEN env var > .admin-token file > generate new.
68
+ *
69
+ * When a token is generated, it is persisted to .admin-token with 0600 perms
70
+ * and returned. The caller is responsible for printing it to the operator.
71
+ */
72
+ export function ensureAdminToken(
73
+ configDir: string,
74
+ env: NodeJS.ProcessEnv = process.env,
75
+ ): ResolvedAdminToken {
76
+ const envToken = env.PI_ROTATOR_ADMIN_TOKEN?.trim();
77
+ if (envToken) {
78
+ return { token: envToken, source: "env", generated: false };
79
+ }
80
+
81
+ const fileToken = readPersistedAdminToken(configDir);
82
+ if (fileToken) {
83
+ return { token: fileToken, source: "file", generated: false };
84
+ }
85
+
86
+ const newToken = generateAdminToken();
87
+ try {
88
+ writePersistedAdminToken(configDir, newToken);
89
+ } catch {
90
+ // If we cannot write the file (read-only fs, perms), still return the
91
+ // token for this session. The next restart will simply generate again.
92
+ }
93
+ return { token: newToken, source: "generated", generated: true };
11
94
  }
12
95
 
13
96
  export function getRequestAdminToken(req: AdminAuthRequest): string | null {