UNPKG

@mastra/core

Version:
618 lines (617 loc) • 23.5 kB
const require_run_registry = require("./run-registry-BrKoxzT0.cjs"); const require_predicate_index = require("./predicate/index.cjs"); const require_validate = require("./validate-BDarBL_5.cjs"); let _mastra_schema_compat_schema = require("@mastra/schema-compat/schema"); // 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 "${require_run_registry.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 = (0, _mastra_schema_compat_schema.toStandardSchema)(raw); return (0, _mastra_schema_compat_schema.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 = require_validate.jsonSchemaToZod(def.inputSchema, opts); const outputSchema = require_validate.jsonSchemaToZod(def.outputSchema, opts); const stateSchema = def.stateSchema ? require_validate.jsonSchemaToZod(def.stateSchema, opts) : void 0; const requestContextSchema = def.requestContextSchema ? require_validate.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" ? require_run_registry.createEventedWorkflow : require_run_registry.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(require_validate.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 ? require_run_registry.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: `${require_run_registry.getSingleStepEntryId(s)}-condition`, fn: require_predicate_index.derivePredicateLabel(predicates[i]) })); const live = { type: "conditional", ...entryOptionFields(entry), steps, conditions: predicates.map((p) => require_run_registry.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: `${require_run_registry.getSingleStepEntryId(step)}-condition`, fn: require_predicate_index.derivePredicateLabel(predicate) }; const live = { type: "loop", ...entryOptionFields(entry), step, condition: require_run_registry.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: require_validate.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: require_run_registry.createStepFromAgent(agent) }; const tool = tryGetToolById(mastra, id); if (tool) return { type: "step", step: require_run_registry.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 ? require_run_registry.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] = require_run_registry.mapVariable({ initData: wf, path: source.path }); } else if ("step" in source) out[key] = require_run_registry.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; } Object.defineProperty(exports, "entryOptionFields", { enumerable: true, get: function() { return entryOptionFields; } }); Object.defineProperty(exports, "rehydrateWorkflow", { enumerable: true, get: function() { return rehydrateWorkflow; } }); Object.defineProperty(exports, "toStorableGraph", { enumerable: true, get: function() { return toStorableGraph; } }); //# sourceMappingURL=rehydrate-BhTMElEh.cjs.map