@mastra/core
Version:
601 lines (600 loc) • 22.9 kB
JavaScript
import { Ml as createStepFromAgent, Pl as createStepFromTool, Ql as getSingleStepEntryId, dt as createWorkflow, lt as cloneWorkflow, ut as createEventedWorkflow, vl as mapVariable, yl as predicateToCondition } from "./run-registry-Ca8idv6o.js";
import { derivePredicateLabel } from "./predicate/index.js";
import { a as jsonSchemaToZod, l as parseMapConfig } from "./validate-CfgsbSxQ.js";
import { standardSchemaToJSONSchema, toStandardSchema } from "./schema/index.js";
// src/workflows/dynamic/serialize.ts
/**
* Live → Storable half of the workflow round-trip: walk a live `stepFlow`
* (runtime references, closures) and emit the JSON-safe storable form
* (ids + serialized mapping configs, no closures).
*
* The static subset that round-trips:
* - agent / tool by id
* - mapping with `value`, `step`, `initData`, `requestContextPath`, `template`,
* `state` sources (no `fn` source — closures don't round-trip)
* - sleep / sleepUntil with literal duration/date
* - parallel (inner entries must themselves be static)
* - foreach with literal concurrency
* - conditional / loop with declarative predicates (closure predicates throw)
* - generic `.then(step)` falls back to a minimal step descriptor — usable
* only when the step's id resolves on the live Mastra at load time
*
* Anything outside the subset throws at `toStorableGraph` time: silent loss
* would ship broken workflows unnoticed.
*/
/**
* The optional identity/display fields (`id` / `description` / `metadata`) of a
* control-flow entry, as a spreadable object. Both halves of the round-trip
* rebuild entries from a whitelist (`serializeEntry` here, `applyGraphEntry` in
* `./rehydrate`), so these must be picked explicitly or they'd be dropped.
*/
function entryOptionFields(entry) {
const out = {};
if (entry.id !== void 0) out.id = entry.id;
if (entry.description !== void 0) out.description = entry.description;
if (entry.metadata !== void 0) out.metadata = entry.metadata;
return out;
}
/**
* Walk a live `stepFlow` and emit a JSON-safe `SerializedStepFlowEntry[]` with
* full (un-truncated) mapping configs and all step/agent/tool references stored
* as ids. Throws on entries that can't round-trip (closures, closure predicates).
*/
function toStorableGraph(stepFlow) {
return stepFlow.map((entry) => serializeEntry(entry));
}
function serializeEntry(entry) {
switch (entry.type) {
case "step":
case "agent":
case "tool":
case "classifier":
case "mapping": return serializeSingleEntry(entry);
case "sleep":
if (typeof entry.duration !== "number") throw new Error(`Sleep step "${entry.id}" cannot be stored: dynamic duration (function) is not supported.`);
return {
type: "sleep",
...entryOptionFields(entry),
id: entry.id,
duration: entry.duration
};
case "sleepUntil":
if (!(entry.date instanceof Date)) throw new Error(`SleepUntil step "${entry.id}" cannot be stored: dynamic date (function) is not supported.`);
return {
type: "sleepUntil",
...entryOptionFields(entry),
id: entry.id,
date: entry.date
};
case "parallel": return {
type: "parallel",
...entryOptionFields(entry),
steps: entry.steps.map((s) => serializeSingleEntry(s))
};
case "foreach":
if (entry.step.type === "mapping") throw new Error(`Foreach step cannot iterate a mapping: mappings project data, they don't execute per item. Use an agent, tool, or plain step as the foreach body.`);
return {
type: "foreach",
...entryOptionFields(entry),
step: serializeSingleEntry(entry.step),
opts: typeof entry.opts.concurrency === "function" ? { fn: entry.opts.concurrency.toString() } : { concurrency: entry.opts.concurrency ?? 1 }
};
case "conditional": {
const predicates = entry.predicates;
if (!predicates || predicates.some((p) => !p || typeof p !== "object")) throw new Error(`Conditional (branch) step cannot be stored: closure predicates do not round-trip. Use the declarative form ({ predicate: {...} }) for each branch.`);
return {
type: "conditional",
...entryOptionFields(entry),
steps: entry.steps.map((s) => serializeSingleEntry(s)),
serializedConditions: entry.serializedConditions,
predicates
};
}
case "loop": {
const predicate = entry.predicate;
if (!predicate || typeof predicate !== "object") throw new Error(`Loop step "${getSingleStepEntryId(entry.step)}" cannot be stored: closure predicates do not round-trip. Use the declarative form ({ predicate: {...} }).`);
return {
type: "loop",
...entryOptionFields(entry),
step: serializeSingleEntry(entry.step),
serializedCondition: entry.serializedCondition,
loopType: entry.loopType,
predicate
};
}
default: throw new Error(`Unknown step entry type: ${JSON.stringify(entry)}`);
}
}
function serializeSingleEntry(entry) {
if (entry.type === "agent") {
const options = pickSerializableStepOptions(entry.options, entry.id, "agent");
const outputSchema = extractStructuredOutputJsonSchema(entry.options, entry.id);
return {
type: "agent",
id: entry.id,
agentId: entry.agentId,
description: entry.agent?.description,
...outputSchema ? { outputSchema } : {},
...options ? { options } : {}
};
}
if (entry.type === "tool") {
const options = pickSerializableStepOptions(entry.options, entry.id, "tool");
return {
type: "tool",
id: entry.id,
toolId: entry.toolId,
description: entry.tool?.description,
...options ? { options } : {}
};
}
if (entry.type === "classifier") {
const options = pickSerializableClassifierStepOptions(entry.options);
return {
type: "classifier",
id: entry.id,
classifierId: entry.classifierId,
...options ? { options } : {}
};
}
if (entry.type === "mapping") {
if (typeof entry.mapConfig === "function") throw new Error(`Mapping step "${entry.id}" cannot be stored: the function form does not round-trip. Use the declarative form (template / step / initData / value).`);
const serialized = {};
for (const [key, mapping] of Object.entries(entry.mapConfig)) {
const m = mapping;
if (m.fn !== void 0) throw new Error(`Mapping step "${entry.id}" key "${key}" cannot be stored: source is a function.`);
if (m.value !== void 0) serialized[key] = { value: m.value };
else if (m.requestContextPath) serialized[key] = { requestContextPath: m.requestContextPath };
else if (typeof m.template === "string") serialized[key] = { template: m.template };
else if (m.initData) serialized[key] = {
initData: m.initData?.id ?? true,
path: m.path
};
else if (m.step) serialized[key] = {
step: Array.isArray(m.step) ? m.step.map((s) => s?.id) : m.step?.id,
path: m.path
};
else serialized[key] = m;
}
return {
type: "mapping",
...entryOptionFields(entry),
id: entry.id,
mapConfig: JSON.stringify(serialized)
};
}
if (entry.step?.component === "WORKFLOW") {
const nestedFlow = entry.step.serializedStepGraph ?? entry.step.serializedStepFlow;
return {
type: "workflow",
id: entry.step.id,
workflowId: entry.step.id,
...entry.step.description ? { description: entry.step.description } : {},
...nestedFlow ? { serializedStepFlow: nestedFlow } : {}
};
}
return {
type: "step",
step: stepDescriptor(entry.step)
};
}
function stepDescriptor(step) {
return {
id: step.id,
description: step.description,
metadata: step.metadata,
component: step.component,
canSuspend: Boolean(step.suspendSchema || step.resumeSchema)
};
}
function assertJsonValue(value, path, seen = /* @__PURE__ */ new Set()) {
if (value === null || typeof value === "string" || typeof value === "boolean") return;
if (typeof value === "number") {
if (!Number.isFinite(value)) throw new TypeError(`${path} must contain only finite numbers.`);
return;
}
if (typeof value !== "object") throw new TypeError(`${path} must contain only JSON-compatible values.`);
if (seen.has(value)) throw new TypeError(`${path} must not contain circular references.`);
seen.add(value);
if (Array.isArray(value)) value.forEach((item, index) => assertJsonValue(item, `${path}.${index}`, seen));
else Object.entries(value).forEach(([key, item]) => assertJsonValue(item, `${path}.${key}`, seen));
seen.delete(value);
}
function pickSerializableClassifierStepOptions(options) {
if (!options || typeof options !== "object") return void 0;
const out = {};
if (typeof options.maxRetries === "number") out.maxRetries = options.maxRetries;
if (options.providerOptions && typeof options.providerOptions === "object") {
assertJsonValue(options.providerOptions, "classifier options.providerOptions");
out.providerOptions = options.providerOptions;
}
if (typeof options.retries === "number") out.retries = options.retries;
if (options.metadata && typeof options.metadata === "object") {
assertJsonValue(options.metadata, "classifier options.metadata");
out.metadata = options.metadata;
}
return Object.keys(out).length > 0 ? out : void 0;
}
/**
* Pull the JSON-safe fields (`retries`, `metadata`) out of the options bag
* carried on a live agent/tool `SingleStepEntry`. Closure-valued fields must
* hard-crash here rather than silently vanish through storage.
*/
function pickSerializableStepOptions(options, entryId, kind) {
if (!options || typeof options !== "object") return void 0;
for (const { key, hint } of [
{
key: "onFinish",
hint: "callback closure"
},
{
key: "onChunk",
hint: "callback closure"
},
{
key: "onError",
hint: "callback closure"
},
{
key: "onStepFinish",
hint: "callback closure"
},
{
key: "onAbort",
hint: "callback closure"
},
{
key: "toolChoice",
hint: "may be a function"
}
]) if (typeof options[key] === "function") throw new Error(`${kind === "agent" ? "Agent" : "Tool"} step "${entryId}" cannot be stored: option "${key}" is a ${hint} that does not round-trip. Remove it or move that logic outside the persisted workflow.`);
if (typeof options.scorers === "function") throw new Error(`${kind === "agent" ? "Agent" : "Tool"} step "${entryId}" cannot be stored: "scorers" is a function; only the static array form round-trips.`);
const out = {};
if (typeof options.retries === "number") out.retries = options.retries;
if (options.metadata && typeof options.metadata === "object") out.metadata = options.metadata;
return Object.keys(out).length > 0 ? out : void 0;
}
/**
* If the agent-step options carry `structuredOutput.schema`, that schema IS
* the step's output shape (see `createStepFromAgent`). Emit it as JSON Schema
* so rehydration can wire the same structured output back in.
*/
function extractStructuredOutputJsonSchema(options, entryId) {
const raw = options?.structuredOutput?.schema;
if (raw === void 0 || raw === null) return void 0;
try {
const standard = toStandardSchema(raw);
return standardSchemaToJSONSchema(standard);
} catch (e) {
throw new Error(`Agent step "${entryId}" cannot be stored: structuredOutput.schema is not convertible to JSON Schema (${e.message}).`);
}
}
// src/workflows/dynamic/rehydrate.ts
async function rehydrateWorkflow(def, mastra, opts) {
const inputSchema = jsonSchemaToZod(def.inputSchema, opts);
const outputSchema = jsonSchemaToZod(def.outputSchema, opts);
const stateSchema = def.stateSchema ? jsonSchemaToZod(def.stateSchema, opts) : void 0;
const requestContextSchema = def.requestContextSchema ? jsonSchemaToZod(def.requestContextSchema, opts) : void 0;
const baseParams = {
id: def.id,
description: def.description,
metadata: def.metadata,
inputSchema,
outputSchema,
stateSchema,
requestContextSchema
};
const factory = opts?.engineType === "evented" ? createEventedWorkflow : createWorkflow;
let wf;
if (def.schedule === void 0) wf = factory(baseParams);
else try {
wf = factory({
...baseParams,
schedule: def.schedule
});
} catch (error) {
if (opts?.onUnsupportedSchema !== "warn") throw error;
opts.onUnsupported?.(`Ignoring invalid stored schedule config: ${error instanceof Error ? error.message : String(error)}`);
wf = factory(baseParams);
}
for (const entry of def.graph) applyGraphEntry(wf, entry, mastra, opts);
const built = wf.commit();
built.origin = "dynamic";
return { workflow: built };
}
function applyGraphEntry(wf, entry, mastra, schemaOpts) {
switch (entry.type) {
case "agent":
case "tool":
case "classifier":
wf.__pushStepFlowEntry(rehydrateSingleEntry(entry, mastra, schemaOpts), entry);
return;
case "mapping": {
const live = rehydrateMapConfig(parseMapConfig(entry.mapConfig, entry.id), mastra);
wf.map(live, {
id: entry.id,
description: entry.description,
metadata: entry.metadata
});
return;
}
case "sleep": {
if (typeof entry.duration !== "number") throw new Error(`Stored sleep "${entry.id}" missing literal duration.`);
const live = {
type: "sleep",
...entryOptionFields(entry),
id: entry.id,
duration: entry.duration
};
wf.__pushStepFlowEntry(live, live);
return;
}
case "sleepUntil": {
if (!(entry.date instanceof Date) && typeof entry.date !== "string") throw new Error(`Stored sleepUntil "${entry.id}" missing literal date.`);
const date = entry.date instanceof Date ? entry.date : new Date(entry.date);
if (Number.isNaN(date.getTime())) throw new Error(`Stored sleepUntil "${entry.id}" has an unparseable date: ${String(entry.date)}`);
const live = {
type: "sleepUntil",
...entryOptionFields(entry),
id: entry.id,
date
};
wf.__pushStepFlowEntry(live, {
type: "sleepUntil",
...entryOptionFields(entry),
id: entry.id,
date
});
return;
}
case "parallel": {
const live = {
type: "parallel",
...entryOptionFields(entry),
steps: entry.steps.map((s) => rehydrateSingleEntry(s, mastra, schemaOpts))
};
wf.__pushStepFlowEntry(live, entry);
return;
}
case "foreach": {
if (entry.step.type === "mapping") throw new Error(`Foreach step cannot iterate a mapping: mappings project data, they don't execute per item. Use an agent, tool, or plain step as the foreach body.`);
const live = {
type: "foreach",
...entryOptionFields(entry),
step: rehydrateSingleEntry(entry.step, mastra, schemaOpts),
opts: { concurrency: entry.opts?.concurrency ?? 1 }
};
wf.__pushStepFlowEntry(live, entry);
return;
}
case "step": {
const live = rehydrateSingleEntry(entry, mastra, schemaOpts);
wf.__pushStepFlowEntry(live, entry);
return;
}
case "workflow": {
const nested = assertWorkflowExists(mastra, entry.workflowId);
wf.then(entry.id && entry.id !== nested.id ? cloneWorkflow(nested, { id: entry.id }) : nested);
return;
}
case "conditional": {
const predicates = entry.predicates;
if (!predicates || predicates.length !== entry.steps.length || predicates.some((p) => !p)) throw new Error(`Cannot rehydrate conditional step: missing or mismatched predicates. Only declarative predicate branches round-trip.`);
const steps = entry.steps.map((s) => rehydrateSingleEntry(s, mastra, schemaOpts));
const serializedConditions = entry.serializedConditions ?? steps.map((s, i) => ({
id: `${getSingleStepEntryId(s)}-condition`,
fn: derivePredicateLabel(predicates[i])
}));
const live = {
type: "conditional",
...entryOptionFields(entry),
steps,
conditions: predicates.map((p) => predicateToCondition(p)),
serializedConditions,
predicates
};
wf.__pushStepFlowEntry(live, {
...entry,
serializedConditions
});
return;
}
case "loop": {
const { predicate, loopType } = entry;
if (!predicate || loopType !== "dowhile" && loopType !== "dountil") throw new Error(`Cannot rehydrate loop step: missing declarative predicate or loopType. Only declarative predicate loops round-trip.`);
const step = rehydrateSingleEntry(entry.step, mastra, schemaOpts);
const serializedCondition = entry.serializedCondition ?? {
id: `${getSingleStepEntryId(step)}-condition`,
fn: derivePredicateLabel(predicate)
};
const live = {
type: "loop",
...entryOptionFields(entry),
step,
condition: predicateToCondition(predicate),
loopType,
serializedCondition,
predicate
};
wf.__pushStepFlowEntry(live, {
...entry,
serializedCondition
});
return;
}
default: throw new Error(`Unknown stored step type: ${JSON.stringify(entry)}`);
}
}
/**
* Reconstruct the options bag `.agent()` accepts from a serialized entry.
* Restores `structuredOutput.schema` from `outputSchema` (JSON Schema → Zod)
* and merges in `retries` / `metadata`. Returns `undefined` when nothing to
* restore so `.agent(agentId)` stays a clean call.
*/
function rebuildAgentOptions(entry, schemaOpts) {
const opts = {};
if (entry.outputSchema) opts.structuredOutput = { schema: jsonSchemaToZod(entry.outputSchema, schemaOpts) };
if (entry.options?.retries !== void 0) opts.retries = entry.options.retries;
if (entry.options?.metadata !== void 0) opts.metadata = entry.options.metadata;
return Object.keys(opts).length > 0 ? opts : void 0;
}
function rebuildToolOptions(entry) {
const opts = {};
if (entry.options?.retries !== void 0) opts.retries = entry.options.retries;
if (entry.options?.metadata !== void 0) opts.metadata = entry.options.metadata;
return Object.keys(opts).length > 0 ? opts : void 0;
}
/**
* Build the live `SingleStepEntry` for a stored entry. Declarative agent/tool
* entries stay declarative — both engines interpret them per-kind at
* execution time (`runAgentEntry` / `runToolEntry`) — so no fake `Step`
* wrapper is needed and the stored `id` / `outputSchema` / `retries` /
* `metadata` round-trip losslessly in every position (top-level, parallel,
* branch, foreach and loop bodies).
*
* `step` descriptors resolve agent-then-tool by id against the live Mastra
* instance; `workflow` entries resolve the registered instance. Both become
* plain `{ type: 'step' }` entries, same as the fluent builder emits.
*/
function rehydrateSingleEntry(entry, mastra, schemaOpts) {
switch (entry.type) {
case "agent": {
const agent = tryGetAgentById(mastra, entry.agentId);
if (!agent) throw new Error(`Dynamic workflow references agent "${entry.agentId}" which is not registered on this Mastra instance.`);
return {
type: "agent",
id: entry.id,
agentId: entry.agentId,
agent,
options: rebuildAgentOptions(entry, schemaOpts)
};
}
case "tool": {
const tool = mastra.getTool?.(entry.toolId);
if (!tool) throw new Error(`Dynamic workflow references tool "${entry.toolId}" which is not registered on this Mastra instance.`);
return {
type: "tool",
id: entry.id,
toolId: entry.toolId,
tool,
options: rebuildToolOptions(entry)
};
}
case "classifier": {
let classifier;
try {
classifier = mastra.getClassifierById(entry.classifierId);
} catch {
throw new Error(`Dynamic workflow references classifier "${entry.classifierId}" which is not registered on this Mastra instance.`);
}
return {
type: "classifier",
id: entry.id,
classifierId: entry.classifierId,
classifier,
options: entry.options
};
}
case "step": {
const { id } = entry.step;
const agent = tryGetAgentById(mastra, id);
if (agent) return {
type: "step",
step: createStepFromAgent(agent)
};
const tool = tryGetToolById(mastra, id);
if (tool) return {
type: "step",
step: createStepFromTool(tool)
};
throw new Error(`Dynamic workflow references step "${id}" which is not registered as an agent or tool on this Mastra instance.`);
}
case "workflow": {
const nested = assertWorkflowExists(mastra, entry.workflowId);
return {
type: "step",
step: entry.id && entry.id !== nested.id ? cloneWorkflow(nested, { id: entry.id }) : nested
};
}
case "mapping": throw new Error(`mapping entries cannot appear inside .parallel(), .branch(), or .foreach(); they must be top-level.`);
}
}
/**
* Rebuild the object shape that `.map()` accepts. Step sources remain workflow-local
* step IDs because mapping execution resolves them from the run's step results.
*/
function rehydrateMapConfig(cfg, mastra) {
const out = {};
for (const [key, source] of Object.entries(cfg)) {
if (!source || typeof source !== "object") {
out[key] = source;
continue;
}
if ("template" in source) out[key] = { template: source.template };
else if ("value" in source) out[key] = { value: source.value };
else if ("requestContextPath" in source) out[key] = { requestContextPath: source.requestContextPath };
else if ("initData" in source && typeof source.initData === "string") {
const wf = mastra.getWorkflow?.(source.initData);
if (!wf) throw new Error(`Mapping references unknown workflow init-data "${source.initData}".`);
out[key] = mapVariable({
initData: wf,
path: source.path
});
} else if ("step" in source) out[key] = mapVariable({
step: source.step,
path: source.path
});
else out[key] = source;
}
return out;
}
/**
* Mastra.getAgentById throws when the id isn't registered; every by-id
* resolution path in this file wants a nullable "does it exist?" answer so it
* can fall through to a tool lookup or a targeted error. Swallow the not-found
* throw and return undefined.
*/
function tryGetAgentById(mastra, id) {
if (!id || typeof mastra.getAgentById !== "function") return void 0;
try {
return mastra.getAgentById(id);
} catch {
return;
}
}
/** Same nullable-lookup contract as `tryGetAgentById`, for tools — `Mastra.getTool` throws on a missing id. */
function tryGetToolById(mastra, id) {
if (!id || typeof mastra.getTool !== "function") return void 0;
try {
return mastra.getTool(id);
} catch {
return;
}
}
/**
* Workflow references resolve like agent references: intrinsic workflow id
* first (`getWorkflowById` scans registered workflows by their own `id`),
* falling back to the registration key. Stored definitions reference the
* intrinsic id — the identity discovery advertises — which may differ from
* the key the workflow was registered under (`workflows: { greetingWorkflow }`
* vs `id: 'greeting-workflow'`).
*/
function tryGetWorkflowById(mastra, id) {
if (!id) return void 0;
if (typeof mastra.getWorkflowById === "function") try {
return mastra.getWorkflowById(id);
} catch {}
if (typeof mastra.getWorkflow !== "function") return void 0;
try {
return mastra.getWorkflow(id);
} catch {
return;
}
}
function assertWorkflowExists(mastra, workflowId) {
const wf = tryGetWorkflowById(mastra, workflowId);
if (!wf) throw new Error(`Dynamic workflow references nested workflow "${workflowId}" which is not registered on this Mastra instance.`);
return wf;
}
export { entryOptionFields as n, toStorableGraph as r, rehydrateWorkflow as t };
//# sourceMappingURL=rehydrate-DzumSyB6.js.map