mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-06 23:32:12 +03:00
* perf: startup parallelization, stream TextEncoder lift, auth middleware bottlenecks
Startup (~100-300ms faster cold start):
- Parallelize 4 early imports via Promise.all() in registerNodejs()
- Parallelize 10 independent background services via Promise.allSettled()
- Each service has independent try/catch — no failure domino effect
Streaming pipeline (8 fewer TextEncoder GC allocations per SSE event):
- Lift new TextEncoder() from per-chunk inside buildClaudeStreamingResponse
to function scope alongside existing decoder singleton
Auth middleware bottlenecks (from PerfBottleneckAnalysis):
- Backoff decay loop: replace updateProviderConnection (full CRUD:
SELECT+encrypt+cache-invalidate+backup) with resetConnectionBackoff
(targeted UPDATE of backoff/error columns only)
- Dual .filter() for quota: replace two passes calling
isQuotaExhaustedForRequest per connection with a single for loop
partitioning into withQuota/exhaustedQuota
- Debug-log filter recomputation: capture connectionFilterStatus Map
during the filter pass; debug loop reads 6 string comparisons instead
of 6 function calls per connection
Supporting:
- Add resetConnectionBackoff to src/lib/db/providers.ts (patterned after
clearConnectionErrorIfUnchanged, no CAS check)
- Re-export resetConnectionBackoff from src/lib/localDb.ts
- Update integration-wiring.test.ts regex for parallelized dynamic import
* perf: P2C quota cache, lazy provider init, structuredClone elimination, getSettings→getCachedSettings
- **auth.ts: P2C quota re-evaluation cache** — quotaResults Map threaded
through selectPoolSubset → compareP2CConnections → getP2CConnectionScore.
Populated during filter + partition passes, eliminating redundant
evaluateQuotaLimitPolicy / isQuotaExhaustedForRequest calls when the
P2C comparator re-evaluates previously-scored connections.
- **constants.ts: lazy PROVIDERS via Proxy** — replaces eager
generateLegacyProviders() + loadProviderCredentials() at module load
with Proxy delegating to deferred init on first property access.
- **providerModels.ts: lazy PROVIDER_MODELS + PROVIDER_ID_TO_ALIAS** —
same Proxy pattern for both exports; generateModels()/generateAliasMap()
deferred until first read.
- **stream.ts: structuredClone → minimal object spread** — replaces
O(n) deep clone of SSE response chunks with targeted reconstruction
of only mutated fields (usage, delta.content, finish_reason).
- **progressTracker.ts: TextDecoder lift** — module-level decoder
instead of per-chunk new TextDecoder().
- **Route files: getSettings() → getCachedSettings()** — 13 API route
files converted from uncached per-request DB reads to TTL-cached
wrapper (5s default), eliminating redundant queries on every request.
- **settings.ts: re-export getCachedSettings** from readCache for
non-localDb consumers.
- **Remove settingsCache.ts** — dead file, no imports reference it.
TS compile: 0 errors. Auth tests: 225/225 pass. Services: 269/269 pass.
* perf: Phase 1 tangible wins — egressCache eviction, mmap_size PRAGMA, composite indexes, proxyFallback lazy import
- egressCache: lazy TTL eviction on getCachedEgressIp access (bounds memory
leak to distinct proxy URLs, typically <100)
- mmap_size: apply stored PRAGMA from key_value table (256MiB default) after
applyStoredDatabaseOptimizationSettings — setting was stored but never applied
- schemaColumns: add idx_uh_provider_model_timestamp (covers getModelLatencyStats)
and idx_pc_provider_auth_type (covers 6+ provider_connections queries)
- proxyFallback: convert static import to dynamic import() inside error handler
(defers 210ms module load from startup to first proxy-retry scenario)
* perf: add dedup expression index, unref() sweep timers
- Add COALESCE expression index idx_uh_dedup on usage_history
matching the exact dedup query pattern. Eliminates FULL TABLE
SCAN on every saveRequestUsage insert.
- Add composite idx_uh_provider_model_timestamp on usage_history.
- Add composite idx_pc_provider_auth_type on provider_connections.
- Add .unref() to setInterval in batchProcessor.ts (polling loop).
- Add .unref() to setInterval in runtimeHeartbeat.ts (heartbeat).
* perf: bump SQLite cache_size default from 16MB to 64MB
New installs now start with 64MB page cache (was 16MB). Existing
users' stored settings are unchanged. Reduces disk reads for the
typical ~250MB database by keeping ~25% of pages in memory.
Also resolved pre-existing merge conflict in webhooks.ts.
* docs: add Redis production config guide and proxy port clash investigation report
- docs/redis-production-config.md: comprehensive Redis tuning guide
covering client options, server config, Docker settings, scaling,
and monitoring for all three Redis workloads (rate limiting,
auth cache, quota store)
- docs/proxy-port-clash-report.md: investigation confirming proxy
subsystem has no port binding issues; real EADDRINUSE history
traced to process supervisor crash-loop restart race (#4425) and
live-dashboard port clash (#6324), both already fixed
* fix: address PR #7893 review — add Proxy traps, extract migrations to reduce providers.ts size
- Add set trap to PROVIDER_ID_TO_ALIAS Proxy (providerModels.ts)
- Add deleteProperty traps to all three lazy Proxies (PROVIDERS,
PROVIDER_MODELS, PROVIDER_ID_TO_ALIAS)
- Extract autoMigrateLegacyEncryptedConnections and getGheCopilotHosts
from providers.ts (1129→1036 lines, -93) into providers/migrations.ts
- Both functions re-exported via providers.ts for backward compat
File-size ratchet resolved: src/lib/db/providers.ts now 1036 lines.
* fix: resolve merge conflict markers in 3 route/test files
- model-combo-mappings/route.ts: kept upstream version (Zod pagination
via validateBody + isValidationFailure), restored missing return
statement for GET handler
- playground/presets/route.ts: kept stashed version details (satisfies
type-narrowing + inlined Response) — functionally identical
- error-sanitization.test.ts: matches upstream exactly (no diff)
Test verification: same 7 pre-existing failures confirmed on upstream
baseline (c1bdd91e7). Zero regressions from conflict resolution.
Closes remaining uncommitted work from PR #7046 rebase.
* test(db): add resetConnectionBackoff coverage + fix file-size ratchet regression
- Add tests/unit/reset-connection-backoff.test.ts: covers the new
resetConnectionBackoff lightweight-UPDATE helper (clears backoff/error
columns and re-activates a connection, unconditional-write behavior on
terminal statuses, no-op for empty/unknown ids). Zero prior coverage
per pre-merge review of PR #7893 (Hard Rule #8).
- open-sse/services/batchProcessor.ts: fold the new unref() call into the
existing setInterval(...).unref() chain instead of a separate statement,
keeping the file at the frozen 915-line ratchet (Timeout.unref() already
returns `this`, so no type cast is needed).
- src/lib/localDb.ts: drop one blank separator line so the new
resetConnectionBackoff re-export stays within the frozen 808-line ratchet.
Pre-merge fix for PR #7893 (perf/startup-stream-auth-optimizations) per
/green-prs plan-file _tasks/pipeline/prs/1-analyzed/7893-*.plan.md.
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouzapw@users.noreply.github.com>
---------
Co-authored-by: oyi77 <oyi77@users.noreply.github.com>
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouza.pw@gmail.com>
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouzapw@users.noreply.github.com>
808 lines
19 KiB
TypeScript
Executable File
808 lines
19 KiB
TypeScript
Executable File
/**
|
|
* localDb.js — Re-export layer for backward compatibility.
|
|
*
|
|
* All 27+ consumer files import from "@/lib/localDb".
|
|
* This thin layer re-exports everything from the domain-specific DB modules,
|
|
* so zero consumer changes are needed.
|
|
*/
|
|
|
|
export {
|
|
// Provider Connections
|
|
getProviderConnections,
|
|
getProviderConnectionsCount,
|
|
getProviderConnectionById,
|
|
createProviderConnection,
|
|
updateProviderConnection,
|
|
resetConnectionBackoff,
|
|
clearConnectionErrorIfUnchanged,
|
|
touchConnectionLastUsed,
|
|
deleteProviderConnection,
|
|
deleteProviderConnections,
|
|
deleteProviderConnectionsByProvider,
|
|
reorderProviderConnections,
|
|
cleanupProviderConnections,
|
|
getProviderNodes,
|
|
getProviderNodesCount,
|
|
getProviderNodeById,
|
|
resolveProviderNodeForConnection,
|
|
createProviderNode,
|
|
updateProviderNode,
|
|
deleteProviderNode,
|
|
// T05: Rate-limit DB persistence (survives token refresh)
|
|
setConnectionRateLimitUntil,
|
|
isConnectionRateLimited,
|
|
getRateLimitedConnections,
|
|
clearStaleCrashCooldowns,
|
|
// T13: Stale quota display fix (zero out usage after window resets)
|
|
getEffectiveQuotaUsage,
|
|
formatResetCountdown,
|
|
} from "./db/providers";
|
|
|
|
export {
|
|
// Model Aliases
|
|
getModelAliases,
|
|
setModelAlias,
|
|
deleteModelAlias,
|
|
deleteModelAliasesForProvider,
|
|
|
|
// MITM Alias
|
|
getMitmAlias,
|
|
setMitmAliasAll,
|
|
|
|
// Custom Models
|
|
getCustomModels,
|
|
getAllCustomModels,
|
|
addCustomModel,
|
|
replaceCustomModels,
|
|
removeCustomModel,
|
|
updateCustomModel,
|
|
getModelCompatOverrides,
|
|
mergeModelCompatOverride,
|
|
removeModelCompatOverride,
|
|
getModelNormalizeToolCallId,
|
|
getModelPreserveOpenAIDeveloperRole,
|
|
getModelUpstreamExtraHeaders,
|
|
getModelIsHidden,
|
|
setModelIsHidden,
|
|
getHiddenModelsByProvider,
|
|
// Synced Available Models
|
|
getSyncedAvailableModels,
|
|
getAllSyncedAvailableModels,
|
|
getActiveProvidersWithSyncedModel,
|
|
replaceSyncedAvailableModelsForConnection,
|
|
deleteSyncedAvailableModelsForConnection,
|
|
deleteSyncedAvailableModelsForProvider,
|
|
removeSyncedAvailableModel,
|
|
} from "./db/models";
|
|
|
|
export type { ModelCompatPerProtocol, ModelCompatPatch, SyncedAvailableModel } from "./db/models";
|
|
|
|
export {
|
|
// Combos
|
|
getCombos,
|
|
getCombosCount,
|
|
getComboById,
|
|
getComboByName,
|
|
getComboByNameInsensitive,
|
|
createCombo,
|
|
updateCombo,
|
|
reorderCombos,
|
|
deleteCombo,
|
|
} from "./db/combos";
|
|
export * from "./db/compressionCacheStats";
|
|
export * from "./db/compressionCombos";
|
|
export * from "./db/compressionContextBudget";
|
|
export * from "./db/compressionRunTelemetry";
|
|
export * from "./db/modelContextOverrides";
|
|
|
|
export {
|
|
getApiKeys,
|
|
getApiKeysCount,
|
|
getApiKeyById,
|
|
createApiKey,
|
|
deleteApiKey,
|
|
validateApiKey,
|
|
getApiKeyMetadata,
|
|
updateApiKeyPermissions,
|
|
regenerateApiKey,
|
|
isModelAllowedForKey,
|
|
pickApiKeyForInternalUse,
|
|
clearApiKeyCaches,
|
|
resetApiKeyState,
|
|
} from "./db/apiKeys";
|
|
|
|
export {
|
|
// Evals
|
|
saveEvalRun,
|
|
listEvalRuns,
|
|
getEvalScorecard,
|
|
listCustomEvalSuites,
|
|
getCustomEvalSuite,
|
|
saveCustomEvalSuite,
|
|
deleteCustomEvalSuite,
|
|
serializeEvalTargetKey,
|
|
} from "./db/evals";
|
|
|
|
export type {
|
|
EvalCaseRecord,
|
|
EvalSuiteRecord,
|
|
EvalTargetType,
|
|
EvalTargetDescriptor,
|
|
EvalRunSummary,
|
|
PersistedEvalRun,
|
|
} from "./db/evals";
|
|
|
|
export {
|
|
// Settings
|
|
getSettings,
|
|
updateSettings,
|
|
isCloudEnabled,
|
|
|
|
// LKGP (Last Known Good Provider) (#919)
|
|
getLKGP,
|
|
setLKGP,
|
|
|
|
// Pricing
|
|
getPricing,
|
|
getPricingWithSources,
|
|
getPricingForModel,
|
|
updatePricing,
|
|
resetPricing,
|
|
resetAllPricing,
|
|
|
|
// Proxy Config
|
|
getProxyConfig,
|
|
getProxyForLevel,
|
|
setProxyForLevel,
|
|
deleteProxyForLevel,
|
|
resolveProxyForConnection,
|
|
setProxyConfig,
|
|
} from "./db/settings";
|
|
|
|
export type { PricingSource, PricingSourceMap } from "./db/settings";
|
|
|
|
export {
|
|
getDatabaseSettings,
|
|
getUserDatabaseSettings,
|
|
updateDatabaseSettings,
|
|
} from "./db/databaseSettings";
|
|
|
|
export type { UserDatabaseSettings } from "./db/databaseSettings";
|
|
|
|
export {
|
|
// Proxy Registry
|
|
listProxies,
|
|
getProxyById,
|
|
createProxy,
|
|
createProxyAndAssign,
|
|
updateProxy,
|
|
updateProxyAndAssign,
|
|
upsertProxy,
|
|
deleteProxyById,
|
|
getProxyAssignments,
|
|
getProxyWhereUsed,
|
|
assignProxyToScope,
|
|
addProxyToScopePool,
|
|
removeProxyFromScopePool,
|
|
getScopeProxyPool,
|
|
setScopeRotationStrategy,
|
|
getScopeRotationStrategy,
|
|
resolveProxyForConnectionFromRegistry,
|
|
resolveProxyForProvider,
|
|
resolveProxyForScopeFromRegistry,
|
|
migrateLegacyProxyConfigToRegistry,
|
|
getProxyHealthStats,
|
|
bulkAssignProxyToScope,
|
|
} from "./db/proxies";
|
|
|
|
export {
|
|
// Pricing Sync
|
|
getSyncedPricing,
|
|
saveSyncedPricing,
|
|
clearSyncedPricing,
|
|
syncPricingFromSources,
|
|
getSyncStatus,
|
|
initPricingSync,
|
|
startPeriodicSync,
|
|
stopPeriodicSync,
|
|
} from "./pricingSync";
|
|
|
|
export {
|
|
// Backup Management
|
|
backupDbFile,
|
|
cleanupDbBackups,
|
|
getDbBackupMaxFiles,
|
|
setDbBackupMaxFiles,
|
|
getDbBackupRetentionDays,
|
|
setDbBackupRetentionDays,
|
|
listDbBackups,
|
|
restoreDbBackup,
|
|
// Export-All / Import helpers (#3500 slice 5)
|
|
exportAllSummaryRows,
|
|
getTableNamesFromAdapter,
|
|
countImportedRows,
|
|
} from "./db/backup";
|
|
|
|
export type { ExportAllRows } from "./db/backup";
|
|
|
|
export {
|
|
// Skills DB operations (#3500 slice 5)
|
|
updateSkill,
|
|
} from "./db/skills";
|
|
|
|
export type { SkillPatch } from "./db/skills";
|
|
|
|
export {
|
|
// Read Cache (cached wrappers for hot-read paths)
|
|
getCachedSettings,
|
|
getCachedPricing,
|
|
getCachedProviderConnections,
|
|
getCachedRawProviderConnections,
|
|
getCachedProviderConnectionById,
|
|
getCachedProviderNodes,
|
|
getCachedLKGP,
|
|
setCachedLKGP,
|
|
invalidateDbCache,
|
|
getCombosCacheVersion,
|
|
} from "./db/readCache";
|
|
|
|
export {
|
|
// Registered Keys Provisioning (#464)
|
|
issueRegisteredKey,
|
|
getRegisteredKey,
|
|
listRegisteredKeys,
|
|
revokeRegisteredKey,
|
|
validateRegisteredKey,
|
|
incrementRegisteredKeyUsage,
|
|
checkQuota,
|
|
setProviderKeyLimit,
|
|
setAccountKeyLimit,
|
|
getProviderKeyLimit,
|
|
getAccountKeyLimit,
|
|
} from "./db/registeredKeys";
|
|
|
|
export type {
|
|
RegisteredKey,
|
|
RegisteredKeyWithSecret,
|
|
ProviderKeyLimit,
|
|
AccountKeyLimit,
|
|
QuotaCheckResult,
|
|
IssueKeyParams,
|
|
} from "./db/registeredKeys";
|
|
|
|
export {
|
|
// Model-Combo Mappings (#563)
|
|
getModelComboMappings,
|
|
getModelComboMappingById,
|
|
createModelComboMapping,
|
|
updateModelComboMapping,
|
|
deleteModelComboMapping,
|
|
resolveComboForModel,
|
|
} from "./db/modelComboMappings";
|
|
|
|
export {
|
|
// Files
|
|
createFile,
|
|
getFile,
|
|
getFileContent,
|
|
listFiles,
|
|
countFiles,
|
|
formatFileResponse,
|
|
deleteFile,
|
|
} from "./db/files";
|
|
|
|
export {
|
|
// Batches
|
|
createBatch,
|
|
getBatch,
|
|
updateBatch,
|
|
listBatches,
|
|
countBatches,
|
|
getPendingBatches,
|
|
getTerminalBatches,
|
|
ensureBatchItemCheckpoints,
|
|
countBatchItemCheckpoints,
|
|
listBatchItemCheckpoints,
|
|
markBatchItemProcessing,
|
|
markBatchItemResult,
|
|
markBatchItemError,
|
|
deleteBatch,
|
|
deleteCompletedBatches,
|
|
} from "./db/batches";
|
|
|
|
export type { FileRecord } from "./db/files";
|
|
export type { BatchItemCheckpoint, BatchRecord } from "./db/batches";
|
|
|
|
export type { ModelComboMapping } from "./db/modelComboMappings";
|
|
export * from "./db/reasoningRoutingRules";
|
|
export * from "./db/autoCandidateOverrides";
|
|
export {
|
|
// Webhooks
|
|
getWebhooks,
|
|
getWebhook,
|
|
getEnabledWebhooks,
|
|
createWebhook,
|
|
updateWebhook as updateWebhookRecord,
|
|
deleteWebhook,
|
|
recordWebhookDelivery,
|
|
disableWebhooksWithHighFailures,
|
|
} from "./db/webhooks";
|
|
|
|
export type { Webhook, WebhookKind } from "./db/webhooks";
|
|
|
|
export { insertDelivery, getDeliveries } from "./db/webhookDeliveries";
|
|
|
|
export {
|
|
upsertDiscoveryResult,
|
|
getDiscoveryResults,
|
|
getDiscoveryResultById,
|
|
markVerified,
|
|
deleteDiscoveryResult,
|
|
} from "./db/discoveryResults";
|
|
|
|
export type {
|
|
DiscoveryResult,
|
|
DiscoveryMethod,
|
|
DiscoveryAuthType,
|
|
DiscoveryRiskLevel,
|
|
DiscoveryStatus,
|
|
} from "./db/discoveryResults";
|
|
export type { WebhookDelivery } from "./db/webhookDeliveries";
|
|
|
|
export {
|
|
saveQuotaSnapshot,
|
|
getQuotaSnapshots,
|
|
getAggregatedSnapshots,
|
|
cleanupOldSnapshots,
|
|
} from "./db/quotaSnapshots";
|
|
|
|
export * from "./db/sessionAccountAffinity";
|
|
export * from "./db/quotaResetEvents";
|
|
|
|
export type { QuotaSnapshotRow, ProviderUtilizationPoint } from "@/shared/types/utilization";
|
|
|
|
export {
|
|
getVersionManagerStatus,
|
|
getVersionManagerTool,
|
|
upsertVersionManagerTool,
|
|
updateVersionManagerTool,
|
|
deleteVersionManagerTool,
|
|
updateToolHealth,
|
|
updateToolVersion,
|
|
setToolStatus,
|
|
getServiceRow,
|
|
updateServiceField,
|
|
} from "./db/versionManager";
|
|
|
|
export {
|
|
listSyncTokens,
|
|
getSyncTokenById,
|
|
getSyncTokenByHash,
|
|
createSyncTokenRecord,
|
|
revokeSyncToken,
|
|
touchSyncTokenLastUsed,
|
|
} from "./db/syncTokens";
|
|
|
|
export {
|
|
getUpstreamProxyConfigs,
|
|
getUpstreamProxyConfig,
|
|
upsertUpstreamProxyConfig,
|
|
updateUpstreamProxyConfig,
|
|
deleteUpstreamProxyConfig,
|
|
getProvidersByMode,
|
|
getFallbackChainForProvider,
|
|
validateProxyUrl,
|
|
} from "./db/upstreamProxy";
|
|
|
|
export {
|
|
getProviderLimitsCache,
|
|
getAllProviderLimitsCache,
|
|
setProviderLimitsCache,
|
|
setProviderLimitsCacheBatch,
|
|
deleteProviderLimitsCache,
|
|
} from "./db/providerLimits";
|
|
|
|
export type { ProviderLimitsCacheEntry } from "./db/providerLimits";
|
|
|
|
export {
|
|
getPersistedCreditBalance,
|
|
getAllPersistedCreditBalances,
|
|
persistCreditBalance,
|
|
} from "./db/creditBalance";
|
|
|
|
export {
|
|
insertCompressionAnalyticsRow,
|
|
getCompressionAnalyticsSummary,
|
|
} from "./db/compressionAnalytics";
|
|
|
|
export type {
|
|
CompressionAnalyticsRow,
|
|
CompressionAnalyticsSummary,
|
|
} from "./db/compressionAnalytics";
|
|
|
|
export {
|
|
// Reasoning Replay Cache (#1628)
|
|
setReasoningCache,
|
|
getReasoningCache,
|
|
deleteReasoningCache,
|
|
clearAllReasoningCache,
|
|
} from "./db/reasoningCache";
|
|
|
|
export type { ReasoningCacheEntry, ReasoningCacheStats } from "./db/reasoningCache";
|
|
|
|
export {
|
|
// 1proxy Integration (#1788)
|
|
listOneproxyProxies,
|
|
getOneproxyStats,
|
|
upsertOneproxyProxy,
|
|
getOneproxyProxyById,
|
|
deleteOneproxyProxy,
|
|
clearAllOneproxyProxies,
|
|
getOneproxyProxyForRotation,
|
|
markOneproxyProxyFailed,
|
|
} from "./db/oneproxy";
|
|
|
|
export type { OneproxyProxyRecord, OneproxyStats } from "./db/oneproxy";
|
|
|
|
export {
|
|
getSessionAccountAffinity,
|
|
upsertSessionAccountAffinity,
|
|
touchSessionAccountAffinity,
|
|
deleteSessionAccountAffinity,
|
|
evictSessionAccountAffinityForConnection,
|
|
cleanupStaleSessionAccountAffinities,
|
|
startSessionAccountAffinityCleanup,
|
|
stopSessionAccountAffinityCleanupForTests,
|
|
} from "./db/sessionAccountAffinity";
|
|
|
|
export {
|
|
// Gamification & Leaderboard
|
|
updateScore,
|
|
getRank,
|
|
getTopN,
|
|
addXp,
|
|
getXp,
|
|
updateLevel,
|
|
unlockBadge,
|
|
hasBadge,
|
|
getBadges,
|
|
getBadgeDefinitions,
|
|
transferTokens,
|
|
getBalance,
|
|
getHistory,
|
|
createInviteToken,
|
|
getInviteByCode,
|
|
redeemInvite,
|
|
revokeInvite,
|
|
connectServer,
|
|
disconnectServer,
|
|
listServers,
|
|
getConnectedServerByKeyHash,
|
|
} from "./db/gamification";
|
|
|
|
export type {
|
|
LeaderboardRow,
|
|
UserLevelRow,
|
|
BadgeDefinition,
|
|
UserBadge,
|
|
XpAuditLogEntry,
|
|
TokenLedgerEntry,
|
|
InviteToken,
|
|
CommunityServer,
|
|
} from "./db/gamification";
|
|
|
|
export * from "./db/featureFlags";
|
|
|
|
export {
|
|
upsertHandoff,
|
|
getHandoff,
|
|
deleteHandoff,
|
|
cleanupExpiredHandoffs,
|
|
hasActiveHandoff,
|
|
recordSessionModelUsage,
|
|
getLastSessionModel,
|
|
} from "./db/contextHandoffs";
|
|
|
|
export type { HandoffPayload } from "./db/contextHandoffs";
|
|
|
|
export {
|
|
getAllMiddlewareHooks,
|
|
getEnabledMiddlewareHooks,
|
|
getComboMiddlewareHooks,
|
|
getMiddlewareHook,
|
|
createMiddlewareHook,
|
|
updateMiddlewareHook,
|
|
deleteMiddlewareHook,
|
|
recordHookExecution,
|
|
insertHookLog,
|
|
getHookLogs,
|
|
cleanupHookLogs,
|
|
} from "./db/middleware";
|
|
|
|
export {
|
|
getAllKeyGroups,
|
|
getKeyGroup,
|
|
getKeyGroupWithPermissions,
|
|
createKeyGroup,
|
|
updateKeyGroup,
|
|
deleteKeyGroup,
|
|
getGroupPermissions,
|
|
addGroupPermission,
|
|
removeGroupPermission,
|
|
clearGroupPermissions,
|
|
getGroupMembers,
|
|
getKeyGroupsForApiKey,
|
|
addKeyToGroup,
|
|
removeKeyFromGroup,
|
|
checkKeyModelAccess,
|
|
} from "./db/apiKeyGroups";
|
|
|
|
export {
|
|
createRelayToken,
|
|
getRelayTokens,
|
|
getRelayToken,
|
|
getRelayTokenByHash,
|
|
updateRelayToken,
|
|
deleteRelayToken,
|
|
toggleRelayToken,
|
|
checkRateLimit,
|
|
recordRelayUsage,
|
|
getRelayUsage,
|
|
getRelayLogs,
|
|
} from "./db/relayProxies";
|
|
|
|
export type {
|
|
RelayToken,
|
|
RelayTokenRow,
|
|
RelayLogRow,
|
|
CreateRelayTokenInput,
|
|
RelayTokenWithSecret,
|
|
} from "./db/relayProxies";
|
|
|
|
export {
|
|
upsertFreeProxy,
|
|
listFreeProxies,
|
|
countFreeProxies,
|
|
listFreeProxiesBySource,
|
|
getFreeProxyById,
|
|
markFreeProxyInPool,
|
|
promoteFreeProxyToPool,
|
|
deleteFreeProxy,
|
|
clearFreeProxiesBySource,
|
|
pruneStaleFreeProxies,
|
|
getFreeProxyStats,
|
|
recordFreeProxySync,
|
|
recordFreeProxySyncErrors,
|
|
clearFreeProxySyncErrors,
|
|
getFreeProxySyncErrors,
|
|
} from "./db/freeProxies";
|
|
|
|
export type { FreeProxyRecord, FreeProxyStats, FreeProxySyncErrors } from "./db/freeProxies";
|
|
|
|
export {
|
|
listPlaygroundPresets,
|
|
getPlaygroundPreset,
|
|
createPlaygroundPreset,
|
|
updatePlaygroundPreset,
|
|
deletePlaygroundPreset,
|
|
} from "./db/playgroundPresets";
|
|
|
|
export type { PlaygroundPresetListItem } from "./db/playgroundPresets";
|
|
// Plan 21 — Memory Engine Redesign
|
|
export {
|
|
getMemoryVecMeta,
|
|
setMemoryVecMeta,
|
|
markMemoryNeedsReindex,
|
|
markAllMemoriesNeedReindex,
|
|
getMemoryReindexQueue,
|
|
countMemoryReindexPending,
|
|
type MemoryVecMeta,
|
|
} from "./db/memoryVec";
|
|
// T-A-F2: AgentBridge state/mappings/bypass + Inspector custom hosts/sessions
|
|
export * from "./db/agentBridgeState";
|
|
export * from "./db/agentBridgeMappings";
|
|
export * from "./db/agentBridgeBypass";
|
|
export * from "./db/inspectorCustomHosts";
|
|
export * from "./db/inspectorSessions";
|
|
export * from "./db/omp";
|
|
// Quota Sharing — Group B (planos 16+22)
|
|
export {
|
|
listPools,
|
|
getPool,
|
|
getPoolsByGroup,
|
|
createPool,
|
|
updatePool,
|
|
deletePool,
|
|
upsertAllocations,
|
|
listAllocationsForApiKey,
|
|
} from "./db/quotaPools";
|
|
// Quota per-(key, model) caps — Group B Fase 3 #7
|
|
export { getModelCap, listModelCaps, setModelCap, deleteModelCap } from "./db/quotaModelCaps";
|
|
|
|
export {
|
|
// Quota Groups (B2)
|
|
createGroup,
|
|
getGroup,
|
|
getGroupName,
|
|
listGroups,
|
|
renameGroup,
|
|
deleteGroup,
|
|
} from "./db/quotaGroups";
|
|
|
|
export type { QuotaGroup } from "./db/quotaGroups";
|
|
export {
|
|
getBucket,
|
|
incrementBucket,
|
|
getPair,
|
|
sumPoolDimension,
|
|
gcOlderThan as gcQuotaConsumption,
|
|
} from "./db/quotaConsumption";
|
|
export {
|
|
getPlan as getProviderPlan,
|
|
listPlans as listProviderPlans,
|
|
upsertPlan as upsertProviderPlan,
|
|
deletePlan as deleteProviderPlan,
|
|
} from "./db/providerPlans";
|
|
|
|
export {
|
|
// Per-API-Key Token Limits (migration 073)
|
|
upsertTokenLimit,
|
|
listTokenLimits,
|
|
getTokenLimitsForRequest,
|
|
deleteTokenLimit,
|
|
getWindowUsage,
|
|
incrementWindowTokens,
|
|
resetWindowIfElapsed,
|
|
logTokenLimitReset,
|
|
} from "./db/tokenLimits";
|
|
|
|
export type {
|
|
TokenLimit,
|
|
TokenLimitScopeType,
|
|
UpsertTokenLimitInput,
|
|
TokenWindowState,
|
|
} from "./db/tokenLimits";
|
|
|
|
export {
|
|
insertPlugin,
|
|
getPluginById,
|
|
getPluginByName,
|
|
listPlugins,
|
|
updatePluginStatus,
|
|
updatePluginConfig,
|
|
deletePlugin,
|
|
pluginExists,
|
|
} from "./db/plugins";
|
|
|
|
export type { PluginRow, PluginCreateInput } from "./db/plugins";
|
|
|
|
export {
|
|
getApiKeyContextSource,
|
|
setApiKeyContextSource,
|
|
deleteApiKeyContextSource,
|
|
listApiKeyContextSources,
|
|
} from "./db/apiKeyContextSources";
|
|
export type { ApiKeyContextSource } from "./db/apiKeyContextSources";
|
|
|
|
export { sumUsageTokensThisMonth } from "./db/usageSummary";
|
|
|
|
export {
|
|
// Model Intelligence (task-fitness scores)
|
|
getModelIntelligence,
|
|
getModelIntelligenceBySource,
|
|
upsertModelIntelligence,
|
|
deleteModelIntelligence,
|
|
deleteExpiredIntelligence,
|
|
deleteModelIntelligenceBySource,
|
|
listModelIntelligence,
|
|
bulkUpsertModelIntelligence,
|
|
getResolvedTaskFitness,
|
|
setUserFitnessOverrideEntry,
|
|
deleteUserFitnessOverrideEntry,
|
|
} from "./db/modelIntelligence";
|
|
|
|
export type { ModelIntelligenceEntry } from "./db/modelIntelligence";
|
|
|
|
export {
|
|
getProviderMetrics,
|
|
getSearchProviderStats,
|
|
getRecentSearchLogs,
|
|
getSearchAggregateStats,
|
|
getSearchProviderCounts,
|
|
getFallbackStats,
|
|
} from "./db/callLogStats";
|
|
export type {
|
|
ProviderMetricRow,
|
|
SearchProviderStatRow,
|
|
SearchRecentRow,
|
|
SearchAggregateStats,
|
|
SearchProviderCountRow,
|
|
FallbackStatsRow,
|
|
} from "./db/callLogStats";
|
|
|
|
export {
|
|
buildUnifiedSource,
|
|
buildPresetUnifiedSource,
|
|
getUsageSummary,
|
|
getDailyUsage,
|
|
getDailyCostRows,
|
|
getHeatmapRows,
|
|
getModelUsageRows,
|
|
getProviderCostRows,
|
|
getProviderUsageRows,
|
|
getAccountCostRows,
|
|
getAccountUsageRows,
|
|
getApiKeyUsageRows,
|
|
getServiceTierUsageRows,
|
|
getApiKeyMetadataRows,
|
|
getWeeklyPatternRows,
|
|
getPresetCostModelRows,
|
|
getAllUsageHistory,
|
|
getAllDomainCostHistory,
|
|
getAllDomainBudgets,
|
|
} from "./db/usageAnalytics";
|
|
export type {
|
|
AnalyticsParams,
|
|
BuildUnifiedSourceOptions,
|
|
UnifiedSourceResult,
|
|
UsageSummaryRow,
|
|
DailyUsageRow,
|
|
DailyCostRow,
|
|
HeatmapRow,
|
|
ModelUsageRow,
|
|
ProviderCostRow,
|
|
ProviderUsageRow,
|
|
AccountCostRow,
|
|
AccountUsageRow,
|
|
ApiKeyUsageRow,
|
|
ServiceTierUsageRow,
|
|
ApiKeyMetadataRow,
|
|
WeeklyPatternRow,
|
|
PresetCostModelRow,
|
|
} from "./db/usageAnalytics";
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// usage_logs — auto-routing analytics (#3500 slice 4)
|
|
// ---------------------------------------------------------------------------
|
|
export {
|
|
getAutoRoutingTotalCount,
|
|
getAutoRoutingVariantBreakdown,
|
|
getAutoRoutingTopProviders,
|
|
} from "./db/usageLogs";
|
|
export type {
|
|
AutoRoutingTotalResult,
|
|
AutoRoutingVariantRow,
|
|
AutoRoutingTopProviderRow,
|
|
} from "./db/usageLogs";
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// semantic_cache — cache entries CRUD (#3500 slice 4)
|
|
// ---------------------------------------------------------------------------
|
|
export {
|
|
listSemanticCacheEntries,
|
|
deleteSemanticCacheBySignature,
|
|
deleteSemanticCacheByModel,
|
|
} from "./db/semanticCache";
|
|
export type {
|
|
SemanticCacheEntry,
|
|
SemanticCacheListOptions,
|
|
SemanticCacheListResult,
|
|
DeleteSemanticCacheBySignatureResult,
|
|
DeleteSemanticCacheByModelResult,
|
|
} from "./db/semanticCache";
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// proxy_logs — export query (#3500 slice 4)
|
|
// ---------------------------------------------------------------------------
|
|
export { exportProxyLogsSince } from "./db/proxyLogs";
|
|
// ---------------------------------------------------------------------------
|
|
// Per-connection 429 cooldown wrappers (#5957 / #5958 — Issue 1 follow-ups)
|
|
// Logic lives in db/providers/rateLimit.ts (Hard Rule #2 — localDb is re-export
|
|
// only); re-exported here for the historical localDb import contract.
|
|
// ---------------------------------------------------------------------------
|
|
export { markConnectionRateLimitedUntil, clearConnectionRateLimit } from "./db/providers";
|
|
// Provider param filters — denylist/allowlist config per provider/model (#6625)
|
|
export * from "./db/paramFilters";
|
|
export * from "./db/interceptionRules"; // Per-model web-search/web-fetch interception rules (#3384)
|
|
export * from "./db/relayProbeStats"; // Relay probe latency/health stats (#6909)
|