@sema-agent/core
Version:
Stateless, task-oriented AI agent core
778 lines (777 loc) • 42.3 kB
JavaScript
import { lstatSync, readFileSync, readdirSync, statSync } from "node:fs";
import { basename, dirname, join, resolve as resolvePath } from "node:path";
import { physicalPathOfExisting } from "../core/physical-path.js";
import { atomicWriteFile, ensureDir, writeThenLink } from "../stores/file/fs-atomic.js";
import { canonicalJsonStringify, textContentHashOf } from "../core/canonical-json.js";
import { asThrownError, codedRefusal, thrownText } from "../core/thrown-value.js";
import { strayMembersOf } from "../core/own-property-receipt.js";
import { journalKeepsLaunches } from "../core/workflow-journal-store.js";
import { parseWorkflowMeta, parseWorkflowRequires, readWorkflowMetaName } from "./workflow-meta.js";
export const WORKFLOW_SOURCES = Object.freeze(["deployment", "project", "user", "builtin"]);
export const WORKFLOW_SAVE_LAYERS = Object.freeze(["project", "user"]);
export const WORKFLOW_CATALOG_ENTRY_DOORS = Object.freeze({ workflow: "workflow_tool", preset: "workflow_tool", team: "run" });
export const WORKFLOW_CATALOG_MAX_FILE_BYTES = 1_000_000;
function overCatalogFileLimit(bytes) {
return bytes > WORKFLOW_CATALOG_MAX_FILE_BYTES ? `${bytes} bytes, over the ${WORKFLOW_CATALOG_MAX_FILE_BYTES}-byte limit` : undefined;
}
export function isWorkflowName(name) {
return typeof name === "string" && /^[A-Za-z0-9._-]{1,120}$/.test(name) && !name.startsWith(".");
}
const NOTICE_CODES = {
invalid_meta: true, unreadable: true, near_miss_extension: true, duplicate_in_layer: true, shadowed: true, shadow_unparseable: true,
name_differs_from_file: true, args_sidecar_retired: true, preset_target_missing: true, official_dir_missing: true,
};
export const WORKFLOW_SAVE_REFUSAL_CODES = Object.freeze(["workflow.save_exists", "workflow.save_name_mismatch", "workflow.save_symlink", "workflow.save_unavailable"]);
const SAVE_EXISTS = "workflow.save_exists";
const SAVE_NAME_MISMATCH = "workflow.save_name_mismatch";
const SAVE_SYMLINK = "workflow.save_symlink";
const SAVE_UNAVAILABLE = "workflow.save_unavailable";
export class WorkflowCatalogSaveError extends Error {
code;
details;
constructor(code, message, reason, location) {
super(message);
this.name = "WorkflowCatalogSaveError";
this.code = code;
this.details = Object.freeze({ code, ...(reason !== undefined ? { reason } : {}), ...(location !== undefined ? { location } : {}) });
}
}
export const WORKFLOW_CATALOG_HELD_CODE = "workflow.catalog_held";
export class WorkflowCatalogHeldError extends Error {
code = WORKFLOW_CATALOG_HELD_CODE;
details;
constructor(name, location, why, by = "deployment") {
super(by === "deployment"
? `workflow "${name}" is published by this deployment but is not runnable now (${location}: ${why}); nothing was started`
: `workflow "${name}" cannot be run now: ${why} (${location}), so whether that layer holds this name is not known; nothing was started`);
this.name = "WorkflowCatalogHeldError";
this.details = Object.freeze({ code: WORKFLOW_CATALOG_HELD_CODE, name, location });
}
}
const sha256 = textContentHashOf;
const catalogConfigError = (message) => codedRefusal("config.invalid_argument", message);
export function workflowArgsSidecarMigration(file, preset, workflow) {
return `keep its arguments as a preset under a name of its own: write ${preset}.preset.json containing {"workflow":${JSON.stringify(workflow)},"description":${JSON.stringify(`${file} with its old default arguments`)},"args":<the JSON in ${file}.args.json>} and call "${preset}" — "${workflow}" itself now runs without them`;
}
function sidecarPresetName(file, taken) {
const base = file.replace(/[^A-Za-z0-9._-]+/g, "-");
for (let i = 1;; i++) {
const suffix = i === 1 ? "-defaults" : `-defaults-${i}`;
const name = `${base.slice(0, 120 - suffix.length)}${suffix}`;
if (!taken.has(name))
return name;
}
}
const wordOf = (v) => (typeof v === "string" ? JSON.stringify(v.length > 120 ? `${v.slice(0, 120)}…` : v) : `a ${v === null ? "null" : typeof v}`);
const NEAR_MISS_EXTENSIONS = new Set([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".jsx", ".tsx"]);
class LayerUnreadable extends Error {
location;
why;
constructor(location, why, cause) {
super(`workflow catalog: ${why}`, cause !== undefined ? { cause } : undefined);
this.location = location;
this.why = why;
}
}
const isAbsent = (err) => err?.code === "ENOENT";
function sameFileByVolume(dirs, a, b) {
if (a === b)
return true;
const dir = dirname(a);
const fold = (s) => basename(s).toUpperCase().toLowerCase();
if (dir !== dirname(b) || !dirs.includes(dir) || fold(a) !== fold(b))
return false;
try {
const x = lstatSync(a);
const y = lstatSync(b);
if (x.ino === 0 || x.dev !== y.dev || x.ino !== y.ino)
return false;
const names = readdirSync(dir);
return !(names.includes(basename(a)) && names.includes(basename(b)));
}
catch {
return false;
}
}
function danglingLinkOn(path) {
for (let p = path;; p = dirname(p)) {
let st;
try {
st = lstatSync(p);
}
catch {
if (dirname(p) === p)
return undefined;
continue;
}
if (!st.isSymbolicLink())
return undefined;
try {
statSync(p);
return undefined;
}
catch {
return p;
}
}
}
function readDirectoryFiles(dir) {
let names;
try {
names = readdirSync(dir).sort();
}
catch (err) {
const link = isAbsent(err) ? danglingLinkOn(dir) : undefined;
if (isAbsent(err) && link === undefined)
return { files: [], notices: [] };
throw new LayerUnreadable(dir, `the directory ${dir} cannot be read: ${link !== undefined ? `${link} is a link to nothing that exists` : thrownText(err)}`, err);
}
const files = [];
const notices = [];
const sidecars = [];
const unread = [];
const recordUnreadUnlessGone = (location, err) => {
if (isAbsent(err) && danglingLinkOn(location) === undefined)
return;
unread.push({ location, why: `${isAbsent(err) ? "a link to nothing that exists" : thrownText(err)}: move it out of the directory, or make it readable — the file and the directory it is in` });
};
for (const file of names) {
if (file.startsWith("."))
continue;
const location = join(dir, file);
let kind;
let stem = "";
if (file.endsWith(".preset.json")) {
kind = "preset";
stem = file.slice(0, -".preset.json".length);
}
else if (file.endsWith(".team.json")) {
kind = "team";
stem = file.slice(0, -".team.json".length);
}
else if (file.endsWith(".js")) {
kind = "workflow";
stem = file.slice(0, -".js".length);
}
else if (file.endsWith(".args.json")) {
sidecars.push({ at: notices.length, stem: file.slice(0, -".args.json".length), file, location });
continue;
}
else {
const dot = file.lastIndexOf(".");
if (dot > 0 && NEAR_MISS_EXTENSIONS.has(file.slice(dot).toLowerCase())) {
notices.push({ code: "near_miss_extension", location, detail: `${file} is not read: a saved workflow is a .js file (a preset is .preset.json, a team .team.json)` });
}
continue;
}
let size;
let isFile;
try {
const st = statSync(location);
size = st.size;
isFile = st.isFile();
}
catch (err) {
recordUnreadUnlessGone(location, err);
continue;
}
if (!isFile)
continue;
const over = overCatalogFileLimit(size);
if (over !== undefined) {
unread.push({ location, why: `${over}: move it out of the directory or make it smaller` });
continue;
}
try {
files.push({ location, stem, kind, text: readFileSync(location, "utf-8") });
}
catch (err) {
recordUnreadUnlessGone(location, err);
}
}
if (unread.length > 0) {
const what = unread.map((u) => `${u.location} (${u.why})`).join("; ");
throw new LayerUnreadable(unread.map((u) => u.location).join(", "), `in the directory ${dir}, ${unread.length === 1 ? "a file" : `${unread.length} files`} cannot be read: ${what}`);
}
const declared = (f) => (f.kind === "workflow" ? readWorkflowMetaName(f.text) : undefined);
const used = new Set(sidecars.length > 0 ? files.flatMap((f) => [f.stem, declared(f) ?? f.stem]) : []);
for (const s of sidecars.reverse()) {
const beside = files.find((f) => f.kind === "workflow" && f.stem === s.stem);
const workflow = (beside !== undefined ? declared(beside) : undefined) ?? s.stem;
const preset = sidecarPresetName(s.stem, used);
used.add(preset);
notices.splice(s.at, 0, { code: "args_sidecar_retired", location: s.location, name: s.stem, detail: `${s.file} is not read: ${workflowArgsSidecarMigration(s.stem, preset, workflow)}` });
}
return { files, notices };
}
export function createDirectoryWorkflowLayer(opts) {
if (!WORKFLOW_SOURCES.includes(opts.source)) {
throw catalogConfigError(`createDirectoryWorkflowLayer: source must be one of ${WORKFLOW_SOURCES.join(", ")}, got ${wordOf(opts.source)}`);
}
if (!Array.isArray(opts.dirs) || opts.dirs.some((d) => typeof d !== "string" || d.length === 0)) {
throw catalogConfigError(`createDirectoryWorkflowLayer: dirs must be an array of directory paths`);
}
const dirs = opts.dirs.map((d) => resolvePath(d));
const read = () => {
const out = [];
const notices = [];
const failed = [];
for (const dir of dirs) {
try {
const got = readDirectoryFiles(dir);
out.push(got.files);
notices.push(...got.notices);
}
catch (err) {
if (!(err instanceof LayerUnreadable))
throw err;
failed.push(err);
}
}
if (failed.length === 1)
throw failed[0];
if (failed.length > 1)
throw new LayerUnreadable(failed.map((f) => f.location).join(", "), failed.map((f) => f.why).join("; "));
if (opts.expectEntries === true && out.every((files) => files.length === 0)) {
notices.push({ code: "official_dir_missing", location: dirs.join(", "), detail: `no workflow was found where this layer's workflows are expected (${dirs.join(", ") || "no directory given"})` });
}
return { dirs: out, notices };
};
const saveDir = dirs[0];
const writable = (opts.source === "project" || opts.source === "user") && saveDir !== undefined;
return {
source: opts.source,
dirs: Object.freeze([...dirs]),
read,
...(writable
? {
save: ({ name, script, overwrite }) => {
if (!isWorkflowName(name))
throw new WorkflowCatalogSaveError(SAVE_NAME_MISMATCH, `cannot save a workflow as ${JSON.stringify(name)}: not a workflow name`);
const over = overCatalogFileLimit(Buffer.byteLength(script, "utf8"));
if (over !== undefined) {
throw new WorkflowCatalogSaveError(SAVE_UNAVAILABLE, `cannot save workflow "${name}" to the ${opts.source} layer: its script is ${over} — this layer does not read a file that large, and one in its directory would make the layer unreadable. Nothing was written.`, "script_too_large");
}
const statOf = (p) => {
try {
return lstatSync(p);
}
catch {
return undefined;
}
};
const symlinkRefusal = (p) => new WorkflowCatalogSaveError(SAVE_SYMLINK, `cannot save workflow "${name}": ${p} is a symbolic link — a saved workflow is written only as a plain file in a plain directory. Remove the link, or save to the other layer.`, undefined, p);
if (statOf(saveDir)?.isSymbolicLink() === true)
throw symlinkRefusal(saveDir);
ensureDir(saveDir);
const target = join(saveDir, `${name}.js`);
const there = statOf(target);
if (there?.isSymbolicLink() === true)
throw symlinkRefusal(target);
if (there !== undefined && !there.isFile()) {
const what = there.isDirectory() ? "a directory" : "not a plain file";
throw new WorkflowCatalogSaveError(SAVE_EXISTS, `cannot save workflow "${name}": ${target} is ${what}, and a saved workflow is a plain file there — overwrite does not replace it. Remove or rename it, or use a different name.`, undefined, target);
}
const exists = () => new WorkflowCatalogSaveError(SAVE_EXISTS, `Dynamic workflow "${name}" already exists at ${target}. Use a different name or overwrite.`, undefined, target);
if (overwrite) {
atomicWriteFile(saveDir, target, script);
}
else {
try {
writeThenLink(target, script);
}
catch (err) {
if (err.code === "EEXIST")
throw exists();
throw err;
}
}
return { location: target };
},
}
: {}),
};
}
const PRESET_KEYS = ["workflow", "description", "whenToUse", "args", "stringArgKey", "requires"];
function parsePresetFile(text) {
let v;
try {
v = JSON.parse(text);
}
catch (err) {
throw new Error(`not JSON: ${thrownText(err)}`);
}
if (typeof v !== "object" || v === null || Array.isArray(v))
throw new Error("a preset is a JSON object");
const r = v;
const stray = strayMembersOf(r, { subject: "a preset file", unit: "key", moment: "when the catalog reads it" }, PRESET_KEYS);
if (stray !== undefined)
throw new Error(stray.sentence);
if (!isWorkflowName(r.workflow))
throw new Error("`workflow` must name the workflow it runs");
if (typeof r.description !== "string" || r.description.length === 0)
throw new Error("`description` is required and must be a non-empty string");
if (r.whenToUse !== undefined && typeof r.whenToUse !== "string")
throw new Error("`whenToUse` must be a string");
if (r.stringArgKey !== undefined && (typeof r.stringArgKey !== "string" || r.stringArgKey.length === 0))
throw new Error("`stringArgKey` must be a non-empty string");
return {
workflow: r.workflow,
description: r.description,
...(r.whenToUse !== undefined ? { whenToUse: r.whenToUse } : {}),
...(r.args !== undefined ? { args: r.args } : {}),
...(r.stringArgKey !== undefined ? { stringArgKey: r.stringArgKey } : {}),
...(r.requires !== undefined ? { requires: parseWorkflowRequires(r.requires, "`requires`") } : {}),
};
}
const TEAM_KEYS = ["description", "whenToUse", "workers", "appendSystemPrompt"];
const TEAM_WORKER_KEYS = ["agent"];
function parseTeamFile(text) {
let v;
try {
v = JSON.parse(text);
}
catch (err) {
throw new Error(`not JSON: ${thrownText(err)}`);
}
if (typeof v !== "object" || v === null || Array.isArray(v))
throw new Error("a team is a JSON object");
const r = v;
const stray = strayMembersOf(r, { subject: "a team file", unit: "key", moment: "when the catalog reads it" }, TEAM_KEYS);
if (stray !== undefined)
throw new Error(stray.sentence);
if (typeof r.description !== "string" || r.description.length === 0)
throw new Error("`description` is required and must be a non-empty string");
if (r.whenToUse !== undefined && typeof r.whenToUse !== "string")
throw new Error("`whenToUse` must be a string");
if (r.appendSystemPrompt !== undefined && typeof r.appendSystemPrompt !== "string")
throw new Error("`appendSystemPrompt` must be a string");
if (!Array.isArray(r.workers) || r.workers.length === 0)
throw new Error("`workers` is required and must be a non-empty list of { agent }");
const workers = r.workers.map((w, i) => {
if (typeof w !== "object" || w === null || Array.isArray(w))
throw new Error(`\`workers[${i}]\` must be { agent }`);
const strayW = strayMembersOf(w, { subject: `a team file's \`workers[${i}]\``, unit: "key", moment: "when the catalog reads it" }, TEAM_WORKER_KEYS);
if (strayW !== undefined)
throw new Error(strayW.sentence);
const agent = w.agent;
if (typeof agent !== "string" || agent.length === 0)
throw new Error(`\`workers[${i}].agent\` must name an agent definition`);
return { agent };
});
const twice = workers.map((w) => w.agent).find((a, i, all) => all.indexOf(a) !== i);
if (twice !== undefined)
throw new Error(`\`workers\` names "${twice}" more than once`);
return {
description: r.description,
...(r.whenToUse !== undefined ? { whenToUse: r.whenToUse } : {}),
workers,
...(r.appendSystemPrompt !== undefined ? { appendSystemPrompt: r.appendSystemPrompt } : {}),
};
}
function mergeRequires(a, b) {
if (a === undefined)
return b;
if (b === undefined)
return a;
const members = [...(a.members ?? []), ...(b.members ?? [])];
const models = [...new Set([...(a.models ?? []), ...(b.models ?? [])])];
return { ...(members.length > 0 ? { members } : {}), ...(models.length > 0 ? { models } : {}) };
}
function candidatesOf(file, source, notices) {
const c = candidateOf(file, source, notices);
if (c.runnable || file.kind !== "workflow")
return [c];
const declared = readWorkflowMetaName(file.text);
return declared !== undefined && declared !== c.name ? [c, { ...c, name: declared }] : [c];
}
function candidateOf(file, source, notices) {
const { location, stem } = file;
if (file.kind === "preset" || file.kind === "team") {
const what = file.kind === "preset" ? "preset" : "team";
if (!isWorkflowName(stem)) {
notices.push({ code: "invalid_meta", source, location, name: stem, detail: `a ${what}'s file name is its name, and ${JSON.stringify(stem)} is not a workflow name (letters, digits, ".", "_", "-"; not starting with ".")` });
return { runnable: false, name: stem, source, location, why: "its file name is not a workflow name" };
}
try {
return file.kind === "preset"
? { runnable: true, name: stem, source, location, preset: parsePresetFile(file.text) }
: { runnable: true, name: stem, source, location, team: parseTeamFile(file.text), text: file.text };
}
catch (err) {
const detail = `the ${what} does not read: ${thrownText(err)}`;
notices.push({ code: "invalid_meta", source, location, name: stem, detail });
return { runnable: false, name: stem, source, location, why: detail };
}
}
let meta;
try {
meta = parseWorkflowMeta(file.text);
}
catch (err) {
const detail = `its meta does not parse: ${thrownText(err)}`;
notices.push({ code: "invalid_meta", source, location, name: stem, detail });
return { runnable: false, name: stem, source, location, why: detail };
}
if (!isWorkflowName(meta.name)) {
const detail = `its meta.name ${JSON.stringify(meta.name)} is not a workflow name (letters, digits, ".", "_", "-"; at most 120; not starting with ".")`;
notices.push({ code: "invalid_meta", source, location, name: stem, detail });
return { runnable: false, name: stem, source, location, why: detail };
}
if (meta.name !== stem) {
notices.push({ code: "name_differs_from_file", source, location, name: meta.name, detail: `listed as "${meta.name}" (its meta.name), not "${stem}" (its file name) — call it by "${meta.name}"` });
}
return { runnable: true, name: meta.name, source, location, workflow: { script: file.text, meta } };
}
function checkedLayerRead(v, source) {
const fail = (where, why) => {
const message = `the ${source} layer answered a read that is not a listing: ${why}`;
throw where !== undefined ? new LayerUnreadable(where, message) : new Error(`workflow catalog: ${message}`);
};
const str = (x) => typeof x === "string";
const listOf = (x) => (Array.isArray(x) ? x : undefined);
if (v === null || typeof v !== "object")
return fail(undefined, `it is ${wordOf(v)}`);
const { dirs: rawDirs, notices: rawNotices } = v;
const dirList = listOf(rawDirs);
const noticeList = listOf(rawNotices);
if (dirList === undefined)
return fail(undefined, `its \`dirs\` is ${wordOf(rawDirs)}, not a list of directories`);
if (noticeList === undefined)
return fail(undefined, `its \`notices\` is ${wordOf(rawNotices)}, not a list`);
const dirs = [...dirList].map((files, di) => {
const fileList = listOf(files);
if (fileList === undefined)
return fail(undefined, `its directory ${di} is ${wordOf(files)}, not a list of files`);
return [...fileList].map((f) => {
const { location, stem, kind, text } = (f !== null && typeof f === "object" ? f : {});
if (!str(location) || !str(stem) || !str(kind) || !Object.hasOwn(WORKFLOW_CATALOG_ENTRY_DOORS, kind) || !str(text)) {
return fail(str(location) ? location : undefined, `a file of its directory ${di} is not { location, stem, kind: ${Object.keys(WORKFLOW_CATALOG_ENTRY_DOORS).map((k) => `"${k}"`).join(" | ")}, text } with strings`);
}
return { location, stem, kind: kind, text };
});
});
const notices = [...noticeList].map((n) => {
const { code, location, name, detail } = (n !== null && typeof n === "object" ? n : {});
if (!str(code) || !Object.hasOwn(NOTICE_CODES, code) || !str(location) || !str(detail) || (name !== undefined && !str(name))) {
return fail(undefined, `a notice is not { code, location, name?, detail } with a code of the closed set`);
}
if (code === "unreadable")
throw new LayerUnreadable(location, `the ${source} layer could not read ${location}: ${detail}`);
return { code: code, location, ...(str(name) ? { name } : {}), detail };
});
return { dirs, notices };
}
export function createWorkflowCatalog(opts) {
const layers = [...(opts.layers ?? [])];
const seen = new Set();
const dirOwner = new Map();
for (const layer of layers) {
if (layer === null || typeof layer !== "object" || typeof layer.read !== "function" || !WORKFLOW_SOURCES.includes(layer.source)) {
throw catalogConfigError(`createWorkflowCatalog: every layer has a \`read\` and a source of ${WORKFLOW_SOURCES.join(", ")} (got ${wordOf(layer?.source)})`);
}
if (seen.has(layer.source))
throw catalogConfigError(`createWorkflowCatalog: two layers of source "${layer.source}" — one layer per source (a layer may hold several directories)`);
seen.add(layer.source);
if (layer.dirs !== undefined && (!Array.isArray(layer.dirs) || layer.dirs.some((d) => typeof d !== "string")))
throw catalogConfigError(`createWorkflowCatalog: the ${layer.source} layer's \`dirs\` is not a list of directory paths`);
for (const dir of new Set((layer.dirs ?? []).map((d) => physicalPathOfExisting(d)))) {
const other = dirOwner.get(dir);
if (other !== undefined)
throw catalogConfigError(`createWorkflowCatalog: the ${other} and ${layer.source} layers both read ${dir} — a directory belongs to one layer (a file saved into one would be served as the other's)`);
dirOwner.set(dir, layer.source);
}
}
layers.sort((a, b) => WORKFLOW_SOURCES.indexOf(a.source) - WORKFLOW_SOURCES.indexOf(b.source));
const compute = async () => {
const reads = await Promise.allSettled(layers.map((layer) => Promise.resolve().then(() => layer.read()).then((v) => checkedLayerRead(v, layer.source))));
const notices = [];
const saveDirClaims = new Map();
const unreadAt = reads.findIndex((r) => r.status === "rejected");
let unread;
const unreadWhy = new Map();
const slots = [];
for (const [li, layer] of layers.entries()) {
const got = reads[li];
if (got.status === "rejected") {
const location = got.reason instanceof LayerUnreadable ? got.reason.location : layer.dirs?.join(", ") || `the ${layer.source} layer`;
if (li === unreadAt)
unread = { source: layer.source, location, why: `the ${layer.source} layer above it cannot be read`, by: "unreadable_layer" };
unreadWhy.set(layer.source, { reason: got.reason, location });
notices.push({ code: "unreadable", source: layer.source, location, detail: `${thrownText(got.reason)} — none of its workflows is listed, and every name a layer below it claims is held: whether this layer shadows that name is not known` });
continue;
}
const read = got.value;
for (const n of read.notices)
notices.push({ ...n, source: layer.source });
read.dirs.forEach((files, di) => {
const cands = files.flatMap((f) => candidatesOf(f, layer.source, notices));
const byName = new Map();
for (const c of cands)
byName.set(c.name, [...(byName.get(c.name) ?? []), c]);
if (di === 0 && layer.save !== undefined)
saveDirClaims.set(layer.source, new Map([...byName].map(([name, group]) => [name, group.map((c) => c.location)])));
const slot = [];
for (const [name, group] of byName) {
if (group.length === 1) {
slot.push(group[0]);
continue;
}
const where = group.map((c) => c.location).join(" and ");
notices.push({ code: "duplicate_in_layer", source: layer.source, location: where, name, detail: `${group.length} files in one directory claim "${name}" (${where}); none of them is listed — rename or remove all but one` });
slot.push({ runnable: false, name, source: layer.source, location: where, why: `${group.length} files in one directory claim it` });
}
slots.push({ below: unreadAt >= 0 && li > unreadAt, cands: slot });
});
}
const winner = new Map();
const held = new Map();
const passedOver = new Map();
for (const { below, cands } of slots) {
for (const c of cands) {
const taken = winner.get(c.name);
const hold = held.get(c.name) ?? (below ? unread : undefined);
if (taken !== undefined || hold !== undefined) {
const detail = taken !== undefined ? `not used: "${c.name}" is taken by ${taken.location} (${taken.source})`
: hold.by === "deployment" ? `not used: "${c.name}" is taken by ${hold.location} (deployment, not runnable: ${hold.why})`
: `not used: ${hold.why} (${hold.location}), so whether it shadows "${c.name}" is not known`;
if (taken === undefined && !held.has(c.name))
held.set(c.name, hold);
notices.push({ code: "shadowed", source: c.source, location: c.location, name: c.name, detail });
continue;
}
if (c.runnable) {
winner.set(c.name, c);
for (const p of passedOver.get(c.name) ?? []) {
notices.push({ code: "shadow_unparseable", source: p.source, location: p.location, name: c.name, detail: `${p.location} (${p.source}) could not be used (${p.why}); ${c.location} (${c.source}) is used for "${c.name}" instead` });
}
continue;
}
if (c.source === "deployment")
held.set(c.name, { source: "deployment", location: c.location, why: c.why, by: "deployment" });
else
passedOver.set(c.name, [...(passedOver.get(c.name) ?? []), c]);
}
}
const entries = new Map();
for (const [name, c] of winner) {
if ("workflow" in c) {
const { script, meta } = c.workflow;
const contentHash = sha256(script);
entries.set(name, {
entry: {
name, kind: "workflow", description: meta.description,
...(meta.whenToUse !== undefined ? { whenToUse: meta.whenToUse } : {}),
...(meta.phases !== undefined ? { phases: meta.phases } : {}),
source: c.source, location: c.location, contentHash,
...(meta.requires !== undefined ? { requires: meta.requires } : {}),
},
contentHash, script,
});
}
}
for (const [name, c] of winner) {
if (!("preset" in c))
continue;
const p = c.preset;
const target = entries.get(p.workflow);
if (target === undefined || target.entry.kind !== "workflow") {
notices.push({ code: "preset_target_missing", source: c.source, location: c.location, name, detail: `preset "${name}" runs workflow "${p.workflow}", which is not a listed workflow — the preset is not listed, and nothing runs under "${name}"` });
continue;
}
const contentHash = sha256(`${target.script}\u0000${canonicalJsonStringify({ args: p.args, stringArgKey: p.stringArgKey })}`);
const requires = mergeRequires(p.requires, target.entry.requires);
entries.set(name, {
entry: {
name, kind: "preset", description: p.description,
...(p.whenToUse !== undefined ? { whenToUse: p.whenToUse } : {}),
...(target.entry.phases !== undefined ? { phases: target.entry.phases } : {}),
source: c.source, location: c.location, contentHash,
...(requires !== undefined ? { requires } : {}),
},
contentHash, script: target.script,
...(p.args !== undefined ? { defaultArgs: structuredClone(p.args) } : {}),
...(p.stringArgKey !== undefined ? { stringArgKey: p.stringArgKey } : {}),
});
}
const teams = new Map();
const teamFiles = new Map();
for (const [name, c] of winner) {
if (!("team" in c))
continue;
teams.set(name, { name, kind: "team", description: c.team.description, ...(c.team.whenToUse !== undefined ? { whenToUse: c.team.whenToUse } : {}), source: c.source, location: c.location, contentHash: sha256(c.text) });
teamFiles.set(name, c.team);
}
const claimants = new Map([...winner].map(([name, c]) => [name, { source: c.source, location: c.location }]));
return { entries, teams, teamFiles, held, claimants, notices, saveDirClaims, unread: unreadWhy };
};
const content = (r) => ({
contentHash: r.contentHash,
script: r.script,
...(r.defaultArgs !== undefined ? { defaultArgs: structuredClone(r.defaultArgs) } : {}),
...(r.stringArgKey !== undefined ? { stringArgKey: r.stringArgKey } : {}),
});
const listingOf = (c) => ({ entries: [...[...c.entries.values()].map((r) => r.entry), ...c.teams.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)), notices: c.notices });
const answerIn = (c, name) => {
const hold = c.held.get(name);
if (hold !== undefined)
throw new WorkflowCatalogHeldError(name, hold.location, hold.why, hold.by);
const r = c.entries.get(name);
return r === undefined ? undefined : { ...content(r), entry: r.entry };
};
const catalog = {
async list() {
return listingOf(await compute());
},
async resolve(name) {
return typeof name === "string" ? answerIn(await compute(), name) : undefined;
},
async resolveTeam(name) {
if (typeof name !== "string")
return undefined;
const c = await compute();
const hold = c.held.get(name);
if (hold !== undefined)
throw new WorkflowCatalogHeldError(name, hold.location, hold.why, hold.by);
const entry = c.teams.get(name);
const file = c.teamFiles.get(name);
if (entry === undefined || file === undefined)
return undefined;
return { entry, workers: file.workers.map((w) => ({ agent: w.agent })), ...(file.appendSystemPrompt !== undefined ? { appendSystemPrompt: file.appendSystemPrompt } : {}) };
},
async readByHash(contentHash) {
if (typeof contentHash !== "string")
return undefined;
const c = await compute();
for (const r of c.entries.values())
if (r.contentHash === contentHash)
return content(r);
return undefined;
},
async snapshot() {
const kept = await compute();
const late = new Map();
return {
list: async () => listingOf(kept),
resolve: async (name) => {
if (typeof name !== "string")
return undefined;
if (kept.held.has(name) || kept.entries.has(name) || kept.teams.has(name))
return answerIn(kept, name);
const pinned = late.get(name);
if (pinned !== undefined)
return answerIn(pinned, name);
const now = await compute();
if (now.entries.has(name) && !now.held.has(name) && !late.has(name))
late.set(name, now);
return answerIn(late.get(name) ?? now, name);
},
};
},
};
const journal = opts.journalStore;
if (journalKeepsLaunches(journal)) {
catalog.saveRunAs = async (runId, scope, req) => {
const layerWord = req?.layer;
const layer = layers.find((l) => l.source === layerWord && WORKFLOW_SAVE_LAYERS.includes(l.source) && typeof l.save === "function");
if (layer === undefined) {
const known = typeof layerWord === "string" && WORKFLOW_SAVE_LAYERS.includes(layerWord);
throw new WorkflowCatalogSaveError(SAVE_UNAVAILABLE, `cannot save a workflow to ${wordOf(layerWord)}: this catalog has no writable ${known ? "layer of that source" : "layer of that name (a workflow is saved to \"project\" or \"user\")"}`, "layer_not_writable");
}
const launch = typeof runId === "string" && typeof scope === "string" ? await journal.loadLaunch(runId, scope) : undefined;
if (launch === undefined || typeof launch.script !== "string") {
throw new WorkflowCatalogSaveError(SAVE_UNAVAILABLE, `cannot save run ${wordOf(runId)}: there is no launch record for it here (it was not recorded, was erased, or belongs to another scope) — only what a run was launched with can be saved`, "no_launch_record");
}
const script = launch.script;
let metaName;
try {
metaName = parseWorkflowMeta(script).name;
}
catch {
metaName = undefined;
}
const name = req?.name;
if (metaName === undefined || !isWorkflowName(metaName) || name !== metaName) {
const why = metaName === undefined ? "its script's meta does not parse"
: !isWorkflowName(metaName) ? `its script's meta.name ${JSON.stringify(metaName)} is not a workflow name (letters, digits, ".", "_", "-"; at most 120; not starting with ".")`
: `a saved workflow is found by its script's meta.name, which is "${metaName}"`;
throw new WorkflowCatalogSaveError(SAVE_NAME_MISMATCH, `cannot save run ${wordOf(runId)} as ${wordOf(name)}: ${why}`);
}
return saveAs(layer, metaName, script, req?.overwrite === true);
};
const saveAs = async (layer, name, script, overwrite) => {
const before = await compute();
const unread = before.unread.get(layer.source);
if (unread !== undefined) {
throw new WorkflowCatalogSaveError(SAVE_UNAVAILABLE, `cannot save workflow "${name}" to the ${layer.source} layer: it cannot be read, so what a save would collide with is not known — ${thrownText(unread.reason)}`, "layer_unreadable", unread.location);
}
const claims = [...(before.saveDirClaims.get(layer.source) ?? new Map())];
const layerDirs = (layer.dirs ?? []).map((d) => resolvePath(d));
const isTarget = (location) => basename(location) === `${name}.js` || sameFileByVolume(layerDirs, location, join(dirname(location), `${name}.js`));
const other = claims.find(([n]) => n === name)?.[1].find((location) => !isTarget(location));
if (other !== undefined) {
throw new WorkflowCatalogSaveError(SAVE_EXISTS, `Dynamic workflow "${name}" already exists at ${other}. Use a different name, or remove that file first.`, undefined, other);
}
const atTarget = claims.filter(([, locations]) => locations.some(isTarget));
const holds = (atTarget.find(([n]) => n !== name) ?? atTarget[0])?.[0];
const targetAt = atTarget[0]?.[1].find(isTarget);
if (!overwrite && holds !== undefined && holds !== name) {
throw new WorkflowCatalogSaveError(SAVE_EXISTS, `Dynamic workflow "${name}" cannot be saved at ${targetAt}: that file holds workflow "${holds}", which saving would replace. Use a different name, or overwrite to replace "${holds}".`, undefined, targetAt);
}
const saved = await layer.save({ name, script, overwrite });
const after = await compute();
const hold = after.held.get(name);
const claimant = after.claimants.get(name);
const shadowedBy = hold !== undefined ? { source: hold.source, location: hold.location } : claimant !== undefined && !sameFileByVolume(layerDirs, claimant.location, saved.location) ? claimant : undefined;
const takesEffect = before.entries.has(name) || before.teams.has(name) || before.held.has(name) ? "next_mount" : "at_once";
return {
name, layer: layer.source, location: saved.location, contentHash: sha256(script),
...(shadowedBy !== undefined ? { shadowedBy } : { takesEffect }),
...(overwrite && holds !== undefined ? { replaced: holds } : {}),
};
};
}
return catalog;
}
export function isWorkflowCatalog(v) {
const m = v;
return m !== null && typeof m === "object" && typeof m.list === "function" && typeof m.resolve === "function" && typeof m.readByHash === "function" && typeof m.snapshot === "function";
}
export function workflowCatalogOfFactory(factory, ctx, onFault) {
const tell = (e) => {
try {
onFault(e);
}
catch {
}
};
let fault;
try {
if (typeof factory !== "function")
throw new TypeError(`RunnerDeps.workflowCatalog must be a function of the task's coordinates, got ${wordOf(factory)}`);
const cat = factory(ctx);
if (isWorkflowCatalog(cat)) {
return {
list: () => cat.list(),
resolve: (name) => cat.resolve(name),
readByHash: (hash) => cat.readByHash(hash),
snapshot: async () => {
const s = await cat.snapshot();
for (const n of (await s.list()).notices)
if (n.code === "unreadable")
tell(new Error(`workflow catalog: the ${n.source} layer cannot be read (${n.location}): ${n.detail}`));
return s;
},
...(typeof cat.saveRunAs === "function" ? { saveRunAs: (runId, scope, req) => cat.saveRunAs(runId, scope, req) } : {}),
...(typeof cat.resolveTeam === "function" ? { resolveTeam: (name) => cat.resolveTeam(name) } : {}),
};
}
throw new TypeError("RunnerDeps.workflowCatalog answered no workflow catalog (one built by createWorkflowCatalog)");
}
catch (err) {
fault = asThrownError(err);
}
tell(fault);
const reject = () => Promise.reject(fault);
return { list: reject, resolve: reject, readByHash: reject, snapshot: reject, resolveTeam: reject };
}