"use strict"; const { Router } = require("express"); const { AgentRpcError } = require("../AgentWorker/private-rpc"); const { LIVE_SOURCE, parseLiveAgentSubmission } = require("../AgentWorker/admission"); const { cancelOwnedAgentJob } = require("../AgentWorker/job-store"); const { reviewProjection, REVIEW_SOURCE_REF_PREFIX } = require("../AgentWorker/action-proposal"); const { isValidServerAgentChatCursor } = require("../services/server-agent-chat-ownership"); const ERRORS = { agent_unavailable: "ADPanel Agent is temporarily unavailable. Try again shortly.", agent_discovery_busy: "Model discovery is busy or rate-limited. Wait a moment and try again.", agent_discovery_failed: "Could not load models from the provider. Check the configuration and try again.", agent_discovery_auth: "The provider rejected the API key or denied access. Check the key and its permissions.", agent_discovery_account: "The provider requires account or billing attention.", agent_discovery_empty: "The provider returned no usable models. Check model access or enter a model ID for a custom provider.", agent_discovery_invalid_response: "The models endpoint did not return a model catalog. Check the API base URL or enter a model ID.", agent_discovery_unsupported: "The provider does not expose a models endpoint at that API URL. Check the URL or enter a model ID.", agent_discovery_model_unavailable: "The provider could not use that model ID. Check the ID, API base URL, and model access.", agent_discovery_redirect: "The provider redirected the request. Enter its final API base URL. Redirects are not followed.", agent_discovery_timeout: "The provider did not respond in time. Try again shortly.", agent_discovery_unreachable: "Could not reach the provider from the panel. Check DNS, TLS, and network access.", agent_discovery_upstream: "The provider returned a service error. Try again shortly.", agent_discovery_response_too_large: "The provider returned a model catalog larger than the discovery limit.", agent_invalid_proposal: "The Agent could not read the provider setup request. Try Save & Connect again.", agent_invalid_manual_model: "Enter up to 32 model IDs, one per line. Each ID must be at most 255 characters, with no control characters, and the list must fit within 4 KB.", agent_client_refresh_required: "Refresh the server page before sending an Agent message.", agent_invalid_chat: "Invalid chat ID.", agent_invalid_server: "A server is required.", agent_invalid_prompt: "A prompt below the size limit is required.", agent_invalid_image: "Use one supported image below the size limit.", agent_invalid_access_mode: "Select General access or Read only.", agent_chat_not_found: "Chat not found.", agent_chat_busy: "Finish or stop the current reply in this chat first.", agent_request_conflict: "This submission ID was already used for a different message.", agent_authority_revoked: "You no longer have permission for that Agent action.", agent_review_not_found: "This action is no longer available for review.", agent_review_used: "This action has already been reviewed.", agent_review_target_changed: "The reviewed server is no longer available.", agent_review_file_unavailable: "This file could not be reviewed as text.", agent_review_invalid_command: "The proposed console command is not valid.", agent_review_invalid: "Invalid action review.", }; function sendAgentError(res, error) { const status = Number(error?.status); if (!Number.isInteger(status) || status < 400 || status > 599) return res.status(500).json({ error: "Agent request failed." }); if (status === 429 || status === 503) res.set("Retry-After", "3"); if (Object.hasOwn(ERRORS, error.code)) return res.status(status).json({ error: ERRORS[error.code], code: error.code }); const code = error instanceof AgentRpcError ? error.code : status === 503 ? "agent_unavailable" : undefined; return res.status(status).json({ error: ERRORS[code] || (status < 500 ? error.message : ERRORS.agent_unavailable), code }); } function createAgentLiveRouter({ db, isAuthenticated, hasAgentAccess, getLoggedInUser, cancelLimiter, statusLimiter, insertAiAgentChatJob, saveSelection, worker, ensureAiChatTablesReady, review, reviewLimiter, getRequestIp }) { const router = Router(); async function authorize(req, res, next) { try { res.set("Cache-Control", "no-store"); if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); const user = await getLoggedInUser(req); if (!user?.id || user.suspended) return res.status(403).json({ error: "no agent access" }); req.agentAccount = user; return next(); } catch (error) { return sendAgentError(res, error); } } router.post("/chat", authorize, async (req, res) => { try { const live = parseLiveAgentSubmission(req.body); const { provider, model } = req.body; if (typeof provider !== "string" || typeof model !== "string" || model.length > 255) { return res.status(400).json({ error: "provider and model are required" }); } const user = req.agentAccount; const job = await insertAiAgentChatJob({ user, serverName: live.server, prompt: live.prompt, provider, model, source: LIVE_SOURCE, live }); await saveSelection(user.id, job.provider, job.model).catch(() => {}); return res.status(202).json({ ok: true, chatId: job.chatId, jobId: job.jobId, status: job.status }); } catch (error) { return sendAgentError(res, error); } }); router.get("/jobs/:id", statusLimiter, authorize, async (req, res) => { try { if (!isValidServerAgentChatCursor(req.params.id)) return res.status(400).json({ error: "invalid job id" }); await ensureAiChatTablesReady(); const [job] = await db.query(`SELECT job.id, job.chat_id, job.status, job.error, job.created_at, job.started_at, job.completed_at, reply.content, reply.agent_actions, reply.thinking_time_ms, reply.thinking_content, reply.model, ${reviewProjection}, (SELECT CAST(conclusion.id AS CHAR) FROM ai_agent_jobs conclusion WHERE conclusion.chat_id = job.chat_id AND conclusion.user_id = job.user_id AND conclusion.source = job.source AND conclusion.source_ref = CONCAT('${REVIEW_SOURCE_REF_PREFIX}', job.id) AND conclusion.status IN ('queued','running') AND conclusion.feature_generation = job.feature_generation LIMIT 1) AS review_conclusion_job_id FROM ai_agent_jobs job LEFT JOIN ai_chats chat ON chat.id = job.chat_id AND chat.created_by = job.user_id LEFT JOIN ai_messages reply ON reply.id = job.result_message_id AND reply.chat_id = chat.id WHERE job.id = ? AND job.user_id = ? LIMIT 1`, [req.params.id, req.agentAccount.id]); if (!job) return res.status(404).json({ error: "job not found" }); return res.json({ ok: true, job }); } catch (error) { return sendAgentError(res, error); } }); router.post("/jobs/:id/cancel", cancelLimiter, authorize, async (req, res) => { try { if (!isValidServerAgentChatCursor(req.params.id)) return res.status(400).json({ error: "invalid job id" }); const id = req.params.id; const userId = req.agentAccount.id; await ensureAiChatTablesReady(); const [job] = await db.query("SELECT claim_token FROM ai_agent_jobs WHERE id = ? AND user_id = ? LIMIT 1", [id, userId]); if (!job) return res.status(404).json({ error: "job not found" }); const cancelled = await cancelOwnedAgentJob(db, userId, id); if (cancelled && job.claim_token) { try { void worker.request("cancel", { id, token: job.claim_token }, AbortSignal.timeout(500)).catch(() => {}); } catch { } } return res.json({ ok: true, cancelled }); } catch (error) { return sendAgentError(res, error); } }); if (review) { router.get("/jobs/:id/review", statusLimiter, authorize, async (req, res) => { try { if (!isValidServerAgentChatCursor(req.params.id) || typeof req.query.server !== "string") { throw new AgentRpcError(400, "agent_review_invalid"); } return res.json(await review.preview(req, req.params.id, req.query.server)); } catch (error) { return sendAgentError(res, error); } }); router.post("/jobs/:id/review", reviewLimiter, authorize, async (req, res) => { try { if (!isValidServerAgentChatCursor(req.params.id)) throw new AgentRpcError(400, "agent_review_invalid"); const result = await review.submit(req, res, req.params.id, getRequestIp(req)); if (result) return res.json(result); } catch (error) { return sendAgentError(res, error); } }); } return router; } module.exports = { createAgentLiveRouter, sendAgentError };