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,188 @@
1
+ // Ported from the ollama-rotator project (same author) into the
2
+ // tuxevil-rotator provider layer.
3
+ // Exhaustion prediction for Ollama Cloud quota pools.
4
+ //
5
+ // Ollama Cloud reports each pool as a usage FRACTION (0..1) — never absolute
6
+ // tokens. The calibration burns (tools/usage-calibration.ts, 2026-08-09)
7
+ // measured the real per-model pool sizes, so a pool's remaining tokens can
8
+ // be estimated as `(1 - fraction) * budget` and, combined with the recent
9
+ // token burn rate, projected to an exhaustion time.
10
+ //
11
+ // This module is pure: it has no I/O, no timers and no state beyond the
12
+ // per-account sliding token meters, so it can be unit-tested directly.
13
+
14
+ export interface PoolBudgetEntry {
15
+ /** Estimated tokens for a full 100% session (5h) pool. */
16
+ sessionTokens: number;
17
+ /** Estimated tokens for a full 100% weekly (7d) pool. */
18
+ weeklyTokens: number;
19
+ }
20
+
21
+ // Measured on 2026-08-09 with controlled burns (see docs/usage-calibration.md).
22
+ // Two gpt-oss:20b runs on different accounts agreed within ~1%, so these are
23
+ // per-account, per-model budgets, not per-IP.
24
+ export const CALIBRATED_MODEL_BUDGETS: Readonly<Record<string, PoolBudgetEntry>> = {
25
+ "gpt-oss:20b": { sessionTokens: 1_560_000, weeklyTokens: 4_210_000 },
26
+ "gemma4:31b": { sessionTokens: 1_150_000, weeklyTokens: 3_110_000 },
27
+ "nemotron-3-nano:30b": { sessionTokens: 1_930_000, weeklyTokens: 5_190_000 },
28
+ "gpt-oss:120b": { sessionTokens: 760_000, weeklyTokens: 2_050_000 },
29
+ "nemotron-3-super": { sessionTokens: 740_000, weeklyTokens: 2_010_000 },
30
+ "minimax-m3": { sessionTokens: 190_000, weeklyTokens: 520_000 },
31
+ "nemotron-3-ultra": { sessionTokens: 120_000, weeklyTokens: 330_000 },
32
+ };
33
+
34
+ // Uncalibrated models get the tier-1 average rounded down so prediction
35
+ // errs on the side of caution (earlier exhaustion, earlier rotation).
36
+ export const FALLBACK_POOL_BUDGET: PoolBudgetEntry = {
37
+ sessionTokens: 1_400_000,
38
+ weeklyTokens: 3_800_000,
39
+ };
40
+
41
+ export interface PoolExhaustionEstimate {
42
+ pool: "session" | "weekly";
43
+ /** Full-pool budget in tokens (from calibration or fallback). */
44
+ budgetTokens: number;
45
+ /** Estimated tokens already consumed (fraction * budget). */
46
+ usedTokens: number;
47
+ /** Estimated tokens remaining. */
48
+ remainingTokens: number;
49
+ /** Recent burn rate in tokens per minute (windowed). */
50
+ tokensPerMinute: number;
51
+ /** Minutes until the pool runs out; null when there is no recent burn. */
52
+ minutesRemaining: number | null;
53
+ /** Epoch ms at which the pool is projected to run out; null when unknown. */
54
+ exhaustedAtMs: number | null;
55
+ }
56
+
57
+ export interface ExhaustionPrediction {
58
+ /** Stable key `<email>::<model>` used for the meters. */
59
+ key: string;
60
+ model: string;
61
+ /** Whether the budget came from calibration or the fallback table. */
62
+ budgetsFrom: "calibrated" | "fallback";
63
+ session: PoolExhaustionEstimate;
64
+ weekly: PoolExhaustionEstimate;
65
+ /** The pool that runs out first; null when neither rate is known. */
66
+ soonest: PoolExhaustionEstimate | null;
67
+ }
68
+
69
+ interface ModelMeter {
70
+ /** minute-bucket ts -> tokens (minuteKey = floor(nowMs / 60_000)). */
71
+ minutes: Map<number, number>;
72
+ /** Buckets older than this are dropped on record. */
73
+ readonly windowMs: number;
74
+ }
75
+
76
+ const WINDOW_MS = 15 * 60_000;
77
+ const MIN_RATE_MINUTES = 1;
78
+
79
+ export class UsagePredictor {
80
+ private readonly budgets: Readonly<Record<string, PoolBudgetEntry>>;
81
+ private readonly meters = new Map<string, ModelMeter>();
82
+
83
+ constructor(budgets: Readonly<Record<string, PoolBudgetEntry>> = CALIBRATED_MODEL_BUDGETS) {
84
+ this.budgets = budgets;
85
+ }
86
+
87
+ /** Resolve a model's budget, falling back to the size tag and then to FALLBACK. */
88
+ getBudget(model: string): { budget: PoolBudgetEntry; from: "calibrated" | "fallback" } {
89
+ const exact = this.budgets[model];
90
+ if (exact) return { budget: exact, from: "calibrated" };
91
+ // Variants like "gpt-oss:120b-preview" share the size-tag budget of
92
+ // "gpt-oss:120b" (same weights, dated/preview suffixes only).
93
+ const [family, tag] = model.split(":");
94
+ if (family && tag) {
95
+ const sizeTag = tag.split("-")[0];
96
+ const stripped = `${family}:${sizeTag}`;
97
+ if (stripped !== model && this.budgets[stripped]) {
98
+ return { budget: this.budgets[stripped], from: "calibrated" };
99
+ }
100
+ }
101
+ return { budget: FALLBACK_POOL_BUDGET, from: "fallback" };
102
+ }
103
+
104
+ /** Record a completed request's token usage for an account+model. */
105
+ recordUsage(
106
+ accountEmail: string,
107
+ model: string,
108
+ inputTokens: number,
109
+ outputTokens: number,
110
+ nowMs: number = Date.now(),
111
+ ): void {
112
+ const tokens = Math.max(0, inputTokens) + Math.max(0, outputTokens);
113
+ if (tokens <= 0) return;
114
+ const key = `${accountEmail.toLowerCase()}::${model}`;
115
+ let meter = this.meters.get(key);
116
+ if (!meter) {
117
+ meter = { minutes: new Map(), windowMs: WINDOW_MS };
118
+ this.meters.set(key, meter);
119
+ }
120
+ const minuteKey = Math.floor(nowMs / 60_000);
121
+ meter.minutes.set(minuteKey, (meter.minutes.get(minuteKey) ?? 0) + tokens);
122
+ this.prune(meter, nowMs);
123
+ }
124
+
125
+ /** Project exhaustion for a pool given the measured usage fraction (0..1). */
126
+ predict(
127
+ accountEmail: string,
128
+ model: string,
129
+ sessionFractionUsed: number,
130
+ weeklyFractionUsed: number,
131
+ nowMs: number = Date.now(),
132
+ ): ExhaustionPrediction {
133
+ const { budget, from } = this.getBudget(model);
134
+ const key = `${accountEmail.toLowerCase()}::${model}`;
135
+ const rate = this.burnRate(key, nowMs);
136
+ const estimate = (
137
+ pool: "session" | "weekly",
138
+ fraction: number,
139
+ ): PoolExhaustionEstimate => {
140
+ const budgetTokens = pool === "session" ? budget.sessionTokens : budget.weeklyTokens;
141
+ const usedFraction = Number.isFinite(fraction) ? Math.max(0, Math.min(1, fraction)) : 0;
142
+ const usedTokens = Math.round(usedFraction * budgetTokens);
143
+ const remainingTokens = Math.max(0, budgetTokens - usedTokens);
144
+ const minutesRemaining = rate > 0 ? remainingTokens / rate : null;
145
+ return {
146
+ pool,
147
+ budgetTokens,
148
+ usedTokens,
149
+ remainingTokens,
150
+ tokensPerMinute: rate,
151
+ minutesRemaining,
152
+ exhaustedAtMs: minutesRemaining !== null ? nowMs + minutesRemaining * 60_000 : null,
153
+ };
154
+ };
155
+ const session = estimate("session", sessionFractionUsed);
156
+ const weekly = estimate("weekly", weeklyFractionUsed);
157
+ const soonest = [session, weekly].reduce<PoolExhaustionEstimate | null>(
158
+ (a, e) => {
159
+ if (e.minutesRemaining === null) return a;
160
+ if (a === null || (a.minutesRemaining !== null && e.minutesRemaining < a.minutesRemaining)) {
161
+ return e;
162
+ }
163
+ return a;
164
+ },
165
+ null,
166
+ );
167
+ return { key, model, budgetsFrom: from, session, weekly, soonest };
168
+ }
169
+
170
+ private burnRate(key: string, _nowMs: number): number {
171
+ const meter = this.meters.get(key);
172
+ if (!meter || meter.minutes.size === 0) return 0;
173
+ const keys = [...meter.minutes.keys()];
174
+ const first = Math.min(...keys);
175
+ const last = Math.max(...keys);
176
+ let total = 0;
177
+ for (const tokens of meter.minutes.values()) total += tokens;
178
+ const minutes = Math.max(MIN_RATE_MINUTES, (last - first + 1));
179
+ return total / minutes;
180
+ }
181
+
182
+ private prune(meter: ModelMeter, nowMs: number): void {
183
+ const cutoff = nowMs - meter.windowMs;
184
+ for (const minuteKey of meter.minutes.keys()) {
185
+ if (minuteKey * 60_000 < cutoff) meter.minutes.delete(minuteKey);
186
+ }
187
+ }
188
+ }
@@ -0,0 +1,160 @@
1
+ // Ported from the ollama-rotator project (same author) into the
2
+ // tuxevil-rotator provider layer.
3
+ // Persistent store of raw quota-poll observations.
4
+ //
5
+ // Every `GET /api/usage` poll returns each pool's usage as a fraction
6
+ // (0..1) with 3-decimal precision, plus per-model request counts inside
7
+ // that window. The rotator rounds these to whole percents for routing;
8
+ // this store keeps the raw values so operators can correlate tokens
9
+ // (from `rotator_spend_logs`) against usage fractions over time and
10
+ // calibrate the real per-model session/weekly budgets without burning
11
+ // quota (see docs/usage-calibration.md).
12
+ //
13
+ // Postgres-only, like spend logs: when no database is configured the
14
+ // store is a silent no-op.
15
+ //
16
+ // The table is created lazily on first write. A typical deployment
17
+ // produces ~2 rows per account per poll (session + weekly), which at the
18
+ // default 5-minute poll interval is ~576 rows/account/day.
19
+
20
+ import { rotatorEnv } from "../../env.js";
21
+ import type { OllamaUsageResponse } from "./quota.js";
22
+
23
+ const RETENTION_DEFAULT_DAYS = 14;
24
+
25
+ let schemaReady: Promise<void> | null = null;
26
+
27
+ export interface QuotaPollRecord {
28
+ accountEmail: string;
29
+ polledAt: string;
30
+ pool: "session" | "weekly";
31
+ usageRaw: number;
32
+ percentRemaining: number;
33
+ /** Per-model request counts observed inside this pool's window. */
34
+ models?: Array<{ name: string; request_count?: number }>;
35
+ }
36
+
37
+ export function isQuotaPollStoreEnabled(): boolean {
38
+ return !!(rotatorEnv("DATABASE_URL") || process.env.DATABASE_URL);
39
+ }
40
+
41
+ async function ensureSchema(): Promise<void> {
42
+ if (!schemaReady) {
43
+ schemaReady = (async () => {
44
+ const { queryDb } = await import("../../db-store.js");
45
+ await queryDb(`
46
+ CREATE TABLE IF NOT EXISTS rotator_quota_polls (
47
+ id BIGSERIAL PRIMARY KEY,
48
+ account_email TEXT NOT NULL,
49
+ polled_at TIMESTAMP WITH TIME ZONE NOT NULL,
50
+ pool VARCHAR(16) NOT NULL,
51
+ usage_raw DOUBLE PRECISION NOT NULL,
52
+ percent_remaining INTEGER NOT NULL,
53
+ models_json TEXT
54
+ );
55
+ CREATE INDEX IF NOT EXISTS idx_quota_polls_account_pool_time
56
+ ON rotator_quota_polls (account_email, pool, polled_at);
57
+ `);
58
+ })().catch((err) => {
59
+ schemaReady = null;
60
+ throw err;
61
+ });
62
+ }
63
+ return schemaReady;
64
+ }
65
+
66
+ /**
67
+ * Persist one pool's raw observation from a usage poll. Fire-and-forget:
68
+ * failures are logged and never surfaced to the polling loop.
69
+ */
70
+ export async function recordQuotaPoll(record: QuotaPollRecord): Promise<void> {
71
+ if (!isQuotaPollStoreEnabled()) return;
72
+ try {
73
+ await ensureSchema();
74
+ const { queryDb } = await import("../../db-store.js");
75
+ await queryDb(
76
+ `INSERT INTO rotator_quota_polls
77
+ (account_email, polled_at, pool, usage_raw, percent_remaining, models_json)
78
+ VALUES ($1, $2, $3, $4, $5, $6)`,
79
+ [
80
+ record.accountEmail,
81
+ record.polledAt,
82
+ record.pool,
83
+ record.usageRaw,
84
+ record.percentRemaining,
85
+ record.models && record.models.length > 0
86
+ ? JSON.stringify(record.models)
87
+ : null,
88
+ ],
89
+ );
90
+ } catch (err) {
91
+ console.error(`Failed to record quota poll for ${record.accountEmail}: ${err}`);
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Persist both pools from a parsed `GET /api/usage` response. No-op when
97
+ * the response lacks the expected shape.
98
+ */
99
+ export async function recordUsagePoll(
100
+ accountEmail: string,
101
+ polledAt: string,
102
+ data: OllamaUsageResponse,
103
+ ): Promise<void> {
104
+ const limits = data?.limits;
105
+ if (!limits || typeof limits !== "object") return;
106
+
107
+ for (const pool of ["session", "weekly"] as const) {
108
+ const info = limits[pool] as
109
+ | { usage?: number | string; models?: unknown[] }
110
+ | undefined;
111
+ if (!info || typeof info !== "object") continue;
112
+ const usageRaw =
113
+ typeof info.usage === "number"
114
+ ? info.usage
115
+ : typeof info.usage === "string"
116
+ ? parseFloat(info.usage)
117
+ : NaN;
118
+ if (!Number.isFinite(usageRaw)) continue;
119
+
120
+ const models = Array.isArray(info.models)
121
+ ? (info.models.filter(
122
+ (m): m is { name: string; request_count?: number } =>
123
+ !!m && typeof m === "object" && typeof (m as { name?: unknown }).name === "string",
124
+ ))
125
+ : undefined;
126
+
127
+ await recordQuotaPoll({
128
+ accountEmail,
129
+ polledAt,
130
+ pool,
131
+ usageRaw,
132
+ percentRemaining: Math.max(0, Math.min(100, Math.round((1 - usageRaw) * 100))),
133
+ models,
134
+ });
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Delete polls older than `days`. Returns the number of rows removed.
140
+ */
141
+ export async function pruneQuotaPolls(days: number = RETENTION_DEFAULT_DAYS): Promise<number> {
142
+ if (!isQuotaPollStoreEnabled()) return 0;
143
+ try {
144
+ await ensureSchema();
145
+ const { queryDb } = await import("../../db-store.js");
146
+ const res = await queryDb<{ deleted: string }>(
147
+ `WITH deleted AS (
148
+ DELETE FROM rotator_quota_polls
149
+ WHERE polled_at < NOW() - ($1 || ' days')::interval
150
+ RETURNING id
151
+ )
152
+ SELECT COUNT(*)::text as deleted FROM deleted`,
153
+ [String(days)],
154
+ );
155
+ return parseInt(res.rows[0]?.deleted || "0", 10);
156
+ } catch (err) {
157
+ console.error(`Failed to prune quota polls: ${err}`);
158
+ return 0;
159
+ }
160
+ }
@@ -0,0 +1,189 @@
1
+ // Ollama Cloud quota polling: `GET /api/usage` → session/weekly pools.
2
+ //
3
+ // Ported from the ollama-rotator project (same author) into the
4
+ // tuxevil-rotator provider layer.
5
+
6
+ import { fetchWithRetry } from "../../fetch-with-retry.js";
7
+ import { OLLAMA_USAGE_URL, OLLAMA_USER_AGENT } from "../../types.js";
8
+ import { getOllamaApiKey } from "./credentials.js";
9
+ import type { AccountRuntime, ModelQuota } from "../../types.js";
10
+ import type { QuotaFetchContext } from "../adapter.js";
11
+ import { recordUsagePoll } from "./quota-poll-store.js";
12
+ import {
13
+ nextWeeklyResetMs,
14
+ sessionWindowEndMs,
15
+ SESSION_WINDOW_MS,
16
+ } from "./usage-windows.js";
17
+ import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
18
+
19
+ /**
20
+ * Poll `GET /api/usage` for one account and store the parsed pool quotas.
21
+ * Non-2xx responses flag the account (401/403) via the context callbacks;
22
+ * network errors are swallowed (quota stays stale, rotation falls back to
23
+ * request-count based rotation).
24
+ */
25
+ export async function fetchProviderUsage(
26
+ account: AccountRuntime,
27
+ ctx: QuotaFetchContext,
28
+ ): Promise<void> {
29
+ try {
30
+ const response = await fetchWithRetry(OLLAMA_USAGE_URL, {
31
+ method: "GET",
32
+ headers: {
33
+ Authorization: `Bearer ${getOllamaApiKey(account.config) ?? ""}`,
34
+ "User-Agent": OLLAMA_USER_AGENT,
35
+ },
36
+ timeoutMs: 8000,
37
+ dispatcher: getAccountProxyDispatcher(account, "ollama"),
38
+ });
39
+
40
+ if (!response.ok) {
41
+ if (response.status === 401 || response.status === 403) {
42
+ const errorText = await response.text().catch(() => "");
43
+ ctx.log(
44
+ `${account.config.email}: usage API returned ${response.status}, flagging account`,
45
+ );
46
+ ctx.reportQuotaPollFlag(account, response.status, errorText);
47
+ ctx.markFlagged(
48
+ account,
49
+ `Usage API ${response.status}: ${errorText}`,
50
+ { triggerProtectivePause: false },
51
+ );
52
+ }
53
+ return;
54
+ }
55
+
56
+ const data = (await response.json()) as OllamaUsageResponse;
57
+ const oldQuota = account.quota || [];
58
+ const fresh = extractUsagePools(data, oldQuota);
59
+ // Drop the previous Ollama entries so the new ones fully replace
60
+ // them; keep entries from OTHER providers (Antigravity) so multi-
61
+ // provider accounts accumulate quotas across credentials.
62
+ const otherProviders = (oldQuota || []).filter(
63
+ (q) => (q as { providerId?: string }).providerId &&
64
+ (q as { providerId?: string }).providerId !== "ollama",
65
+ );
66
+ fresh.forEach(
67
+ (q) => ((q as { providerId?: string }).providerId = "ollama"),
68
+ );
69
+ account.quota = [...otherProviders, ...fresh];
70
+ account.lastQuotaPoll = Date.now();
71
+ void recordUsagePoll(account.config.email, new Date().toISOString(), data);
72
+
73
+ // Stash the provider-local poll log for the rotator to emit as a
74
+ // single consolidated line per cycle.
75
+ account.lastPollByProvider ??= {};
76
+ account.lastPollByProvider["ollama"] = account.quota
77
+ .filter(
78
+ (q) => (q as { providerId?: string }).providerId === "ollama",
79
+ )
80
+ .map((q) => {
81
+ const remain = q.resetTime
82
+ ? Math.round(
83
+ (new Date(q.resetTime).getTime() - Date.now()) / 60000,
84
+ ) + "m"
85
+ : "no_reset";
86
+ const fraction =
87
+ typeof q.usageRaw === "number" ? `@${q.usageRaw.toFixed(3)}` : "";
88
+ return `[${q.modelKey}: ${q.timerType} ${q.percentRemaining}%${fraction} in ${remain}]`;
89
+ })
90
+ .join(" | ");
91
+ } catch {
92
+ // Network error, skip
93
+ }
94
+ }
95
+
96
+ export interface OllamaUsageResponse {
97
+ limits?: Record<
98
+ string,
99
+ | { usage?: number | string; models?: unknown[] }
100
+ | undefined
101
+ >;
102
+ }
103
+
104
+ /**
105
+ * Parse `GET /api/usage` into the two Ollama quota pools (session + weekly).
106
+ * The API reports each pool's usage as a fraction (0..1); reset times are
107
+ * computed from the window rules in ./usage-windows.ts, anchored at the
108
+ * first observed usage for the session pool.
109
+ */
110
+ export function extractUsagePools(
111
+ data: OllamaUsageResponse,
112
+ oldQuota: ModelQuota[],
113
+ ): ModelQuota[] {
114
+ const quotas: ModelQuota[] = [];
115
+ const now = Date.now();
116
+ const limits = data?.limits;
117
+ if (!limits || typeof limits !== "object") return quotas;
118
+
119
+ for (const pool of ["session", "weekly"] as const) {
120
+ const info = limits[pool];
121
+ if (!info || typeof info !== "object") continue;
122
+
123
+ const usageFraction =
124
+ typeof info.usage === "number"
125
+ ? info.usage
126
+ : typeof info.usage === "string"
127
+ ? parseFloat(info.usage)
128
+ : NaN;
129
+ if (!Number.isFinite(usageFraction)) continue;
130
+
131
+ const percentRemaining = Math.max(
132
+ 0,
133
+ Math.min(100, Math.round((1 - usageFraction) * 100)),
134
+ );
135
+
136
+ if (pool === "weekly") {
137
+ quotas.push({
138
+ modelKey: "weekly",
139
+ displayName: "Weekly",
140
+ percentRemaining,
141
+ usageRaw: usageFraction,
142
+ resetTime: new Date(nextWeeklyResetMs(now)).toISOString(),
143
+ timerType: "7d",
144
+ });
145
+ continue;
146
+ }
147
+
148
+ // session: active only while usage > 0. Anchor the window at the
149
+ // first observation of usage (or a detected reset) and keep that
150
+ // anchor while the window is still valid.
151
+ const running = usageFraction > 0;
152
+ const old = oldQuota.find((q) => q.modelKey === "session");
153
+ let windowStart: number | null = null;
154
+ if (running) {
155
+ const oldUsed =
156
+ old && old.percentRemaining >= 0
157
+ ? 1 - old.percentRemaining / 100
158
+ : NaN;
159
+ const resetDetected =
160
+ Number.isFinite(oldUsed) && usageFraction < oldUsed - 0.01;
161
+ const oldAnchor = old?.resetTime
162
+ ? new Date(old.resetTime).getTime() - SESSION_WINDOW_MS
163
+ : NaN;
164
+ if (
165
+ resetDetected ||
166
+ !Number.isFinite(oldAnchor) ||
167
+ now >= oldAnchor + SESSION_WINDOW_MS
168
+ ) {
169
+ windowStart = now;
170
+ } else {
171
+ windowStart = oldAnchor;
172
+ }
173
+ }
174
+
175
+ quotas.push({
176
+ modelKey: "session",
177
+ displayName: "Session",
178
+ percentRemaining,
179
+ usageRaw: usageFraction,
180
+ resetTime:
181
+ windowStart !== null
182
+ ? new Date(sessionWindowEndMs(windowStart)).toISOString()
183
+ : null,
184
+ timerType: windowStart !== null ? "5h" : "fresh",
185
+ });
186
+ }
187
+
188
+ return quotas;
189
+ }