src/index.js
// AgentRove native agent: workflow-automation (MIT).
// Runs small declarative automation recipes (JSON) made only of built-in steps: read CSV / JSON /
// Markdown / text files, list files, filter, map, sort, dedupe, summarize, join, template text, and
// write, move or copy files inside one workspace folder. No shell, no network, no code evaluation,
// no deletes. validate_recipe and plan_recipe never write; run_recipe writes only after confirm: true.
import { readFileSync } from "node:fs";
import { defineAgent, makeContext, handleMcpMessage, runCli, runMcpStdio, validateManifest } from "../sdk/index.js";
import { ToolError } from "./errors.js";
import { checkRecipe, compileOrThrow, checkInputVars, STEP_TYPE_NAMES } from "./recipe.js";
import { workspaceRoot } from "./fsguard.js";
import { createRunContext, evaluateRecipe, planHash, previewOf } from "./engine.js";
import { applyOperations } from "./apply.js";
import { summarize, diffText, markdownReport } from "./report.js";
export { makeContext, handleMcpMessage, runCli, runMcpStdio, validateManifest };
export { checkRecipe, STEP_TYPE_NAMES } from "./recipe.js";
export { parseTemplate, renderTemplate } from "./template.js";
export { parseCsv, toCsv } from "./csv.js";
export { compileGlob, matchSegment } from "./glob.js";
export { normalizeRel, workspaceRoot } from "./fsguard.js";
export const manifest = JSON.parse(readFileSync(new URL("../agent.json", import.meta.url), "utf8"));
/** The workspace folder: AGENTROVE_WORKFLOW_ROOT, or the folder the CLI / MCP server was started in. */
export function currentWorkspace(env = process.env) {
// An explicitly set folder is used as given (except roots, the home folder itself and system folders);
// the start folder is used only when it looks like a project (see PROJECT_MARKERS in fsguard.js).
const explicit = !!env.AGENTROVE_WORKFLOW_ROOT;
return workspaceRoot(explicit ? env.AGENTROVE_WORKFLOW_ROOT : process.cwd(), { explicit, envName: "AGENTROVE_WORKFLOW_ROOT" });
}
const PUBLIC_OP_KEYS = ["index", "step", "op", "path", "from", "mode", "status", "reason", "bytes", "sha256", "before_sha256", "renamed_from", "case_only", "diff", "preview"];
/**
* Builds the plan: validates the recipe, reads inputs and runs every step in memory, and lists the
* file operations without performing them. opts: { root, now, deadlineMs } (tests and embedding).
*/
export function buildPlan(input, opts = {}) {
const { compiled, warnings: staticWarnings } = compileOrThrow(input.recipe);
const v = checkInputVars(input.vars);
if (v.errors.length) throw new ToolError("invalid_input", v.errors.map((e) => `${e.path}: ${e.message}`).join("; "));
const root = opts.root ?? currentWorkspace(opts.env);
const ctx = createRunContext({ root, compiled, vars: v.vars, inputText: input.input_text, now: opts.now ?? new Date(), deadlineMs: opts.deadlineMs });
staticWarnings.forEach((w) => ctx.warn(w));
const stepInfo = evaluateRecipe(ctx, compiled);
const hash = planHash(input.recipe, { ...compiled.vars, ...v.vars }, input.input_text, ctx);
return { ctx, compiled, stepInfo, hash, root };
}
function publicPlan(plan, input, { executed, results }) {
const { ctx, compiled, stepInfo, hash, root } = plan;
const n = input.preview_rows ?? 5;
const steps = stepInfo.map((s) => (n > 0 && s.type !== "write_file" && s.type !== "move_files" && s.type !== "copy_files" ? { ...s, preview: previewOf(ctx.outputs[s.id], n) } : s));
const operations = ctx.ops.map((o) => {
const p = {};
for (const k of PUBLIC_OP_KEYS) if (o[k] !== undefined) p[k] = o[k];
if (input.include_contents && o._content !== undefined) p.content = o._content;
return p;
});
const summary = summarize(ctx.ops);
const out = {
recipe_name: compiled.name,
workspace: root,
plan_hash: hash,
executed,
ready: summary.conflicts === 0,
summary,
operations,
diff: diffText(ctx.ops, { name: compiled.name, workspace: root, executed }),
steps,
warnings: ctx.warnings,
};
if (results) out.results = results;
out.report = markdownReport(ctx.ops, { name: compiled.name, workspace: root, executed, warnings: ctx.warnings, planHash: hash });
return out;
}
async function validate_recipe(input) {
const r = checkRecipe(input.recipe);
return {
valid: r.errors.length === 0,
recipe_name: r.compiled?.name ?? "Untitled recipe",
errors: r.errors,
warnings: r.warnings,
steps: r.steps,
step_types: STEP_TYPE_NAMES,
};
}
async function plan_recipe(input, ctx) {
return publicPlan(buildPlan(input, { now: ctx.now() }), input, { executed: false });
}
async function run_recipe(input, ctx) {
const plan = buildPlan(input, { now: ctx.now() });
if (input.expected_plan_hash && input.expected_plan_hash !== plan.hash) {
throw new ToolError("plan_changed", `The plan is different from the one you reviewed (expected ${input.expected_plan_hash.slice(0, 12)}..., now ${plan.hash.slice(0, 12)}...): files, the recipe, vars or the date changed. Nothing was written. Run plan_recipe again and review it.`);
}
const conflicts = plan.ctx.ops.filter((o) => o.status === "conflict");
if (conflicts.length) {
throw new ToolError("plan_has_conflicts", `Nothing was written: ${conflicts.length} operation(s) conflict (${conflicts.slice(0, 5).map((o) => `${o.path}: ${o.reason}`).join("; ")}${conflicts.length > 5 ? "; ..." : ""}). Change if_exists (skip, suffix${conflicts.some((o) => o.op === "write_file") ? ", overwrite, append" : ""}) or the target paths, then plan again.`);
}
if (!input.expected_plan_hash) plan.ctx.warn("Ran without expected_plan_hash. Pass the plan_hash from plan_recipe so run_recipe stops if anything changed after you reviewed the plan.");
const results = applyOperations(plan.root, plan.ctx.ops, () => plan.ctx.tick());
return publicPlan(plan, input, { executed: true, results });
}
const agent = defineAgent(manifest, { validate_recipe, plan_recipe, run_recipe });
export default agent;