Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,168 @@
|
||||
"use strict";
|
||||
|
||||
const { execFile } = require("node:child_process");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { promisify } = require("node:util");
|
||||
const { createCrossProcessOperationMutex } = require("../utils/cross-process-mutex");
|
||||
const { readAgentFeatureConfig, readPanelEnv, PANEL_ENV_PATH } = require("./feature-config");
|
||||
const { ensureAgentQueueSchema, reconcileAgentQueueState } = require("./queue-state");
|
||||
const { AgentRpcError, RPC_VERSION, WORKER_SOCKET, PANEL_SOCKET_DIRECTORY, deriveRpcSecret, createAgentRpcClient, startAgentRpcServer, listPanelAgentSockets } = require("./private-rpc");
|
||||
const { pruneCredentialProposals } = require("./credential-proposals");
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const PRIV_RUNNER = "/usr/local/lib/adpanel/adpanel-priv";
|
||||
const CONTROL_INTERVAL_MS = 2000;
|
||||
const STARTUP_ATTEMPTS = 24;
|
||||
|
||||
async function reconcileService(action) {
|
||||
const args = ["agent-service", action];
|
||||
const options = { timeout: action === "start" ? 6000 : 16_000, maxBuffer: 8192 };
|
||||
if (process.getuid() === 0) return execFileAsync(PRIV_RUNNER, args, options);
|
||||
return execFileAsync("/usr/bin/sudo", ["-n", PRIV_RUNNER, ...args], options);
|
||||
}
|
||||
|
||||
function createPanelAgentRuntime({ db, sessionSecret, enabledAtStartup, authorizeRequest, onDiagnosticError, logger = console }) {
|
||||
const mutex = createCrossProcessOperationMutex({
|
||||
label: "[agent-reconcile]",
|
||||
lockFilePath: path.join(path.dirname(PANEL_ENV_PATH), ".agent-reconcile.lock"),
|
||||
logger,
|
||||
});
|
||||
let closeSocket;
|
||||
let interval;
|
||||
let attempts = 0;
|
||||
let inFlight = false;
|
||||
let stopped = false;
|
||||
let reconciled;
|
||||
let secret;
|
||||
let call;
|
||||
let stateConfirmedAt = 0;
|
||||
|
||||
async function startMatchingWorker(generation) {
|
||||
let incompatible = false;
|
||||
try {
|
||||
const health = await call("health");
|
||||
incompatible = health?.version !== RPC_VERSION || health.generation !== generation;
|
||||
} catch (error) {
|
||||
incompatible = error.code === "agent_rpc_auth" || error.code === "agent_rpc_version";
|
||||
}
|
||||
if (stopped || !readAgentFeatureConfig().enabled) throw new AgentRpcError(503, "agent_unavailable");
|
||||
if (incompatible && readPanelEnv().SESSION_SECRET !== sessionSecret) {
|
||||
throw new AgentRpcError(503, "agent_unavailable");
|
||||
}
|
||||
await reconcileService(incompatible ? "restart" : "start");
|
||||
}
|
||||
|
||||
async function bindDiagnosticSocket() {
|
||||
if (closeSocket) return;
|
||||
secret ||= deriveRpcSecret(sessionSecret);
|
||||
call ||= createAgentRpcClient({ socketPath: WORKER_SOCKET, receiver: "worker", secret, timeoutMs: 2000 });
|
||||
const socketPath = path.join(PANEL_SOCKET_DIRECTORY, `panel-${process.pid}.sock`);
|
||||
await fs.unlink(socketPath).catch((error) => { if (error.code !== "ENOENT") throw error; });
|
||||
const close = await startAgentRpcServer({
|
||||
socketPath, secret, receiver: "panel", onError: onDiagnosticError,
|
||||
handlers: {
|
||||
health: () => ({ version: RPC_VERSION, generation: !stopped && reconciled?.enabled ? reconciled.generation : null }),
|
||||
context: (args, signal) => authorizeRequest("context", args, signal),
|
||||
tool: (args, signal) => authorizeRequest("tool", args, signal),
|
||||
autoFileEdit: (args, signal) => authorizeRequest("autoFileEdit", args, signal),
|
||||
fileReads: (args, signal) => authorizeRequest("fileReads", args, signal),
|
||||
localConsole: (args, signal) => authorizeRequest("localConsole", args, signal),
|
||||
verify: (args, signal) => authorizeRequest("verify", args, signal),
|
||||
plannerDone: (args, signal) => authorizeRequest("plannerDone", args, signal),
|
||||
},
|
||||
});
|
||||
if (stopped) await close();
|
||||
else closeSocket = close;
|
||||
}
|
||||
|
||||
async function tick() {
|
||||
if (inFlight || stopped) return;
|
||||
inFlight = true;
|
||||
try {
|
||||
if (!reconciled && attempts < STARTUP_ATTEMPTS) {
|
||||
const release = mutex.tryAcquire();
|
||||
if (!release) return;
|
||||
try {
|
||||
const desired = readAgentFeatureConfig();
|
||||
if (desired.enabled !== enabledAtStartup) return;
|
||||
attempts += 1;
|
||||
if (desired.enabled) {
|
||||
await bindDiagnosticSocket();
|
||||
await pruneCredentialProposals();
|
||||
}
|
||||
const reconcileQueue = async () => {
|
||||
await ensureAgentQueueSchema(db);
|
||||
return reconcileAgentQueueState(db.pool, desired.enabled);
|
||||
};
|
||||
if (desired.enabled) {
|
||||
reconciled = await reconcileQueue();
|
||||
try { await startMatchingWorker(reconciled.generation); } catch (error) { reconciled = null; throw error; }
|
||||
} else {
|
||||
const [queue, service] = await Promise.allSettled([reconcileQueue(), reconcileService("stop")]);
|
||||
if (queue.status === "rejected") throw queue.reason;
|
||||
if (service.status === "rejected") throw service.reason;
|
||||
reconciled = queue.value;
|
||||
}
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
if (!reconciled?.enabled || !call) return;
|
||||
const health = await call("health");
|
||||
if (health?.ready && health.version === RPC_VERSION && health.generation === reconciled.generation) {
|
||||
stateConfirmedAt = Date.now();
|
||||
} else {
|
||||
stateConfirmedAt = 0;
|
||||
}
|
||||
} catch {
|
||||
stateConfirmedAt = 0;
|
||||
if (attempts === 1 || attempts === STARTUP_ATTEMPTS) logger.warn("[Agent] Worker unavailable during startup reconciliation.");
|
||||
} finally {
|
||||
inFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
function start() {
|
||||
if (interval || stopped) return;
|
||||
interval = setInterval(tick, CONTROL_INTERVAL_MS);
|
||||
interval.unref();
|
||||
void tick();
|
||||
}
|
||||
|
||||
async function stop() {
|
||||
stopped = true;
|
||||
stateConfirmedAt = 0;
|
||||
clearInterval(interval);
|
||||
if (closeSocket) await closeSocket();
|
||||
}
|
||||
|
||||
function requireReady() {
|
||||
if (stopped || !reconciled?.enabled || Date.now() - stateConfirmedAt > 2 * CONTROL_INTERVAL_MS) {
|
||||
throw new AgentRpcError(503, "agent_unavailable");
|
||||
}
|
||||
return reconciled;
|
||||
}
|
||||
|
||||
function request(operation, args, signal) {
|
||||
requireReady();
|
||||
return createAgentRpcClient({ socketPath: WORKER_SOCKET, receiver: "worker", secret })(operation, args, signal);
|
||||
}
|
||||
|
||||
async function readLocalConsole(claim, target, limit, signal) {
|
||||
const paths = await listPanelAgentSockets();
|
||||
const results = await Promise.allSettled(paths.map((socketPath) => createAgentRpcClient({
|
||||
socketPath, receiver: "panel", secret, timeoutMs: 1500,
|
||||
})("localConsole", { claim, target, limit }, signal)));
|
||||
if (!results.length || results.some((result) => result.status === "rejected")) {
|
||||
throw new AgentRpcError(503, "agent_console_owner_unavailable");
|
||||
}
|
||||
const snapshots = results.map((result) => result.value).filter((lines) => Array.isArray(lines) && lines.length);
|
||||
if (snapshots.length > 1) throw new AgentRpcError(503, "agent_console_owner_ambiguous");
|
||||
return snapshots[0] || [];
|
||||
}
|
||||
|
||||
return { start, stop, requireReady, request, readLocalConsole, getState: () => reconciled };
|
||||
}
|
||||
|
||||
module.exports = { createPanelAgentRuntime };
|
||||
Reference in new issue
Block a user