@mastra/core 0.23.2 → 0.24.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +87 -0
- package/dist/agent/agent.d.ts +6 -0
- package/dist/agent/agent.d.ts.map +1 -1
- package/dist/agent/index.cjs +10 -10
- package/dist/agent/index.js +1 -1
- package/dist/agent/input-processor/index.cjs +6 -6
- package/dist/agent/input-processor/index.js +1 -1
- package/dist/{chunk-F7DVKNKD.cjs → chunk-253FBVD4.cjs} +25 -21
- package/dist/chunk-253FBVD4.cjs.map +1 -0
- package/dist/{chunk-Q7Y7FU4Y.js → chunk-2B3VLGTH.js} +3 -3
- package/dist/{chunk-Q7Y7FU4Y.js.map → chunk-2B3VLGTH.js.map} +1 -1
- package/dist/{chunk-ELFP5KHN.js → chunk-3VXXCPKX.js} +3 -3
- package/dist/{chunk-ELFP5KHN.js.map → chunk-3VXXCPKX.js.map} +1 -1
- package/dist/{chunk-JZGCSEW5.js → chunk-6C7VGVK4.js} +3 -3
- package/dist/{chunk-JZGCSEW5.js.map → chunk-6C7VGVK4.js.map} +1 -1
- package/dist/{chunk-OLFLBDUQ.cjs → chunk-77JHIM4E.cjs} +12 -12
- package/dist/{chunk-OLFLBDUQ.cjs.map → chunk-77JHIM4E.cjs.map} +1 -1
- package/dist/{chunk-CL6Z33KH.cjs → chunk-7J3XX4AO.cjs} +86 -12
- package/dist/chunk-7J3XX4AO.cjs.map +1 -0
- package/dist/{chunk-EV64MRWJ.cjs → chunk-ABZOBBLL.cjs} +4 -4
- package/dist/{chunk-EV64MRWJ.cjs.map → chunk-ABZOBBLL.cjs.map} +1 -1
- package/dist/{chunk-4RWU3F4F.js → chunk-BWGXM3D4.js} +3 -3
- package/dist/{chunk-4RWU3F4F.js.map → chunk-BWGXM3D4.js.map} +1 -1
- package/dist/{chunk-5YHNPD6A.cjs → chunk-C7OVZMPW.cjs} +4 -4
- package/dist/{chunk-5YHNPD6A.cjs.map → chunk-C7OVZMPW.cjs.map} +1 -1
- package/dist/{chunk-ICGCDCJE.js → chunk-FHVFGVIO.js} +85 -11
- package/dist/chunk-FHVFGVIO.js.map +1 -0
- package/dist/{chunk-WCTRQHTG.cjs → chunk-HEQTUMUA.cjs} +4 -4
- package/dist/{chunk-WCTRQHTG.cjs.map → chunk-HEQTUMUA.cjs.map} +1 -1
- package/dist/{chunk-ML3WETVK.js → chunk-LG5B3KIW.js} +24 -20
- package/dist/chunk-LG5B3KIW.js.map +1 -0
- package/dist/{chunk-PHMC6B3L.cjs → chunk-ROS5CMJS.cjs} +11 -11
- package/dist/{chunk-PHMC6B3L.cjs.map → chunk-ROS5CMJS.cjs.map} +1 -1
- package/dist/{chunk-OSAYWQD3.js → chunk-Z4RIRDU3.js} +4 -4
- package/dist/{chunk-OSAYWQD3.js.map → chunk-Z4RIRDU3.js.map} +1 -1
- package/dist/index.cjs +32 -32
- package/dist/index.js +7 -7
- package/dist/llm/index.cjs +7 -7
- package/dist/llm/index.js +1 -1
- package/dist/llm/model/provider-types.generated.d.ts +36 -3
- package/dist/loop/index.cjs +2 -2
- package/dist/loop/index.js +1 -1
- package/dist/loop/network/index.d.ts.map +1 -1
- package/dist/mastra/index.cjs +2 -2
- package/dist/mastra/index.js +1 -1
- package/dist/memory/index.cjs +4 -4
- package/dist/memory/index.js +1 -1
- package/dist/processors/index.cjs +11 -11
- package/dist/processors/index.js +1 -1
- package/dist/processors/runner.d.ts.map +1 -1
- package/dist/provider-registry.json +83 -9
- package/dist/relevance/index.cjs +4 -4
- package/dist/relevance/index.js +1 -1
- package/dist/scores/index.cjs +4 -4
- package/dist/scores/index.js +1 -1
- package/dist/scores/scoreTraces/index.cjs +3 -3
- package/dist/scores/scoreTraces/index.js +1 -1
- package/dist/stream/RunOutput.d.ts.map +1 -1
- package/dist/stream/index.cjs +8 -8
- package/dist/stream/index.js +1 -1
- package/dist/workflows/default.d.ts +9 -4
- package/dist/workflows/default.d.ts.map +1 -1
- package/dist/workflows/evented/index.cjs +10 -10
- package/dist/workflows/evented/index.js +1 -1
- package/dist/workflows/index.cjs +14 -14
- package/dist/workflows/index.js +1 -1
- package/dist/workflows/legacy/index.cjs +22 -22
- package/dist/workflows/legacy/index.js +1 -1
- package/dist/workflows/types.d.ts +16 -4
- package/dist/workflows/types.d.ts.map +1 -1
- package/dist/workflows/workflow.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/llm/model/provider-types.generated.d.ts +36 -3
- package/dist/chunk-CL6Z33KH.cjs.map +0 -1
- package/dist/chunk-F7DVKNKD.cjs.map +0 -1
- package/dist/chunk-ICGCDCJE.js.map +0 -1
- package/dist/chunk-ML3WETVK.js.map +0 -1
|
@@ -4,7 +4,7 @@ var chunkWBAXXG34_cjs = require('./chunk-WBAXXG34.cjs');
|
|
|
4
4
|
var chunkABJOUEVA_cjs = require('./chunk-ABJOUEVA.cjs');
|
|
5
5
|
var chunkAQGLVU53_cjs = require('./chunk-AQGLVU53.cjs');
|
|
6
6
|
var chunkMJMID7LX_cjs = require('./chunk-MJMID7LX.cjs');
|
|
7
|
-
var
|
|
7
|
+
var chunk7J3XX4AO_cjs = require('./chunk-7J3XX4AO.cjs');
|
|
8
8
|
var chunkMCASUJWY_cjs = require('./chunk-MCASUJWY.cjs');
|
|
9
9
|
var chunkTSNDVBUU_cjs = require('./chunk-TSNDVBUU.cjs');
|
|
10
10
|
var chunk4WQYXT2I_cjs = require('./chunk-4WQYXT2I.cjs');
|
|
@@ -229,18 +229,18 @@ function prepareToolsAndToolChoice({tools,toolChoice,activeTools}){if(Object.key
|
|
|
229
229
|
id:sdkTool.id,args:sdkTool.args};default:{const exhaustiveCheck=toolType;throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);}}}catch(e){console.error("Error preparing tool",e);return null;}}).filter(tool=>tool!==null),toolChoice:toolChoice==null?{type:"auto"}:typeof toolChoice==="string"?{type:toolChoice}:{type:"tool",toolName:toolChoice.toolName}};}// src/stream/aisdk/v5/compat/consume-stream.ts
|
|
230
230
|
async function consumeStream({stream,onError}){const reader=stream.getReader();try{while(true){const{done}=await reader.read();if(done)break;}}catch(error){console.error("consumeStream error",error);onError?.(error);}finally{reader.releaseLock();}}// src/agent/agent.ts
|
|
231
231
|
var import_fast_deep_equal2=chunkEBVYYC2Q_cjs.__toESM(require_fast_deep_equal(),1);async function consumeStream2({stream,onError}){const reader=stream.getReader();try{while(true){const{done}=await reader.read();if(done)break;}}catch(error){onError==null?void 0:onError(error);}finally{reader.releaseLock();}}// src/stream/RunOutput.ts
|
|
232
|
-
var WorkflowRunOutput=class{#status="running";#usageCount={inputTokens:0,outputTokens:0,totalTokens:0,cachedInputTokens:0,reasoningTokens:0};#consumptionStarted=false;#baseStream;#emitter=new EventEmitter__default.default();#bufferedChunks=[];#streamFinished=false;#delayedPromises={usage:new DelayedPromise(),result:new DelayedPromise()};/**
|
|
232
|
+
var WorkflowRunOutput=class{#status="running";#usageCount={inputTokens:0,outputTokens:0,totalTokens:0,cachedInputTokens:0,reasoningTokens:0};#consumptionStarted=false;#baseStream;#emitter=new EventEmitter__default.default();#bufferedChunks=[];#streamFinished=false;#streamError;#delayedPromises={usage:new DelayedPromise(),result:new DelayedPromise()};/**
|
|
233
233
|
* Unique identifier for this workflow run
|
|
234
234
|
*/runId;/**
|
|
235
235
|
* Unique identifier for this workflow
|
|
236
|
-
*/workflowId;constructor({runId,workflowId,stream}){const self=this;this.runId=runId;this.workflowId=workflowId;this.#baseStream=stream;stream.pipeTo(new WritableStream({start(){const chunk={type:"workflow-start",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowId:self.workflowId}};self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);},write(chunk){if(chunk.type!=="workflow-step-finish"){self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);}if(chunk.type==="workflow-step-finish"&&chunk.payload.usage){self.#updateUsageCount(chunk.payload.usage);}else if(chunk.type==="workflow-canceled"){self.#status="canceled";}else if(chunk.type==="workflow-step-suspended"){self.#status="suspended";}else if(chunk.type==="workflow-step-result"&&chunk.payload.status==="failed"){self.#status="failed";}},close(){if(self.#status==="running"){self.#status="success";}self.#emitter.emit("chunk",{type:"workflow-finish",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowStatus:self.#status,metadata:{},output:{// @ts-ignore
|
|
236
|
+
*/workflowId;constructor({runId,workflowId,stream}){const self=this;this.runId=runId;this.workflowId=workflowId;this.#baseStream=stream;stream.pipeTo(new WritableStream({start(){const chunk={type:"workflow-start",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowId:self.workflowId}};self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);},write(chunk){if(chunk.type!=="workflow-step-finish"){self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);}if(chunk.type==="workflow-step-finish"&&chunk.payload.usage){self.#updateUsageCount(chunk.payload.usage);}else if(chunk.type==="workflow-canceled"){self.#status="canceled";}else if(chunk.type==="workflow-step-suspended"){self.#status="suspended";}else if(chunk.type==="workflow-step-result"&&chunk.payload.status==="failed"){self.#status="failed";}},close(){if(self.#status==="running"){self.#status="success";}self.#emitter.emit("chunk",{type:"workflow-finish",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowStatus:self.#status,metadata:self.#streamError?{error:self.#streamError,errorMessage:self.#streamError?.message}:{},output:{// @ts-ignore
|
|
237
237
|
usage:self.#usageCount}}});self.#delayedPromises.usage.resolve(self.#usageCount);Object.entries(self.#delayedPromises).forEach(([key,promise])=>{if(promise.status.type==="pending"){promise.reject(new Error(`promise '${key}' was not resolved or rejected when stream finished`));}});self.#streamFinished=true;self.#emitter.emit("finish");}})).catch(reason=>{console.log(" something went wrong",reason);});}#getDelayedPromise(promise){if(!this.#consumptionStarted){void this.consumeStream();}return promise.promise;}#updateUsageCount(usage){let totalUsage={inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0};if("inputTokens"in usage){totalUsage.inputTokens+=parseInt(usage?.inputTokens?.toString()??"0",10);totalUsage.outputTokens+=parseInt(usage?.outputTokens?.toString()??"0",10);}else if("promptTokens"in usage){totalUsage.inputTokens+=parseInt(usage?.promptTokens?.toString()??"0",10);totalUsage.outputTokens+=parseInt(usage?.completionTokens?.toString()??"0",10);}totalUsage.totalTokens+=parseInt(usage?.totalTokens?.toString()??"0",10);totalUsage.reasoningTokens+=parseInt(usage?.reasoningTokens?.toString()??"0",10);totalUsage.cachedInputTokens+=parseInt(usage?.cachedInputTokens?.toString()??"0",10);this.#usageCount=totalUsage;}/**
|
|
238
238
|
* @internal
|
|
239
239
|
*/updateResults(results){this.#delayedPromises.result.resolve(results);}/**
|
|
240
240
|
* @internal
|
|
241
|
-
*/rejectResults(error){this.#delayedPromises.result.reject(error);}/**
|
|
241
|
+
*/rejectResults(error){this.#delayedPromises.result.reject(error);this.#status="failed";this.#streamError=error;}/**
|
|
242
242
|
* @internal
|
|
243
|
-
*/resume(stream){this.#baseStream=stream;this.#streamFinished=false;this.#consumptionStarted=false;this.#status="running";this.#delayedPromises={usage:new DelayedPromise(),result:new DelayedPromise()};const self=this;stream.pipeTo(new WritableStream({start(){const chunk={type:"workflow-start",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowId:self.workflowId}};self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);},write(chunk){if(chunk.type!=="workflow-step-finish"){self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);}if(chunk.type==="workflow-step-finish"&&chunk.payload.usage){self.#updateUsageCount(chunk.payload.usage);}else if(chunk.type==="workflow-canceled"){self.#status="canceled";}else if(chunk.type==="workflow-step-suspended"){self.#status="suspended";}else if(chunk.type==="workflow-step-result"&&chunk.payload.status==="failed"){self.#status="failed";}},close(){if(self.#status==="running"){self.#status="success";}self.#emitter.emit("chunk",{type:"workflow-finish",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowStatus:self.#status,metadata:{},output:{// @ts-ignore
|
|
243
|
+
*/resume(stream){this.#baseStream=stream;this.#streamFinished=false;this.#consumptionStarted=false;this.#status="running";this.#delayedPromises={usage:new DelayedPromise(),result:new DelayedPromise()};const self=this;stream.pipeTo(new WritableStream({start(){const chunk={type:"workflow-start",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowId:self.workflowId}};self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);},write(chunk){if(chunk.type!=="workflow-step-finish"){self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);}if(chunk.type==="workflow-step-finish"&&chunk.payload.usage){self.#updateUsageCount(chunk.payload.usage);}else if(chunk.type==="workflow-canceled"){self.#status="canceled";}else if(chunk.type==="workflow-step-suspended"){self.#status="suspended";}else if(chunk.type==="workflow-step-result"&&chunk.payload.status==="failed"){self.#status="failed";}},close(){if(self.#status==="running"){self.#status="success";}self.#emitter.emit("chunk",{type:"workflow-finish",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowStatus:self.#status,metadata:self.#streamError?{error:self.#streamError,errorMessage:self.#streamError?.message}:{},output:{// @ts-ignore
|
|
244
244
|
usage:self.#usageCount}}});self.#streamFinished=true;self.#emitter.emit("finish");}})).catch(reason=>{console.log(" something went wrong",reason);});}async consumeStream(options){if(this.#consumptionStarted){return;}this.#consumptionStarted=true;try{await consumeStream2({stream:this.#baseStream,onError:options?.onError});}catch(error){options?.onError?.(error);}}get fullStream(){const self=this;return new web.ReadableStream({start(controller){self.#bufferedChunks.forEach(chunk=>{controller.enqueue(chunk);});if(self.#streamFinished){controller.close();return;}const chunkHandler=chunk=>{controller.enqueue(chunk);};const finishHandler=()=>{self.#emitter.off("chunk",chunkHandler);self.#emitter.off("finish",finishHandler);controller.close();};self.#emitter.on("chunk",chunkHandler);self.#emitter.on("finish",finishHandler);},pull(_controller){if(!self.#consumptionStarted){void self.consumeStream();}},cancel(){self.#emitter.removeAllListeners();}});}get status(){return this.#status;}get result(){return this.#getDelayedPromise(this.#delayedPromises.result);}get usage(){return this.#getDelayedPromise(this.#delayedPromises.usage);}/**
|
|
245
245
|
* @deprecated Use `fullStream.locked` instead
|
|
246
246
|
*/get locked(){console.warn("WorkflowRunOutput.locked is deprecated. Use fullStream.locked instead.");return this.fullStream.locked;}/**
|
|
@@ -283,16 +283,16 @@ var DefaultExecutionEngine=class extends ExecutionEngine{/**
|
|
|
283
283
|
* @param graph The execution graph to execute
|
|
284
284
|
* @param input The input data for the workflow
|
|
285
285
|
* @returns A promise that resolves to the workflow output
|
|
286
|
-
*/async execute(params){const{workflowId,runId,resourceId,graph,input,initialState,resume,retryConfig,workflowAISpan,disableScorers}=params;const{attempts=0,delay:delay2=0}=retryConfig??{};const steps=graph.steps;this.runCounts.clear();if(steps.length===0){const empty_graph_error=new chunk5NTO7S5I_cjs.MastraError({id:"WORKFLOW_EXECUTE_EMPTY_GRAPH",text:"Workflow must have at least one step",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */});workflowAISpan?.error({error:empty_graph_error});throw empty_graph_error;}const executionSpan=this.mastra?.getTelemetry()?.tracer.startSpan(`workflow.${workflowId}.execute`,{attributes:{componentName:workflowId,runId,resourceId}});let startIdx=0;if(resume?.resumePath){startIdx=resume.resumePath[0];resume.resumePath.shift();}const stepResults=resume?.stepResults||{input};let lastOutput;let lastState=initialState??{};for(let i=startIdx;i<steps.length;i++){const entry=steps[i];const executionContext={workflowId,runId,executionPath:[i],suspendedPaths:{},resumeLabels:{},retryConfig:{attempts,delay:delay2},executionSpan,format:params.format,state:lastState??initialState};try{lastOutput=await this.executeEntry({workflowId,runId,resourceId,entry,executionContext,serializedStepGraph:params.serializedStepGraph,prevStep:steps[i-1],stepResults,resume,tracingContext:{currentSpan:workflowAISpan},abortController:params.abortController,emitter:params.emitter,runtimeContext:params.runtimeContext,writableStream:params.writableStream,disableScorers});if(lastOutput.executionContext?.state){lastState=lastOutput.executionContext.state;}if(lastOutput.result.status!=="success"){if(lastOutput.result.status==="bailed"){lastOutput.result.status="success";}const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});if(result2.error){workflowAISpan?.error({error:result2.error,attributes:{status:result2.status}});}else {workflowAISpan?.end({output:result2.result,attributes:{status:result2.status}});}if(lastOutput.result.status==="suspended"&¶ms.outputOptions?.includeResumeLabels){return {...result2,resumeLabels:lastOutput.executionContext?.resumeLabels};}return result2;}}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_ENGINE_STEP_EXECUTION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error executing step: ");const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result,e);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});workflowAISpan?.error({error,attributes:{status:result2.status}});return result2;}}const result=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result.status,result:result.result,error:result.error,runtimeContext:params.runtimeContext});workflowAISpan?.end({output:result.result,attributes:{status:result.status}});if(params.outputOptions?.includeState){return {...result,state:lastState};}return result;}getStepOutput(stepResults,step){if(!step){return stepResults.input;}else if(step.type==="step"||step.type==="waitForEvent"){return stepResults[step.step.id]?.output;}else if(step.type==="sleep"||step.type==="sleepUntil"){return stepResults[step.id]?.output;}else if(step.type==="parallel"||step.type==="conditional"){return step.steps.reduce((acc,entry)=>{
|
|
286
|
+
*/async execute(params){const{workflowId,runId,resourceId,graph,input,initialState,resume,retryConfig,workflowAISpan,disableScorers}=params;const{attempts=0,delay:delay2=0}=retryConfig??{};const steps=graph.steps;this.runCounts.clear();if(steps.length===0){const empty_graph_error=new chunk5NTO7S5I_cjs.MastraError({id:"WORKFLOW_EXECUTE_EMPTY_GRAPH",text:"Workflow must have at least one step",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */});workflowAISpan?.error({error:empty_graph_error});throw empty_graph_error;}const executionSpan=this.mastra?.getTelemetry()?.tracer.startSpan(`workflow.${workflowId}.execute`,{attributes:{componentName:workflowId,runId,resourceId}});let startIdx=0;if(resume?.resumePath){startIdx=resume.resumePath[0];resume.resumePath.shift();}const stepResults=resume?.stepResults||{input};let lastOutput;let lastState=initialState??{};for(let i=startIdx;i<steps.length;i++){const entry=steps[i];const executionContext={workflowId,runId,executionPath:[i],suspendedPaths:{},resumeLabels:{},retryConfig:{attempts,delay:delay2},executionSpan,format:params.format,state:lastState??initialState};try{lastOutput=await this.executeEntry({workflowId,runId,resourceId,entry,executionContext,serializedStepGraph:params.serializedStepGraph,prevStep:steps[i-1],stepResults,resume,tracingContext:{currentSpan:workflowAISpan},abortController:params.abortController,emitter:params.emitter,runtimeContext:params.runtimeContext,writableStream:params.writableStream,disableScorers});if(lastOutput.executionContext?.state){lastState=lastOutput.executionContext.state;}if(lastOutput.result.status!=="success"){if(lastOutput.result.status==="bailed"){lastOutput.result.status="success";}const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});if(result2.error){workflowAISpan?.error({error:result2.error,attributes:{status:result2.status}});}else {workflowAISpan?.end({output:result2.result,attributes:{status:result2.status}});}if(lastOutput.result.status==="suspended"&¶ms.outputOptions?.includeResumeLabels){return {...result2,resumeLabels:lastOutput.executionContext?.resumeLabels};}return result2;}}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_ENGINE_STEP_EXECUTION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error executing step: ");const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result,e);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});workflowAISpan?.error({error,attributes:{status:result2.status}});return result2;}}const result=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result.status,result:result.result,error:result.error,runtimeContext:params.runtimeContext});workflowAISpan?.end({output:result.result,attributes:{status:result.status}});if(params.outputOptions?.includeState){return {...result,state:lastState};}return result;}getStepOutput(stepResults,step){if(!step){return stepResults.input;}else if(step.type==="step"||step.type==="waitForEvent"){return stepResults[step.step.id]?.output;}else if(step.type==="sleep"||step.type==="sleepUntil"){return stepResults[step.id]?.output;}else if(step.type==="parallel"||step.type==="conditional"){return step.steps.reduce((acc,entry)=>{acc[entry.step.id]=stepResults[entry.step.id]?.output;return acc;},{});}else if(step.type==="loop"){return stepResults[step.step.id]?.output;}else if(step.type==="foreach"){return stepResults[step.step.id]?.output;}}async executeSleep({workflowId,runId,entry,prevOutput,stepResults,emitter,abortController,runtimeContext,executionContext,writableStream,tracingContext}){let{duration,fn}=entry;const sleepSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_sleep"/* WORKFLOW_SLEEP */,name:`sleep: ${duration?`${duration}ms`:"dynamic"}`,attributes:{durationMs:duration,sleepType:fn?"dynamic":"fixed"},tracingPolicy:this.options?.tracingPolicy});if(fn){const stepCallId=crypto2.randomUUID();duration=await fn({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:sleepSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
|
|
287
287
|
suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:stepCallId,name:"sleep",runId},writableStream)});sleepSpan?.update({attributes:{durationMs:duration}});}try{await new Promise(resolve=>setTimeout(resolve,!duration||duration<0?0:duration));sleepSpan?.end();}catch(e){sleepSpan?.error({error:e});}}async executeSleepUntil({workflowId,runId,entry,prevOutput,stepResults,emitter,abortController,runtimeContext,executionContext,writableStream,tracingContext}){let{date,fn}=entry;const sleepUntilSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_sleep"/* WORKFLOW_SLEEP */,name:`sleepUntil: ${date?date.toISOString():"dynamic"}`,attributes:{untilDate:date,durationMs:date?Math.max(0,date.getTime()-Date.now()):void 0,sleepType:fn?"dynamic":"fixed"},tracingPolicy:this.options?.tracingPolicy});if(fn){const stepCallId=crypto2.randomUUID();date=await fn({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:sleepUntilSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
|
|
288
288
|
suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:stepCallId,name:"sleepUntil",runId},writableStream)});const time2=!date?0:date.getTime()-Date.now();sleepUntilSpan?.update({attributes:{durationMs:Math.max(0,time2)}});}const time=!date?0:date?.getTime()-Date.now();try{await new Promise(resolve=>setTimeout(resolve,time<0?0:time));sleepUntilSpan?.end();}catch(e){sleepUntilSpan?.error({error:e});}}async executeWaitForEvent({event,emitter,timeout,tracingContext}){const waitSpan=tracingContext?.currentSpan?.createChildSpan({type:"workflow_wait_event"/* WORKFLOW_WAIT_EVENT */,name:`wait: ${event}`,attributes:{eventName:event,timeoutMs:timeout},tracingPolicy:this.options?.tracingPolicy});const startTime=Date.now();return new Promise((resolve,reject)=>{const cb=eventData=>{waitSpan?.end({output:eventData,attributes:{eventReceived:true,waitDurationMs:Date.now()-startTime}});resolve(eventData);};if(timeout){setTimeout(()=>{emitter.off(`user-event-${event}`,cb);const error=new Error("Timeout waiting for event");waitSpan?.error({error,attributes:{eventReceived:false,waitDurationMs:Date.now()-startTime}});reject(error);},timeout);}emitter.once(`user-event-${event}`,cb);});}async executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume,prevOutput,emitter,abortController,runtimeContext,skipEmits=false,writableStream,disableScorers,serializedStepGraph,tracingContext,iterationCount}){const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepCallId=crypto2.randomUUID();const{inputData,validationError}=await validateStepInput({prevOutput,step,validateInputs:this.options?.validateInputs??false});const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:inputData}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{}),status:"running",...(iterationCount?{metadata:{iterationCount}}:{})};const stepAISpan=tracingContext.currentSpan?.createChildSpan({name:`workflow step: '${step.id}'`,type:"workflow_step"/* WORKFLOW_STEP */,input:inputData,attributes:{stepId:step.id},tracingPolicy:this.options?.tracingPolicy});if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,stepCallId,...stepInfo}});}await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults:{...stepResults,[step.id]:stepInfo},executionContext,workflowStatus:"running",runtimeContext});const _runStep=(step2,spanName,attributes)=>{return async data=>{const telemetry=this.mastra?.getTelemetry();const span=executionContext.executionSpan;if(!telemetry||!span){return step2.execute(data);}return api.context.with(api.trace.setSpan(api.context.active(),span),async()=>{return telemetry.traceMethod(step2.execute.bind(step2),{spanName,attributes})(data);});};};const runStep=_runStep(step,`workflow.${workflowId}.step.${step.id}`,{componentName:workflowId,runId,resourceId:resourceId??""});let execResults;const retries=step.retries??executionContext.retryConfig.attempts??0;const delay2=executionContext.retryConfig.delay??0;for(let i=0;i<retries+1;i++){if(i>0&&delay2){await new Promise(resolve=>setTimeout(resolve,delay2));}try{let suspended;let bailed;if(validationError){throw validationError;}const result=await runStep({runId,resourceId,workflowId,mastra:this.mastra?chunkP35FNLTQ_cjs.wrapMastra(this.mastra,{currentSpan:stepAISpan}):void 0,runtimeContext,inputData,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:this.getOrGenerateRunCount(step.id),resumeData:resume?.steps[0]===step.id?resume?.resumePayload:void 0,tracingContext:{currentSpan:stepAISpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),suspend:async(suspendPayload,suspendOptions)=>{executionContext.suspendedPaths[step.id]=executionContext.executionPath;if(suspendOptions?.resumeLabel){const resumeLabel=Array.isArray(suspendOptions.resumeLabel)?suspendOptions.resumeLabel:[suspendOptions.resumeLabel];for(const label of resumeLabel){executionContext.resumeLabels[label]={stepId:step.id,foreachIndex:executionContext.foreachIndex};}}suspended={payload:suspendPayload};},bail:result2=>{bailed={payload:result2};},abort:()=>{abortController?.abort();},// Only pass resume data if this step was actually suspended before
|
|
289
289
|
// This prevents pending nested workflows from trying to resume instead of start
|
|
290
290
|
resume:stepResults[step.id]?.status==="suspended"?{steps:resume?.steps?.slice(1)||[],resumePayload:resume?.resumePayload,// @ts-ignore
|
|
291
291
|
runId:stepResults[step.id]?.suspendPayload?.__workflow_meta?.runId,label:resume?.label,forEachIndex:resume?.forEachIndex}:void 0,[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:stepCallId,name:step.id,runId},writableStream),// Disable scorers must be explicitly set to false they are on by default
|
|
292
|
-
scorers:disableScorers===false?void 0:step.scorers,validateInputs:this.options?.validateInputs});if(step.scorers){await this.runScorers({scorers:step.scorers,runId,input:inputData,output:result,workflowId,stepId:step.id,runtimeContext,disableScorers,tracingContext:{currentSpan:stepAISpan}});}if(suspended){execResults={status:"suspended",suspendPayload:suspended.payload,suspendedAt:Date.now()};}else if(bailed){execResults={status:"bailed",output:bailed.payload,endedAt:Date.now()};}else {execResults={status:"success",output:result,endedAt:Date.now()};}break;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_STEP_INVOKE_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId,stepId:step.id}},`Error executing step ${step.id}: `);stepAISpan?.error({error,attributes:{status:"failed"}});execResults={status:"failed",error:error?.stack,endedAt:Date.now()};}}if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,stepCallId,...execResults}});}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,stepCallId,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,stepCallId,metadata:{}}});}}if(execResults.status!="failed"){stepAISpan?.end({output:execResults.output,attributes:{status:execResults.status}});}return {...stepInfo,...execResults};}async runScorers({scorers,runId,input,output,workflowId,stepId,runtimeContext,disableScorers,tracingContext}){let scorersToUse=scorers;if(typeof scorersToUse==="function"){try{scorersToUse=await scorersToUse({runtimeContext});}catch(error){this.preprocessExecutionError(error,{id:"WORKFLOW_FAILED_TO_FETCH_SCORERS",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{runId,workflowId,stepId}},"Error fetching scorers: ");}}if(!disableScorers&&scorersToUse&&Object.keys(scorersToUse||{}).length>0){for(const[_id,scorerObject]of Object.entries(scorersToUse||{})){runScorer({scorerId:scorerObject.name,scorerObject,runId,input,output,runtimeContext,entity:{id:workflowId,stepId},structuredOutput:true,source:"LIVE",entityType:"WORKFLOW",tracingContext});}}}async executeParallel({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const parallelSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_parallel"/* WORKFLOW_PARALLEL */,name:`parallel: '${entry.steps.length} branches'`,input:this.getStepOutput(stepResults,prevStep),attributes:{branchCount:entry.steps.length,parallelSteps:entry.steps.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)},tracingPolicy:this.options?.tracingPolicy});const prevOutput=this.getStepOutput(stepResults,prevStep);for(const step of entry.steps){if(step.type==="step"){const startTime=resume?.steps[0]===step.step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.step.id?Date.now():void 0;stepResults[step.step.id]={...stepResults[step.step.id],status:"running",...(resumeTime?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{})};}}let execResults;const results=await Promise.all(entry.steps.map((step,i)=>this.
|
|
293
|
-
suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:crypto2.randomUUID(),name:"conditional",runId},writableStream)});evalSpan?.end({output:result,attributes:{result:!!result}});return result?index:null;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_CONDITION_EVALUATION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error evaluating condition: ");evalSpan?.error({error,attributes:{result:false}});return null;}}))).filter(index=>index!==null);const stepsToRun=entry.steps.filter((_,index)=>truthyIndexes.includes(index));conditionalSpan?.update({attributes:{truthyIndexes,selectedSteps:stepsToRun.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)}});const stepsToExecute=stepsToRun.filter(step=>{if(resume&&step.type==="step"){const existingResult=stepResults[step.step.id];return !existingResult||existingResult.status==="suspended"||existingResult.status==="failed";}return true;});const results=await Promise.all(stepsToExecute.map((step,_index)=>this.executeEntry({workflowId,runId,resourceId,entry:step,prevStep,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,stepsToRun.indexOf(step)],suspendedPaths:executionContext.suspendedPaths,resumeLabels:executionContext.resumeLabels,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext:{currentSpan:conditionalSpan},emitter,abortController,runtimeContext,writableStream,disableScorers})));const mergedStepResults={...stepResults};results.forEach(result=>{if("stepResults"in result&&result.stepResults){Object.assign(mergedStepResults,result.stepResults);}});const allResults=stepsToRun.map(step=>{if(step.type==="step"){const stepResult=mergedStepResults[step.step.id];if(stepResult){return {result:stepResult};}}return {result:{status:"success",output:{}}};}).filter(Boolean);const hasFailed=allResults.find(result=>result.result.status==="failed");const hasSuspended=allResults.find(result=>result.result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.result.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.result.suspendPayload};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:allResults.reduce((acc,result,index)=>{if(result.result.status==="success"){acc[stepsToRun[index].step.id]=result.result.output;}return acc;},{})};}if(execResults.status==="failed"){conditionalSpan?.error({error:new Error(execResults.error)});}else {conditionalSpan?.end({output:execResults.output||execResults});}return execResults;}async executeLoop({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,condition}=entry;const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: '${entry.loopType}'`,input:prevOutput,attributes:{loopType:entry.loopType},tracingPolicy:this.options?.tracingPolicy});let isTrue=true;const prevIterationCount=stepResults[step.id]?.metadata?.iterationCount;let iteration=prevIterationCount?prevIterationCount-1:0;const prevPayload=stepResults[step.id]?.payload;let result={status:"success",output:prevPayload??prevOutput};let currentResume=resume;do{result=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume:currentResume,prevOutput:result.output,tracingContext:{currentSpan:loopSpan},emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph,iterationCount:iteration+1});if(currentResume&&result.status!=="suspended"){currentResume=void 0;}if(result.status!=="success"){loopSpan?.end({attributes:{totalIterations:iteration}});return result;}const evalSpan=loopSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition: '${entry.loopType}'`,input:chunkP35FNLTQ_cjs.selectFields(result.output,["stepResult","output.text","output.object","messages"]),attributes:{conditionIndex:iteration},tracingPolicy:this.options?.tracingPolicy});isTrue=await condition({workflowId,runId,mastra:this.mastra,runtimeContext,inputData:result.output,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:evalSpan},iterationCount:iteration+1,getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:crypto2.randomUUID(),name:"loop",runId},writableStream)});evalSpan?.end({output:isTrue});iteration++;}while(entry.loopType==="dowhile"?isTrue:!isTrue);loopSpan?.end({output:result.output,attributes:{totalIterations:iteration}});return result;}async executeForeach({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,opts}=entry;const results=[];const concurrency=opts.concurrency;const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{})};const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: 'foreach'`,input:prevOutput,attributes:{loopType:"foreach",concurrency},tracingPolicy:this.options?.tracingPolicy});await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,status:"running",...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{status:"running",...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,...stepInfo,status:"running"}});const prevPayload=stepResults[step.id];const foreachIndexObj={};const resumeIndex=prevPayload?.status==="suspended"?prevPayload?.suspendPayload?.__workflow_meta?.foreachIndex||0:0;const prevForeachOutput=prevPayload?.suspendPayload?.__workflow_meta?.foreachOutput||[];const prevResumeLabels=prevPayload?.suspendPayload?.__workflow_meta?.resumeLabels||{};const resumeLabels=getResumeLabelsByStepId(prevResumeLabels,step.id);for(let i=0;i<prevOutput.length;i+=concurrency){const items=prevOutput.slice(i,i+concurrency);const itemsResults=await Promise.all(items.map((item,j)=>{const k=i+j;const prevItemResult=prevForeachOutput[k];if(prevItemResult?.status==="success"||prevItemResult?.status==="suspended"&&resume?.forEachIndex!==k&&resume?.forEachIndex!==void 0){return prevItemResult;}let resumeToUse=void 0;if(resume?.forEachIndex!==void 0){resumeToUse=resume.forEachIndex===k?resume:void 0;}else {const isIndexSuspended=prevItemResult?.status==="suspended"||resumeIndex===k;if(isIndexSuspended){resumeToUse=resume;}}return this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext:{...executionContext,foreachIndex:k},resume:resumeToUse,prevOutput:item,tracingContext:{currentSpan:loopSpan},emitter,abortController,runtimeContext,skipEmits:true,writableStream,disableScorers,serializedStepGraph});}));for(const[resultIndex,result]of itemsResults.entries()){if(result.status!=="success"){const{status,error,suspendPayload,suspendedAt,endedAt,output}=result;const execResults={status,error,suspendPayload,suspendedAt,endedAt,output};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){foreachIndexObj[i+resultIndex]=execResults;}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});return result;}}else {const indexResumeLabel=Object.keys(resumeLabels).find(key=>resumeLabels[key]?.foreachIndex===i+resultIndex);delete resumeLabels[indexResumeLabel];}if(result?.output){results[i+resultIndex]=result?.output;}prevForeachOutput[i+resultIndex]={...result,suspendPayload:{}};}if(Object.keys(foreachIndexObj).length>0){const suspendedIndices=Object.keys(foreachIndexObj).map(Number);const foreachIndex=suspendedIndices[0];await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,...foreachIndexObj[foreachIndex]}});executionContext.suspendedPaths[step.id]=executionContext.executionPath;executionContext.resumeLabels={...resumeLabels,...executionContext.resumeLabels};return {...stepInfo,suspendedAt:Date.now(),status:"suspended",suspendPayload:{...foreachIndexObj[foreachIndex].suspendPayload,__workflow_meta:{...foreachIndexObj[foreachIndex].suspendPayload?.__workflow_meta,foreachIndex,foreachOutput:prevForeachOutput,resumeLabels:executionContext.resumeLabels}}};}}await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,status:"success",output:results,endedAt:Date.now()},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,status:"success",output:results,endedAt:Date.now()}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,status:"success",output:results,endedAt:Date.now()}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});loopSpan?.end({output:results});return {...stepInfo,status:"success",output:results,//@ts-ignore
|
|
292
|
+
scorers:disableScorers===false?void 0:step.scorers,validateInputs:this.options?.validateInputs});if(step.scorers){await this.runScorers({scorers:step.scorers,runId,input:inputData,output:result,workflowId,stepId:step.id,runtimeContext,disableScorers,tracingContext:{currentSpan:stepAISpan}});}if(suspended){execResults={status:"suspended",suspendPayload:suspended.payload,suspendedAt:Date.now()};}else if(bailed){execResults={status:"bailed",output:bailed.payload,endedAt:Date.now()};}else {execResults={status:"success",output:result,endedAt:Date.now()};}break;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_STEP_INVOKE_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId,stepId:step.id}},`Error executing step ${step.id}: `);stepAISpan?.error({error,attributes:{status:"failed"}});execResults={status:"failed",error:error?.stack,endedAt:Date.now()};}}if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,stepCallId,...execResults}});}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,stepCallId,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,stepCallId,metadata:{}}});}}if(execResults.status!="failed"){stepAISpan?.end({output:execResults.output,attributes:{status:execResults.status}});}return {...stepInfo,...execResults};}async runScorers({scorers,runId,input,output,workflowId,stepId,runtimeContext,disableScorers,tracingContext}){let scorersToUse=scorers;if(typeof scorersToUse==="function"){try{scorersToUse=await scorersToUse({runtimeContext});}catch(error){this.preprocessExecutionError(error,{id:"WORKFLOW_FAILED_TO_FETCH_SCORERS",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{runId,workflowId,stepId}},"Error fetching scorers: ");}}if(!disableScorers&&scorersToUse&&Object.keys(scorersToUse||{}).length>0){for(const[_id,scorerObject]of Object.entries(scorersToUse||{})){runScorer({scorerId:scorerObject.name,scorerObject,runId,input,output,runtimeContext,entity:{id:workflowId,stepId},structuredOutput:true,source:"LIVE",entityType:"WORKFLOW",tracingContext});}}}async executeParallel({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const parallelSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_parallel"/* WORKFLOW_PARALLEL */,name:`parallel: '${entry.steps.length} branches'`,input:this.getStepOutput(stepResults,prevStep),attributes:{branchCount:entry.steps.length,parallelSteps:entry.steps.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)},tracingPolicy:this.options?.tracingPolicy});const prevOutput=this.getStepOutput(stepResults,prevStep);for(const step of entry.steps){if(step.type==="step"){const startTime=resume?.steps[0]===step.step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.step.id?Date.now():void 0;stepResults[step.step.id]={...stepResults[step.step.id],status:"running",...(resumeTime?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{})};}}let execResults;const results=await Promise.all(entry.steps.map(async(step,i)=>{const result=await this.executeStep({workflowId,runId,resourceId,step:step.step,prevOutput,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,i],suspendedPaths:executionContext.suspendedPaths,resumeLabels:executionContext.resumeLabels,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext:{currentSpan:parallelSpan},emitter,abortController,runtimeContext,writableStream,disableScorers});stepResults[step.step.id]=result;return result;}));const hasFailed=results.find(result=>result.status==="failed");const hasSuspended=results.find(result=>result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.suspendPayload};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:results.reduce((acc,result,index)=>{if(result.status==="success"){acc[entry.steps[index].step.id]=result.output;}return acc;},{})};}if(execResults.status==="failed"){parallelSpan?.error({error:new Error(execResults.error)});}else {parallelSpan?.end({output:execResults.output||execResults});}return execResults;}async executeConditional({workflowId,runId,resourceId,entry,prevOutput,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const conditionalSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_conditional"/* WORKFLOW_CONDITIONAL */,name:`conditional: '${entry.conditions.length} conditions'`,input:prevOutput,attributes:{conditionCount:entry.conditions.length},tracingPolicy:this.options?.tracingPolicy});let execResults;const truthyIndexes=(await Promise.all(entry.conditions.map(async(cond,index)=>{const evalSpan=conditionalSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition '${index}'`,input:prevOutput,attributes:{conditionIndex:index},tracingPolicy:this.options?.tracingPolicy});try{const result=await cond({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:evalSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
|
|
293
|
+
suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:crypto2.randomUUID(),name:"conditional",runId},writableStream)});evalSpan?.end({output:result,attributes:{result:!!result}});return result?index:null;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_CONDITION_EVALUATION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error evaluating condition: ");evalSpan?.error({error,attributes:{result:false}});return null;}}))).filter(index=>index!==null);const stepsToRun=entry.steps.filter((_,index)=>truthyIndexes.includes(index));conditionalSpan?.update({attributes:{truthyIndexes,selectedSteps:stepsToRun.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)}});const results=await Promise.all(stepsToRun.map(async(step,index)=>{const currStepResult=stepResults[step.step.id];if(currStepResult&&currStepResult.status==="success"){return currStepResult;}const result=await this.executeStep({workflowId,runId,resourceId,step:step.step,prevOutput,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,index],suspendedPaths:executionContext.suspendedPaths,resumeLabels:executionContext.resumeLabels,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext:{currentSpan:conditionalSpan},emitter,abortController,runtimeContext,writableStream,disableScorers});stepResults[step.step.id]=result;return result;}));const hasFailed=results.find(result=>result.status==="failed");const hasSuspended=results.find(result=>result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.suspendPayload,suspendedAt:Date.now()};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:results.reduce((acc,result,index)=>{if(result.status==="success"){acc[stepsToRun[index].step.id]=result.output;}return acc;},{})};}if(execResults.status==="failed"){conditionalSpan?.error({error:new Error(execResults.error)});}else {conditionalSpan?.end({output:execResults.output||execResults});}return execResults;}async executeLoop({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,condition}=entry;const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: '${entry.loopType}'`,input:prevOutput,attributes:{loopType:entry.loopType},tracingPolicy:this.options?.tracingPolicy});let isTrue=true;const prevIterationCount=stepResults[step.id]?.metadata?.iterationCount;let iteration=prevIterationCount?prevIterationCount-1:0;const prevPayload=stepResults[step.id]?.payload;let result={status:"success",output:prevPayload??prevOutput};let currentResume=resume;do{result=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume:currentResume,prevOutput:result.output,tracingContext:{currentSpan:loopSpan},emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph,iterationCount:iteration+1});if(currentResume&&result.status!=="suspended"){currentResume=void 0;}if(result.status!=="success"){loopSpan?.end({attributes:{totalIterations:iteration}});return result;}const evalSpan=loopSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition: '${entry.loopType}'`,input:chunkP35FNLTQ_cjs.selectFields(result.output,["stepResult","output.text","output.object","messages"]),attributes:{conditionIndex:iteration},tracingPolicy:this.options?.tracingPolicy});isTrue=await condition({workflowId,runId,mastra:this.mastra,runtimeContext,inputData:result.output,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:evalSpan},iterationCount:iteration+1,getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:crypto2.randomUUID(),name:"loop",runId},writableStream)});evalSpan?.end({output:isTrue});iteration++;}while(entry.loopType==="dowhile"?isTrue:!isTrue);loopSpan?.end({output:result.output,attributes:{totalIterations:iteration}});return result;}async executeForeach({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,opts}=entry;const results=[];const concurrency=opts.concurrency;const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{})};const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: 'foreach'`,input:prevOutput,attributes:{loopType:"foreach",concurrency},tracingPolicy:this.options?.tracingPolicy});await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,status:"running",...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{status:"running",...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,...stepInfo,status:"running"}});const prevPayload=stepResults[step.id];const foreachIndexObj={};const resumeIndex=prevPayload?.status==="suspended"?prevPayload?.suspendPayload?.__workflow_meta?.foreachIndex||0:0;const prevForeachOutput=prevPayload?.suspendPayload?.__workflow_meta?.foreachOutput||[];const prevResumeLabels=prevPayload?.suspendPayload?.__workflow_meta?.resumeLabels||{};const resumeLabels=getResumeLabelsByStepId(prevResumeLabels,step.id);for(let i=0;i<prevOutput.length;i+=concurrency){const items=prevOutput.slice(i,i+concurrency);const itemsResults=await Promise.all(items.map((item,j)=>{const k=i+j;const prevItemResult=prevForeachOutput[k];if(prevItemResult?.status==="success"||prevItemResult?.status==="suspended"&&resume?.forEachIndex!==k&&resume?.forEachIndex!==void 0){return prevItemResult;}let resumeToUse=void 0;if(resume?.forEachIndex!==void 0){resumeToUse=resume.forEachIndex===k?resume:void 0;}else {const isIndexSuspended=prevItemResult?.status==="suspended"||resumeIndex===k;if(isIndexSuspended){resumeToUse=resume;}}return this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext:{...executionContext,foreachIndex:k},resume:resumeToUse,prevOutput:item,tracingContext:{currentSpan:loopSpan},emitter,abortController,runtimeContext,skipEmits:true,writableStream,disableScorers,serializedStepGraph});}));for(const[resultIndex,result]of itemsResults.entries()){if(result.status!=="success"){const{status,error,suspendPayload,suspendedAt,endedAt,output}=result;const execResults={status,error,suspendPayload,suspendedAt,endedAt,output};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){foreachIndexObj[i+resultIndex]=execResults;}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});return result;}}else {const indexResumeLabel=Object.keys(resumeLabels).find(key=>resumeLabels[key]?.foreachIndex===i+resultIndex);delete resumeLabels[indexResumeLabel];}if(result?.output){results[i+resultIndex]=result?.output;}prevForeachOutput[i+resultIndex]={...result,suspendPayload:{}};}if(Object.keys(foreachIndexObj).length>0){const suspendedIndices=Object.keys(foreachIndexObj).map(Number);const foreachIndex=suspendedIndices[0];await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,...foreachIndexObj[foreachIndex]}});executionContext.suspendedPaths[step.id]=executionContext.executionPath;executionContext.resumeLabels={...resumeLabels,...executionContext.resumeLabels};return {...stepInfo,suspendedAt:Date.now(),status:"suspended",suspendPayload:{...foreachIndexObj[foreachIndex].suspendPayload,__workflow_meta:{...foreachIndexObj[foreachIndex].suspendPayload?.__workflow_meta,foreachIndex,foreachOutput:prevForeachOutput,resumeLabels:executionContext.resumeLabels}}};}}await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,status:"success",output:results,endedAt:Date.now()},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,status:"success",output:results,endedAt:Date.now()}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,status:"success",output:results,endedAt:Date.now()}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});loopSpan?.end({output:results});return {...stepInfo,status:"success",output:results,//@ts-ignore
|
|
294
294
|
endedAt:Date.now()};}async persistStepUpdate({workflowId,runId,resourceId,stepResults,serializedStepGraph,executionContext,workflowStatus,result,error,runtimeContext}){const shouldPersistSnapshot=this.options?.shouldPersistSnapshot?.({stepResults,workflowStatus});if(!shouldPersistSnapshot){return;}const runtimeContextObj={};runtimeContext.forEach((value,key)=>{runtimeContextObj[key]=value;});await this.mastra?.getStorage()?.persistWorkflowSnapshot({workflowName:workflowId,runId,resourceId,snapshot:{runId,status:workflowStatus,value:executionContext.state,context:stepResults,activePaths:[],serializedStepGraph,suspendedPaths:executionContext.suspendedPaths,waitingPaths:{},resumeLabels:executionContext.resumeLabels,result,error,runtimeContext:runtimeContextObj,// @ts-ignore
|
|
295
|
-
timestamp:Date.now()}});}async executeEntry({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const prevOutput=this.getStepOutput(stepResults,prevStep);let execResults;if(entry.type==="step"){const{step}=entry;execResults=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume,prevOutput,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(resume?.resumePath?.length&&entry.type==="parallel"){const idx=resume.resumePath.shift();const resumedStepResult=await this.executeEntry({workflowId,runId,resourceId,entry:entry.steps[idx],prevStep,serializedStepGraph,stepResults,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,idx],suspendedPaths:executionContext.suspendedPaths,resumeLabels:executionContext.resumeLabels,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});if(resumedStepResult.stepResults){Object.assign(stepResults,resumedStepResult.stepResults);}const allParallelStepsComplete=entry.steps.every(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="success";}return true;});if(allParallelStepsComplete){execResults={status:"success",output:entry.steps.reduce((acc,parallelStep)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="success"){acc[parallelStep.step.id]=stepResult.output;}}return acc;},{})};}else {const stillSuspended=entry.steps.find(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="suspended";}return false;});execResults={status:"suspended",payload:stillSuspended&&stillSuspended.type==="step"?stepResults[stillSuspended.step.id]?.suspendPayload:{}};}const updatedExecutionContext={...executionContext,...resumedStepResult.executionContext,suspendedPaths:{...executionContext.suspendedPaths,...resumedStepResult.executionContext?.suspendedPaths}};if(execResults.status==="suspended"){entry.steps.forEach((parallelStep,stepIndex)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="suspended"){updatedExecutionContext.suspendedPaths[parallelStep.step.id]=[...executionContext.executionPath,stepIndex];}}});}return {result:execResults,stepResults:resumedStepResult.stepResults,executionContext:updatedExecutionContext};}else if(entry.type==="parallel"){execResults=await this.executeParallel({workflowId,runId,entry,prevStep,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});}else if(entry.type==="conditional"){execResults=await this.executeConditional({workflowId,runId,entry,
|
|
295
|
+
timestamp:Date.now()}});}async executeEntry({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const prevOutput=this.getStepOutput(stepResults,prevStep);let execResults;if(entry.type==="step"){const{step}=entry;execResults=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume,prevOutput,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(resume?.resumePath?.length&&entry.type==="parallel"){const idx=resume.resumePath.shift();const resumedStepResult=await this.executeEntry({workflowId,runId,resourceId,entry:entry.steps[idx],prevStep,serializedStepGraph,stepResults,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,idx],suspendedPaths:executionContext.suspendedPaths,resumeLabels:executionContext.resumeLabels,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});if(resumedStepResult.stepResults){Object.assign(stepResults,resumedStepResult.stepResults);}const allParallelStepsComplete=entry.steps.every(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="success";}return true;});if(allParallelStepsComplete){execResults={status:"success",output:entry.steps.reduce((acc,parallelStep)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="success"){acc[parallelStep.step.id]=stepResult.output;}}return acc;},{})};}else {const stillSuspended=entry.steps.find(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="suspended";}return false;});execResults={status:"suspended",payload:stillSuspended&&stillSuspended.type==="step"?stepResults[stillSuspended.step.id]?.suspendPayload:{}};}const updatedExecutionContext={...executionContext,...resumedStepResult.executionContext,suspendedPaths:{...executionContext.suspendedPaths,...resumedStepResult.executionContext?.suspendedPaths}};if(execResults.status==="suspended"){entry.steps.forEach((parallelStep,stepIndex)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="suspended"){updatedExecutionContext.suspendedPaths[parallelStep.step.id]=[...executionContext.executionPath,stepIndex];}}});}return {result:execResults,stepResults:resumedStepResult.stepResults,executionContext:updatedExecutionContext};}else if(entry.type==="parallel"){execResults=await this.executeParallel({workflowId,runId,entry,prevStep,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});}else if(entry.type==="conditional"){execResults=await this.executeConditional({workflowId,runId,entry,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});}else if(entry.type==="loop"){execResults=await this.executeLoop({workflowId,runId,entry,prevStep,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(entry.type==="foreach"){execResults=await this.executeForeach({workflowId,runId,entry,prevStep,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(entry.type==="sleep"){const startedAt=Date.now();await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.id,payload:prevOutput,startedAt,status:"waiting"}});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});await this.executeSleep({workflowId,runId,entry,prevStep,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"running",runtimeContext});const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...stepInfo,status:"success",output:prevOutput};stepResults[entry.id]={...stepInfo,status:"success",output:prevOutput};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,...execResults},workflowState:{status:"running",steps:{...stepResults,[entry.id]:{...execResults}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:entry.id,endedAt,status:"success",output:prevOutput}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:entry.id,metadata:{}}});}else if(entry.type==="sleepUntil"){const startedAt=Date.now();await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.id,payload:prevOutput,startedAt,status:"waiting"}});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});await this.executeSleepUntil({workflowId,runId,entry,prevStep,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"running",runtimeContext});const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...stepInfo,status:"success",output:prevOutput};stepResults[entry.id]={...stepInfo,status:"success",output:prevOutput};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,...execResults},workflowState:{status:"running",steps:{...stepResults,[entry.id]:{...execResults}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:entry.id,endedAt,status:"success",output:prevOutput}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:entry.id,metadata:{}}});}else if(entry.type==="waitForEvent"){const startedAt=Date.now();let eventData;await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.step.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.step.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.step.id,payload:prevOutput,startedAt,status:"waiting"}});stepResults[entry.step.id]={status:"waiting",payload:prevOutput,startedAt};await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});try{eventData=await this.executeWaitForEvent({event:entry.event,emitter,timeout:entry.timeout,tracingContext});const{step}=entry;execResults=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume:{resumePayload:eventData,steps:[entry.step.id]},prevOutput,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}catch(error){execResults={status:"failed",error};}const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...execResults,...stepInfo};}if(entry.type==="step"||entry.type==="waitForEvent"||entry.type==="loop"||entry.type==="foreach"){stepResults[entry.step.id]=execResults;}if(abortController?.signal?.aborted){execResults={...execResults,status:"canceled"};}await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:execResults.status==="success"?"running":execResults.status,runtimeContext});if(execResults.status==="canceled"){await emitter.emit("watch-v2",{type:"workflow-canceled",payload:{}});}return {result:execResults,stepResults,executionContext};}};// src/workflows/workflow.ts
|
|
296
296
|
function mapVariable(config){return config;}function createStep(params,agentOptions){if(params instanceof exports.Agent){return {id:params.name,description:params.getDescription(),// @ts-ignore
|
|
297
297
|
inputSchema:z9.z.object({prompt:z9.z.string()// resourceId: z.string().optional(),
|
|
298
298
|
// threadId: z.string().optional(),
|
|
@@ -339,7 +339,7 @@ condition,loopType:"dountil",serializedCondition:{id:`${step.id}-condition`,fn:c
|
|
|
339
339
|
*/async createRunAsync(options){if(this.stepFlow.length===0){throw new Error("Execution flow of workflow is not defined. Add steps to the workflow via .then(), .branch(), etc.");}if(!this.executionGraph.steps){throw new Error("Uncommitted step flow changes detected. Call .commit() to register the steps.");}const runIdToUse=options?.runId||this.#mastra?.generateId()||crypto2.randomUUID();const run=this.#runs.get(runIdToUse)??new Run({workflowId:this.id,stateSchema:this.stateSchema,runId:runIdToUse,resourceId:options?.resourceId,executionEngine:this.executionEngine,executionGraph:this.executionGraph,mastra:this.#mastra,retryConfig:this.retryConfig,serializedStepGraph:this.serializedStepGraph,disableScorers:options?.disableScorers,cleanup:()=>this.#runs.delete(runIdToUse),tracingPolicy:this.#options?.tracingPolicy,workflowSteps:this.steps,validateInputs:this.#options?.validateInputs});this.#runs.set(runIdToUse,run);const shouldPersistSnapshot=this.#options.shouldPersistSnapshot({workflowStatus:run.workflowRunStatus,stepResults:{}});const workflowSnapshotInStorage=await this.getWorkflowRunExecutionResult(runIdToUse,false);if(!workflowSnapshotInStorage&&shouldPersistSnapshot){await this.mastra?.getStorage()?.persistWorkflowSnapshot({workflowName:this.id,runId:runIdToUse,resourceId:options?.resourceId,snapshot:{runId:runIdToUse,status:"pending",value:{},context:{},activePaths:[],serializedStepGraph:this.serializedStepGraph,suspendedPaths:{},resumeLabels:{},waitingPaths:{},result:void 0,error:void 0,// @ts-ignore
|
|
340
340
|
timestamp:Date.now()}});}return run;}async getScorers({runtimeContext=new chunkGPWMM745_cjs.RuntimeContext()}={}){const steps=this.steps;if(!steps||Object.keys(steps).length===0){return {};}const scorers={};for(const step of Object.values(steps)){if(step.scorers){let scorersToUse=step.scorers;if(typeof scorersToUse==="function"){scorersToUse=await scorersToUse({runtimeContext});}for(const[id,scorer]of Object.entries(scorersToUse)){scorers[id]=scorer;}}}return scorers;}// This method should only be called internally for nested workflow execution, as well as from mastra server handlers
|
|
341
341
|
// To run a workflow use `.createRunAsync` and then `.start` or `.resume`
|
|
342
|
-
async execute({runId,inputData,resumeData,state,setState,suspend,resume,[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,mastra,runtimeContext,abort,abortSignal,runCount,tracingContext,writer,validateInputs}){this.__registerMastra(mastra);if(validateInputs){this.#options={...(this.#options||{}),validateInputs};}this.executionEngine.options={...(this.executionEngine.options||{}),validateInputs:validateInputs??false};const isResume=!!(resume?.steps&&resume.steps.length>0)||!!resume?.label;const run=isResume?await this.createRunAsync({runId:resume.runId}):await this.createRunAsync({runId});const nestedAbortCb=()=>{abort();};run.abortController.signal.addEventListener("abort",nestedAbortCb);abortSignal.addEventListener("abort",async()=>{run.abortController.signal.removeEventListener("abort",nestedAbortCb);await run.cancel();});const unwatchV2=run.watch(event=>{emitter.emit("nested-watch-v2",{event,workflowId:this.id});},"watch-v2");const unwatch=run.watch(event=>{emitter.emit("nested-watch",{event,workflowId:this.id,runId:run.runId,isResume:!!resume?.steps?.length});},"watch");if(runCount&&runCount>0&&
|
|
342
|
+
async execute({runId,inputData,resumeData,state,setState,suspend,resume,[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,mastra,runtimeContext,abort,abortSignal,runCount,tracingContext,writer,validateInputs}){this.__registerMastra(mastra);if(validateInputs){this.#options={...(this.#options||{}),validateInputs};}this.executionEngine.options={...(this.executionEngine.options||{}),validateInputs:validateInputs??false};const isResume=!!(resume?.steps&&resume.steps.length>0)||!!resume?.label||!!(resume?.steps&&resume.steps.length===0&&(!runCount||runCount===0));const run=isResume?await this.createRunAsync({runId:resume.runId}):await this.createRunAsync({runId});const nestedAbortCb=()=>{abort();};run.abortController.signal.addEventListener("abort",nestedAbortCb);abortSignal.addEventListener("abort",async()=>{run.abortController.signal.removeEventListener("abort",nestedAbortCb);await run.cancel();});const unwatchV2=run.watch(event=>{emitter.emit("nested-watch-v2",{event,workflowId:this.id});},"watch-v2");const unwatch=run.watch(event=>{emitter.emit("nested-watch",{event,workflowId:this.id,runId:run.runId,isResume:!!resume?.steps?.length});},"watch");if(runCount&&runCount>0&&isResume&&runtimeContext){runtimeContext.set("__mastraWorflowInputData",inputData);}const res=isResume?await run.resume({resumeData,step:resume.steps?.length>0?resume.steps:void 0,runtimeContext,tracingContext,outputOptions:{includeState:true,includeResumeLabels:true},label:resume.label}):await run.start({inputData,runtimeContext,tracingContext,writableStream:writer,initialState:state,outputOptions:{includeState:true,includeResumeLabels:true}});unwatch();unwatchV2();const suspendedSteps=Object.entries(res.steps).filter(([_stepName,stepResult])=>{const stepRes=stepResult;return stepRes?.status==="suspended";});if(res.state){setState(res.state);}if(suspendedSteps?.length){for(const[stepName,stepResult]of suspendedSteps){const suspendPath=[stepName,...(stepResult?.suspendPayload?.__workflow_meta?.path??[])];await suspend({...stepResult?.suspendPayload,__workflow_meta:{runId:run.runId,path:suspendPath}},{resumeLabel:Object.keys(res.resumeLabels??{})});}}if(res.status==="failed"){throw res.error;}return res.status==="success"?res.result:void 0;}async getWorkflowRuns(args){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow runs. Mastra storage is not initialized");return {runs:[],total:0};}return storage.getWorkflowRuns({workflowName:this.id,...(args??{})});}async getWorkflowRunById(runId){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow runs from storage. Mastra storage is not initialized");return this.#runs.get(runId)?{...this.#runs.get(runId),workflowName:this.id}:null;}const run=await storage.getWorkflowRunById({runId,workflowName:this.id});return run??(this.#runs.get(runId)?{...this.#runs.get(runId),workflowName:this.id}:null);}async getWorkflowRunSteps({runId,workflowId}){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow run steps. Mastra storage is not initialized");return {};}const run=await storage.getWorkflowRunById({runId,workflowName:workflowId});let snapshot=run?.snapshot;if(!snapshot){return {};}if(typeof snapshot==="string"){try{snapshot=JSON.parse(snapshot);}catch(e){this.logger.debug("Cannot get workflow run execution result. Snapshot is not a valid JSON string",e);return {};}}const{serializedStepGraph,context}=snapshot;const{input,...steps}=context;let finalSteps={};for(const step of Object.keys(steps)){const stepGraph=serializedStepGraph.find(stepGraph2=>stepGraph2?.step?.id===step);finalSteps[step]=steps[step];if(stepGraph&&stepGraph?.step?.component==="WORKFLOW"){const nestedSteps=await this.getWorkflowRunSteps({runId,workflowId:step});if(nestedSteps){const updatedNestedSteps=Object.entries(nestedSteps).reduce((acc,[key,value])=>{acc[`${step}.${key}`]=value;return acc;},{});finalSteps={...finalSteps,...updatedNestedSteps};}}}return finalSteps;}async getWorkflowRunExecutionResult(runId,withNestedWorkflows=true){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow run execution result. Mastra storage is not initialized");return null;}const run=await storage.getWorkflowRunById({runId,workflowName:this.id});let snapshot=run?.snapshot;if(!snapshot){return null;}if(typeof snapshot==="string"){try{snapshot=JSON.parse(snapshot);}catch(e){this.logger.debug("Cannot get workflow run execution result. Snapshot is not a valid JSON string",e);return null;}}const fullSteps=withNestedWorkflows?await this.getWorkflowRunSteps({runId,workflowId:this.id}):snapshot.context;return {status:snapshot.status,result:snapshot.result,error:snapshot.error,payload:snapshot.context?.input,steps:fullSteps};}};var Run=class{#abortController;emitter;/**
|
|
343
343
|
* Unique identifier for this workflow
|
|
344
344
|
*/workflowId;/**
|
|
345
345
|
* Unique identifier for this run
|
|
@@ -398,7 +398,7 @@ async execute({runId,inputData,resumeData,state,setState,suspend,resume,[chunkAB
|
|
|
398
398
|
* Resumes the workflow execution with the provided input as a stream
|
|
399
399
|
* @param input The input data for the workflow
|
|
400
400
|
* @returns A promise that resolves to the workflow output
|
|
401
|
-
*/resumeStreamVNext({step,resumeData,runtimeContext,tracingContext,tracingOptions,forEachIndex}={}){this.closeStreamAction=async()=>{};const self=this;const stream=new web.ReadableStream({async start(controller){const unwatch=self.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{controller.enqueue({type,runId:self.runId,from,payload:{stepName:payload.id,...payload}});},"watch-v2");self.closeStreamAction=async()=>{unwatch();try{await controller.close();}catch(err){console.error("Error closing stream:",err);}};const executionResultsPromise=self._resume({resumeData,step,runtimeContext,tracingContext,tracingOptions,writableStream:new web.WritableStream({write(chunk){controller.enqueue(chunk);}}),isVNext:true,forEachIndex});self.executionResults=executionResultsPromise;
|
|
401
|
+
*/resumeStreamVNext({step,resumeData,runtimeContext,tracingContext,tracingOptions,forEachIndex}={}){this.closeStreamAction=async()=>{};const self=this;const stream=new web.ReadableStream({async start(controller){const unwatch=self.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{controller.enqueue({type,runId:self.runId,from,payload:{stepName:payload.id,...payload}});},"watch-v2");self.closeStreamAction=async()=>{unwatch();try{await controller.close();}catch(err){console.error("Error closing stream:",err);}};const executionResultsPromise=self._resume({resumeData,step,runtimeContext,tracingContext,tracingOptions,writableStream:new web.WritableStream({write(chunk){controller.enqueue(chunk);}}),isVNext:true,forEachIndex});self.executionResults=executionResultsPromise;let executionResults;try{executionResults=await executionResultsPromise;self.closeStreamAction?.().catch(()=>{});if(self.#streamOutput){self.#streamOutput.updateResults(executionResults);}}catch(err){self.#streamOutput?.rejectResults(err);self.closeStreamAction?.().catch(()=>{});}}});this.#streamOutput=new WorkflowRunOutput({runId:this.runId,workflowId:this.workflowId,stream});return this.#streamOutput;}watch(cb,type="watch"){const watchCb=event=>{this.updateState(event.payload);cb({type:event.type,payload:this.getState(),eventTimestamp:event.eventTimestamp});};const nestedWatchCb=({event,workflowId})=>{try{const{type:type2,payload,eventTimestamp}=event;const prefixedSteps=Object.fromEntries(Object.entries(payload?.workflowState?.steps??{}).map(([stepId,step])=>[`${workflowId}.${stepId}`,step]));const newPayload={currentStep:{...payload?.currentStep,id:`${workflowId}.${payload?.currentStep?.id}`},workflowState:{steps:prefixedSteps}};this.updateState(newPayload);cb({type:type2,payload:this.getState(),eventTimestamp});}catch(e){console.error(e);}};const nestedWatchV2Cb=({event,workflowId})=>{this.emitter.emit("watch-v2",{...event,...(event.payload?.id?{payload:{...event.payload,id:`${workflowId}.${event.payload.id}`}}:{})});};if(type==="watch"){this.emitter.on("watch",watchCb);this.emitter.on("nested-watch",nestedWatchCb);}else if(type==="watch-v2"){this.emitter.on("watch-v2",cb);this.emitter.on("nested-watch-v2",nestedWatchV2Cb);}return ()=>{if(type==="watch-v2"){this.emitter.off("watch-v2",cb);this.emitter.off("nested-watch-v2",nestedWatchV2Cb);}else {this.emitter.off("watch",watchCb);this.emitter.off("nested-watch",nestedWatchCb);}};}async watchAsync(cb,type="watch"){return this.watch(cb,type);}async resume(params){return this._resume(params);}async _resume(params){const snapshot=await this.#mastra?.getStorage()?.loadWorkflowSnapshot({workflowName:this.workflowId,runId:this.runId});if(!snapshot){throw new Error("No snapshot found for this workflow run: "+this.workflowId+" "+this.runId);}if(snapshot.status!=="suspended"){throw new Error("This workflow run was not suspended");}const snapshotResumeLabel=params.label?snapshot?.resumeLabels?.[params.label]:void 0;const stepParam=snapshotResumeLabel?.stepId??params.step;let steps;if(stepParam){let newStepParam=stepParam;if(typeof stepParam==="string"){newStepParam=stepParam.split(".");}steps=(Array.isArray(newStepParam)?newStepParam:[newStepParam]).map(step=>typeof step==="string"?step:step?.id);}else {const suspendedStepPaths=[];Object.entries(snapshot?.suspendedPaths??{}).forEach(([stepId,_executionPath])=>{const stepResult=snapshot?.context?.[stepId];if(stepResult&&typeof stepResult==="object"&&"status"in stepResult){const stepRes=stepResult;if(stepRes.status==="suspended"){const nestedPath=stepRes.suspendPayload?.__workflow_meta?.path;if(nestedPath&&Array.isArray(nestedPath)){suspendedStepPaths.push([stepId,...nestedPath]);}else {suspendedStepPaths.push([stepId]);}}}});if(suspendedStepPaths.length===0){throw new Error("No suspended steps found in this workflow run");}if(suspendedStepPaths.length===1){steps=suspendedStepPaths[0];}else {const pathStrings=suspendedStepPaths.map(path=>`[${path.join(", ")}]`);throw new Error(`Multiple suspended steps found: ${pathStrings.join(", ")}. Please specify which step to resume using the "step" parameter.`);}}if(!params.runCount){const suspendedStepIds=Object.keys(snapshot?.suspendedPaths??{});const isStepSuspended=suspendedStepIds.includes(steps?.[0]??"");if(!isStepSuspended){throw new Error(`This workflow step "${steps?.[0]}" was not suspended. Available suspended steps: [${suspendedStepIds.join(", ")}]`);}}const suspendedStep=this.workflowSteps[steps?.[0]??""];const resumeDataToUse=await this._validateResumeData(params.resumeData,suspendedStep);let runtimeContextInput;if(params.runCount&¶ms.runCount>0&¶ms.runtimeContext){runtimeContextInput=params.runtimeContext.get("__mastraWorflowInputData");params.runtimeContext.delete("__mastraWorflowInputData");}const stepResults={...(snapshot?.context??{}),input:runtimeContextInput??snapshot?.context?.input};let runtimeContextToUse=params.runtimeContext??new chunkGPWMM745_cjs.RuntimeContext();Object.entries(snapshot?.runtimeContext??{}).forEach(([key,value])=>{if(!runtimeContextToUse.has(key)){runtimeContextToUse.set(key,value);}});const workflowAISpan=chunkP35FNLTQ_cjs.getOrCreateSpan({type:"workflow_run"/* WORKFLOW_RUN */,name:`workflow run: '${this.workflowId}'`,input:resumeDataToUse,attributes:{workflowId:this.workflowId},metadata:{resourceId:this.resourceId,runId:this.runId},tracingPolicy:this.tracingPolicy,tracingOptions:params.tracingOptions,tracingContext:params.tracingContext,runtimeContext:runtimeContextToUse});const traceId=chunkP35FNLTQ_cjs.getValidTraceId(workflowAISpan);const executionResultPromise=this.executionEngine.execute({workflowId:this.workflowId,runId:this.runId,resourceId:this.resourceId,graph:this.executionGraph,serializedStepGraph:this.serializedStepGraph,input:snapshot?.context?.input,initialState:snapshot?.value??{},resume:{steps,stepResults,resumePayload:resumeDataToUse,// @ts-ignore
|
|
402
402
|
resumePath:snapshot?.suspendedPaths?.[steps?.[0]],forEachIndex:params.forEachIndex??snapshotResumeLabel?.foreachIndex,label:params.label},format:params.format,emitter:{emit:(event,data)=>{this.emitter.emit(event,data);return Promise.resolve();},on:(event,callback)=>{this.emitter.on(event,callback);},off:(event,callback)=>{this.emitter.off(event,callback);},once:(event,callback)=>{this.emitter.once(event,callback);}},runtimeContext:runtimeContextToUse,abortController:this.abortController,workflowAISpan,outputOptions:params.outputOptions,writableStream:params.writableStream}).then(result=>{if(!params.isVNext&&result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}result.traceId=traceId;return result;});this.executionResults=executionResultPromise;return executionResultPromise.then(result=>{this.#streamOutput?.updateResults(result);return result;});}/**
|
|
403
403
|
* Returns the current state of the workflow run
|
|
404
404
|
* @returns The current state of the workflow run
|
|
@@ -485,7 +485,7 @@ async function getRoutingAgent({runtimeContext,agent}){const instructionsToUse=a
|
|
|
485
485
|
When calling an agent, the prompt should be a text value, like you would call an LLM in a chat interface.
|
|
486
486
|
Keep in mind that the user only sees the final result of the task. When reviewing completion, you should know that the user will not see the intermediate results.
|
|
487
487
|
`;return new exports.Agent({name:"routing-agent",instructions,model,memory:memoryToUse,// @ts-ignore
|
|
488
|
-
_agentNetworkAppend:true});}function getLastMessage(messages){let message="";if(typeof messages==="string"){message=messages;}else {const lastMessage=Array.isArray(messages)?messages[messages.length-1]:messages;if(typeof lastMessage==="string"){message=lastMessage;}else if(lastMessage&&`content`in lastMessage&&lastMessage?.content){const lastMessageContent=lastMessage.content;if(typeof lastMessageContent==="string"){message=lastMessageContent;}else if(Array.isArray(lastMessageContent)){const lastPart=lastMessageContent[lastMessageContent.length-1];if(lastPart?.type==="text"){message=lastPart.text;}}}}return message;}async function prepareMemoryStep({threadId,resourceId,messages,routingAgent,runtimeContext,generateId:generateId3,tracingContext,memoryConfig}){const memory=await routingAgent.getMemory({runtimeContext});let thread=await memory?.getThreadById({threadId});if(!thread){thread=await memory?.createThread({threadId,title:`New Thread ${(/* @__PURE__ */new Date()).toISOString()}`,resourceId});}let userMessage;const promises=[];if(typeof messages==="string"){userMessage=messages;if(memory){promises.push(memory.saveMessages({messages:[{id:generateId3(),type:"text",role:"user",content:{parts:[{type:"text",text:messages}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:thread?.id,resourceId:thread?.resourceId}],format:"v2"}));}}else {const messageList=new chunkMJMID7LX_cjs.MessageList({threadId:thread?.id,resourceId:thread?.resourceId});messageList.add(messages,"user");const messagesToSave=messageList.get.all.v2();if(memory){promises.push(memory.saveMessages({messages:messagesToSave,format:"v2"}));}const uiMessages=messageList.get.all.ui();const mostRecentUserMessage=routingAgent.getMostRecentUserMessage(uiMessages);userMessage=mostRecentUserMessage?.content;}if(thread?.title?.startsWith("New Thread")&&memory){const config=memory.getMergedThreadConfig(memoryConfig||{});const{shouldGenerate,model:titleModel,instructions:titleInstructions}=routingAgent.resolveTitleGenerationConfig(config?.threads?.generateTitle);if(shouldGenerate&&userMessage){promises.push(routingAgent.genTitle(userMessage,runtimeContext,tracingContext||{currentSpan:void 0},titleModel,titleInstructions).then(title=>{if(title){return memory.createThread({threadId:thread.id,resourceId:thread.resourceId,memoryConfig,title,metadata:thread.metadata});}}));}}await Promise.all(promises);return {thread};}async function createNetworkLoop({networkName,runtimeContext,runId,agent,generateId:generateId3,routingAgentOptions}){const routingStep=createStep({id:"routing-agent-step",inputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,result:z9__default.default.string().optional(),iteration:z9__default.default.number(),threadId:z9__default.default.string().optional(),threadResourceId:z9__default.default.string().optional(),isOneOff:z9__default.default.boolean(),verboseIntrospection:z9__default.default.boolean()}),outputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),selectionReason:z9__default.default.string(),iteration:z9__default.default.number()}),execute:async({inputData,getInitData,writer})=>{const initData=await getInitData();const completionSchema=z9__default.default.object({isComplete:z9__default.default.boolean(),finalResult:z9__default.default.string(),completionReason:z9__default.default.string()});const routingAgent=await getRoutingAgent({runtimeContext,agent});let completionResult;let iterationCount=(inputData.iteration
|
|
488
|
+
_agentNetworkAppend:true});}function getLastMessage(messages){let message="";if(typeof messages==="string"){message=messages;}else {const lastMessage=Array.isArray(messages)?messages[messages.length-1]:messages;if(typeof lastMessage==="string"){message=lastMessage;}else if(lastMessage&&`content`in lastMessage&&lastMessage?.content){const lastMessageContent=lastMessage.content;if(typeof lastMessageContent==="string"){message=lastMessageContent;}else if(Array.isArray(lastMessageContent)){const lastPart=lastMessageContent[lastMessageContent.length-1];if(lastPart?.type==="text"){message=lastPart.text;}}}}return message;}async function prepareMemoryStep({threadId,resourceId,messages,routingAgent,runtimeContext,generateId:generateId3,tracingContext,memoryConfig}){const memory=await routingAgent.getMemory({runtimeContext});let thread=await memory?.getThreadById({threadId});if(!thread){thread=await memory?.createThread({threadId,title:`New Thread ${(/* @__PURE__ */new Date()).toISOString()}`,resourceId});}let userMessage;const promises=[];if(typeof messages==="string"){userMessage=messages;if(memory){promises.push(memory.saveMessages({messages:[{id:generateId3(),type:"text",role:"user",content:{parts:[{type:"text",text:messages}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:thread?.id,resourceId:thread?.resourceId}],format:"v2"}));}}else {const messageList=new chunkMJMID7LX_cjs.MessageList({threadId:thread?.id,resourceId:thread?.resourceId});messageList.add(messages,"user");const messagesToSave=messageList.get.all.v2();if(memory){promises.push(memory.saveMessages({messages:messagesToSave,format:"v2"}));}const uiMessages=messageList.get.all.ui();const mostRecentUserMessage=routingAgent.getMostRecentUserMessage(uiMessages);userMessage=mostRecentUserMessage?.content;}if(thread?.title?.startsWith("New Thread")&&memory){const config=memory.getMergedThreadConfig(memoryConfig||{});const{shouldGenerate,model:titleModel,instructions:titleInstructions}=routingAgent.resolveTitleGenerationConfig(config?.threads?.generateTitle);if(shouldGenerate&&userMessage){promises.push(routingAgent.genTitle(userMessage,runtimeContext,tracingContext||{currentSpan:void 0},titleModel,titleInstructions).then(title=>{if(title){return memory.createThread({threadId:thread.id,resourceId:thread.resourceId,memoryConfig,title,metadata:thread.metadata});}}));}}await Promise.all(promises);return {thread};}async function createNetworkLoop({networkName,runtimeContext,runId,agent,generateId:generateId3,routingAgentOptions}){const routingStep=createStep({id:"routing-agent-step",inputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,result:z9__default.default.string().optional(),iteration:z9__default.default.number(),threadId:z9__default.default.string().optional(),threadResourceId:z9__default.default.string().optional(),isOneOff:z9__default.default.boolean(),verboseIntrospection:z9__default.default.boolean()}),outputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),selectionReason:z9__default.default.string(),iteration:z9__default.default.number()}),execute:async({inputData,getInitData,writer})=>{const initData=await getInitData();const completionSchema=z9__default.default.object({isComplete:z9__default.default.boolean(),finalResult:z9__default.default.string(),completionReason:z9__default.default.string()});const routingAgent=await getRoutingAgent({runtimeContext,agent});let completionResult;let iterationCount=(inputData.iteration?inputData.iteration:-1)+1;await writer.write({type:"routing-agent-start",payload:{agentId:routingAgent.id,runId,inputData:{...inputData,iteration:iterationCount}},runId,from:"NETWORK"/* NETWORK */});if(inputData.primitiveType!=="none"&&inputData?.result){const completionPrompt=`
|
|
489
489
|
The ${inputData.primitiveType} ${inputData.primitiveId} has contributed to the task.
|
|
490
490
|
This is the result from the agent: ${typeof inputData.result==="object"?JSON.stringify(inputData.result):inputData.result}
|
|
491
491
|
|
|
@@ -501,7 +501,7 @@ _agentNetworkAppend:true});}function getLastMessage(messages){let message="";if(
|
|
|
501
501
|
"completionReason": string,
|
|
502
502
|
"finalResult": string
|
|
503
503
|
}
|
|
504
|
-
`;const
|
|
504
|
+
`;const streamOptions={structuredOutput:{schema:completionSchema},runtimeContext,maxSteps:1,memory:{thread:initData?.threadId??runId,resource:initData?.threadResourceId??networkName,readOnly:true},...routingAgentOptions};let completionStream=await routingAgent.stream(completionPrompt,streamOptions);let currentText="";let currentTextIdx=0;await writer.write({type:"routing-agent-text-start",payload:{runId},from:"NETWORK"/* NETWORK */,runId});for await(const chunk of completionStream.objectStream){if(chunk?.finalResult){currentText=chunk.finalResult;}const currentSlice=currentText.slice(currentTextIdx);if(chunk?.isComplete&¤tSlice.length){await writer.write({type:"routing-agent-text-delta",payload:{text:currentSlice},from:"NETWORK"/* NETWORK */,runId});currentTextIdx=currentText.length;}}if(completionStream.error){console.warn("Error detected in structured output stream. Attempting fallback with JSON prompt injection.");currentText="";currentTextIdx=0;completionStream=await routingAgent.stream(completionPrompt,{...streamOptions,structuredOutput:{...streamOptions.structuredOutput,jsonPromptInjection:true}});for await(const chunk of completionStream.objectStream){if(chunk?.finalResult){currentText=chunk.finalResult;}const currentSlice=currentText.slice(currentTextIdx);if(chunk?.isComplete&¤tSlice.length){await writer.write({type:"routing-agent-text-delta",payload:{text:currentSlice},from:"NETWORK"/* NETWORK */,runId});currentTextIdx=currentText.length;}}}completionResult=await completionStream.getFullOutput();if(completionResult?.object?.isComplete){const endPayload2={task:inputData.task,primitiveId:"",primitiveType:"none",prompt:"",result:completionResult.object.finalResult,isComplete:true,selectionReason:completionResult.object.completionReason||"",iteration:iterationCount,runId};await writer.write({type:"routing-agent-end",payload:{...endPayload2,usage:await completionStream.usage},from:"NETWORK"/* NETWORK */,runId});const memory=await agent.getMemory({runtimeContext});await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:completionResult?.object?.finalResult||""}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData?.threadId||runId,resourceId:initData?.threadResourceId||networkName}],format:"v2"});return endPayload2;}}const prompt=[{role:"assistant",content:`
|
|
505
505
|
${inputData.isOneOff?"You are executing just one primitive based on the user task. Make sure to pick the primitive that is the best suited to accomplish the whole task. Primitives that execute only part of the task should be avoided.":"You will be calling just *one* primitive at a time to accomplish the user task, every call to you is one decision in the process of accomplishing the user task. Make sure to pick primitives that are the best suited to accomplish the whole task. Completeness is the highest priority."}
|
|
506
506
|
|
|
507
507
|
The user has given you the following task:
|
|
@@ -535,11 +535,11 @@ ${completionResult?.object?.finalResult}`:""}
|
|
|
535
535
|
`}];const options={structuredOutput:{schema:z9__default.default.object({primitiveId:z9__default.default.string().describe("The id of the primitive to be called"),primitiveType:PRIMITIVE_TYPES.describe("The type of the primitive to be called"),prompt:z9__default.default.string().describe("The json string or text value to be sent to the primitive"),selectionReason:z9__default.default.string().describe("The reason you picked the primitive")})},runtimeContext,maxSteps:1,memory:{thread:initData?.threadId??runId,resource:initData?.threadResourceId??networkName,readOnly:true},...routingAgentOptions};const result=await tryGenerateWithJsonFallback(routingAgent,prompt,options);const object=result.object;const endPayload={task:inputData.task,result:"",primitiveId:object.primitiveId,primitiveType:object.primitiveType,prompt:object.prompt,isComplete:object.primitiveId==="none"&&object.primitiveType==="none",selectionReason:object.selectionReason,iteration:iterationCount,runId};await writer.write({type:"routing-agent-end",payload:{...endPayload,usage:result.usage},from:"NETWORK"/* NETWORK */,runId});return endPayload;}});const agentStep=createStep({id:"agent-execution-step",inputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),selectionReason:z9__default.default.string(),iteration:z9__default.default.number()}),outputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),iteration:z9__default.default.number()}),execute:async({inputData,writer,getInitData})=>{const agentsMap=await agent.listAgents({runtimeContext});const agentId=inputData.primitiveId;const agentForStep=agentsMap[agentId];if(!agentForStep){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_NETWORK_AGENT_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Agent ${agentId} not found`});throw mastraError;}await writer.write({type:"agent-execution-start",payload:{agentId:inputData.primitiveId,args:inputData,runId},from:"NETWORK"/* NETWORK */,runId});const result=await agentForStep.stream(inputData.prompt,{// resourceId: inputData.resourceId,
|
|
536
536
|
// threadId: inputData.threadId,
|
|
537
537
|
runtimeContext,runId});for await(const chunk of result.fullStream){await writer.write({type:`agent-execution-event-${chunk.type}`,payload:chunk,runId:chunk.runId,from:"NETWORK"/* NETWORK */});}const memory=await agent.getMemory({runtimeContext});const initData=await getInitData();const messages=result.messageList.get.all.v1();await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:JSON.stringify({isNetwork:true,selectionReason:inputData.selectionReason,primitiveType:inputData.primitiveType,primitiveId:inputData.primitiveId,input:inputData.prompt,finalResult:{text:await result.text,toolCalls:await result.toolCalls,messages}})}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData?.threadId||runId,resourceId:initData?.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,agentId:inputData.primitiveId,result:await result.text,isComplete:false,iteration:inputData.iteration};await writer.write({type:"agent-execution-end",payload:{...endPayload,usage:await result.usage},from:"NETWORK"/* NETWORK */,runId});return {task:inputData.task,primitiveId:inputData.primitiveId,primitiveType:inputData.primitiveType,result:await result.text,isComplete:false,iteration:inputData.iteration};}});const workflowStep=createStep({id:"workflow-execution-step",inputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),selectionReason:z9__default.default.string(),iteration:z9__default.default.number()}),outputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),iteration:z9__default.default.number()}),execute:async({inputData,writer,getInitData})=>{const workflowsMap=await agent.getWorkflows({runtimeContext});const workflowId=inputData.primitiveId;const wf=workflowsMap[workflowId];if(!wf){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_NETWORK_WORKFLOW_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Workflow ${workflowId} not found`});throw mastraError;}let input;try{input=JSON.parse(inputData.prompt);}catch(e){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"WORKFLOW_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Invalid task input: ${inputData.task}`},e);throw mastraError;}const run=await wf.createRunAsync({runId});const toolData={name:wf.name,args:inputData,runId};await writer?.write({type:"workflow-execution-start",payload:toolData,from:"NETWORK"/* NETWORK */,runId});const stream=run.streamVNext({inputData:input,runtimeContext});let chunks=[];for await(const chunk of stream){chunks.push(chunk);await writer?.write({type:`workflow-execution-event-${chunk.type}`,payload:chunk,runId:chunk.runId,from:"NETWORK"/* NETWORK */});}let runSuccess=true;const workflowState=await stream.result;if(!workflowState?.status||workflowState?.status==="failed"){runSuccess=false;}const finalResult=JSON.stringify({isNetwork:true,primitiveType:inputData.primitiveType,primitiveId:inputData.primitiveId,selectionReason:inputData.selectionReason,input,finalResult:{runId:run.runId,runResult:workflowState,chunks,runSuccess}});const memory=await agent.getMemory({runtimeContext});const initData=await getInitData();await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:finalResult}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData?.threadId||runId,resourceId:initData?.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,primitiveId:inputData.primitiveId,primitiveType:inputData.primitiveType,result:finalResult,isComplete:false,iteration:inputData.iteration,name:wf.name};await writer?.write({type:"workflow-execution-end",payload:{...endPayload,usage:await stream.usage},from:"NETWORK"/* NETWORK */,runId});return endPayload;}});const toolStep=createStep({id:"tool-execution-step",inputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),selectionReason:z9__default.default.string(),iteration:z9__default.default.number()}),outputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),iteration:z9__default.default.number()}),execute:async({inputData,getInitData,writer})=>{const initData=await getInitData();const agentTools=await agent.getTools({runtimeContext});const memory=await agent.getMemory({runtimeContext});const memoryTools=await memory?.getTools?.();const toolsMap={...agentTools,...memoryTools};const toolId=inputData.primitiveId;let tool=toolsMap[toolId];if(!tool){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Tool ${toolId} not found`});throw mastraError;}if(!tool.execute){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Tool ${toolId} does not have an execute function`});throw mastraError;}let inputDataToUse;try{inputDataToUse=JSON.parse(inputData.prompt);}catch(e){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Invalid task input: ${inputData.task}`},e);throw mastraError;}const toolCallId=generateId3();await writer?.write({type:"tool-execution-start",payload:{args:{...inputData,args:inputDataToUse,toolName:toolId,toolCallId},runId},from:"NETWORK"/* NETWORK */,runId});const finalResult=await tool.execute({runtimeContext,mastra:agent.getMastraInstance(),resourceId:initData.threadResourceId||networkName,threadId:initData.threadId,runId,memory,context:inputDataToUse,// TODO: Pass proper tracing context when network supports tracing
|
|
538
|
-
tracingContext:{currentSpan:void 0},writer},{toolCallId,messages:[]});await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:JSON.stringify({isNetwork:true,selectionReason:inputData.selectionReason,primitiveType:inputData.primitiveType,primitiveId:toolId,finalResult:{result:finalResult,toolCallId},input:inputDataToUse})}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData.threadId||runId,resourceId:initData.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,primitiveId:toolId,primitiveType:inputData.primitiveType,result:finalResult,isComplete:false,iteration:inputData.iteration,toolCallId,toolName:toolId};await writer?.write({type:"tool-execution-end",payload:endPayload,from:"NETWORK"/* NETWORK */,runId});return endPayload;}});const finishStep=createStep({id:"finish-step",inputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),selectionReason:z9__default.default.string(),iteration:z9__default.default.number()}),outputSchema:z9__default.default.object({task:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean(),iteration:z9__default.default.number()}),execute:async({inputData,writer})=>{let endResult=inputData.result;if(inputData.primitiveId==="none"&&inputData.primitiveType==="none"&&!inputData.result){endResult=inputData.selectionReason;}const endPayload={task:inputData.task,result:endResult,isComplete:!!inputData.isComplete,iteration:inputData.iteration,runId};await writer?.write({type:"network-execution-event-step-finish",payload:endPayload,from:"NETWORK"/* NETWORK */,runId});return endPayload;}});const networkWorkflow=createWorkflow({id:"Agent-Network-Outer-Workflow",inputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,result:z9__default.default.string().optional(),iteration:z9__default.default.number(),threadId:z9__default.default.string().optional(),threadResourceId:z9__default.default.string().optional(),isOneOff:z9__default.default.boolean(),verboseIntrospection:z9__default.default.boolean()}),outputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),completionReason:z9__default.default.string().optional(),iteration:z9__default.default.number(),threadId:z9__default.default.string().optional(),threadResourceId:z9__default.default.string().optional(),isOneOff:z9__default.default.boolean()}),options:{shouldPersistSnapshot:({workflowStatus})=>workflowStatus==="suspended"}});networkWorkflow.then(routingStep).branch([[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="agent",agentStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="workflow",workflowStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="tool",toolStep],[async({inputData})=>!!inputData.isComplete,finishStep]]).map({task:{step:[routingStep,agentStep,workflowStep,toolStep],path:"task"},isComplete:{step:[agentStep,workflowStep,toolStep,finishStep],path:"isComplete"},completionReason:{step:[routingStep,agentStep,workflowStep,toolStep,finishStep],path:"completionReason"},result:{step:[agentStep,workflowStep,toolStep,finishStep],path:"result"},primitiveId:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveId"},primitiveType:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveType"},iteration:{step:[routingStep,agentStep,workflowStep,toolStep],path:"iteration"},isOneOff:{initData:networkWorkflow,path:"isOneOff"},threadId:{initData:networkWorkflow,path:"threadId"},threadResourceId:{initData:networkWorkflow,path:"threadResourceId"}}).commit();return {networkWorkflow};}async function networkLoop({networkName,runtimeContext,runId,routingAgent,routingAgentOptions,generateId:generateId3,maxIterations,threadId,resourceId,messages}){const memoryToUse=await routingAgent.getMemory({runtimeContext});if(!memoryToUse){throw new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_NETWORK_MEMORY_REQUIRED",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:"Memory is required for the agent network to function properly. Please configure memory for the agent.",details:{status:400}});}const{memory:routingAgentMemoryOptions,...routingAgentOptionsWithoutMemory}=routingAgentOptions||{};const{networkWorkflow}=await createNetworkLoop({networkName,runtimeContext,runId,agent:routingAgent,routingAgentOptions:routingAgentOptionsWithoutMemory,generateId:generateId3});const finalStep=createStep({id:"final-step",inputSchema:networkWorkflow.outputSchema,outputSchema:networkWorkflow.outputSchema,execute:async({inputData,writer})=>{if(inputData.iteration>=maxIterations){await writer?.write({type:"network-execution-event-finish",payload:{...inputData,completionReason:`Max iterations reached: ${maxIterations}`}});return {...inputData,completionReason:`Max iterations reached: ${maxIterations}`};}return inputData;}});const mainWorkflow=createWorkflow({id:"agent-loop-main-workflow",inputSchema:z9__default.default.object({iteration:z9__default.default.number(),task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,result:z9__default.default.string().optional(),threadId:z9__default.default.string().optional(),threadResourceId:z9__default.default.string().optional(),isOneOff:z9__default.default.boolean(),verboseIntrospection:z9__default.default.boolean()}),outputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),completionReason:z9__default.default.string().optional(),iteration:z9__default.default.number()}),options:{shouldPersistSnapshot:({workflowStatus})=>workflowStatus==="suspended"}}).dountil(networkWorkflow,async({inputData})=>{return inputData.isComplete||inputData.iteration>=maxIterations;}).then(finalStep).commit();const run=await mainWorkflow.createRunAsync({runId});const{thread}=await prepareMemoryStep({runtimeContext,threadId:threadId||run.runId,resourceId:resourceId||networkName,messages,routingAgent,generateId:generateId3,tracingContext:routingAgentOptions?.tracingContext,memoryConfig:routingAgentMemoryOptions?.options});const task=getLastMessage(messages);return new MastraAgentNetworkStream({run,createStream:()=>{return run.streamVNext({inputData:{task,primitiveId:"",primitiveType:"none",iteration:0,threadResourceId:thread?.resourceId,threadId:thread?.id,isOneOff:false,verboseIntrospection:true}}).fullStream;}});}// src/processors/runner.ts
|
|
538
|
+
tracingContext:{currentSpan:void 0},writer},{toolCallId,messages:[]});await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:JSON.stringify({isNetwork:true,selectionReason:inputData.selectionReason,primitiveType:inputData.primitiveType,primitiveId:toolId,finalResult:{result:finalResult,toolCallId},input:inputDataToUse})}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData.threadId||runId,resourceId:initData.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,primitiveId:toolId,primitiveType:inputData.primitiveType,result:finalResult,isComplete:false,iteration:inputData.iteration,toolCallId,toolName:toolId};await writer?.write({type:"tool-execution-end",payload:endPayload,from:"NETWORK"/* NETWORK */,runId});return endPayload;}});const finishStep=createStep({id:"finish-step",inputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),selectionReason:z9__default.default.string(),iteration:z9__default.default.number()}),outputSchema:z9__default.default.object({task:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean(),iteration:z9__default.default.number()}),execute:async({inputData,writer})=>{let endResult=inputData.result;if(inputData.primitiveId==="none"&&inputData.primitiveType==="none"&&!inputData.result){endResult=inputData.selectionReason;}const endPayload={task:inputData.task,result:endResult,isComplete:!!inputData.isComplete,iteration:inputData.iteration,runId};await writer?.write({type:"network-execution-event-step-finish",payload:endPayload,from:"NETWORK"/* NETWORK */,runId});return endPayload;}});const networkWorkflow=createWorkflow({id:"Agent-Network-Outer-Workflow",inputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,result:z9__default.default.string().optional(),iteration:z9__default.default.number(),threadId:z9__default.default.string().optional(),threadResourceId:z9__default.default.string().optional(),isOneOff:z9__default.default.boolean(),verboseIntrospection:z9__default.default.boolean()}),outputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),completionReason:z9__default.default.string().optional(),iteration:z9__default.default.number(),threadId:z9__default.default.string().optional(),threadResourceId:z9__default.default.string().optional(),isOneOff:z9__default.default.boolean()}),options:{shouldPersistSnapshot:({workflowStatus})=>workflowStatus==="suspended"}});networkWorkflow.then(routingStep).branch([[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="agent",agentStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="workflow",workflowStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="tool",toolStep],[async({inputData})=>!!inputData.isComplete,finishStep]]).map({task:{step:[routingStep,agentStep,workflowStep,toolStep],path:"task"},isComplete:{step:[agentStep,workflowStep,toolStep,finishStep],path:"isComplete"},completionReason:{step:[routingStep,agentStep,workflowStep,toolStep,finishStep],path:"completionReason"},result:{step:[agentStep,workflowStep,toolStep,finishStep],path:"result"},primitiveId:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveId"},primitiveType:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveType"},iteration:{step:[routingStep,agentStep,workflowStep,toolStep],path:"iteration"},isOneOff:{initData:networkWorkflow,path:"isOneOff"},threadId:{initData:networkWorkflow,path:"threadId"},threadResourceId:{initData:networkWorkflow,path:"threadResourceId"}}).commit();return {networkWorkflow};}async function networkLoop({networkName,runtimeContext,runId,routingAgent,routingAgentOptions,generateId:generateId3,maxIterations,threadId,resourceId,messages}){const memoryToUse=await routingAgent.getMemory({runtimeContext});if(!memoryToUse){throw new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_NETWORK_MEMORY_REQUIRED",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:"Memory is required for the agent network to function properly. Please configure memory for the agent.",details:{status:400}});}const{memory:routingAgentMemoryOptions,...routingAgentOptionsWithoutMemory}=routingAgentOptions||{};const{networkWorkflow}=await createNetworkLoop({networkName,runtimeContext,runId,agent:routingAgent,routingAgentOptions:routingAgentOptionsWithoutMemory,generateId:generateId3});const finalStep=createStep({id:"final-step",inputSchema:networkWorkflow.outputSchema,outputSchema:networkWorkflow.outputSchema,execute:async({inputData,writer})=>{if(inputData.iteration>=maxIterations){await writer?.write({type:"network-execution-event-finish",payload:{...inputData,completionReason:`Max iterations reached: ${maxIterations}`},from:"NETWORK"/* NETWORK */,runId});return {...inputData,completionReason:`Max iterations reached: ${maxIterations}`};}return inputData;}});const mainWorkflow=createWorkflow({id:"agent-loop-main-workflow",inputSchema:z9__default.default.object({iteration:z9__default.default.number(),task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,result:z9__default.default.string().optional(),threadId:z9__default.default.string().optional(),threadResourceId:z9__default.default.string().optional(),isOneOff:z9__default.default.boolean(),verboseIntrospection:z9__default.default.boolean()}),outputSchema:z9__default.default.object({task:z9__default.default.string(),primitiveId:z9__default.default.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9__default.default.string(),result:z9__default.default.string(),isComplete:z9__default.default.boolean().optional(),completionReason:z9__default.default.string().optional(),iteration:z9__default.default.number()}),options:{shouldPersistSnapshot:({workflowStatus})=>workflowStatus==="suspended"}}).dountil(networkWorkflow,async({inputData})=>{return inputData.isComplete||inputData.iteration>=maxIterations;}).then(finalStep).commit();const run=await mainWorkflow.createRunAsync({runId});const{thread}=await prepareMemoryStep({runtimeContext,threadId:threadId||run.runId,resourceId:resourceId||networkName,messages,routingAgent,generateId:generateId3,tracingContext:routingAgentOptions?.tracingContext,memoryConfig:routingAgentMemoryOptions?.options});const task=getLastMessage(messages);return new MastraAgentNetworkStream({run,createStream:()=>{return run.streamVNext({inputData:{task,primitiveId:"",primitiveType:"none",iteration:0,threadResourceId:thread?.resourceId,threadId:thread?.id,isOneOff:false,verboseIntrospection:true}}).fullStream;}});}// src/processors/runner.ts
|
|
539
539
|
var ProcessorState=class{accumulatedText="";customState={};streamParts=[];span;constructor(options){const{processorName,tracingContext,processorIndex}=options;const currentSpan=tracingContext?.currentSpan;const parentSpan=currentSpan?.findParent("agent_run"/* AGENT_RUN */)||currentSpan?.parent||currentSpan;this.span=parentSpan?.createChildSpan({type:"processor_run"/* PROCESSOR_RUN */,name:`output processor: ${processorName}`,attributes:{processorName,processorType:"output",processorIndex:processorIndex??0},input:{streamParts:[],state:{},totalChunks:0}});}// Internal methods for the runner
|
|
540
540
|
addPart(part){if(part.type==="text-delta"){this.accumulatedText+=part.payload.text;}this.streamParts.push(part);if(this.span){this.span.input={streamParts:this.streamParts,state:this.customState,totalChunks:this.streamParts.length,accumulatedText:this.accumulatedText};}}};var ProcessorRunner=class{inputProcessors;outputProcessors;logger;agentName;constructor({inputProcessors,outputProcessors,logger,agentName}){this.inputProcessors=inputProcessors??[];this.outputProcessors=outputProcessors??[];this.logger=logger;this.agentName=agentName;}async runOutputProcessors(messageList,tracingContext,telemetry){const responseMessages=messageList.clear.response.v2();let processableMessages=[...responseMessages];const ctx={abort:()=>{throw new TripWire("Tripwire triggered");}};for(const[index,processor]of this.outputProcessors.entries()){const abort=reason=>{throw new TripWire(reason||`Tripwire triggered by ${processor.name}`);};ctx.abort=abort;const processMethod=processor.processOutputResult?.bind(processor);if(!processMethod){continue;}const currentSpan=tracingContext?.currentSpan;const parentSpan=currentSpan?.findParent("agent_run"/* AGENT_RUN */)||currentSpan?.parent||currentSpan;const processorSpan=parentSpan?.createChildSpan({type:"processor_run"/* PROCESSOR_RUN */,name:`output processor: ${processor.name}`,attributes:{processorName:processor.name,processorType:"output",processorIndex:index},input:processableMessages});if(!telemetry){processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});}else {await telemetry.traceMethod(async()=>{processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});return processableMessages;},{spanName:`agent.outputProcessor.${processor.name}`,attributes:{"processor.name":processor.name,"processor.index":index.toString(),"processor.total":this.outputProcessors.length.toString()}})();}processorSpan?.end({output:processableMessages});}if(processableMessages.length>0){messageList.add(processableMessages,"response");}return messageList;}/**
|
|
541
541
|
* Process a stream part through all output processors with state management
|
|
542
|
-
*/async processPart(part,processorStates,tracingContext){if(!this.outputProcessors.length){return {part,blocked:false};}try{let processedPart=part;const isFinishChunk=part.type==="finish";for(const[index,processor]of this.outputProcessors.entries()){try{if(processor.processOutputStream&&processedPart){let state=processorStates.get(processor.name);if(!state){state=new ProcessorState({processorName:processor.name,tracingContext,processorIndex:index});processorStates.set(processor.name,state);}state.addPart(processedPart);const result=await processor.processOutputStream({part:processedPart,streamParts:state.streamParts,state:state.customState,abort:reason=>{throw new TripWire(reason||`Stream part blocked by ${processor.name}`);},tracingContext:{currentSpan:state.span}});if(state.span&&!state.span.isEvent){state.span.output=result;}processedPart=result;}}catch(error){if(error instanceof TripWire){const state2=processorStates.get(processor.name);state2?.span?.end({metadata:{blocked:true,reason:error.message}});return {part:null,blocked:true,reason:error.message};}const state=processorStates.get(processor.name);state?.span?.error({error,endSpan:true});this.logger.error(`[Agent:${this.agentName}] - Output processor ${processor.name} failed:`,error);}}if(isFinishChunk){for(const state of processorStates.values()){if(state.span){const finalOutput={...state.span.output,totalChunks:state.streamParts.length,finalState:state.customState};state.span.end({output:finalOutput});}}}return {part:processedPart,blocked:false};}catch(error){this.logger.error(`[Agent:${this.agentName}] - Stream part processing failed:`,error);for(const state of processorStates.values()){state.span?.error({error,endSpan:true});}return {part,blocked:false};}}async runOutputProcessorsForStream(streamResult,tracingContext){return new ReadableStream({start:async controller=>{const reader=streamResult.fullStream.getReader();const processorStates=/* @__PURE__ */new Map();try{while(true){const{done,value}=await reader.read();if(done){controller.close();break;}const{part:processedPart,blocked,reason}=await this.processPart(value,processorStates,tracingContext);if(blocked){void this.logger.debug(`[Agent:${this.agentName}] - Stream part blocked by output processor`,{reason,originalPart:value});controller.enqueue({type:"tripwire",tripwireReason:reason||"Output processor blocked content"});controller.close();break;}else if(processedPart!==null){controller.enqueue(processedPart);}}}catch(error){controller.error(error);}}});}async runInputProcessors(messageList,tracingContext,telemetry){const userMessages=messageList.clear.input.v2();let processableMessages=[...userMessages];const ctx={abort:()=>{throw new TripWire("Tripwire triggered");}};for(const[index,processor]of this.inputProcessors.entries()){const abort=reason=>{throw new TripWire(reason||`Tripwire triggered by ${processor.name}`);};ctx.abort=abort;const processMethod=processor.processInput?.bind(processor);if(!processMethod){continue;}const currentSpan=tracingContext?.currentSpan;const parentSpan=currentSpan?.findParent("agent_run"/* AGENT_RUN */)||currentSpan?.parent||currentSpan;const processorSpan=parentSpan?.createChildSpan({type:"processor_run"/* PROCESSOR_RUN */,name:`input processor: ${processor.name}`,attributes:{processorName:processor.name,processorType:"input",processorIndex:index},input:processableMessages});if(!telemetry){processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});}else {await telemetry.traceMethod(async()=>{processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});return processableMessages;},{spanName:`agent.inputProcessor.${processor.name}`,attributes:{"processor.name":processor.name,"processor.index":index.toString(),"processor.total":this.inputProcessors.length.toString()}})();}processorSpan?.end({output:processableMessages});}if(processableMessages.length>0){messageList.add(
|
|
542
|
+
*/async processPart(part,processorStates,tracingContext){if(!this.outputProcessors.length){return {part,blocked:false};}try{let processedPart=part;const isFinishChunk=part.type==="finish";for(const[index,processor]of this.outputProcessors.entries()){try{if(processor.processOutputStream&&processedPart){let state=processorStates.get(processor.name);if(!state){state=new ProcessorState({processorName:processor.name,tracingContext,processorIndex:index});processorStates.set(processor.name,state);}state.addPart(processedPart);const result=await processor.processOutputStream({part:processedPart,streamParts:state.streamParts,state:state.customState,abort:reason=>{throw new TripWire(reason||`Stream part blocked by ${processor.name}`);},tracingContext:{currentSpan:state.span}});if(state.span&&!state.span.isEvent){state.span.output=result;}processedPart=result;}}catch(error){if(error instanceof TripWire){const state2=processorStates.get(processor.name);state2?.span?.end({metadata:{blocked:true,reason:error.message}});return {part:null,blocked:true,reason:error.message};}const state=processorStates.get(processor.name);state?.span?.error({error,endSpan:true});this.logger.error(`[Agent:${this.agentName}] - Output processor ${processor.name} failed:`,error);}}if(isFinishChunk){for(const state of processorStates.values()){if(state.span){const finalOutput={...state.span.output,totalChunks:state.streamParts.length,finalState:state.customState};state.span.end({output:finalOutput});}}}return {part:processedPart,blocked:false};}catch(error){this.logger.error(`[Agent:${this.agentName}] - Stream part processing failed:`,error);for(const state of processorStates.values()){state.span?.error({error,endSpan:true});}return {part,blocked:false};}}async runOutputProcessorsForStream(streamResult,tracingContext){return new ReadableStream({start:async controller=>{const reader=streamResult.fullStream.getReader();const processorStates=/* @__PURE__ */new Map();try{while(true){const{done,value}=await reader.read();if(done){controller.close();break;}const{part:processedPart,blocked,reason}=await this.processPart(value,processorStates,tracingContext);if(blocked){void this.logger.debug(`[Agent:${this.agentName}] - Stream part blocked by output processor`,{reason,originalPart:value});controller.enqueue({type:"tripwire",tripwireReason:reason||"Output processor blocked content"});controller.close();break;}else if(processedPart!==null){controller.enqueue(processedPart);}}}catch(error){controller.error(error);}}});}async runInputProcessors(messageList,tracingContext,telemetry){const userMessages=messageList.clear.input.v2();let processableMessages=[...userMessages];const ctx={abort:()=>{throw new TripWire("Tripwire triggered");}};for(const[index,processor]of this.inputProcessors.entries()){const abort=reason=>{throw new TripWire(reason||`Tripwire triggered by ${processor.name}`);};ctx.abort=abort;const processMethod=processor.processInput?.bind(processor);if(!processMethod){continue;}const currentSpan=tracingContext?.currentSpan;const parentSpan=currentSpan?.findParent("agent_run"/* AGENT_RUN */)||currentSpan?.parent||currentSpan;const processorSpan=parentSpan?.createChildSpan({type:"processor_run"/* PROCESSOR_RUN */,name:`input processor: ${processor.name}`,attributes:{processorName:processor.name,processorType:"input",processorIndex:index},input:processableMessages});if(!telemetry){processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});}else {await telemetry.traceMethod(async()=>{processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});return processableMessages;},{spanName:`agent.inputProcessor.${processor.name}`,attributes:{"processor.name":processor.name,"processor.index":index.toString(),"processor.total":this.inputProcessors.length.toString()}})();}processorSpan?.end({output:processableMessages});}if(processableMessages.length>0){const systemMessages=processableMessages.filter(m=>m.role==="system");const nonSystemMessages=processableMessages.filter(m=>m.role!=="system");for(const sysMsg of systemMessages){messageList.addSystem(sysMsg.content.content||sysMsg.content.parts.map(p=>p.type==="text"?p.text:"").join("\n"));}if(nonSystemMessages.length>0){messageList.add(nonSystemMessages,"input");}}return messageList;}};// src/workflows/legacy/workflow.ts
|
|
543
543
|
var LegacyStep=class{id;description;inputSchema;outputSchema;payload;execute;retryConfig;mastra;constructor({id,description,execute:execute2,payload,outputSchema,inputSchema,retryConfig}){this.id=id;this.description=description??"";this.inputSchema=inputSchema;this.payload=payload;this.outputSchema=outputSchema;this.execute=execute2;this.retryConfig=retryConfig;}};// src/workflows/legacy/types.ts
|
|
544
544
|
var WhenConditionReturnValue=/* @__PURE__ */(WhenConditionReturnValue2=>{WhenConditionReturnValue2["CONTINUE"]="continue";WhenConditionReturnValue2["CONTINUE_FAILED"]="continue_failed";WhenConditionReturnValue2["ABORT"]="abort";WhenConditionReturnValue2["LIMBO"]="limbo";return WhenConditionReturnValue2;})(WhenConditionReturnValue||{});// src/workflows/legacy/utils.ts
|
|
545
545
|
function isErrorEvent(stateEvent){return stateEvent.type.startsWith("xstate.error.actor.");}function isTransitionEvent(stateEvent){return stateEvent.type.startsWith("xstate.done.actor.");}function isVariableReference(value){return typeof value==="object"&&"step"in value&&"path"in value;}function getStepResult2(result){if(result?.status==="success")return result.output;return void 0;}function getSuspendedPaths({value,path,suspendedPaths}){if(typeof value==="string"){if(value==="suspended"){suspendedPaths.add(path);}}else {Object.keys(value).forEach(key=>getSuspendedPaths({value:value[key],path:path?`${path}.${key}`:key,suspendedPaths}));}}function isFinalState(status){return ["completed","failed"].includes(status);}function isLimboState(status){return status==="limbo";}function recursivelyCheckForFinalState({value,suspendedPaths,path}){if(typeof value==="string"){return isFinalState(value)||isLimboState(value)||suspendedPaths.has(path);}return Object.keys(value).every(key=>recursivelyCheckForFinalState({value:value[key],suspendedPaths,path:path?`${path}.${key}`:key}));}function getActivePathsAndStatus(value){const paths=[];const traverse=(current,path=[])=>{for(const[key,value2]of Object.entries(current)){const currentPath=[...path,key];if(typeof value2==="string"){paths.push({stepPath:currentPath,stepId:key,status:value2});}else if(typeof value2==="object"&&value2!==null){traverse(value2,currentPath);}}};traverse(value);return paths;}function mergeChildValue(startStepId,parent,child){const traverse=current=>{const obj={};for(const[key,value]of Object.entries(current)){if(key===startStepId){obj[key]={...child};}else if(typeof value==="string"){obj[key]=value;}else if(typeof value==="object"&&value!==null){obj[key]=traverse(value);}}return obj;};return traverse(parent);}var updateStepInHierarchy=(value,targetStepId)=>{const result={};for(const key of Object.keys(value)){const currentValue=value[key];if(key===targetStepId){result[key]="pending";}else if(typeof currentValue==="object"&¤tValue!==null){result[key]=updateStepInHierarchy(currentValue,targetStepId);}else {result[key]=currentValue;}}return result;};function getResultActivePaths(state){const activePaths=getActivePathsAndStatus(state.value);const activePathsAndStatus=activePaths.reduce((acc,curr)=>{const entry={status:curr.status,stepPath:curr.stepPath};if(curr.status==="suspended"){entry.suspendPayload=state.context.steps[curr.stepId].suspendPayload;entry.stepPath=curr.stepPath;}acc.set(curr.stepId,entry);return acc;},/* @__PURE__ */new Map());return activePathsAndStatus;}function isWorkflow(step){return step instanceof LegacyWorkflow;}function isAgent(step){return step instanceof exports.Agent;}function resolveVariables({runId,logger,variables,context}){const resolvedData={};for(const[key,variable]of Object.entries(variables)){const sourceData=variable.step==="trigger"?context.triggerData:getStepResult2(context.steps[variable.step.id??variable.step.name]);logger.debug(`Got source data for ${key} variable from ${variable.step==="trigger"?"trigger":variable.step.id??variable.step.name}`,{sourceData,path:variable.path,runId});if(!sourceData&&variable.step!=="trigger"){resolvedData[key]=void 0;continue;}const value=variable.path===""||variable.path==="."?sourceData:radash.get(sourceData,variable.path);logger.debug(`Resolved variable ${key}`,{value,runId});resolvedData[key]=value;}return resolvedData;}function agentToStep(agent,{mastra}={}){return {id:agent.name,inputSchema:z9.z.object({prompt:z9.z.string(),resourceId:z9.z.string().optional(),threadId:z9.z.string().optional()}),outputSchema:z9.z.object({text:z9.z.string()}),execute:async({context,runId,mastra:mastraFromExecute})=>{const realMastra=mastraFromExecute??mastra;if(!realMastra){throw new Error("Mastra instance not found");}agent.__registerMastra(realMastra);agent.__registerPrimitives({logger:realMastra.getLogger(),telemetry:realMastra.getTelemetry()});const result=await agent.generateLegacy(context.inputData.prompt,{runId,resourceId:context.inputData.resourceId,threadId:context.inputData.threadId});return {text:result.text};}};}function workflowToStep(workflow,{mastra}){workflow.setNested(true);return {id:workflow.name,workflow,workflowId:toCamelCaseWithRandomSuffix(workflow.name),execute:async({context,suspend,emit,mastra:mastraFromExecute,runtimeContext})=>{const realMastra=mastraFromExecute??mastra;if(realMastra){workflow.__registerMastra(realMastra);workflow.__registerPrimitives({logger:realMastra.getLogger(),telemetry:realMastra.getTelemetry()});}const run=context.isResume?workflow.createRun({runId:context.isResume.runId}):workflow.createRun();const unwatch=run.watch(state=>{emit("state-update",workflow.name,state.results,{...context,...{[workflow.name]:state.results}});});const awaitedResult=context.isResume&&context.isResume.stepId.includes(".")?await run.resume({stepId:context.isResume.stepId.split(".").slice(1).join("."),context:context.inputData,runtimeContext}):await run.start({triggerData:context.inputData,runtimeContext});unwatch();if(!awaitedResult){throw new Error("LegacyWorkflow run failed");}if(awaitedResult.activePaths?.size>0){const suspendedStep=[...awaitedResult.activePaths.entries()].find(([,{status}])=>{return status==="suspended";});if(suspendedStep){await suspend(suspendedStep[1].suspendPayload,{...awaitedResult,runId:run.runId});}}return {...awaitedResult,runId:run.runId};}};}function toCamelCaseWithRandomSuffix(str){if(!str)return "";const normalizedStr=str.replace(/[-_]/g," ");const words=normalizedStr.split(" ").filter(word=>word.length>0);const camelCase=words.map((word,index)=>{word=word.replace(/[^a-zA-Z0-9]/g,"");if(index===0){return word.toLowerCase();}return word.charAt(0).toUpperCase()+word.slice(1).toLowerCase();}).join("");const randomString=generateRandomLetters(3);return camelCase+randomString;}function generateRandomLetters(length){const characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let result="";for(let i=0;i<length;i++){const randomIndex=Math.floor(Math.random()*characters.length);result+=characters.charAt(randomIndex);}return result;}function isConditionalKey(key){return key.startsWith("__")&&(key.includes("_if")||key.includes("_else"));}// src/workflows/legacy/workflow-instance.ts
|
|
@@ -716,7 +716,7 @@ function createPrepareToolsStep({capabilities,options,threadFromArgs,resourceId,
|
|
|
716
716
|
function createStreamStep({capabilities,runId,returnScorerData,format="mastra",requireToolApproval,resumeContext,agentId,toolCallId}){return createStep({id:"stream-text-step",inputSchema:z9.z.any(),// tried to type this in various ways but it's too complex
|
|
717
717
|
outputSchema:z9.z.union([z9.z.instanceof(MastraModelOutput),z9.z.instanceof(AISDKV5OutputStream)]),execute:async({inputData,tracingContext})=>{const validatedInputData=inputData;capabilities.logger.debug(`Starting agent ${capabilities.agentName} llm stream call`,{runId});const processors=validatedInputData.outputProcessors||(capabilities.outputProcessors?typeof capabilities.outputProcessors==="function"?await capabilities.outputProcessors({runtimeContext:validatedInputData.runtimeContext||new chunkGPWMM745_cjs.RuntimeContext()}):capabilities.outputProcessors:[]);const streamResult=capabilities.llm.stream({...validatedInputData,outputProcessors:processors,returnScorerData,tracingContext,requireToolApproval,resumeContext,_internal:{generateId:capabilities.generateMessageId},agentId,toolCallId});if(format==="aisdk"){return streamResult.aisdk.v5;}return streamResult;}});}// src/agent/workflows/prepare-stream/index.ts
|
|
718
718
|
function createPrepareStreamWorkflow({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,format,instructions,memoryConfig,memory,saveQueueManager,returnScorerData,requireToolApproval,resumeContext,agentId,toolCallId}){const prepareToolsStep=createPrepareToolsStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,memory});const prepareMemoryStep2=createPrepareMemoryStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,instructions,memoryConfig,memory});const streamStep=createStreamStep({capabilities,runId,returnScorerData,format,requireToolApproval,resumeContext,agentId,toolCallId});const mapResultsStep=createMapResultsStep({capabilities,options,resourceId,runId,runtimeContext,memory,memoryConfig,saveQueueManager,agentAISpan,instructions,agentId});return createWorkflow({id:"execution-workflow",inputSchema:z9.z.object({}),outputSchema:z9.z.union([z9.z.instanceof(MastraModelOutput),z9.z.instanceof(AISDKV5OutputStream)]),steps:[prepareToolsStep,prepareMemoryStep2,streamStep],options:{tracingPolicy:{internal:1/* WORKFLOW */}}}).parallel([prepareToolsStep,prepareMemoryStep2]).map(mapResultsStep).then(streamStep).commit();}// src/agent/agent.ts
|
|
719
|
-
function resolveMaybePromise(value,cb){if(value instanceof Promise||value!=null&&typeof value.then==="function"){return Promise.resolve(value).then(cb);}return cb(value);}function resolveThreadIdFromArgs(args){if(args?.memory?.thread){if(typeof args.memory.thread==="string")return {id:args.memory.thread};if(typeof args.memory.thread==="object"&&args.memory.thread.id)return args.memory.thread;}if(args?.threadId)return {id:args.threadId};return void 0;}var _Agent_decorators,_init,_a;_Agent_decorators=[chunkAQGLVU53_cjs.InstrumentClass({prefix:"agent",excludeMethods:["hasOwnMemory","getMemory","__primitive","__registerMastra","__registerPrimitives","__runInputProcessors","__runOutputProcessors","_wrapToolsWithAITracing","getProcessorRunner","__setTools","__setLogger","__setTelemetry","log","listAgents","getModel","getInstructions","getTools","getLLM","getWorkflows","getDefaultGenerateOptions","getDefaultStreamOptions","getDescription","getScorers","getVoice"]})];exports.Agent=class Agent extends(_a=chunk6VOPKVYH_cjs.MastraBase){id;name;#instructions;#description;model;maxRetries;#mastra;#memory;#workflows;#defaultGenerateOptions;#defaultStreamOptions;#defaultVNextStreamOptions;#tools;evals;#scorers;#agents;#voice;#inputProcessors;#outputProcessors;#options;// This flag is for agent network messages. We should change the agent network formatting and remove this flag after.
|
|
719
|
+
function resolveMaybePromise(value,cb){if(value instanceof Promise||value!=null&&typeof value.then==="function"){return Promise.resolve(value).then(cb);}return cb(value);}function resolveThreadIdFromArgs(args){if(args?.memory?.thread){if(typeof args.memory.thread==="string")return {id:args.memory.thread};if(typeof args.memory.thread==="object"&&args.memory.thread.id)return args.memory.thread;}if(args?.threadId)return {id:args.threadId};return void 0;}var _Agent_decorators,_init,_a;_Agent_decorators=[chunkAQGLVU53_cjs.InstrumentClass({prefix:"agent",excludeMethods:["hasOwnMemory","getMemory","__primitive","__registerMastra","__registerPrimitives","__runInputProcessors","__runOutputProcessors","_wrapToolsWithAITracing","getProcessorRunner","__setTools","__setLogger","__setTelemetry","log","listAgents","getModel","getInstructions","getTools","getLLM","getWorkflows","getDefaultGenerateOptions","getDefaultStreamOptions","getDescription","getScorers","getVoice"]})];exports.Agent=class Agent extends(_a=chunk6VOPKVYH_cjs.MastraBase){id;name;#instructions;#description;model;#originalModel;maxRetries;#mastra;#memory;#workflows;#defaultGenerateOptions;#defaultStreamOptions;#defaultVNextStreamOptions;#tools;evals;#scorers;#agents;#voice;#inputProcessors;#outputProcessors;#options;// This flag is for agent network messages. We should change the agent network formatting and remove this flag after.
|
|
720
720
|
_agentNetworkAppend=false;/**
|
|
721
721
|
* Creates a new Agent instance with the specified configuration.
|
|
722
722
|
*
|
|
@@ -734,7 +734,7 @@ _agentNetworkAppend=false;/**
|
|
|
734
734
|
* maxRetries: 2,
|
|
735
735
|
* });
|
|
736
736
|
* ```
|
|
737
|
-
*/constructor(config){super({component:chunkA5KDVZDL_cjs.RegisteredLogger.AGENT});this.name=config.name;this.id=config.id??config.name;this.#instructions=config.instructions;this.#description=config.description;this.#options=config.options;if(!config.model){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_CONSTRUCTOR_MODEL_REQUIRED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:config.name},text:`LanguageModel is required to create an Agent. Please provide the 'model'.`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}if(Array.isArray(config.model)){if(config.model.length===0){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_CONSTRUCTOR_MODEL_ARRAY_EMPTY",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:config.name},text:`Model array is empty. Please provide at least one model.`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}this.model=config.model.map(mdl=>({id:crypto2.randomUUID(),model:mdl.model,maxRetries:mdl.maxRetries??config?.maxRetries??0,enabled:mdl.enabled??true}));}else {this.model=config.model;}this.maxRetries=config.maxRetries??0;if(config.workflows){this.#workflows=config.workflows;}this.#defaultGenerateOptions=config.defaultGenerateOptions||{};this.#defaultStreamOptions=config.defaultStreamOptions||{};this.#defaultVNextStreamOptions=config.defaultVNextStreamOptions||{};this.#tools=config.tools||{};this.evals={};if(config.mastra){this.__registerMastra(config.mastra);this.__registerPrimitives({telemetry:config.mastra.getTelemetry(),logger:config.mastra.getLogger()});}this.#scorers=config.scorers||{};this.#agents=config.agents||{};if(config.evals){this.evals=config.evals;}if(config.memory){this.#memory=config.memory;}if(config.voice){this.#voice=config.voice;if(typeof config.tools!=="function"){this.#voice?.addTools(this.tools);}if(typeof config.instructions==="string"){this.#voice?.addInstructions(config.instructions);}}else {this.#voice=new chunkWBAXXG34_cjs.DefaultVoice();}if(config.inputProcessors){this.#inputProcessors=config.inputProcessors;}if(config.outputProcessors){this.#outputProcessors=config.outputProcessors;}this._agentNetworkAppend=config._agentNetworkAppend||false;}getMastraInstance(){return this.#mastra;}/**
|
|
737
|
+
*/constructor(config){super({component:chunkA5KDVZDL_cjs.RegisteredLogger.AGENT});this.name=config.name;this.id=config.id??config.name;this.#instructions=config.instructions;this.#description=config.description;this.#options=config.options;if(!config.model){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_CONSTRUCTOR_MODEL_REQUIRED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:config.name},text:`LanguageModel is required to create an Agent. Please provide the 'model'.`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}if(Array.isArray(config.model)){if(config.model.length===0){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_CONSTRUCTOR_MODEL_ARRAY_EMPTY",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:config.name},text:`Model array is empty. Please provide at least one model.`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}this.model=config.model.map(mdl=>({id:crypto2.randomUUID(),model:mdl.model,maxRetries:mdl.maxRetries??config?.maxRetries??0,enabled:mdl.enabled??true}));this.#originalModel=[...this.model];}else {this.model=config.model;this.#originalModel=config.model;}this.maxRetries=config.maxRetries??0;if(config.workflows){this.#workflows=config.workflows;}this.#defaultGenerateOptions=config.defaultGenerateOptions||{};this.#defaultStreamOptions=config.defaultStreamOptions||{};this.#defaultVNextStreamOptions=config.defaultVNextStreamOptions||{};this.#tools=config.tools||{};this.evals={};if(config.mastra){this.__registerMastra(config.mastra);this.__registerPrimitives({telemetry:config.mastra.getTelemetry(),logger:config.mastra.getLogger()});}this.#scorers=config.scorers||{};this.#agents=config.agents||{};if(config.evals){this.evals=config.evals;}if(config.memory){this.#memory=config.memory;}if(config.voice){this.#voice=config.voice;if(typeof config.tools!=="function"){this.#voice?.addTools(this.tools);}if(typeof config.instructions==="string"){this.#voice?.addInstructions(config.instructions);}}else {this.#voice=new chunkWBAXXG34_cjs.DefaultVoice();}if(config.inputProcessors){this.#inputProcessors=config.inputProcessors;}if(config.outputProcessors){this.#outputProcessors=config.outputProcessors;}this._agentNetworkAppend=config._agentNetworkAppend||false;}getMastraInstance(){return this.#mastra;}/**
|
|
738
738
|
* Returns the agents configured for this agent, resolving function-based agents if necessary.
|
|
739
739
|
* Used in multi-agent collaboration scenarios where this agent can delegate to other agents.
|
|
740
740
|
*
|
|
@@ -866,7 +866,7 @@ _agentNetworkAppend=false;/**
|
|
|
866
866
|
* @param modelConfig The model configuration (magic string, config object, or LanguageModel)
|
|
867
867
|
* @returns A LanguageModel instance
|
|
868
868
|
* @internal
|
|
869
|
-
*/async resolveModelConfig(modelConfig,runtimeContext){try{return await
|
|
869
|
+
*/async resolveModelConfig(modelConfig,runtimeContext){try{return await chunk7J3XX4AO_cjs.resolveModelConfig(modelConfig,runtimeContext,this.#mastra);}catch(error){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_GET_MODEL_MISSING_MODEL_INSTANCE",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name,originalError:error instanceof Error?error.message:String(error)},text:`[Agent:${this.name}] - Failed to resolve model configuration`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}}/**
|
|
870
870
|
* Gets the model instance, resolving it if it's a function or model configuration.
|
|
871
871
|
* When the agent has multiple models configured, returns the first enabled model.
|
|
872
872
|
*
|
|
@@ -895,7 +895,11 @@ _agentNetworkAppend=false;/**
|
|
|
895
895
|
*/__updateInstructions(newInstructions){this.#instructions=newInstructions;this.logger.debug(`[Agents:${this.name}] Instructions updated.`,{model:this.model,name:this.name});}/**
|
|
896
896
|
* Updates the agent's model configuration.
|
|
897
897
|
* @internal
|
|
898
|
-
*/__updateModel({model}){this.model=model;this.logger.debug(`[Agents:${this.name}] Model updated.`,{model:this.model,name:this.name});}
|
|
898
|
+
*/__updateModel({model}){this.model=model;this.logger.debug(`[Agents:${this.name}] Model updated.`,{model:this.model,name:this.name});}/**
|
|
899
|
+
* Resets the agent's model to the original model set during construction.
|
|
900
|
+
* Clones arrays to prevent reordering mutations from affecting the original snapshot.
|
|
901
|
+
* @internal
|
|
902
|
+
*/__resetToOriginalModel(){this.model=Array.isArray(this.#originalModel)?[...this.#originalModel]:this.#originalModel;this.logger.debug(`[Agents:${this.name}] Model reset to original.`,{model:this.model,name:this.name});}reorderModels(modelIds){if(!Array.isArray(this.model)){this.logger.warn(`[Agents:${this.name}] model is not an array`);return;}this.model=this.model.sort((a,b)=>{const aIndex=modelIds.indexOf(a.id);const bIndex=modelIds.indexOf(b.id);return aIndex-bIndex;});this.logger.debug(`[Agents:${this.name}] Models reordered`);}updateModelInModelList({id,model,enabled,maxRetries}){if(!Array.isArray(this.model)){this.logger.warn(`[Agents:${this.name}] model is not an array`);return;}const modelToUpdate=this.model.find(m=>m.id===id);if(!modelToUpdate){this.logger.warn(`[Agents:${this.name}] model ${id} not found`);return;}this.model=this.model.map(mdl=>{if(mdl.id===id){return {...mdl,model:model??mdl.model,enabled:enabled??mdl.enabled,maxRetries:maxRetries??mdl.maxRetries};}return mdl;});this.logger.debug(`[Agents:${this.name}] model ${id} updated`);}#primitives;/**
|
|
899
903
|
* Registers telemetry and logger primitives with the agent.
|
|
900
904
|
* @internal
|
|
901
905
|
*/__registerPrimitives(p){if(p.telemetry){this.__setTelemetry(p.telemetry);}if(p.logger){this.__setLogger(p.logger);}this.#primitives=p;this.logger.debug(`[Agents:${this.name}] initialized.`,{model:this.model,name:this.name});}/**
|
|
@@ -1295,5 +1299,5 @@ exports.tryStreamWithJsonFallback = tryStreamWithJsonFallback;
|
|
|
1295
1299
|
exports.updateStepInHierarchy = updateStepInHierarchy;
|
|
1296
1300
|
exports.validateStepInput = validateStepInput;
|
|
1297
1301
|
exports.workflowToStep = workflowToStep;
|
|
1298
|
-
//# sourceMappingURL=chunk-
|
|
1299
|
-
//# sourceMappingURL=chunk-
|
|
1302
|
+
//# sourceMappingURL=chunk-253FBVD4.cjs.map
|
|
1303
|
+
//# sourceMappingURL=chunk-253FBVD4.cjs.map
|