tuxevil-rotator 3.2.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.2.1] - 2026-08-16
4
+
5
+ ### Fixed
6
+
7
+ - **Credential persistence across restarts with PostgreSQL**: When PostgreSQL is configured as the account store, credentials added via the login panel (`ollama`, `opencode-zen`, `openai-codex`) were stored using the legacy flat `apiKey` field instead of the structured `credentials[{provider, apiKey}]` shape. On the next quota poll, the rotator read back the correct structured credential from the database but the Ollama provider adapter found nothing, flagging the account with 401. The `handleOllamaCliLogin` onboarding handler now always persists as `credentials: [{ provider: "ollama", apiKey }]`.
8
+
9
+ - **OpenCode Zen and sibling credentials lost on `replaceConfig`**: When the dashboard config editor saved a new config (e.g. after changing routing settings), `replaceConfig()` merged credentials correctly in memory but then persisted the original unmerged `config.accounts` payload to PostgreSQL. After the next restart the database-sourced config lacked the `opencode-zen` (or `ollama`) credential entirely. The fix builds the merged account list first and persists that merged list, so no credential is ever dropped by a config save.
10
+
11
+ - **Legacy Ollama JSON re-imported on every boot with PostgreSQL**: `importLegacyOllamaRotatorAccounts()` ran unconditionally at startup, allowing a stale `~/.ollama-rotator/accounts.json` to re-introduce revoked API keys each time the service restarted. The import is now skipped when `TUXEVIL_ROTATOR_DATABASE_URL` is configured, making PostgreSQL the sole authoritative source.
12
+
13
+ - **`accounts.json` disk file migrated into PostgreSQL on startup**: `PostgresSettingsRepository.init()` migrated any on-disk `accounts.json` into the database on first boot. If the file contained an outdated credential it would silently overwrite the database value. The `accounts_json` key is now excluded from the disk-to-database migration path; only non-credential settings (state, token usage, admin token) are migrated from disk.
14
+
15
+ - **PostgreSQL writes were fire-and-forget**: Account config writes to PostgreSQL were non-blocking background promises. A service restart occurring within the write window could lose the latest credential update. All settings writes are now awaited before returning a success response.
16
+
17
+ - **`mergeCredentials` called on pre-normalization data in `addAccountToConfig`**: The merge was applied against the raw (possibly legacy-shaped) existing account instead of its normalized form, causing duplicate or missing credentials in edge cases. The existing account is now normalized before merging.
18
+
19
+ ### Changed
20
+
21
+ - **`replaceConfig` syncs in-memory and persisted accounts atomically**: The merged account list is computed once and used for both `this.accounts`/`this.config` and the PostgreSQL write, preventing divergence.
22
+
3
23
  ## [3.2.0] - 2026-08-14
4
24
 
5
25
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tuxevil-rotator",
3
- "version": "3.2.0",
3
+ "version": "3.2.1",
4
4
  "description": "Multi-provider, multi-account AI proxy rotator with per-model routing, real-time quota tracking, and infringement detection (Google Antigravity, Ollama Cloud)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -92,7 +92,7 @@ function validateCredentialLengths(
92
92
 
93
93
  export { validateAccountConfigLengths };
94
94
 
95
- function mergeCredentials(
95
+ export function mergeCredentials(
96
96
  existing: AccountConfig["credentials"] | undefined,
97
97
  incoming: AccountConfig["credentials"] | undefined,
98
98
  ): AccountConfig["credentials"] {
@@ -141,10 +141,11 @@ export async function addAccountToConfig(
141
141
  if (existing) {
142
142
  assertCodexIdentityCompatible(existing, entryNorm);
143
143
  validateCredentialLengths(entryNorm.credentials);
144
+ const existingNorm = normalizeAccountConfig(existing);
144
145
  config.accounts[config.accounts.indexOf(existing)] = {
145
- ...normalizeAccountConfig(existing),
146
+ ...existingNorm,
146
147
  ...entryNorm,
147
- credentials: mergeCredentials(existing.credentials, entryNorm.credentials),
148
+ credentials: mergeCredentials(existingNorm.credentials, entryNorm.credentials),
148
149
  };
149
150
  await saveAccountsConfig(config);
150
151
  return { isNew: false };
package/src/index.ts CHANGED
@@ -21,7 +21,7 @@ import {
21
21
  } from "./compat.js";
22
22
  import { setModelAliasesOverride } from "./types.js";
23
23
  import { readTextFile, writeTextFileAtomic } from "./storage.js";
24
- import { initDb } from "./db-store.js";
24
+ import { initDb, isDbConfigured } from "./db-store.js";
25
25
  import { runKeyMigrations } from "./key-migrations.js";
26
26
  import { flushSpendLogs, stopRetentionCleanup, startRetentionCleanup } from "./spend-logger.js";
27
27
  import { stopPendingSessionReaper } from "./onboarding.js";
@@ -170,7 +170,11 @@ export async function main(): Promise<void> {
170
170
 
171
171
  await initDb();
172
172
  await runKeyMigrations();
173
- await importLegacyOllamaRotatorAccounts();
173
+ // PostgreSQL is the authoritative account store. Importing the legacy
174
+ // Ollama JSON here would allow a stale disk credential to re-enter on boot.
175
+ if (!isDbConfigured()) {
176
+ await importLegacyOllamaRotatorAccounts();
177
+ }
174
178
  startRetentionCleanup();
175
179
 
176
180
  const config = loadConfig();
package/src/onboarding.ts CHANGED
@@ -924,12 +924,12 @@ async function handleOllamaCliLogin(
924
924
  return;
925
925
  }
926
926
 
927
- const entry = {
927
+ const entry: AccountConfig = {
928
928
  email: email || defaultAccountEmail(apiKey),
929
- apiKey,
929
+ credentials: [{ provider: "ollama", apiKey }],
930
930
  label: email || defaultAccountEmail(apiKey).split("@")[0],
931
931
  };
932
- if (entry.label.length > MAX_ACCOUNT_LABEL_LENGTH) {
932
+ if (typeof entry.label !== "string" || entry.label.length > MAX_ACCOUNT_LABEL_LENGTH) {
933
933
  res.writeHead(400, { "Content-Type": "application/json" });
934
934
  res.end(JSON.stringify({ ok: false, error: "Account label too long" }));
935
935
  return;
package/src/rotator.ts CHANGED
@@ -41,6 +41,7 @@ import {
41
41
  applyConfigDefaults,
42
42
  saveAccountsConfig,
43
43
  removeAccountFromConfig,
44
+ mergeCredentials,
44
45
  } from "./account-store.js";
45
46
  import { isHostedOAuthConfigured } from "./providers/google-antigravity/oauth.js";
46
47
  import type { RequestBody } from "./proxy.js";
@@ -799,7 +800,16 @@ export class AccountRotator {
799
800
  : modelKey.startsWith(`${OPENCODE_ZEN_PROVIDER_ID}:`)
800
801
  ? account.quota.find((candidate) => candidate.providerId === OPENCODE_ZEN_PROVIDER_ID)
801
802
  : undefined);
802
- return q ? q.percentRemaining : -1;
803
+ if (!q) return -1;
804
+ // Ollama: the session pool is gated by the weekly pool. If the weekly
805
+ // quota is fully exhausted (0%), the account cannot accept any requests
806
+ // regardless of how much session quota remains. Treat it as 0 so the
807
+ // account is skipped at all call sites that check `quota === 0`.
808
+ if (modelKey === "session") {
809
+ const weekly = account.quota.find((w) => w.modelKey === "weekly");
810
+ if (weekly && weekly.percentRemaining === 0) return 0;
811
+ }
812
+ return q.percentRemaining;
803
813
  }
804
814
 
805
815
  // Get timer type for a specific model on an account
@@ -3157,13 +3167,17 @@ export class AccountRotator {
3157
3167
  const previous = new Map(
3158
3168
  this.accounts.map((account) => [account.config.email, account]),
3159
3169
  );
3160
- this.config = normalized;
3161
- this.accounts = normalized.accounts.map((config) => {
3170
+ const mergedAccounts = normalized.accounts.map((config) => {
3162
3171
  const existing = previous.get(config.email);
3163
3172
  if (existing) {
3173
+ const mergedConfig = {
3174
+ ...existing.config,
3175
+ ...config,
3176
+ credentials: mergeCredentials(existing.config.credentials, config.credentials),
3177
+ };
3164
3178
  return {
3165
3179
  ...existing,
3166
- config: { ...existing.config, ...config },
3180
+ config: mergedConfig,
3167
3181
  };
3168
3182
  }
3169
3183
  return {
@@ -3199,6 +3213,8 @@ export class AccountRotator {
3199
3213
  },
3200
3214
  };
3201
3215
  });
3216
+ this.config = { ...normalized, accounts: mergedAccounts.map((account) => account.config) };
3217
+ this.accounts = mergedAccounts;
3202
3218
  await saveAccountsConfig(this.config);
3203
3219
  await this.saveState();
3204
3220
  this.refreshHealthScores();
@@ -3260,6 +3276,7 @@ export class AccountRotator {
3260
3276
  existing.config = {
3261
3277
  ...existing.config,
3262
3278
  ...accountConfig,
3279
+ credentials: mergeCredentials(existing.config.credentials, accountConfig.credentials),
3263
3280
  tier: accountConfig.tier || existing.config.tier || "unknown",
3264
3281
  };
3265
3282
  existing.disabled = false;
@@ -118,8 +118,11 @@ export class PostgresSettingsRepository implements ISettingsRepository {
118
118
  this.cache.set(row.key, row.value);
119
119
  }
120
120
 
121
- // Migrate from disk for any keys not already in DB
121
+ // Migrate non-account settings from disk for any keys not already in DB.
122
+ // accounts.json is deliberately excluded: when PostgreSQL is configured,
123
+ // it must be the sole source of account credentials.
122
124
  for (const [key, spec] of Object.entries(DISK_FILES)) {
125
+ if (key === "accounts_json") continue;
123
126
  if (this.cache.has(key)) continue;
124
127
  try {
125
128
  const path = join(getConfigDir(), spec.filename);
@@ -166,21 +169,21 @@ export class PostgresSettingsRepository implements ISettingsRepository {
166
169
  async set(key: string, value: string): Promise<void> {
167
170
  this.cache.set(key, value);
168
171
  if (this.pool) {
169
- // Non-blocking background save
170
- this.pool
171
- .query(
172
+ try {
173
+ // Account changes must be durable before the API reports success.
174
+ // A background-only write could be lost when the service restarts.
175
+ await this.pool.query(
172
176
  `INSERT INTO rotator_settings (key, value, updated_at)
173
- VALUES ($1, $2, CURRENT_TIMESTAMP)
174
- ON CONFLICT (key) DO UPDATE
175
- SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP`,
177
+ VALUES ($1, $2, CURRENT_TIMESTAMP)
178
+ ON CONFLICT (key) DO UPDATE
179
+ SET value = EXCLUDED.value, updated_at = CURRENT_TIMESTAMP`,
176
180
  [key, value],
177
- )
178
- .catch((err) => {
179
- console.error(
180
- `Failed to save ${key} to database in background: ${err}`,
181
- );
182
- this.enqueueRetry(key, value);
183
- });
181
+ );
182
+ } catch (err) {
183
+ console.error(`Failed to save ${key} to database: ${err}`);
184
+ this.enqueueRetry(key, value);
185
+ throw err;
186
+ }
184
187
  }
185
188
  }
186
189
 
@@ -371,6 +371,11 @@ const MODEL_PRICING = {
371
371
  "hy3-free": { inputPer1M: 0.25, outputPer1M: 1.00 },
372
372
  "ling-3.0-tiny-free": { inputPer1M: 0.05, outputPer1M: 0.20 },
373
373
  "laguna-s-2.1-free": { inputPer1M: 0.20, outputPer1M: 0.80 },
374
+
375
+ // OpenAI Codex models — mirrors MODEL_PRICING in src/types.ts
376
+ "gpt-5.6-sol": { inputPer1M: 5.00, outputPer1M: 30.00 },
377
+ "gpt-5.6-terra": { inputPer1M: 2.00, outputPer1M: 12.00 },
378
+ "gpt-5.6-luna": { inputPer1M: 0.20, outputPer1M: 1.20 },
374
379
  };
375
380
 
376
381
  function getModelPricing(model) {