Files
Kelx/services/server-agent-queue.js
2026-11-30 16:32:37 +00:00

70 lines
3.9 KiB
JavaScript

"use strict";
const BASE_ACTIVE_CAPACITY = 200;
const SERVER_AGENT_MAX_CONCURRENCY = 500;
const ACCOUNTS_PER_STEP = 10;
const SLOTS_PER_STEP = 5;
// adpanel:agent-rollback - old workers only match feature_generation, which consented jobs get on claim.
const AGENT_JOB_GENERATION_SQL = `((auto_approve_file_edits = FALSE AND feature_generation = ?)
OR (auto_approve_file_edits = TRUE AND auto_file_edit_generation = ?
AND ((status = 'queued' AND feature_generation IS NULL)
OR (status = 'running' AND feature_generation = auto_file_edit_generation))))`;
async function assertServerAgentQueueCapacity(connection, { accountId, maxPending, maxPendingPerAccount, source }) {
const limit = Math.max(1, Math.min(5000, Math.trunc(maxPending)));
// A locking read sees committed rows even if the outer Planner transaction has an older snapshot.
const [rows] = await connection.execute(`SELECT user_id, source FROM ai_agent_jobs
WHERE status IN ('queued','running') LIMIT ${limit} FOR UPDATE`);
const accountPending = rows.filter((row) => String(row.user_id) === String(accountId)).length;
const background = rows.filter((row) => row.source !== "live_chat").length;
if (rows.length >= limit || (source !== "live_chat" && background >= Math.max(1, Math.floor(limit * 0.35)))) {
throw Object.assign(new Error("ADPanel Agent queue is full. Please try again shortly."), { status: 503 });
}
if (accountPending >= maxPendingPerAccount) {
throw Object.assign(new Error("ADPanel Agent per-user queue limit reached. Please wait for your queued or running jobs to finish before queueing more."), { status: 503 });
}
}
function createServerAgentJobPump({ query, canPump, runJob, onJobError, onJobSettled, maxActive = SERVER_AGENT_MAX_CONCURRENCY, lane, generation }) {
const activeJobs = new Set();
let pumping = false;
return async function pumpAiAgentJobs() {
if (pumping || activeJobs.size >= maxActive || !canPump()) return;
pumping = true;
try {
// adpanel:agent-active-slots - count local reservations before their claims become visible in the database.
const reserved = [...activeJobs];
const unreserved = reserved.length ? ` AND id NOT IN (${reserved.map(() => "?").join(", ")})` : "";
const scope = lane === "live" ? " AND feature_generation = ? AND source = 'live_chat'"
: lane === "background" ? ` AND ${AGENT_JOB_GENERATION_SQL} AND source <> 'live_chat'` : "";
const params = lane === "background" ? [...reserved, generation, generation] : scope ? [...reserved, generation] : reserved;
const [stats] = await query(`SELECT COUNT(DISTINCT CASE WHEN status = 'queued' THEN user_id END) AS waiting_accounts,
COUNT(CASE WHEN status = 'running' THEN 1 END) AS running_count
FROM ai_agent_jobs WHERE status IN ('queued','running')${unreserved}${scope}`, params);
const waitingAccounts = Number(stats.waiting_accounts);
const limit = Math.min(maxActive, BASE_ACTIVE_CAPACITY + Math.floor(waitingAccounts / ACCOUNTS_PER_STEP) * SLOTS_PER_STEP);
const slots = limit - reserved.length - Number(stats.running_count);
if (!waitingAccounts || !(slots > 0) || !canPump()) return;
const accountSlots = scope ? ` AND (SELECT COUNT(*) FROM ai_agent_jobs active
WHERE active.user_id = ai_agent_jobs.user_id AND active.status = 'running') < 2` : "";
const rows = await query(`SELECT id FROM ai_agent_jobs WHERE status = 'queued'${unreserved}${scope}${accountSlots}
ORDER BY created_at ASC, id ASC LIMIT ${slots}`, params);
if (!canPump()) return;
for (const { id } of rows) {
activeJobs.add(id);
runJob(id).catch((error) => onJobError(id, error)).finally(() => {
activeJobs.delete(id);
onJobSettled();
});
}
} finally {
pumping = false;
}
};
}
module.exports = { AGENT_JOB_GENERATION_SQL, SERVER_AGENT_MAX_CONCURRENCY, assertServerAgentQueueCapacity, createServerAgentJobPump };