@mastra/core 0.23.1 → 0.23.2-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.
Files changed (113) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/agent/agent.d.ts.map +1 -1
  3. package/dist/agent/index.cjs +13 -13
  4. package/dist/agent/index.js +2 -2
  5. package/dist/agent/input-processor/index.cjs +6 -6
  6. package/dist/agent/input-processor/index.js +1 -1
  7. package/dist/ai-tracing/index.cjs +36 -36
  8. package/dist/ai-tracing/index.d.ts +1 -1
  9. package/dist/ai-tracing/index.js +1 -1
  10. package/dist/ai-tracing/model-tracing.d.ts +63 -0
  11. package/dist/ai-tracing/model-tracing.d.ts.map +1 -0
  12. package/dist/{chunk-NVDVFJWA.js → chunk-32ZQNYMV.js} +3 -3
  13. package/dist/{chunk-NVDVFJWA.js.map → chunk-32ZQNYMV.js.map} +1 -1
  14. package/dist/{chunk-MRJUTTCU.js → chunk-455LR5KI.js} +3 -3
  15. package/dist/{chunk-MRJUTTCU.js.map → chunk-455LR5KI.js.map} +1 -1
  16. package/dist/{chunk-HANVMC6C.cjs → chunk-4PYSODHR.cjs} +12 -12
  17. package/dist/{chunk-HANVMC6C.cjs.map → chunk-4PYSODHR.cjs.map} +1 -1
  18. package/dist/{chunk-PS4ABZY7.js → chunk-6GDXSCHL.js} +5 -5
  19. package/dist/{chunk-PS4ABZY7.js.map → chunk-6GDXSCHL.js.map} +1 -1
  20. package/dist/{chunk-34WQUECJ.cjs → chunk-CE2Y5BC2.cjs} +52 -52
  21. package/dist/chunk-CE2Y5BC2.cjs.map +1 -0
  22. package/dist/{chunk-4YHU6R7W.cjs → chunk-CL6Z33KH.cjs} +18 -18
  23. package/dist/chunk-CL6Z33KH.cjs.map +1 -0
  24. package/dist/{chunk-ONKGWHY6.js → chunk-DTTOVV72.js} +194 -146
  25. package/dist/chunk-DTTOVV72.js.map +1 -0
  26. package/dist/{chunk-ZWF7AVLU.js → chunk-E3PG7G6E.js} +3 -3
  27. package/dist/{chunk-ZWF7AVLU.js.map → chunk-E3PG7G6E.js.map} +1 -1
  28. package/dist/{chunk-JZ7I64PK.js → chunk-ICGCDCJE.js} +17 -17
  29. package/dist/chunk-ICGCDCJE.js.map +1 -0
  30. package/dist/{chunk-ITCG6QJR.js → chunk-JZGCSEW5.js} +5 -5
  31. package/dist/{chunk-ITCG6QJR.js.map → chunk-JZGCSEW5.js.map} +1 -1
  32. package/dist/{chunk-HFXV34OE.js → chunk-KAEQISOW.js} +3 -3
  33. package/dist/{chunk-HFXV34OE.js.map → chunk-KAEQISOW.js.map} +1 -1
  34. package/dist/{chunk-4XE7GVZM.cjs → chunk-MCASUJWY.cjs} +35 -35
  35. package/dist/chunk-MCASUJWY.cjs.map +1 -0
  36. package/dist/{chunk-JTI6TVDV.cjs → chunk-MJMID7LX.cjs} +4 -4
  37. package/dist/{chunk-JTI6TVDV.cjs.map → chunk-MJMID7LX.cjs.map} +1 -1
  38. package/dist/{chunk-7KYNQSR4.js → chunk-N4DKYHQH.js} +15 -15
  39. package/dist/chunk-N4DKYHQH.js.map +1 -0
  40. package/dist/{chunk-QOTPNUIA.js → chunk-NNBF7NYQ.js} +4 -4
  41. package/dist/{chunk-QOTPNUIA.js.map → chunk-NNBF7NYQ.js.map} +1 -1
  42. package/dist/{chunk-A55YFHFT.js → chunk-NR77P3TK.js} +32 -32
  43. package/dist/chunk-NR77P3TK.js.map +1 -0
  44. package/dist/{chunk-DPE27ECD.cjs → chunk-NTKOVUTG.cjs} +11 -11
  45. package/dist/{chunk-DPE27ECD.cjs.map → chunk-NTKOVUTG.cjs.map} +1 -1
  46. package/dist/{chunk-5P4S4AVU.cjs → chunk-OOMWL2VB.cjs} +4 -4
  47. package/dist/{chunk-5P4S4AVU.cjs.map → chunk-OOMWL2VB.cjs.map} +1 -1
  48. package/dist/{chunk-PDST7KX7.cjs → chunk-P35FNLTQ.cjs} +194 -146
  49. package/dist/chunk-P35FNLTQ.cjs.map +1 -0
  50. package/dist/{chunk-7XAVBWZI.cjs → chunk-SKAKD7UJ.cjs} +12 -12
  51. package/dist/{chunk-7XAVBWZI.cjs.map → chunk-SKAKD7UJ.cjs.map} +1 -1
  52. package/dist/{chunk-VTNVK7HN.cjs → chunk-UZKIGB7M.cjs} +4 -4
  53. package/dist/{chunk-VTNVK7HN.cjs.map → chunk-UZKIGB7M.cjs.map} +1 -1
  54. package/dist/{chunk-TYWQLUF6.cjs → chunk-WCTRQHTG.cjs} +8 -8
  55. package/dist/{chunk-TYWQLUF6.cjs.map → chunk-WCTRQHTG.cjs.map} +1 -1
  56. package/dist/index.cjs +48 -48
  57. package/dist/index.js +8 -8
  58. package/dist/llm/index.cjs +7 -7
  59. package/dist/llm/index.js +1 -1
  60. package/dist/llm/model/model.d.ts.map +1 -1
  61. package/dist/llm/model/model.loop.d.ts.map +1 -1
  62. package/dist/llm/model/provider-registry.d.ts.map +1 -1
  63. package/dist/loop/index.cjs +2 -2
  64. package/dist/loop/index.js +1 -1
  65. package/dist/loop/loop.d.ts +1 -1
  66. package/dist/loop/loop.d.ts.map +1 -1
  67. package/dist/loop/test-utils/options.d.ts.map +1 -1
  68. package/dist/loop/types.d.ts +1 -2
  69. package/dist/loop/types.d.ts.map +1 -1
  70. package/dist/loop/workflows/stream.d.ts +1 -1
  71. package/dist/loop/workflows/stream.d.ts.map +1 -1
  72. package/dist/mastra/index.cjs +2 -2
  73. package/dist/mastra/index.js +1 -1
  74. package/dist/memory/index.cjs +4 -4
  75. package/dist/memory/index.js +1 -1
  76. package/dist/processors/index.cjs +11 -11
  77. package/dist/processors/index.js +1 -1
  78. package/dist/relevance/index.cjs +4 -4
  79. package/dist/relevance/index.js +1 -1
  80. package/dist/scores/index.cjs +9 -9
  81. package/dist/scores/index.js +2 -2
  82. package/dist/scores/scoreTraces/index.cjs +8 -8
  83. package/dist/scores/scoreTraces/index.js +3 -3
  84. package/dist/storage/index.cjs +3 -3
  85. package/dist/storage/index.js +1 -1
  86. package/dist/stream/index.cjs +11 -11
  87. package/dist/stream/index.js +2 -2
  88. package/dist/test-utils/llm-mock.cjs +2 -2
  89. package/dist/test-utils/llm-mock.js +1 -1
  90. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  91. package/dist/utils.cjs +17 -17
  92. package/dist/utils.js +1 -1
  93. package/dist/workflows/evented/index.cjs +10 -10
  94. package/dist/workflows/evented/index.js +1 -1
  95. package/dist/workflows/execution-engine.d.ts +1 -0
  96. package/dist/workflows/execution-engine.d.ts.map +1 -1
  97. package/dist/workflows/index.cjs +13 -13
  98. package/dist/workflows/index.js +1 -1
  99. package/dist/workflows/legacy/index.cjs +22 -22
  100. package/dist/workflows/legacy/index.js +1 -1
  101. package/dist/workflows/workflow.d.ts +3 -1
  102. package/dist/workflows/workflow.d.ts.map +1 -1
  103. package/package.json +4 -4
  104. package/dist/ai-tracing/chunk-tracing.d.ts +0 -76
  105. package/dist/ai-tracing/chunk-tracing.d.ts.map +0 -1
  106. package/dist/chunk-34WQUECJ.cjs.map +0 -1
  107. package/dist/chunk-4XE7GVZM.cjs.map +0 -1
  108. package/dist/chunk-4YHU6R7W.cjs.map +0 -1
  109. package/dist/chunk-7KYNQSR4.js.map +0 -1
  110. package/dist/chunk-A55YFHFT.js.map +0 -1
  111. package/dist/chunk-JZ7I64PK.js.map +0 -1
  112. package/dist/chunk-ONKGWHY6.js.map +0 -1
  113. package/dist/chunk-PDST7KX7.cjs.map +0 -1
@@ -1,12 +1,12 @@
1
1
  import { DefaultVoice } from './chunk-WCHE6FJ7.js';
2
2
  import { STREAM_FORMAT_SYMBOL, EMITTER_SYMBOL } from './chunk-NLNKQD2T.js';
3
3
  import { InstrumentClass, Telemetry } from './chunk-BLUDYAPI.js';
4
- import { MessageList, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-ZWF7AVLU.js';
5
- import { resolveModelConfig } from './chunk-JZ7I64PK.js';
6
- import { MastraLLMV1 } from './chunk-A55YFHFT.js';
4
+ import { MessageList, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-E3PG7G6E.js';
5
+ import { resolveModelConfig } from './chunk-ICGCDCJE.js';
6
+ import { MastraLLMV1 } from './chunk-NR77P3TK.js';
7
7
  import { executeHook } from './chunk-TTELJD4F.js';
8
8
  import { zodToJsonSchema } from './chunk-PJKCPRYF.js';
9
- import { wrapMastra, selectFields, getOrCreateSpan, getValidTraceId, ensureToolProperties, makeCoreTool, createMastraProxy, ModelSpanTracker, delay } from './chunk-ONKGWHY6.js';
9
+ import { wrapMastra, selectFields, getOrCreateSpan, getValidTraceId, ensureToolProperties, makeCoreTool, createMastraProxy, ModelSpanTracker, delay } from './chunk-DTTOVV72.js';
10
10
  import { RuntimeContext } from './chunk-HLRWYUFN.js';
11
11
  import { MastraError, safeParseErrorObject, getErrorFromUnknown } from './chunk-PZUZNPFM.js';
12
12
  import { ToolStream } from './chunk-HGNRQ3OG.js';
@@ -264,13 +264,13 @@ scorers:disableScorers===false?void 0:step.scorers,validateInputs:this.options?.
264
264
  suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId: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: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();},[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId: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
265
265
  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
266
266
  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,prevStep,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
267
- function mapVariable(config){return config;}function createStep(params){if(params instanceof Agent){return {id:params.name,description:params.getDescription(),// @ts-ignore
267
+ function mapVariable(config){return config;}function createStep(params,agentOptions){if(params instanceof Agent){return {id:params.name,description:params.getDescription(),// @ts-ignore
268
268
  inputSchema:z.object({prompt:z.string()// resourceId: z.string().optional(),
269
269
  // threadId: z.string().optional(),
270
270
  }),// @ts-ignore
271
- outputSchema:z.object({text:z.string()}),execute:async({inputData,[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:streamFormat,runtimeContext,tracingContext,abortSignal,abort,writer})=>{let streamPromise={};streamPromise.promise=new Promise((resolve,reject)=>{streamPromise.resolve=resolve;streamPromise.reject=reject;});const toolData={name:params.name,args:inputData};let stream;if((await params.getModel()).specificationVersion==="v1"){const{fullStream}=await params.streamLegacy(inputData.prompt,{// resourceId: inputData.resourceId,
271
+ outputSchema:z.object({text:z.string()}),execute:async({inputData,[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:streamFormat,runtimeContext,tracingContext,abortSignal,abort,writer})=>{let streamPromise={};streamPromise.promise=new Promise((resolve,reject)=>{streamPromise.resolve=resolve;streamPromise.reject=reject;});const toolData={name:params.name,args:inputData};let stream;if((await params.getModel()).specificationVersion==="v1"){const{fullStream}=await params.streamLegacy(inputData.prompt,{...(agentOptions??{}),// resourceId: inputData.resourceId,
272
272
  // threadId: inputData.threadId,
273
- runtimeContext,tracingContext,onFinish:result=>{streamPromise.resolve(result.text);},abortSignal});stream=fullStream;}else {const modelOutput=await params.stream(inputData.prompt,{runtimeContext,tracingContext,onFinish:result=>{streamPromise.resolve(result.text);},abortSignal});stream=modelOutput.fullStream;}if(streamFormat==="legacy"){await emitter.emit("watch-v2",{type:"tool-call-streaming-start",...(toolData??{})});for await(const chunk of stream){if(chunk.type==="text-delta"){await emitter.emit("watch-v2",{type:"tool-call-delta",...(toolData??{}),argsTextDelta:chunk.textDelta});}}await emitter.emit("watch-v2",{type:"tool-call-streaming-finish",...(toolData??{})});}else {for await(const chunk of stream){await writer.write(chunk);}}if(abortSignal.aborted){return abort();}return {text:await streamPromise.promise};},component:params.component};}if(params instanceof Tool){if(!params.inputSchema||!params.outputSchema){throw new Error("Tool must have input and output schemas defined");}return {// TODO: tool probably should have strong id type
273
+ runtimeContext,tracingContext,onFinish:result=>{streamPromise.resolve(result.text);void agentOptions?.onFinish?.(result);},abortSignal});stream=fullStream;}else {const modelOutput=await params.stream(inputData.prompt,{...(agentOptions??{}),runtimeContext,tracingContext,onFinish:result=>{streamPromise.resolve(result.text);void agentOptions?.onFinish?.(result);},abortSignal});stream=modelOutput.fullStream;}if(streamFormat==="legacy"){await emitter.emit("watch-v2",{type:"tool-call-streaming-start",...(toolData??{})});for await(const chunk of stream){if(chunk.type==="text-delta"){await emitter.emit("watch-v2",{type:"tool-call-delta",...(toolData??{}),argsTextDelta:chunk.textDelta});}}await emitter.emit("watch-v2",{type:"tool-call-streaming-finish",...(toolData??{})});}else {for await(const chunk of stream){await writer.write(chunk);}}if(abortSignal.aborted){return abort();}return {text:await streamPromise.promise};},component:params.component};}if(params instanceof Tool){if(!params.inputSchema||!params.outputSchema){throw new Error("Tool must have input and output schemas defined");}return {// TODO: tool probably should have strong id type
274
274
  // @ts-ignore
275
275
  id:params.id,description:params.description,inputSchema:params.inputSchema,outputSchema:params.outputSchema,execute:async({inputData,mastra,runtimeContext,tracingContext,suspend,resumeData})=>{return params.execute({context:inputData,mastra,runtimeContext,tracingContext,suspend,resumeData});},component:"TOOL"};}return {id:params.id,description:params.description,inputSchema:params.inputSchema,stateSchema:params.stateSchema,outputSchema:params.outputSchema,resumeSchema:params.resumeSchema,suspendSchema:params.suspendSchema,scorers:params.scorers,retries:params.retries,execute:params.execute.bind(params)};}function cloneStep(step,opts){return {id:opts.id,description:step.description,inputSchema:step.inputSchema,outputSchema:step.outputSchema,execute:step.execute,retries:step.retries,component:step.component};}function createWorkflow(params){return new Workflow(params);}function cloneWorkflow(workflow,opts){const wf=new Workflow({id:opts.id,inputSchema:workflow.inputSchema,outputSchema:workflow.outputSchema,steps:workflow.stepDefs,mastra:workflow.mastra});wf.setStepFlow(workflow.stepGraph);wf.commit();return wf;}var Workflow=class extends MastraBase{id;description;inputSchema;outputSchema;stateSchema;steps;stepDefs;stepFlow;serializedStepFlow;executionEngine;executionGraph;#options;retryConfig;#mastra;#runs=/* @__PURE__ */new Map();constructor({mastra,id,inputSchema,outputSchema,stateSchema,description,executionEngine,retryConfig,steps,options={}}){super({name:id,component:RegisteredLogger.WORKFLOW});this.id=id;this.description=description;this.inputSchema=inputSchema;this.outputSchema=outputSchema;this.stateSchema=stateSchema;this.retryConfig=retryConfig??{attempts:0,delay:0};this.executionGraph=this.buildExecutionGraph();this.stepFlow=[];this.serializedStepFlow=[];this.#mastra=mastra;this.steps={};this.stepDefs=steps;this.#options={validateInputs:options.validateInputs??false,shouldPersistSnapshot:options.shouldPersistSnapshot??(()=>true),tracingPolicy:options.tracingPolicy};if(!executionEngine){this.executionEngine=new DefaultExecutionEngine({mastra:this.#mastra,options:this.#options});}else {this.executionEngine=executionEngine;}this.#runs=/* @__PURE__ */new Map();}get runs(){return this.#runs;}get mastra(){return this.#mastra;}get options(){return this.#options;}__registerMastra(mastra){this.#mastra=mastra;this.executionEngine.__registerMastra(mastra);}__registerPrimitives(p){if(p.telemetry){this.__setTelemetry(p.telemetry);}if(p.logger){this.__setLogger(p.logger);}}setStepFlow(stepFlow){this.stepFlow=stepFlow;}/**
276
276
  * Adds a step to the workflow
@@ -370,7 +370,7 @@ async execute({runId,inputData,resumeData,state,setState,suspend,resume,[EMITTER
370
370
  * @param input The input data for the workflow
371
371
  * @returns A promise that resolves to the workflow output
372
372
  */resumeStreamVNext({step,resumeData,runtimeContext,tracingContext,tracingOptions,forEachIndex}={}){this.closeStreamAction=async()=>{};const self=this;const stream=new ReadableStream$1({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 WritableStream$1({write(chunk){controller.enqueue(chunk);}}),isVNext:true,forEachIndex});self.executionResults=executionResultsPromise;const executionResults=await executionResultsPromise;self.closeStreamAction?.().catch(()=>{});if(self.#streamOutput){self.#streamOutput.updateResults(executionResults);}}});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);}const snapshotResumeLabel=params.label?snapshot?.resumeLabels?.[params.label]:void 0;const stepParam=snapshotResumeLabel?.stepId??params.step;let steps;if(stepParam){steps=(Array.isArray(stepParam)?stepParam:[stepParam]).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){if(snapshot.status!=="suspended"){throw new Error("This workflow run was not suspended");}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&&params.runCount>0&&params.runtimeContext){runtimeContextInput=params.runtimeContext.get("__mastraWorflowInputData");params.runtimeContext.delete("__mastraWorflowInputData");}const stepResults={...(snapshot?.context??{}),input:runtimeContextInput??snapshot?.context?.input};let runtimeContextToUse=params.runtimeContext??new RuntimeContext();Object.entries(snapshot?.runtimeContext??{}).forEach(([key,value])=>{if(!runtimeContextToUse.has(key)){runtimeContextToUse.set(key,value);}});const workflowAISpan=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=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
373
- 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}).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;});}/**
373
+ 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;});}/**
374
374
  * Returns the current state of the workflow run
375
375
  * @returns The current state of the workflow run
376
376
  */getState(){return this.state;}updateState(state){if(state.currentStep){this.state.currentStep=state.currentStep;}else if(state.workflowState?.status!=="running"){delete this.state.currentStep;}if(state.workflowState){this.state.workflowState=deepMergeWorkflowState(this.state.workflowState??{},state.workflowState??{});}}/**
@@ -418,7 +418,7 @@ async function processOutputStream({tools,messageId,messageList,outputStream,run
418
418
  chunk.type!=="response-metadata"&&runState.state.isStreaming){if(runState.state.textDeltas.length){const textStartPayload=chunk.payload;const providerMetadata=textStartPayload.providerMetadata??runState.state.providerOptions;messageList.add({id:messageId,role:"assistant",content:[providerMetadata?{type:"text",text:runState.state.textDeltas.join(""),providerOptions:providerMetadata}:{type:"text",text:runState.state.textDeltas.join("")}]},"response");}runState.setState({isStreaming:false,textDeltas:[]});}if(chunk.type!=="reasoning-start"&&chunk.type!=="reasoning-delta"&&chunk.type!=="reasoning-end"&&chunk.type!=="redacted-reasoning"&&chunk.type!=="reasoning-signature"&&chunk.type!=="response-metadata"&&runState.state.isReasoning){runState.setState({isReasoning:false,reasoningDeltas:[]});}switch(chunk.type){case "response-metadata":runState.setState({responseMetadata:{id:chunk.payload.id,timestamp:chunk.payload.timestamp,modelId:chunk.payload.modelId,headers:chunk.payload.headers}});break;case "text-delta":{const textDeltasFromState=runState.state.textDeltas;textDeltasFromState.push(chunk.payload.text);runState.setState({textDeltas:textDeltasFromState,isStreaming:true});if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "tool-call-input-streaming-start":{const tool=tools?.[chunk.payload.toolName]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===chunk.payload.toolName);if(tool&&"onInputStart"in tool){try{await tool?.onInputStart?.({toolCallId:chunk.payload.toolCallId,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error2){console.error("Error calling onInputStart",error2);}}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "tool-call-delta":{const tool=tools?.[chunk.payload.toolName||""]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===chunk.payload.toolName);if(tool&&"onInputDelta"in tool){try{await tool?.onInputDelta?.({inputTextDelta:chunk.payload.argsTextDelta,toolCallId:chunk.payload.toolCallId,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error2){console.error("Error calling onInputDelta",error2);}}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "reasoning-start":{runState.setState({isReasoning:true,reasoningDeltas:[],providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions});if(Object.values(chunk.payload.providerMetadata||{}).find(v=>v?.redactedData)){messageList.add({id:messageId,role:"assistant",content:[{type:"reasoning",text:"",providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions}]},"response");if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "reasoning-delta":{const reasoningDeltasFromState=runState.state.reasoningDeltas;reasoningDeltasFromState.push(chunk.payload.text);runState.setState({isReasoning:true,reasoningDeltas:reasoningDeltasFromState,providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions});if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "reasoning-end":{if(runState.state.reasoningDeltas.length>0){messageList.add({id:messageId,role:"assistant",content:[{type:"reasoning",text:runState.state.reasoningDeltas.join(""),providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions}]},"response");}runState.setState({isReasoning:false,reasoningDeltas:[]});if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "file":messageList.add({id:messageId,role:"assistant",content:[{type:"file",data:chunk.payload.data,mimeType:chunk.payload.mimeType}]},"response");controller.enqueue(chunk);break;case "source":messageList.add({id:messageId,role:"assistant",content:{format:2,parts:[{type:"source",source:{sourceType:"url",id:chunk.payload.id,url:chunk.payload.url||"",title:chunk.payload.title,providerMetadata:chunk.payload.providerMetadata}}]},createdAt:/* @__PURE__ */new Date()},"response");controller.enqueue(chunk);break;case "finish":runState.setState({providerOptions:chunk.payload.metadata.providerMetadata,stepResult:{reason:chunk.payload.reason,logprobs:chunk.payload.logprobs,warnings:responseFromModel.warnings,totalUsage:chunk.payload.totalUsage,headers:responseFromModel.rawResponse?.headers,messageId,isContinued:!["stop","error"].includes(chunk.payload.stepResult.reason),request:responseFromModel.request}});break;case "error":if(isAbortError(chunk.payload.error)&&options?.abortSignal?.aborted){break;}runState.setState({hasErrored:true});runState.setState({stepResult:{isContinued:false,reason:"error"}});const error=getErrorFromUnknown(chunk.payload.error,{fallbackMessage:"Unknown error in agent stream"});controller.enqueue({...chunk,payload:{...chunk.payload,error}});await options?.onError?.({error});break;default:if(isControllerOpen(controller)){controller.enqueue(chunk);}}if(["text-delta","reasoning-delta","source","tool-call","tool-call-input-streaming-start","tool-call-delta","raw"].includes(chunk.type)){const transformedChunk=convertMastraChunkToAISDKv5({chunk});if(chunk.type==="raw"&&!includeRawChunks){return;}await options?.onChunk?.({chunk:transformedChunk});}if(runState.state.hasErrored){break;}}}function executeStreamWithFallbackModels(models){return async callback=>{let index=0;let finalResult;let done=false;for(const modelConfig of models){index++;const maxRetries=modelConfig.maxRetries||0;let attempt=0;if(done){break;}while(attempt<=maxRetries){try{const isLastModel=attempt===maxRetries&&index===models.length;const result=await callback(modelConfig.model,isLastModel);finalResult=result;done=true;break;}catch(err){attempt++;console.error(`Error executing model ${modelConfig.model.modelId}, attempt ${attempt}====`,err);if(attempt>maxRetries){break;}}}}if(typeof finalResult==="undefined"){console.error("Exhausted all fallback models and reached the maximum number of retries.");throw new Error("Exhausted all fallback models and reached the maximum number of retries.");}return finalResult;};}function createLLMExecutionStep({models,_internal,messageId,runId,modelStreamSpan,telemetry_settings,tools,toolChoice,messageList,includeRawChunks,modelSettings,providerOptions,options,toolCallStreaming,controller,structuredOutput,outputProcessors,headers,downloadRetries,downloadConcurrency,processorStates}){return createStep({id:"llm-execution",inputSchema:llmIterationOutputSchema,outputSchema:llmIterationOutputSchema,execute:async({inputData,bail,tracingContext})=>{let modelResult;let warnings;let request;let rawResponse;const{outputStream,callBail,runState}=await executeStreamWithFallbackModels(models)(async(model,isLastModel)=>{const runState2=new AgenticRunState({_internal,model});switch(model.specificationVersion){case "v2":{const messageListPromptArgs={downloadRetries,downloadConcurrency,supportedUrls:model?.supportedUrls};let inputMessages=await messageList.get.all.aiV5.llmPrompt(messageListPromptArgs);let stepModel=model;let stepToolChoice=toolChoice;let stepTools=tools;if(options?.prepareStep){try{const prepareStepResult=await options.prepareStep({stepNumber:inputData.output?.steps?.length||0,steps:inputData.output?.steps||[],model,messages:messageList.get.all.aiV5.model()});if(prepareStepResult){if(prepareStepResult.model){stepModel=prepareStepResult.model;}if(prepareStepResult.toolChoice){stepToolChoice=prepareStepResult.toolChoice;}if(prepareStepResult.activeTools&&stepTools){const activeToolsSet=new Set(prepareStepResult.activeTools);stepTools=Object.fromEntries(Object.entries(stepTools).filter(([toolName])=>activeToolsSet.has(toolName)));}if(prepareStepResult.messages){const newMessages=prepareStepResult.messages;const newMessageList=new MessageList();for(const message of newMessages){if(message.role==="system"){newMessageList.addSystem(message);}else if(message.role==="user"){newMessageList.add(message,"input");}else if(message.role==="assistant"||message.role==="tool"){newMessageList.add(message,"response");}}inputMessages=await newMessageList.get.all.aiV5.llmPrompt(messageListPromptArgs);}}}catch(error){console.error("Error in prepareStep callback:",error);}}modelResult=execute({runId,model:stepModel,providerOptions,inputMessages,tools:stepTools,toolChoice:stepToolChoice,options,modelSettings,telemetry_settings,includeRawChunks,structuredOutput,headers,onResult:({warnings:warningsFromStream,request:requestFromStream,rawResponse:rawResponseFromStream})=>{warnings=warningsFromStream;request=requestFromStream||{};rawResponse=rawResponseFromStream;if(!isControllerOpen(controller)){return;}controller.enqueue({runId,from:"AGENT"/* AGENT */,type:"step-start",payload:{request:request||{},warnings:warnings||[],messageId}});},modelStreamSpan,shouldThrowError:!isLastModel});break;}default:{throw new Error(`Unsupported model version: ${model.specificationVersion}`);}}const outputStream2=new MastraModelOutput({model:{modelId:model.modelId,provider:model.provider,version:model.specificationVersion},stream:modelResult,messageList,messageId,options:{runId,rootSpan:modelStreamSpan,toolCallStreaming,telemetry_settings,includeRawChunks,structuredOutput,outputProcessors,isLLMExecutionStep:true,tracingContext,processorStates}});try{await processOutputStream({outputStream:outputStream2,includeRawChunks,tools,messageId,messageList,runState:runState2,options,controller,responseFromModel:{warnings,request,rawResponse}});}catch(error){console.error("Error in LLM Execution Step",error);if(isAbortError(error)&&options?.abortSignal?.aborted){await options?.onAbort?.({steps:inputData?.output?.steps??[]});if(isControllerOpen(controller)){controller.enqueue({type:"abort",runId,from:"AGENT"/* AGENT */,payload:{}});}return {callBail:true,outputStream:outputStream2,runState:runState2};}if(isLastModel){if(isControllerOpen(controller)){controller.enqueue({type:"error",runId,from:"AGENT"/* AGENT */,payload:{error}});}runState2.setState({hasErrored:true,stepResult:{isContinued:false,reason:"error"}});}else {throw error;}}return {outputStream:outputStream2,callBail:false,runState:runState2};});if(callBail){const usage2=outputStream._getImmediateUsage();const responseMetadata2=runState.state.responseMetadata;const text2=outputStream._getImmediateText();return bail({messageId,stepResult:{reason:"abort",warnings,isContinued:false},metadata:{providerMetadata:runState.state.providerOptions,...responseMetadata2,modelMetadata:runState.state.modelMetadata,headers:rawResponse?.headers,request},output:{text:text2,toolCalls:[],usage:usage2??inputData.output?.usage,steps:[]},messages:{all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:messageList.get.response.aiV5.model()}});}if(outputStream.tripwire){runState.setState({stepResult:{isContinued:false,reason:"abort"}});}const toolCalls=outputStream._getImmediateToolCalls()?.map(chunk=>{return chunk.payload;});if(toolCalls.length>0){const assistantContent=[...toolCalls.map(toolCall=>{return {type:"tool-call",toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,args:toolCall.args};})];messageList.add({id:messageId,role:"assistant",content:assistantContent},"response");}const finishReason=runState?.state?.stepResult?.reason??outputStream._getImmediateFinishReason();const hasErrored=runState.state.hasErrored;const usage=outputStream._getImmediateUsage();const responseMetadata=runState.state.responseMetadata;const text=outputStream._getImmediateText();const object=outputStream._getImmediateObject();const tripwireTriggered=outputStream.tripwire;const steps=inputData.output?.steps||[];const existingResponseCount=inputData.messages?.nonUser?.length||0;const allResponseContent=messageList.get.response.aiV5.modelContent(steps.length);const currentIterationContent=allResponseContent.slice(existingResponseCount);steps.push(new DefaultStepResult({warnings:outputStream._getImmediateWarnings(),providerMetadata:runState.state.providerOptions,finishReason:runState.state.stepResult?.reason,content:currentIterationContent,response:{...responseMetadata,...rawResponse,messages:messageList.get.response.aiV5.model()},request,usage:outputStream._getImmediateUsage()}));const messages={all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:messageList.get.response.aiV5.model()};return {messageId,stepResult:{reason:tripwireTriggered?"abort":hasErrored?"error":finishReason,warnings,isContinued:tripwireTriggered?false:!["stop","error"].includes(finishReason)},metadata:{providerMetadata:runState.state.providerOptions,...responseMetadata,...rawResponse,modelMetadata:runState.state.modelMetadata,headers:rawResponse?.headers,request},output:{text,toolCalls,usage:usage??inputData.output?.usage,steps,...(object?{object}:{})},messages};}});}// src/loop/workflows/agentic-execution/llm-mapping-step.ts
419
419
  function createLLMMappingStep({models,telemetry_settings,_internal,modelStreamSpan,...rest},llmExecutionStep){return createStep({id:"llmExecutionMappingStep",inputSchema:z9.array(toolCallOutputSchema),outputSchema:llmIterationOutputSchema,execute:async({inputData,getStepResult:getStepResult3,bail})=>{const initialResult=getStepResult3(llmExecutionStep);if(inputData?.every(toolCall=>toolCall?.result===void 0)){const errorResults=inputData.filter(toolCall=>toolCall?.error);const toolResultMessageId=rest.experimental_generateMessageId?.()||_internal?.generateId?.();if(errorResults?.length){errorResults.forEach(toolCall=>{const chunk={type:"tool-error",runId:rest.runId,from:"AGENT"/* AGENT */,payload:{error:toolCall.error,args:toolCall.args,toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,providerMetadata:toolCall.providerMetadata}};rest.controller.enqueue(chunk);});rest.messageList.add({id:toolResultMessageId,role:"tool",content:errorResults.map(toolCall=>{return {type:"tool-result",args:toolCall.args,toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,result:{tool_execution_error:toolCall.error?.message??toolCall.error}};})},"response");}initialResult.stepResult.isContinued=false;return bail(initialResult);}if(inputData?.length){for(const toolCall of inputData){const chunk={type:"tool-result",runId:rest.runId,from:"AGENT"/* AGENT */,payload:{args:toolCall.args,toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,result:toolCall.result,providerMetadata:toolCall.providerMetadata,providerExecuted:toolCall.providerExecuted}};rest.controller.enqueue(chunk);if(initialResult?.metadata?.modelVersion==="v2"){await rest.options?.onChunk?.({chunk:convertMastraChunkToAISDKv5({chunk})});}const toolResultMessageId=rest.experimental_generateMessageId?.()||_internal?.generateId?.();rest.messageList.add({id:toolResultMessageId,role:"tool",content:inputData.map(toolCall2=>{return {type:"tool-result",args:toolCall2.args,toolCallId:toolCall2.toolCallId,toolName:toolCall2.toolName,result:toolCall2.result};})},"response");}return {...initialResult,messages:{all:rest.messageList.get.all.aiV5.model(),user:rest.messageList.get.input.aiV5.model(),nonUser:rest.messageList.get.response.aiV5.model()}};}}});}// src/loop/workflows/agentic-execution/tool-call-step.ts
420
420
  function createToolCallStep({tools,messageList,options,telemetry_settings,writer,controller,runId,streamState,modelSpanTracker}){return createStep({id:"toolCallStep",inputSchema:toolCallInputSchema,outputSchema:toolCallOutputSchema,execute:async({inputData,suspend,resumeData,runtimeContext})=>{if(inputData.providerExecuted){const tracer2=getTracer({isEnabled:telemetry_settings?.isEnabled,tracer:telemetry_settings?.tracer});const span2=tracer2.startSpan("mastra.stream.toolCall").setAttributes({...assembleOperationName({operationId:"mastra.stream.toolCall",telemetry:telemetry_settings}),"stream.toolCall.toolName":inputData.toolName,"stream.toolCall.toolCallId":inputData.toolCallId,"stream.toolCall.args":JSON.stringify(inputData.args),"stream.toolCall.providerExecuted":true});if(inputData.output){span2.setAttributes({"stream.toolCall.result":JSON.stringify(inputData.output)});}span2.end();return {...inputData,result:inputData.output};}const tool=tools?.[inputData.toolName]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===inputData.toolName);if(!tool){throw new Error(`Tool ${inputData.toolName} not found`);}if(tool&&"onInputAvailable"in tool){try{await tool?.onInputAvailable?.({toolCallId:inputData.toolCallId,input:inputData.args,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error){console.error("Error calling onInputAvailable",error);}}if(!tool.execute){return inputData;}const tracer=getTracer({isEnabled:telemetry_settings?.isEnabled,tracer:telemetry_settings?.tracer});const span=tracer.startSpan("mastra.stream.toolCall").setAttributes({...assembleOperationName({operationId:"mastra.stream.toolCall",telemetry:telemetry_settings}),"stream.toolCall.toolName":inputData.toolName,"stream.toolCall.toolCallId":inputData.toolCallId,"stream.toolCall.args":JSON.stringify(inputData.args)});try{const requireToolApproval=runtimeContext.get("__mastra_requireToolApproval");if(requireToolApproval||tool.requireApproval){if(!resumeData){controller.enqueue({type:"tool-call-approval",runId,from:"AGENT"/* AGENT */,payload:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,args:inputData.args}});return suspend({requireToolApproval:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,args:inputData.args},__streamState:streamState.serialize()},{resumeLabel:inputData.toolCallId});}else {if(!resumeData.approved){span.end();span.setAttributes({"stream.toolCall.result":"Tool call was not approved by the user"});return {result:"Tool call was not approved by the user",...inputData};}}}const toolOptions={abortSignal:options?.abortSignal,toolCallId:inputData.toolCallId,messages:messageList.get.input.aiV5.model(),writableStream:writer,// Pass current step span as parent for tool call spans
421
- tracingContext:{currentSpan:modelSpanTracker?.getCurrentStepSpan()},suspend:async suspendPayload=>{controller.enqueue({type:"tool-call-suspended",runId,from:"AGENT"/* AGENT */,payload:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,suspendPayload}});return await suspend({toolCallSuspended:suspendPayload,__streamState:streamState.serialize()},{resumeLabel:inputData.toolCallId});},resumeData};const result=await tool.execute(inputData.args,toolOptions);span.setAttributes({"stream.toolCall.result":JSON.stringify(result)});span.end();return {result,...inputData};}catch(error){span.setStatus({code:2,message:error?.message??error});span.recordException(error);return {error,...inputData};}}});}// src/loop/workflows/agentic-execution/index.ts
421
+ tracingContext:modelSpanTracker?.getTracingContext(),suspend:async suspendPayload=>{controller.enqueue({type:"tool-call-suspended",runId,from:"AGENT"/* AGENT */,payload:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,suspendPayload}});return await suspend({toolCallSuspended:suspendPayload,__streamState:streamState.serialize()},{resumeLabel:inputData.toolCallId});},resumeData};const result=await tool.execute(inputData.args,toolOptions);span.setAttributes({"stream.toolCall.result":JSON.stringify(result)});span.end();return {result,...inputData};}catch(error){span.setStatus({code:2,message:error?.message??error});span.recordException(error);return {error,...inputData};}}});}// src/loop/workflows/agentic-execution/index.ts
422
422
  function createAgenticExecutionWorkflow({models,telemetry_settings,_internal,modelStreamSpan,...rest}){const llmExecutionStep=createLLMExecutionStep({models,_internal,modelStreamSpan,telemetry_settings,...rest});const toolCallStep=createToolCallStep({telemetry_settings,...rest});const llmMappingStep=createLLMMappingStep({models,telemetry_settings,_internal,modelStreamSpan,...rest},llmExecutionStep);return createWorkflow({id:"executionWorkflow",inputSchema:llmIterationOutputSchema,outputSchema:llmIterationOutputSchema,options:{tracingPolicy:{// mark all workflow spans related to the
423
423
  // VNext execution as internal
424
424
  internal:1/* WORKFLOW */},shouldPersistSnapshot:({workflowStatus})=>workflowStatus==="suspended"}}).then(llmExecutionStep).map(async({inputData})=>{const typedInputData=inputData;if(modelStreamSpan&&telemetry_settings?.recordOutputs!==false&&typedInputData.output.toolCalls?.length){modelStreamSpan.setAttribute("stream.response.toolCalls",JSON.stringify(typedInputData.output.toolCalls?.map(toolCall=>{return {toolCallId:toolCall.toolCallId,// @ts-ignore TODO: look into the type here
@@ -428,10 +428,10 @@ function createAgenticLoopWorkflow(params){const{models,_internal,messageId,runI
428
428
  internal:1/* WORKFLOW */},shouldPersistSnapshot:params2=>{return params2.workflowStatus==="suspended";}}}).dowhile(agenticExecutionWorkflow,async({inputData})=>{const typedInputData=inputData;let hasFinishedSteps=false;const allContent=typedInputData.messages.nonUser.flatMap(message=>message.content);const currentContent=allContent.slice(previousContentLength);previousContentLength=allContent.length;const currentStep={content:currentContent,usage:typedInputData.output.usage||{inputTokens:0,outputTokens:0,totalTokens:0},// we need to cast this because we add 'abort' for tripwires
429
429
  finishReason:typedInputData.stepResult?.reason||"unknown",warnings:typedInputData.stepResult?.warnings||[],request:typedInputData.metadata?.request||{},response:{...typedInputData.metadata,modelId:typedInputData.metadata?.modelId||typedInputData.metadata?.model||"",messages:[]},text:typedInputData.output.text||"",reasoning:typedInputData.output.reasoning||[],reasoningText:typedInputData.output.reasoningText||"",files:typedInputData.output.files||[],toolCalls:typedInputData.output.toolCalls||[],toolResults:typedInputData.output.toolResults||[],sources:typedInputData.output.sources||[],staticToolCalls:typedInputData.output.staticToolCalls||[],dynamicToolCalls:typedInputData.output.dynamicToolCalls||[],staticToolResults:typedInputData.output.staticToolResults||[],dynamicToolResults:typedInputData.output.dynamicToolResults||[],providerMetadata:typedInputData.metadata?.providerMetadata};accumulatedSteps.push(currentStep);if(rest.stopWhen&&typedInputData.stepResult?.isContinued&&accumulatedSteps.length>0){const conditions=await Promise.all((Array.isArray(rest.stopWhen)?rest.stopWhen:[rest.stopWhen]).map(condition=>{return condition({steps:accumulatedSteps});}));const hasStopped=conditions.some(condition=>condition);hasFinishedSteps=hasStopped;}if(typedInputData.stepResult){typedInputData.stepResult.isContinued=hasFinishedSteps?false:typedInputData.stepResult.isContinued;}if(typedInputData.stepResult?.reason!=="abort"){if(isControllerOpen(controller)){controller.enqueue({type:"step-finish",runId,from:"AGENT"/* AGENT */,// @ts-ignore TODO: Look into the proper types for this
430
430
  payload:typedInputData});}}modelStreamSpan.setAttributes({"stream.response.id":typedInputData.metadata?.id,"stream.response.model":typedInputData.metadata?.modelId,...(typedInputData.metadata?.providerMetadata?{"stream.response.providerMetadata":JSON.stringify(typedInputData.metadata.providerMetadata)}:{}),"stream.response.finishReason":typedInputData.stepResult?.reason,"stream.usage.inputTokens":typedInputData.output.usage?.inputTokens,"stream.usage.outputTokens":typedInputData.output.usage?.outputTokens,"stream.usage.totalTokens":typedInputData.output.usage?.totalTokens,...(telemetry_settings?.recordOutputs!==false?{"stream.response.text":typedInputData.output.text,"stream.prompt.messages":JSON.stringify(messageList.get.input.aiV5.model())}:{})});modelStreamSpan.end();const reason=typedInputData.stepResult?.reason;if(reason===void 0){return false;}return typedInputData.stepResult?.isContinued??false;}).commit();}// src/loop/workflows/stream.ts
431
- function isControllerOpen(controller){return controller.desiredSize!==0&&controller.desiredSize!==null;}function workflowLoopStream({resumeContext,requireToolApproval,telemetry_settings,models,toolChoice,modelSettings,_internal,modelStreamSpan,llmAISpan,messageId,runId,messageList,startTimestamp,streamState,agentId,toolCallId,...rest}){return new ReadableStream$1({start:async controller=>{const writer=new WritableStream({write:chunk=>{controller.enqueue(chunk);}});modelStreamSpan.setAttributes({...(telemetry_settings?.recordInputs!==false?{"stream.prompt.toolChoice":toolChoice?JSON.stringify(toolChoice):"auto"}:{})});const agenticLoopWorkflow=createAgenticLoopWorkflow({resumeContext,messageId,models,telemetry_settings,_internal,modelSettings,toolChoice,modelStreamSpan,controller,writer,runId,messageList,startTimestamp,streamState,agentId,...rest});if(rest.mastra){agenticLoopWorkflow.__registerMastra(rest.mastra);}const initialData={messageId,messages:{all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:[]},output:{steps:[],usage:{inputTokens:0,outputTokens:0,totalTokens:0}},metadata:{},stepResult:{reason:"undefined",warnings:[],isContinued:true,totalUsage:{inputTokens:0,outputTokens:0,totalTokens:0}}};const msToFirstChunk=_internal?.now?.()-startTimestamp;modelStreamSpan.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":msToFirstChunk});modelStreamSpan.setAttributes({"stream.response.timestamp":new Date(startTimestamp).toISOString(),"stream.response.msToFirstChunk":msToFirstChunk});if(!resumeContext){controller.enqueue({type:"start",runId,from:"AGENT"/* AGENT */,payload:{id:agentId}});}const run=await agenticLoopWorkflow.createRunAsync({runId});const runtimeContext=new RuntimeContext();if(requireToolApproval){runtimeContext.set("__mastra_requireToolApproval",true);}const executionResult=resumeContext?await run.resume({resumeData:resumeContext.resumeData,tracingContext:{currentSpan:llmAISpan},label:toolCallId}):await run.start({inputData:initialData,tracingContext:{currentSpan:llmAISpan},runtimeContext});if(executionResult.status!=="success"){controller.close();return;}if(executionResult.result.stepResult?.reason==="abort"){controller.close();return;}controller.enqueue({type:"finish",runId,from:"AGENT"/* AGENT */,payload:{...executionResult.result,stepResult:{...executionResult.result.stepResult,// @ts-ignore we add 'abort' for tripwires so the type is not compatible
431
+ function isControllerOpen(controller){return controller.desiredSize!==0&&controller.desiredSize!==null;}function workflowLoopStream({resumeContext,requireToolApproval,telemetry_settings,models,toolChoice,modelSettings,_internal,modelStreamSpan,messageId,runId,messageList,startTimestamp,streamState,agentId,toolCallId,...rest}){return new ReadableStream$1({start:async controller=>{const writer=new WritableStream({write:chunk=>{controller.enqueue(chunk);}});modelStreamSpan.setAttributes({...(telemetry_settings?.recordInputs!==false?{"stream.prompt.toolChoice":toolChoice?JSON.stringify(toolChoice):"auto"}:{})});const agenticLoopWorkflow=createAgenticLoopWorkflow({resumeContext,messageId,models,telemetry_settings,_internal,modelSettings,toolChoice,modelStreamSpan,controller,writer,runId,messageList,startTimestamp,streamState,agentId,...rest});if(rest.mastra){agenticLoopWorkflow.__registerMastra(rest.mastra);}const initialData={messageId,messages:{all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:[]},output:{steps:[],usage:{inputTokens:0,outputTokens:0,totalTokens:0}},metadata:{},stepResult:{reason:"undefined",warnings:[],isContinued:true,totalUsage:{inputTokens:0,outputTokens:0,totalTokens:0}}};const msToFirstChunk=_internal?.now?.()-startTimestamp;modelStreamSpan.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":msToFirstChunk});modelStreamSpan.setAttributes({"stream.response.timestamp":new Date(startTimestamp).toISOString(),"stream.response.msToFirstChunk":msToFirstChunk});if(!resumeContext){controller.enqueue({type:"start",runId,from:"AGENT"/* AGENT */,payload:{id:agentId}});}const run=await agenticLoopWorkflow.createRunAsync({runId});const runtimeContext=new RuntimeContext();if(requireToolApproval){runtimeContext.set("__mastra_requireToolApproval",true);}const executionResult=resumeContext?await run.resume({resumeData:resumeContext.resumeData,tracingContext:rest.modelSpanTracker?.getTracingContext(),label:toolCallId}):await run.start({inputData:initialData,tracingContext:rest.modelSpanTracker?.getTracingContext(),runtimeContext});if(executionResult.status!=="success"){controller.close();return;}if(executionResult.result.stepResult?.reason==="abort"){controller.close();return;}controller.enqueue({type:"finish",runId,from:"AGENT"/* AGENT */,payload:{...executionResult.result,stepResult:{...executionResult.result.stepResult,// @ts-ignore we add 'abort' for tripwires so the type is not compatible
432
432
  reason:executionResult.result.stepResult.reason}}});const msToFinish=(_internal?.now?.()??Date.now())-startTimestamp;modelStreamSpan.addEvent("ai.stream.finish");modelStreamSpan.setAttributes({"stream.response.msToFinish":msToFinish,"stream.response.avgOutputTokensPerSecond":1e3*(executionResult?.result?.output?.usage?.outputTokens??0)/msToFinish});controller.close();}});}// src/loop/loop.ts
433
- function loop({resumeContext,models,logger,runId,idGenerator,telemetry_settings,messageList,includeRawChunks,modelSettings,tools,_internal,mode="stream",outputProcessors,returnScorerData,llmAISpan,requireToolApproval,agentId,...rest}){let loggerToUse=logger||new ConsoleLogger({level:"debug"});if(models.length===0||!models[0]){const mastraError=new MastraError({id:"LOOP_MODELS_EMPTY",domain:"LLM"/* LLM */,category:"USER"/* USER */});loggerToUse.trackException(mastraError);loggerToUse.error(mastraError.toString());throw mastraError;}const firstModel=models[0];let runIdToUse=runId;if(!runIdToUse){runIdToUse=idGenerator?.()||crypto.randomUUID();}const internalToUse={now:_internal?.now||(()=>Date.now()),generateId:_internal?.generateId||(()=>generateId()),currentDate:_internal?.currentDate||(()=>/* @__PURE__ */new Date())};let startTimestamp=internalToUse.now?.();const{rootSpan}=getRootSpan({operationId:mode==="stream"?`mastra.stream`:`mastra.generate`,model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider},modelSettings,headers:modelSettings?.headers??rest.headers,telemetry_settings});rootSpan.setAttributes({...(telemetry_settings?.recordOutputs!==false?{"stream.prompt.messages":JSON.stringify(messageList.get.input.aiV5.model())}:{})});const{rootSpan:modelStreamSpan}=getRootSpan({operationId:`mastra.${mode}.aisdk.doStream`,model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider},modelSettings,headers:modelSettings?.headers??rest.headers,telemetry_settings});const messageId=rest.experimental_generateMessageId?.()||internalToUse.generateId?.();let modelOutput;const serializeStreamState=()=>{return modelOutput?.serializeState();};const deserializeStreamState=state=>{modelOutput?.deserializeState(state);};const processorStates=outputProcessors&&outputProcessors.length>0?/* @__PURE__ */new Map():void 0;const workflowLoopProps={resumeContext,models,runId:runIdToUse,logger:loggerToUse,startTimestamp,messageList,includeRawChunks:!!includeRawChunks,_internal:internalToUse,tools,modelStreamSpan,telemetry_settings,modelSettings,outputProcessors,llmAISpan,messageId,agentId,requireToolApproval,streamState:{serialize:serializeStreamState,deserialize:deserializeStreamState},processorStates,...rest};const existingSnapshot=resumeContext?.snapshot;let initialStreamState;if(existingSnapshot){for(const key in existingSnapshot?.context){const step=existingSnapshot?.context[key];if(step&&step.status==="suspended"&&step.suspendPayload?.__streamState){initialStreamState=step.suspendPayload?.__streamState;break;}}}const baseStream=workflowLoopStream(workflowLoopProps);const stream=rest.modelSpanTracker?.wrapStream(baseStream)??baseStream;modelOutput=new MastraModelOutput({model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider,version:firstModel.model.specificationVersion},stream,messageList,messageId,options:{runId:runIdToUse,telemetry_settings,rootSpan,toolCallStreaming:rest.toolCallStreaming,onFinish:rest.options?.onFinish,onStepFinish:rest.options?.onStepFinish,includeRawChunks:!!includeRawChunks,structuredOutput:rest.structuredOutput,outputProcessors,returnScorerData,tracingContext:{currentSpan:llmAISpan}},initialState:initialStreamState});return createDestructurableOutput(modelOutput);}// src/llm/model/model.loop.ts
434
- var MastraLLMVNext=class extends MastraBase{#models;#mastra;#options;#firstModel;constructor({mastra,models,options}){super({name:"aisdk"});this.#options=options;if(mastra){this.#mastra=mastra;if(mastra.getLogger()){this.__setLogger(this.#mastra.getLogger());}}if(models.length===0||!models[0]){const mastraError=new MastraError({id:"LLM_LOOP_MODELS_EMPTY",domain:"LLM"/* LLM */,category:"USER"/* USER */});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}else {this.#models=models;this.#firstModel=models[0];}}__registerPrimitives(p){if(p.telemetry){this.__setTelemetry(p.telemetry);}if(p.logger){this.__setLogger(p.logger);}}__registerMastra(p){this.#mastra=p;}getProvider(){return this.#firstModel.model.provider;}getModelId(){return this.#firstModel.model.modelId;}getModel(){return this.#firstModel.model;}_applySchemaCompat(schema){const model=this.#firstModel.model;const schemaCompatLayers=[];if(model){const modelInfo={modelId:model.modelId,supportsStructuredOutputs:true,provider:model.provider};schemaCompatLayers.push(new OpenAIReasoningSchemaCompatLayer(modelInfo),new OpenAISchemaCompatLayer(modelInfo),new GoogleSchemaCompatLayer(modelInfo),new AnthropicSchemaCompatLayer(modelInfo),new DeepSeekSchemaCompatLayer(modelInfo),new MetaSchemaCompatLayer(modelInfo));}return applyCompatLayer({schema,compatLayers:schemaCompatLayers,mode:"aiSdkSchema"});}convertToMessages(messages){if(Array.isArray(messages)){return messages.map(m=>{if(typeof m==="string"){return {role:"user",content:m};}return m;});}return [{role:"user",content:messages}];}stream({resumeContext,runId,stopWhen=stepCountIs(5),maxSteps,tools={},modelSettings,toolChoice="auto",telemetry_settings,threadId,resourceId,structuredOutput,options,outputProcessors,returnScorerData,providerOptions,tracingContext,messageList,requireToolApproval,_internal,agentId,toolCallId}){let stopWhenToUse;if(maxSteps&&typeof maxSteps==="number"){stopWhenToUse=stepCountIs(maxSteps);}else {stopWhenToUse=stopWhen;}const messages=messageList.get.all.aiV5.model();const firstModel=this.#firstModel.model;this.logger.debug(`[LLM] - Streaming text`,{runId,threadId,resourceId,messages,tools:Object.keys(tools||{})});const llmAISpan=tracingContext?.currentSpan?.createChildSpan({name:`llm: '${firstModel.modelId}'`,type:"model_generation"/* MODEL_GENERATION */,input:{messages:[...messageList.getSystemMessages(),...messages]},attributes:{model:firstModel.modelId,provider:firstModel.provider,streaming:true,parameters:modelSettings},metadata:{runId,threadId,resourceId},tracingPolicy:this.#options?.tracingPolicy});const modelSpanTracker=new ModelSpanTracker(llmAISpan);try{const loopOptions={mastra:this.#mastra,resumeContext,runId,toolCallId,messageList,models:this.#models,tools,stopWhen:stopWhenToUse,toolChoice,modelSettings,providerOptions,telemetry_settings:{...this.experimental_telemetry,...telemetry_settings},_internal,structuredOutput,outputProcessors,returnScorerData,llmAISpan,modelSpanTracker,requireToolApproval,agentId,options:{...options,onStepFinish:async props=>{try{await options?.onStepFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_STEP_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);llmAISpan?.error({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}this.logger.debug("[LLM] - Stream Step Change:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId});if(props?.response?.headers?.["x-ratelimit-remaining-tokens"]&&parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"],10)<2e3){this.logger.warn("Rate limit approaching, waiting 10 seconds",{runId});await delay(10*1e3);}},onFinish:async props=>{try{await options?.onFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);llmAISpan?.error({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}llmAISpan?.end({output:{files:props?.files,object:props?.object,reasoning:props?.reasoning,reasoningText:props?.reasoningText,sources:props?.sources,text:props?.text,warnings:props?.warnings},attributes:{finishReason:props?.finishReason,usage:{inputTokens:props?.totalUsage?.inputTokens,outputTokens:props?.totalUsage?.outputTokens,totalTokens:props?.totalUsage?.totalTokens,reasoningTokens:props?.totalUsage?.reasoningTokens,cachedInputTokens:props?.totalUsage?.cachedInputTokens}}});this.logger.debug("[LLM] - Stream Finished:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId,threadId,resourceId});}}};return loop(loopOptions);}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_TEXT_AI_SDK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"THIRD_PARTY"/* THIRD_PARTY */,details:{modelId:firstModel.modelId,modelProvider:firstModel.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown"}},e);llmAISpan?.error({error:mastraError});throw mastraError;}}};// src/loop/network/index.ts
433
+ function loop({resumeContext,models,logger,runId,idGenerator,telemetry_settings,messageList,includeRawChunks,modelSettings,tools,_internal,mode="stream",outputProcessors,returnScorerData,requireToolApproval,agentId,...rest}){let loggerToUse=logger||new ConsoleLogger({level:"debug"});if(models.length===0||!models[0]){const mastraError=new MastraError({id:"LOOP_MODELS_EMPTY",domain:"LLM"/* LLM */,category:"USER"/* USER */});loggerToUse.trackException(mastraError);loggerToUse.error(mastraError.toString());throw mastraError;}const firstModel=models[0];let runIdToUse=runId;if(!runIdToUse){runIdToUse=idGenerator?.()||crypto.randomUUID();}const internalToUse={now:_internal?.now||(()=>Date.now()),generateId:_internal?.generateId||(()=>generateId()),currentDate:_internal?.currentDate||(()=>/* @__PURE__ */new Date())};let startTimestamp=internalToUse.now?.();const{rootSpan}=getRootSpan({operationId:mode==="stream"?`mastra.stream`:`mastra.generate`,model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider},modelSettings,headers:modelSettings?.headers??rest.headers,telemetry_settings});rootSpan.setAttributes({...(telemetry_settings?.recordOutputs!==false?{"stream.prompt.messages":JSON.stringify(messageList.get.input.aiV5.model())}:{})});const{rootSpan:modelStreamSpan}=getRootSpan({operationId:`mastra.${mode}.aisdk.doStream`,model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider},modelSettings,headers:modelSettings?.headers??rest.headers,telemetry_settings});const messageId=rest.experimental_generateMessageId?.()||internalToUse.generateId?.();let modelOutput;const serializeStreamState=()=>{return modelOutput?.serializeState();};const deserializeStreamState=state=>{modelOutput?.deserializeState(state);};const processorStates=outputProcessors&&outputProcessors.length>0?/* @__PURE__ */new Map():void 0;const workflowLoopProps={resumeContext,models,runId:runIdToUse,logger:loggerToUse,startTimestamp,messageList,includeRawChunks:!!includeRawChunks,_internal:internalToUse,tools,modelStreamSpan,telemetry_settings,modelSettings,outputProcessors,messageId,agentId,requireToolApproval,streamState:{serialize:serializeStreamState,deserialize:deserializeStreamState},processorStates,...rest};const existingSnapshot=resumeContext?.snapshot;let initialStreamState;if(existingSnapshot){for(const key in existingSnapshot?.context){const step=existingSnapshot?.context[key];if(step&&step.status==="suspended"&&step.suspendPayload?.__streamState){initialStreamState=step.suspendPayload?.__streamState;break;}}}const baseStream=workflowLoopStream(workflowLoopProps);const stream=rest.modelSpanTracker?.wrapStream(baseStream)??baseStream;modelOutput=new MastraModelOutput({model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider,version:firstModel.model.specificationVersion},stream,messageList,messageId,options:{runId:runIdToUse,telemetry_settings,rootSpan,toolCallStreaming:rest.toolCallStreaming,onFinish:rest.options?.onFinish,onStepFinish:rest.options?.onStepFinish,includeRawChunks:!!includeRawChunks,structuredOutput:rest.structuredOutput,outputProcessors,returnScorerData,tracingContext:rest.modelSpanTracker?.getTracingContext()},initialState:initialStreamState});return createDestructurableOutput(modelOutput);}// src/llm/model/model.loop.ts
434
+ var MastraLLMVNext=class extends MastraBase{#models;#mastra;#options;#firstModel;constructor({mastra,models,options}){super({name:"aisdk"});this.#options=options;if(mastra){this.#mastra=mastra;if(mastra.getLogger()){this.__setLogger(this.#mastra.getLogger());}}if(models.length===0||!models[0]){const mastraError=new MastraError({id:"LLM_LOOP_MODELS_EMPTY",domain:"LLM"/* LLM */,category:"USER"/* USER */});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}else {this.#models=models;this.#firstModel=models[0];}}__registerPrimitives(p){if(p.telemetry){this.__setTelemetry(p.telemetry);}if(p.logger){this.__setLogger(p.logger);}}__registerMastra(p){this.#mastra=p;}getProvider(){return this.#firstModel.model.provider;}getModelId(){return this.#firstModel.model.modelId;}getModel(){return this.#firstModel.model;}_applySchemaCompat(schema){const model=this.#firstModel.model;const schemaCompatLayers=[];if(model){const modelInfo={modelId:model.modelId,supportsStructuredOutputs:true,provider:model.provider};schemaCompatLayers.push(new OpenAIReasoningSchemaCompatLayer(modelInfo),new OpenAISchemaCompatLayer(modelInfo),new GoogleSchemaCompatLayer(modelInfo),new AnthropicSchemaCompatLayer(modelInfo),new DeepSeekSchemaCompatLayer(modelInfo),new MetaSchemaCompatLayer(modelInfo));}return applyCompatLayer({schema,compatLayers:schemaCompatLayers,mode:"aiSdkSchema"});}convertToMessages(messages){if(Array.isArray(messages)){return messages.map(m=>{if(typeof m==="string"){return {role:"user",content:m};}return m;});}return [{role:"user",content:messages}];}stream({resumeContext,runId,stopWhen=stepCountIs(5),maxSteps,tools={},modelSettings,toolChoice="auto",telemetry_settings,threadId,resourceId,structuredOutput,options,outputProcessors,returnScorerData,providerOptions,tracingContext,messageList,requireToolApproval,_internal,agentId,toolCallId}){let stopWhenToUse;if(maxSteps&&typeof maxSteps==="number"){stopWhenToUse=stepCountIs(maxSteps);}else {stopWhenToUse=stopWhen;}const messages=messageList.get.all.aiV5.model();const firstModel=this.#firstModel.model;this.logger.debug(`[LLM] - Streaming text`,{runId,threadId,resourceId,messages,tools:Object.keys(tools||{})});const llmAISpan=tracingContext?.currentSpan?.createChildSpan({name:`llm: '${firstModel.modelId}'`,type:"model_generation"/* MODEL_GENERATION */,input:{messages:[...messageList.getSystemMessages(),...messages]},attributes:{model:firstModel.modelId,provider:firstModel.provider,streaming:true,parameters:modelSettings},metadata:{runId,threadId,resourceId},tracingPolicy:this.#options?.tracingPolicy});const modelSpanTracker=new ModelSpanTracker(llmAISpan);try{const loopOptions={mastra:this.#mastra,resumeContext,runId,toolCallId,messageList,models:this.#models,tools,stopWhen:stopWhenToUse,toolChoice,modelSettings,providerOptions,telemetry_settings:{...this.experimental_telemetry,...telemetry_settings},_internal,structuredOutput,outputProcessors,returnScorerData,modelSpanTracker,requireToolApproval,agentId,options:{...options,onStepFinish:async props=>{try{await options?.onStepFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_STEP_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);modelSpanTracker?.reportGenerationError({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}this.logger.debug("[LLM] - Stream Step Change:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId});if(props?.response?.headers?.["x-ratelimit-remaining-tokens"]&&parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"],10)<2e3){this.logger.warn("Rate limit approaching, waiting 10 seconds",{runId});await delay(10*1e3);}},onFinish:async props=>{modelSpanTracker?.endGeneration({output:{files:props?.files,object:props?.object,reasoning:props?.reasoning,reasoningText:props?.reasoningText,sources:props?.sources,text:props?.text,warnings:props?.warnings},attributes:{finishReason:props?.finishReason,usage:{inputTokens:props?.totalUsage?.inputTokens,outputTokens:props?.totalUsage?.outputTokens,totalTokens:props?.totalUsage?.totalTokens,reasoningTokens:props?.totalUsage?.reasoningTokens,cachedInputTokens:props?.totalUsage?.cachedInputTokens}}});try{await options?.onFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);modelSpanTracker?.reportGenerationError({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}this.logger.debug("[LLM] - Stream Finished:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId,threadId,resourceId});}}};return loop(loopOptions);}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_TEXT_AI_SDK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"THIRD_PARTY"/* THIRD_PARTY */,details:{modelId:firstModel.modelId,modelProvider:firstModel.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown"}},e);modelSpanTracker?.reportGenerationError({error:mastraError});throw mastraError;}}};// src/loop/network/index.ts
435
435
  var MastraAgentNetworkStream=class extends ReadableStream$1{#usageCount={inputTokens:0,outputTokens:0,totalTokens:0};#streamPromise;#run;constructor({createStream,run}){const deferredPromise={promise:null,resolve:null,reject:null};deferredPromise.promise=new Promise((resolve,reject)=>{deferredPromise.resolve=resolve;deferredPromise.reject=reject;});const updateUsageCount=usage=>{this.#usageCount.inputTokens+=parseInt(usage?.inputTokens?.toString()??"0",10);this.#usageCount.outputTokens+=parseInt(usage?.outputTokens?.toString()??"0",10);this.#usageCount.totalTokens+=parseInt(usage?.totalTokens?.toString()??"0",10);};super({start:async controller=>{const writer=new WritableStream({write:chunk=>{if(chunk.type==="step-output"&&chunk.payload?.output?.from==="AGENT"&&chunk.payload?.output?.type==="finish"||chunk.type==="step-output"&&chunk.payload?.output?.from==="WORKFLOW"&&chunk.payload?.output?.type==="finish"){const output=chunk.payload?.output;if(output&&"payload"in output&&output.payload){const finishPayload=output.payload;if("usage"in finishPayload&&finishPayload.usage){updateUsageCount(finishPayload.usage);}}}controller.enqueue(chunk);}});const stream=await createStream(writer);for await(const chunk of stream){if(chunk.type==="workflow-step-output"){const innerChunk=chunk.payload.output;if(innerChunk&&typeof innerChunk==="object"&&"payload"in innerChunk){const nestedOutput=innerChunk.payload;if(nestedOutput&&typeof nestedOutput==="object"&&"output"in nestedOutput&&nestedOutput.output){controller.enqueue(nestedOutput.output);}}}}controller.close();deferredPromise.resolve();}});this.#run=run;this.#streamPromise=deferredPromise;}get status(){return this.#streamPromise.promise.then(()=>this.#run._getExecutionResults()).then(res=>res.status);}get result(){return this.#streamPromise.promise.then(()=>this.#run._getExecutionResults());}get usage(){return this.#streamPromise.promise.then(()=>this.#usageCount);}};// src/loop/types.ts
436
436
  var PRIMITIVE_TYPES=z9.enum(["agent","workflow","none","tool"]);// src/loop/network/index.ts
437
437
  async function getRoutingAgent({runtimeContext,agent}){const instructionsToUse=await agent.getInstructions({runtimeContext});const agentsToUse=await agent.listAgents({runtimeContext});const workflowsToUse=await agent.getWorkflows({runtimeContext});const toolsToUse=await agent.getTools({runtimeContext});const model=await agent.getModel({runtimeContext});const memoryToUse=await agent.getMemory({runtimeContext});const agentList=Object.entries(agentsToUse).map(([name,agent2])=>{return ` - **${name}**: ${agent2.getDescription()}`;}).join("\n");const workflowList=Object.entries(workflowsToUse).map(([name,workflow])=>{return ` - **${name}**: ${workflow.description}, input schema: ${JSON.stringify(zodToJsonSchema(workflow.inputSchema))}`;}).join("\n");const memoryTools=await memoryToUse?.getTools?.();const toolList=Object.entries({...toolsToUse,...memoryTools}).map(([name,tool])=>{return ` - **${name}**: ${tool.description}, input schema: ${JSON.stringify(zodToJsonSchema(tool.inputSchema||z9.object({})))}`;}).join("\n");const instructions=`
@@ -995,7 +995,7 @@ _agentNetworkAppend:this._agentNetworkAppend}).add(result.response.messages,"res
995
995
  * @deprecated `generateVNext()` has been renamed to `generate()`. Please use `generate()` instead.
996
996
  */async generateVNext(_messages,_options){throw new MastraError({id:"AGENT_GENERATE_VNEXT_DEPRECATED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"generateVNext has been renamed to generate. Please use generate instead."});}async generate(messages,options){if(options?.structuredOutput?.schema&&options?.output){throw new MastraError({id:"AGENT_GENERATE_STRUCTURED_OUTPUT_AND_OUTPUT_PROVIDED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"structuredOutput and output cannot be provided at the same time to agent.generate"});}const normalizedOptions=options?.output?{structuredOutput:{schema:options.output,...options.structuredOutput},...options,output:void 0}:options;const result=await this.stream(messages,normalizedOptions);const fullOutput=await result.getFullOutput();const error=fullOutput.error;if(fullOutput.finishReason==="error"&&error){throw error;}return fullOutput;}/**
997
997
  * @deprecated `streamVNext()` has been renamed to `stream()`. Please use `stream()` instead.
998
- */async streamVNext(_messages,_streamOptions){throw new MastraError({id:"AGENT_STREAM_VNEXT_DEPRECATED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"streamVNext has been renamed to stream. Please use stream instead."});}async stream(messages,streamOptions){const defaultStreamOptions=await this.getDefaultVNextStreamOptions({runtimeContext:streamOptions?.runtimeContext});if(streamOptions?.structuredOutput?.schema&&streamOptions?.output){throw new MastraError({id:"AGENT_STREAM_STRUCTURED_OUTPUT_AND_OUTPUT_PROVIDED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"structuredOutput and output cannot be provided at the same time to agent.stream"});}const baseStreamOptions={...defaultStreamOptions,...(streamOptions??{}),onFinish:this.#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions)};const mergedStreamOptions=baseStreamOptions.output?{structuredOutput:{schema:baseStreamOptions.output,...baseStreamOptions.structuredOutput},...baseStreamOptions,output:void 0}:baseStreamOptions;const llm=await this.getLLM({runtimeContext:mergedStreamOptions.runtimeContext});if(llm.getModel().specificationVersion!=="v2"){const modelInfo=llm.getModel();const modelId=modelInfo.modelId||"unknown";const provider=modelInfo.provider||"unknown";throw new MastraError({id:"AGENT_STREAM_V1_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:`Agent "${this.name}" is using AI SDK v4 model (${provider}:${modelId}) which is not compatible with stream(). Please use AI SDK v5 models or call the streamLegacy() method instead. See https://mastra.ai/en/docs/streaming/overview for more information.`,details:{agentName:this.name,modelId,provider,specificationVersion:modelInfo.specificationVersion}});}const executeOptions={...mergedStreamOptions,messages,methodType:"stream"};const result=await this.#execute(executeOptions);if(result.status!=="success"){if(result.status==="failed"){throw new MastraError({id:"AGENT_STREAM_FAILED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */},// pass original error to preserve stack trace
998
+ */async streamVNext(_messages,_streamOptions){throw new MastraError({id:"AGENT_STREAM_VNEXT_DEPRECATED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"streamVNext has been renamed to stream. Please use stream instead."});}async stream(messages,streamOptions){const defaultStreamOptions=await this.getDefaultVNextStreamOptions({runtimeContext:streamOptions?.runtimeContext});if(streamOptions?.structuredOutput?.schema&&streamOptions?.output){throw new MastraError({id:"AGENT_STREAM_STRUCTURED_OUTPUT_AND_OUTPUT_PROVIDED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"structuredOutput and output cannot be provided at the same time to agent.stream"});}const baseStreamOptions={...defaultStreamOptions,...(streamOptions??{}),onFinish:this.#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions)};const mergedStreamOptions=baseStreamOptions.output?{structuredOutput:{schema:baseStreamOptions.output,...baseStreamOptions.structuredOutput},...baseStreamOptions,output:void 0}:baseStreamOptions;const llm=await this.getLLM({runtimeContext:mergedStreamOptions.runtimeContext});const modelInfo=llm.getModel();if(modelInfo.specificationVersion!=="v2"){const modelId=modelInfo.modelId||"unknown";const provider=modelInfo.provider||"unknown";throw new MastraError({id:"AGENT_STREAM_V1_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:`Agent "${this.name}" is using AI SDK v4 model (${provider}:${modelId}) which is not compatible with stream(). Please use AI SDK v5 models or call the streamLegacy() method instead. See https://mastra.ai/en/docs/streaming/overview for more information.`,details:{agentName:this.name,modelId,provider,specificationVersion:modelInfo.specificationVersion}});}const executeOptions={...mergedStreamOptions,messages,methodType:"stream"};const result=await this.#execute(executeOptions);if(result.status!=="success"){if(result.status==="failed"){throw new MastraError({id:"AGENT_STREAM_FAILED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */},// pass original error to preserve stack trace
999
999
  result.error);}throw new MastraError({id:"AGENT_STREAM_UNKNOWN_ERROR",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"An unknown error occurred while streaming"});}if(streamOptions?.format==="aisdk"){this.logger.warn('The `format: "aisdk"` is deprecated in stream/generate options. Use the @mastra/ai-sdk package instead. See https://mastra.ai/en/docs/frameworks/agentic-uis/ai-sdk#streaming');}return result.result;}/**
1000
1000
  * Resumes a previously suspended VNext stream execution.
1001
1001
  * Used to continue execution after a suspension point (e.g., tool approval, workflow suspend).
@@ -1207,5 +1207,5 @@ providerMetadata:baseFinishStep.providerMetadata,text:baseFinishStep.text,warnin
1207
1207
  /** @internal */_getImmediateToolCalls(){return this.#toolCalls;}/** @internal */_getImmediateToolResults(){return this.#toolResults;}/** @internal */_getImmediateText(){return this.#bufferedText.join("");}/** @internal */_getImmediateObject(){return this.#bufferedObject;}/** @internal */_getImmediateUsage(){return this.#usageCount;}/** @internal */_getImmediateWarnings(){return this.#warnings;}/** @internal */_getImmediateFinishReason(){return this.#finishReason;}/** @internal */_getBaseStream(){return this.#baseStream;}#getTotalUsage(){let total=this.#usageCount.totalTokens;if(total===void 0){const input=this.#usageCount.inputTokens??0;const output=this.#usageCount.outputTokens??0;const reasoning=this.#usageCount.reasoningTokens??0;total=input+output+reasoning;}return {inputTokens:this.#usageCount.inputTokens,outputTokens:this.#usageCount.outputTokens,totalTokens:total,reasoningTokens:this.#usageCount.reasoningTokens,cachedInputTokens:this.#usageCount.cachedInputTokens};}#emitChunk(chunk){this.#bufferedChunks.push(chunk);this.#emitter.emit("chunk",chunk);}#createEventedStream(){const self=this;return new ReadableStream$1({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;}serializeState(){return {status:this.#status,bufferedSteps:this.#bufferedSteps,bufferedReasoningDetails:this.#bufferedReasoningDetails,bufferedByStep:this.#bufferedByStep,bufferedText:this.#bufferedText,bufferedTextChunks:this.#bufferedTextChunks,bufferedSources:this.#bufferedSources,bufferedReasoning:this.#bufferedReasoning,bufferedFiles:this.#bufferedFiles,toolCallArgsDeltas:this.#toolCallArgsDeltas,toolCallDeltaIdNameMap:this.#toolCallDeltaIdNameMap,toolCalls:this.#toolCalls,toolResults:this.#toolResults,warnings:this.#warnings,finishReason:this.#finishReason,request:this.#request,usageCount:this.#usageCount,tripwire:this.#tripwire,tripwireReason:this.#tripwireReason,messageList:this.messageList.serialize()};}deserializeState(state){this.#status=state.status;this.#bufferedSteps=state.bufferedSteps;this.#bufferedReasoningDetails=state.bufferedReasoningDetails;this.#bufferedByStep=state.bufferedByStep;this.#bufferedText=state.bufferedText;this.#bufferedTextChunks=state.bufferedTextChunks;this.#bufferedSources=state.bufferedSources;this.#bufferedReasoning=state.bufferedReasoning;this.#bufferedFiles=state.bufferedFiles;this.#toolCallArgsDeltas=state.toolCallArgsDeltas;this.#toolCallDeltaIdNameMap=state.toolCallDeltaIdNameMap;this.#toolCalls=state.toolCalls;this.#toolResults=state.toolResults;this.#warnings=state.warnings;this.#finishReason=state.finishReason;this.#request=state.request;this.#usageCount=state.usageCount;this.#tripwire=state.tripwire;this.#tripwireReason=state.tripwireReason;this.messageList=this.messageList.deserialize(state.messageList);}};
1208
1208
 
1209
1209
  export { AISDKV5OutputStream, Agent, BatchPartsProcessor, ChunkFrom, DefaultExecutionEngine, ExecutionEngine, LanguageDetector, LanguageDetectorInputProcessor, LegacyStep, LegacyWorkflow, MastraAgentNetworkStream, MastraModelOutput, ModerationInputProcessor, ModerationProcessor, PIIDetector, PIIDetectorInputProcessor, ProcessorState, PromptInjectionDetector, PromptInjectionDetectorInputProcessor, Run, StructuredOutputProcessor, SystemPromptScrubber, TokenLimiterProcessor, TripWire, UnicodeNormalizer, UnicodeNormalizerInputProcessor, WhenConditionReturnValue, Workflow, WorkflowRunOutput, agentToStep, cloneStep, cloneWorkflow, convertFullStreamChunkToUIMessageStream, convertMastraChunkToAISDKv5, createStep, createWorkflow, getActivePathsAndStatus, getResultActivePaths, getResumeLabelsByStepId, getStepResult, getStepResult2, getSuspendedPaths, isAgent, isConditionalKey, isErrorEvent, isFinalState, isLimboState, isTransitionEvent, isVariableReference, isWorkflow, loop, mapVariable, mergeChildValue, recursivelyCheckForFinalState, resolveVariables, tryGenerateWithJsonFallback, tryStreamWithJsonFallback, updateStepInHierarchy, validateStepInput, workflowToStep };
1210
- //# sourceMappingURL=chunk-7KYNQSR4.js.map
1211
- //# sourceMappingURL=chunk-7KYNQSR4.js.map
1210
+ //# sourceMappingURL=chunk-N4DKYHQH.js.map
1211
+ //# sourceMappingURL=chunk-N4DKYHQH.js.map