"use strict"; const { createAgentConversation } = require("./conversation"); const { generateFirstAgentChatTitle } = require("./chat-title"); const { parseAiAgentFileOperations } = require("../services/server-agent-file-directives"); const { AgentRpcError } = require("./private-rpc"); const { withProviderBudget, RUN_TIMEOUT_MS } = require("./budgets"); const { claimAgentJob, readAgentRunTranscript, readAgentReviewContinuation, publishAgentResult, failAgentClaim } = require("./job-store"); const { LIVE_SOURCE, agentReviewParentId } = require("./admission"); const { describeAgentReview, renderAgentReviewSummary } = require("./review-conclusion"); const { AGENT_ACTION_TOOL, AGENT_FILE_TOOLS, AGENT_ACTION_READY_MESSAGE, buildAgentActionOffer, MAX_AGENT_REVIEW_ACTIONS, normalizeAgentAction, normalizeAgentFileTasks, pendingAgentFileTasks, serializeAgentReview, hasAgentActionPermissions, getAgentCreationConflict, isAgentFilePlan, canAutoApproveAgentFileEdits, isAutomaticAgentFileEdit, MAX_AGENT_AUTOMATIC_FILE_EDITS } = require("./action-proposal"); const { AiProviderError } = require("../services/server-agent-provider-http"); const { AiAgentJobDeadlineExceeded } = require("./run-deadline"); const AUTOMATIC_EDIT_PREFLIGHT_REFUSALS = new Set([ "agent_authority_revoked", "agent_claim_inactive", "agent_automatic_file_edit_denied", "agent_automatic_file_edit_invalid", ]); function buildBackgroundAiAgentMessages({ prompt, perms }) { return [ { role: "system", content: perms?.files_read ? "If the user explicitly asks to list or read server files, reply with FILE_LIST: or FILE_READ: on its own line. Use . for the root. Do not issue file changes." : "You cannot list or read server files for this user.", }, { role: "user", content: String(prompt || "") }, ]; } function providerFailureCode(error) { if (error.failureCode) return error.failureCode; if (error.status === 401 || error.status === 403) return "agent_provider_auth"; if (error.status === 402) return "agent_provider_account"; if (error.status === 404 || error.status === 405) return "agent_provider_model_unavailable"; if (error.status === 429) return "agent_provider_busy"; if (error.status >= 500) return "agent_provider_unavailable"; return "agent_provider_rejected"; } function createAgentJobRunner({ db, generation, active, callPanel, getProviderSettings, formatModelLabel, assertDeadline, stopping, logger = console }) { return async function processAiAgentJob(jobId) { if (stopping()) return; const row = await claimAgentJob(db, jobId, generation); if (!row) return; const deadline = Date.now() + RUN_TIMEOUT_MS; const controller = new AbortController(); const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(RUN_TIMEOUT_MS)]); const claim = { id: String(row.id), token: row.claim_token, generation }; const lane = row.source === LIVE_SOURCE ? "live" : "background"; const call = (operation, args = {}) => callPanel(operation, { ...args, claim }, signal); active.set(String(row.id), { token: row.claim_token, controller }); let stage = "context"; try { if (stopping()) controller.abort(); signal.throwIfAborted(); const context = await call("context"); const parentId = agentReviewParentId(row); let resume; if (parentId) { stage = "review continuation"; const envelope = JSON.parse(row.prompt); const facts = envelope.facts || envelope; const { submissionMessageId, receipts, remainingActions, fileTasks, planComplete, reviewCount } = await readAgentReviewContinuation(db, row, parentId, facts); const outcomes = [...receipts, facts]; const pending = fileTasks && pendingAgentFileTasks(fileTasks, outcomes); const [next, ...remaining] = remainingActions; const allowedNext = next && context.reviewActions && hasAgentActionPermissions(next, context.permissions); const finishedPlan = planComplete === true && !next && !pending?.length; if (envelope.resumeModel === true && !finishedPlan && (!allowedNext || reviewCount >= MAX_AGENT_REVIEW_ACTIONS)) { resume = { submissionMessageId, receipt: envelope.receipt, facts: outcomes, fileTasks, pending, reviewCount }; } else { await call("verify"); let result; if (next) { if (!allowedNext) { result = { content: renderAgentReviewSummary({ outcomes, note: "The next step is no longer permitted. No additional change was sent.", skipped: remainingActions.length }) }; } else { result = { content: `${envelope.receipt} Next step: ${next.action.replaceAll("_", " ")}.`, actionProposal: next, remainingActions: remaining, ...(envelope.resumeModel === true && { resumeModel: true, fileTasks, planComplete }) }; } } else { result = { content: renderAgentReviewSummary({ outcomes, complete: finishedPlan, skipped: envelope.resumeModel === true ? 0 : facts.skippedSteps }) }; } await call("verify"); if (!(await publishAgentResult(db, row, result, formatModelLabel(row.provider, row.model), signal))) { throw new AgentRpcError(409, "agent_claim_inactive"); } return; } } stage = "provider configuration"; const provider = getProviderSettings(row.provider, row.model); const req = { aiAgentChatSignal: signal, aiAgentJobDeadlineMs: deadline, aiAgentPermClamp: context.clamped }; // adpanel:agent-action-review - preserve the live Agent's proposal tools across provider changes. Only the panel can apply them. const readOnly = Number(row.read_only) === 1; const reviewAvailable = lane === "live" && row.server_id != null && context.reviewActions; const automaticConsent = canAutoApproveAgentFileEdits(row); const automatic = context.automaticFileEdits === true && automaticConsent; const requiresConfirmedEdit = automaticConsent && context.clamped; const limitReached = resume?.reviewCount >= MAX_AGENT_REVIEW_ACTIONS; const fileTools = (reviewAvailable || automatic) && context.permissions?.files_read ? AGENT_FILE_TOOLS : []; const actionOffer = (reviewAvailable || automatic) && !readOnly && !limitReached ? buildAgentActionOffer(context.permissions, { automatic }) : null; const actionRestriction = readOnly ? "Read only mode does not allow change proposals. Switch to General access to request a review if your server permissions allow it." : limitReached ? "This turn reached its action limit. Summarize the confirmed results and any unfinished work." : lane !== "live" ? "Only live chats can prepare actions for review." : !reviewAvailable ? "This server does not support reviewed changes in the Agent. Use the server controls to make changes." : "Your current server permissions do not allow any reviewed changes."; req.agentExtraTools = actionOffer ? [actionOffer.tool, ...fileTools] : fileTools; req.agentAutomaticFileEdits = automatic && !!actionOffer; if (actionOffer) req.agentActionInstructions = actionOffer.instructions; else if (automaticConsent) req.agentActionInstructions = "No automatic edits are available for this run. Do not claim a file was changed."; else if (lane === "live") { req.agentActionInstructions = `Use available diagnostics. Do not propose, attempt, or claim a server change. If asked to make a change, explain: ${actionRestriction}`; } if (resume) { req.agentReviewEvidence = resume.facts.map(({ approvedNewLines, changeSummary, ...fact }) => fact); req.agentPendingFileTasks = resume.pending; } const fileReads = req.agentFileReads = new Map(); const editVersions = new Map(); const pendingEditReads = new Map(); if (automatic) req.acceptAgentEditReads = (results) => { const delivered = new Set(results.map(({ result }) => result)); for (const [path, { diagnostic, editVersion }] of pendingEditReads) { if (delivered.has(diagnostic)) editVersions.set(path, editVersion); } pendingEditReads.clear(); }; const automaticOutcomes = []; let automaticAttempts = 0; let automaticFailure = false; let uncertainEdit = false; let automaticDispatchStopped = false; const unreadEdits = new Set(); const completeAiChatConversation = createAgentConversation({ applyAiAgentPermClamp: async () => context.permissions, assertAiAgentJobDeadline: assertDeadline, getAccessibleServerEntriesForAi: async () => context.servers, getEffectivePermsForUserOnServer: async () => context.permissions, getLoggedInUser: async () => null, getRequestIp: () => "", isBackgroundAgentJobRequest: () => true, maybeExecuteDirectBotConsoleCommand: () => null, resolveAiAgentClampAuthorAccess: async (_req, name) => ({ authorHasAccess: context.visibleServers.includes(name) }), runBotAssistantTool: async ({ name, args, followingProposals = [], hasUnqueuedWork = false }) => { if (name !== AGENT_ACTION_TOOL.name) { const result = await call("tool", { name, args }); if (name === "read_server_file" && typeof args?.path === "string") { if (automatic) { const { editVersion, ...diagnostic } = result; editVersions.delete(args.path); pendingEditReads.delete(args.path); if (diagnostic.ok === true && editVersion) pendingEditReads.set(args.path, { diagnostic, editVersion }); return diagnostic; } fileReads.delete(args.path); fileReads.set(args.path, result); } return result; } if (!actionOffer) { if (automatic) automaticFailure = true; return { ok: false, error: automatic ? "This job lacks permission to read and edit server files." : actionRestriction }; } if (automatic) { const proposal = normalizeAgentAction(args); if (!isAutomaticAgentFileEdit(proposal)) { automaticFailure = true; return { ok: false, code: "agent_action_arguments", error: "Only targeted text edits are allowed for this job." }; } if (automaticDispatchStopped || uncertainEdit || automaticAttempts >= MAX_AGENT_AUTOMATIC_FILE_EDITS) { automaticFailure = true; return { ok: false, error: "No more automatic edits are allowed in this run." }; } const editVersion = editVersions.get(proposal.path); if (!editVersion) { unreadEdits.add(proposal.path); return { ok: false, code: "agent_action_arguments", error: "Read the complete text at this exact path before editing it." }; } // adpanel:agent-auto-edit - a read version authorizes one attempt; never reuse it or retry an uncertain RPC. editVersions.delete(proposal.path); let result; try { result = await call("autoFileEdit", { proposal, editVersion, attempt: ++automaticAttempts }); } catch (error) { signal.throwIfAborted(); if (error instanceof AgentRpcError && error.status < 500 && AUTOMATIC_EDIT_PREFLIGHT_REFUSALS.has(error.code)) { automaticDispatchStopped = true; result = { state: "refused", receipt: describeAgentReview(context.serverName, proposal, "refused", error.code) }; } } automaticOutcomes.push(result?.receipt?.facts ?? describeAgentReview(context.serverName, proposal, "unknown").facts); if (result?.state === "applied") { unreadEdits.delete(proposal.path); return { ok: true, result: result.receipt.text }; } automaticFailure = true; if (!result || result.state === "unknown") { uncertainEdit = true; return { ok: false, error: `The panel could not confirm the edit of ${proposal.path}. No further edits will be sent in this run.` }; } return { ok: false, error: result.receipt.text }; } const { fileTasks, planComplete, ...fields } = args || {}; const proposal = normalizeAgentAction(fields); if (!proposal) return { ok: false, code: "agent_action_arguments", error: args?.action === "write_file" ? "Use read_server_file, then supply path, oldText, and newText as described by the write_file instructions. If the operator requested a full replacement, use replace_file with path and nonempty content." : "Supply one supported action with its exact arguments." }; if (!hasAgentActionPermissions(proposal, context.permissions)) return { ok: false, error: `You do not have permission for ${proposal.action}.` }; const read = fileReads.get(proposal.path); if (proposal.action === "write_file" && read?.ok !== true) { return { ok: false, code: "agent_action_arguments", error: read?.error ? `${read.error} Do not guess the existing text. Continue independent work.` : "Read this exact path with read_server_file before proposing an edit. Do not guess the existing text." }; } const conflict = resume && getAgentCreationConflict(proposal, resume.facts); if (conflict) return conflict; const suppliedTasks = fileTasks === undefined ? undefined : normalizeAgentFileTasks(fileTasks); if (fileTasks !== undefined && (!suppliedTasks || suppliedTasks.some((task) => !hasAgentActionPermissions(task, context.permissions)))) { return { ok: false, code: "agent_action_arguments", error: "fileTasks may contain only unique permitted file actions with exact paths, without contents or approvals." }; } const queued = []; for (const draft of followingProposals) { const candidate = normalizeAgentAction(draft); if (!candidate || !isAgentFilePlan([proposal, ...queued, candidate]) || !hasAgentActionPermissions(candidate, context.permissions) || (candidate.action === "write_file" && fileReads.get(candidate.path)?.ok !== true) || (resume && getAgentCreationConflict(candidate, resume.facts)) || (resume?.reviewCount || 0) + queued.length + 2 > MAX_AGENT_REVIEW_ACTIONS) break; queued.push(candidate); } let checklist; if (resume?.fileTasks || suppliedTasks || queued.length) { const tasks = [...(resume?.fileTasks || []), ...(suppliedTasks || [])]; const uniqueTasks = new Map(tasks.map((task) => [`${task.action}:${task.path}`, task])); for (const { action, path } of [proposal, ...queued]) { if (!path) continue; const key = `${action}:${path}`; const observed = fileReads.get(path); if (action === "create_file" && !uniqueTasks.has(key) && observed?.ok === false && observed.code === "file_not_found") { uniqueTasks.delete(`write_file:${path}`); uniqueTasks.delete(`replace_file:${path}`); } uniqueTasks.set(key, { action, path }); } checklist = normalizeAgentFileTasks([...uniqueTasks.values()]); if (!checklist) return { ok: false, code: "agent_action_arguments", error: "The combined file checklist exceeds the supported task limit." }; } if (!serializeAgentReview(proposal, [], true, checklist)) { return { ok: false, code: "agent_action_arguments", error: "The proposed change is too large for one review. Prepare a smaller change." }; } req.agentReviewProposal = proposal; while (queued.length && !serializeAgentReview(proposal, queued, true, checklist)) queued.pop(); req.agentReviewRemainingActions = queued; req.agentReviewFileTasks = checklist; req.agentReviewPlanComplete = planComplete === true && !hasUnqueuedWork && queued.length === followingProposals.length && (!proposal.path || !!(suppliedTasks || resume?.fileTasks)) && pendingAgentFileTasks(checklist, resume?.facts).every(({ action, path }) => [proposal, ...queued].some((draft) => draft.action === action && draft.path === path)) && !!serializeAgentReview(proposal, queued, true, checklist, true); return { ok: true, pending_review: true }; }, sanitizeBotToolArgs: (_name, args) => args, }); const background = buildBackgroundAiAgentMessages({ prompt: row.prompt, perms: context.permissions }); stage = "transcript"; const transcriptRow = resume ? { ...row, submission_message_id: resume.submissionMessageId } : row; let messages = background; if (transcriptRow.submission_message_id) { const transcript = await readAgentRunTranscript(db, transcriptRow, { includeFileActivity: fileTools.length > 0 }); req.agentFileActionHistory = transcript.flatMap(({ fileActions }) => fileActions || []).slice(-12); messages = [...(actionOffer || fileTools.length ? [] : [background[0]]), ...transcript]; } await call("verify"); stage = "conversation"; let result; let interrupted = false; try { result = await withProviderBudget(provider.provider, lane, signal, async () => { const firstMessage = !resume && row.source === LIVE_SOURCE && row.submission_message_id != null ? messages.at(-1) : null; const chatTitle = firstMessage?.role === "user" && firstMessage.content ? await generateFirstAgentChatTitle(db, row, provider, firstMessage.content, signal) : null; if (chatTitle) await call("verify"); const reply = await completeAiChatConversation({ req, ...provider, messages, serverContext: { currentServer: context.serverName } }); return chatTitle?.title ? { ...reply, chatTitle } : reply; }); } catch (error) { if (signal.aborted || stopping() || (!automaticAttempts && (!resume || error?.status !== 429))) throw error; interrupted = true; result = {}; } if (req.agentReviewProposal) { result.actionProposal = req.agentReviewProposal; result.remainingActions = req.agentReviewRemainingActions; result.resumeModel = true; result.fileTasks = req.agentReviewFileTasks; result.planComplete = req.agentReviewPlanComplete; result.content = resume?.receipt || AGENT_ACTION_READY_MESSAGE; } else { stage = "file diagnostics"; const parsed = parseAiAgentFileOperations(String(result.content || "").slice(0, 24_000)); if (!req.agentPendingFileTasks?.length && parsed.operations.length) result.content = await call("fileReads", { content: String(result.content).slice(0, 24_000) }); if (resume) { const pending = (req.agentPendingFileTasks || []).map(({ action, path }) => ({ action, path, blocker: (action === "write_file" ? fileReads.get(path)?.error : undefined) || getAgentCreationConflict({ action, path }, resume.facts)?.error })); const note = interrupted ? "A request limit interrupted the remaining work. No further changes were sent." : limitReached ? `This turn reached its limit of ${MAX_AGENT_REVIEW_ACTIONS} reviewed actions.` : ""; result.content = renderAgentReviewSummary({ outcomes: resume.facts, pending, note, followUp: pending.length ? "" : result.content }); } else if (requiresConfirmedEdit || automaticAttempts || automaticFailure || unreadEdits.size || (automatic && result.toolLoopExhausted)) { // adpanel:agent-planner-completion - a provider reply alone cannot confirm a consented edit. const missingEdit = requiresConfirmedEdit && !automaticOutcomes.some(({ decision, writeVerification }) => decision === "accepted" && writeVerification !== "unchanged"); const note = uncertainEdit ? "An automatic edit could not be confirmed. Check the file before trying again." : interrupted ? "The Agent stopped before finishing." : result.toolLoopExhausted ? "The Agent reached its tool limit before finishing." : automaticFailure || unreadEdits.size ? "One or more automatic edits did not complete." : missingEdit ? actionOffer ? "No automatic edit was confirmed." : "Automatic edits are unavailable with the current server and file permissions." : ""; result.content = renderAgentReviewSummary({ outcomes: automaticOutcomes, note, followUp: note && automaticAttempts ? "" : result.content, automatic: true }); result.automaticEditFailed = !!note; } } stage = "publish"; await call("verify"); const published = await publishAgentResult(db, row, result, formatModelLabel(row.provider, row.model), signal); if (!published) throw new AgentRpcError(409, "agent_claim_inactive"); if (context.clamped && !result.automaticEditFailed) await call("plannerDone").catch(() => {}); } catch (error) { const reason = stopping() ? "agent_interrupted" : signal.aborted || error instanceof AiAgentJobDeadlineExceeded ? "agent_run_stopped" : error instanceof AgentRpcError ? error.code : error instanceof AiProviderError ? providerFailureCode(error) : stage === "provider configuration" ? "agent_provider_configuration" : "agent_run_failed"; if (!signal.aborted && !stopping()) { const status = error instanceof AiProviderError && Number.isInteger(error.status) ? ` (provider HTTP ${error.status})` : ""; logger.warn(`[Agent] Job ${row.id} failed during ${stage}: ${reason}${status}.`); } await failAgentClaim(db, row, reason); } finally { active.delete(String(row.id)); } }; } module.exports = { createAgentJobRunner, buildBackgroundAiAgentMessages };