"use strict"; const { randomUUID } = require("node:crypto"); const { AUTOMATIC_EDIT_STOP_ERROR_SQL, LEGACY_AUTOMATIC_EDIT_QUARANTINE_SQL, lockAgentQueueState, transact } = require("./queue-state"); const { AgentRpcError } = require("./private-rpc"); const { readableImageSql } = require("./attachments"); const { safeTruncateUtf16 } = require("../utils/safe-truncate"); const { LIVE_SOURCE, agentReviewParentId, storeAgentSubmission } = require("./admission"); const { hashAgentFile } = require("./file-edit"); const { AGENT_JOB_GENERATION_SQL } = require("../services/server-agent-queue"); const { isValidServerAgentChatCursor } = require("../services/server-agent-chat-ownership"); const { parseAgentReview, serializeAgentReview, remainingAgentReviewSteps, splitAgentReview, projectAgentFileActivity, reviewFollowUpStates, MAX_AGENT_REVIEW_ACTIONS, canAutoApproveAgentFileEdits } = require("./action-proposal"); const CONTEXT_MESSAGES = 18; const CONTEXT_BYTES = 3 * 1024 * 1024; const CONTEXT_ACTIVITY_BYTES = 128 * 1024; const RESULT_CHARS = 32_000; const isPlannerJob = ({ source }) => source === "planner_send" || source === "scheduler_planner_next"; async function holdPlannerEdit(db, row) { if (!isPlannerJob(row)) return true; if (!isValidServerAgentChatCursor(row.source_ref)) return false; // adpanel:agent-edit-hold - preserve the hold even if this worker dies or the job is pruned. const result = await db.query(`UPDATE server_planner_items item JOIN ai_agent_jobs job ON job.id = ? SET item.agent_edit_hold_job_id = job.id, item.updated_at = item.updated_at WHERE item.id = ? AND item.server_name = job.server_name AND item.is_done = 0 AND job.status = 'running' AND job.claim_token = ? AND (item.agent_edit_hold_job_id IS NULL OR item.agent_edit_hold_job_id = job.id)`, [row.id, row.source_ref, row.claim_token]); return Number(result.affectedRows) === 1; } async function claimAgentJob(db, id, generation) { return transact(db.pool, async (connection) => { const state = await lockAgentQueueState(connection); if (!state.enabled || state.generation !== generation) return null; const [active] = await connection.execute(`SELECT running.id FROM ai_agent_jobs candidate JOIN ai_agent_jobs running ON running.user_id = candidate.user_id AND running.status = 'running' WHERE candidate.id = ? LIMIT 2 FOR UPDATE`, [id]); if (active.length >= 2) return null; const token = randomUUID(); const [claim] = await connection.execute(`UPDATE ai_agent_jobs SET status = 'running', started_at = NOW(), error = NULL, claim_token = ?, feature_generation = ? WHERE id = ? AND status = 'queued' AND ${AGENT_JOB_GENERATION_SQL}`, [token, generation, id, generation, generation]); if (!claim.affectedRows) return null; const [[row]] = await connection.execute("SELECT * FROM ai_agent_jobs WHERE id = ? AND claim_token = ?", [id, token]); return row; }); } async function findAgentClaim(db, { id, token, generation }, completed = false) { const [row] = await db.query(`SELECT job.* FROM ai_agent_jobs job JOIN ai_agent_worker_state state ON state.id = 1 WHERE job.id = ? AND job.claim_token = ? AND job.feature_generation = ? AND state.generation = job.feature_generation AND state.enabled = TRUE AND job.status = ? LIMIT 1`, [id, token, generation, completed ? "completed" : "running"]); if (!row) throw new AgentRpcError(409, "agent_claim_inactive"); return row; } async function readAgentRunTranscript(db, row, { includeFileActivity = false } = {}) { // adpanel:agent-context-recovery - keep failed prompts in chat history without replaying them to the provider. const window = await db.query(`SELECT CAST(message.id AS CHAR) AS id, OCTET_LENGTH(message.content) + COALESCE(OCTET_LENGTH(${readableImageSql}), 0) AS bytes FROM ai_messages message JOIN ai_chats chat ON chat.id = message.chat_id WHERE chat.id = ? AND chat.created_by = ? AND message.id <= ? AND message.role IN ('user','assistant') AND NOT EXISTS (SELECT 1 FROM ai_agent_jobs previous WHERE previous.chat_id = chat.id AND previous.user_id = chat.created_by AND previous.submission_message_id = message.id AND previous.status IN ('failed','cancelled')) ORDER BY message.id DESC LIMIT ${CONTEXT_MESSAGES}`, [row.chat_id, row.user_id, row.submission_message_id]); if (String(window[0]?.id) !== String(row.submission_message_id)) throw new AgentRpcError(409, "agent_transcript_changed"); let bytes = 0; const ids = []; for (const entry of window) { bytes += Number(entry.bytes); if (bytes > CONTEXT_BYTES) break; ids.push(entry.id); } if (!ids.length) throw new AgentRpcError(409, "agent_transcript_changed"); const activityScope = includeFileActivity && row.source === LIVE_SOURCE && row.server_id != null && row.account_epoch != null; // adpanel:agent-file-activity - bind prior outcomes to the existing server and account generation; never pass raw activity to the provider. const activity = activityScope ? `, CASE WHEN message.role = 'assistant' AND OCTET_LENGTH(message.agent_actions) <= ${CONTEXT_ACTIVITY_BYTES} AND EXISTS (SELECT 1 FROM ai_agent_jobs review WHERE review.chat_id = chat.id AND review.user_id = chat.created_by AND review.result_message_id = message.id AND review.source = ? AND review.server_id = CAST(? AS UNSIGNED) AND review.server_name = ? AND review.account_epoch = CAST(? AS UNSIGNED) AND review.status = 'completed' AND review.action_review_state IS NOT NULL) THEN message.agent_actions END AS file_activity` : ""; const messages = await db.query(`SELECT message.role, message.content, ${readableImageSql} AS image${activity} FROM ai_messages message JOIN ai_chats chat ON chat.id = message.chat_id WHERE chat.id = ? AND chat.created_by = ? AND message.id IN (${ids.map(() => "?").join(",")}) ORDER BY message.id`, [...(activityScope ? [LIVE_SOURCE, row.server_id, row.server_name, row.account_epoch] : []), row.chat_id, row.user_id, ...ids]); return activityScope ? messages.map(({ file_activity, ...message }) => ({ ...message, ...(file_activity ? { fileActions: projectAgentFileActivity(file_activity) } : {}), })) : messages; } async function readAgentReviewContinuation(db, row, parentId, outcome) { const receipts = []; let remainingActions = []; let fileTasks; let planComplete; for (let step = 0; parentId && step < MAX_AGENT_REVIEW_ACTIONS; step += 1) { const [parent] = await db.query(`SELECT parent.source, parent.source_ref, parent.submission_message_id, parent.action_review_state, parent.action_proposal, parent.review_file_plan, parent.prompt FROM ai_agent_jobs parent JOIN ai_chats chat ON chat.id = parent.chat_id AND chat.created_by = parent.user_id WHERE parent.id = ? AND parent.chat_id = ? AND parent.user_id = ? AND parent.source = ? AND parent.status = 'completed' AND parent.action_review_state IN ${reviewFollowUpStates} AND parent.server_id = ? AND parent.server_name = ? AND parent.account_epoch = ? AND parent.feature_generation = ? AND parent.result_message_id IS NOT NULL`, [parentId, row.chat_id, row.user_id, LIVE_SOURCE, row.server_id, row.server_name, row.account_epoch, row.feature_generation]); if (!parent) throw new AgentRpcError(409, "agent_review_not_found"); if (step === 0) { const saved = parseAgentReview(parent.action_proposal); const review = splitAgentReview(saved?.actions || [], parent.review_file_plan, saved?.resumeModel); remainingActions = remainingAgentReviewSteps(review.remainingActions, parent.action_review_state, { resumeModel: saved?.resumeModel, outcome }); fileTasks = saved?.fileTasks; planComplete = saved?.planComplete; } if (parent.submission_message_id != null) return { submissionMessageId: parent.submission_message_id, receipts: receipts.reverse(), remainingActions, fileTasks, planComplete, reviewCount: step + 1, }; const previous = JSON.parse(parent.prompt); if (previous.facts?.evidence) receipts.push(previous.facts); parentId = agentReviewParentId(parent); } throw new AgentRpcError(409, "agent_review_not_found"); } async function replaceAgentReply(connection, chatId, messageId, text, activity) { const appendActivity = activity?.length ? ", agent_actions = JSON_MERGE_PRESERVE(COALESCE(agent_actions, JSON_ARRAY()), ?)" : ""; const [update] = await connection.execute(`UPDATE ai_messages SET content = ?, thinking_time_ms = NULL, thinking_content = NULL${appendActivity} WHERE id = ? AND chat_id = ? AND role = 'assistant'`, [safeTruncateUtf16(text, RESULT_CHARS), ...(appendActivity ? [JSON.stringify(activity)] : []), messageId, chatId]); return Number(update.affectedRows) === 1; } async function readRevertableAgentEdit(db, row, path) { const key = `$."${hashAgentFile(path)}"`; const [entry] = await db.query(`SELECT CAST(id AS CHAR) AS edit_id, action_proposal, action_edit_result, CAST(JSON_EXTRACT(action_file_edits, ?) AS CHAR) AS file_edit FROM ai_agent_jobs WHERE chat_id = ? AND user_id = ? AND server_name = ? AND server_id = ? AND account_epoch = ? AND source = ? AND id < ? AND status = 'completed' AND action_proposal IS NOT NULL AND (JSON_CONTAINS_PATH(action_file_edits, 'one', ?) = 1 OR ( action_review_state = 'applied' AND JSON_VALID(action_proposal) AND JSON_UNQUOTE(JSON_EXTRACT(action_proposal, '$.action')) = 'write_file' AND BINARY JSON_UNQUOTE(JSON_EXTRACT(action_proposal, '$.path')) = BINARY ?)) ORDER BY id DESC LIMIT 1`, [key, row.chat_id, row.user_id, row.server_name, row.server_id, row.account_epoch, LIVE_SOURCE, row.id, key, path]); if (!entry?.file_edit && !entry?.action_edit_result) return null; try { const snapshot = JSON.parse(entry.file_edit || entry.action_edit_result); const proposal = parseAgentReview(entry.action_proposal)?.actions[entry.file_edit ? snapshot.index : 0]; if (proposal?.path !== path) return null; const edit = proposal.action === "write_file" ? proposal : proposal.action === "replace_file" && typeof snapshot.originalText === "string" ? { oldText: snapshot.originalText, newText: proposal.content } : null; return edit ? { id: entry.edit_id, edit, snapshot } : null; } catch { return null; } } async function settleAgentReview(db, row, state, receipt, conclusion, edits, activity) { const save = (queue) => transact(db.pool, async (connection) => { if (queue) await lockAgentQueueState(connection); const [[chat]] = await connection.execute("SELECT id FROM ai_chats WHERE id = ? AND created_by = ? FOR UPDATE", [row.chat_id, row.user_id]); if (!chat) return null; const [claimed] = await connection.execute(`UPDATE ai_agent_jobs SET action_review_state = ?, action_file_edits = ? WHERE id = ? AND user_id = ? AND status = 'completed' AND action_review_state = 'applying'`, [state, Object.keys(edits).length ? JSON.stringify(edits) : null, row.id, row.user_id]); if (Number(claimed.affectedRows) !== 1) return null; const content = queue ? receipt : conclusion?.fallbackReceipt || receipt; if (!(await replaceAgentReply(connection, row.chat_id, row.result_message_id, content, activity))) throw new AgentRpcError(409, "agent_review_not_found"); if (queue) { const job = await storeAgentSubmission(db, conclusion, connection); return { conclusionJobId: String(job.jobId) }; } await connection.execute("UPDATE ai_chats SET updated_at = NOW() WHERE id = ?", [row.chat_id]); return {}; }); if (conclusion) { try { return await save(true); } catch { console.warn(`[Agent] Could not queue a conclusion for reviewed job ${row.id}; saving the receipt alone.`); } } return save(false); } async function publishAgentResult(db, row, result, modelLabel, signal) { const incomplete = result.automaticEditFailed === true && canAutoApproveAgentFileEdits(row); const holdItem = incomplete && isPlannerJob(row) && isValidServerAgentChatCursor(row.source_ref); return transact(db.pool, async (connection) => { // adpanel:planner-lock-order - Scheduler admission takes the Planner item before the queue state. if (holdItem) await connection.execute(`SELECT id FROM server_planner_items WHERE id = ? AND server_name = ? FOR UPDATE`, [row.source_ref, row.server_name]); const state = await lockAgentQueueState(connection); if (!state.enabled || state.generation !== String(row.feature_generation)) return false; signal.throwIfAborted(); const [[chat]] = await connection.execute("SELECT id FROM ai_chats WHERE id = ? AND created_by = ? FOR UPDATE", [row.chat_id, row.user_id]); if (!chat) return false; if (holdItem) await holdPlannerEdit({ query: async (...args) => (await connection.execute(...args))[0] }, row); const [owned] = await connection.execute(`UPDATE ai_agent_jobs job SET status = ${incomplete ? "'failed'" : "'completed'"}, completed_at = NOW(), error = ${incomplete ? "'agent_automatic_edits_incomplete'" : "NULL"} WHERE job.id = ? AND job.status = 'running' AND job.claim_token = ? AND job.feature_generation = ? AND EXISTS (SELECT 1 FROM users account WHERE account.id = job.user_id AND account.suspended = FALSE AND (account.admin = TRUE OR account.agent_access = TRUE) AND (job.account_epoch IS NULL OR account.session_epoch = job.account_epoch))`, [row.id, row.claim_token, state.generation]); if (!owned.affectedRows) return false; const parentId = agentReviewParentId(row); // adpanel:agent-access-mode - browser preferences may suppress proposals, never authorize execution. const proposal = row.source === LIVE_SOURCE && Number(row.read_only) !== 1 && row.server_id != null && result.actionProposal ? serializeAgentReview(result.actionProposal, result.remainingActions, result.resumeModel, result.fileTasks, result.planComplete) : null; if (parentId) { const [[parent]] = await connection.execute(`SELECT result_message_id FROM ai_agent_jobs WHERE id = ? AND chat_id = ? AND user_id = ? AND source = ? AND status = 'completed' AND action_review_state IN ${reviewFollowUpStates} AND server_id = ? AND feature_generation = ? FOR UPDATE`, [parentId, row.chat_id, row.user_id, LIVE_SOURCE, row.server_id, state.generation]); if (!parent?.result_message_id || !(await replaceAgentReply(connection, row.chat_id, parent.result_message_id, result.content))) { throw new AgentRpcError(409, "agent_review_not_found"); } await connection.execute("UPDATE ai_agent_jobs SET result_message_id = ?, action_proposal = ? WHERE id = ?", [parent.result_message_id, proposal, row.id]); await connection.execute("UPDATE ai_chats SET updated_at = NOW() WHERE id = ?", [row.chat_id]); signal.throwIfAborted(); return true; } const [message] = await connection.execute(`INSERT INTO ai_messages (chat_id, role, content, thinking_time_ms, thinking_content, model) VALUES (?, 'assistant', ?, ?, ?, ?)`, [ row.chat_id, safeTruncateUtf16(result.content || "Done.", RESULT_CHARS), Math.min(4_294_967_295, Math.max(0, Math.trunc(Number(result.thinking_time_ms) || 0))), safeTruncateUtf16(result.thinking_content || "", RESULT_CHARS) || null, modelLabel, ]); await connection.execute("UPDATE ai_agent_jobs SET result_message_id = ?, action_proposal = ? WHERE id = ?", [message.insertId, proposal, row.id]); if (row.source === LIVE_SOURCE && result.chatTitle) { const { title, previousTitle } = result.chatTitle; await connection.execute(`UPDATE ai_chats SET title = CASE WHEN BINARY title = BINARY ? THEN ? ELSE title END, updated_at = NOW() WHERE id = ? AND created_by = ?`, [previousTitle, title, row.chat_id, row.user_id]); } else { await connection.execute("UPDATE ai_chats SET updated_at = NOW() WHERE id = ?", [row.chat_id]); } signal.throwIfAborted(); return true; }); } async function failAgentClaim(db, row, reason) { return db.query(`UPDATE ai_agent_jobs SET status = 'failed', completed_at = NOW(), error = CASE ${AUTOMATIC_EDIT_STOP_ERROR_SQL} ELSE ? END WHERE id = ? AND status = 'running' AND claim_token = ? AND feature_generation = ?`, [reason, row.id, row.claim_token, row.feature_generation]); } async function recoverInterruptedAgentJobs(db, staleAfterSeconds = null) { // adpanel:agent-no-billable-replay - a lost worker may already have sent the upstream request. const scope = staleAfterSeconds === null ? "" : " AND started_at < DATE_SUB(NOW(), INTERVAL ? SECOND)"; await db.query(`UPDATE ai_agent_jobs SET status = 'failed', completed_at = NOW(), error = CASE ${AUTOMATIC_EDIT_STOP_ERROR_SQL} ELSE 'agent_interrupted' END WHERE status = 'running'${scope}`, staleAfterSeconds === null ? [] : [staleAfterSeconds]); await db.query(LEGACY_AUTOMATIC_EDIT_QUARANTINE_SQL); } async function cancelOwnedAgentJob(db, userId, jobId) { const update = await db.query(`UPDATE ai_agent_jobs SET status = 'cancelled', completed_at = NOW(), error = CASE ${AUTOMATIC_EDIT_STOP_ERROR_SQL} ELSE 'agent_cancelled' END WHERE id = ? AND user_id = ? AND status IN ('queued','running')`, [jobId, userId]); return Number(update.affectedRows) > 0; } module.exports = { claimAgentJob, findAgentClaim, readAgentRunTranscript, readAgentReviewContinuation, readRevertableAgentEdit, settleAgentReview, holdPlannerEdit, publishAgentResult, failAgentClaim, recoverInterruptedAgentJobs, cancelOwnedAgentJob };