Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Workflow Automation v0.1.2 · generic

Archive SHA-256 c81ec2960b297ad150638bde4ce14c8be5d176cfe9967ea74e47eee60f9c98a4 · 87.5 KB · built Dec 1, 2026

src/engine.js

// Runs a compiled recipe in memory and PLANS file operations; nothing is written here. Reading
// happens only through src/fsguard.js (workspace-confined, size-limited). The plan lists every
// folder to create and every file to write, append, move or copy, with the reason for each skip or
// conflict, a line diff for overwrites and a plan_hash that run_recipe can be pinned to.
import { createHash } from "node:crypto";
import { ToolError } from "./errors.js";
import { normalizeRel, readText, findFiles, inspectTarget, inspectSource, pathKey, readBytes, checkWritableName } from "./fsguard.js";
import { renderTemplate, ESCAPERS } from "./template.js";
import { parseCsv, toCsv, columnsOf, DELIMITERS } from "./csv.js";
import { analyzeMarkdown } from "./markdown.js";
import { matchSegment } from "./glob.js";
import { record, cloneRecord, safeJson, isRecord, isRows, getField, isEmpty, textOf, compareValues, toNumber, toDateMs, isFloatingDate, tidy, formatDate } from "./values.js";

const sha256 = (s) => createHash("sha256").update(s).digest("hex");

// ---------------------------------------------------------------------------------------------
// Context
// ---------------------------------------------------------------------------------------------
export function createRunContext({ root, compiled, vars = {}, inputText, now = new Date(), deadlineMs }) {
  const limits = compiled.limits;
  const deadline = deadlineMs ?? Date.now() + limits.timeout_seconds * 1000;
  const tz = compiled.timezone;
  const nowMs = now.getTime();
  const warnings = [];
  const ctx = {
    root,
    limits,
    tz,
    vars: record(Object.entries({ ...compiled.vars, ...vars })),
    run: record([["date", formatDate(nowMs, "YYYY-MM-DD", tz)], ["time", formatDate(nowMs, "HH:mm", tz)], ["timestamp", new Date(nowMs).toISOString()], ["timezone", tz], ["recipe", compiled.name]]),
    inputText,
    sources: new Map(),
    overlay: new Map(), // pathKey -> { kind: "file" | "dir" | "absent", byPlan: true }
    ops: [],
    outputs: record(),
    readBytes: 0,
    writeBytes: 0,
    warnings,
    warn(w) {
      if (!warnings.includes(w) && warnings.length < 200) warnings.push(w);
    },
    tick() {
      if (Date.now() > deadline) throw new ToolError("time_limit_exceeded", `The recipe ran longer than its time limit (${limits.timeout_seconds} s; limits.timeout_seconds, hard limit 120). Nothing was written.`);
    },
    addRead(n, field) {
      ctx.readBytes += n;
      if (ctx.readBytes > limits.max_total_read_bytes) throw new ToolError("limit_exceeded", `${field}: the recipe read more than ${limits.max_total_read_bytes} bytes in total (limits.max_total_read_bytes).`);
    },
  };
  return ctx;
}

const baseFrame = (ctx) => record([["vars", ctx.vars], ["run", ctx.run], ["steps", ctx.outputs]]);
const metaFrame = (i, n) => record([["@index", i], ["@number", i + 1], ["@first", i === 0], ["@last", i === n - 1]]);

function render(ctx, tp, frames, { escape = "none", strict = false, field }) {
  const r = renderTemplate(tp.ast, frames, { escape, strict, field, timezone: ctx.tz, maxChars: ctx.limits.max_output_chars, tick: () => ctx.tick() });
  for (const m of r.missing) ctx.warn(`${field}: {{${m}}} has no value and was left empty.`);
  return r.text;
}

function renderPath(ctx, tp, frames, field) {
  if (typeof tp === "string") return tp;
  if (!tp.templated) return normalizeRel(tp.text, field);
  const text = render(ctx, tp, frames, { escape: "path", strict: true, field });
  return normalizeRel(text, field);
}

function rowsOf(v, field) {
  if (isRows(v)) return v;
  if (Array.isArray(v)) throw new ToolError("invalid_input", `${field}: expected a list of objects (rows), but some items are not objects.`);
  throw new ToolError("invalid_input", `${field}: expected rows (a list of objects), got ${v === null ? "null" : typeof v}.`);
}

function checkRows(ctx, rows, field) {
  if (rows.length > ctx.limits.max_rows) throw new ToolError("limit_exceeded", `${field}: produced ${rows.length} rows; the limit is ${ctx.limits.max_rows} (limits.max_rows).`);
  return rows;
}

/** A read must not target something an earlier file step of this recipe changes (reads see the disk as it was). */
function checkReadAgainstPlan(ctx, rel, field) {
  const ov = ctx.overlay.get(pathKey(rel));
  if (ov) throw new ToolError("invalid_recipe", `${field}: ${rel} is changed by an earlier step of this recipe. All reading happens before anything is written, so read the earlier step's output with "from" instead.`);
}

// ---------------------------------------------------------------------------------------------
// Sources
// ---------------------------------------------------------------------------------------------
function sourceFiles(ctx, step, field) {
  if (step.glob) {
    const files = findFiles(ctx, step.glob.pattern, field).filter((f) => f.kind === "file");
    if (!files.length) ctx.warn(`${field}: the pattern ${step.glob.pattern} matched no files.`);
    return { files: files.map((f) => f.path), multi: true };
  }
  return { files: [renderPath(ctx, step.path, [baseFrame(ctx)], field)], multi: false };
}

function fileInfo(rel) {
  const name = rel.split("/").pop();
  const dot = name.lastIndexOf(".");
  return { name, stem: dot > 0 ? name.slice(0, dot) : name, ext: dot > 0 ? name.slice(dot + 1).toLowerCase() : "", folder: rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "." };
}

function jsonPointer(v, pointer, field) {
  if (!pointer) return v;
  let cur = v;
  for (const raw of pointer.split("/").slice(1)) {
    const k = raw.replace(/~1/g, "/").replace(/~0/g, "~");
    if (Array.isArray(cur) && /^\d+$/.test(k) && +k < cur.length) cur = cur[+k];
    else if (isRecord(cur) && Object.hasOwn(cur, k)) cur = cur[k];
    else throw new ToolError("invalid_input", `${field}: the JSON pointer ${pointer} does not exist in the document.`);
  }
  return cur;
}

function parseJson(text, field) {
  try {
    return safeJson(JSON.parse(text));
  } catch (e) {
    if (e instanceof ToolError) throw e;
    throw new ToolError("invalid_input", `${field}: not valid JSON (${String(e.message).slice(0, 120)}).`);
  }
}

function markdownRow(rel, text, mtimeMs) {
  const md = analyzeMarkdown(text);
  const info = fileInfo(rel);
  const fm = md.front_matter;
  const tags = Array.isArray(fm.tags) ? fm.tags : typeof fm.tags === "string" && fm.tags ? fm.tags.split(",").map((t) => t.trim()).filter(Boolean) : [];
  return record([
    ["path", rel], ["name", info.name], ["stem", info.stem], ["folder", info.folder], ["title", md.title || info.stem], ["front_matter", fm], ["tags", tags],
    ["headings", md.headings], ["tasks", md.tasks], ["open_tasks", md.tasks.filter((t) => !t.done).length], ["word_count", md.word_count], ["text", md.body],
    ["modified", mtimeMs ? new Date(mtimeMs).toISOString() : null],
  ]);
}

const STEPS = {
  read_csv(ctx, step, field) {
    const { files, multi } = sourceFiles(ctx, step, field);
    const rows = [];
    for (const rel of files) {
      checkReadAgainstPlan(ctx, rel, field);
      const text = readText(ctx, rel, field);
      const r = parseCsv(text, { delimiter: step.delimiter ?? "auto", header: step.header !== false, maxRows: ctx.limits.max_rows - rows.length, field: `${field} (${rel})`, tick: () => ctx.tick() });
      r.warnings.forEach((w) => ctx.warn(w));
      for (const row of r.rows) {
        if (multi) row._file = rel;
        rows.push(row);
      }
    }
    return checkRows(ctx, rows, field);
  },
  read_json(ctx, step, field) {
    const { files, multi } = sourceFiles(ctx, step, field);
    if (!multi) {
      checkReadAgainstPlan(ctx, files[0], field);
      return jsonPointer(parseJson(readText(ctx, files[0], field), field), step.pointer, field);
    }
    const rows = [];
    for (const rel of files) {
      checkReadAgainstPlan(ctx, rel, field);
      const v = jsonPointer(parseJson(readText(ctx, rel, field), `${field} (${rel})`), step.pointer, `${field} (${rel})`);
      for (const item of Array.isArray(v) ? v : [v]) {
        const row = isRecord(item) ? cloneRecord(item) : record([["value", item]]);
        row._file = rel;
        rows.push(row);
      }
    }
    return checkRows(ctx, rows, field);
  },
  read_markdown(ctx, step, field) {
    const { files } = sourceFiles(ctx, step, field);
    return checkRows(ctx, files.map((rel) => {
      checkReadAgainstPlan(ctx, rel, field);
      const text = readText(ctx, rel, field);
      return markdownRow(rel, text, ctx.sources.get(pathKey(rel))?.mtime_ms);
    }), field);
  },
  read_text(ctx, step, field) {
    const rel = renderPath(ctx, step.path, [baseFrame(ctx)], field);
    checkReadAgainstPlan(ctx, rel, field);
    return readText(ctx, rel, field);
  },
  list_files(ctx, step, field) {
    const folder = step.folder ?? ".";
    const pattern = normalizeRel(folder === "." ? step.pattern ?? "*" : `${folder}/${step.pattern ?? "*"}`, field, { glob: true });
    const prefix = folder === "." ? "" : pathKey(folder + "/");
    for (const k of ctx.overlay.keys()) if (k.startsWith(prefix)) throw new ToolError("invalid_recipe", `${field}: an earlier step of this recipe changes files in ${folder}. All reading happens before anything is written, so list files before the file steps.`);
    const files = findFiles(ctx, pattern, field, { includeDirs: step.include_folders === true });
    ctx.sources.set(`list:${pathKey(pattern)}`, { path: pattern, listing_sha256: sha256(JSON.stringify(files.map((f) => [f.path, f.size, f._mtime_ms]))) });
    return checkRows(ctx, files.map((f) => record(Object.entries(f).filter(([k]) => k !== "_mtime_ms"))), field);
  },
  read_input(ctx, step, field) {
    if (typeof ctx.inputText !== "string") throw new ToolError("missing_input", `${field}: read_input needs the tool's input_text, which was not given.`);
    const t = ctx.inputText;
    if (step.format === "text") return t;
    if (step.format === "json") return jsonPointer(parseJson(t, field), step.pointer, field);
    if (step.format === "markdown") return [markdownRow("input", t, null)];
    const r = parseCsv(t, { delimiter: step.delimiter ?? "auto", header: step.header !== false, maxRows: ctx.limits.max_rows, field, tick: () => ctx.tick() });
    r.warnings.forEach((w) => ctx.warn(w));
    return r.rows;
  },
  literal(ctx, step) {
    return safeJson(step.value);
  },

  // ------------------------------------------------------------------------------------------
  // Transforms
  // ------------------------------------------------------------------------------------------
  filter(ctx, step, field, input) {
    const rows = rowsOf(input, field);
    const base = baseFrame(ctx);
    const conds = step.where.map((c) => ({ ...c, value: c.value && c.value.ast ? render(ctx, c.value, [base], { field: `${field}.where` }) : c.value }));
    return rows.filter((row, i) => {
      if (i % 2000 === 0) ctx.tick();
      const results = conds.map((c) => testCondition(row, c));
      return step.match === "any" ? results.some(Boolean) : results.every(Boolean);
    });
  },
  map(ctx, step, field, input) {
    const rows = rowsOf(input, field);
    const base = baseFrame(ctx);
    let badCasts = 0;
    const out = rows.map((row, i) => {
      if (i % 2000 === 0) ctx.tick();
      let r = cloneRecord(row);
      for (const [from, to] of Object.entries(step.rename ?? {})) {
        if (!Object.hasOwn(r, from)) continue;
        const v = r[from];
        delete r[from];
        r[to] = v;
      }
      for (const [k, tp] of step.set ?? []) r[k] = render(ctx, tp, [base, metaFrame(i, rows.length), r], { field: `${field}.set.${k}` });
      for (const [k, type] of Object.entries(step.cast ?? {})) {
        if (!Object.hasOwn(r, k)) continue;
        const c = castValue(r[k], type);
        if (c === null && !isEmpty(r[k])) badCasts++;
        r[k] = c;
      }
      if (step.pick) r = record(step.pick.filter((k) => Object.hasOwn(r, k)).map((k) => [k, r[k]]));
      for (const k of step.omit ?? []) delete r[k];
      return r;
    });
    if (badCasts) ctx.warn(`${field}: ${badCasts} value(s) could not be converted and became empty (null).`);
    return out;
  },
  sort(ctx, step, field, input) {
    const rows = rowsOf(input, field);
    return rows
      .map((r, i) => [r, i])
      .sort(([a, ia], [b, ib]) => {
        for (const by of step.by) {
          const x = getField(a, by.field);
          const y = getField(b, by.field);
          const ex = isEmpty(x);
          const ey = isEmpty(y);
          if (ex || ey) {
            if (ex && ey) continue;
            return ex ? 1 : -1; // empty values last in both directions
          }
          const c = compareValues(x, y, by.type);
          if (c) return by.order === "desc" ? -c : c;
        }
        return ia - ib;
      })
      .map(([r]) => r);
  },
  dedupe(ctx, step, field, input) {
    const rows = rowsOf(input, field);
    const keyOf = (r) => {
      const vals = step.by?.length ? step.by.map((f) => textOf(getField(r, f)).trim()) : Object.keys(r).sort().map((k) => [k, textOf(r[k])]);
      const s = JSON.stringify(vals);
      return step.ignore_case ? s.toLowerCase() : s;
    };
    const keep = new Map();
    rows.forEach((r, i) => {
      const k = keyOf(r);
      if (step.keep === "last" || !keep.has(k)) keep.set(k, i);
    });
    const idx = new Set(keep.values());
    const out = rows.filter((_, i) => idx.has(i));
    if (out.length < rows.length) ctx.warn(`${field}: removed ${rows.length - out.length} duplicate row(s).`);
    return out;
  },
  limit(ctx, step, field, input) {
    const rows = rowsOf(input, field);
    const off = step.offset ?? 0;
    return rows.slice(off, off + step.count);
  },
  summarize(ctx, step, field, input) {
    const rows = rowsOf(input, field);
    const by = step.group_by ?? [];
    const groups = new Map();
    rows.forEach((r, i) => {
      if (i % 5000 === 0) ctx.tick();
      const key = JSON.stringify(by.map((f) => textOf(getField(r, f))));
      let g = groups.get(key);
      if (!g) groups.set(key, (g = { first: r, rows: [] }));
      g.rows.push(r);
    });
    if (!by.length && !groups.size) groups.set("[]", { first: record(), rows: [] });
    let skipped = 0;
    const out = [];
    for (const g of groups.values()) {
      const o = record(by.map((f) => [f, getField(g.first, f) ?? null]));
      for (const m of step.metrics) {
        const vals = m.field ? g.rows.map((r) => getField(r, m.field)) : [];
        const present = vals.filter((v) => !isEmpty(v));
        let v = null;
        if (m.op === "count") v = g.rows.length;
        else if (m.op === "count_distinct") v = new Set(present.map((x) => textOf(x))).size;
        else if (m.op === "sum" || m.op === "avg") {
          const nums = present.map(toNumber).filter(Number.isFinite);
          skipped += present.length - nums.length;
          const sum = nums.reduce((a, b) => a + b, 0);
          v = nums.length ? tidy(m.op === "sum" ? sum : sum / nums.length) : null;
        } else if (m.op === "min" || m.op === "max") {
          if (present.length) {
            const allNum = present.every((x) => Number.isFinite(toNumber(x)));
            v = present.reduce((a, b) => (compareValues(b, a, allNum ? "number" : "auto") * (m.op === "min" ? -1 : 1) > 0 ? b : a));
            if (allNum) v = toNumber(v);
          }
        } else if (m.op === "first") v = present.length ? present[0] : null;
        else if (m.op === "last") v = present.length ? present[present.length - 1] : null;
        else if (m.op === "values") v = [...new Set(present.map((x) => textOf(x)))].join(", ");
        o[m.as] = v;
      }
      out.push(o);
    }
    if (skipped) ctx.warn(`${field}: ${skipped} non-numeric value(s) were left out of sum/avg.`);
    return out;
  },
  join(ctx, step, field, input) {
    const left = rowsOf(input, field);
    const right = rowsOf(ctx.outputs[step.with], `${field}.with`);
    const lk = step.left_on ?? step.on;
    const rk = step.right_on ?? step.on;
    const norm = (v) => {
      const s = textOf(v).trim();
      return step.ignore_case ? s.toLowerCase() : s;
    };
    const index = new Map();
    let dup = 0;
    for (const r of right) {
      const k = norm(getField(r, rk));
      if (!k) continue;
      if (index.has(k)) dup++;
      else index.set(k, r);
    }
    if (dup) ctx.warn(`${field}: ${dup} row(s) of ${step.with} repeat a key already seen; the first match is used.`);
    const fields = step.fields ?? columnsOf(right).filter((c) => c !== rk);
    const prefix = step.prefix ?? "";
    let collisions = 0;
    const out = [];
    for (const l of left) {
      const match = index.get(norm(getField(l, lk)));
      if (!match && step.how === "inner") continue;
      const o = cloneRecord(l);
      for (const f of fields) {
        const name = prefix + f;
        if (Object.hasOwn(o, name)) {
          collisions++;
          continue;
        }
        o[name] = match ? getField(match, f) ?? null : null;
      }
      out.push(o);
    }
    if (collisions) ctx.warn(`${field}: some fields of ${step.with} have the same name as existing fields and were not copied (set prefix to keep both).`);
    return checkRows(ctx, out, field);
  },
  concat(ctx, step, field) {
    const out = [];
    for (const id of step.from) out.push(...rowsOf(ctx.outputs[id], `${field} (${id})`));
    return checkRows(ctx, out, field);
  },
  unnest(ctx, step, field, input) {
    const rows = rowsOf(input, field);
    const out = [];
    let collisions = 0;
    for (const r of rows) {
      const list = getField(r, step.field);
      const parent = cloneRecord(r);
      delete parent[step.field];
      if (!Array.isArray(list) || !list.length) {
        if (step.keep_empty) {
          parent[step.as ?? step.field] = null;
          out.push(parent);
        }
        continue;
      }
      for (const item of list) {
        const o = cloneRecord(parent);
        if (step.as) o[step.as] = item;
        else if (isRecord(item)) {
          for (const k of Object.keys(item)) {
            if (Object.hasOwn(o, k)) collisions++;
            o[k] = item[k];
          }
        } else o[step.field] = item;
        out.push(o);
        if (out.length > ctx.limits.max_rows) throw new ToolError("limit_exceeded", `${field}: produced more than ${ctx.limits.max_rows} rows (limits.max_rows).`);
      }
    }
    if (collisions) ctx.warn(`${field}: item fields replaced parent fields with the same name (set "as" to keep them apart).`);
    return out;
  },

  // ------------------------------------------------------------------------------------------
  // Formatting
  // ------------------------------------------------------------------------------------------
  template(ctx, step, field, input) {
    const frames = [baseFrame(ctx)];
    if (step.from) {
      if (typeof input === "string") frames.push(record([["text", input]]));
      else if (isRows(input)) frames.push(record([["rows", input], ["count", input.length]]));
      else {
        frames.push(record([["data", input]]));
        if (isRecord(input)) frames.push(input);
      }
    }
    return render(ctx, step.template, frames, { escape: step.escape ?? "html", field: `${field}.template` });
  },
  to_csv(ctx, step, field, input) {
    const rows = rowsOf(input, field);
    const d = step.delimiter ? DELIMITERS[step.delimiter] : ",";
    return toCsv(rows, step.columns ?? columnsOf(rows), { delimiter: d, protect: step.protect_formulas !== false, header: step.header !== false });
  },
  to_json(ctx, step, field, input) {
    return JSON.stringify(input, null, step.pretty === false ? 0 : 2) + "\n";
  },
  to_markdown_table(ctx, step, field, input) {
    const rows = rowsOf(input, field);
    const cols = step.columns ?? columnsOf(rows);
    if (!cols.length) return "";
    const cell = (v) => ESCAPERS.markdown(textOf(v)) || " ";
    const head = `| ${cols.map((c) => cell(step.headers?.[c] ?? c)).join(" | ")} |`;
    const sep = `| ${cols.map((c) => (rows.length && rows.every((r) => isEmpty(r[c]) || Number.isFinite(toNumber(r[c]))) ? "---:" : "---")).join(" | ")} |`;
    return [head, sep, ...rows.map((r) => `| ${cols.map((c) => cell(getField(r, c))).join(" | ")} |`)].join("\n") + "\n";
  },

  // ------------------------------------------------------------------------------------------
  // File steps: plan only
  // ------------------------------------------------------------------------------------------
  write_file(ctx, step, field, input) {
    const items = step.for_each ? rowsOf(ctx.outputs[step.for_each], `${field}.for_each`) : [null];
    const base = baseFrame(ctx);
    const out = [];
    items.forEach((item, i) => {
      ctx.tick();
      const frames = item ? [base, metaFrame(i, items.length), item] : [base];
      const rel = renderPath(ctx, step.path, frames, `${field}.path`);
      let content;
      if (step.content) content = render(ctx, step.content, frames, { escape: step.escape ?? "html", field: `${field}.content` });
      else if (typeof input === "string") content = input;
      else throw new ToolError("invalid_input", `${field}: from must produce text.`);
      out.push(planWrite(ctx, step, rel, content, field));
    });
    return out;
  },
  move_files(ctx, step, field, input) {
    return planTransfer(ctx, step, field, rowsOf(input, field), "move_file");
  },
  copy_files(ctx, step, field, input) {
    return planTransfer(ctx, step, field, rowsOf(input, field), "copy_file");
  },
};

function testCondition(row, c) {
  const v = getField(row, c.field);
  const t = c.value;
  const ic = c.ignore_case;
  const txt = (x) => (ic ? textOf(x).toLowerCase() : textOf(x));
  const eq = (a, b) => {
    if (c.type !== "string") {
      const x = toNumber(a);
      const y = toNumber(b);
      if (Number.isFinite(x) && Number.isFinite(y)) return x === y;
      if (c.type === "number") return false;
    }
    if (c.type === "date") return toDateMs(a) === toDateMs(b);
    if (typeof b === "boolean") return txt(a) === String(b);
    return txt(a) === txt(b);
  };
  const list = Array.isArray(v) ? v : null;
  switch (c.op) {
    case "empty":
      return isEmpty(v);
    case "not_empty":
      return !isEmpty(v);
    case "eq":
      return list ? list.some((x) => eq(x, t)) : eq(v, t);
    case "ne":
      return list ? !list.some((x) => eq(x, t)) : !eq(v, t);
    case "in":
      return t.some((x) => (list ? list.some((y) => eq(y, x)) : eq(v, x)));
    case "not_in":
      return !t.some((x) => (list ? list.some((y) => eq(y, x)) : eq(v, x)));
    case "gt":
    case "gte":
    case "lt":
    case "lte": {
      if (isEmpty(v)) return false;
      const r = compareValues(v, t, c.type, ic);
      return c.op === "gt" ? r > 0 : c.op === "gte" ? r >= 0 : c.op === "lt" ? r < 0 : r <= 0;
    }
    case "contains":
      return list ? list.some((x) => eq(x, t)) : txt(v).includes(txt(t));
    case "not_contains":
      return list ? !list.some((x) => eq(x, t)) : !txt(v).includes(txt(t));
    case "starts_with":
      return txt(v).startsWith(txt(t));
    case "ends_with":
      return txt(v).endsWith(txt(t));
    case "like":
      return matchSegment(textOf(t), textOf(v));
    case "not_like":
      return !matchSegment(textOf(t), textOf(v));
    default:
      return false;
  }
}

function castValue(v, type) {
  if (v === null || v === undefined) return null;
  switch (type) {
    case "string":
      return textOf(v);
    case "number": {
      const n = toNumber(v);
      return Number.isFinite(n) ? n : null;
    }
    case "integer": {
      const n = toNumber(v);
      return Number.isFinite(n) ? Math.trunc(n) : null;
    }
    case "boolean": {
      if (typeof v === "boolean") return v;
      const s = textOf(v).trim().toLowerCase();
      if (["true", "yes", "y", "1", "x", "done"].includes(s)) return true;
      if (["false", "no", "n", "0", ""].includes(s)) return false;
      return null;
    }
    case "date": {
      const ms = toDateMs(v);
      if (!Number.isFinite(ms)) return null;
      return isFloatingDate(v) ? String(v).trim() : new Date(ms).toISOString();
    }
    default:
      return v;
  }
}

// ---------------------------------------------------------------------------------------------
// Planning file operations (virtual overlay of the workspace; nothing is written)
// ---------------------------------------------------------------------------------------------
function addOp(ctx, op) {
  const planned = ctx.ops.filter((o) => o.op !== "create_folder").length;
  if (op.op !== "create_folder" && planned >= ctx.limits.max_operations) throw new ToolError("limit_exceeded", `The recipe plans more than ${ctx.limits.max_operations} file operations (limits.max_operations, hard limit 1000).`);
  op.index = ctx.ops.length + 1;
  ctx.ops.push(op);
  return op;
}

function planFolders(ctx, step, target, createFolders) {
  for (const folder of target.missingFolders) {
    const ov = ctx.overlay.get(pathKey(folder));
    if (ov?.kind === "dir") continue;
    if (ov?.kind === "file") return `${folder} is a file written by this recipe, not a folder`;
    if (!createFolders) return `folder ${folder} does not exist (create_folders is false)`;
  }
  for (const folder of target.missingFolders) {
    if (ctx.overlay.get(pathKey(folder))?.kind === "dir") continue;
    addOp(ctx, { op: "create_folder", step: step.id, path: folder, status: "planned" });
    ctx.overlay.set(pathKey(folder), { kind: "dir", byPlan: true });
  }
  return null;
}

/** Existing state of a path, combining the disk with operations planned earlier in this recipe. */
function targetState(ctx, rel, field) {
  const ov = ctx.overlay.get(pathKey(rel));
  if (ov?.kind === "file") return { exists: true, byPlan: true, missingFolders: [], rel };
  if (ov?.kind === "dir") return { exists: true, isDir: true, byPlan: true, missingFolders: [], rel };
  const t = inspectTarget(ctx.root, rel, field);
  if (ov?.kind === "absent") return { ...t, exists: false, movedAway: true };
  return t;
}

function freeSuffix(ctx, rel, field) {
  const slash = rel.lastIndexOf("/");
  const dir = slash >= 0 ? rel.slice(0, slash + 1) : "";
  const name = rel.slice(slash + 1);
  const dot = name.lastIndexOf(".");
  const stem = dot > 0 ? name.slice(0, dot) : name;
  const ext = dot > 0 ? name.slice(dot) : "";
  for (let n = 2; n <= 99; n++) {
    const cand = `${dir}${stem}-${n}${ext}`;
    const st = targetState(ctx, cand, field);
    if (!st.exists) return { rel: cand, state: st };
  }
  return null;
}

function lineDiff(before, after, maxLines = 40) {
  const a = before.split(/\r?\n/);
  const b = after.split(/\r?\n/);
  let s = 0;
  while (s < a.length && s < b.length && a[s] === b[s]) s++;
  let ea = a.length;
  let eb = b.length;
  while (ea > s && eb > s && a[ea - 1] === b[eb - 1]) {
    ea--;
    eb--;
  }
  const A = a.slice(s, ea);
  const B = b.slice(s, eb);
  const lines = [];
  let added = 0;
  let removed = 0;
  if (A.length * B.length <= 250_000) {
    // LCS table over the changed middle part
    const w = B.length + 1;
    const t = new Uint32Array((A.length + 1) * w);
    for (let i = A.length - 1; i >= 0; i--) for (let j = B.length - 1; j >= 0; j--) t[i * w + j] = A[i] === B[j] ? t[(i + 1) * w + j + 1] + 1 : Math.max(t[(i + 1) * w + j], t[i * w + j + 1]);
    let i = 0;
    let j = 0;
    while (i < A.length || j < B.length) {
      if (i < A.length && j < B.length && A[i] === B[j]) {
        i++;
        j++;
      } else if (j < B.length && (i === A.length || t[i * w + j + 1] > t[(i + 1) * w + j])) {
        added++;
        if (lines.length < maxLines) lines.push(`+ ${B[j]}`);
        j++;
      } else {
        removed++;
        if (lines.length < maxLines) lines.push(`- ${A[i]}`);
        i++;
      }
    }
  } else {
    removed = A.length;
    added = B.length;
    for (const l of A.slice(0, maxLines / 2)) lines.push(`- ${l}`);
    for (const l of B.slice(0, maxLines / 2)) lines.push(`+ ${l}`);
  }
  return { added, removed, first_changed_line: s + 1, lines, truncated: added + removed > lines.length };
}

/** Reason a target name is protected (instruction/config/code names AI tools and build tools read), or null. */
function protectedReason(rel, field) {
  try {
    checkWritableName(rel, field);
    return null;
  } catch (err) {
    if (err instanceof ToolError && err.code === "protected_name") return err.message.replace(`${field}: `, "");
    throw err;
  }
}

function planWrite(ctx, step, rel0, content, field) {
  const ifExists = step.if_exists ?? "error";
  const bytes = Buffer.byteLength(content, "utf8");
  if (bytes > ctx.limits.max_file_bytes) throw new ToolError("limit_exceeded", `${field}: ${rel0} would be ${bytes} bytes; the limit is ${ctx.limits.max_file_bytes} bytes per file.`);
  let rel = rel0;
  let st = targetState(ctx, rel, field);
  const op = { op: "write_file", step: step.id, path: rel, mode: "create", status: "planned", bytes, sha256: sha256(content), _content: content };
  const prot = protectedReason(rel, field);
  if (prot) return addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: prot }));
  if (st.isDir) return addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: "a folder is planned at this path" }));
  if (st.exists) {
    if (ifExists === "error") return addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: st.byPlan ? "another operation in this recipe already writes this path" : 'already exists (if_exists: "error")' }));
    if (ifExists === "skip") return addResult(ctx, addOp(ctx, { ...op, status: "skip", reason: st.byPlan ? "written by an earlier operation of this recipe" : 'already exists (if_exists: "skip")' }));
    if (ifExists === "suffix") {
      const free = freeSuffix(ctx, rel, field);
      if (!free) return addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: "no free name up to -99" }));
      rel = free.rel;
      st = free.state;
      op.path = rel;
      op.renamed_from = rel0;
    } else if (ifExists === "overwrite") {
      if (st.byPlan) return addResult(ctx, addOp(ctx, { ...op, mode: "overwrite", status: "conflict", reason: "another operation in this recipe already writes this path" }));
      if (st.size > ctx.limits.max_file_bytes) throw new ToolError("limit_exceeded", `${field}: existing ${rel} is larger than the per-file limit, so it is not compared.`);
      const before = readBytes(st.abs);
      const beforeText = before.toString("utf8");
      op.mode = "overwrite";
      op.before_sha256 = sha256(before);
      op.before_bytes = before.length;
      ctx.sources.set(`target:${pathKey(rel)}`, { path: rel, size: before.length, sha256: op.before_sha256 });
      if (op.before_sha256 === op.sha256) return addResult(ctx, addOp(ctx, { ...op, status: "unchanged", reason: "existing file already has this content" }));
      if (!before.subarray(0, 8000).includes(0)) op.diff = lineDiff(beforeText, content);
    } else if (ifExists === "append") {
      op.mode = "append";
      if (!st.byPlan) {
        if (st.nlink > 1) return addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: "the file has several hard links; appending would change the other copies too" }));
        op.before_bytes = st.size;
        op.before_mtime_ms = st.mtimeMs;
        ctx.sources.set(`target:${pathKey(rel)}`, { path: rel, size: st.size, mtime_ms: st.mtimeMs });
      } else op.after_planned_write = true;
      if (!bytes) return addResult(ctx, addOp(ctx, { ...op, status: "unchanged", reason: "nothing to append" }));
      op.diff = { added: content.split(/\r?\n/).filter((l, i, arr) => i < arr.length - 1 || l !== "").length, removed: 0, lines: content.split(/\r?\n/).slice(0, 20).map((l) => `+ ${l}`) };
      const r = addResult(ctx, addOp(ctx, op));
      ctx.writeBytes += bytes;
      checkWriteBudget(ctx, field);
      return r;
    }
  }
  const folderProblem = planFolders(ctx, step, st, step.create_folders !== false);
  if (folderProblem) return addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: folderProblem }));
  if (op.mode === "create" && !op.diff) op.preview = content.length > 1200 ? content.slice(0, 1200) + "\n…" : content;
  addOp(ctx, op);
  ctx.overlay.set(pathKey(rel), { kind: "file", byPlan: true });
  ctx.writeBytes += bytes;
  checkWriteBudget(ctx, field);
  return addResult(ctx, op);
}

function checkWriteBudget(ctx, field) {
  if (ctx.writeBytes > ctx.limits.max_write_bytes) throw new ToolError("limit_exceeded", `${field}: the recipe would write more than ${ctx.limits.max_write_bytes} bytes in total (limits.max_write_bytes).`);
}

function addResult(ctx, op) {
  return record([["path", op.path], ["from", op.from ?? null], ["operation", op.op], ["mode", op.mode ?? null], ["status", op.status], ["reason", op.reason ?? null]]);
}

function planTransfer(ctx, step, field, rows, kind) {
  const pf = step.path_field ?? "path";
  const base = baseFrame(ctx);
  const ifExists = step.if_exists ?? "error";
  const out = [];
  rows.forEach((row, i) => {
    ctx.tick();
    const raw = getField(row, pf);
    if (typeof raw !== "string" || !raw) throw new ToolError("invalid_input", `${field}: row ${i + 1} has no "${pf}" text field with the file to ${kind === "move_file" ? "move" : "copy"}.`);
    const from = normalizeRel(raw, `${field} (row ${i + 1})`);
    const ovSrc = ctx.overlay.get(pathKey(from));
    const rel0 = renderPath(ctx, step.to, [base, metaFrame(i, rows.length), row], `${field}.to`);
    const op = { op: kind, step: step.id, from, path: rel0, status: "planned" };
    // A file is never moved or copied to a protected name (it stays where it is).
    const prot = protectedReason(rel0, `${field}.to`);
    if (prot) return out.push(addResult(ctx, addOp(ctx, { ...op, status: "skip", reason: prot })));
    if (ovSrc?.kind === "absent") return out.push(addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: "already moved by an earlier operation of this recipe" })));
    if (ovSrc) return out.push(addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: "the source is created by this recipe; only existing files can be moved or copied" })));
    const src = inspectSource(ctx.root, from, `${field} (row ${i + 1})`);
    op.bytes = src.size;
    ctx.sources.set(`src:${pathKey(from)}`, { path: from, size: src.size, mtime_ms: src.mtimeMs });
    if (pathKey(rel0) === pathKey(from)) {
      if (rel0 === from || kind === "copy_file") return out.push(addResult(ctx, addOp(ctx, { ...op, status: kind === "copy_file" ? "conflict" : "unchanged", reason: kind === "copy_file" ? "source and destination are the same file" : "already at this path" })));
      // Case-only rename (for example photo.JPG -> photo.jpg) on a case-insensitive file system.
      addOp(ctx, { ...op, case_only: true });
      ctx.overlay.set(pathKey(rel0), { kind: "file", byPlan: true });
      return out.push(addResult(ctx, op));
    }
    let rel = rel0;
    let st = targetState(ctx, rel, `${field}.to`);
    if (st.isDir) return out.push(addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: "a folder is planned at this path" })));
    if (st.exists) {
      if (ifExists === "error") return out.push(addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: st.byPlan ? "another operation in this recipe already puts a file at this path" : 'destination already exists (if_exists: "error"); existing files are never replaced' })));
      if (ifExists === "skip") return out.push(addResult(ctx, addOp(ctx, { ...op, status: "skip", reason: st.byPlan ? "another operation in this recipe already puts a file at this path" : 'destination already exists (if_exists: "skip")' })));
      const free = freeSuffix(ctx, rel, `${field}.to`);
      if (!free) return out.push(addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: "no free name up to -99" })));
      rel = free.rel;
      st = free.state;
      op.path = rel;
      op.renamed_from = rel0;
    }
    const folderProblem = planFolders(ctx, step, st, step.create_folders !== false);
    if (folderProblem) return out.push(addResult(ctx, addOp(ctx, { ...op, status: "conflict", reason: folderProblem })));
    addOp(ctx, op);
    if (kind === "move_file") ctx.overlay.set(pathKey(from), { kind: "absent", byPlan: true });
    else {
      ctx.writeBytes += src.size;
      checkWriteBudget(ctx, field);
    }
    ctx.overlay.set(pathKey(rel), { kind: "file", byPlan: true });
    out.push(addResult(ctx, op));
  });
  return out;
}

// ---------------------------------------------------------------------------------------------
// Whole recipe
// ---------------------------------------------------------------------------------------------
export function evaluateRecipe(ctx, compiled) {
  const stepInfo = [];
  for (const step of compiled.steps) {
    ctx.tick();
    const field = `${step.id} (${step.type})`;
    const input = step.from && !Array.isArray(step.from) ? ctx.outputs[step.from] : undefined;
    const opsBefore = ctx.ops.length;
    const value = STEPS[step.type](ctx, step, field, input);
    ctx.outputs[step.id] = value;
    stepInfo.push(describe(step, value, ctx.ops.length - opsBefore));
  }
  return stepInfo;
}

function describe(step, v, ops) {
  const d = { id: step.id, type: step.type, output: typeof v === "string" ? "text" : isRows(v) ? "rows" : "value" };
  if (typeof v === "string") d.chars = v.length;
  else if (Array.isArray(v)) {
    d.rows = v.length;
    if (isRows(v)) d.columns = columnsOf(v).slice(0, 40);
  }
  if (step.spec.group === "file") d.operations = ops;
  return d;
}

const previewValue = (v) => {
  if (typeof v === "string") return v.length > 200 ? v.slice(0, 199) + "…" : v;
  if (v === null || typeof v !== "object") return v ?? null;
  const s = JSON.stringify(v);
  return s.length > 200 ? s.slice(0, 199) + "…" : JSON.parse(s);
};

export function previewOf(v, n) {
  if (typeof v === "string") return v.length > 1000 ? v.slice(0, 1000) + "…" : v;
  if (Array.isArray(v)) return v.slice(0, n).map((r) => (isRecord(r) ? Object.fromEntries(Object.keys(r).map((k) => [k, previewValue(r[k])])) : previewValue(r)));
  return previewValue(v);
}

export function planHash(rawRecipe, vars, inputText, ctx) {
  const ops = ctx.ops.map((o) => [o.op, o.path, o.from ?? null, o.mode ?? null, o.status, o.sha256 ?? null, o.bytes ?? null, o.before_sha256 ?? null]);
  const sources = [...ctx.sources.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
  return sha256(JSON.stringify({ v: 1, recipe: sha256(JSON.stringify(rawRecipe)), vars, input: inputText === undefined ? null : sha256(inputText), ops, sources }));
}

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).