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 · claude-code

Archive SHA-256 85be31abe46644f344964c8b1d4b56f6d7218b34a58fd31ffb075c5e5b587476 · 89.5 KB · built Dec 1, 2026

src/recipe.js

// Recipe format and static validation (no file access). A recipe is JSON:
//   { "name": "...", "timezone": "Europe/London", "vars": {...}, "limits": {...}, "steps": [ {id, type, ...}, ... ] }
// Steps run in order; a step reads the output of an earlier step through "from" (default: the step
// before it). Only the built-in step types below exist: there is no shell, network, delete or code step.
import { ToolError } from "./errors.js";
import { normalizeRel } from "./fsguard.js";
import { parseTemplate, templateNames } from "./template.js";
import { compileGlob } from "./glob.js";
import { validTimezone } from "./values.js";

export const HARD_LIMITS = {
  max_file_bytes: 10 * 1024 * 1024,
  max_total_read_bytes: 50 * 1024 * 1024,
  max_rows: 100_000,
  max_files: 10_000,
  max_operations: 1_000,
  max_write_bytes: 50 * 1024 * 1024,
  max_output_chars: 5_000_000,
  timeout_seconds: 120,
};
export const DEFAULT_LIMITS = {
  max_file_bytes: 10 * 1024 * 1024,
  max_total_read_bytes: 50 * 1024 * 1024,
  max_rows: 100_000,
  max_files: 5_000,
  max_operations: 500,
  max_write_bytes: 20 * 1024 * 1024,
  max_output_chars: 2_000_000,
  timeout_seconds: 30,
};
export const MAX_RECIPE_CHARS = 512 * 1024;
export const MAX_STEPS = 50;

const ID_RE = /^[a-z][a-z0-9_]{0,39}$/;
const VAR_RE = /^[A-Za-z_][A-Za-z0-9_]{0,39}$/;
const BLOCKED_FIELDS = new Set(["__proto__", "constructor", "prototype"]);

export const WHERE_OPS = ["eq", "ne", "gt", "gte", "lt", "lte", "contains", "not_contains", "starts_with", "ends_with", "in", "not_in", "empty", "not_empty", "like", "not_like"];
export const METRIC_OPS = ["count", "count_distinct", "sum", "avg", "min", "max", "first", "last", "values"];
export const CAST_TYPES = ["number", "integer", "string", "boolean", "date"];
export const COMPARE_TYPES = ["auto", "number", "string", "date"];
export const ESCAPES = ["html", "markdown", "none"];

// group: source | transform | format | file. in: what "from" must produce. out: what the step produces.
// props: allowed properties ("from" is added for steps with an input).
export const STEP_TYPES = {
  read_csv: { group: "source", out: "rows", props: { path: "read_path", glob: "glob", delimiter: ["auto", ",", ";", "tab", "|"], header: "bool" }, one: ["path", "glob"], doc: "Rows from a CSV file (or every file matching glob, with a _file column)." },
  read_json: { group: "source", out: "value", props: { path: "read_path", glob: "glob", pointer: "pointer" }, one: ["path", "glob"], doc: "A JSON file's value (optionally the part at a JSON pointer such as /items); with glob, one row per file or array item." },
  read_markdown: { group: "source", out: "rows", props: { path: "read_path", glob: "glob" }, one: ["path", "glob"], doc: "One row per Markdown file: path, name, title, front_matter, headings, tasks, word_count, text." },
  read_text: { group: "source", out: "text", props: { path: "read_path" }, required: ["path"], doc: "A text file as text." },
  list_files: { group: "source", out: "rows", props: { folder: "folder", pattern: "glob_rel", include_folders: "bool" }, doc: "Files (path, name, stem, ext, folder, size, modified) under folder matching pattern (default *; use **/ for subfolders). Hidden entries and links are skipped." },
  read_input: { group: "source", out: "by_format", props: { format: ["text", "csv", "json", "markdown"], delimiter: ["auto", ",", ";", "tab", "|"], header: "bool", pointer: "pointer" }, required: ["format"], doc: "The tool call's input_text, read as text, CSV rows, JSON or a Markdown row." },
  literal: { group: "source", out: "value", props: { value: "any" }, required: ["value"], doc: "A fixed JSON value written in the recipe (a list of objects is a row table)." },

  filter: { group: "transform", in: "rows", out: "rows", props: { where: "where", match: ["all", "any"] }, required: ["where"], doc: "Keeps rows matching the conditions." },
  map: { group: "transform", in: "rows", out: "rows", props: { rename: "rename", set: "set", cast: "cast", pick: "fields", omit: "fields" }, doc: "Renames, adds (templates), converts, keeps or drops fields (applied in that order)." },
  sort: { group: "transform", in: "rows", out: "rows", props: { by: "sort_by" }, required: ["by"], doc: "Stable sort by one or more fields; empty values last." },
  dedupe: { group: "transform", in: "rows", out: "rows", props: { by: "fields", keep: ["first", "last"], ignore_case: "bool" }, doc: "Removes duplicate rows (by the given fields, or whole rows)." },
  limit: { group: "transform", in: "rows", out: "rows", props: { count: "count", offset: "count" }, required: ["count"], doc: "Keeps count rows after offset." },
  summarize: { group: "transform", in: "rows", out: "rows", props: { group_by: "fields", metrics: "metrics" }, required: ["metrics"], doc: "One row per group with count, count_distinct, sum, avg, min, max, first, last or values." },
  join: { group: "transform", in: "rows", out: "rows", props: { with: "step", on: "field", left_on: "field", right_on: "field", how: ["left", "inner"], fields: "fields", prefix: "prefix", ignore_case: "bool" }, required: ["with"], doc: "Adds fields from the first matching row of another step (left or inner join on one key)." },
  concat: { group: "transform", in: "rows", out: "rows", props: {}, fromList: true, doc: "Appends the rows of several steps (from: [ids])." },
  unnest: { group: "transform", in: "rows", out: "rows", props: { field: "field", as: "field", keep_empty: "bool" }, required: ["field"], doc: "One row per item of a list field (for example the tasks of read_markdown)." },

  template: { group: "format", in: "any", out: "text", props: { template: "template", escape: ESCAPES }, required: ["template"], optionalFrom: true, doc: "Text from a Mustache-like template. Context: rows/count (rows input), data (other values), text, vars, run, steps." },
  to_csv: { group: "format", in: "rows", out: "text", props: { columns: "fields", delimiter: [",", ";", "tab", "|"], header: "bool", protect_formulas: "bool" }, doc: "CSV text; cells starting with = + - @ get a ' prefix unless protect_formulas is false." },
  to_json: { group: "format", in: "any", out: "text", props: { pretty: "bool" }, doc: "JSON text." },
  to_markdown_table: { group: "format", in: "rows", out: "text", props: { columns: "fields", headers: "labels" }, doc: "A Markdown table (cell text escaped)." },

  write_file: { group: "file", in: "text", out: "rows", props: { path: "out_path", content: "template", for_each: "step", if_exists: ["error", "skip", "overwrite", "append", "suffix"], create_folders: "bool", escape: ESCAPES }, required: ["path"], optionalFrom: true, doc: "Writes text (from a text step, or a content template; with for_each, one file per row). if_exists: error (default), skip, overwrite, append, suffix." },
  move_files: { group: "file", in: "rows", out: "rows", props: { to: "out_path", path_field: "field", if_exists: ["error", "skip", "suffix"], create_folders: "bool" }, required: ["to"], doc: "Moves (renames) each row's file (path_field, default path) to the to template. Never replaces an existing file." },
  copy_files: { group: "file", in: "rows", out: "rows", props: { to: "out_path", path_field: "field", if_exists: ["error", "skip", "suffix"], create_folders: "bool" }, required: ["to"], doc: "Copies each row's file to the to template. Never replaces an existing file." },
};
export const STEP_TYPE_NAMES = Object.keys(STEP_TYPES);
const FORBIDDEN_HINT = "There are no shell, script, network, download, delete or code steps.";

const typeName = (v) => (Array.isArray(v) ? "array" : v === null ? "null" : typeof v);
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);

/**
 * Validates a recipe without touching files. Returns { errors: [{path, message}], warnings, steps, compiled }.
 * compiled is a normalised copy (paths normalised, templates parsed) used by the engine; only valid if errors is empty.
 */
export function checkRecipe(recipe) {
  const errors = [];
  const warnings = [];
  const err = (path, message) => {
    errors.push({ path, message });
    return undefined;
  };
  if (!isObj(recipe)) {
    err("recipe", "must be a JSON object with a steps array.");
    return { errors, warnings, steps: [], compiled: null };
  }
  let size = 0;
  try {
    size = JSON.stringify(recipe).length;
  } catch {
    err("recipe", "is not plain JSON.");
  }
  if (size > MAX_RECIPE_CHARS) err("recipe", `is ${size} characters; the limit is ${MAX_RECIPE_CHARS}.`);
  const allowedTop = ["recipe_version", "name", "description", "timezone", "vars", "limits", "steps"];
  for (const k of Object.keys(recipe)) if (!allowedTop.includes(k)) err(`recipe.${k}`, `unknown property (allowed: ${allowedTop.join(", ")}).`);
  if (recipe.recipe_version !== undefined && recipe.recipe_version !== 1) err("recipe.recipe_version", "must be 1.");
  if (recipe.name !== undefined && (typeof recipe.name !== "string" || recipe.name.length > 120)) err("recipe.name", "must be a string of at most 120 characters.");
  if (recipe.description !== undefined && (typeof recipe.description !== "string" || recipe.description.length > 2000)) err("recipe.description", "must be a string of at most 2000 characters.");
  const timezone = recipe.timezone ?? "UTC";
  if (typeof timezone !== "string" || !validTimezone(timezone)) err("recipe.timezone", `"${String(timezone).slice(0, 60)}" is not an IANA time zone (for example Europe/London or America/Toronto).`);
  const vars = {};
  if (recipe.vars !== undefined) {
    if (!isObj(recipe.vars)) err("recipe.vars", "must be an object.");
    else checkVars(recipe.vars, "recipe.vars", err, vars);
  }
  const limits = { ...DEFAULT_LIMITS };
  if (recipe.limits !== undefined) {
    if (!isObj(recipe.limits)) err("recipe.limits", "must be an object.");
    else
      for (const [k, v] of Object.entries(recipe.limits)) {
        if (!(k in HARD_LIMITS)) err(`recipe.limits.${k}`, `unknown limit (allowed: ${Object.keys(HARD_LIMITS).join(", ")}).`);
        else if (!Number.isInteger(v) || v < 1 || v > HARD_LIMITS[k]) err(`recipe.limits.${k}`, `must be a whole number from 1 to ${HARD_LIMITS[k]}.`);
        else limits[k] = v;
      }
  }
  const steps = [];
  const compiled = { name: typeof recipe.name === "string" && recipe.name.trim() ? recipe.name.trim() : "Untitled recipe", description: recipe.description ?? "", timezone: typeof timezone === "string" ? timezone : "UTC", vars, limits, steps: [] };
  if (!Array.isArray(recipe.steps) || !recipe.steps.length) {
    err("recipe.steps", "must be a non-empty array of steps.");
    return { errors, warnings, steps, compiled };
  }
  if (recipe.steps.length > MAX_STEPS) err("recipe.steps", `has ${recipe.steps.length} steps; the limit is ${MAX_STEPS}.`);
  const kinds = new Map(); // id -> output kind
  const ids = [];
  recipe.steps.slice(0, MAX_STEPS).forEach((raw, i) => {
    const at = `steps[${i}]`;
    if (!isObj(raw)) return err(at, "must be an object with id and type.");
    const label = typeof raw.id === "string" ? `${at} (${raw.id})` : at;
    const spec = Object.hasOwn(STEP_TYPES, raw.type) ? STEP_TYPES[raw.type] : null;
    if (typeof raw.type !== "string") return err(`${label}.type`, `is required (one of: ${STEP_TYPE_NAMES.join(", ")}).`);
    if (!spec) return err(`${label}.type`, `unknown step type "${raw.type.slice(0, 40)}". Allowed: ${STEP_TYPE_NAMES.join(", ")}. ${FORBIDDEN_HINT}`);
    if (typeof raw.id !== "string" || !ID_RE.test(raw.id)) return err(`${label}.id`, "is required: lowercase letters, digits and _, starting with a letter (at most 40).");
    if (kinds.has(raw.id)) return err(`${label}.id`, `"${raw.id}" is used by an earlier step; ids must be unique.`);
    const step = { id: raw.id, type: raw.type, spec, index: i };
    const hasInput = !!spec.in;
    const allowed = ["id", "type", "note", ...Object.keys(spec.props), ...(hasInput ? ["from"] : [])];
    for (const k of Object.keys(raw)) if (!allowed.includes(k)) err(`${label}.${k}`, `unknown property for ${raw.type} (allowed: ${allowed.join(", ")}).`);
    for (const r of spec.required ?? []) if (raw[r] === undefined) err(`${label}.${r}`, `is required for ${raw.type}.`);
    if (spec.one) {
      const given = spec.one.filter((k) => raw[k] !== undefined);
      if (given.length !== 1) err(label, `give exactly one of ${spec.one.join(" or ")}.`);
    }
    // from
    if (hasInput) {
      if (spec.fromList) {
        if (!Array.isArray(raw.from) || raw.from.length < 2) err(`${label}.from`, "must list at least two earlier step ids.");
        else {
          step.from = [];
          for (const f of raw.from) {
            if (!kinds.has(f)) err(`${label}.from`, `"${String(f).slice(0, 40)}" is not an earlier step.`);
            else if (!kindAccepts("rows", kinds.get(f))) err(`${label}.from`, `${f} produces ${kinds.get(f)}, not rows.`);
            else step.from.push(f);
          }
        }
      } else {
        let from = raw.from;
        if (from === undefined && !(raw.type === "write_file" && (raw.content !== undefined || raw.for_each !== undefined))) from = ids.length ? ids[ids.length - 1] : null;
        if (raw.type === "write_file" && raw.content !== undefined && raw.from !== undefined) err(label, "give either from (a text step) or content (a template), not both.");
        if (raw.type === "write_file" && raw.for_each !== undefined && raw.from !== undefined) err(label, "for_each writes one file per row from the content template; do not combine it with from.");
        if (raw.type === "write_file" && raw.for_each !== undefined && raw.content === undefined) err(`${label}.content`, "is required with for_each.");
        if (from === null || from === undefined) {
          if (!spec.optionalFrom) err(`${label}.from`, `${raw.type} needs an earlier step to read from.`);
          else if (raw.type === "write_file" && raw.content === undefined) err(label, "write_file needs from (a text step) or content (a template).");
          step.from = null;
        } else if (typeof from !== "string" || !kinds.has(from)) err(`${label}.from`, `"${String(from).slice(0, 40)}" is not an earlier step (steps can only read from steps before them).`);
        else if (!kindAccepts(spec.in, kinds.get(from))) err(`${label}.from`, `${raw.type} needs ${spec.in} but ${from} produces ${kinds.get(from)}${spec.in === "text" ? " (turn rows into text with to_csv, to_json, to_markdown_table or template first)" : ""}.`);
        else step.from = from;
      }
    }
    // properties
    for (const [k, t] of Object.entries(spec.props)) {
      if (raw[k] === undefined) continue;
      const v = checkProp(t, raw[k], `${label}.${k}`, err, kinds, raw);
      if (v !== undefined) step[k] = v;
    }
    if (raw.type === "join" && raw.on === undefined && (raw.left_on === undefined || raw.right_on === undefined)) err(label, "join needs on (same field name on both sides) or left_on and right_on.");
    if (raw.type === "join" && step.with && !kindAccepts("rows", kinds.get(step.with))) err(`${label}.with`, `${step.with} produces ${kinds.get(step.with)}, not rows.`);
    if (raw.type === "write_file" && step.for_each && !kindAccepts("rows", kinds.get(step.for_each))) err(`${label}.for_each`, `${step.for_each} produces ${kinds.get(step.for_each)}, not rows.`);
    if (raw.type === "write_file" && raw.if_exists === "append" && raw.for_each !== undefined) warnings.push(`${label}: append with for_each adds to each row's file.`);
    if (raw.type === "write_file" && raw.if_exists === "overwrite") warnings.push(`${label}: if_exists "overwrite" replaces existing files (no copy is kept); the plan shows a diff first.`);
    let out = spec.out;
    if (out === "by_format") out = raw.format === "text" ? "text" : raw.format === "json" ? "value" : "rows";
    kinds.set(raw.id, out);
    ids.push(raw.id);
    step.out = out;
    compiled.steps.push(step);
    steps.push({ id: raw.id, type: raw.type, group: spec.group, from: step.from ?? null, output: out, reads: readsOf(step), writes: writesOf(step) });
  });
  if (!compiled.steps.some((s) => s.spec.group === "file")) warnings.push("The recipe has no write_file, move_files or copy_files step, so running it changes no files.");
  return { errors, warnings, steps, compiled };
}

function kindAccepts(want, got) {
  if (want === "any") return true;
  if (got === "value" || got === "any") return want === "rows" || want === "value";
  return want === got;
}

function readsOf(step) {
  const out = [];
  if (step.path && step.spec.group === "source") out.push(step.path.text ?? step.path);
  if (step.glob) out.push(step.glob.pattern);
  if (step.type === "list_files") out.push(`${step.folder ?? "."}/${step.pattern ?? "*"}`.replace(/^\.\//, ""));
  return out;
}

function writesOf(step) {
  if (step.type === "write_file") return [step.path.text];
  if (step.type === "move_files" || step.type === "copy_files") return [step.to.text];
  return [];
}

function checkVars(obj, at, err, into) {
  for (const [k, v] of Object.entries(obj)) {
    if (!VAR_RE.test(k)) err(`${at}.${k}`, "variable names use letters, digits and _ (at most 40, not starting with a digit).");
    else if (!["string", "number", "boolean"].includes(typeof v) || (typeof v === "string" && v.length > 2000)) err(`${at}.${k}`, "must be a string (at most 2000 characters), number or boolean.");
    else into[k] = v;
  }
}

export function checkInputVars(vars) {
  const errors = [];
  const out = {};
  if (vars !== undefined) checkVars(vars, "vars", (path, message) => errors.push({ path, message }), out);
  return { errors, vars: out };
}

function fieldName(v, at, err) {
  if (typeof v !== "string" || !v.length || v.length > 100) return err(at, "must be a field name (1 to 100 characters).");
  if (v.split(".").some((p) => BLOCKED_FIELDS.has(p))) return err(at, `"${v}" is not allowed as a field name.`);
  return v;
}

function templ(v, at, err, kinds) {
  if (typeof v !== "string") return err(at, `must be a string, got ${typeName(v)}.`);
  let ast;
  try {
    ast = parseTemplate(v, at);
  } catch (e) {
    return err(at, e.message.replace(`${at}: `, ""));
  }
  // {{steps.<id>}} may only name steps that run earlier.
  for (const name of templateNames(ast)) {
    const m = /^steps\.([^.]+)/.exec(name);
    if (m && kinds && !kinds.has(m[1])) err(at, `{{${name}}} refers to step "${m[1]}", which is not an earlier step.`);
  }
  return { text: v, ast, templated: v.includes("{{") };
}

function checkProp(t, v, at, err, kinds, raw) {
  if (Array.isArray(t)) return t.includes(v) ? v : err(at, `must be one of ${t.map((x) => JSON.stringify(x)).join(", ")}.`);
  switch (t) {
    case "bool":
      return typeof v === "boolean" ? v : err(at, "must be true or false.");
    case "count":
      return Number.isInteger(v) && v >= 0 && v <= HARD_LIMITS.max_rows ? v : err(at, `must be a whole number from 0 to ${HARD_LIMITS.max_rows}.`);
    case "any":
      return v;
    case "prefix":
      return typeof v === "string" && v.length <= 40 && !BLOCKED_FIELDS.has(v) ? v : err(at, "must be a string of at most 40 characters.");
    case "pointer":
      return typeof v === "string" && (v === "" || v.startsWith("/")) && v.length <= 400 ? v : err(at, 'must be a JSON pointer such as "/items" (or "" for the whole document).');
    case "field":
      return fieldName(v, at, err);
    case "fields":
      if (!Array.isArray(v) || v.length > 200) return err(at, "must be an array of field names.");
      return v.map((x, i) => fieldName(x, `${at}[${i}]`, err));
    case "labels":
    case "rename":
      if (!isObj(v)) return err(at, "must be an object of field names.");
      for (const [k, x] of Object.entries(v)) {
        fieldName(k, `${at}.${k}`, err);
        if (typeof x !== "string" || !x) err(`${at}.${k}`, "must be a non-empty string.");
        else if (t === "rename") fieldName(x, `${at}.${k}`, err);
      }
      return v;
    case "set": {
      if (!isObj(v)) return err(at, 'must be an object of field: template (for example {"month": "{{date | date:\\"YYYY-MM\\"}}"}).');
      const out = [];
      for (const [k, x] of Object.entries(v)) {
        if (fieldName(k, `${at}.${k}`, err) === undefined) continue;
        const tp = templ(x, `${at}.${k}`, err, kinds);
        if (tp) out.push([k, tp]);
      }
      return out;
    }
    case "cast":
      if (!isObj(v)) return err(at, `must be an object of field: type (${CAST_TYPES.join(", ")}).`);
      for (const [k, x] of Object.entries(v)) {
        fieldName(k, `${at}.${k}`, err);
        if (!CAST_TYPES.includes(x)) err(`${at}.${k}`, `must be one of ${CAST_TYPES.join(", ")}.`);
      }
      return v;
    case "template":
      return templ(v, at, err, kinds);
    case "step":
      if (typeof v !== "string" || !kinds.has(v)) return err(at, `"${String(v).slice(0, 40)}" is not an earlier step.`);
      return v;
    case "where": {
      if (!Array.isArray(v) || !v.length || v.length > 50) return err(at, "must be an array of 1 to 50 conditions like {\"field\": \"status\", \"op\": \"eq\", \"value\": \"paid\"}.");
      return v.map((c, i) => {
        const a = `${at}[${i}]`;
        if (!isObj(c)) return err(a, "must be an object with field and op.");
        for (const k of Object.keys(c)) if (!["field", "op", "value", "type", "ignore_case"].includes(k)) err(`${a}.${k}`, "unknown property (allowed: field, op, value, type, ignore_case).");
        const field = fieldName(c.field, `${a}.field`, err);
        if (!WHERE_OPS.includes(c.op)) err(`${a}.op`, `must be one of ${WHERE_OPS.join(", ")}.`);
        if (c.type !== undefined && !COMPARE_TYPES.includes(c.type)) err(`${a}.type`, `must be one of ${COMPARE_TYPES.join(", ")}.`);
        if (c.ignore_case !== undefined && typeof c.ignore_case !== "boolean") err(`${a}.ignore_case`, "must be true or false.");
        const needsValue = !["empty", "not_empty"].includes(c.op);
        if (needsValue && c.value === undefined) err(`${a}.value`, `is required for op ${c.op}.`);
        if ((c.op === "in" || c.op === "not_in") && !Array.isArray(c.value)) err(`${a}.value`, `must be an array for op ${c.op}.`);
        if (c.value !== undefined && !(Array.isArray(c.value) ? c.value.every((x) => ["string", "number", "boolean"].includes(typeof x)) : ["string", "number", "boolean"].includes(typeof c.value))) err(`${a}.value`, "must be a string, number, boolean or an array of them.");
        const value = typeof c.value === "string" && c.value.includes("{{") ? templ(c.value, `${a}.value`, err, kinds) : c.value;
        return { field, op: c.op, value, type: c.type ?? "auto", ignore_case: c.ignore_case === true };
      });
    }
    case "sort_by": {
      const list = typeof v === "string" ? [v] : v;
      if (!Array.isArray(list) || !list.length || list.length > 10) return err(at, 'must be a field name, "-field" for descending, or an array of them / of {field, order, type}.');
      return list.map((b, i) => {
        const a = `${at}[${i}]`;
        if (typeof b === "string") {
          const desc = b.startsWith("-");
          return { field: fieldName(desc ? b.slice(1) : b, a, err), order: desc ? "desc" : "asc", type: "auto" };
        }
        if (!isObj(b)) return err(a, "must be a field name or {field, order, type}.");
        if (b.order !== undefined && !["asc", "desc"].includes(b.order)) err(`${a}.order`, 'must be "asc" or "desc".');
        if (b.type !== undefined && !COMPARE_TYPES.includes(b.type)) err(`${a}.type`, `must be one of ${COMPARE_TYPES.join(", ")}.`);
        return { field: fieldName(b.field, `${a}.field`, err), order: b.order ?? "asc", type: b.type ?? "auto" };
      });
    }
    case "metrics": {
      if (!Array.isArray(v) || !v.length || v.length > 50) return err(at, 'must be an array like [{"op": "count", "as": "orders"}, {"op": "sum", "field": "amount", "as": "total"}].');
      const names = new Set();
      return v.map((m, i) => {
        const a = `${at}[${i}]`;
        if (!isObj(m)) return err(a, "must be an object with op.");
        if (!METRIC_OPS.includes(m.op)) err(`${a}.op`, `must be one of ${METRIC_OPS.join(", ")}.`);
        if (m.op !== "count" && m.field === undefined) err(`${a}.field`, `is required for ${m.op}.`);
        const field = m.field === undefined ? undefined : fieldName(m.field, `${a}.field`, err);
        const as = m.as === undefined ? (m.op === "count" ? "count" : `${m.op}_${m.field}`) : fieldName(m.as, `${a}.as`, err);
        if (as !== undefined && names.has(as)) err(`${a}.as`, `"${as}" is used by another metric.`);
        names.add(as);
        return { op: m.op, field, as };
      });
    }
    case "read_path": {
      if (typeof v !== "string") return err(at, "must be a path relative to the workspace.");
      if (v.includes("{{")) return templ(v, at, err, kinds);
      try {
        return normalizeRel(v, at);
      } catch (e) {
        return err(at, e.message.replace(`${at}: `, ""));
      }
    }
    case "folder":
      if (typeof v !== "string") return err(at, "must be a folder path relative to the workspace.");
      try {
        return normalizeRel(v, at, { allowRoot: true });
      } catch (e) {
        return err(at, e.message.replace(`${at}: `, ""));
      }
    case "glob":
    case "glob_rel":
      if (typeof v !== "string") return err(at, "must be a glob pattern such as exports/*.csv.");
      try {
        const n = normalizeRel(v, at, { glob: true });
        if (t === "glob_rel") return n;
        return compileGlob(n, at);
      } catch (e) {
        return err(at, e.message.replace(`${at}: `, ""));
      }
    case "out_path": {
      const tp = templ(v, at, err, kinds);
      if (!tp) return undefined;
      if (!tp.templated) {
        try {
          normalizeRel(v, at);
        } catch (e) {
          return err(at, e.message.replace(`${at}: `, ""));
        }
      } else if (/^\s*(?:[\\/]|[A-Za-z]:)/.test(v)) err(at, "must be relative to the workspace (no leading / or drive letter).");
      else if (/(^|[\\/])\.\.([\\/]|$)/.test(v)) err(at, 'must not contain "..".');
      void raw;
      return tp;
    }
    default:
      return err(at, "unsupported property.");
  }
}

/** Throws ToolError("invalid_recipe") listing the problems. */
export function compileOrThrow(recipe) {
  const r = checkRecipe(recipe);
  if (r.errors.length) {
    const list = r.errors.slice(0, 20).map((e) => `${e.path}: ${e.message}`).join("; ");
    throw new ToolError("invalid_recipe", `The recipe is not valid (${r.errors.length} problem${r.errors.length === 1 ? "" : "s"}): ${list}${r.errors.length > 20 ? "; ..." : ""}. Run validate_recipe for the full list.`, r.errors);
  }
  return r;
}

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).