"use strict"; const { createHash } = require("node:crypto"); const { createServerAgentChat, isValidServerAgentChatCursor } = require("../services/server-agent-chat-ownership"); const { assertServerAgentQueueCapacity } = require("../services/server-agent-queue"); const { lockAgentQueueState, agentOccurrencePredatesEnable, transact } = require("./queue-state"); const { AgentRpcError } = require("./private-rpc"); const { ATTACHMENT_RETENTION_DAYS } = require("./attachments"); const { REVIEW_SOURCE_REF_PREFIX, reviewFollowUpStates, canAutoApproveAgentFileEdits } = require("./action-proposal"); const MAX_LIVE_PROMPT_BYTES = 32_000; const MAX_LIVE_IMAGE_BYTES = 2 * 1024 * 1024; const LIVE_JSON_LIMIT = MAX_LIVE_IMAGE_BYTES + 256 * 1024; const LIVE_SOURCE = "live_chat"; const LIVE_ACCESS_MODES = new Set(["general", "read_only", "file_plan"]); const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i; function agentReviewParentId(row) { if (row.source !== LIVE_SOURCE || row.submission_message_id != null || typeof row.source_ref !== "string" || !row.source_ref.startsWith(REVIEW_SOURCE_REF_PREFIX)) return null; const id = row.source_ref.slice(REVIEW_SOURCE_REF_PREFIX.length); return isValidServerAgentChatCursor(id) ? id : null; } function createAgentSubmissionParser({ parser, authenticate, hasAgentAccess, anonymousLimiter, accountLimiter, maxActive = 12 }) { let active = 0; return async (req, res, next) => { try { if (!req.session?.user) { return anonymousLimiter(req, res, (error) => error ? next(error) : res.status(401).json({ error: "not authenticated" })); } if (!(await authenticate(req))) return res.status(401).json({ error: "not authenticated" }); if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); return accountLimiter(req, res, (error) => { if (error) return next(error); if (active >= maxActive) { return res.set("Retry-After", "1").status(503).json({ error: "Agent submission is busy. Try again shortly.", code: "agent_unavailable" }); } active += 1; const deadline = setTimeout(() => req.destroy(), 10_000); const release = () => { clearTimeout(deadline); active -= 1; res.off("close", release); }; res.once("close", release); parser(req, res, (parseError) => { if (!res.destroyed) release(); if (parseError?.status === 413) return res.status(413).json({ error: "Agent submission is too large.", code: "agent_invalid_image" }); return next(parseError); }); }); } catch (error) { return next(error); } }; } function parseLiveAgentSubmission(body) { if (!body || !UUID_PATTERN.test(typeof body.requestKey === "string" ? body.requestKey : "")) { throw new AgentRpcError(409, "agent_client_refresh_required"); } const chatId = body.chatId == null ? null : String(body.chatId); if (chatId !== null && !isValidServerAgentChatCursor(chatId)) throw new AgentRpcError(400, "agent_invalid_chat"); if (typeof body.server !== "string" || !body.server.trim() || body.server.length > 120) { throw new AgentRpcError(400, "agent_invalid_server"); } const prompt = typeof body.prompt === "string" ? body.prompt.trim() : ""; if (!prompt || Buffer.byteLength(prompt) > MAX_LIVE_PROMPT_BYTES) { throw new AgentRpcError(400, "agent_invalid_prompt"); } const image = body.image == null ? null : body.image; if (image !== null && (typeof image !== "string" || image.length > MAX_LIVE_IMAGE_BYTES || !/^data:image\/(?:png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(image))) { throw new AgentRpcError(400, "agent_invalid_image"); } const accessMode = body.accessMode === undefined ? "general" : body.accessMode; if (!LIVE_ACCESS_MODES.has(accessMode)) throw new AgentRpcError(400, "agent_invalid_access_mode"); return { requestKey: body.requestKey.toLowerCase(), chatId, prompt, image, server: body.server.trim(), accessMode }; } function submissionHash({ live, serverName, serverId, provider, model, prompt }) { const parts = [live.chatId, serverName, serverId, provider, model, prompt, live.image]; if (live.accessMode && live.accessMode !== "general") parts.push(live.accessMode); return createHash("sha256").update(JSON.stringify(parts)).digest("hex"); } function agentScheduleRef(taskId, repeatKey) { const identity = repeatKey || taskId; if (identity == null || identity === "") return null; return createHash("sha256").update(JSON.stringify([repeatKey ? "repeat" : "once", String(identity)])).digest("hex"); } async function storeAgentSubmission(db, submission, connection = null) { const { user, serverName, serverId, prompt, provider, model, modelLabel, source, sourceRef, title, envelope, live, generation, occurrence, maxPending, maxPendingPerAccount, reviewParent, } = submission; if (reviewParent && (source !== LIVE_SOURCE || live || !isValidServerAgentChatCursor(String(reviewParent.id)))) { throw new AgentRpcError(400, "agent_review_invalid"); } const requestHash = live ? submissionHash(submission) : null; const scheduleRef = occurrence ? agentScheduleRef(occurrence.id, occurrence.repeatJobKey || occurrence.opts?.repeat?.key) : null; const occurrenceRef = occurrence ? agentScheduleRef(occurrence.id) : null; const consent = occurrence ? !!scheduleRef && occurrence.data?.autoApproveFileEdits === true && String(occurrence.data.userId) === String(user.id) && String(occurrence.data.serverId) === String(serverId) : source === "planner_send" && submission.autoApproveFileEdits === true; const automaticFileEdits = !live && !reviewParent && canAutoApproveAgentFileEdits({ source, server_id: serverId, account_epoch: user.session_epoch, read_only: false, auto_approve_file_edits: consent, }); const write = async (tx) => { // adpanel:agent-admission-lock - the state row lock spans the caller's commit, including Planner's outer transaction. const state = await lockAgentQueueState(tx); if (occurrence) { if (!scheduleRef || !occurrenceRef || agentOccurrencePredatesEnable(occurrence, state)) { throw new AgentRpcError(409, "agent_occurrence_skipped"); } const [receipts] = await tx.execute(`SELECT occurrence_ref, CAST(job_id AS CHAR) AS job_id, CAST(chat_id AS CHAR) AS chat_id FROM ai_agent_schedule_receipts WHERE schedule_ref = ? AND occurrence_ref IN ('', ?) FOR UPDATE`, [scheduleRef, occurrenceRef]); if (receipts.some((receipt) => receipt.occurrence_ref === "")) throw new AgentRpcError(409, "agent_occurrence_skipped"); if (receipts.length) { const [receipt] = receipts; return { jobId: receipt.job_id, chatId: receipt.chat_id, skipped: true, reason: "agent_occurrence_already_admitted" }; } } else if (!state.enabled || state.generation !== generation) { throw new AgentRpcError(503, "agent_unavailable"); } if (live) { const [[existing]] = await tx.execute(`SELECT id, chat_id, status, request_hash FROM ai_agent_jobs WHERE user_id = ? AND request_key = ? FOR UPDATE`, [user.id, live.requestKey]); if (existing) { if (existing.request_hash !== requestHash) throw new AgentRpcError(409, "agent_request_conflict"); return { chatId: existing.chat_id, jobId: existing.id, status: existing.status, provider, model }; } } await assertServerAgentQueueCapacity(tx, { accountId: user.id, maxPending, maxPendingPerAccount, source }); let chatId = live?.chatId ?? reviewParent?.chat_id; if (chatId) { const [[chat]] = await tx.execute("SELECT id FROM ai_chats WHERE id = ? AND created_by = ? FOR UPDATE", [chatId, user.id]); if (!chat) throw new AgentRpcError(404, "agent_chat_not_found"); const [[active]] = await tx.execute(`SELECT id FROM ai_agent_jobs WHERE chat_id = ? AND status IN ('queued','running') LIMIT 1 FOR UPDATE`, [chatId]); if (active) throw new AgentRpcError(409, "agent_chat_busy"); if (reviewParent) { const [[parent]] = await tx.execute(`SELECT id FROM ai_agent_jobs WHERE id = ? AND chat_id = ? AND user_id = ? AND source = ? AND status = 'completed' AND feature_generation = ? AND result_message_id IS NOT NULL AND action_review_state IN ${reviewFollowUpStates} FOR UPDATE`, [reviewParent.id, chatId, user.id, LIVE_SOURCE, state.generation]); if (!parent) throw new AgentRpcError(409, "agent_review_not_found"); const [[superseding]] = await tx.execute(`SELECT id FROM ai_agent_jobs WHERE chat_id = ? AND user_id = ? AND source = ? AND id > ? AND submission_message_id IS NOT NULL LIMIT 1 FOR UPDATE`, [chatId, user.id, LIVE_SOURCE, parent.id]); if (superseding) throw new AgentRpcError(409, "agent_review_not_found"); const [[alreadyQueued]] = await tx.execute(`SELECT id FROM ai_agent_jobs WHERE chat_id = ? AND user_id = ? AND source = ? AND source_ref = ? LIMIT 1 FOR UPDATE`, [chatId, user.id, LIVE_SOURCE, `${REVIEW_SOURCE_REF_PREFIX}${reviewParent.id}`]); if (alreadyQueued) return { chatId, jobId: alreadyQueued.id }; } } else { chatId = await createServerAgentChat(db, user, title, tx); } const image = live?.image || null; let submissionMessageId = null; if (!reviewParent) { const [message] = await tx.execute(`INSERT INTO ai_messages (chat_id, role, content, image_data, model, image_expires_at) VALUES (?, 'user', ?, ?, ?, IF(?, DATE_ADD(NOW(3), INTERVAL ${ATTACHMENT_RETENTION_DAYS} DAY), NULL))`, [chatId, prompt, image, modelLabel, Boolean(image)]); submissionMessageId = message.insertId; } const [job] = await tx.execute(`INSERT INTO ai_agent_jobs (chat_id, user_id, user_email, server_name, server_id, provider, model, prompt, status, source, source_ref, perm_file_envelope, feature_generation, request_key, request_hash, submission_message_id, account_epoch, read_only, auto_approve_file_edits, schedule_ref, auto_file_edit_generation) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ chatId, user.id, String(user.email || "").trim().toLowerCase(), serverName, serverId, provider, model, live ? "" : prompt, source, reviewParent ? `${REVIEW_SOURCE_REF_PREFIX}${reviewParent.id}` : sourceRef, envelope, automaticFileEdits ? null : state.generation, live?.requestKey || null, requestHash, submissionMessageId, user.session_epoch ?? null, live?.accessMode === "read_only", automaticFileEdits, scheduleRef, automaticFileEdits ? state.generation : null, ]); if (occurrence) await tx.execute(`INSERT INTO ai_agent_schedule_receipts (schedule_ref, occurrence_ref, job_id, chat_id) VALUES (?, ?, ?, ?)`, [scheduleRef, occurrenceRef, job.insertId, chatId]); await tx.execute("UPDATE ai_chats SET updated_at = NOW() WHERE id = ?", [chatId]); return { chatId, jobId: job.insertId, status: "queued", provider, model }; }; return connection ? write(connection) : transact(db.pool, write); } module.exports = { LIVE_SOURCE, LIVE_JSON_LIMIT, UUID_PATTERN, agentReviewParentId, createAgentSubmissionParser, parseLiveAgentSubmission, agentScheduleRef, storeAgentSubmission };