Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,112 @@
|
||||
"use strict";
|
||||
|
||||
const { parseAiAgentFileOperations } = require("./server-agent-file-directives");
|
||||
const { safeJoinUnix, buildFsListPayload, relayFsJson, renderFsListOutcome, renderFsReadOutcome } = require("./node-fs-relay");
|
||||
const { safeTruncateUtf16 } = require("../utils/safe-truncate");
|
||||
const { AiAgentJobDeadlineExceeded, assertAiAgentJobDeadline } = require("../AgentWorker/run-deadline");
|
||||
const { MAX_ACTION_TEXT_BYTES } = require("../AgentWorker/action-proposal");
|
||||
const { hashAgentFile } = require("../AgentWorker/file-edit");
|
||||
|
||||
const MAX_OPERATIONS = 12;
|
||||
const FILE_DIAGNOSTIC_TIMEOUT_MS = 8000;
|
||||
const MAX_RESULT_CHARS = 32_000;
|
||||
|
||||
function createAgentFileDiagnostics({ resolveRemoteFsContext, fsRelayDeps, env = process.env }) {
|
||||
const readLimit = Math.max(2000, Math.min(50_000, parseInt(env.AI_AGENT_FILE_READ_MAX_CHARS, 10) || 18_000));
|
||||
const listLimit = Math.max(20, Math.min(500, parseInt(env.AI_AGENT_FILE_LIST_MAX_ITEMS, 10) || 120));
|
||||
|
||||
function summarizeDirectory({ entries, truncated }) {
|
||||
const lines = entries.slice(0, listLimit).map((entry) => {
|
||||
const name = String(entry?.name || "").trim();
|
||||
const directory = entry?.isDirectory === true || entry?.type === "dir" || entry?.type === "directory";
|
||||
const size = !directory && entry?.size ? ` (${entry.size} bytes)` : "";
|
||||
return `${directory ? "[dir]" : "[file]"} ${name}${size}`;
|
||||
});
|
||||
if (truncated || entries.length > listLimit) lines.push("...[listing truncated]");
|
||||
return lines.join("\n") || "(empty)";
|
||||
}
|
||||
|
||||
async function executeAiAgentFileOperations({ operations, serverName, serverId, req, structured = false, includeEditVersion = false }) {
|
||||
const results = [];
|
||||
const add = (ok, text, code, editVersion) => {
|
||||
const message = safeTruncateUtf16(text, MAX_RESULT_CHARS);
|
||||
results.push(structured ? (ok ? { ok, result: message, ...(editVersion && { editVersion }) } : { ok, code, error: message }) : message);
|
||||
};
|
||||
const deadline = Date.now() + FILE_DIAGNOSTIC_TIMEOUT_MS;
|
||||
|
||||
for (const { action, path: relative } of operations.slice(0, MAX_OPERATIONS)) {
|
||||
if (typeof relative !== "string" || !relative) {
|
||||
add(false, "Skipped one file operation because the path was invalid.", "file_path_invalid");
|
||||
continue;
|
||||
}
|
||||
// adpanel:agent-file-diagnostics - neither legacy directives nor native tools may dispatch a mutation here.
|
||||
if (action !== "list" && action !== "read") {
|
||||
add(false, `ADPanel Agent cannot change ${relative}. Use the file manager to make changes.`, "file_operation_not_allowed");
|
||||
continue;
|
||||
}
|
||||
const checkDeadline = () => { req.aiAgentChatSignal?.throwIfAborted(); assertAiAgentJobDeadline(req); };
|
||||
checkDeadline();
|
||||
try {
|
||||
const context = await resolveRemoteFsContext(serverName);
|
||||
if (!(await req.readAiAgentFilePermissions())?.files_read) {
|
||||
add(false, `No permission to read ${relative}.`, "file_read_denied");
|
||||
continue;
|
||||
}
|
||||
if (!context.remote || (serverId != null && String(context.serverId) !== String(serverId))) {
|
||||
add(false, `Could not access node files for ${serverName}.`, "file_target_unavailable");
|
||||
continue;
|
||||
}
|
||||
const full = safeJoinUnix(context.baseDir, relative);
|
||||
checkDeadline();
|
||||
const remaining = deadline - Date.now();
|
||||
if (remaining <= 0) {
|
||||
add(false, `Could not ${action} ${relative}: the file diagnostic deadline was reached.`, "file_node_unavailable");
|
||||
continue;
|
||||
}
|
||||
const listing = action === "list";
|
||||
const payload = listing ? buildFsListPayload(full, context.serverName) : { path: full, server: context.serverName, encoding: "base64" };
|
||||
const outcome = await relayFsJson(fsRelayDeps, context.node, `/v1/fs/${action}`, payload, remaining);
|
||||
checkDeadline();
|
||||
const response = listing ? renderFsListOutcome(outcome, relative) : renderFsReadOutcome(outcome, relative, { strictText: true });
|
||||
if (response.status !== 200) {
|
||||
const [code, detail] = outcome.kind === "not_found" ? ["file_not_found", listing ? "directory not found" : "file not found"]
|
||||
: outcome.kind === "offline" ? ["file_node_unavailable", "the server node did not respond"]
|
||||
: outcome.kind === "too_large" ? ["file_response_too_large", response.json.message]
|
||||
: outcome.kind === "ok" ? ["file_invalid_content", "the server node did not return valid file content"]
|
||||
: ["file_read_failed", "the server node refused the request"];
|
||||
add(false, `Could not ${action} ${relative}: ${detail.replace(/\.$/, "")}.`, code);
|
||||
} else if (listing) {
|
||||
add(true, `Contents of ${relative}:\n${summarizeDirectory(response.json)}`);
|
||||
} else if (response.json.binary) {
|
||||
add(false, `Cannot read ${relative}: binary file (not readable as text).`, "file_not_text");
|
||||
} else {
|
||||
const content = response.json.content;
|
||||
const text = safeTruncateUtf16(content, Math.min(readLimit, MAX_RESULT_CHARS - 2100));
|
||||
const truncated = text.length < content.length ? "\n...[truncated]" : "";
|
||||
const editVersion = includeEditVersion && context.nodeId && !truncated && Buffer.byteLength(content) <= MAX_ACTION_TEXT_BYTES
|
||||
? { sha256: hashAgentFile(content), nodeId: context.nodeId, path: full } : null;
|
||||
const message = content === "" ? `Read ${relative}: the file exists and is empty (0 bytes).`
|
||||
: `Read ${relative}:\n\`\`\`\n${text}${truncated}\n\`\`\``;
|
||||
add(true, message, undefined, editVersion);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error?.status === 403 || error instanceof AiAgentJobDeadlineExceeded || req.aiAgentChatSignal?.aborted) throw error;
|
||||
add(false, `Could not ${action} ${relative}: file diagnostics failed.`, "file_read_failed");
|
||||
}
|
||||
}
|
||||
|
||||
if (operations.length > MAX_OPERATIONS) add(false, `Skipped ${operations.length - MAX_OPERATIONS} extra file operation(s) to keep this job bounded.`, "file_operation_limit");
|
||||
return results;
|
||||
}
|
||||
|
||||
async function postProcessAiAgentResponse({ content, serverName, serverId, req }) {
|
||||
const { operations, message } = parseAiAgentFileOperations(content);
|
||||
if (!operations.length) return String(content || "").trim();
|
||||
const results = await executeAiAgentFileOperations({ operations, serverName, serverId, req });
|
||||
return [message, ...results].filter(Boolean).join("\n\n") || "Done.";
|
||||
}
|
||||
|
||||
return { executeAiAgentFileOperations, postProcessAiAgentResponse };
|
||||
}
|
||||
|
||||
module.exports = { createAgentFileDiagnostics };
|
||||
Reference in new issue
Block a user