tuxevil-rotator 3.0.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 (142) hide show
  1. package/CHANGELOG.md +773 -0
  2. package/LICENSE +21 -0
  3. package/README.md +341 -0
  4. package/bin/pi-antigravity-rotator.js +27 -0
  5. package/bin/tuxevil-rotator.js +5 -0
  6. package/package.json +63 -0
  7. package/src/account-store.ts +542 -0
  8. package/src/admin-auth.ts +126 -0
  9. package/src/body-limit.ts +52 -0
  10. package/src/cli.ts +293 -0
  11. package/src/compat/cache.ts +38 -0
  12. package/src/compat/model-specs.ts +82 -0
  13. package/src/compat/schema-sanitizer.ts +284 -0
  14. package/src/compat.ts +2357 -0
  15. package/src/compression/index.ts +92 -0
  16. package/src/compression/lite.ts +210 -0
  17. package/src/compression/preservation.ts +183 -0
  18. package/src/compression/rtk/command-detector.ts +170 -0
  19. package/src/compression/rtk/deduplicator.ts +39 -0
  20. package/src/compression/rtk/filter-loader.ts +84 -0
  21. package/src/compression/rtk/filter-types.ts +25 -0
  22. package/src/compression/rtk/filters/aws.json +34 -0
  23. package/src/compression/rtk/filters/biome.json +35 -0
  24. package/src/compression/rtk/filters/build-eslint.json +37 -0
  25. package/src/compression/rtk/filters/build-typescript.json +33 -0
  26. package/src/compression/rtk/filters/build-vite.json +41 -0
  27. package/src/compression/rtk/filters/build-webpack.json +34 -0
  28. package/src/compression/rtk/filters/bundle-install.json +35 -0
  29. package/src/compression/rtk/filters/composer.json +81 -0
  30. package/src/compression/rtk/filters/curl.json +34 -0
  31. package/src/compression/rtk/filters/df.json +34 -0
  32. package/src/compression/rtk/filters/docker-build.json +78 -0
  33. package/src/compression/rtk/filters/docker-logs.json +42 -0
  34. package/src/compression/rtk/filters/docker-ps.json +33 -0
  35. package/src/compression/rtk/filters/dotnet.json +47 -0
  36. package/src/compression/rtk/filters/du.json +33 -0
  37. package/src/compression/rtk/filters/error-stacktrace.json +41 -0
  38. package/src/compression/rtk/filters/gcloud.json +34 -0
  39. package/src/compression/rtk/filters/generic-output.json +32 -0
  40. package/src/compression/rtk/filters/gh.json +98 -0
  41. package/src/compression/rtk/filters/git-branch.json +45 -0
  42. package/src/compression/rtk/filters/git-diff.json +33 -0
  43. package/src/compression/rtk/filters/git-log.json +33 -0
  44. package/src/compression/rtk/filters/git-status.json +40 -0
  45. package/src/compression/rtk/filters/golangci-lint.json +34 -0
  46. package/src/compression/rtk/filters/gradle.json +47 -0
  47. package/src/compression/rtk/filters/json-output.json +40 -0
  48. package/src/compression/rtk/filters/kubectl.json +99 -0
  49. package/src/compression/rtk/filters/make.json +38 -0
  50. package/src/compression/rtk/filters/mypy.json +34 -0
  51. package/src/compression/rtk/filters/npm-audit.json +43 -0
  52. package/src/compression/rtk/filters/npm-install.json +41 -0
  53. package/src/compression/rtk/filters/nx.json +34 -0
  54. package/src/compression/rtk/filters/pip.json +41 -0
  55. package/src/compression/rtk/filters/playwright.json +42 -0
  56. package/src/compression/rtk/filters/poetry-install.json +35 -0
  57. package/src/compression/rtk/filters/prettier.json +40 -0
  58. package/src/compression/rtk/filters/ps.json +34 -0
  59. package/src/compression/rtk/filters/rsync.json +33 -0
  60. package/src/compression/rtk/filters/rubocop.json +34 -0
  61. package/src/compression/rtk/filters/ruff.json +40 -0
  62. package/src/compression/rtk/filters/shell-find.json +33 -0
  63. package/src/compression/rtk/filters/shell-grep.json +37 -0
  64. package/src/compression/rtk/filters/shell-ls.json +33 -0
  65. package/src/compression/rtk/filters/ssh.json +43 -0
  66. package/src/compression/rtk/filters/systemctl-status.json +43 -0
  67. package/src/compression/rtk/filters/terraform-plan.json +34 -0
  68. package/src/compression/rtk/filters/test-cargo.json +42 -0
  69. package/src/compression/rtk/filters/test-go.json +41 -0
  70. package/src/compression/rtk/filters/test-jest.json +43 -0
  71. package/src/compression/rtk/filters/test-pytest.json +41 -0
  72. package/src/compression/rtk/filters/test-vitest.json +43 -0
  73. package/src/compression/rtk/filters/tofu-plan.json +34 -0
  74. package/src/compression/rtk/filters/turbo.json +34 -0
  75. package/src/compression/rtk/filters/uv-sync.json +35 -0
  76. package/src/compression/rtk/filters/wget.json +34 -0
  77. package/src/compression/rtk/index.ts +103 -0
  78. package/src/compression/rtk/line-filter.ts +124 -0
  79. package/src/compression/rtk/smart-truncate.ts +71 -0
  80. package/src/config-defaults.ts +93 -0
  81. package/src/config-normalize.ts +48 -0
  82. package/src/config-storage.ts +21 -0
  83. package/src/dashboard.ts +1169 -0
  84. package/src/db-store.ts +188 -0
  85. package/src/doctor.ts +115 -0
  86. package/src/env.ts +15 -0
  87. package/src/exposure.ts +17 -0
  88. package/src/fetch-with-retry.ts +93 -0
  89. package/src/idempotency.ts +137 -0
  90. package/src/index.ts +267 -0
  91. package/src/key-auth.ts +159 -0
  92. package/src/key-migrations.ts +84 -0
  93. package/src/logger.ts +92 -0
  94. package/src/login.ts +48 -0
  95. package/src/notification-poller.ts +155 -0
  96. package/src/onboarding.ts +754 -0
  97. package/src/paths.ts +153 -0
  98. package/src/providers/adapter.ts +131 -0
  99. package/src/providers/credential-helpers.ts +72 -0
  100. package/src/providers/google-antigravity/code-assist.ts +161 -0
  101. package/src/providers/google-antigravity/credentials.ts +24 -0
  102. package/src/providers/google-antigravity/forward.ts +424 -0
  103. package/src/providers/google-antigravity/index.ts +168 -0
  104. package/src/providers/google-antigravity/login.ts +285 -0
  105. package/src/providers/google-antigravity/oauth.ts +314 -0
  106. package/src/providers/google-antigravity/quota.ts +152 -0
  107. package/src/providers/google-antigravity/translators.ts +1663 -0
  108. package/src/providers/ollama/api-key-validation.ts +59 -0
  109. package/src/providers/ollama/credentials.ts +28 -0
  110. package/src/providers/ollama/forward.ts +306 -0
  111. package/src/providers/ollama/index.ts +85 -0
  112. package/src/providers/ollama/login.ts +55 -0
  113. package/src/providers/ollama/prediction.ts +188 -0
  114. package/src/providers/ollama/quota-poll-store.ts +160 -0
  115. package/src/providers/ollama/quota.ts +189 -0
  116. package/src/providers/ollama/translators.ts +256 -0
  117. package/src/providers/ollama/usage-windows.ts +48 -0
  118. package/src/providers/proxy-dispatcher.ts +269 -0
  119. package/src/providers/registry.ts +70 -0
  120. package/src/proxy.ts +2446 -0
  121. package/src/rate-limit-parser.ts +126 -0
  122. package/src/response-headers.ts +98 -0
  123. package/src/responses-store.ts +159 -0
  124. package/src/rotator.ts +3614 -0
  125. package/src/settings-repository.ts +327 -0
  126. package/src/spend-logger.ts +696 -0
  127. package/src/static/dashboard-keys.js +384 -0
  128. package/src/static/dashboard-logs.js +797 -0
  129. package/src/static/dashboard.css +2740 -0
  130. package/src/static/dashboard.js +3177 -0
  131. package/src/storage.ts +105 -0
  132. package/src/systemd-env.ts +214 -0
  133. package/src/telemetry.ts +384 -0
  134. package/src/token-encryption.ts +199 -0
  135. package/src/types.ts +897 -0
  136. package/src/validators.ts +218 -0
  137. package/src/version-check.ts +225 -0
  138. package/src/virtual-keys.ts +312 -0
  139. package/tools/telemetry-receiver/README.md +147 -0
  140. package/tools/telemetry-receiver/package.json +13 -0
  141. package/tools/telemetry-receiver/receiver.js +2334 -0
  142. package/tuxevil-rotator_logo.png +0 -0
package/src/paths.ts ADDED
@@ -0,0 +1,153 @@
1
+ // Config directory resolution
2
+ // Default: ~/.tuxevil-rotator/
3
+ // Override: --config-dir <path> or TUXEVIL_ROTATOR_DIR env var
4
+ // Legacy: PI_ROTATOR_DIR env var and ~/.pi-antigravity-rotator/ still work
5
+ // (the first run auto-migrates the legacy directory contents).
6
+
7
+ import {
8
+ chmodSync,
9
+ copyFileSync,
10
+ existsSync,
11
+ mkdirSync,
12
+ readdirSync,
13
+ statSync,
14
+ } from "node:fs";
15
+ import { join, resolve } from "node:path";
16
+ import { homedir } from "node:os";
17
+ import { rotatorEnv } from "./env.js";
18
+
19
+ const DEFAULT_DIR = join(homedir(), ".tuxevil-rotator");
20
+
21
+ // Legacy config directories checked (in order) for first-run auto-migration.
22
+ const LEGACY_DIRS = [join(homedir(), ".pi-antigravity-rotator")];
23
+
24
+ let configDir: string | null = null;
25
+
26
+ export interface LegacyMigrationReport {
27
+ targetDir: string;
28
+ copied: string[];
29
+ skipped: string[];
30
+ errors: string[];
31
+ }
32
+
33
+ let lastLegacyMigrationReport: LegacyMigrationReport | null = null;
34
+
35
+ /**
36
+ * Validate that a user-supplied config dir doesn't contain obvious path
37
+ * traversal. Refuses to mkdir and returns the default if the input contains
38
+ * `..` segments that escape the intended root. Throws otherwise.
39
+ */
40
+ export function resolveSafeConfigDir(
41
+ input: string,
42
+ source: "argv" | "env" = "argv",
43
+ ): string {
44
+ // Check the ORIGINAL input (before resolve() collapses ".."), since
45
+ // resolve("/a/../../b") silently becomes "/b" and would mask the attack.
46
+ const segments = input.split(/[\\/]+/);
47
+ for (const seg of segments) {
48
+ if (seg === "..") {
49
+ throw new Error(
50
+ `Refusing --config-dir="${input}" from ${source}: contains '..' segment which could escape the config root. ` +
51
+ `Use an absolute path or TUXEVIL_ROTATOR_DIR env var set by the container orchestrator.`,
52
+ );
53
+ }
54
+ }
55
+ return resolve(input);
56
+ }
57
+
58
+ /**
59
+ * Copy any config files present in a legacy config dir into the active
60
+ * config dir. Only runs when the active dir holds no file at the target
61
+ * path yet, so it never overwrites newer data.
62
+ */
63
+ export function migrateLegacyConfig(
64
+ targetDir: string,
65
+ legacyDirs: string[] = LEGACY_DIRS,
66
+ ): LegacyMigrationReport {
67
+ const report: LegacyMigrationReport = {
68
+ targetDir,
69
+ copied: [],
70
+ skipped: [],
71
+ errors: [],
72
+ };
73
+ mkdirSync(targetDir, { recursive: true });
74
+ for (const legacyDir of legacyDirs) {
75
+ if (!existsSync(legacyDir)) continue;
76
+ let entries: string[];
77
+ try {
78
+ entries = readdirSync(legacyDir);
79
+ } catch (error) {
80
+ report.errors.push(
81
+ `${legacyDir}: ${error instanceof Error ? error.message : String(error)}`,
82
+ );
83
+ continue;
84
+ }
85
+ for (const entry of entries) {
86
+ const sourcePath = join(legacyDir, entry);
87
+ const targetPath = join(targetDir, entry);
88
+ try {
89
+ if (!statSync(sourcePath).isFile()) continue;
90
+ } catch {
91
+ continue;
92
+ }
93
+ if (existsSync(targetPath)) {
94
+ report.skipped.push(entry);
95
+ continue;
96
+ }
97
+ try {
98
+ copyFileSync(sourcePath, targetPath);
99
+ chmodSync(targetPath, statSync(sourcePath).mode & 0o7777);
100
+ report.copied.push(entry);
101
+ } catch (error) {
102
+ report.errors.push(
103
+ `${entry}: ${error instanceof Error ? error.message : String(error)}`,
104
+ );
105
+ }
106
+ }
107
+ }
108
+ lastLegacyMigrationReport = report;
109
+ return report;
110
+ }
111
+
112
+ export function getLastLegacyMigrationReport(): LegacyMigrationReport | null {
113
+ return lastLegacyMigrationReport;
114
+ }
115
+
116
+ export function getConfigDir(): string {
117
+ if (configDir) return configDir;
118
+
119
+ let explicit = false;
120
+
121
+ // Check CLI arg
122
+ const idx = process.argv.indexOf("--config-dir");
123
+ if (idx !== -1 && process.argv[idx + 1]) {
124
+ configDir = resolveSafeConfigDir(process.argv[idx + 1], "argv");
125
+ explicit = true;
126
+ } else if (rotatorEnv("DIR")) {
127
+ configDir = resolveSafeConfigDir(rotatorEnv("DIR")!, "env");
128
+ explicit = true;
129
+ } else {
130
+ configDir = DEFAULT_DIR;
131
+ }
132
+
133
+ mkdirSync(configDir, { recursive: true });
134
+
135
+ // Auto-migrate legacy config files on first run of the new directory.
136
+ if (!explicit) {
137
+ migrateLegacyConfig(configDir);
138
+ }
139
+
140
+ return configDir;
141
+ }
142
+
143
+ export function getAccountsPath(): string {
144
+ return join(getConfigDir(), "accounts.json");
145
+ }
146
+
147
+ export function getStatePath(): string {
148
+ return join(getConfigDir(), "state.json");
149
+ }
150
+
151
+ export function getTokenUsagePath(): string {
152
+ return join(getConfigDir(), "token-usage.json");
153
+ }
@@ -0,0 +1,131 @@
1
+ // Provider adapter contract.
2
+ //
3
+ // Every upstream provider (Google Antigravity, Ollama Cloud, ...) plugs into
4
+ // the rotator core through this interface. The core talks to providers ONLY
5
+ // through a ProviderAdapter; adding a new provider means implementing this
6
+ // interface and registering it in ./registry.ts — nothing in the core needs
7
+ // to change.
8
+
9
+ import type { RequestBody, ForwardedResponse } from "../proxy.js";
10
+ import type { AccountRuntime } from "../types.js";
11
+ import type { AccountConfig } from "../types.js";
12
+
13
+ /** Fractional token usage extracted from an upstream stream. */
14
+ export interface TokenUsage {
15
+ inputTokens: number;
16
+ outputTokens: number;
17
+ }
18
+
19
+ /**
20
+ * Streaming accumulator for a provider's upstream response format
21
+ * (Google: SSE events; Ollama Cloud: NDJSON lines).
22
+ */
23
+ export interface StreamAccumulator {
24
+ /** Append a raw chunk; returns usage from any newly completed events. */
25
+ append(chunkText: string): TokenUsage | null;
26
+ /** Accumulated visible text (used for diagnostics / raw error bodies). */
27
+ getText(): string;
28
+ /** Flush any partial event at end-of-stream. */
29
+ final(): TokenUsage | null;
30
+ }
31
+
32
+ /** Callbacks the core hands to provider code when polling quota. */
33
+ export interface QuotaFetchContext {
34
+ log(message: string): void;
35
+ markFlagged(
36
+ account: AccountRuntime,
37
+ reason: string,
38
+ options?: { triggerProtectivePause?: boolean },
39
+ ): void;
40
+ reportQuotaPollFlag(
41
+ account: AccountRuntime,
42
+ statusCode: number,
43
+ errorText: string,
44
+ ): void;
45
+ }
46
+
47
+ export type CredentialValidationResult =
48
+ | { ok: true }
49
+ | { ok: false; status: number; error: string };
50
+
51
+ /** Provider-reported account tier names, ranked best → worst. */
52
+ export interface TierRanking {
53
+ [tier: string]: number;
54
+ }
55
+
56
+ export interface ProviderFeatures {
57
+ /** Project/model circuit breakers on repeated 429s (opt-in via config). */
58
+ circuitBreakers: boolean;
59
+ /** Per-account / per-project concurrency caps. */
60
+ concurrencyLimits: boolean;
61
+ /** Calibrated exhaustion prediction + proactive rotation. */
62
+ proactiveRotation: boolean;
63
+ }
64
+
65
+ export interface ProviderAdapter {
66
+ readonly id: string;
67
+ readonly displayName: string;
68
+ readonly credentialKind: "oauth" | "api-key";
69
+ readonly tierRanking: TierRanking;
70
+ readonly features: ProviderFeatures;
71
+
72
+ // --- Credentials / login ---
73
+ /** Interactive CLI flow that returns a ready-to-store AccountConfig. */
74
+ runLogin(): Promise<AccountConfig>;
75
+ /** Validate credentials before persisting an account. */
76
+ validateCredentials(config: AccountConfig): Promise<CredentialValidationResult>;
77
+ /** True when the account has valid, usable credentials right now. */
78
+ hasValidCredentials(account: AccountRuntime): boolean;
79
+
80
+ // --- Auth lifecycle ---
81
+ /**
82
+ * Ensure the account has a usable access token (OAuth refresh for Google,
83
+ * no-op for static API keys). Throws on unrecoverable failures.
84
+ */
85
+ ensureValidToken(account: AccountRuntime): Promise<void>;
86
+ /** Auth header value for outgoing upstream requests. */
87
+ getAuthHeader(account: AccountRuntime): string;
88
+
89
+ /**
90
+ * Whether a provider's RESOURCE_EXHAUSTED response is scoped to this
91
+ * account and can safely be retried with another credential.
92
+ */
93
+ shouldRetryOnQuotaExhaustion(
94
+ account: AccountRuntime,
95
+ model: string,
96
+ errorText: string,
97
+ ): boolean;
98
+
99
+ // --- Quota / usage telemetry ---
100
+ /** Poll current quota/usage and write it into account.quota. */
101
+ fetchQuota(account: AccountRuntime, ctx: QuotaFetchContext): Promise<void>;
102
+
103
+ // --- Request forwarding ---
104
+ /** Build + send the upstream request, swapping in provider credentials. */
105
+ forwardRequest(
106
+ account: AccountRuntime,
107
+ body: RequestBody,
108
+ originalHeaders: Record<string, string>,
109
+ signal?: AbortSignal,
110
+ ): Promise<ForwardedResponse>;
111
+ /** Forward one allowlisted non-generation Code Assist operation. */
112
+ forwardCodeAssistRequest?(
113
+ account: AccountRuntime,
114
+ action: string,
115
+ body: unknown,
116
+ originalHeaders: Record<string, string>,
117
+ signal?: AbortSignal,
118
+ ): Promise<ForwardedResponse>;
119
+ /** Accumulator matching this provider's stream format. */
120
+ createStreamAccumulator(): StreamAccumulator;
121
+
122
+ // --- Catalog / helpers ---
123
+ /** Cheap upstream model that warms a quota pool during kickstart. */
124
+ getKickstartModelForPool(quotaModelKey: string): string | undefined;
125
+ /** Benchmark request used to measure account latency/health. */
126
+ getBenchmark(account: AccountRuntime): {
127
+ body: RequestBody;
128
+ parseUsage(raw: string): { outputTokens: number } | null;
129
+ parseText(raw: string): string;
130
+ };
131
+ }
@@ -0,0 +1,72 @@
1
+ // Credential helpers for the parent-account model: independent of the
2
+ // provider adapters so they can be imported from the config layer without
3
+ // pulling in the translators/responses-store cycle.
4
+
5
+ export const DEFAULT_PROVIDER = "google-antigravity";
6
+
7
+ export interface CredentialEntry {
8
+ provider: string;
9
+ apiKey?: string;
10
+ refreshToken?: string;
11
+ projectId?: string;
12
+ projectSource?: "google" | "manual";
13
+ proxyUrl?: string;
14
+ }
15
+
16
+ export interface AccountLike {
17
+ credentials?: CredentialEntry[];
18
+ provider?: string;
19
+ apiKey?: string;
20
+ refreshToken?: string;
21
+ projectId?: string;
22
+ projectSource?: "google" | "manual";
23
+ proxyUrl?: string;
24
+ }
25
+
26
+ export function primaryProviderId(account: AccountLike): string {
27
+ if (account.credentials && account.credentials.length > 0) {
28
+ return account.credentials[0].provider;
29
+ }
30
+ return account.provider ?? DEFAULT_PROVIDER;
31
+ }
32
+
33
+ export function hasCredential(account: AccountLike, providerId: string): boolean {
34
+ if (account.credentials && account.credentials.length > 0) {
35
+ return account.credentials.some((c) => c.provider === providerId);
36
+ }
37
+ return (account.provider ?? DEFAULT_PROVIDER) === providerId;
38
+ }
39
+
40
+ export function getCredential(
41
+ account: AccountLike,
42
+ providerId: string,
43
+ ): CredentialEntry | undefined {
44
+ if (account.credentials && account.credentials.length > 0) {
45
+ const found = account.credentials.find((c) => c.provider === providerId);
46
+ if (found) return found;
47
+ }
48
+ if ((account.provider ?? DEFAULT_PROVIDER) === providerId) {
49
+ const legacy: CredentialEntry = { provider: providerId };
50
+ if (account.apiKey !== undefined) legacy.apiKey = account.apiKey;
51
+ if (account.refreshToken !== undefined) legacy.refreshToken = account.refreshToken;
52
+ if (account.projectId !== undefined) legacy.projectId = account.projectId;
53
+ if (account.projectSource !== undefined) legacy.projectSource = account.projectSource;
54
+ if (account.proxyUrl !== undefined) legacy.proxyUrl = account.proxyUrl;
55
+ return legacy;
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ /**
61
+ * Resolve the egress proxy configured for one provider credential. Incoming
62
+ * request headers are deliberately not consulted here; proxy selection is
63
+ * always an account/configuration concern.
64
+ */
65
+ export function getProviderProxyUrl(
66
+ account: AccountLike,
67
+ providerId: string,
68
+ ): string | undefined {
69
+ const credential = getCredential(account, providerId);
70
+ if (credential?.proxyUrl !== undefined) return credential.proxyUrl;
71
+ return undefined;
72
+ }
@@ -0,0 +1,161 @@
1
+ import {
2
+ ANTIGRAVITY_ENDPOINTS,
3
+ REQUEST_CLIENT_METADATA,
4
+ REQUEST_GOOG_API_CLIENT,
5
+ REQUEST_USER_AGENT,
6
+ } from "../../types.js";
7
+ import type { AccountRuntime } from "../../types.js";
8
+ import type { ForwardedResponse } from "../../proxy.js";
9
+ import { fetchWithRetry } from "../../fetch-with-retry.js";
10
+ import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
11
+
12
+ export const CODE_ASSIST_ACTIONS = [
13
+ "loadCodeAssist",
14
+ "fetchAvailableModels",
15
+ "onboardUser",
16
+ "listExperiments",
17
+ "countTokens",
18
+ "retrieveUserQuota",
19
+ "retrieveUserQuotaSummary",
20
+ ] as const;
21
+
22
+ export type CodeAssistAction = (typeof CODE_ASSIST_ACTIONS)[number];
23
+
24
+ export function isCodeAssistAction(value: string): value is CodeAssistAction {
25
+ return (CODE_ASSIST_ACTIONS as readonly string[]).includes(value);
26
+ }
27
+
28
+ function isRecord(value: unknown): value is Record<string, unknown> {
29
+ return typeof value === "object" && value !== null && !Array.isArray(value);
30
+ }
31
+
32
+ function requireObjectBody(action: CodeAssistAction, body: unknown): Record<string, unknown> {
33
+ if (!isRecord(body)) {
34
+ throw new Error(`Code Assist ${action} requires a JSON object body`);
35
+ }
36
+ return body;
37
+ }
38
+
39
+ export function validateCodeAssistPayload(
40
+ action: CodeAssistAction,
41
+ body: unknown,
42
+ ): void {
43
+ const object = requireObjectBody(action, body);
44
+ if (action === "onboardUser") {
45
+ if (typeof object.tier_id !== "string" || object.tier_id.trim() === "") {
46
+ throw new Error("Code Assist onboardUser requires tier_id");
47
+ }
48
+ }
49
+ if (action === "countTokens") {
50
+ if (typeof object.model !== "string" || object.model.trim() === "") {
51
+ throw new Error("Code Assist countTokens requires model");
52
+ }
53
+ if (!("request" in object)) {
54
+ throw new Error("Code Assist countTokens requires request");
55
+ }
56
+ }
57
+ }
58
+
59
+ function buildHeaders(
60
+ account: AccountRuntime,
61
+ originalHeaders: Record<string, string>,
62
+ ): Record<string, string> {
63
+ const headers: Record<string, string> = { ...originalHeaders };
64
+ const hopByHop = new Set([
65
+ "authorization",
66
+ "connection",
67
+ "content-length",
68
+ "host",
69
+ "keep-alive",
70
+ "proxy-authenticate",
71
+ "proxy-authorization",
72
+ "te",
73
+ "trailers",
74
+ "transfer-encoding",
75
+ "upgrade",
76
+ "user-agent",
77
+ "x-goog-api-client",
78
+ "client-metadata",
79
+ ]);
80
+ for (const key of Object.keys(headers)) {
81
+ if (hopByHop.has(key.toLowerCase())) delete headers[key];
82
+ }
83
+ headers.Authorization = `Bearer ${account.accessToken ?? ""}`;
84
+ headers["Content-Type"] = "application/json";
85
+ headers.Accept = "application/json";
86
+ headers["User-Agent"] = REQUEST_USER_AGENT;
87
+ headers["X-Goog-Api-Client"] = REQUEST_GOOG_API_CLIENT;
88
+ headers["Client-Metadata"] = REQUEST_CLIENT_METADATA;
89
+ return headers;
90
+ }
91
+
92
+ function buildUpstreamBody(
93
+ account: AccountRuntime,
94
+ action: CodeAssistAction,
95
+ body: Record<string, unknown>,
96
+ ): Record<string, unknown> {
97
+ const projectScoped = new Set([
98
+ "fetchAvailableModels",
99
+ "countTokens",
100
+ "retrieveUserQuota",
101
+ "retrieveUserQuotaSummary",
102
+ ]);
103
+ if (!projectScoped.has(action)) return { ...body };
104
+ const projectId = account.config.projectId?.trim();
105
+ if (!projectId) {
106
+ throw new Error(`Code Assist ${action} requires the active account projectId`);
107
+ }
108
+ return { ...body, project: projectId };
109
+ }
110
+
111
+ export async function forwardCodeAssistRequest(
112
+ account: AccountRuntime,
113
+ action: CodeAssistAction,
114
+ body: unknown,
115
+ originalHeaders: Record<string, string>,
116
+ signal?: AbortSignal,
117
+ ): Promise<ForwardedResponse> {
118
+ validateCodeAssistPayload(action, body);
119
+ const requestBody = buildUpstreamBody(
120
+ account,
121
+ action,
122
+ body as Record<string, unknown>,
123
+ );
124
+ const headers = buildHeaders(account, originalHeaders);
125
+ let lastError: unknown;
126
+
127
+ for (let index = 0; index < ANTIGRAVITY_ENDPOINTS.length; index++) {
128
+ const endpoint = ANTIGRAVITY_ENDPOINTS[index];
129
+ try {
130
+ const response = await fetchWithRetry(
131
+ `${endpoint}/v1internal:${action}`,
132
+ {
133
+ method: "POST",
134
+ headers,
135
+ body: JSON.stringify(requestBody),
136
+ signal,
137
+ dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
138
+ retries: 0,
139
+ timeoutMs: 10_000,
140
+ },
141
+ );
142
+ if (
143
+ (response.status === 401 ||
144
+ response.status === 403 ||
145
+ response.status === 404) &&
146
+ index < ANTIGRAVITY_ENDPOINTS.length - 1
147
+ ) {
148
+ await response.body?.cancel().catch(() => undefined);
149
+ continue;
150
+ }
151
+ return { response, endpoint };
152
+ } catch (err) {
153
+ lastError = err;
154
+ if (index < ANTIGRAVITY_ENDPOINTS.length - 1) continue;
155
+ }
156
+ }
157
+
158
+ throw lastError instanceof Error
159
+ ? lastError
160
+ : new Error("All Code Assist endpoints failed");
161
+ }
@@ -0,0 +1,24 @@
1
+ // Google Antigravity credential validation.
2
+ //
3
+ // Google accounts are validated through the OAuth flow itself (the exchange
4
+ // fails for invalid credentials), so there is nothing else to probe here.
5
+
6
+ import type { AccountConfig } from "../../types.js";
7
+ import type { CredentialValidationResult } from "../adapter.js";
8
+
9
+ export async function validateCredentials(
10
+ config: AccountConfig,
11
+ ): Promise<CredentialValidationResult> {
12
+ if (
13
+ config.provider !== "google-antigravity" ||
14
+ typeof config.refreshToken !== "string" ||
15
+ config.refreshToken.length === 0
16
+ ) {
17
+ return {
18
+ ok: false,
19
+ status: 0,
20
+ error: "Missing refreshToken for Google Antigravity account",
21
+ };
22
+ }
23
+ return { ok: true };
24
+ }