|
| 1 | +// CHANGE: add API-level account pool service with persistence and rate-limit monitoring |
| 2 | +// WHY: enable automatic switching between registered accounts when one hits API rate limits |
| 3 | +// QUOTE(ТЗ): "Сделать возможность регистрировать много аккаунтов codex, claude code и когда на одном лимиты закаончиваются он переходит на другой аккаунт" |
| 4 | +// REF: issue-213 |
| 5 | +// SOURCE: n/a |
| 6 | +// FORMAT THEOREM: ∀op ∈ PoolOperation: op(state) → persist(nextState) ∧ consistent(nextState) |
| 7 | +// PURITY: SHELL |
| 8 | +// EFFECT: Effect<Result, ApiError> |
| 9 | +// INVARIANT: pool state is persisted to disk after every mutation; in-memory state is source of truth |
| 10 | +// COMPLEXITY: O(n) per operation where n = total accounts |
| 11 | + |
| 12 | +import { defaultProjectsRoot } from "@effect-template/lib/usecases/path-helpers" |
| 13 | +import type { |
| 14 | + AccountPoolProvider, |
| 15 | + AccountPoolState, |
| 16 | + AccountEntry, |
| 17 | + RateLimitEvent |
| 18 | +} from "@effect-template/lib/core/account-pool-domain" |
| 19 | +import { |
| 20 | + addAccount, |
| 21 | + removeAccount, |
| 22 | + markRateLimited, |
| 23 | + clearCooldown, |
| 24 | + selectNextAvailable, |
| 25 | + advanceActiveIndex, |
| 26 | + listAccounts, |
| 27 | + listAllAccounts, |
| 28 | + poolSummary, |
| 29 | + emptyPoolState |
| 30 | +} from "@effect-template/lib/usecases/account-pool" |
| 31 | +import { detectRateLimit } from "@effect-template/lib/usecases/rate-limit-detector" |
| 32 | +import { promises as fs } from "node:fs" |
| 33 | +import { join } from "node:path" |
| 34 | + |
| 35 | +let poolState: AccountPoolState = emptyPoolState(new Date().toISOString()) |
| 36 | +let initialized = false |
| 37 | + |
| 38 | +const nowIso = (): string => new Date().toISOString() |
| 39 | + |
| 40 | +const stateFilePath = (): string => |
| 41 | + join(defaultProjectsRoot(process.cwd()), ".orch", "state", "account-pool.json") |
| 42 | + |
| 43 | +const persistState = async (): Promise<void> => { |
| 44 | + const filePath = stateFilePath() |
| 45 | + await fs.mkdir(join(filePath, ".."), { recursive: true }) |
| 46 | + await fs.writeFile(filePath, JSON.stringify(poolState, null, 2), "utf8") |
| 47 | +} |
| 48 | + |
| 49 | +const persistBestEffort = (): void => { |
| 50 | + void persistState().catch(() => { |
| 51 | + // best effort |
| 52 | + }) |
| 53 | +} |
| 54 | + |
| 55 | +export const initializeAccountPool = async (): Promise<void> => { |
| 56 | + if (initialized) { |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + const filePath = stateFilePath() |
| 61 | + const exists = await fs.stat(filePath).then(() => true).catch(() => false) |
| 62 | + if (exists) { |
| 63 | + const raw = await fs.readFile(filePath, "utf8") |
| 64 | + const parsed = JSON.parse(raw) as AccountPoolState |
| 65 | + poolState = { |
| 66 | + pools: parsed.pools ?? [], |
| 67 | + updatedAt: parsed.updatedAt ?? nowIso() |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + initialized = true |
| 72 | +} |
| 73 | + |
| 74 | +export const addPoolAccount = ( |
| 75 | + provider: AccountPoolProvider, |
| 76 | + label: string |
| 77 | +): AccountPoolState => { |
| 78 | + const now = nowIso() |
| 79 | + poolState = addAccount(poolState, provider, label, now) |
| 80 | + persistBestEffort() |
| 81 | + return poolState |
| 82 | +} |
| 83 | + |
| 84 | +export const removePoolAccount = ( |
| 85 | + provider: AccountPoolProvider, |
| 86 | + label: string |
| 87 | +): AccountPoolState => { |
| 88 | + const now = nowIso() |
| 89 | + poolState = removeAccount(poolState, provider, label, now) |
| 90 | + persistBestEffort() |
| 91 | + return poolState |
| 92 | +} |
| 93 | + |
| 94 | +export const markAccountRateLimited = ( |
| 95 | + event: RateLimitEvent |
| 96 | +): AccountPoolState => { |
| 97 | + const now = nowIso() |
| 98 | + poolState = markRateLimited(poolState, event, now) |
| 99 | + persistBestEffort() |
| 100 | + return poolState |
| 101 | +} |
| 102 | + |
| 103 | +export const clearAccountCooldown = ( |
| 104 | + provider: AccountPoolProvider, |
| 105 | + label: string |
| 106 | +): AccountPoolState => { |
| 107 | + const now = nowIso() |
| 108 | + poolState = clearCooldown(poolState, provider, label, now) |
| 109 | + persistBestEffort() |
| 110 | + return poolState |
| 111 | +} |
| 112 | + |
| 113 | +export const selectNextPoolAccount = ( |
| 114 | + provider: AccountPoolProvider |
| 115 | +): AccountEntry | undefined => { |
| 116 | + const now = nowIso() |
| 117 | + const account = selectNextAvailable(poolState, provider, now) |
| 118 | + if (account !== undefined) { |
| 119 | + poolState = advanceActiveIndex(poolState, provider, now) |
| 120 | + persistBestEffort() |
| 121 | + } |
| 122 | + return account |
| 123 | +} |
| 124 | + |
| 125 | +export const listPoolAccounts = ( |
| 126 | + provider: AccountPoolProvider |
| 127 | +): ReadonlyArray<AccountEntry> => |
| 128 | + listAccounts(poolState, provider) |
| 129 | + |
| 130 | +export const listAllPoolAccounts = (): ReadonlyArray<AccountEntry> => |
| 131 | + listAllAccounts(poolState) |
| 132 | + |
| 133 | +export const getPoolSummary = ( |
| 134 | + provider: AccountPoolProvider |
| 135 | +): { |
| 136 | + readonly total: number |
| 137 | + readonly available: number |
| 138 | + readonly coolingDown: number |
| 139 | + readonly activeLabel: string | undefined |
| 140 | +} => poolSummary(poolState, provider, nowIso()) |
| 141 | + |
| 142 | +export const getPoolState = (): AccountPoolState => poolState |
| 143 | + |
| 144 | +/** |
| 145 | + * Check an agent output line for rate-limit signals. |
| 146 | + * If a rate-limit is detected, marks the account as rate-limited |
| 147 | + * and returns the event for the caller to act upon. |
| 148 | + * |
| 149 | + * @effect mutates poolState on detection |
| 150 | + */ |
| 151 | +export const checkLineForRateLimit = ( |
| 152 | + provider: AccountPoolProvider, |
| 153 | + label: string, |
| 154 | + line: string |
| 155 | +): RateLimitEvent | undefined => { |
| 156 | + const now = nowIso() |
| 157 | + const event = detectRateLimit(provider, label, line, now) |
| 158 | + if (event !== undefined) { |
| 159 | + markAccountRateLimited(event) |
| 160 | + } |
| 161 | + return event |
| 162 | +} |
0 commit comments