"use strict"; const { diffLines } = require("diff"); const { isAgentFileEdit, isAgentFolderAlreadyPresent } = require("./action-proposal"); const { safeTruncateUtf16 } = require("../utils/safe-truncate"); const POWER_ACTIONS = new Set(["start", "stop", "restart", "kill"]); const REVIEW_FAILURES = Object.freeze({ agent_authority_revoked: "Permission to make this edit was revoked. No change was sent.", agent_claim_inactive: "This Agent run is no longer active. No change was sent.", agent_automatic_file_edit_denied: "This run does not authorize an automatic edit. No change was sent.", agent_automatic_file_edit_invalid: "The automatic edit request was invalid. No change was sent.", review_target_changed: "The server moved or another server operation is in progress. No change was sent.", review_preflight_unavailable: "The panel could not verify permissions in time. No change was sent.", file_changed_on_disk: "The file changed after review. No edit or deletion was made.", node_review_update_required: "The node refused the version-checked request. Update the node daemon and request a new review.", review_path_exists: "The path already exists. Nothing was overwritten.", review_path_missing: "The node reported that the file was not found. No change was made.", review_file_rejected: "The node refused the file operation. Check the path and node permissions.", review_file_unavailable: "The panel could not re-read the reviewed file. No change was sent.", review_disk_limit: "The node refused the operation because there is not enough disk space or quota.", review_edit_invalid: "The proposed edit is missing an exact fragment or replacement. No change was written.", review_edit_not_found: "The exact text to replace was not found. No change was written.", review_edit_ambiguous: "The text to replace matches more than once. No change was written.", review_edit_whole_file: "This edit would replace or clear the entire file. Request a smaller exact edit; no change was written.", review_edit_too_large: "The file would exceed the reviewed edit limit. No change was written.", review_revert_unavailable: "This chat has no recorded original text for the last edit to this file. Use a known-good backup; no change was written.", review_revert_changed: "The file no longer matches the version saved by the Agent. A revert could overwrite newer changes, so nothing was written.", minecraft_eula_required: "The node requires Minecraft EULA acceptance. Review it in the server console before starting the server.", }); const actionDescriptions = Object.freeze({ start: "start", stop: "stop", restart: "restart", kill: "force-stop", console_command: "console command", write_file: "file edit", replace_file: "whole-file replacement", revert_file: "file revert", create_file: "file creation", create_folder: "folder creation", delete_file: "file deletion", create_backup: "backup creation", restore_backup: "backup restore", delete_backup: "backup deletion", }); const completedActions = Object.freeze({ write_file: "Edited", replace_file: "Replaced contents", revert_file: "Restored recorded contents", create_file: "Created", create_folder: "Created folder", delete_file: "Deleted", create_backup: "Created backup", restore_backup: "Restored backup", delete_backup: "Deleted backup", }); function describeAgentReview(server, proposal, state, code, result) { const { action, path, name, backup, deleteOldFiles } = proposal; const target = path ? ` for \`${path}\`` : backup ? ` for backup \`${backup}\`` : ""; if (state === "dismissed") return { text: `Declined the proposed ${actionDescriptions[action]}${target}. No change was sent.`, facts: { server, action, path, backup, name, decision: "declined", evidence: "The operator declined this proposal. No modification or command was sent." }, }; if (state === "refused") return { text: Object.hasOwn(REVIEW_FAILURES, code) ? REVIEW_FAILURES[code] : `The panel refused the reviewed ${actionDescriptions[action]}${target}.`, facts: { server, action, path, backup, name, decision: "refused", ...(Object.hasOwn(REVIEW_FAILURES, code) ? { code } : {}), evidence: REVIEW_FAILURES[code] || "The panel refused the reviewed action." }, }; if (state !== "applied") return { text: `The node did not confirm the ${actionDescriptions[action]}${target} on \`${server}\`. Check the server before trying again; the operation was not retried.`, facts: { server, action, path, backup, name, decision: "unknown", evidence: "The node did not confirm the result. The operation was not retried." }, }; const facts = { server, action, decision: "accepted" }; if (path) facts.path = path; if (backup) facts.backup = backup; if (name) facts.name = name; if (proposal.changeSummary && result?.evidence !== "unchanged") facts.changeSummary = proposal.changeSummary; let text; if (POWER_ACTIONS.has(action)) { facts.evidence = "The node acknowledged the power request. The final running state was not verified."; text = `The node accepted the ${actionDescriptions[action]} request for \`${server}\`. The final server state was not verified.`; } else if (action === "console_command") { facts.evidence = "The node acknowledged delivery of the reviewed console command. Its output was not verified."; text = `Sent the reviewed console command to \`${server}\`. Its output was not verified.`; } else if (isAgentFileEdit(proposal) || action === "revert_file") { if (result.evidence === "unchanged") { facts.writeVerification = "unchanged"; facts.evidence = "The file already matched the approved contents. No write was sent."; text = `\`${path}\` on \`${server}\` already matched the approved contents. No write was needed.`; } else { if (typeof result.before === "string" && typeof result.after === "string") { const changes = diffLines(result.before, result.after, { timeout: 50 }); if (changes) { facts.addedLines = changes.reduce((total, part) => total + (part.added ? part.count : 0), 0); facts.removedLines = changes.reduce((total, part) => total + (part.removed ? part.count : 0), 0); } } if (result.evidence === "readback") { facts.writeVerification = "readback"; facts.evidence = "The write response was lost, but a read confirmed the exact approved bytes are present. The write was not retried."; text = `Verified that \`${path}\` on \`${server}\` contains the approved text after the write response was lost. The write was not retried.`; } else { facts.evidence = "The node acknowledged the version-checked file write. No service restart or behavior test was performed."; text = action === "revert_file" ? `Restored the recorded text in \`${path}\` on \`${server}\`. The node confirmed the write.` : action === "replace_file" ? `Replaced \`${path}\` on \`${server}\` with the approved contents. The node confirmed the write.` : `Updated \`${path}\` on \`${server}\` with the approved text. The node confirmed the write.`; } if (facts.addedLines !== undefined) text += ` Lines added: ${facts.addedLines}; removed: ${facts.removedLines}.`; } } else if (action === "restore_backup") { facts.replaceExistingFiles = deleteOldFiles; facts.evidence = "The node confirmed the backup restore request completed."; text = `Restored backup \`${backup}\` on \`${server}\` ${deleteOldFiles ? "with replacement of existing files" : "by merging it with existing files"}.`; } else { facts.evidence = "The node reported success for the approved operation."; if (action === "create_file") facts.createdBytes = Buffer.byteLength(proposal.content); const descriptions = { create_file: `Created \`${path}\` with the approved text`, create_folder: `Created folder \`${path}\``, delete_file: `Deleted the reviewed file \`${path}\``, create_backup: `Created backup \`${name}\``, delete_backup: `Deleted backup \`${backup}\``, }; text = `${descriptions[action]} on \`${server}\`.`; } return { text, facts }; } function plainReportText(value) { return value.replace(/[\x00-\x1f\x7f`*~\[\]<>]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`); } function isUnchangedReview(fact) { return fact.writeVerification === "unchanged" || fact.evidence === "The file already matched the approved contents. No write was sent."; } function describeReviewResult(fact) { const { action, decision, path, name, backup, server, code, writeVerification, createdBytes, changeSummary, addedLines, removedLines } = fact; const target = path || backup || name || server; const label = target ? `\`${plainReportText(target)}\`` : actionDescriptions[action]; if (decision === "declined") return `${label} - Declined ${actionDescriptions[action]}; no change sent.`; if (decision === "refused" && isAgentFolderAlreadyPresent(fact)) return `${label} - Folder already existed; nothing was overwritten.`; if (decision === "refused") return `${label} - ${REVIEW_FAILURES[code] || `The panel refused the ${actionDescriptions[action]}.`}`; if (decision !== "accepted") return `${label} - ${actionDescriptions[action]} not confirmed; not retried.`; if (isUnchangedReview(fact)) { return `${label} - Already matched the reviewed contents. No write was sent.`; } if (POWER_ACTIONS.has(action) || action === "console_command") { return `${label} - ${actionDescriptions[action]} sent and acknowledged. ${action === "console_command" ? "Output not verified." : "Final running state not verified."}`; } const change = action === "create_file" && createdBytes === 0 ? "Created empty file" : action === "create_file" && Number.isInteger(createdBytes) ? `Created (${createdBytes} bytes)` : completedActions[action]; const description = typeof changeSummary === "string" && changeSummary ? ` ${plainReportText(changeSummary)}` : ""; const counts = Number.isInteger(addedLines) && Number.isInteger(removedLines) ? ` (+${addedLines} / -${removedLines} lines).` : ""; const readback = writeVerification === "readback" || fact.evidence?.startsWith("The write response was lost,"); return `${label} - ${change}.${description}${counts}${readback ? " A readback verified the exact approved bytes; the write was not retried." : ""}`; } function renderAgentReviewSummary({ outcomes, pending = [], note = "", followUp = "", complete = false, skipped = 0, automatic = false }) { const facts = outcomes.flatMap((outcome) => [...(outcome?.previousSteps || []), outcome]) .filter((fact) => fact && Object.hasOwn(actionDescriptions, fact.action)); const changed = []; const unchanged = []; const acknowledged = []; const unfinished = []; for (const fact of facts) { const { action, decision } = fact; const category = decision === "refused" && isAgentFolderAlreadyPresent(fact) ? unchanged : decision !== "accepted" ? unfinished : isUnchangedReview(fact) ? unchanged : POWER_ACTIONS.has(action) || action === "console_command" ? acknowledged : changed; category.push(describeReviewResult(fact)); } for (const { action, path, blocker } of pending) { unfinished.push(`\`${plainReportText(path)}\` - ${actionDescriptions[action]} not performed.${blocker ? ` ${plainReportText(blocker)}` : ""}`); } if (skipped) unfinished.push(`${skipped} additional ${skipped === 1 ? "step was" : "steps were"} not run.`); const status = note || unfinished.length || !facts.length ? "[!] Task incomplete or not fully confirmed" : acknowledged.length ? "[!] Requests acknowledged; final effect not verified" : automatic ? "[\u2713] Automatic file edits confirmed" : complete ? "[\u2713] Task completed successfully" : "[\u2713] Reviewed actions confirmed"; const reply = typeof followUp === "string" ? followUp.trim() : ""; const additional = reply && !/^(?:done|ok(?:ay)?|finished|completed|all set|no response received)[.!\s]*$/i.test(reply) ? plainReportText(safeTruncateUtf16(reply.replace(/\s+/g, " "), 1600)) : ""; return [ `**Status:** ${status}.${note ? ` ${note}` : ""}`, changed.length && `**Changed:** ${changed.join(" ")}`, unchanged.length && `**Unchanged:** ${unchanged.join(" ")}`, acknowledged.length && `**Acknowledged:** ${acknowledged.join(" ")}`, unfinished.length && `**Not completed:** ${unfinished.join(" ")}`, additional && `**Follow-up:** ${additional}`, ].filter(Boolean).join("\n"); } module.exports = { describeAgentReview, renderAgentReviewSummary };