import { env } from "cloudflare:workers"; import { decryptSecret, encryptSecret } from "../crypto"; import { all, first, run } from "../db"; import { badRequest } from "../errors"; import { numberVar } from "../limits"; import { DEFAULT_THRESHOLDS } from "./decide"; import type { Thresholds } from "./decide"; import type { TokenUsage } from "./plan"; export type RepoMergeFixSettings = { queueEnabled: boolean; allowPrivate: boolean; thresholds: Thresholds }; type SettingsRow = { queue_enabled: number; allow_private: number; min_confidence: number; min_margin: number }; export async function loadRepoSettings(repoId: string): Promise { const row = await first("SELECT * FROM repo_mergefix_settings WHERE repo_id = ?", repoId); return { queueEnabled: row?.queue_enabled === 1, allowPrivate: row?.allow_private === 1, thresholds: row ? { confidence: row.min_confidence, margin: row.min_margin } : DEFAULT_THRESHOLDS, }; } export async function saveRepoSettings(repoId: string, settings: RepoMergeFixSettings): Promise { await run( `INSERT INTO repo_mergefix_settings (repo_id, queue_enabled, allow_private, min_confidence, min_margin, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (repo_id) DO UPDATE SET queue_enabled = excluded.queue_enabled, allow_private = excluded.allow_private, min_confidence = excluded.min_confidence, min_margin = excluded.min_margin, updated_at = excluded.updated_at`, repoId, settings.queueEnabled ? 1 : 0, settings.allowPrivate ? 1 : 0, settings.thresholds.confidence, settings.thresholds.margin, Date.now(), ); } export type ByokKey = { provider: string; model: string; apiKey: string }; type KeyRow = { provider: string; model: string; key_ciphertext: string; key_iv: string; updated_at: number }; function secretsKey(): string { if (!env.SECRETS_KEY) throw badRequest("SECRETS_KEY is not configured on this instance"); return env.SECRETS_KEY; } export async function loadAccountKey(accountId: string): Promise { const row = await first("SELECT * FROM account_ai_keys WHERE account_id = ?", accountId); if (!row) return null; return { provider: row.provider, model: row.model, apiKey: await decryptSecret(secretsKey(), row.key_ciphertext, row.key_iv), }; } export async function accountKeySummary(accountId: string) { const row = await first( "SELECT provider, model, updated_at FROM account_ai_keys WHERE account_id = ?", accountId, ); return row ? { provider: row.provider, model: row.model, updatedAt: row.updated_at } : null; } export async function saveAccountKey(accountId: string, key: ByokKey, actorId: string): Promise { const sealed = await encryptSecret(secretsKey(), key.apiKey); await run( `INSERT INTO account_ai_keys (account_id, provider, model, key_ciphertext, key_iv, updated_by, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (account_id) DO UPDATE SET provider = excluded.provider, model = excluded.model, key_ciphertext = excluded.key_ciphertext, key_iv = excluded.key_iv, updated_by = excluded.updated_by, updated_at = excluded.updated_at`, accountId, key.provider, key.model, sealed.ciphertext, sealed.iv, actorId, Date.now(), ); } export async function deleteAccountKey(accountId: string): Promise { await run("DELETE FROM account_ai_keys WHERE account_id = ?", accountId); } export function usageMonth(now = Date.now()): string { return new Date(now).toISOString().slice(0, 7); } export type UsageRow = { calls: number; input_tokens: number; output_tokens: number; byok_calls: number }; export function monthlyCaps() { return { calls: numberVar(env.MERGEFIX_CALLS_PER_MONTH, 500), tokens: numberVar(env.MERGEFIX_TOKENS_PER_MONTH, 2_000_000), }; } export async function loadUsage(accountId: string, month = usageMonth()): Promise { const row = await first( "SELECT calls, input_tokens, output_tokens, byok_calls FROM ai_usage WHERE account_id = ? AND month = ?", accountId, month, ); return row ?? { calls: 0, input_tokens: 0, output_tokens: 0, byok_calls: 0 }; } export class UsageCapError extends Error {} async function ensureUsageRow(accountId: string, month: string): Promise { await run("INSERT OR IGNORE INTO ai_usage (account_id, month) VALUES (?, ?)", accountId, month); } /** Read-only pre-check used before starting a run; per-call enforcement happens in `reserveCall`. */ export async function assertWithinCaps(accountId: string): Promise { const usage = await loadUsage(accountId); const caps = monthlyCaps(); if (usage.calls - usage.byok_calls >= caps.calls) throw new UsageCapError("Monthly AI call limit reached"); if (usage.input_tokens + usage.output_tokens >= caps.tokens) throw new UsageCapError("Monthly AI token limit reached"); } /** * Atomically counts a call before it is made, so concurrent runs cannot overshoot the caps and calls that * time out or fail still count. Bring-your-own-key calls are recorded but never capped. */ export async function reserveCall(accountId: string, byok: boolean): Promise { const month = usageMonth(); await ensureUsageRow(accountId, month); if (byok) { await run( "UPDATE ai_usage SET calls = calls + 1, byok_calls = byok_calls + 1 WHERE account_id = ? AND month = ?", accountId, month, ); return; } const caps = monthlyCaps(); const result = await run( `UPDATE ai_usage SET calls = calls + 1 WHERE account_id = ? AND month = ? AND calls - byok_calls < ? AND input_tokens + output_tokens < ?`, accountId, month, caps.calls, caps.tokens, ); if ((result.meta.changes ?? 0) === 0) throw new UsageCapError("Monthly AI usage limit reached"); } /** Adds the tokens of an instance-paid call that `reserveCall` already counted. */ export async function recordTokens(accountId: string, usage: TokenUsage): Promise { const month = usageMonth(); await ensureUsageRow(accountId, month); await run( "UPDATE ai_usage SET input_tokens = input_tokens + ?, output_tokens = output_tokens + ? WHERE account_id = ? AND month = ?", Math.max(0, Math.round(usage.inputTokens)), Math.max(0, Math.round(usage.outputTokens)), accountId, month, ); } export type RunRow = { id: string; pull_issue_id: string; repo_id: string; account_id: string; actor_id: string; trigger: "button" | "queue"; status: "queued" | "running" | "applying" | "applied" | "suggested" | "failed"; head_sha: string; base_sha: string | null; commit_sha: string | null; calls: number; result_json: string | null; error: string | null; created_at: number; updated_at: number; }; export async function loadRun(id: string): Promise { return first("SELECT * FROM mergefix_runs WHERE id = ?", id); } export async function latestRuns(pullIssueId: string, limit = 5): Promise { return all( "SELECT * FROM mergefix_runs WHERE pull_issue_id = ? ORDER BY created_at DESC LIMIT ?", pullIssueId, limit, ); } export const ACTIVE_STATUSES: RunRow["status"][] = ["queued", "running", "applying"]; /** Status transitions are compare-and-set on `from`, so a late writer can never resurrect a settled run. */ export async function updateRun( id: string, from: RunRow["status"][], fields: Partial>, ): Promise { const entries = Object.entries({ ...fields, updated_at: Date.now() }); const result = await run( `UPDATE mergefix_runs SET ${entries.map(([key]) => `${key} = ?`).join(", ")} WHERE id = ? AND status IN (${from.map(() => "?").join(", ")})`, ...entries.map(([, value]) => value ?? null), id, ...from, ); return (result.meta.changes ?? 0) > 0; }