"use strict"; const { AsyncLocalStorage } = require("node:async_hooks"); const { performance } = require("node:perf_hooks"); const { setTimeout: delay } = require("node:timers/promises"); const { proxyAiRequest } = require("../services/server-agent-provider-http"); const { AgentRpcError } = require("./private-rpc"); const LIVE_CONCURRENCY = 12; const BACKGROUND_CONCURRENCY = 4; const DISCOVERY_CONCURRENCY = 2; const DB_CONNECTIONS = 6; const RUN_TIMEOUT_MS = 3 * 60 * 1000; const DISCOVERY_TIMEOUT_MS = 10_000; const MAX_RUN_CALLS = 16; const PROVIDER_CALLS_PER_MINUTE = Object.freeze({ live: 78, background: 8, discovery: 4, setup: 8 }); const OUTPUT_TOKENS_PER_TURN = 2500; const providerContext = new AsyncLocalStorage(); const buckets = new Map(); function withProviderBudget(provider, lane, signal, operation) { if (!Object.hasOwn(PROVIDER_CALLS_PER_MINUTE, lane)) throw new TypeError("Unknown Agent provider lane"); return providerContext.run({ provider, lane, signal, calls: 0 }, operation); } async function takeProviderSlot(run, outputTokens, signal) { const key = `${run.provider}:${run.lane}`; const callLimit = PROVIDER_CALLS_PER_MINUTE[run.lane]; const tokenLimit = callLimit * OUTPUT_TOKENS_PER_TURN; const minute = 60_000; for (;;) { signal?.throwIfAborted(); const previous = buckets.get(key); const now = performance.now(); const elapsed = previous ? (now - previous.at) / minute : 1; const calls = Math.min(callLimit, (previous?.calls || 0) + elapsed * callLimit); const tokens = Math.min(tokenLimit, (previous?.tokens || 0) + elapsed * tokenLimit); if (calls >= 1 && tokens >= outputTokens) { buckets.set(key, { at: now, calls: calls - 1, tokens: tokens - outputTokens }); return; } if (run.lane === "discovery" || run.lane === "setup") throw new AgentRpcError(429, "agent_discovery_busy"); if (!signal) throw new AgentRpcError(429, "agent_provider_busy"); const waitMs = Math.ceil(minute * Math.max((1 - calls) / callLimit, (outputTokens - tokens) / tokenLimit)); await delay(waitMs, undefined, { signal }); } } async function requestAgentProvider(url, options, timeoutMs) { const run = providerContext.getStore(); if (!run) return proxyAiRequest(url, options, timeoutMs); const signals = [run.signal, options.signal].filter(Boolean); const signal = signals.length ? AbortSignal.any(signals) : undefined; signal?.throwIfAborted(); if (++run.calls > MAX_RUN_CALLS) throw new AgentRpcError(429, "agent_provider_busy"); await takeProviderSlot(run, options.method === "GET" ? 0 : OUTPUT_TOKENS_PER_TURN, signal); signal?.throwIfAborted(); return proxyAiRequest(url, { ...options, signal }, timeoutMs); } module.exports = { LIVE_CONCURRENCY, BACKGROUND_CONCURRENCY, DISCOVERY_CONCURRENCY, DB_CONNECTIONS, RUN_TIMEOUT_MS, DISCOVERY_TIMEOUT_MS, withProviderBudget, requestAgentProvider, };