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,59 @@
1
+ // API key validation for the Ollama Cloud (ollama.com) login flows.
2
+ // Both the CLI (login.ts) and the dashboard (onboarding.ts) use this.
3
+
4
+ import { fetchWithRetry } from "../../fetch-with-retry.js";
5
+ import { OLLAMA_USAGE_URL, OLLAMA_USER_AGENT } from "../../types.js";
6
+
7
+ export type ApiKeyValidationResult =
8
+ | { ok: true }
9
+ | { ok: false; status: number; error: string };
10
+
11
+ /**
12
+ * Validate an Ollama Cloud API key by hitting `GET /api/usage` with it.
13
+ * 200 → valid key. 401/403 → invalid/revoked key. Anything else → treated
14
+ * as inconclusive (still an error, but the key may be fine).
15
+ */
16
+ export async function validateApiKey(
17
+ apiKey: string,
18
+ ): Promise<ApiKeyValidationResult> {
19
+ try {
20
+ const response = await fetchWithRetry(OLLAMA_USAGE_URL, {
21
+ method: "GET",
22
+ headers: {
23
+ Authorization: `Bearer ${apiKey.trim()}`,
24
+ "User-Agent": OLLAMA_USER_AGENT,
25
+ },
26
+ timeoutMs: 10_000,
27
+ });
28
+
29
+ if (response.ok) return { ok: true };
30
+
31
+ const body = await response.text().catch(() => "");
32
+ if (response.status === 401 || response.status === 403) {
33
+ return {
34
+ ok: false,
35
+ status: response.status,
36
+ error:
37
+ body.trim().slice(0, 300) ||
38
+ "Invalid API key (unauthorized). Create one at ollama.com/settings/keys.",
39
+ };
40
+ }
41
+ return {
42
+ ok: false,
43
+ status: response.status,
44
+ error: `Usage endpoint returned HTTP ${response.status}: ${body.trim().slice(0, 300)}`,
45
+ };
46
+ } catch (err) {
47
+ return {
48
+ ok: false,
49
+ status: 0,
50
+ error: `Network error while validating API key: ${err instanceof Error ? err.message : String(err)}`,
51
+ };
52
+ }
53
+ }
54
+
55
+ /** Build a stable account identifier for a key that has no email attached. */
56
+ export function defaultAccountEmail(apiKey: string): string {
57
+ const suffix = apiKey.trim().slice(-6).toLowerCase();
58
+ return `key-${suffix}@ollama.local`;
59
+ }
@@ -0,0 +1,28 @@
1
+ // Ollama Cloud credential validation: an API key is valid iff it is a
2
+ // non-empty string (keys never expire; network validation happens during
3
+ // login via validateApiKey).
4
+
5
+ import type { AccountConfig } from "../../types.js";
6
+ import type { CredentialValidationResult } from "../adapter.js";
7
+ import { getCredential } from "../registry.js";
8
+
9
+ /**
10
+ * Ollama API key for an account: the `ollama` credential in the
11
+ * parent-account model, falling back to the legacy flat `apiKey` field.
12
+ */
13
+ export function getOllamaApiKey(config: AccountConfig): string | undefined {
14
+ return getCredential(config, "ollama")?.apiKey;
15
+ }
16
+
17
+ export async function validateCredentials(
18
+ config: AccountConfig,
19
+ ): Promise<CredentialValidationResult> {
20
+ if (typeof getOllamaApiKey(config) !== "string" || getOllamaApiKey(config)!.trim() === "") {
21
+ return {
22
+ ok: false,
23
+ status: 0,
24
+ error: "Ollama account is missing an apiKey",
25
+ };
26
+ }
27
+ return { ok: true };
28
+ }
@@ -0,0 +1,306 @@
1
+ // Ollama Cloud request forwarding: `POST /api/chat` (NDJSON streaming).
2
+ //
3
+ // Ported from the ollama-rotator project (same author) into the
4
+ // tuxevil-rotator provider layer.
5
+
6
+ import {
7
+ applyModelAlias,
8
+ OLLAMA_CHAT_ENDPOINTS,
9
+ OLLAMA_USER_AGENT,
10
+ } from "../../types.js";
11
+ import type { AccountRuntime } from "../../types.js";
12
+ import type { ForwardedResponse, RequestBody } from "../../proxy.js";
13
+ import { isRecord } from "../../compat/schema-sanitizer.js";
14
+ import { getOllamaApiKey } from "./credentials.js";
15
+ import {
16
+ extractTextFromUnknownContent,
17
+ normalizeContentBlocks,
18
+ } from "../google-antigravity/translators.js";
19
+ import type { StreamAccumulator, TokenUsage } from "../adapter.js";
20
+ import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
21
+ import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
22
+
23
+ const OLLAMA_BENCHMARK_MODEL = "gpt-oss:20b";
24
+
25
+ /**
26
+ * Normalize one upstream message for Ollama's Go API, which requires
27
+ * `messages[].content` to be a plain string (it rejects OpenAI-style content
28
+ * arrays with `cannot unmarshal array ... into Go struct field
29
+ * ChatRequest.messages.content of type string`). Text blocks are flattened
30
+ * into the string; image_url blocks are moved to the message's `images` field
31
+ * (Ollama's native multimodal format).
32
+ */
33
+ function normalizeOllamaMessageContent(
34
+ msg: Record<string, unknown>,
35
+ ): void {
36
+ const content = msg.content;
37
+ if (
38
+ typeof content === "string" ||
39
+ content === null ||
40
+ content === undefined
41
+ ) {
42
+ return;
43
+ }
44
+ if (!Array.isArray(content)) {
45
+ msg.content = extractTextFromUnknownContent(content);
46
+ return;
47
+ }
48
+ const blocks = normalizeContentBlocks(content);
49
+ const parts = Array.isArray(blocks) ? blocks : [];
50
+ const textParts: string[] = [];
51
+ const images: string[] = [];
52
+ for (const block of parts) {
53
+ if (!isRecord(block)) continue;
54
+ if (block.type === "text" && typeof block.text === "string") {
55
+ if (block.text) textParts.push(block.text);
56
+ } else if (
57
+ block.type === "image_url" &&
58
+ isRecord(block.image_url) &&
59
+ typeof block.image_url.url === "string"
60
+ ) {
61
+ images.push(block.image_url.url);
62
+ }
63
+ }
64
+ msg.content = textParts.join("\n");
65
+ if (images.length > 0) {
66
+ const existing = Array.isArray(msg.images) ? msg.images : [];
67
+ msg.images = [...existing, ...images];
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Forward a request to Ollama Cloud. The payload shape matches Ollama's
73
+ * native `/api/chat` (messages, stream, tools, options); OpenAI-style
74
+ * bodies are translated by the compat layer before this function. Content
75
+ * arrays are flattened to plain strings and image blocks are moved to the
76
+ * native `images` field before forwarding, since Ollama's Go API rejects
77
+ * array content.
78
+ */
79
+ export function buildOllamaPayload(body: RequestBody): Record<string, unknown> {
80
+ const request = isRecord(body.request) ? body.request : {};
81
+ const rawMessages = Array.isArray(request.messages) ? request.messages : [];
82
+ const messages = rawMessages.map((msg) => {
83
+ if (!isRecord(msg)) return msg;
84
+ const normalized = { ...msg };
85
+ normalizeOllamaMessageContent(normalized);
86
+ return normalized;
87
+ });
88
+ const payload: Record<string, unknown> = {
89
+ model: applyModelAlias(body.model),
90
+ messages,
91
+ stream: request.stream === false ? false : true,
92
+ };
93
+ if (Array.isArray(request.tools) && request.tools.length > 0) {
94
+ payload.tools = request.tools;
95
+ }
96
+ if (isRecord(request.options)) {
97
+ payload.options = request.options;
98
+ }
99
+ return payload;
100
+ }
101
+
102
+ const HOP_BY_HOP = new Set([
103
+ "connection",
104
+ "keep-alive",
105
+ "proxy-authenticate",
106
+ "proxy-authorization",
107
+ "te",
108
+ "trailers",
109
+ "transfer-encoding",
110
+ "upgrade",
111
+ "x-forwarded-for",
112
+ "x-forwarded-host",
113
+ "x-forwarded-proto",
114
+ "x-forwarded-port",
115
+ "x-real-ip",
116
+ "forwarded",
117
+ "via",
118
+ ]);
119
+
120
+ /** Forward `POST /api/chat` with the account's Ollama API key. */
121
+ export async function forwardRequest(
122
+ account: AccountRuntime,
123
+ body: RequestBody,
124
+ originalHeaders: Record<string, string>,
125
+ signal?: AbortSignal,
126
+ ): Promise<ForwardedResponse> {
127
+ const payload = buildOllamaPayload(body);
128
+ const requestBody = JSON.stringify(payload);
129
+
130
+ const forwardHeaders: Record<string, string> = {
131
+ ...originalHeaders,
132
+ "Content-Type": "application/json",
133
+ Accept: "application/x-ndjson",
134
+ };
135
+ for (const key of Object.keys(forwardHeaders)) {
136
+ const lowerKey = key.toLowerCase();
137
+ if (HOP_BY_HOP.has(lowerKey) || lowerKey === "authorization") {
138
+ delete forwardHeaders[key];
139
+ }
140
+ }
141
+ forwardHeaders["Authorization"] = `Bearer ${getOllamaApiKey(account.config) ?? ""}`;
142
+ forwardHeaders["User-Agent"] = OLLAMA_USER_AGENT;
143
+ delete forwardHeaders["host"];
144
+ delete forwardHeaders["connection"];
145
+ delete forwardHeaders["transfer-encoding"];
146
+ delete forwardHeaders["content-length"];
147
+
148
+ const endpoint = OLLAMA_CHAT_ENDPOINTS[0] || "https://ollama.com/api/chat";
149
+ const response = await fetch(endpoint, {
150
+ method: "POST",
151
+ headers: forwardHeaders,
152
+ body: requestBody,
153
+ signal,
154
+ dispatcher: getAccountProxyDispatcher(account, "ollama"),
155
+ } as RequestInitWithDispatcher);
156
+
157
+ return { response, endpoint };
158
+ }
159
+
160
+ /** Max bytes kept in the NDJSON buffer. */
161
+ const NDJSON_BUFFER_MAX = 1024 * 1024;
162
+
163
+ /**
164
+ * Parse one Ollama NDJSON line: accumulate message content and, on the
165
+ * final `done` record, capture token usage.
166
+ */
167
+ export function extractOllamaUsageFromLine(
168
+ parsed: Record<string, unknown>,
169
+ ): TokenUsage | null {
170
+ if (parsed.done !== true) return null;
171
+ const inputTokens =
172
+ typeof parsed.prompt_eval_count === "number" ? parsed.prompt_eval_count : 0;
173
+ const outputTokens =
174
+ typeof parsed.eval_count === "number" ? parsed.eval_count : 0;
175
+ return inputTokens > 0 || outputTokens > 0
176
+ ? { inputTokens, outputTokens }
177
+ : null;
178
+ }
179
+
180
+ /** NDJSON line-split accumulator implementing the StreamAccumulator contract. */
181
+ export class OllamaNdjsonAccumulator implements StreamAccumulator {
182
+ private buffer = "";
183
+ private accumulatedText = "";
184
+ private readonly maxBytes: number;
185
+
186
+ constructor(maxBytes: number = NDJSON_BUFFER_MAX) {
187
+ this.maxBytes = maxBytes;
188
+ }
189
+
190
+ append(chunkText: string): TokenUsage | null {
191
+ this.buffer += chunkText;
192
+ if (this.buffer.length > this.maxBytes) {
193
+ this.buffer = this.buffer.slice(-this.maxBytes);
194
+ }
195
+ let extracted: TokenUsage | null = null;
196
+ let newlineIdx = this.buffer.indexOf("\n");
197
+ while (newlineIdx !== -1) {
198
+ const line = this.buffer.slice(0, newlineIdx).trim();
199
+ this.buffer = this.buffer.slice(newlineIdx + 1);
200
+ if (!line) {
201
+ newlineIdx = this.buffer.indexOf("\n");
202
+ continue;
203
+ }
204
+ try {
205
+ const parsed = JSON.parse(line) as Record<string, unknown>;
206
+ const usage = extractOllamaUsageFromLine(parsed);
207
+ if (usage && !extracted) extracted = usage;
208
+ const message = isRecord(parsed.message) ? parsed.message : null;
209
+ const text =
210
+ message && typeof message.content === "string"
211
+ ? message.content
212
+ : "";
213
+ if (text && this.accumulatedText.length < 100000) {
214
+ this.accumulatedText += text;
215
+ }
216
+ } catch {
217
+ // Ignore malformed NDJSON lines
218
+ }
219
+ newlineIdx = this.buffer.indexOf("\n");
220
+ }
221
+ return extracted;
222
+ }
223
+
224
+ getText(): string {
225
+ return this.accumulatedText;
226
+ }
227
+
228
+ final(): TokenUsage | null {
229
+ const line = this.buffer.trim();
230
+ this.buffer = "";
231
+ if (!line) return null;
232
+ try {
233
+ const parsed = JSON.parse(line) as Record<string, unknown>;
234
+ const usage = extractOllamaUsageFromLine(parsed);
235
+ const message = isRecord(parsed.message) ? parsed.message : null;
236
+ const text =
237
+ message && typeof message.content === "string" ? message.content : "";
238
+ if (text && this.accumulatedText.length < 100000) {
239
+ this.accumulatedText += text;
240
+ }
241
+ return usage;
242
+ } catch {
243
+ return null;
244
+ }
245
+ }
246
+ }
247
+
248
+ const BENCHMARK_PROMPT = "Reply with exactly: OK";
249
+ const BENCHMARK_MAX_OUTPUT_TOKENS = 16;
250
+
251
+ function benchmarkUsage(raw: string): { outputTokens: number } | null {
252
+ let outputTokens = 0;
253
+ for (const line of raw.split(/\r?\n/)) {
254
+ if (!line.trim()) continue;
255
+ try {
256
+ const parsed = JSON.parse(line) as Record<string, unknown>;
257
+ if (parsed.done === true && typeof parsed.eval_count === "number") {
258
+ outputTokens = parsed.eval_count;
259
+ }
260
+ } catch {
261
+ // Ignore malformed NDJSON lines
262
+ }
263
+ }
264
+ return { outputTokens };
265
+ }
266
+
267
+ function benchmarkText(raw: string): string {
268
+ let text = "";
269
+ for (const line of raw.split(/\r?\n/)) {
270
+ if (!line.trim()) continue;
271
+ try {
272
+ const parsed = JSON.parse(line) as Record<string, unknown>;
273
+ const message = isRecord(parsed.message) ? parsed.message : null;
274
+ const content =
275
+ message && typeof message.content === "string" ? message.content : "";
276
+ if (content) text += content;
277
+ } catch {
278
+ // Ignore malformed NDJSON lines
279
+ }
280
+ }
281
+ return text;
282
+ }
283
+
284
+ /**
285
+ * Benchmark spec for Ollama accounts: chat with the cheapest calibrated
286
+ * model and read eval_count from the terminal NDJSON record.
287
+ */
288
+ export function getBenchmarkSpec(): {
289
+ body: RequestBody;
290
+ parseUsage(raw: string): { outputTokens: number } | null;
291
+ parseText(raw: string): string;
292
+ } {
293
+ return {
294
+ body: {
295
+ project: "",
296
+ model: OLLAMA_BENCHMARK_MODEL,
297
+ request: {
298
+ messages: [{ role: "user", content: BENCHMARK_PROMPT }],
299
+ options: { num_predict: BENCHMARK_MAX_OUTPUT_TOKENS },
300
+ stream: false,
301
+ },
302
+ },
303
+ parseUsage: benchmarkUsage,
304
+ parseText: benchmarkText,
305
+ };
306
+ }
@@ -0,0 +1,85 @@
1
+ // Ollama Cloud provider adapter.
2
+ //
3
+ // Implements the ProviderAdapter contract for Ollama Cloud (ollama.com):
4
+ // static API keys, NDJSON `/api/chat` forwarding, and session/weekly
5
+ // usage-fraction quota pools with exhaustion prediction.
6
+ //
7
+ // Ported from the ollama-rotator project (same author) into the
8
+ // tuxevil-rotator provider layer.
9
+
10
+ import type { ProviderAdapter, ProviderFeatures } from "../adapter.js";
11
+ import { fetchProviderUsage } from "./quota.js";
12
+ import {
13
+ forwardRequest,
14
+ OllamaNdjsonAccumulator,
15
+ getBenchmarkSpec,
16
+ } from "./forward.js";
17
+ import { runLogin } from "./login.js";
18
+ import { getOllamaApiKey, validateCredentials } from "./credentials.js";
19
+ import { UsagePredictor, type ExhaustionPrediction } from "./prediction.js";
20
+ import type { AccountRuntime } from "../../types.js";
21
+
22
+ const OLLAMA_TIER_RANKING = {
23
+ max: 0,
24
+ team: 1,
25
+ pro: 2,
26
+ free: 3,
27
+ unknown: 4,
28
+ };
29
+
30
+ export const ollamaAdapter: ProviderAdapter = {
31
+ id: "ollama",
32
+ displayName: "Ollama Cloud",
33
+ credentialKind: "api-key",
34
+ tierRanking: OLLAMA_TIER_RANKING,
35
+
36
+ features: {
37
+ circuitBreakers: true,
38
+ concurrencyLimits: true,
39
+ proactiveRotation: true,
40
+ } satisfies ProviderFeatures,
41
+
42
+ runLogin,
43
+
44
+ validateCredentials,
45
+
46
+ hasValidCredentials(account: AccountRuntime): boolean {
47
+ return typeof getOllamaApiKey(account.config) === "string" &&
48
+ (getOllamaApiKey(account.config) ?? "").length > 0;
49
+ },
50
+
51
+ // Ollama API keys never expire: there is no refresh flow. 401/403
52
+ // responses are handled by the response classifier (marked flagged).
53
+ async ensureValidToken(): Promise<void> {},
54
+
55
+ getAuthHeader(account: AccountRuntime): string {
56
+ return `Bearer ${getOllamaApiKey(account.config) ?? ""}`;
57
+ },
58
+
59
+ shouldRetryOnQuotaExhaustion(): boolean {
60
+ // Ollama Cloud usage is tied to the API-key account, so another account
61
+ // can be attempted without treating the pool as globally exhausted.
62
+ return true;
63
+ },
64
+
65
+ async fetchQuota(
66
+ account: AccountRuntime,
67
+ ctx,
68
+ ): Promise<void> {
69
+ await fetchProviderUsage(account, ctx);
70
+ },
71
+
72
+ forwardRequest,
73
+ createStreamAccumulator: () => new OllamaNdjsonAccumulator(),
74
+
75
+ getKickstartModelForPool(quotaModelKey: string): string | undefined {
76
+ // Only the session pool can be kickstarted for Ollama accounts.
77
+ return quotaModelKey === "session" ? "gpt-oss:20b" : undefined;
78
+ },
79
+
80
+ getBenchmark() {
81
+ return getBenchmarkSpec();
82
+ },
83
+ };
84
+
85
+ export type { ExhaustionPrediction, UsagePredictor };
@@ -0,0 +1,55 @@
1
+ // Ollama Cloud login flow: paste an API key, validate it against the
2
+ // usage endpoint, and derive a stable account email.
3
+ //
4
+ // Ported from the ollama-rotator project (same author) into the
5
+ // tuxevil-rotator provider layer.
6
+
7
+ import { createInterface } from "node:readline";
8
+ import type { AccountConfig } from "../../types.js";
9
+ import { defaultAccountEmail, validateApiKey } from "./api-key-validation.js";
10
+
11
+ function askQuestion(prompt: string): Promise<string> {
12
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
13
+ return new Promise((resolve) => {
14
+ rl.question(prompt, (answer) => {
15
+ rl.close();
16
+ resolve(answer.trim());
17
+ });
18
+ });
19
+ }
20
+
21
+ /**
22
+ * Interactive Ollama Cloud login: ask for an API key, validate it against
23
+ * `GET /api/usage`, and return an account config (email derived from the
24
+ * key suffix unless the user overrides it).
25
+ */
26
+ export async function runLogin(): Promise<AccountConfig> {
27
+ console.log("=== Tuxevil Rotator - Add Ollama Cloud Account ===");
28
+ console.log();
29
+
30
+ const apiKey = await askQuestion(
31
+ "Paste your Ollama Cloud API key (ollama.com/settings/keys): ",
32
+ );
33
+
34
+ if (!apiKey) {
35
+ console.error("No API key provided.");
36
+ process.exit(1);
37
+ }
38
+
39
+ console.log("Validating API key against ollama.com...");
40
+ const result = await validateApiKey(apiKey);
41
+ if (!result.ok) {
42
+ console.error(`API key validation failed: ${result.error}`);
43
+ process.exit(1);
44
+ }
45
+
46
+ const label = await askQuestion(
47
+ `Account label (default: ${defaultAccountEmail(apiKey).split("@")[0]}): `,
48
+ );
49
+
50
+ return {
51
+ email: defaultAccountEmail(apiKey),
52
+ apiKey,
53
+ label: label || defaultAccountEmail(apiKey).split("@")[0],
54
+ };
55
+ }