/** * saved.ts — resolve `SubagentWorkflow({ name })` to a script on disk. * * A saved workflow is a plain `.js` file whose contents are exactly what * `script` would have carried. Nothing is parsed here: `extractMeta` still runs * over the source at the call site, so a saved file and an inline one fail the * same way on a bad `meta` block. * * Roots mirror `loadCustomAgents` rather than inventing a fourth convention — * project `.pi` is the authority, the shared `.agents` workspace is an extra * read location, and the user's agent dir is the fallback: * * 1. /.pi/workflows/.js * 2. /.agents/workflows/.js * 3. getAgentDir()/workflows/.js (default ~/.pi/agent/workflows) * * Precedence is expressed as first-hit-wins here, not last-write-wins as in the * agent loader, because a name resolves to one file — there is no map to * overwrite. * * Symlinks are rejected through `safeReadFile`, and the name is whitelisted * before it is ever joined to a path: `name` arrives from a model, and * `../../etc/passwd` must not become a readable workflow. * * ## Not every `.js` in the folder is a workflow * * These are ordinary directories. `.agents/workflows/` is shared across tools * and the user's agent dir is theirs to fill; either may hold a build artifact, * a config, or a scratch script. A file is only treated as a workflow if it * carries the `export const meta =` declaration every workflow opens with. * * Nothing is ever executed to decide this — the check is a regex over the * source, and even the real parse only evaluates the `meta` object literal in * an empty vm. What the filter buys is honesty: a listing that offers `utils.js` * as a runnable workflow invites the model to try it, and naming it should say * "that is not a workflow" rather than produce a parser error about a block the * author never intended to write. */ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; import { isAbsolute, join } from "node:path"; import { resolveAgentDir } from "../home-paths.js"; import { isSymlink, isUnsafeName, safeReadFile } from "../memory.js"; import { isPackageResourceExcluded, packageWorkflowDirs, packageWorkflowFiles } from "../package-resources.js"; import { hasMetaDeclaration } from "./meta.js"; import { MAX_SCRIPT_LENGTH } from "./runtime.js"; /** Extension a saved workflow file carries. */ const WORKFLOW_EXTENSION = ".js"; /** * The roots a `name` is looked up in, highest priority first. * * Directories declared by installed pi packages come last, so a project, shared * workspace or personal script always wins the name. That is the same tier * package-provided agents get, and the same tier pi gives package-provided * skills — a package offers a workflow, it never takes a name away from you. * * The `packageWorkflows` gate and pi's project-trust answer are session state in * package-resources.ts rather than parameters here, so a gate set in `/agents` * reaches this without an options bag travelling through `resolveWorkflowScript`, * `resolveWorkflowSource` and `readSavedWorkflow` purely to be consulted once. */ export function savedWorkflowRoots(cwd: string, homeDir?: string): string[] { return [ join(cwd, ".pi", "workflows"), join(cwd, ".agents", "workflows"), join(resolveAgentDir(homeDir), "workflows"), ...packageWorkflowDirs(cwd, { homeDir }), ]; } export type SavedWorkflow = | { ok: true; script: string; path: string } | { ok: false; message: string }; /** * Read the saved workflow called `name`. * * Failure carries the roots that were searched and, when there are any, the * names that do exist — a model that guessed the name can correct itself from * the error instead of spending a turn asking. */ export function readSavedWorkflow(name: string, cwd: string, homeDir?: string): SavedWorkflow { const trimmed = name.trim(); if (isUnsafeName(trimmed)) { return { ok: false, message: `"${name}" is not a usable workflow name. Use letters, digits, dots, hyphens and underscores only ` + "— a path is what `scriptPath` is for.", }; } const roots = savedWorkflowRoots(cwd, homeDir); for (const root of roots) { if (isSymlink(root)) continue; // reject a symlinked root entirely, as skill-loader does const path = join(root, `${trimmed}${WORKFLOW_EXTENSION}`); // A `!` entry in the declaring package's manifest. Only ever true for a path // under a package root, so the local roots pay one set lookup for it. if (isPackageResourceExcluded(path, cwd, "workflows", { homeDir })) continue; const script = safeReadFile(path); if (script === undefined) continue; // Found the file, so stop looking — a shadowing name that turns out not to // be a workflow is worth reporting, not worth silently reaching past. if (!hasMetaDeclaration(script)) { return { ok: false, message: `"${path}" is not a workflow script — it has no \`export const meta = { name, description }\` ` + "declaration. Nothing was run.", }; } return { ok: true, script, path }; } // Last: a package that declared an individual file rather than a directory. // It carries no root to look a name up in, so it is matched by name here // instead — after every root, which keeps package scripts lowest-precedence. const declared = packageWorkflowFiles(cwd, { homeDir }).get(trimmed); if (declared !== undefined) { const script = safeReadFile(declared); if (script !== undefined) { if (!hasMetaDeclaration(script)) { return { ok: false, message: `"${declared}" is not a workflow script — it has no \`export const meta = { name, description }\` ` + "declaration. Nothing was run.", }; } return { ok: true, script, path: declared }; } } const known = listSavedWorkflows(cwd, homeDir); return { ok: false, message: `No saved workflow named "${trimmed}". Looked in: ${roots.join(", ")}. ` + (known.length > 0 ? `Available: ${known.join(", ")}.` : "Save one as `.js` in one of those directories, or pass `script`/`scriptPath` instead."), }; } /** * Resolve a reference — a saved name, or a path — to source. * * The one place that decides what a reference means, so the tool's `name` / * `scriptPath` parameters and a script's nested `workflow()` cannot drift apart * on precedence or on what counts as a workflow. */ export function resolveWorkflowSource( ref: { name?: string; scriptPath?: string }, cwd: string, homeDir?: string, ): SavedWorkflow { const path = ref.scriptPath?.trim(); if (path !== undefined && path !== "") { const resolved = isAbsolute(path) ? path : join(cwd, path); try { return { ok: true, script: readFileSync(resolved, "utf-8"), path: resolved }; } catch (err) { // `readFileSync` only ever throws Node's own `Error`s. return { ok: false, message: `Could not read workflow script "${resolved}": ${(err as Error).message}` }; } } const name = ref.name?.trim(); if (name !== undefined && name !== "") return readSavedWorkflow(name, cwd, homeDir); return { ok: false, message: "A workflow reference needs a `name` or a `scriptPath`." }; } /** Every saved workflow name, de-duplicated across roots and sorted. */ export function listSavedWorkflows(cwd: string, homeDir?: string): string[] { const names = new Set(); for (const root of savedWorkflowRoots(cwd, homeDir)) { if (!existsSync(root) || isSymlink(root)) continue; let entries: string[]; try { entries = readdirSync(root); } catch { continue; // an unreadable root is not worth failing a lookup over } for (const entry of entries) { if (!entry.endsWith(WORKFLOW_EXTENSION)) continue; const name = entry.slice(0, -WORKFLOW_EXTENSION.length); if (isUnsafeName(name)) continue; const path = join(root, entry); if (isPackageResourceExcluded(path, cwd, "workflows", { homeDir })) continue; if (isWorkflowFile(path)) names.add(name); } } for (const [name, path] of packageWorkflowFiles(cwd, { homeDir })) { if (isUnsafeName(name)) continue; if (isWorkflowFile(path)) names.add(name); } return [...names].sort(); } /** * Whether the file at `path` is a workflow rather than some other script. * * Size-guarded before reading: the listing runs over a whole directory, and a * file too large to be a workflow at all should not be pulled into memory just * to check its first line. */ function isWorkflowFile(path: string): boolean { try { if (statSync(path).size > MAX_SCRIPT_LENGTH) return false; } catch { return false; } const source = safeReadFile(path); return source !== undefined && hasMetaDeclaration(source); } /** * Resolve which source a `SubagentWorkflow` call runs. * * `scriptPath` wins over `script`, which wins over `name` — Claude Code's * order — and at least one is required: a call with none is a mistake worth * naming rather than an empty run. Lives beside {@link resolveWorkflowSource} * because that is the function it defers to once precedence is settled, so the * two cannot disagree about what a reference means. */ export function resolveWorkflowScript( params: { script?: string; scriptPath?: string; name?: string }, cwd: string, homeDir?: string, ): { ok: true; script: string; scriptPath?: string } | { ok: false; message: string } { const path = params.scriptPath?.trim(); if (path !== undefined && path !== "") { const resolved = resolveWorkflowSource({ scriptPath: path }, cwd, homeDir); return resolved.ok ? { ok: true, script: resolved.script, scriptPath: resolved.path } : resolved; } const script = params.script; if (script !== undefined && script.trim() !== "") return { ok: true, script }; // A saved workflow is the same source by another route, so it reports its // file as `scriptPath`: the "edit the file and re-run" loop then works on a // named workflow without the author having to find where it lives. Shared // with a script's nested `workflow()`, so one definition decides what a // reference means. const name = params.name?.trim(); if (name !== undefined && name !== "") { const saved = resolveWorkflowSource({ name }, cwd, homeDir); return saved.ok ? { ok: true, script: saved.script, scriptPath: saved.path } : saved; } const known = listSavedWorkflows(cwd, homeDir); return { ok: false, message: "Provide `script` (inline source), `scriptPath` (a file to read), or `name` (a saved workflow). " + "`scriptPath` takes precedence, then `script`, then `name`." + (known.length > 0 ? ` Saved workflows: ${known.join(", ")}.` : ""), }; }