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
@@ -0,0 +1,256 @@
1
+ // Ollama Cloud compat translators: OpenAI/Anthropic bodies -> Ollama native.
2
+ //
3
+ // Ported from the ollama-rotator project (same author) into the
4
+ // tuxevil-rotator provider layer. Shared helpers (chat message shapes,
5
+ // Anthropic -> OpenAI conversion) come from the Google translator module,
6
+ // which both providers inherited from the same original compat layer.
7
+
8
+ import type { RequestBody } from "../../proxy.js";
9
+ import { isRecord } from "../../compat/schema-sanitizer.js";
10
+ import { getModelSpec } from "../../compat/model-specs.js";
11
+ import {
12
+ type AnthropicMessagesRequest,
13
+ type ChatMessage,
14
+ type CompatCompletion,
15
+ type OpenAIChatCompletionRequest,
16
+ type OpenAIToolCall,
17
+ extractText,
18
+ convertAnthropicToolsToOpenAI,
19
+ convertAnthropicToolChoice,
20
+ convertAnthropicMessagesToOpenAI,
21
+ toolArgumentsToObject,
22
+ toolArgumentsToString,
23
+ } from "../google-antigravity/translators.js";
24
+
25
+ /**
26
+ * Translate an OpenAI chat completion request into the body shape consumed
27
+ * by the Ollama adapter (buildOllamaPayload: request.messages / stream /
28
+ * tools / options). Mirrors the Ollama rotator's openAIToOllamaBody.
29
+ */
30
+ export function openAIToOllamaBody(
31
+ input: OpenAIChatCompletionRequest,
32
+ ): RequestBody {
33
+ const messages: ChatMessage[] = [];
34
+ for (const msg of input.messages) {
35
+ const rawRole = msg.role === "developer" ? "system" : msg.role;
36
+ if (rawRole === "system") {
37
+ const systemText =
38
+ typeof msg.content === "string"
39
+ ? msg.content
40
+ : extractText(msg.content);
41
+ if (systemText) messages.push({ role: "system", content: systemText });
42
+ continue;
43
+ }
44
+ if (rawRole === "tool") {
45
+ const toolText =
46
+ typeof msg.content === "string"
47
+ ? msg.content
48
+ : extractText(msg.content);
49
+ const entry: ChatMessage = {
50
+ role: "tool",
51
+ content: toolText || "",
52
+ tool_call_id: msg.tool_call_id,
53
+ };
54
+ if (isRecord(msg) && typeof msg.name === "string") {
55
+ entry.name = msg.name;
56
+ }
57
+ messages.push(entry);
58
+ continue;
59
+ }
60
+ if (rawRole === "assistant" || rawRole === "model") {
61
+ const text =
62
+ typeof msg.content === "string" ? msg.content : extractText(msg.content);
63
+ const entry: ChatMessage = { role: "assistant", content: text || null };
64
+ const toolCalls = Array.isArray(msg.tool_calls)
65
+ ? msg.tool_calls.filter(
66
+ (tc) =>
67
+ isRecord(tc) &&
68
+ isRecord(tc.function) &&
69
+ typeof tc.function.name === "string",
70
+ )
71
+ : [];
72
+ if (toolCalls.length > 0) {
73
+ entry.tool_calls = toolCalls.map((tc) => {
74
+ // Ollama expects `function.arguments` as a parsed object, but
75
+ // OpenAI sends it as a JSON-encoded string. Parse it back so
76
+ // the Go upstream doesn't reject the body.
77
+ const parsedArgs = toolArgumentsToObject(
78
+ (tc.function as { arguments?: unknown }).arguments,
79
+ );
80
+ return {
81
+ id:
82
+ (tc.id as string) || `call_${Date.now().toString(36)}`,
83
+ type: "function" as const,
84
+ function: {
85
+ name: (tc.function as { name: string }).name,
86
+ arguments: parsedArgs,
87
+ },
88
+ };
89
+ });
90
+ }
91
+ messages.push(entry);
92
+ continue;
93
+ }
94
+ // user
95
+ const content = msg.content;
96
+ if (Array.isArray(content)) {
97
+ const parts: Array<Record<string, unknown>> = [];
98
+ for (const part of content) {
99
+ if (!isRecord(part)) continue;
100
+ if (part.type === "text" && typeof part.text === "string") {
101
+ if (part.text) parts.push({ type: "text", text: part.text });
102
+ continue;
103
+ }
104
+ if (
105
+ part.type === "image_url" &&
106
+ isRecord(part.image_url) &&
107
+ typeof part.image_url.url === "string"
108
+ ) {
109
+ parts.push({
110
+ type: "image_url",
111
+ image_url: { url: part.image_url.url },
112
+ });
113
+ continue;
114
+ }
115
+ if (
116
+ part.type === "image" &&
117
+ isRecord(part.source) &&
118
+ typeof part.source.data === "string"
119
+ ) {
120
+ const mediaType =
121
+ typeof part.source.media_type === "string"
122
+ ? part.source.media_type
123
+ : "image/png";
124
+ parts.push({
125
+ type: "image_url",
126
+ image_url: {
127
+ url: `data:${mediaType};base64,${part.source.data}`,
128
+ },
129
+ });
130
+ }
131
+ }
132
+ if (parts.length > 0) {
133
+ messages.push({
134
+ role: "user",
135
+ content: parts as ChatMessage["content"],
136
+ });
137
+ continue;
138
+ }
139
+ const text = extractText(content);
140
+ if (text) messages.push({ role: "user", content: text });
141
+ continue;
142
+ }
143
+ const text = typeof content === "string" ? content : extractText(content);
144
+ if (text) messages.push({ role: "user", content: text });
145
+ }
146
+ if (messages.length === 0) messages.push({ role: "user", content: "Hello" });
147
+
148
+ const options: Record<string, unknown> = {};
149
+ if (typeof input.temperature === "number" && input.temperature !== 1)
150
+ options.temperature = input.temperature;
151
+ const requestedMaxOutput =
152
+ typeof input.max_tokens === "number"
153
+ ? input.max_tokens
154
+ : typeof input.max_completion_tokens === "number"
155
+ ? input.max_completion_tokens
156
+ : undefined;
157
+ const maxOutputTokens =
158
+ requestedMaxOutput ?? getModelSpec(input.model)?.maxOutputTokens ?? 8192;
159
+ options.num_predict = maxOutputTokens;
160
+ const tools = Array.isArray(input.tools) && input.tools.length > 0
161
+ ? input.tools
162
+ : undefined;
163
+ return {
164
+ project: "",
165
+ model: input.model,
166
+ request: {
167
+ model: input.model,
168
+ messages,
169
+ stream: input.stream !== false,
170
+ ...(tools ? { tools } : {}),
171
+ ...(Object.keys(options).length > 0 ? { options } : {}),
172
+ },
173
+ };
174
+ }
175
+
176
+ /**
177
+ * Translate an Anthropic messages request into an Ollama native body by
178
+ * first converting to the OpenAI chat shape (shared with the Google path).
179
+ */
180
+ export function anthropicToOllamaBody(
181
+ input: AnthropicMessagesRequest,
182
+ ): RequestBody {
183
+ const systemText =
184
+ typeof input.system === "string"
185
+ ? input.system
186
+ : Array.isArray(input.system)
187
+ ? extractText(input.system as ChatMessage["content"])
188
+ : "";
189
+ const tools = convertAnthropicToolsToOpenAI(input.tools);
190
+ const toolChoice = convertAnthropicToolChoice(input.tool_choice);
191
+ const convertedMessages = convertAnthropicMessagesToOpenAI(input.messages);
192
+ return openAIToOllamaBody({
193
+ model: input.model,
194
+ stream: input.stream,
195
+ temperature: input.temperature,
196
+ max_tokens: input.max_tokens,
197
+ tools,
198
+ tool_choice: toolChoice,
199
+ messages: [
200
+ ...(systemText ? [{ role: "system" as const, content: systemText }] : []),
201
+ ...convertedMessages,
202
+ ],
203
+ });
204
+ }
205
+
206
+ /**
207
+ * Parse a complete NDJSON response body into a CompatCompletion
208
+ * (text, token usage from the terminal `done` record, tool calls).
209
+ */
210
+ export function parseOllamaNdjson(raw: string): CompatCompletion {
211
+ let inputTokens = 0;
212
+ let outputTokens = 0;
213
+ let text = "";
214
+ const toolCalls: OpenAIToolCall[] = [];
215
+ for (const chunk of raw.split(/\r?\n/)) {
216
+ const line = chunk.trim();
217
+ if (!line) continue;
218
+ try {
219
+ const parsed = JSON.parse(line) as Record<string, unknown>;
220
+ if (parsed.done === true) {
221
+ inputTokens = (parsed.prompt_eval_count as number) ?? 0;
222
+ outputTokens = (parsed.eval_count as number) ?? 0;
223
+ }
224
+ const msg = isRecord(parsed.message) ? parsed.message : null;
225
+ if (msg) {
226
+ if (typeof msg.content === "string" && msg.content) {
227
+ text += msg.content;
228
+ }
229
+ if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
230
+ for (const tc of msg.tool_calls) {
231
+ if (!isRecord(tc) || !isRecord(tc.function)) continue;
232
+ toolCalls.push({
233
+ id: (tc.id as string) || `call_${Date.now().toString(36)}`,
234
+ type: "function",
235
+ function: {
236
+ name:
237
+ typeof tc.function.name === "string"
238
+ ? tc.function.name
239
+ : "unknown",
240
+ arguments: toolArgumentsToString(tc.function.arguments),
241
+ },
242
+ });
243
+ }
244
+ }
245
+ }
246
+ } catch {
247
+ // Ignore malformed NDJSON lines
248
+ }
249
+ }
250
+ return {
251
+ text,
252
+ inputTokens,
253
+ outputTokens,
254
+ ...(toolCalls.length > 0 ? { toolCalls } : {}),
255
+ };
256
+ }
@@ -0,0 +1,48 @@
1
+ // Ported from the ollama-rotator project (same author) into the
2
+ // tuxevil-rotator provider layer.
3
+ // ── Quota window math ────────────────────────────────────────────────
4
+ // Ollama Cloud usage limits:
5
+ // - weekly: fixed calendar window that always runs; resets every Monday
6
+ // 00:00 UTC (which is Sunday 19:00 in GMT-5). The reset moment is
7
+ // deterministic — no heuristic needed, and using the pool never
8
+ // "starts" or shifts the window.
9
+ // - session: child of the weekly window. It is inactive until the first
10
+ // request, and each activation lasts exactly 5 hours (rolling from
11
+ // when the window opened).
12
+ //
13
+ // The session window start is only observed indirectly via the usage
14
+ // fraction, so callers anchor it at the moment usage first becomes > 0
15
+ // (or the poll that detects a drop after a reset).
16
+
17
+ export const SESSION_WINDOW_MS = 5 * 3600 * 1000;
18
+ export const WEEKLY_WINDOW_MS = 7 * 24 * 3600 * 1000;
19
+
20
+ // Resets take place at 00:00 UTC on Monday (end of Sunday UTC).
21
+ const WEEKLY_RESET_UTC_WEEKDAY = 1; // Date.prototype.getUTCDay(): 1 = Monday
22
+
23
+ // Start of the current weekly window (the Monday 00:00 UTC at or before now).
24
+ export function weeklyStartUtcMs(now: number = Date.now()): number {
25
+ const date = new Date(now);
26
+ const dayOffset = (date.getUTCDay() - WEEKLY_RESET_UTC_WEEKDAY + 7) % 7;
27
+ return Date.UTC(
28
+ date.getUTCFullYear(),
29
+ date.getUTCMonth(),
30
+ date.getUTCDate() - dayOffset,
31
+ );
32
+ }
33
+
34
+ export function nextWeeklyResetMs(now: number = Date.now()): number {
35
+ return weeklyStartUtcMs(now) + WEEKLY_WINDOW_MS;
36
+ }
37
+
38
+ export function sessionWindowEndMs(startMs: number): number {
39
+ return startMs + SESSION_WINDOW_MS;
40
+ }
41
+
42
+ // Remaining time on the current session window, clamped to >= 0.
43
+ export function sessionRemainingMs(
44
+ startMs: number,
45
+ now: number = Date.now(),
46
+ ): number {
47
+ return Math.max(0, sessionWindowEndMs(startMs) - now);
48
+ }
@@ -0,0 +1,269 @@
1
+ import { Agent, ProxyAgent } from "undici";
2
+ import type { Dispatcher } from "undici";
3
+ import { connect as netConnect, isIP, type Socket } from "node:net";
4
+ import { connect as tlsConnect, type TLSSocket } from "node:tls";
5
+ import type { AccountRuntime } from "../types.js";
6
+ import { getProviderProxyUrl } from "./credential-helpers.js";
7
+
8
+ const SUPPORTED_PROXY_PROTOCOLS = new Set([
9
+ "http:",
10
+ "https:",
11
+ "socks:",
12
+ "socks5:",
13
+ "socks5h:",
14
+ ]);
15
+
16
+ const dispatchers = new Map<string, Dispatcher>();
17
+
18
+ function normalizedProxyUrl(value: string): string {
19
+ const url = new URL(value);
20
+ if (!SUPPORTED_PROXY_PROTOCOLS.has(url.protocol)) {
21
+ throw new Error("Account proxy must use http://, https://, socks5://, or socks5h://");
22
+ }
23
+ if (!url.hostname) {
24
+ throw new Error("Account proxy must include a hostname");
25
+ }
26
+ if ((url.username === "") !== (url.password === "")) {
27
+ throw new Error("Account proxy username and password must be provided together");
28
+ }
29
+ if ((url.pathname && url.pathname !== "/") || url.search || url.hash) {
30
+ throw new Error("Account proxy must not include a path, query, or fragment");
31
+ }
32
+ if (url.protocol === "socks5h:") url.protocol = "socks5:";
33
+ if (url.protocol === "socks:") url.protocol = "socks5:";
34
+ return url.toString();
35
+ }
36
+
37
+ /** Return a safe validation message without echoing proxy credentials. */
38
+ export function getProxyConfigurationError(value: unknown): string | null {
39
+ if (value === undefined || value === null || value === "") return null;
40
+ if (typeof value !== "string") return "proxyUrl must be a string";
41
+ if (value.length > 2048) return "proxyUrl exceeds the maximum length of 2048 characters";
42
+ try {
43
+ normalizedProxyUrl(value.trim());
44
+ return null;
45
+ } catch (err) {
46
+ const message = err instanceof Error ? err.message : "invalid URL";
47
+ return message === "Invalid URL" ? "proxyUrl is invalid" : `proxyUrl ${message.toLowerCase()}`;
48
+ }
49
+ }
50
+
51
+ function createDispatcher(proxyUrl: string): Dispatcher {
52
+ const normalized = normalizedProxyUrl(proxyUrl);
53
+ const url = new URL(normalized);
54
+ if (url.protocol === "socks5:") return createSocks5Dispatcher(url);
55
+ return new ProxyAgent({ uri: normalized, proxyTunnel: false });
56
+ }
57
+
58
+ type SocksSocket = Socket | TLSSocket;
59
+
60
+ function createSocketReader(socket: Socket): {
61
+ read(length: number): Promise<Buffer>;
62
+ close(): void;
63
+ } {
64
+ let buffered = Buffer.alloc(0);
65
+ let failure: Error | null = null;
66
+ let waiter: {
67
+ length: number;
68
+ resolve: (value: Buffer) => void;
69
+ reject: (err: Error) => void;
70
+ } | null = null;
71
+
72
+ const drain = (): void => {
73
+ if (!waiter || buffered.length < waiter.length) return;
74
+ const current = waiter;
75
+ waiter = null;
76
+ const value = buffered.subarray(0, current.length);
77
+ buffered = buffered.subarray(current.length);
78
+ current.resolve(value);
79
+ };
80
+ const onData = (chunk: Buffer): void => {
81
+ buffered = Buffer.concat([buffered, chunk]);
82
+ drain();
83
+ };
84
+ const onError = (err: Error): void => {
85
+ failure = err;
86
+ if (waiter) {
87
+ const current = waiter;
88
+ waiter = null;
89
+ current.reject(err);
90
+ }
91
+ };
92
+ const onClose = (): void => onError(new Error("SOCKS5 proxy connection closed"));
93
+ const onTimeout = (): void => onError(new Error("SOCKS5 proxy connection timed out"));
94
+ socket.on("data", onData);
95
+ socket.once("error", onError);
96
+ socket.once("close", onClose);
97
+ socket.once("timeout", onTimeout);
98
+
99
+ return {
100
+ read(length: number): Promise<Buffer> {
101
+ if (failure) return Promise.reject(failure);
102
+ if (buffered.length >= length) {
103
+ const value = buffered.subarray(0, length);
104
+ buffered = buffered.subarray(length);
105
+ return Promise.resolve(value);
106
+ }
107
+ return new Promise((resolve, reject) => {
108
+ waiter = { length, resolve, reject };
109
+ drain();
110
+ });
111
+ },
112
+ close(): void {
113
+ socket.off("data", onData);
114
+ socket.off("error", onError);
115
+ socket.off("close", onClose);
116
+ socket.off("timeout", onTimeout);
117
+ },
118
+ };
119
+ }
120
+
121
+ function encodeIpv6(host: string): Buffer {
122
+ const [headText, tailText] = host.split("::");
123
+ const head = headText ? headText.split(":").filter(Boolean) : [];
124
+ const tail = tailText ? tailText.split(":").filter(Boolean) : [];
125
+ const missing = 8 - head.length - tail.length;
126
+ const groups = host.includes("::")
127
+ ? [...head, ...Array.from({ length: Math.max(0, missing) }, () => "0"), ...tail]
128
+ : [...head, ...tail];
129
+ const encoded = Buffer.alloc(16);
130
+ for (let index = 0; index < 8; index++) {
131
+ encoded.writeUInt16BE(parseInt(groups[index] || "0", 16) || 0, index * 2);
132
+ }
133
+ return encoded;
134
+ }
135
+
136
+ async function openSocks5Connection(
137
+ proxy: URL,
138
+ target: { hostname: string; port: string; protocol: string; servername?: string },
139
+ ): Promise<SocksSocket> {
140
+ const socket = netConnect({
141
+ host: proxy.hostname,
142
+ port: Number(proxy.port || 1080),
143
+ });
144
+ socket.setTimeout(10_000);
145
+ const reader = createSocketReader(socket);
146
+ try {
147
+ await new Promise<void>((resolve, reject) => {
148
+ const onConnect = (): void => {
149
+ socket.off("error", onError);
150
+ resolve();
151
+ };
152
+ const onError = (err: Error): void => {
153
+ socket.off("connect", onConnect);
154
+ reject(err);
155
+ };
156
+ socket.once("connect", onConnect);
157
+ socket.once("error", onError);
158
+ });
159
+
160
+ const username = proxy.username ? decodeURIComponent(proxy.username) : "";
161
+ const password = proxy.password ? decodeURIComponent(proxy.password) : "";
162
+ const hasAuth = username.length > 0 || password.length > 0;
163
+ const methods = hasAuth ? [0x02, 0x00] : [0x00];
164
+ socket.write(Buffer.from([0x05, methods.length, ...methods]));
165
+ const methodReply = await reader.read(2);
166
+ if (methodReply[0] !== 0x05 || methodReply[1] === 0xff) {
167
+ throw new Error("SOCKS5 proxy rejected authentication methods");
168
+ }
169
+ if (methodReply[1] === 0x02) {
170
+ const user = Buffer.from(username);
171
+ const pass = Buffer.from(password);
172
+ if (user.length > 255 || pass.length > 255) {
173
+ throw new Error("SOCKS5 proxy credentials are too long");
174
+ }
175
+ socket.write(Buffer.concat([
176
+ Buffer.from([0x01, user.length]),
177
+ user,
178
+ Buffer.from([pass.length]),
179
+ pass,
180
+ ]));
181
+ const authReply = await reader.read(2);
182
+ if (authReply[0] !== 0x01 || authReply[1] !== 0x00) {
183
+ throw new Error("SOCKS5 proxy authentication failed");
184
+ }
185
+ } else if (methodReply[1] !== 0x00) {
186
+ throw new Error("SOCKS5 proxy selected an unsupported authentication method");
187
+ }
188
+
189
+ const targetHost = target.hostname;
190
+ const targetIpVersion = isIP(targetHost);
191
+ const targetAddress = targetIpVersion === 4
192
+ ? Buffer.from([0x01, ...targetHost.split(".").map((part) => Number(part))])
193
+ : targetIpVersion === 6
194
+ ? Buffer.from([0x04, ...encodeIpv6(targetHost)])
195
+ : Buffer.from([0x03, Buffer.byteLength(targetHost), ...Buffer.from(targetHost)]);
196
+ const port = Number(target.port || (target.protocol === "https:" ? 443 : 80));
197
+ if (!Number.isInteger(port) || port < 1 || port > 65_535) {
198
+ throw new Error("SOCKS5 target port is invalid");
199
+ }
200
+ const connectRequest = Buffer.alloc(3 + targetAddress.length + 2);
201
+ Buffer.from([0x05, 0x01, 0x00]).copy(connectRequest, 0);
202
+ targetAddress.copy(connectRequest, 3);
203
+ connectRequest.writeUInt16BE(port, connectRequest.length - 2);
204
+ socket.write(connectRequest);
205
+ const replyHead = await reader.read(4);
206
+ if (replyHead[0] !== 0x05 || replyHead[1] !== 0x00) {
207
+ throw new Error(`SOCKS5 proxy connection failed (code ${replyHead[1] ?? "unknown"})`);
208
+ }
209
+ const replyAddressLength = replyHead[3] === 0x01
210
+ ? 4
211
+ : replyHead[3] === 0x04
212
+ ? 16
213
+ : 1 + (await reader.read(1))[0];
214
+ await reader.read(replyAddressLength + 2);
215
+
216
+ if (target.protocol !== "https:") return socket;
217
+ const tlsSocket = tlsConnect({
218
+ socket,
219
+ servername: target.servername || target.hostname,
220
+ });
221
+ await new Promise<void>((resolve, reject) => {
222
+ tlsSocket.once("secureConnect", resolve);
223
+ tlsSocket.once("error", reject);
224
+ });
225
+ return tlsSocket;
226
+ } catch (err) {
227
+ socket.destroy();
228
+ throw err;
229
+ } finally {
230
+ reader.close();
231
+ socket.setTimeout(0);
232
+ }
233
+ }
234
+
235
+ function createSocks5Dispatcher(proxy: URL): Dispatcher {
236
+ return new Agent({
237
+ connect: (target, callback) => {
238
+ void openSocks5Connection(proxy, target)
239
+ .then((socket) => callback(null, socket))
240
+ .catch((err: unknown) => callback(err instanceof Error ? err : new Error(String(err)), null));
241
+ },
242
+ });
243
+ }
244
+
245
+ /**
246
+ * Return the reusable dispatcher for an account/provider pair. The cache key
247
+ * includes the complete normalized URL, including credentials, but that value
248
+ * is never logged or returned to callers.
249
+ */
250
+ export function getAccountProxyDispatcher(
251
+ account: AccountRuntime,
252
+ providerId: string,
253
+ ): Dispatcher | undefined {
254
+ const configured = getProviderProxyUrl(account.config, providerId)?.trim();
255
+ if (!configured) return undefined;
256
+ const key = normalizedProxyUrl(configured);
257
+ const existing = dispatchers.get(key);
258
+ if (existing) return existing;
259
+ const dispatcher = createDispatcher(key);
260
+ dispatchers.set(key, dispatcher);
261
+ return dispatcher;
262
+ }
263
+
264
+ /** Close cached agents during controlled process shutdown or test teardown. */
265
+ export async function closeProxyDispatchers(): Promise<void> {
266
+ const pending = [...dispatchers.values()].map((dispatcher) => dispatcher.close());
267
+ dispatchers.clear();
268
+ await Promise.allSettled(pending);
269
+ }
@@ -0,0 +1,70 @@
1
+ // Provider registry: maps provider ids to their adapters.
2
+ //
3
+ // To add a new provider:
4
+ // 1. Implement ProviderAdapter in src/providers/<id>/index.ts
5
+ // 2. Add an entry to PROVIDERS below
6
+ // 3. Extend AccountConfig in src/types.ts with your credential fields
7
+ // 4. Wire your login flow through `rotator login --provider <id>`
8
+
9
+ import type { ProviderAdapter } from "./adapter.js";
10
+ import { googleAntigravityAdapter } from "./google-antigravity/index.js";
11
+ import { ollamaAdapter } from "./ollama/index.js";
12
+ import { logger } from "../logger.js";
13
+ import {
14
+ DEFAULT_PROVIDER,
15
+ primaryProviderId,
16
+ hasCredential,
17
+ getCredential,
18
+ type CredentialEntry,
19
+ type AccountLike as ProviderCredentialLike,
20
+ } from "./credential-helpers.js";
21
+
22
+ export {
23
+ DEFAULT_PROVIDER,
24
+ primaryProviderId,
25
+ hasCredential,
26
+ getCredential,
27
+ type CredentialEntry,
28
+ type AccountLike as ProviderCredentialLike,
29
+ } from "./credential-helpers.js";
30
+
31
+ const PROVIDERS: Record<string, ProviderAdapter> = {
32
+ "google-antigravity": googleAntigravityAdapter,
33
+ ollama: ollamaAdapter,
34
+ };
35
+
36
+ export function getProviderAdapter(providerId: string): ProviderAdapter {
37
+ const adapter = PROVIDERS[providerId];
38
+ if (!adapter) {
39
+ throw new Error(
40
+ `Unknown provider "${providerId}". Available: ${Object.keys(PROVIDERS).join(", ")}`,
41
+ );
42
+ }
43
+ return adapter;
44
+ }
45
+
46
+ export function listProviders(): ProviderAdapter[] {
47
+ return Object.values(PROVIDERS);
48
+ }
49
+
50
+ export function isKnownProvider(providerId: string): boolean {
51
+ return Object.prototype.hasOwnProperty.call(PROVIDERS, providerId);
52
+ }
53
+
54
+ export function getProviderForAccount(
55
+ account: { credentials?: Array<{ provider: string }>; provider?: string },
56
+ providerId?: string,
57
+ ): ProviderAdapter {
58
+ const id = providerId ?? primaryProviderId(account);
59
+ try {
60
+ return getProviderAdapter(id);
61
+ } catch {
62
+ logger
63
+ .child("registry")
64
+ .warn(
65
+ `Account references unknown provider "${id}", falling back to ${DEFAULT_PROVIDER}; check config`,
66
+ );
67
+ return getProviderAdapter(DEFAULT_PROVIDER);
68
+ }
69
+ }
70
+