63 lines
2.4 KiB
JavaScript
63 lines
2.4 KiB
JavaScript
"use strict";
|
|
|
|
const FILE_CONTENT_START = "---FILE_CONTENT_START---";
|
|
const FILE_CONTENT_END = "---FILE_CONTENT_END---";
|
|
|
|
function sanitizeAiAgentFilePath(value) {
|
|
let rel = String(value || "").replace(/\0/g, "").trim();
|
|
if (rel === ".") return rel;
|
|
rel = rel.replace(/^["'`]+|["'`]+$/g, "").replace(/[.,!?;:]+$/g, "").trim();
|
|
while (rel.startsWith("/")) rel = rel.slice(1);
|
|
if (!rel || rel.length > 2048 || /[\r\n]/.test(rel)) return "";
|
|
return rel;
|
|
}
|
|
|
|
function parseAiAgentFileOperations(content) {
|
|
const lines = String(content || "").split(/\r?\n/);
|
|
const operations = [];
|
|
const message = [];
|
|
const seen = new Set();
|
|
let fence = "";
|
|
|
|
// adpanel:agent-file-directives - quoted examples and file bodies are data, never nested actions.
|
|
for (let index = 0; index < lines.length; index += 1) {
|
|
const line = lines[index];
|
|
const fenceMarker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1] || "";
|
|
if (fence || fenceMarker) {
|
|
message.push(line);
|
|
if (!fence) fence = fenceMarker;
|
|
else if (fenceMarker[0] === fence[0] && fenceMarker.length >= fence.length && line.trim() === fenceMarker) fence = "";
|
|
continue;
|
|
}
|
|
|
|
const directive = /^FILE_(LIST|READ|MKDIR|DELETE|CREATE|WRITE):([^\s]+)[ \t]*$/i.exec(line);
|
|
const action = directive?.[1].toLowerCase();
|
|
const writesContent = action === "create" || action === "write";
|
|
let body;
|
|
if (line === FILE_CONTENT_START || (writesContent && lines[index + 1] === FILE_CONTENT_START)) {
|
|
const start = index;
|
|
const bodyStart = index + (writesContent ? 2 : 1);
|
|
index = bodyStart;
|
|
while (index < lines.length && lines[index] !== FILE_CONTENT_END) index += 1;
|
|
if (index === lines.length || !writesContent) {
|
|
message.push(lines.slice(start, index + 1).join("\n"));
|
|
continue;
|
|
}
|
|
body = lines.slice(bodyStart, index).join("\n");
|
|
}
|
|
if (!directive || (writesContent && body === undefined)) {
|
|
message.push(line);
|
|
continue;
|
|
}
|
|
|
|
const filePath = sanitizeAiAgentFilePath(directive[2]);
|
|
const key = `${action}:${filePath}`;
|
|
if (!filePath || seen.has(key)) continue;
|
|
seen.add(key);
|
|
operations.push(writesContent ? { action, path: filePath, content: body } : { action, path: filePath });
|
|
}
|
|
|
|
return { operations, message: message.join("\n").trim() };
|
|
}
|
|
|
|
module.exports = { parseAiAgentFileOperations, sanitizeAiAgentFilePath }; |