Files
2026-11-30 16:32:37 +00:00

189 lines
8.5 KiB
JavaScript

"use strict";
const { createPanelAgentRpcClient, deriveRpcSecret, startAgentRpcServer, WORKER_SOCKET, RPC_VERSION, AgentRpcError } = require("./private-rpc");
const { readAgentFeatureConfig, reportAgentFeatureConfig, PANEL_ENV_PATH } = require("./feature-config");
const { readAgentQueueState } = require("./queue-state");
const { recoverInterruptedAgentJobs } = require("./job-store");
const { createAgentJobRunner } = require("./run-job");
const { createServerAgentJobPump } = require("../services/server-agent-queue");
const { fetchAvailableAiModels, toAgentDiscoveryError } = require("./provider-discovery");
const { getAiProviderConfig } = require("./provider-config");
const { readProviderSettings, assertAiProviderReady, formatAiMessageModelLabel } = require("./provider-settings");
const { assertAiAgentJobDeadline } = require("./run-deadline");
const { readCredentialProposal } = require("./credential-proposals");
const { ATTACHMENT_PRUNE_INTERVAL_MS, pruneExpiredAgentAttachments } = require("./attachments");
const { LIVE_CONCURRENCY, BACKGROUND_CONCURRENCY, DISCOVERY_CONCURRENCY, DB_CONNECTIONS, DISCOVERY_TIMEOUT_MS, RUN_TIMEOUT_MS, withProviderBudget } = require("./budgets");
const fs = require("node:fs/promises");
const dotenv = require("dotenv");
const POLL_MS = 750;
const RECOVERY_INTERVAL_MS = 30_000;
const STALE_RUN_SECONDS = Math.ceil(RUN_TIMEOUT_MS / 1000) + 60;
const CONSUMER_LOCK = "adpanel:agent-worker:v1";
async function main({ updateSignal } = {}) {
const config = readAgentFeatureConfig();
reportAgentFeatureConfig(config);
if (!config.enabled) return;
dotenv.config({ path: PANEL_ENV_PATH, override: true, quiet: true });
const secret = deriveRpcSecret(process.env.SESSION_SECRET);
const { probe: probePanel, request: callPanel } = createPanelAgentRpcClient({ secret });
const { createPanelDatabasePool } = require("../db");
const pool = createPanelDatabasePool({ connectionLimit: DB_CONNECTIONS + 1, queueLimit: 48 });
const db = { pool, query: async (query, params) => (await pool.execute(query, params))[0] };
const active = new Map();
const jobs = new Set();
const workerLifetime = new AbortController();
let closeSocket;
let lockConnection;
let timer;
let polling = false;
let discovering = 0;
let connectingProvider = false;
let healthyAt = 0;
let generation;
let stopping = false;
const isReady = () => !stopping && healthyAt > 0 && Date.now() - healthyAt < 2 * POLL_MS + 1000;
async function stop(exitCode = 0) {
if (stopping) return;
stopping = true;
if (exitCode) process.exitCode = exitCode;
clearInterval(timer);
workerLifetime.abort();
for (const { controller } of active.values()) controller.abort();
const killTimer = setTimeout(() => process.exit(1), 8000);
killTimer.unref();
if (closeSocket) await closeSocket();
await Promise.allSettled(jobs);
lockConnection?.destroy();
await pool.end();
clearTimeout(killTimer);
}
process.on("SIGTERM", () => { void stop().catch(() => process.exit(1)); });
process.on("SIGINT", () => { void stop().catch(() => process.exit(1)); });
updateSignal?.addEventListener("abort", () => { void stop(1).catch(() => process.exit(1)); }, { once: true });
async function discover({ provider, proposalId } = {}, requestSignal) {
if (!getAiProviderConfig(provider)) throw new AgentRpcError(400, "agent_invalid_provider");
const setup = Boolean(proposalId);
if ((setup ? connectingProvider : discovering >= DISCOVERY_CONCURRENCY) || !isReady()) {
throw new AgentRpcError(503, "agent_discovery_busy");
}
if (setup) connectingProvider = true;
else discovering += 1;
const signal = AbortSignal.any([requestSignal, workerLifetime.signal, AbortSignal.timeout(DISCOVERY_TIMEOUT_MS)]);
try {
const settings = setup ? await readCredentialProposal(proposalId) : readProviderSettings(provider);
return await withProviderBudget(provider, setup ? "setup" : "discovery", signal,
() => fetchAvailableAiModels(provider, settings, { validateModel: setup, signal }));
} catch (error) {
throw toAgentDiscoveryError(error, signal);
} finally {
if (setup) connectingProvider = false;
else discovering -= 1;
}
}
try {
lockConnection = await pool.getConnection();
if (stopping) { lockConnection.destroy(); return; }
const [[lock]] = await lockConnection.execute("SELECT GET_LOCK(?, 0) AS acquired", [CONSUMER_LOCK]);
if (Number(lock.acquired) !== 1) throw new Error("Consumer already active");
lockConnection.connection?.on("error", () => { void stop(1).catch(() => process.exit(1)); });
const state = await readAgentQueueState(db);
if (!state?.enabled || stopping) { await stop(); return; }
generation = state.generation;
await recoverInterruptedAgentJobs(db);
let lastRecovery = Date.now();
let lastAttachmentPrune = 0;
const run = createAgentJobRunner({ db, generation, active, callPanel,
getProviderSettings: assertAiProviderReady, formatModelLabel: formatAiMessageModelLabel,
assertDeadline: assertAiAgentJobDeadline, stopping: () => stopping,
});
const pump = (lane, maxActive) => createServerAgentJobPump({
query: db.query, lane, generation, maxActive, canPump: isReady,
runJob: (id) => {
const task = run(id);
jobs.add(task);
return task.finally(() => jobs.delete(task));
},
onJobError: () => console.warn("[Agent] A job could not settle."), onJobSettled: () => {},
});
const pumpLive = pump("live", LIVE_CONCURRENCY);
const pumpBackground = pump("background", BACKGROUND_CONCURRENCY);
async function poll() {
if (polling || stopping) return;
polling = true;
try {
const [[ownership]] = await lockConnection.execute("SELECT IS_USED_LOCK(?) = CONNECTION_ID() AS owned", [CONSUMER_LOCK]);
if (Number(ownership.owned) !== 1) {
void stop(1).catch(() => process.exit(1));
return;
}
const current = await readAgentQueueState(db);
if (!current?.enabled || current.generation !== generation) {
void stop().catch(() => process.exit(1));
return;
}
if (Date.now() - lastRecovery >= RECOVERY_INTERVAL_MS) {
await recoverInterruptedAgentJobs(db, STALE_RUN_SECONDS);
lastRecovery = Date.now();
}
if (Date.now() - lastAttachmentPrune >= ATTACHMENT_PRUNE_INTERVAL_MS) {
lastAttachmentPrune = Date.now();
await pruneExpiredAgentAttachments(db).catch(() => console.warn("[Agent] Attachment cleanup could not finish."));
}
if (active.size) {
const ids = [...active.keys()];
const running = await db.query(`SELECT id, claim_token FROM ai_agent_jobs WHERE status = 'running'
AND id IN (${ids.map(() => "?").join(",")})`, ids);
const tokens = new Map(running.map((row) => [String(row.id), row.claim_token]));
for (const [id, claim] of active) if (ids.includes(id) && tokens.get(id) !== claim.token) claim.controller.abort();
}
// adpanel:agent-panel-readiness - A SQL lease alone cannot authorize diagnostic execution.
const signal = AbortSignal.any([workerLifetime.signal, AbortSignal.timeout(POLL_MS)]);
try {
await probePanel(generation, signal);
} catch {
healthyAt = 0;
return;
}
healthyAt = Date.now();
await Promise.all([pumpLive(), pumpBackground()]);
} catch {
healthyAt = 0;
for (const { controller } of active.values()) controller.abort();
} finally {
polling = false;
}
}
await fs.unlink(WORKER_SOCKET).catch((error) => { if (error.code !== "ENOENT") throw error; });
const close = await startAgentRpcServer({ socketPath: WORKER_SOCKET, secret, receiver: "worker", handlers: {
health: () => ({ version: RPC_VERSION, generation, ready: isReady() }),
discover,
cancel: ({ id, token }) => {
const claim = active.get(String(id));
if (claim && claim.token === token) claim.controller.abort();
return { ok: true };
},
} });
if (stopping) { await close(); return; }
closeSocket = close;
timer = setInterval(() => { void poll(); }, POLL_MS);
await poll();
} catch (error) {
await stop();
throw error;
}
}
if (require.main === module) main().catch(() => {
console.error("[Agent] Worker startup failed. Check service configuration, MySQL readiness, and the panel version.");
process.exitCode = 1;
});
module.exports = { main };