UNPKG

@mastra/core

Version:
1 lines • 45.1 kB
{"version":3,"file":"rehydrate-BhTMElEh.cjs","names":["getSingleStepEntryId","_exhaustive","toStandardSchema","standardSchemaToJSONSchema","jsonSchemaToZod","createEventedWorkflow","createWorkflow","parseMapConfig","cloneWorkflow","getSingleStepEntryId","derivePredicateLabel","predicateToCondition","_exhaustive","createStepFromAgent","createStepFromTool","mapVariable"],"sources":["../src/workflows/dynamic/serialize.ts","../src/workflows/dynamic/rehydrate.ts"],"sourcesContent":["/**\n * Live → Storable half of the workflow round-trip: walk a live `stepFlow`\n * (runtime references, closures) and emit the JSON-safe storable form\n * (ids + serialized mapping configs, no closures).\n *\n * The static subset that round-trips:\n * - agent / tool by id\n * - mapping with `value`, `step`, `initData`, `requestContextPath`, `template`,\n * `state` sources (no `fn` source — closures don't round-trip)\n * - sleep / sleepUntil with literal duration/date\n * - parallel (inner entries must themselves be static)\n * - foreach with literal concurrency\n * - conditional / loop with declarative predicates (closure predicates throw)\n * - generic `.then(step)` falls back to a minimal step descriptor — usable\n * only when the step's id resolves on the live Mastra at load time\n *\n * Anything outside the subset throws at `toStorableGraph` time: silent loss\n * would ship broken workflows unnoticed.\n */\nimport { standardSchemaToJSONSchema, toStandardSchema } from '../../schema';\nimport type {\n SerializableClassifierStepOptions,\n SerializedSingleStepEntry,\n SerializedStepFlowEntry,\n SerializedStepOptions,\n SingleStepEntry,\n StepFlowEntry,\n StepFlowEntryOptions,\n} from '../types';\nimport { getSingleStepEntryId } from '../utils';\n\n/**\n * The optional identity/display fields (`id` / `description` / `metadata`) of a\n * control-flow entry, as a spreadable object. Both halves of the round-trip\n * rebuild entries from a whitelist (`serializeEntry` here, `applyGraphEntry` in\n * `./rehydrate`), so these must be picked explicitly or they'd be dropped.\n */\nexport function entryOptionFields(entry: {\n id?: string;\n description?: string;\n metadata?: Record<string, any>;\n}): StepFlowEntryOptions {\n const out: StepFlowEntryOptions = {};\n if (entry.id !== undefined) out.id = entry.id;\n if (entry.description !== undefined) out.description = entry.description;\n if (entry.metadata !== undefined) out.metadata = entry.metadata;\n return out;\n}\n\n/**\n * Walk a live `stepFlow` and emit a JSON-safe `SerializedStepFlowEntry[]` with\n * full (un-truncated) mapping configs and all step/agent/tool references stored\n * as ids. Throws on entries that can't round-trip (closures, closure predicates).\n */\nexport function toStorableGraph(stepFlow: StepFlowEntry[]): SerializedStepFlowEntry[] {\n return stepFlow.map(entry => serializeEntry(entry));\n}\n\nfunction serializeEntry(entry: StepFlowEntry): SerializedStepFlowEntry {\n switch (entry.type) {\n case 'step':\n case 'agent':\n case 'tool':\n case 'classifier':\n case 'mapping':\n return serializeSingleEntry(entry);\n case 'sleep':\n if (typeof entry.duration !== 'number') {\n throw new Error(`Sleep step \"${entry.id}\" cannot be stored: dynamic duration (function) is not supported.`);\n }\n return { type: 'sleep', ...entryOptionFields(entry), id: entry.id, duration: entry.duration };\n case 'sleepUntil':\n if (!(entry.date instanceof Date)) {\n throw new Error(`SleepUntil step \"${entry.id}\" cannot be stored: dynamic date (function) is not supported.`);\n }\n return { type: 'sleepUntil', ...entryOptionFields(entry), id: entry.id, date: entry.date };\n case 'parallel':\n return { type: 'parallel', ...entryOptionFields(entry), steps: entry.steps.map(s => serializeSingleEntry(s)) };\n case 'foreach':\n if (entry.step.type === 'mapping') {\n throw new Error(\n `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.`,\n );\n }\n return {\n type: 'foreach',\n ...entryOptionFields(entry),\n step: serializeSingleEntry(entry.step),\n opts:\n typeof entry.opts.concurrency === 'function'\n ? { fn: entry.opts.concurrency.toString() }\n : // The live entry keeps the caller's options object by reference, and\n // `.foreach(step, { id })` is valid without a concurrency — default it\n // here so stored graphs never carry an empty (schema-invalid) opts.\n { concurrency: entry.opts.concurrency ?? 1 },\n };\n case 'conditional': {\n const predicates = entry.predicates;\n if (!predicates || predicates.some(p => !p || typeof p !== 'object')) {\n throw new Error(\n `Conditional (branch) step cannot be stored: closure predicates do not round-trip. Use the declarative form ({ predicate: {...} }) for each branch.`,\n );\n }\n return {\n type: 'conditional',\n ...entryOptionFields(entry),\n steps: entry.steps.map(s => serializeSingleEntry(s)),\n serializedConditions: entry.serializedConditions,\n predicates,\n };\n }\n case 'loop': {\n const predicate = entry.predicate;\n if (!predicate || typeof predicate !== 'object') {\n throw new Error(\n `Loop step \"${getSingleStepEntryId(entry.step)}\" cannot be stored: closure predicates do not round-trip. Use the declarative form ({ predicate: {...} }).`,\n );\n }\n return {\n type: 'loop',\n ...entryOptionFields(entry),\n step: serializeSingleEntry(entry.step),\n serializedCondition: entry.serializedCondition,\n loopType: entry.loopType,\n predicate,\n };\n }\n default: {\n const _exhaustive: never = entry;\n throw new Error(`Unknown step entry type: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\nfunction serializeSingleEntry(entry: SingleStepEntry): SerializedSingleStepEntry {\n if (entry.type === 'agent') {\n const options = pickSerializableStepOptions(entry.options, entry.id, 'agent');\n const outputSchema = extractStructuredOutputJsonSchema(entry.options, entry.id);\n return {\n type: 'agent',\n id: entry.id,\n agentId: entry.agentId,\n description: entry.agent?.description,\n ...(outputSchema ? { outputSchema } : {}),\n ...(options ? { options } : {}),\n };\n }\n if (entry.type === 'tool') {\n const options = pickSerializableStepOptions(entry.options, entry.id, 'tool');\n return {\n type: 'tool',\n id: entry.id,\n toolId: entry.toolId,\n description: entry.tool?.description,\n ...(options ? { options } : {}),\n };\n }\n if (entry.type === 'classifier') {\n const options = pickSerializableClassifierStepOptions(entry.options);\n return {\n type: 'classifier',\n id: entry.id,\n classifierId: entry.classifierId,\n ...(options ? { options } : {}),\n };\n }\n if (entry.type === 'mapping') {\n if (typeof entry.mapConfig === 'function') {\n throw new Error(\n `Mapping step \"${entry.id}\" cannot be stored: the function form does not round-trip. Use the declarative form (template / step / initData / value).`,\n );\n }\n const serialized: Record<string, any> = {};\n for (const [key, mapping] of Object.entries(entry.mapConfig as Record<string, any>)) {\n const m: any = mapping;\n if (m.fn !== undefined) {\n throw new Error(`Mapping step \"${entry.id}\" key \"${key}\" cannot be stored: source is a function.`);\n }\n if (m.value !== undefined) {\n serialized[key] = { value: m.value };\n } else if (m.requestContextPath) {\n serialized[key] = { requestContextPath: m.requestContextPath };\n } else if (typeof m.template === 'string') {\n serialized[key] = { template: m.template };\n } else if (m.initData) {\n serialized[key] = { initData: m.initData?.id ?? true, path: m.path };\n } else if (m.step) {\n serialized[key] = {\n step: Array.isArray(m.step) ? m.step.map((s: any) => s?.id) : m.step?.id,\n path: m.path,\n };\n } else {\n serialized[key] = m;\n }\n }\n return { type: 'mapping', ...entryOptionFields(entry), id: entry.id, mapConfig: JSON.stringify(serialized) };\n }\n // A nested Workflow reached the generic `.then(step)` fallback (its\n // component discriminator is 'WORKFLOW'). Emit a declarative `workflow`\n // entry so the rehydrator can rebuild it by id. Inline the nested graph\n // when present so Studio/API consumers can expand it (same role the old\n // `type:'step' + component:'WORKFLOW'` shape played).\n if ((entry.step as any)?.component === 'WORKFLOW') {\n // Prefer the public getter (serializedStepGraph); fall back to the\n // protected/legacy serializedStepFlow field.\n const nestedFlow =\n ((entry.step as any).serializedStepGraph as SerializedStepFlowEntry[] | undefined) ??\n ((entry.step as any).serializedStepFlow as SerializedStepFlowEntry[] | undefined);\n return {\n type: 'workflow',\n id: (entry.step as any).id,\n workflowId: (entry.step as any).id,\n ...((entry.step as any).description ? { description: (entry.step as any).description } : {}),\n ...(nestedFlow ? { serializedStepFlow: nestedFlow } : {}),\n };\n }\n // generic `.then(step)` — descriptor only; rehydration looks the step up\n // by id on the live Mastra instance.\n return { type: 'step', step: stepDescriptor(entry.step) };\n}\n\nfunction stepDescriptor(step: any) {\n return {\n id: step.id,\n description: step.description,\n metadata: step.metadata,\n component: step.component,\n canSuspend: Boolean(step.suspendSchema || step.resumeSchema),\n };\n}\n\nfunction assertJsonValue(value: unknown, path: string, seen = new Set<object>()): void {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new TypeError(`${path} must contain only finite numbers.`);\n return;\n }\n if (typeof value !== 'object') throw new TypeError(`${path} must contain only JSON-compatible values.`);\n if (seen.has(value)) throw new TypeError(`${path} must not contain circular references.`);\n\n seen.add(value);\n if (Array.isArray(value)) {\n value.forEach((item, index) => assertJsonValue(item, `${path}.${index}`, seen));\n } else {\n Object.entries(value).forEach(([key, item]) => assertJsonValue(item, `${path}.${key}`, seen));\n }\n seen.delete(value);\n}\n\nfunction pickSerializableClassifierStepOptions(options: any): SerializableClassifierStepOptions | undefined {\n if (!options || typeof options !== 'object') return undefined;\n\n const out: SerializableClassifierStepOptions = {};\n if (typeof options.maxRetries === 'number') out.maxRetries = options.maxRetries;\n if (options.providerOptions && typeof options.providerOptions === 'object') {\n assertJsonValue(options.providerOptions, 'classifier options.providerOptions');\n out.providerOptions = options.providerOptions;\n }\n if (typeof options.retries === 'number') out.retries = options.retries;\n if (options.metadata && typeof options.metadata === 'object') {\n assertJsonValue(options.metadata, 'classifier options.metadata');\n out.metadata = options.metadata;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * Pull the JSON-safe fields (`retries`, `metadata`) out of the options bag\n * carried on a live agent/tool `SingleStepEntry`. Closure-valued fields must\n * hard-crash here rather than silently vanish through storage.\n */\nfunction pickSerializableStepOptions(\n options: any,\n entryId: string,\n kind: 'agent' | 'tool',\n): SerializedStepOptions | undefined {\n if (!options || typeof options !== 'object') return undefined;\n\n // Closure-valued options don't round-trip. Fail loudly at serialize time so\n // the workflow author immediately learns their step won't persist rather\n // than discovering it in production when the callback silently no-ops.\n const forbidden: Array<{ key: string; hint: string }> = [\n { key: 'onFinish', hint: 'callback closure' },\n { key: 'onChunk', hint: 'callback closure' },\n { key: 'onError', hint: 'callback closure' },\n { key: 'onStepFinish', hint: 'callback closure' },\n { key: 'onAbort', hint: 'callback closure' },\n { key: 'toolChoice', hint: 'may be a function' },\n ];\n for (const { key, hint } of forbidden) {\n if (typeof options[key] === 'function') {\n throw new Error(\n `${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.`,\n );\n }\n }\n if (typeof options.scorers === 'function') {\n throw new Error(\n `${kind === 'agent' ? 'Agent' : 'Tool'} step \"${entryId}\" cannot be stored: \"scorers\" is a function; only the static array form round-trips.`,\n );\n }\n\n const out: SerializedStepOptions = {};\n if (typeof options.retries === 'number') out.retries = options.retries;\n if (options.metadata && typeof options.metadata === 'object') {\n out.metadata = options.metadata as Record<string, any>;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * If the agent-step options carry `structuredOutput.schema`, that schema IS\n * the step's output shape (see `createStepFromAgent`). Emit it as JSON Schema\n * so rehydration can wire the same structured output back in.\n */\nfunction extractStructuredOutputJsonSchema(options: any, entryId: string): Record<string, any> | undefined {\n const raw = options?.structuredOutput?.schema;\n if (raw === undefined || raw === null) return undefined;\n try {\n // `.agent()`'s typed overload requires a StandardSchemaWithJSON, but the\n // any-form accepts a raw Zod schema. Normalize either shape here so the\n // storage form is consistent.\n const standard = toStandardSchema(raw);\n return standardSchemaToJSONSchema(standard) as Record<string, any>;\n } catch (e) {\n throw new Error(\n `Agent step \"${entryId}\" cannot be stored: structuredOutput.schema is not convertible to JSON Schema (${(e as Error).message}).`,\n );\n }\n}\n","/**\n * Storable → Runnable half of the workflow round-trip: rebuild a runnable\n * `Workflow` from the stored JSON form. References to agents/tools/workflows\n * are resolved against the live Mastra instance; throws if a reference is\n * missing — better to surface the failure at load time than at run time.\n */\nimport type { Mastra } from '../../mastra';\nimport { cloneWorkflow, createEventedWorkflow, createWorkflow } from '../create';\nimport { derivePredicateLabel } from '../predicate';\nimport type { WorkflowScheduleConfig } from '../scheduler/types';\nimport type { Step } from '../step';\nimport { createStepFromAgent, createStepFromTool } from '../step-factories';\nimport type { SerializedSingleStepEntry, SerializedStepOptions, SingleStepEntry, StepFlowEntry } from '../types';\nimport { getSingleStepEntryId } from '../utils';\nimport { mapVariable, predicateToCondition } from '../workflow';\nimport { jsonSchemaToZod } from './json-schema-to-zod';\nimport type { JsonSchema, JsonSchemaToZodOptions } from './json-schema-to-zod';\nimport { parseMapConfig } from './mapping-config';\nimport { entryOptionFields } from './serialize';\nimport type { ValidatableStepFlowEntry } from './validate/types';\n\n/**\n * JSON shape persisted to WorkflowDefinitionsStorage, and the same shape\n * `addDynamicWorkflows` hydrates from before it writes the row.\n */\nexport interface DynamicWorkflowGraph {\n id: string;\n description?: string;\n metadata?: Record<string, unknown>;\n inputSchema: JsonSchema;\n outputSchema: JsonSchema;\n stateSchema?: JsonSchema;\n requestContextSchema?: JsonSchema;\n graph: ValidatableStepFlowEntry[];\n /**\n * Optional declarative schedule config(s), preserved through the storage\n * round-trip so rehydrated workflows re-declare their schedules on boot —\n * without this, boot-time declarative schedule sync would treat the\n * persisted `wf_*` schedule rows as orphans and delete them.\n */\n schedule?: WorkflowScheduleConfig | WorkflowScheduleConfig[];\n}\n\n/**\n * Wrapper so the return value isn't recognized as a thenable by `await`.\n * `Workflow` carries a `.then(step)` builder method — returning one directly\n * from an `async` function (or any `await`-ed call) makes the runtime call\n * that builder method as a Promise resolver and the call hangs forever.\n * Always destructure: `const { workflow } = await rehydrateWorkflow(...)`.\n */\nexport interface RehydratedWorkflow {\n workflow: any;\n}\n\n/**\n * Options controlling how `rehydrateWorkflow` handles unsupported JSON Schema\n * keywords. Forwarded to `jsonSchemaToZod` for every schema on the definition\n * (top-level + per-step `agent.outputSchema`). See `JsonSchemaToZodOptions`.\n */\nexport type RehydrateWorkflowOptions = JsonSchemaToZodOptions & {\n engineType?: 'default' | 'evented';\n};\n\nexport async function rehydrateWorkflow(\n def: DynamicWorkflowGraph,\n mastra: Mastra,\n opts?: RehydrateWorkflowOptions,\n): Promise<RehydratedWorkflow> {\n const inputSchema = jsonSchemaToZod(def.inputSchema, opts);\n const outputSchema = jsonSchemaToZod(def.outputSchema, opts);\n const stateSchema = def.stateSchema ? jsonSchemaToZod(def.stateSchema, opts) : undefined;\n const requestContextSchema = def.requestContextSchema ? jsonSchemaToZod(def.requestContextSchema, opts) : undefined;\n\n const baseParams = {\n id: def.id,\n description: def.description,\n metadata: def.metadata,\n inputSchema: inputSchema as any,\n outputSchema: outputSchema as any,\n stateSchema: stateSchema as any,\n requestContextSchema: requestContextSchema as any,\n };\n\n const factory = opts?.engineType === 'evented' ? createEventedWorkflow : createWorkflow;\n let wf;\n if (def.schedule === undefined) {\n wf = factory(baseParams);\n } else {\n try {\n // The cron expression(s) are validated at construction time.\n wf = factory({ ...baseParams, schedule: def.schedule as any });\n } catch (error) {\n // A bad stored schedule shouldn't sink the whole workflow: degrade to\n // an unscheduled workflow and surface the problem.\n if (opts?.onUnsupportedSchema !== 'warn') throw error;\n opts.onUnsupported?.(\n `Ignoring invalid stored schedule config: ${error instanceof Error ? error.message : String(error)}`,\n );\n wf = factory(baseParams);\n }\n }\n\n for (const entry of def.graph) {\n applyGraphEntry(wf, entry, mastra, opts);\n }\n const built: any = wf.commit();\n built.origin = 'dynamic';\n return { workflow: built };\n}\n\nfunction applyGraphEntry(\n wf: any,\n entry: ValidatableStepFlowEntry,\n mastra: Mastra,\n schemaOpts?: JsonSchemaToZodOptions,\n): void {\n switch (entry.type) {\n case 'agent':\n case 'tool':\n case 'classifier':\n wf.__pushStepFlowEntry(rehydrateSingleEntry(entry, mastra, schemaOpts), entry);\n return;\n case 'mapping': {\n const cfg = parseMapConfig(entry.mapConfig, entry.id);\n const live = rehydrateMapConfig(cfg, mastra);\n wf.map(live, { id: entry.id, description: entry.description, metadata: entry.metadata });\n return;\n }\n case 'sleep': {\n if (typeof entry.duration !== 'number') {\n throw new Error(`Stored sleep \"${entry.id}\" missing literal duration.`);\n }\n // Push directly (not wf.sleep()) so the stored step id survives the\n // round-trip — the builder generates a fresh random id per call.\n const live: StepFlowEntry = {\n type: 'sleep',\n ...entryOptionFields(entry),\n id: entry.id,\n duration: entry.duration,\n };\n wf.__pushStepFlowEntry(live, live);\n return;\n }\n case 'sleepUntil': {\n if (!(entry.date instanceof Date) && typeof entry.date !== 'string') {\n throw new Error(`Stored sleepUntil \"${entry.id}\" missing literal date.`);\n }\n const date = entry.date instanceof Date ? entry.date : new Date(entry.date);\n if (Number.isNaN(date.getTime())) {\n throw new Error(`Stored sleepUntil \"${entry.id}\" has an unparseable date: ${String(entry.date)}`);\n }\n const live: StepFlowEntry = { type: 'sleepUntil', ...entryOptionFields(entry), id: entry.id, date };\n wf.__pushStepFlowEntry(live, { type: 'sleepUntil', ...entryOptionFields(entry), id: entry.id, date });\n return;\n }\n case 'parallel': {\n const live: StepFlowEntry = {\n type: 'parallel',\n ...entryOptionFields(entry),\n steps: entry.steps.map(s => rehydrateSingleEntry(s, mastra, schemaOpts)),\n };\n wf.__pushStepFlowEntry(live, entry);\n return;\n }\n case 'foreach': {\n if (entry.step.type === 'mapping') {\n throw new Error(\n `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.`,\n );\n }\n const live: StepFlowEntry = {\n type: 'foreach',\n ...entryOptionFields(entry),\n step: rehydrateSingleEntry(entry.step, mastra, schemaOpts),\n opts: { concurrency: entry.opts?.concurrency ?? 1 },\n };\n wf.__pushStepFlowEntry(live, entry);\n return;\n }\n case 'step': {\n const live = rehydrateSingleEntry(entry, mastra, schemaOpts);\n wf.__pushStepFlowEntry(live, entry);\n return;\n }\n case 'workflow': {\n const nested = assertWorkflowExists(mastra, entry.workflowId);\n // A nested workflow executes as its own `Workflow`, so the engine keys its\n // result by the workflow's intrinsic id. The portable definition addresses\n // it by the declared call-site id, which is what mappings, predicates and\n // `${stepResults...}` templates reference. Clone it under the declared id so\n // every reference resolves instead of silently falling back to `initData`.\n wf.then(entry.id && entry.id !== nested.id ? cloneWorkflow(nested as any, { id: entry.id }) : nested);\n return;\n }\n case 'conditional': {\n const predicates = entry.predicates;\n if (!predicates || predicates.length !== entry.steps.length || predicates.some(p => !p)) {\n throw new Error(\n `Cannot rehydrate conditional step: missing or mismatched predicates. Only declarative predicate branches round-trip.`,\n );\n }\n const steps = entry.steps.map(s => rehydrateSingleEntry(s, mastra, schemaOpts));\n // Wire graphs may omit the Studio-facing condition labels; derive them\n // from the predicates (same convention as the fluent builder).\n const serializedConditions =\n entry.serializedConditions ??\n steps.map((s, i) => ({ id: `${getSingleStepEntryId(s)}-condition`, fn: derivePredicateLabel(predicates[i]!) }));\n const live: StepFlowEntry = {\n type: 'conditional',\n ...entryOptionFields(entry),\n steps,\n conditions: predicates.map(p => predicateToCondition(p!)),\n serializedConditions,\n predicates,\n };\n wf.__pushStepFlowEntry(live, { ...entry, serializedConditions });\n return;\n }\n case 'loop': {\n const { predicate, loopType } = entry;\n if (!predicate || (loopType !== 'dowhile' && loopType !== 'dountil')) {\n throw new Error(\n `Cannot rehydrate loop step: missing declarative predicate or loopType. Only declarative predicate loops round-trip.`,\n );\n }\n const step = rehydrateSingleEntry(entry.step, mastra, schemaOpts);\n const serializedCondition = entry.serializedCondition ?? {\n id: `${getSingleStepEntryId(step)}-condition`,\n fn: derivePredicateLabel(predicate),\n };\n const live: StepFlowEntry = {\n type: 'loop',\n ...entryOptionFields(entry),\n step,\n condition: predicateToCondition(predicate),\n loopType,\n serializedCondition,\n predicate,\n };\n wf.__pushStepFlowEntry(live, { ...entry, serializedCondition });\n return;\n }\n default: {\n const _exhaustive: never = entry;\n throw new Error(`Unknown stored step type: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\n/**\n * Reconstruct the options bag `.agent()` accepts from a serialized entry.\n * Restores `structuredOutput.schema` from `outputSchema` (JSON Schema → Zod)\n * and merges in `retries` / `metadata`. Returns `undefined` when nothing to\n * restore so `.agent(agentId)` stays a clean call.\n */\nfunction rebuildAgentOptions(\n entry: {\n outputSchema?: Record<string, any>;\n options?: SerializedStepOptions;\n },\n schemaOpts?: JsonSchemaToZodOptions,\n): Record<string, any> | undefined {\n const opts: Record<string, any> = {};\n if (entry.outputSchema) {\n opts.structuredOutput = { schema: jsonSchemaToZod(entry.outputSchema, schemaOpts) };\n }\n if (entry.options?.retries !== undefined) opts.retries = entry.options.retries;\n if (entry.options?.metadata !== undefined) opts.metadata = entry.options.metadata;\n return Object.keys(opts).length > 0 ? opts : undefined;\n}\n\nfunction rebuildToolOptions(entry: { options?: SerializedStepOptions }): Record<string, any> | undefined {\n const opts: Record<string, any> = {};\n if (entry.options?.retries !== undefined) opts.retries = entry.options.retries;\n if (entry.options?.metadata !== undefined) opts.metadata = entry.options.metadata;\n return Object.keys(opts).length > 0 ? opts : undefined;\n}\n\n/**\n * Build the live `SingleStepEntry` for a stored entry. Declarative agent/tool\n * entries stay declarative — both engines interpret them per-kind at\n * execution time (`runAgentEntry` / `runToolEntry`) — so no fake `Step`\n * wrapper is needed and the stored `id` / `outputSchema` / `retries` /\n * `metadata` round-trip losslessly in every position (top-level, parallel,\n * branch, foreach and loop bodies).\n *\n * `step` descriptors resolve agent-then-tool by id against the live Mastra\n * instance; `workflow` entries resolve the registered instance. Both become\n * plain `{ type: 'step' }` entries, same as the fluent builder emits.\n */\nfunction rehydrateSingleEntry(\n entry: SerializedSingleStepEntry,\n mastra: Mastra,\n schemaOpts?: JsonSchemaToZodOptions,\n): SingleStepEntry {\n switch (entry.type) {\n case 'agent': {\n const agent = tryGetAgentById(mastra, entry.agentId);\n if (!agent) {\n throw new Error(\n `Dynamic workflow references agent \"${entry.agentId}\" which is not registered on this Mastra instance.`,\n );\n }\n return {\n type: 'agent',\n id: entry.id,\n agentId: entry.agentId,\n agent,\n options: rebuildAgentOptions(entry, schemaOpts),\n };\n }\n case 'tool': {\n const tool = mastra.getTool?.(entry.toolId);\n if (!tool) {\n throw new Error(\n `Dynamic workflow references tool \"${entry.toolId}\" which is not registered on this Mastra instance.`,\n );\n }\n return { type: 'tool', id: entry.id, toolId: entry.toolId, tool, options: rebuildToolOptions(entry) };\n }\n case 'classifier': {\n let classifier;\n try {\n classifier = mastra.getClassifierById(entry.classifierId);\n } catch {\n throw new Error(\n `Dynamic workflow references classifier \"${entry.classifierId}\" which is not registered on this Mastra instance.`,\n );\n }\n return {\n type: 'classifier',\n id: entry.id,\n classifierId: entry.classifierId,\n classifier,\n options: entry.options,\n };\n }\n case 'step': {\n const { id } = entry.step;\n // Wrap the resolved agent/tool in a real Step (same adapters `createStep`\n // uses) so the entry honors the executeStep contract instead of casting a\n // raw Agent/Tool instance — those don't carry a step-shaped `execute`.\n const agent = tryGetAgentById(mastra, id);\n if (agent) {\n return { type: 'step', step: createStepFromAgent(agent) as unknown as Step };\n }\n const tool = tryGetToolById(mastra, id);\n if (tool) {\n return { type: 'step', step: createStepFromTool(tool as any) as unknown as Step };\n }\n throw new Error(\n `Dynamic workflow references step \"${id}\" which is not registered as an agent or tool on this Mastra instance.`,\n );\n }\n case 'workflow': {\n const nested = assertWorkflowExists(mastra, entry.workflowId);\n // Same call-site identity rule as top-level nested workflows: run the\n // clone under the declared id so results are keyed the way the portable\n // definition addresses them.\n const step = entry.id && entry.id !== nested.id ? cloneWorkflow(nested as any, { id: entry.id }) : nested;\n return { type: 'step', step: step as unknown as Step };\n }\n case 'mapping':\n throw new Error(\n `mapping entries cannot appear inside .parallel(), .branch(), or .foreach(); they must be top-level.`,\n );\n }\n}\n\n/**\n * Rebuild the object shape that `.map()` accepts. Step sources remain workflow-local\n * step IDs because mapping execution resolves them from the run's step results.\n */\nfunction rehydrateMapConfig(cfg: Record<string, any>, mastra: Mastra): Record<string, any> {\n const out: Record<string, any> = {};\n for (const [key, source] of Object.entries(cfg)) {\n if (!source || typeof source !== 'object') {\n out[key] = source;\n continue;\n }\n if ('template' in source) {\n out[key] = { template: source.template };\n } else if ('value' in source) {\n out[key] = { value: source.value };\n } else if ('requestContextPath' in source) {\n out[key] = { requestContextPath: source.requestContextPath };\n } else if ('initData' in source && typeof source.initData === 'string') {\n const wf = mastra.getWorkflow?.(source.initData);\n if (!wf) {\n throw new Error(`Mapping references unknown workflow init-data \"${source.initData}\".`);\n }\n out[key] = mapVariable({ initData: wf as any, path: source.path });\n } else if ('step' in source) {\n out[key] = mapVariable({ step: source.step as any, path: source.path });\n } else {\n out[key] = source;\n }\n }\n return out;\n}\n\n/**\n * Mastra.getAgentById throws when the id isn't registered; every by-id\n * resolution path in this file wants a nullable \"does it exist?\" answer so it\n * can fall through to a tool lookup or a targeted error. Swallow the not-found\n * throw and return undefined.\n */\nfunction tryGetAgentById(mastra: Mastra, id: string): any | undefined {\n if (!id || typeof mastra.getAgentById !== 'function') return undefined;\n try {\n return mastra.getAgentById(id);\n } catch {\n return undefined;\n }\n}\n\n/** Same nullable-lookup contract as `tryGetAgentById`, for tools — `Mastra.getTool` throws on a missing id. */\nfunction tryGetToolById(mastra: Mastra, id: string): any | undefined {\n if (!id || typeof mastra.getTool !== 'function') return undefined;\n try {\n return mastra.getTool(id);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Workflow references resolve like agent references: intrinsic workflow id\n * first (`getWorkflowById` scans registered workflows by their own `id`),\n * falling back to the registration key. Stored definitions reference the\n * intrinsic id — the identity discovery advertises — which may differ from\n * the key the workflow was registered under (`workflows: { greetingWorkflow }`\n * vs `id: 'greeting-workflow'`).\n */\nfunction tryGetWorkflowById(mastra: Mastra, id: string): any | undefined {\n if (!id) return undefined;\n if (typeof (mastra as any).getWorkflowById === 'function') {\n try {\n return (mastra as any).getWorkflowById(id);\n } catch {\n // fall through to registration-key lookup\n }\n }\n if (typeof (mastra as any).getWorkflow !== 'function') return undefined;\n try {\n return (mastra as any).getWorkflow(id);\n } catch {\n return undefined;\n }\n}\n\nfunction assertWorkflowExists(mastra: Mastra, workflowId: string): any {\n const wf = tryGetWorkflowById(mastra, workflowId);\n if (!wf) {\n throw new Error(\n `Dynamic workflow references nested workflow \"${workflowId}\" which is not registered on this Mastra instance.`,\n );\n }\n return wf;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,kBAAkB,OAIT;CACvB,MAA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