Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/api/src/api/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,32 @@ export type FederationInboxResult =
readonly subscription: FollowSubscription
}

// CHANGE: add account pool API types for multi-account management
// WHY: expose account pool CRUD and status via the API
// QUOTE(ТЗ): "Сделать возможность регистрировать много аккаунтов"
// REF: issue-213
// PURITY: CORE
// COMPLEXITY: O(1)
export type AccountPoolProvider = "claude" | "codex" | "gemini"

export type AddAccountRequest = {
readonly provider: AccountPoolProvider
readonly label: string
}

export type RemoveAccountRequest = {
readonly provider: AccountPoolProvider
readonly label: string
}

export type AccountPoolSummary = {
readonly provider: AccountPoolProvider
readonly total: number
readonly available: number
readonly coolingDown: number
readonly activeLabel: string | undefined
}

export type ApiEventType =
| "snapshot"
| "project.created"
Expand Down
20 changes: 20 additions & 0 deletions packages/api/src/api/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,26 @@ export const CreateAgentRequestSchema = Schema.Struct({
label: OptionalString
})

// CHANGE: add account pool request schemas
// WHY: validate API requests for multi-account pool management
// REF: issue-213
// PURITY: CORE
// COMPLEXITY: O(1)
export const AccountPoolProviderSchema = Schema.Literal("claude", "codex", "gemini")

export const AddAccountRequestSchema = Schema.Struct({
provider: AccountPoolProviderSchema,
label: Schema.String
})

export const RemoveAccountRequestSchema = Schema.Struct({
provider: AccountPoolProviderSchema,
label: Schema.String
})

export type AddAccountRequestInput = Schema.Schema.Type<typeof AddAccountRequestSchema>
export type RemoveAccountRequestInput = Schema.Schema.Type<typeof RemoveAccountRequestSchema>

export const CreateFollowRequestSchema = Schema.Struct({
actor: OptionalString,
object: Schema.String,
Expand Down
69 changes: 68 additions & 1 deletion packages/api/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { renderError, type AppError } from "@effect-template/lib/usecases/errors

import { ApiAuthRequiredError, ApiBadRequestError, ApiConflictError, ApiInternalError, ApiNotFoundError, describeUnknown } from "./api/errors.js"
import {
AddAccountRequestSchema,
ApplyAllRequestSchema,
CodexAuthImportRequestSchema,
CodexAuthLoginRequestSchema,
Expand All @@ -21,6 +22,7 @@ import {
CreateProjectRequestSchema,
GithubAuthLoginRequestSchema,
GithubAuthLogoutRequestSchema,
RemoveAccountRequestSchema,
StateCommitRequestSchema,
StateInitRequestSchema,
StateSyncRequestSchema,
Expand All @@ -36,6 +38,15 @@ import {
readGithubAuthStatus
} from "./services/auth.js"
import { streamCodexAuthLogin } from "./services/auth-codex-login-stream.js"
import {
addPoolAccount,
clearAccountCooldown,
getPoolSummary,
listAllPoolAccounts,
listPoolAccounts,
removePoolAccount,
selectNextPoolAccount
} from "./services/account-pool.js"
import { getAgent, getAgentAttachInfo, listAgents, readAgentLogs, startAgent, stopAgent } from "./services/agents.js"
import { latestProjectCursor, listProjectEventsSince } from "./services/events.js"
import {
Expand Down Expand Up @@ -415,7 +426,63 @@ export const makeRouter = () => {
)
)

const withState = base.pipe(
const withAccountPool = base.pipe(
HttpRouter.get(
"/account-pool",
Effect.sync(() => ({ accounts: listAllPoolAccounts() })).pipe(
Effect.flatMap((payload) => jsonResponse(payload, 200)),
Effect.catchAll(errorResponse)
)
),
HttpRouter.get(
"/account-pool/:provider",
HttpRouter.schemaParams(Schema.Struct({ provider: Schema.Literal("claude", "codex", "gemini") })).pipe(
Effect.flatMap(({ provider }) =>
jsonResponse({
accounts: listPoolAccounts(provider),
summary: getPoolSummary(provider)
}, 200)
),
Effect.catchAll(errorResponse)
)
),
HttpRouter.post(
"/account-pool/add",
Effect.gen(function*(_) {
const request = yield* _(HttpServerRequest.schemaBodyJson(AddAccountRequestSchema))
const state = addPoolAccount(request.provider, request.label)
return yield* _(jsonResponse({ ok: true, state }, 201))
}).pipe(Effect.catchAll(errorResponse))
),
HttpRouter.post(
"/account-pool/remove",
Effect.gen(function*(_) {
const request = yield* _(HttpServerRequest.schemaBodyJson(RemoveAccountRequestSchema))
const state = removePoolAccount(request.provider, request.label)
return yield* _(jsonResponse({ ok: true, state }, 200))
}).pipe(Effect.catchAll(errorResponse))
),
HttpRouter.post(
"/account-pool/next",
Effect.gen(function*(_) {
const request = yield* _(HttpServerRequest.schemaBodyJson(
Schema.Struct({ provider: Schema.Literal("claude", "codex", "gemini") })
))
const account = selectNextPoolAccount(request.provider)
return yield* _(jsonResponse({ account: account ?? null }, 200))
}).pipe(Effect.catchAll(errorResponse))
),
HttpRouter.post(
"/account-pool/clear-cooldown",
Effect.gen(function*(_) {
const request = yield* _(HttpServerRequest.schemaBodyJson(RemoveAccountRequestSchema))
const state = clearAccountCooldown(request.provider, request.label)
return yield* _(jsonResponse({ ok: true, state }, 200))
}).pipe(Effect.catchAll(errorResponse))
)
)

const withState = withAccountPool.pipe(
HttpRouter.get(
"/state/path",
readStatePathOutput().pipe(
Expand Down
6 changes: 6 additions & 0 deletions packages/api/src/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Console, Effect, Layer, Option } from "effect"
import { createServer } from "node:http"

import { makeRouter } from "./http.js"
import { initializeAccountPool } from "./services/account-pool.js"
import { initializeAgentState } from "./services/agents.js"
import { startOutboxPolling } from "./services/federation.js"

Expand Down Expand Up @@ -49,6 +50,11 @@ export const program = (() => {
return Effect.scoped(
Console.log(`docker-git api boot port=${port}`).pipe(
Effect.zipRight(initializeAgentState()),
Effect.zipRight(
Effect.tryPromise({ try: () => initializeAccountPool(), catch: () => new Error("account pool init failed") }).pipe(
Effect.catchAll(() => Effect.void)
)
),
Effect.zipRight(
Console.log(`docker-git outbox polling interval=${pollingInterval}ms`)
),
Expand Down
162 changes: 162 additions & 0 deletions packages/api/src/services/account-pool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
// CHANGE: add API-level account pool service with persistence and rate-limit monitoring
// WHY: enable automatic switching between registered accounts when one hits API rate limits
// QUOTE(ТЗ): "Сделать возможность регистрировать много аккаунтов codex, claude code и когда на одном лимиты закаончиваются он переходит на другой аккаунт"
// REF: issue-213
// SOURCE: n/a
// FORMAT THEOREM: ∀op ∈ PoolOperation: op(state) → persist(nextState) ∧ consistent(nextState)
// PURITY: SHELL
// EFFECT: Effect<Result, ApiError>
// INVARIANT: pool state is persisted to disk after every mutation; in-memory state is source of truth
// COMPLEXITY: O(n) per operation where n = total accounts

import { defaultProjectsRoot } from "@effect-template/lib/usecases/path-helpers"
import type {
AccountPoolProvider,
AccountPoolState,
AccountEntry,
RateLimitEvent
} from "@effect-template/lib/core/account-pool-domain"
import {
addAccount,
removeAccount,
markRateLimited,
clearCooldown,
selectNextAvailable,
advanceActiveIndex,
listAccounts,
listAllAccounts,
poolSummary,
emptyPoolState
} from "@effect-template/lib/usecases/account-pool"
import { detectRateLimit } from "@effect-template/lib/usecases/rate-limit-detector"
import { promises as fs } from "node:fs"
import { join } from "node:path"

let poolState: AccountPoolState = emptyPoolState(new Date().toISOString())
let initialized = false

const nowIso = (): string => new Date().toISOString()

const stateFilePath = (): string =>
join(defaultProjectsRoot(process.cwd()), ".orch", "state", "account-pool.json")

const persistState = async (): Promise<void> => {
const filePath = stateFilePath()
await fs.mkdir(join(filePath, ".."), { recursive: true })
await fs.writeFile(filePath, JSON.stringify(poolState, null, 2), "utf8")
}

const persistBestEffort = (): void => {
void persistState().catch(() => {
// best effort
})
}

export const initializeAccountPool = async (): Promise<void> => {
if (initialized) {
return
}

const filePath = stateFilePath()
const exists = await fs.stat(filePath).then(() => true).catch(() => false)
if (exists) {
const raw = await fs.readFile(filePath, "utf8")
const parsed = JSON.parse(raw) as AccountPoolState
poolState = {
pools: parsed.pools ?? [],
updatedAt: parsed.updatedAt ?? nowIso()
}
}

initialized = true
}

export const addPoolAccount = (
provider: AccountPoolProvider,
label: string
): AccountPoolState => {
const now = nowIso()
poolState = addAccount(poolState, provider, label, now)
persistBestEffort()
return poolState
}

export const removePoolAccount = (
provider: AccountPoolProvider,
label: string
): AccountPoolState => {
const now = nowIso()
poolState = removeAccount(poolState, provider, label, now)
persistBestEffort()
return poolState
}

export const markAccountRateLimited = (
event: RateLimitEvent
): AccountPoolState => {
const now = nowIso()
poolState = markRateLimited(poolState, event, now)
persistBestEffort()
return poolState
}

export const clearAccountCooldown = (
provider: AccountPoolProvider,
label: string
): AccountPoolState => {
const now = nowIso()
poolState = clearCooldown(poolState, provider, label, now)
persistBestEffort()
return poolState
}

export const selectNextPoolAccount = (
provider: AccountPoolProvider
): AccountEntry | undefined => {
const now = nowIso()
const account = selectNextAvailable(poolState, provider, now)
if (account !== undefined) {
poolState = advanceActiveIndex(poolState, provider, now)
persistBestEffort()
}
return account
}

export const listPoolAccounts = (
provider: AccountPoolProvider
): ReadonlyArray<AccountEntry> =>
listAccounts(poolState, provider)

export const listAllPoolAccounts = (): ReadonlyArray<AccountEntry> =>
listAllAccounts(poolState)

export const getPoolSummary = (
provider: AccountPoolProvider
): {
readonly total: number
readonly available: number
readonly coolingDown: number
readonly activeLabel: string | undefined
} => poolSummary(poolState, provider, nowIso())

export const getPoolState = (): AccountPoolState => poolState

/**
* Check an agent output line for rate-limit signals.
* If a rate-limit is detected, marks the account as rate-limited
* and returns the event for the caller to act upon.
*
* @effect mutates poolState on detection
*/
export const checkLineForRateLimit = (
provider: AccountPoolProvider,
label: string,
line: string
): RateLimitEvent | undefined => {
const now = nowIso()
const event = detectRateLimit(provider, label, line, now)
if (event !== undefined) {
markAccountRateLimited(event)
}
return event
}
Loading