@mastra/core 0.22.2 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +60 -0
- package/dist/agent/agent.d.ts +5 -1
- package/dist/agent/agent.d.ts.map +1 -1
- package/dist/agent/agent.types.d.ts +5 -1
- package/dist/agent/agent.types.d.ts.map +1 -1
- package/dist/agent/index.cjs +13 -13
- package/dist/agent/index.js +2 -2
- package/dist/agent/input-processor/index.cjs +6 -6
- package/dist/agent/input-processor/index.js +1 -1
- package/dist/agent/message-list/index.d.ts +32 -0
- package/dist/agent/message-list/index.d.ts.map +1 -1
- package/dist/agent/utils.d.ts +2 -8
- package/dist/agent/utils.d.ts.map +1 -1
- package/dist/agent/workflows/prepare-stream/index.d.ts +6 -2
- package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
- package/dist/agent/workflows/prepare-stream/stream-step.d.ts +6 -2
- package/dist/agent/workflows/prepare-stream/stream-step.d.ts.map +1 -1
- package/dist/ai-tracing/chunk-tracing.d.ts +10 -10
- package/dist/ai-tracing/chunk-tracing.d.ts.map +1 -1
- package/dist/ai-tracing/index.cjs +36 -36
- package/dist/ai-tracing/index.js +1 -1
- package/dist/ai-tracing/types.d.ts +17 -17
- package/dist/ai-tracing/types.d.ts.map +1 -1
- package/dist/{chunk-5CHZUAZV.cjs → chunk-34WQUECJ.cjs} +98 -98
- package/dist/chunk-34WQUECJ.cjs.map +1 -0
- package/dist/{chunk-VQLW7LPO.js → chunk-34ZCWSUA.js} +3 -3
- package/dist/{chunk-VQLW7LPO.js.map → chunk-34ZCWSUA.js.map} +1 -1
- package/dist/{chunk-YGL6E6PD.cjs → chunk-3JX2Y3WH.cjs} +9 -9
- package/dist/{chunk-YGL6E6PD.cjs.map → chunk-3JX2Y3WH.cjs.map} +1 -1
- package/dist/{chunk-RWWOJXMF.cjs → chunk-4XE7GVZM.cjs} +23 -23
- package/dist/{chunk-RWWOJXMF.cjs.map → chunk-4XE7GVZM.cjs.map} +1 -1
- package/dist/{chunk-FMNZ3BPT.cjs → chunk-4YHU6R7W.cjs} +96 -12
- package/dist/chunk-4YHU6R7W.cjs.map +1 -0
- package/dist/{chunk-WM4VQWOZ.cjs → chunk-5NTO7S5I.cjs} +72 -2
- package/dist/chunk-5NTO7S5I.cjs.map +1 -0
- package/dist/{chunk-MQ67HP3O.cjs → chunk-5P4S4AVU.cjs} +4 -4
- package/dist/{chunk-MQ67HP3O.cjs.map → chunk-5P4S4AVU.cjs.map} +1 -1
- package/dist/{chunk-576KDLXN.cjs → chunk-6KOL2B3A.cjs} +5 -5
- package/dist/{chunk-576KDLXN.cjs.map → chunk-6KOL2B3A.cjs.map} +1 -1
- package/dist/{chunk-T2RDWNN6.js → chunk-7KYNQSR4.js} +38 -39
- package/dist/chunk-7KYNQSR4.js.map +1 -0
- package/dist/{chunk-AMHNTB4N.cjs → chunk-7XAVBWZI.cjs} +19 -19
- package/dist/{chunk-AMHNTB4N.cjs.map → chunk-7XAVBWZI.cjs.map} +1 -1
- package/dist/{chunk-HZIF7HQC.js → chunk-A55YFHFT.js} +8 -8
- package/dist/{chunk-HZIF7HQC.js.map → chunk-A55YFHFT.js.map} +1 -1
- package/dist/{chunk-2JUDZXVI.cjs → chunk-AQGLVU53.cjs} +6 -6
- package/dist/{chunk-2JUDZXVI.cjs.map → chunk-AQGLVU53.cjs.map} +1 -1
- package/dist/{chunk-2DVGQK2L.js → chunk-BLUDYAPI.js} +3 -3
- package/dist/{chunk-2DVGQK2L.js.map → chunk-BLUDYAPI.js.map} +1 -1
- package/dist/{chunk-ROBLMWF6.cjs → chunk-DMBN72QF.cjs} +4 -4
- package/dist/{chunk-ROBLMWF6.cjs.map → chunk-DMBN72QF.cjs.map} +1 -1
- package/dist/{chunk-HD455BM6.cjs → chunk-DPE27ECD.cjs} +23 -23
- package/dist/{chunk-HD455BM6.cjs.map → chunk-DPE27ECD.cjs.map} +1 -1
- package/dist/{chunk-CGT36GQE.cjs → chunk-HANVMC6C.cjs} +36 -36
- package/dist/{chunk-CGT36GQE.cjs.map → chunk-HANVMC6C.cjs.map} +1 -1
- package/dist/{chunk-5NYWRAJN.js → chunk-HFXV34OE.js} +3 -3
- package/dist/{chunk-5NYWRAJN.js.map → chunk-HFXV34OE.js.map} +1 -1
- package/dist/{chunk-KQBF5ZEN.js → chunk-ITCG6QJR.js} +5 -5
- package/dist/{chunk-KQBF5ZEN.js.map → chunk-ITCG6QJR.js.map} +1 -1
- package/dist/{chunk-634YFL42.cjs → chunk-JTI6TVDV.cjs} +63 -12
- package/dist/chunk-JTI6TVDV.cjs.map +1 -0
- package/dist/{chunk-RBO5BUGG.js → chunk-JVV5LREI.js} +3 -3
- package/dist/{chunk-RBO5BUGG.js.map → chunk-JVV5LREI.js.map} +1 -1
- package/dist/{chunk-A3TQYIIR.js → chunk-JZ7I64PK.js} +93 -9
- package/dist/chunk-JZ7I64PK.js.map +1 -0
- package/dist/{chunk-PJDIDFKV.js → chunk-MRJUTTCU.js} +3 -3
- package/dist/{chunk-PJDIDFKV.js.map → chunk-MRJUTTCU.js.map} +1 -1
- package/dist/{chunk-NFIADRH5.js → chunk-NPNGPMT2.js} +3 -3
- package/dist/{chunk-NFIADRH5.js.map → chunk-NPNGPMT2.js.map} +1 -1
- package/dist/{chunk-IQGDOBME.cjs → chunk-NUAURT4I.cjs} +6 -6
- package/dist/{chunk-IQGDOBME.cjs.map → chunk-NUAURT4I.cjs.map} +1 -1
- package/dist/{chunk-4PMF7QUH.js → chunk-NVDVFJWA.js} +4 -4
- package/dist/{chunk-4PMF7QUH.js.map → chunk-NVDVFJWA.js.map} +1 -1
- package/dist/{chunk-M4AX46DS.js → chunk-OIT3PCWA.js} +3 -3
- package/dist/{chunk-M4AX46DS.js.map → chunk-OIT3PCWA.js.map} +1 -1
- package/dist/{chunk-3CVE7NQC.js → chunk-ONKGWHY6.js} +17 -17
- package/dist/chunk-ONKGWHY6.js.map +1 -0
- package/dist/{chunk-5GIAZ3CH.cjs → chunk-PDST7KX7.cjs} +22 -22
- package/dist/chunk-PDST7KX7.cjs.map +1 -0
- package/dist/{chunk-VD27FF3L.js → chunk-PS4ABZY7.js} +7 -7
- package/dist/{chunk-VD27FF3L.js.map → chunk-PS4ABZY7.js.map} +1 -1
- package/dist/{chunk-T3JFFQH2.js → chunk-PZUZNPFM.js} +72 -3
- package/dist/chunk-PZUZNPFM.js.map +1 -0
- package/dist/{chunk-VX7NIAMW.js → chunk-QOTPNUIA.js} +5 -5
- package/dist/{chunk-VX7NIAMW.js.map → chunk-QOTPNUIA.js.map} +1 -1
- package/dist/{chunk-TKYKL7Y4.cjs → chunk-TX4TTPYJ.cjs} +16 -16
- package/dist/{chunk-TKYKL7Y4.cjs.map → chunk-TX4TTPYJ.cjs.map} +1 -1
- package/dist/{chunk-ZDW322JC.cjs → chunk-TYWQLUF6.cjs} +8 -8
- package/dist/{chunk-ZDW322JC.cjs.map → chunk-TYWQLUF6.cjs.map} +1 -1
- package/dist/{chunk-A4B6IAKN.cjs → chunk-VTNVK7HN.cjs} +4 -4
- package/dist/{chunk-A4B6IAKN.cjs.map → chunk-VTNVK7HN.cjs.map} +1 -1
- package/dist/{chunk-I7KJDXUK.cjs → chunk-WBAXXG34.cjs} +19 -19
- package/dist/{chunk-I7KJDXUK.cjs.map → chunk-WBAXXG34.cjs.map} +1 -1
- package/dist/{chunk-LBEV3YZ2.js → chunk-WCHE6FJ7.js} +4 -4
- package/dist/{chunk-LBEV3YZ2.js.map → chunk-WCHE6FJ7.js.map} +1 -1
- package/dist/{chunk-Z2OK2JM2.js → chunk-ZISECZZO.js} +3 -3
- package/dist/{chunk-Z2OK2JM2.js.map → chunk-ZISECZZO.js.map} +1 -1
- package/dist/{chunk-AGD5B3FB.js → chunk-ZWF7AVLU.js} +55 -4
- package/dist/chunk-ZWF7AVLU.js.map +1 -0
- package/dist/error/index.cjs +9 -5
- package/dist/error/index.d.ts +1 -1
- package/dist/error/index.d.ts.map +1 -1
- package/dist/error/index.js +1 -1
- package/dist/error/utils.d.ts +28 -0
- package/dist/error/utils.d.ts.map +1 -1
- package/dist/eval/index.cjs +3 -3
- package/dist/eval/index.js +1 -1
- package/dist/index.cjs +72 -68
- package/dist/index.js +15 -15
- package/dist/llm/index.cjs +7 -7
- package/dist/llm/index.js +1 -1
- package/dist/llm/model/model.loop.d.ts +1 -1
- package/dist/llm/model/model.loop.d.ts.map +1 -1
- package/dist/llm/model/provider-registry.d.ts.map +1 -1
- package/dist/llm/model/provider-types.generated.d.ts +14 -0
- package/dist/loop/index.cjs +2 -2
- package/dist/loop/index.js +1 -1
- package/dist/loop/loop.d.ts.map +1 -1
- package/dist/loop/types.d.ts +6 -3
- package/dist/loop/types.d.ts.map +1 -1
- package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
- package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +1 -1
- package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
- package/dist/loop/workflows/stream.d.ts +1 -1
- package/dist/loop/workflows/stream.d.ts.map +1 -1
- package/dist/mastra/index.cjs +2 -2
- package/dist/mastra/index.js +1 -1
- package/dist/memory/index.cjs +4 -4
- package/dist/memory/index.js +1 -1
- package/dist/netlify-TX6V7SJJ.cjs +12 -0
- package/dist/{netlify-F3MVGV4Y.cjs.map → netlify-TX6V7SJJ.cjs.map} +1 -1
- package/dist/netlify-VJXBII33.js +3 -0
- package/dist/{netlify-26MMY5X4.js.map → netlify-VJXBII33.js.map} +1 -1
- package/dist/processors/index.cjs +11 -11
- package/dist/processors/index.js +1 -1
- package/dist/provider-registry.json +38 -2
- package/dist/relevance/index.cjs +4 -4
- package/dist/relevance/index.js +1 -1
- package/dist/scores/index.cjs +9 -9
- package/dist/scores/index.js +2 -2
- package/dist/scores/scoreTraces/index.cjs +15 -15
- package/dist/scores/scoreTraces/index.cjs.map +1 -1
- package/dist/scores/scoreTraces/index.js +6 -6
- package/dist/scores/scoreTraces/index.js.map +1 -1
- package/dist/server/index.cjs +7 -7
- package/dist/server/index.js +2 -2
- package/dist/storage/index.cjs +25 -25
- package/dist/storage/index.js +4 -4
- package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
- package/dist/stream/aisdk/v5/output.d.ts +2 -8
- package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
- package/dist/stream/base/output.d.ts +31 -13
- package/dist/stream/base/output.d.ts.map +1 -1
- package/dist/stream/index.cjs +11 -11
- package/dist/stream/index.js +2 -2
- package/dist/telemetry/index.cjs +7 -7
- package/dist/telemetry/index.js +1 -1
- package/dist/test-utils/llm-mock.cjs +2 -2
- package/dist/test-utils/llm-mock.js +1 -1
- package/dist/tts/index.cjs +2 -2
- package/dist/tts/index.js +1 -1
- package/dist/utils.cjs +17 -17
- package/dist/utils.js +1 -1
- package/dist/vector/index.cjs +4 -4
- package/dist/vector/index.js +1 -1
- package/dist/voice/index.cjs +4 -4
- package/dist/voice/index.js +1 -1
- package/dist/workflows/default.d.ts +11 -1
- package/dist/workflows/default.d.ts.map +1 -1
- package/dist/workflows/evented/index.cjs +10 -10
- package/dist/workflows/evented/index.js +1 -1
- package/dist/workflows/execution-engine.d.ts +3 -0
- package/dist/workflows/execution-engine.d.ts.map +1 -1
- package/dist/workflows/index.cjs +16 -12
- package/dist/workflows/index.js +1 -1
- package/dist/workflows/legacy/index.cjs +22 -22
- package/dist/workflows/legacy/index.js +1 -1
- package/dist/workflows/step.d.ts +1 -1
- package/dist/workflows/step.d.ts.map +1 -1
- package/dist/workflows/types.d.ts +16 -1
- package/dist/workflows/types.d.ts.map +1 -1
- package/dist/workflows/utils.d.ts +7 -0
- package/dist/workflows/utils.d.ts.map +1 -1
- package/dist/workflows/workflow.d.ts +12 -3
- package/dist/workflows/workflow.d.ts.map +1 -1
- package/package.json +11 -4
- package/src/llm/model/provider-types.generated.d.ts +14 -0
- package/dist/chunk-3CVE7NQC.js.map +0 -1
- package/dist/chunk-5CHZUAZV.cjs.map +0 -1
- package/dist/chunk-5GIAZ3CH.cjs.map +0 -1
- package/dist/chunk-634YFL42.cjs.map +0 -1
- package/dist/chunk-A3TQYIIR.js.map +0 -1
- package/dist/chunk-AGD5B3FB.js.map +0 -1
- package/dist/chunk-FMNZ3BPT.cjs.map +0 -1
- package/dist/chunk-T2RDWNN6.js.map +0 -1
- package/dist/chunk-T3JFFQH2.js.map +0 -1
- package/dist/chunk-WM4VQWOZ.cjs.map +0 -1
- package/dist/netlify-26MMY5X4.js +0 -3
- package/dist/netlify-F3MVGV4Y.cjs +0 -12
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { DefaultVoice } from './chunk-
|
|
1
|
+
import { DefaultVoice } from './chunk-WCHE6FJ7.js';
|
|
2
2
|
import { STREAM_FORMAT_SYMBOL, EMITTER_SYMBOL } from './chunk-NLNKQD2T.js';
|
|
3
|
-
import { InstrumentClass, Telemetry } from './chunk-
|
|
4
|
-
import { MessageList, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-
|
|
5
|
-
import { resolveModelConfig } from './chunk-
|
|
6
|
-
import { MastraLLMV1 } from './chunk-
|
|
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';
|
|
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-
|
|
9
|
+
import { wrapMastra, selectFields, getOrCreateSpan, getValidTraceId, ensureToolProperties, makeCoreTool, createMastraProxy, ModelSpanTracker, delay } from './chunk-ONKGWHY6.js';
|
|
10
10
|
import { RuntimeContext } from './chunk-HLRWYUFN.js';
|
|
11
|
-
import { MastraError, safeParseErrorObject } from './chunk-
|
|
11
|
+
import { MastraError, safeParseErrorObject, getErrorFromUnknown } from './chunk-PZUZNPFM.js';
|
|
12
12
|
import { ToolStream } from './chunk-HGNRQ3OG.js';
|
|
13
13
|
import { Tool, createTool } from './chunk-WM4RO23J.js';
|
|
14
14
|
import { MastraBase } from './chunk-VQASQG5D.js';
|
|
@@ -21,7 +21,7 @@ import * as crypto2 from 'crypto';
|
|
|
21
21
|
import { randomUUID } from 'crypto';
|
|
22
22
|
import { context, trace } from '@opentelemetry/api';
|
|
23
23
|
import { getErrorMessage, TypeValidationError } from '@ai-sdk/provider-v5';
|
|
24
|
-
import { generateId, createTextStreamResponse, createUIMessageStreamResponse, createUIMessageStream, asSchema, parsePartialJson, isDeepEqualData, jsonSchema, tool, stepCountIs } from 'ai-v5';
|
|
24
|
+
import { generateId, createTextStreamResponse, createUIMessageStreamResponse, createUIMessageStream, asSchema, parsePartialJson, isDeepEqualData, jsonSchema, APICallError, tool, stepCountIs } from 'ai-v5';
|
|
25
25
|
import slugify from '@sindresorhus/slugify';
|
|
26
26
|
import { OpenAIReasoningSchemaCompatLayer, OpenAISchemaCompatLayer, GoogleSchemaCompatLayer, AnthropicSchemaCompatLayer, DeepSeekSchemaCompatLayer, MetaSchemaCompatLayer, applyCompatLayer } from '@mastra/schema-compat';
|
|
27
27
|
import { isEmpty, get } from 'radash';
|
|
@@ -233,7 +233,7 @@ usage:self.#usageCount}}});self.#streamFinished=true;self.#emitter.emit("finish"
|
|
|
233
233
|
function runScorer({runId,scorerId,scorerObject,input,output,runtimeContext,entity,structuredOutput,source,entityType,threadId,resourceId,tracingContext}){let shouldExecute=false;if(!scorerObject?.sampling||scorerObject?.sampling?.type==="none"){shouldExecute=true;}if(scorerObject?.sampling?.type){switch(scorerObject?.sampling?.type){case "ratio":shouldExecute=Math.random()<scorerObject?.sampling?.rate;break;default:shouldExecute=true;}}if(!shouldExecute){return;}const payload={scorer:{id:scorerId,name:scorerObject.scorer.name,description:scorerObject.scorer.description},input,output,runtimeContext:Object.fromEntries(runtimeContext.entries()),runId,source,entity,structuredOutput,entityType,threadId,resourceId,tracingContext};executeHook("onScorerRun"/* ON_SCORER_RUN */,payload);}// src/workflows/execution-engine.ts
|
|
234
234
|
var ExecutionEngine=class extends MastraBase{mastra;options;constructor({mastra,options}){super({name:"ExecutionEngine",component:RegisteredLogger.WORKFLOW});this.mastra=mastra;this.options=options;}__registerMastra(mastra){this.mastra=mastra;}};// src/workflows/step.ts
|
|
235
235
|
var getStepResult=(stepResults,step)=>{let result;if(typeof step==="string"){result=stepResults[step];}else {if(!step?.id){return null;}result=stepResults[step.id];}return result?.status==="success"?result.output:null;};// src/workflows/utils.ts
|
|
236
|
-
async function validateStepInput({prevOutput,step,validateInputs}){let inputData=prevOutput;let validationError;if(validateInputs){const inputSchema=step.inputSchema;const validatedInput=await inputSchema.safeParseAsync(prevOutput);if(!validatedInput.success){const errorMessages=validatedInput.error.errors.map(e=>`- ${e.path?.join(".")}: ${e.message}`)?.join("\n");validationError=new Error("Step input validation failed: \n"+errorMessages);}else {inputData=isEmpty(validatedInput.data)?prevOutput:validatedInput.data;}}return {inputData,validationError};}// src/workflows/default.ts
|
|
236
|
+
async function validateStepInput({prevOutput,step,validateInputs}){let inputData=prevOutput;let validationError;if(validateInputs){const inputSchema=step.inputSchema;const validatedInput=await inputSchema.safeParseAsync(prevOutput);if(!validatedInput.success){const errorMessages=validatedInput.error.errors.map(e=>`- ${e.path?.join(".")}: ${e.message}`)?.join("\n");validationError=new Error("Step input validation failed: \n"+errorMessages);}else {inputData=isEmpty(validatedInput.data)?prevOutput:validatedInput.data;}}return {inputData,validationError};}function getResumeLabelsByStepId(resumeLabels,stepId){return Object.entries(resumeLabels).filter(([_,value])=>value.stepId===stepId).reduce((acc,[key,value])=>{acc[key]=value;return acc;},{});}// src/workflows/default.ts
|
|
237
237
|
var DefaultExecutionEngine=class extends ExecutionEngine{/**
|
|
238
238
|
* Preprocesses an error caught during workflow execution.
|
|
239
239
|
*
|
|
@@ -254,15 +254,14 @@ var DefaultExecutionEngine=class extends ExecutionEngine{/**
|
|
|
254
254
|
* @param graph The execution graph to execute
|
|
255
255
|
* @param input The input data for the workflow
|
|
256
256
|
* @returns A promise that resolves to the workflow output
|
|
257
|
-
*/async execute(params){const{workflowId,runId,resourceId,graph,input,initialState,resume,retryConfig,workflowAISpan,disableScorers}=params;const{attempts=0,delay:delay2=0}=retryConfig??{};const steps=graph.steps;this.runCounts.clear();if(steps.length===0){const empty_graph_error=new MastraError({id:"WORKFLOW_EXECUTE_EMPTY_GRAPH",text:"Workflow must have at least one step",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */});workflowAISpan?.error({error:empty_graph_error});throw empty_graph_error;}const executionSpan=this.mastra?.getTelemetry()?.tracer.startSpan(`workflow.${workflowId}.execute`,{attributes:{componentName:workflowId,runId,resourceId}});let startIdx=0;if(resume?.resumePath){startIdx=resume.resumePath[0];resume.resumePath.shift();}const stepResults=resume?.stepResults||{input};let lastOutput;let lastState=initialState??{};for(let i=startIdx;i<steps.length;i++){const entry=steps[i];const executionContext={workflowId,runId,executionPath:[i],suspendedPaths:{},resumeLabels:{},retryConfig:{attempts,delay:delay2},executionSpan,format:params.format,state:lastState??initialState};try{lastOutput=await this.executeEntry({workflowId,runId,resourceId,entry,executionContext,serializedStepGraph:params.serializedStepGraph,prevStep:steps[i-1],stepResults,resume,tracingContext:{currentSpan:workflowAISpan},abortController:params.abortController,emitter:params.emitter,runtimeContext:params.runtimeContext,writableStream:params.writableStream,disableScorers});if(lastOutput.executionContext?.state){lastState=lastOutput.executionContext.state;}if(lastOutput.result.status!=="success"){if(lastOutput.result.status==="bailed"){lastOutput.result.status="success";}const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});if(result2.error){workflowAISpan?.error({error:result2.error,attributes:{status:result2.status}});}else {workflowAISpan?.end({output:result2.result,attributes:{status:result2.status}});}return result2;}}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_ENGINE_STEP_EXECUTION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error executing step: ");const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result,e);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});workflowAISpan?.error({error,attributes:{status:result2.status}});return result2;}}const result=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result.status,result:result.result,error:result.error,runtimeContext:params.runtimeContext});workflowAISpan?.end({output:result.result,attributes:{status:result.status}});if(params.outputOptions?.includeState){return {...result,state:lastState};}return result;}getStepOutput(stepResults,step){if(!step){return stepResults.input;}else if(step.type==="step"||step.type==="waitForEvent"){return stepResults[step.step.id]?.output;}else if(step.type==="sleep"||step.type==="sleepUntil"){return stepResults[step.id]?.output;}else if(step.type==="parallel"||step.type==="conditional"){return step.steps.reduce((acc,entry)=>{if(entry.type==="step"||entry.type==="waitForEvent"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="parallel"||entry.type==="conditional"){const parallelResult=this.getStepOutput(stepResults,entry)?.output;acc={...acc,...parallelResult};}else if(entry.type==="loop"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="foreach"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="sleep"||entry.type==="sleepUntil"){acc[entry.id]=stepResults[entry.id]?.output;}return acc;},{});}else if(step.type==="loop"){return stepResults[step.step.id]?.output;}else if(step.type==="foreach"){return stepResults[step.step.id]?.output;}}async executeSleep({workflowId,runId,entry,prevOutput,stepResults,emitter,abortController,runtimeContext,executionContext,writableStream,tracingContext}){let{duration,fn}=entry;const sleepSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_sleep"/* WORKFLOW_SLEEP */,name:`sleep: ${duration?`${duration}ms`:"dynamic"}`,attributes:{durationMs:duration,sleepType:fn?"dynamic":"fixed"},tracingPolicy:this.options?.tracingPolicy});if(fn){const stepCallId=randomUUID();duration=await fn({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:sleepSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
|
|
257
|
+
*/async execute(params){const{workflowId,runId,resourceId,graph,input,initialState,resume,retryConfig,workflowAISpan,disableScorers}=params;const{attempts=0,delay:delay2=0}=retryConfig??{};const steps=graph.steps;this.runCounts.clear();if(steps.length===0){const empty_graph_error=new MastraError({id:"WORKFLOW_EXECUTE_EMPTY_GRAPH",text:"Workflow must have at least one step",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */});workflowAISpan?.error({error:empty_graph_error});throw empty_graph_error;}const executionSpan=this.mastra?.getTelemetry()?.tracer.startSpan(`workflow.${workflowId}.execute`,{attributes:{componentName:workflowId,runId,resourceId}});let startIdx=0;if(resume?.resumePath){startIdx=resume.resumePath[0];resume.resumePath.shift();}const stepResults=resume?.stepResults||{input};let lastOutput;let lastState=initialState??{};for(let i=startIdx;i<steps.length;i++){const entry=steps[i];const executionContext={workflowId,runId,executionPath:[i],suspendedPaths:{},resumeLabels:{},retryConfig:{attempts,delay:delay2},executionSpan,format:params.format,state:lastState??initialState};try{lastOutput=await this.executeEntry({workflowId,runId,resourceId,entry,executionContext,serializedStepGraph:params.serializedStepGraph,prevStep:steps[i-1],stepResults,resume,tracingContext:{currentSpan:workflowAISpan},abortController:params.abortController,emitter:params.emitter,runtimeContext:params.runtimeContext,writableStream:params.writableStream,disableScorers});if(lastOutput.executionContext?.state){lastState=lastOutput.executionContext.state;}if(lastOutput.result.status!=="success"){if(lastOutput.result.status==="bailed"){lastOutput.result.status="success";}const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});if(result2.error){workflowAISpan?.error({error:result2.error,attributes:{status:result2.status}});}else {workflowAISpan?.end({output:result2.result,attributes:{status:result2.status}});}if(lastOutput.result.status==="suspended"&¶ms.outputOptions?.includeResumeLabels){return {...result2,resumeLabels:lastOutput.executionContext?.resumeLabels};}return result2;}}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_ENGINE_STEP_EXECUTION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error executing step: ");const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result,e);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});workflowAISpan?.error({error,attributes:{status:result2.status}});return result2;}}const result=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result.status,result:result.result,error:result.error,runtimeContext:params.runtimeContext});workflowAISpan?.end({output:result.result,attributes:{status:result.status}});if(params.outputOptions?.includeState){return {...result,state:lastState};}return result;}getStepOutput(stepResults,step){if(!step){return stepResults.input;}else if(step.type==="step"||step.type==="waitForEvent"){return stepResults[step.step.id]?.output;}else if(step.type==="sleep"||step.type==="sleepUntil"){return stepResults[step.id]?.output;}else if(step.type==="parallel"||step.type==="conditional"){return step.steps.reduce((acc,entry)=>{if(entry.type==="step"||entry.type==="waitForEvent"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="parallel"||entry.type==="conditional"){const parallelResult=this.getStepOutput(stepResults,entry)?.output;acc={...acc,...parallelResult};}else if(entry.type==="loop"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="foreach"){acc[entry.step.id]=stepResults[entry.step.id]?.output;}else if(entry.type==="sleep"||entry.type==="sleepUntil"){acc[entry.id]=stepResults[entry.id]?.output;}return acc;},{});}else if(step.type==="loop"){return stepResults[step.step.id]?.output;}else if(step.type==="foreach"){return stepResults[step.step.id]?.output;}}async executeSleep({workflowId,runId,entry,prevOutput,stepResults,emitter,abortController,runtimeContext,executionContext,writableStream,tracingContext}){let{duration,fn}=entry;const sleepSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_sleep"/* WORKFLOW_SLEEP */,name:`sleep: ${duration?`${duration}ms`:"dynamic"}`,attributes:{durationMs:duration,sleepType:fn?"dynamic":"fixed"},tracingPolicy:this.options?.tracingPolicy});if(fn){const stepCallId=randomUUID();duration=await fn({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:sleepSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
|
|
258
258
|
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:stepCallId,name:"sleep",runId},writableStream)});sleepSpan?.update({attributes:{durationMs:duration}});}try{await new Promise(resolve=>setTimeout(resolve,!duration||duration<0?0:duration));sleepSpan?.end();}catch(e){sleepSpan?.error({error:e});}}async executeSleepUntil({workflowId,runId,entry,prevOutput,stepResults,emitter,abortController,runtimeContext,executionContext,writableStream,tracingContext}){let{date,fn}=entry;const sleepUntilSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_sleep"/* WORKFLOW_SLEEP */,name:`sleepUntil: ${date?date.toISOString():"dynamic"}`,attributes:{untilDate:date,durationMs:date?Math.max(0,date.getTime()-Date.now()):void 0,sleepType:fn?"dynamic":"fixed"},tracingPolicy:this.options?.tracingPolicy});if(fn){const stepCallId=randomUUID();date=await fn({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:sleepUntilSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
|
|
259
|
-
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:stepCallId,name:"sleepUntil",runId},writableStream)});const time2=!date?0:date.getTime()-Date.now();sleepUntilSpan?.update({attributes:{durationMs:Math.max(0,time2)}});}const time=!date?0:date?.getTime()-Date.now();try{await new Promise(resolve=>setTimeout(resolve,time<0?0:time));sleepUntilSpan?.end();}catch(e){sleepUntilSpan?.error({error:e});}}async executeWaitForEvent({event,emitter,timeout,tracingContext}){const waitSpan=tracingContext?.currentSpan?.createChildSpan({type:"workflow_wait_event"/* WORKFLOW_WAIT_EVENT */,name:`wait: ${event}`,attributes:{eventName:event,timeoutMs:timeout},tracingPolicy:this.options?.tracingPolicy});const startTime=Date.now();return new Promise((resolve,reject)=>{const cb=eventData=>{waitSpan?.end({output:eventData,attributes:{eventReceived:true,waitDurationMs:Date.now()-startTime}});resolve(eventData);};if(timeout){setTimeout(()=>{emitter.off(`user-event-${event}`,cb);const error=new Error("Timeout waiting for event");waitSpan?.error({error,attributes:{eventReceived:false,waitDurationMs:Date.now()-startTime}});reject(error);},timeout);}emitter.once(`user-event-${event}`,cb);});}async executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume,prevOutput,emitter,abortController,runtimeContext,skipEmits=false,writableStream,disableScorers,serializedStepGraph,tracingContext,iterationCount}){const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepCallId=randomUUID();const{inputData,validationError}=await validateStepInput({prevOutput,step,validateInputs:this.options?.validateInputs??false});const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:inputData}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{}),status:"running",...(iterationCount?{metadata:{iterationCount}}:{})};const stepAISpan=tracingContext.currentSpan?.createChildSpan({name:`workflow step: '${step.id}'`,type:"workflow_step"/* WORKFLOW_STEP */,input:inputData,attributes:{stepId:step.id},tracingPolicy:this.options?.tracingPolicy});if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,stepCallId,...stepInfo}});}await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults:{...stepResults,[step.id]:stepInfo},executionContext,workflowStatus:"running",runtimeContext});const _runStep=(step2,spanName,attributes)=>{return async data=>{const telemetry=this.mastra?.getTelemetry();const span=executionContext.executionSpan;if(!telemetry||!span){return step2.execute(data);}return context.with(trace.setSpan(context.active(),span),async()=>{return telemetry.traceMethod(step2.execute.bind(step2),{spanName,attributes})(data);});};};const runStep=_runStep(step,`workflow.${workflowId}.step.${step.id}`,{componentName:workflowId,runId,resourceId:resourceId??""});let execResults;const retries=step.retries??executionContext.retryConfig.attempts??0;const delay2=executionContext.retryConfig.delay??0;for(let i=0;i<retries+1;i++){if(i>0&&delay2){await new Promise(resolve=>setTimeout(resolve,delay2));}try{let suspended;let bailed;if(validationError){throw validationError;}const result=await runStep({runId,resourceId,workflowId,mastra:this.mastra?wrapMastra(this.mastra,{currentSpan:stepAISpan}):void 0,runtimeContext,inputData,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:this.getOrGenerateRunCount(step.id),resumeData:resume?.steps[0]===step.id?resume?.resumePayload:void 0,tracingContext:{currentSpan:stepAISpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),suspend:async(suspendPayload,suspendOptions)=>{executionContext.suspendedPaths[step.id]=executionContext.executionPath;if(suspendOptions?.resumeLabel){
|
|
259
|
+
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:stepCallId,name:"sleepUntil",runId},writableStream)});const time2=!date?0:date.getTime()-Date.now();sleepUntilSpan?.update({attributes:{durationMs:Math.max(0,time2)}});}const time=!date?0:date?.getTime()-Date.now();try{await new Promise(resolve=>setTimeout(resolve,time<0?0:time));sleepUntilSpan?.end();}catch(e){sleepUntilSpan?.error({error:e});}}async executeWaitForEvent({event,emitter,timeout,tracingContext}){const waitSpan=tracingContext?.currentSpan?.createChildSpan({type:"workflow_wait_event"/* WORKFLOW_WAIT_EVENT */,name:`wait: ${event}`,attributes:{eventName:event,timeoutMs:timeout},tracingPolicy:this.options?.tracingPolicy});const startTime=Date.now();return new Promise((resolve,reject)=>{const cb=eventData=>{waitSpan?.end({output:eventData,attributes:{eventReceived:true,waitDurationMs:Date.now()-startTime}});resolve(eventData);};if(timeout){setTimeout(()=>{emitter.off(`user-event-${event}`,cb);const error=new Error("Timeout waiting for event");waitSpan?.error({error,attributes:{eventReceived:false,waitDurationMs:Date.now()-startTime}});reject(error);},timeout);}emitter.once(`user-event-${event}`,cb);});}async executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume,prevOutput,emitter,abortController,runtimeContext,skipEmits=false,writableStream,disableScorers,serializedStepGraph,tracingContext,iterationCount}){const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepCallId=randomUUID();const{inputData,validationError}=await validateStepInput({prevOutput,step,validateInputs:this.options?.validateInputs??false});const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:inputData}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{}),status:"running",...(iterationCount?{metadata:{iterationCount}}:{})};const stepAISpan=tracingContext.currentSpan?.createChildSpan({name:`workflow step: '${step.id}'`,type:"workflow_step"/* WORKFLOW_STEP */,input:inputData,attributes:{stepId:step.id},tracingPolicy:this.options?.tracingPolicy});if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,stepCallId,...stepInfo}});}await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults:{...stepResults,[step.id]:stepInfo},executionContext,workflowStatus:"running",runtimeContext});const _runStep=(step2,spanName,attributes)=>{return async data=>{const telemetry=this.mastra?.getTelemetry();const span=executionContext.executionSpan;if(!telemetry||!span){return step2.execute(data);}return context.with(trace.setSpan(context.active(),span),async()=>{return telemetry.traceMethod(step2.execute.bind(step2),{spanName,attributes})(data);});};};const runStep=_runStep(step,`workflow.${workflowId}.step.${step.id}`,{componentName:workflowId,runId,resourceId:resourceId??""});let execResults;const retries=step.retries??executionContext.retryConfig.attempts??0;const delay2=executionContext.retryConfig.delay??0;for(let i=0;i<retries+1;i++){if(i>0&&delay2){await new Promise(resolve=>setTimeout(resolve,delay2));}try{let suspended;let bailed;if(validationError){throw validationError;}const result=await runStep({runId,resourceId,workflowId,mastra:this.mastra?wrapMastra(this.mastra,{currentSpan:stepAISpan}):void 0,runtimeContext,inputData,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:this.getOrGenerateRunCount(step.id),resumeData:resume?.steps[0]===step.id?resume?.resumePayload:void 0,tracingContext:{currentSpan:stepAISpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),suspend:async(suspendPayload,suspendOptions)=>{executionContext.suspendedPaths[step.id]=executionContext.executionPath;if(suspendOptions?.resumeLabel){const resumeLabel=Array.isArray(suspendOptions.resumeLabel)?suspendOptions.resumeLabel:[suspendOptions.resumeLabel];for(const label of resumeLabel){executionContext.resumeLabels[label]={stepId:step.id,foreachIndex:executionContext.foreachIndex};}}suspended={payload:suspendPayload};},bail:result2=>{bailed={payload:result2};},abort:()=>{abortController?.abort();},// Only pass resume data if this step was actually suspended before
|
|
260
260
|
// This prevents pending nested workflows from trying to resume instead of start
|
|
261
261
|
resume:stepResults[step.id]?.status==="suspended"?{steps:resume?.steps?.slice(1)||[],resumePayload:resume?.resumePayload,// @ts-ignore
|
|
262
|
-
runId:stepResults[step.id]?.suspendPayload?.__workflow_meta?.runId}:void 0,[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:stepCallId,name:step.id,runId},writableStream),// Disable scorers must be explicitly set to false they are on by default
|
|
262
|
+
runId:stepResults[step.id]?.suspendPayload?.__workflow_meta?.runId,label:resume?.label,forEachIndex:resume?.forEachIndex}:void 0,[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:stepCallId,name:step.id,runId},writableStream),// Disable scorers must be explicitly set to false they are on by default
|
|
263
263
|
scorers:disableScorers===false?void 0:step.scorers,validateInputs:this.options?.validateInputs});if(step.scorers){await this.runScorers({scorers:step.scorers,runId,input:inputData,output:result,workflowId,stepId:step.id,runtimeContext,disableScorers,tracingContext:{currentSpan:stepAISpan}});}if(suspended){execResults={status:"suspended",suspendPayload:suspended.payload,suspendedAt:Date.now()};}else if(bailed){execResults={status:"bailed",output:bailed.payload,endedAt:Date.now()};}else {execResults={status:"success",output:result,endedAt:Date.now()};}break;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_STEP_INVOKE_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId,stepId:step.id}},`Error executing step ${step.id}: `);stepAISpan?.error({error,attributes:{status:"failed"}});execResults={status:"failed",error:error?.stack,endedAt:Date.now()};}}if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,stepCallId,...execResults}});}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,stepCallId,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,stepCallId,metadata:{}}});}}if(execResults.status!="failed"){stepAISpan?.end({output:execResults.output,attributes:{status:execResults.status}});}return {...stepInfo,...execResults};}async runScorers({scorers,runId,input,output,workflowId,stepId,runtimeContext,disableScorers,tracingContext}){let scorersToUse=scorers;if(typeof scorersToUse==="function"){try{scorersToUse=await scorersToUse({runtimeContext});}catch(error){this.preprocessExecutionError(error,{id:"WORKFLOW_FAILED_TO_FETCH_SCORERS",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{runId,workflowId,stepId}},"Error fetching scorers: ");}}if(!disableScorers&&scorersToUse&&Object.keys(scorersToUse||{}).length>0){for(const[_id,scorerObject]of Object.entries(scorersToUse||{})){runScorer({scorerId:scorerObject.name,scorerObject,runId,input,output,runtimeContext,entity:{id:workflowId,stepId},structuredOutput:true,source:"LIVE",entityType:"WORKFLOW",tracingContext});}}}async executeParallel({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const parallelSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_parallel"/* WORKFLOW_PARALLEL */,name:`parallel: '${entry.steps.length} branches'`,input:this.getStepOutput(stepResults,prevStep),attributes:{branchCount:entry.steps.length,parallelSteps:entry.steps.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)},tracingPolicy:this.options?.tracingPolicy});let execResults;const results=await Promise.all(entry.steps.map((step,i)=>this.executeEntry({workflowId,runId,resourceId,entry:step,prevStep,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,i],suspendedPaths:executionContext.suspendedPaths,resumeLabels:executionContext.resumeLabels,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext:{currentSpan:parallelSpan},emitter,abortController,runtimeContext,writableStream,disableScorers})));const hasFailed=results.find(result=>result.result.status==="failed");const hasSuspended=results.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:results.reduce((acc,result,index)=>{if(result.result.status==="success"){acc[entry.steps[index].step.id]=result.result.output;}return acc;},{})};}if(execResults.status==="failed"){parallelSpan?.error({error:new Error(execResults.error)});}else {parallelSpan?.end({output:execResults.output||execResults});}return execResults;}async executeConditional({workflowId,runId,resourceId,entry,prevOutput,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const conditionalSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_conditional"/* WORKFLOW_CONDITIONAL */,name:`conditional: '${entry.conditions.length} conditions'`,input:prevOutput,attributes:{conditionCount:entry.conditions.length},tracingPolicy:this.options?.tracingPolicy});let execResults;const truthyIndexes=(await Promise.all(entry.conditions.map(async(cond,index)=>{const evalSpan=conditionalSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition '${index}'`,input:prevOutput,attributes:{conditionIndex:index},tracingPolicy:this.options?.tracingPolicy});try{const result=await cond({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:evalSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
|
|
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 resumeIndex=prevPayload?.status==="suspended"?prevPayload?.suspendPayload?.__workflow_meta?.foreachIndex||0:0;for(let i=resumeIndex;i<prevOutput.length;i+=concurrency){const items=prevOutput.slice(i,i+concurrency);const itemsResults=await Promise.all(items.map((item,j)=>{return this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume:resumeIndex===i+j?resume:void 0,prevOutput:item,tracingContext:{currentSpan:loopSpan},emitter,abortController,runtimeContext,skipEmits:true,writableStream,disableScorers,serializedStepGraph});}));for(const result of itemsResults){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"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,...execResults}});return {...stepInfo,status:"suspended",suspendPayload:{...execResults.suspendPayload,__workflow_meta:{...execResults.suspendPayload?.__workflow_meta,foreachIndex:i}},//@ts-ignore
|
|
265
|
-
endedAt:Date.now()};}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;}}results.push(result?.output);}}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
|
|
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
|
|
266
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
|
|
267
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
|
|
268
267
|
function mapVariable(config){return config;}function createStep(params){if(params instanceof Agent){return {id:params.name,description:params.getDescription(),// @ts-ignore
|
|
@@ -311,7 +310,7 @@ condition,loopType:"dountil",serializedCondition:{id:`${step.id}-condition`,fn:c
|
|
|
311
310
|
*/async createRunAsync(options){if(this.stepFlow.length===0){throw new Error("Execution flow of workflow is not defined. Add steps to the workflow via .then(), .branch(), etc.");}if(!this.executionGraph.steps){throw new Error("Uncommitted step flow changes detected. Call .commit() to register the steps.");}const runIdToUse=options?.runId||this.#mastra?.generateId()||randomUUID();const run=this.#runs.get(runIdToUse)??new Run({workflowId:this.id,stateSchema:this.stateSchema,runId:runIdToUse,resourceId:options?.resourceId,executionEngine:this.executionEngine,executionGraph:this.executionGraph,mastra:this.#mastra,retryConfig:this.retryConfig,serializedStepGraph:this.serializedStepGraph,disableScorers:options?.disableScorers,cleanup:()=>this.#runs.delete(runIdToUse),tracingPolicy:this.#options?.tracingPolicy,workflowSteps:this.steps,validateInputs:this.#options?.validateInputs});this.#runs.set(runIdToUse,run);const shouldPersistSnapshot=this.#options.shouldPersistSnapshot({workflowStatus:run.workflowRunStatus,stepResults:{}});const workflowSnapshotInStorage=await this.getWorkflowRunExecutionResult(runIdToUse,false);if(!workflowSnapshotInStorage&&shouldPersistSnapshot){await this.mastra?.getStorage()?.persistWorkflowSnapshot({workflowName:this.id,runId:runIdToUse,resourceId:options?.resourceId,snapshot:{runId:runIdToUse,status:"pending",value:{},context:{},activePaths:[],serializedStepGraph:this.serializedStepGraph,suspendedPaths:{},resumeLabels:{},waitingPaths:{},result:void 0,error:void 0,// @ts-ignore
|
|
312
311
|
timestamp:Date.now()}});}return run;}async getScorers({runtimeContext=new RuntimeContext()}={}){const steps=this.steps;if(!steps||Object.keys(steps).length===0){return {};}const scorers={};for(const step of Object.values(steps)){if(step.scorers){let scorersToUse=step.scorers;if(typeof scorersToUse==="function"){scorersToUse=await scorersToUse({runtimeContext});}for(const[id,scorer]of Object.entries(scorersToUse)){scorers[id]=scorer;}}}return scorers;}// This method should only be called internally for nested workflow execution, as well as from mastra server handlers
|
|
313
312
|
// To run a workflow use `.createRunAsync` and then `.start` or `.resume`
|
|
314
|
-
async execute({runId,inputData,resumeData,state,setState,suspend,resume,[EMITTER_SYMBOL]:emitter,mastra,runtimeContext,abort,abortSignal,runCount,tracingContext,writer,validateInputs}){this.__registerMastra(mastra);if(validateInputs){this.#options={...(this.#options||{}),validateInputs};}this.executionEngine.options={...(this.executionEngine.options||{}),validateInputs:validateInputs??false};const isResume=!!(resume?.steps&&resume.steps.length>0);const run=isResume?await this.createRunAsync({runId:resume.runId}):await this.createRunAsync({runId});const nestedAbortCb=()=>{abort();};run.abortController.signal.addEventListener("abort",nestedAbortCb);abortSignal.addEventListener("abort",async()=>{run.abortController.signal.removeEventListener("abort",nestedAbortCb);await run.cancel();});const unwatchV2=run.watch(event=>{emitter.emit("nested-watch-v2",{event,workflowId:this.id});},"watch-v2");const unwatch=run.watch(event=>{emitter.emit("nested-watch",{event,workflowId:this.id,runId:run.runId,isResume:!!resume?.steps?.length});},"watch");if(runCount&&runCount>0&&resume?.steps?.length&&runtimeContext){runtimeContext.set("__mastraWorflowInputData",inputData);}const res=isResume?await run.resume({resumeData,step:resume.steps,runtimeContext,tracingContext,outputOptions:{includeState:true}}):await run.start({inputData,runtimeContext,tracingContext,writableStream:writer,initialState:state,outputOptions:{includeState:true}});unwatch();unwatchV2();const suspendedSteps=Object.entries(res.steps).filter(([_stepName,stepResult])=>{const stepRes=stepResult;return stepRes?.status==="suspended";});if(res.state){setState(res.state);}if(suspendedSteps?.length){for(const[stepName,stepResult]of suspendedSteps){const suspendPath=[stepName,...(stepResult?.suspendPayload?.__workflow_meta?.path??[])];await suspend({...stepResult?.suspendPayload,__workflow_meta:{runId:run.runId,path:suspendPath}});}}if(res.status==="failed"){throw res.error;}return res.status==="success"?res.result:void 0;}async getWorkflowRuns(args){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow runs. Mastra storage is not initialized");return {runs:[],total:0};}return storage.getWorkflowRuns({workflowName:this.id,...(args??{})});}async getWorkflowRunById(runId){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow runs from storage. Mastra storage is not initialized");return this.#runs.get(runId)?{...this.#runs.get(runId),workflowName:this.id}:null;}const run=await storage.getWorkflowRunById({runId,workflowName:this.id});return run??(this.#runs.get(runId)?{...this.#runs.get(runId),workflowName:this.id}:null);}async getWorkflowRunSteps({runId,workflowId}){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow run steps. Mastra storage is not initialized");return {};}const run=await storage.getWorkflowRunById({runId,workflowName:workflowId});let snapshot=run?.snapshot;if(!snapshot){return {};}if(typeof snapshot==="string"){try{snapshot=JSON.parse(snapshot);}catch(e){this.logger.debug("Cannot get workflow run execution result. Snapshot is not a valid JSON string",e);return {};}}const{serializedStepGraph,context}=snapshot;const{input,...steps}=context;let finalSteps={};for(const step of Object.keys(steps)){const stepGraph=serializedStepGraph.find(stepGraph2=>stepGraph2?.step?.id===step);finalSteps[step]=steps[step];if(stepGraph&&stepGraph?.step?.component==="WORKFLOW"){const nestedSteps=await this.getWorkflowRunSteps({runId,workflowId:step});if(nestedSteps){const updatedNestedSteps=Object.entries(nestedSteps).reduce((acc,[key,value])=>{acc[`${step}.${key}`]=value;return acc;},{});finalSteps={...finalSteps,...updatedNestedSteps};}}}return finalSteps;}async getWorkflowRunExecutionResult(runId,withNestedWorkflows=true){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow run execution result. Mastra storage is not initialized");return null;}const run=await storage.getWorkflowRunById({runId,workflowName:this.id});let snapshot=run?.snapshot;if(!snapshot){return null;}if(typeof snapshot==="string"){try{snapshot=JSON.parse(snapshot);}catch(e){this.logger.debug("Cannot get workflow run execution result. Snapshot is not a valid JSON string",e);return null;}}const fullSteps=withNestedWorkflows?await this.getWorkflowRunSteps({runId,workflowId:this.id}):snapshot.context;return {status:snapshot.status,result:snapshot.result,error:snapshot.error,payload:snapshot.context?.input,steps:fullSteps};}};var Run=class{#abortController;emitter;/**
|
|
313
|
+
async execute({runId,inputData,resumeData,state,setState,suspend,resume,[EMITTER_SYMBOL]:emitter,mastra,runtimeContext,abort,abortSignal,runCount,tracingContext,writer,validateInputs}){this.__registerMastra(mastra);if(validateInputs){this.#options={...(this.#options||{}),validateInputs};}this.executionEngine.options={...(this.executionEngine.options||{}),validateInputs:validateInputs??false};const isResume=!!(resume?.steps&&resume.steps.length>0)||!!resume?.label;const run=isResume?await this.createRunAsync({runId:resume.runId}):await this.createRunAsync({runId});const nestedAbortCb=()=>{abort();};run.abortController.signal.addEventListener("abort",nestedAbortCb);abortSignal.addEventListener("abort",async()=>{run.abortController.signal.removeEventListener("abort",nestedAbortCb);await run.cancel();});const unwatchV2=run.watch(event=>{emitter.emit("nested-watch-v2",{event,workflowId:this.id});},"watch-v2");const unwatch=run.watch(event=>{emitter.emit("nested-watch",{event,workflowId:this.id,runId:run.runId,isResume:!!resume?.steps?.length});},"watch");if(runCount&&runCount>0&&resume?.steps?.length&&runtimeContext){runtimeContext.set("__mastraWorflowInputData",inputData);}const res=isResume?await run.resume({resumeData,step:resume.steps,runtimeContext,tracingContext,outputOptions:{includeState:true,includeResumeLabels:true},label:resume.label}):await run.start({inputData,runtimeContext,tracingContext,writableStream:writer,initialState:state,outputOptions:{includeState:true,includeResumeLabels:true}});unwatch();unwatchV2();const suspendedSteps=Object.entries(res.steps).filter(([_stepName,stepResult])=>{const stepRes=stepResult;return stepRes?.status==="suspended";});if(res.state){setState(res.state);}if(suspendedSteps?.length){for(const[stepName,stepResult]of suspendedSteps){const suspendPath=[stepName,...(stepResult?.suspendPayload?.__workflow_meta?.path??[])];await suspend({...stepResult?.suspendPayload,__workflow_meta:{runId:run.runId,path:suspendPath}},{resumeLabel:Object.keys(res.resumeLabels??{})});}}if(res.status==="failed"){throw res.error;}return res.status==="success"?res.result:void 0;}async getWorkflowRuns(args){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow runs. Mastra storage is not initialized");return {runs:[],total:0};}return storage.getWorkflowRuns({workflowName:this.id,...(args??{})});}async getWorkflowRunById(runId){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow runs from storage. Mastra storage is not initialized");return this.#runs.get(runId)?{...this.#runs.get(runId),workflowName:this.id}:null;}const run=await storage.getWorkflowRunById({runId,workflowName:this.id});return run??(this.#runs.get(runId)?{...this.#runs.get(runId),workflowName:this.id}:null);}async getWorkflowRunSteps({runId,workflowId}){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow run steps. Mastra storage is not initialized");return {};}const run=await storage.getWorkflowRunById({runId,workflowName:workflowId});let snapshot=run?.snapshot;if(!snapshot){return {};}if(typeof snapshot==="string"){try{snapshot=JSON.parse(snapshot);}catch(e){this.logger.debug("Cannot get workflow run execution result. Snapshot is not a valid JSON string",e);return {};}}const{serializedStepGraph,context}=snapshot;const{input,...steps}=context;let finalSteps={};for(const step of Object.keys(steps)){const stepGraph=serializedStepGraph.find(stepGraph2=>stepGraph2?.step?.id===step);finalSteps[step]=steps[step];if(stepGraph&&stepGraph?.step?.component==="WORKFLOW"){const nestedSteps=await this.getWorkflowRunSteps({runId,workflowId:step});if(nestedSteps){const updatedNestedSteps=Object.entries(nestedSteps).reduce((acc,[key,value])=>{acc[`${step}.${key}`]=value;return acc;},{});finalSteps={...finalSteps,...updatedNestedSteps};}}}return finalSteps;}async getWorkflowRunExecutionResult(runId,withNestedWorkflows=true){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow run execution result. Mastra storage is not initialized");return null;}const run=await storage.getWorkflowRunById({runId,workflowName:this.id});let snapshot=run?.snapshot;if(!snapshot){return null;}if(typeof snapshot==="string"){try{snapshot=JSON.parse(snapshot);}catch(e){this.logger.debug("Cannot get workflow run execution result. Snapshot is not a valid JSON string",e);return null;}}const fullSteps=withNestedWorkflows?await this.getWorkflowRunSteps({runId,workflowId:this.id}):snapshot.context;return {status:snapshot.status,result:snapshot.result,error:snapshot.error,payload:snapshot.context?.input,steps:fullSteps};}};var Run=class{#abortController;emitter;/**
|
|
315
314
|
* Unique identifier for this workflow
|
|
316
315
|
*/workflowId;/**
|
|
317
316
|
* Unique identifier for this run
|
|
@@ -370,8 +369,8 @@ async execute({runId,inputData,resumeData,state,setState,suspend,resume,[EMITTER
|
|
|
370
369
|
* Resumes the workflow execution with the provided input as a stream
|
|
371
370
|
* @param input The input data for the workflow
|
|
372
371
|
* @returns A promise that resolves to the workflow output
|
|
373
|
-
*/resumeStreamVNext({step,resumeData,runtimeContext,tracingContext,tracingOptions}={}){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});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
|
|
374
|
-
resumePath:snapshot?.suspendedPaths?.[steps?.[0]]},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;});}/**
|
|
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&¶ms.runCount>0&¶ms.runtimeContext){runtimeContextInput=params.runtimeContext.get("__mastraWorflowInputData");params.runtimeContext.delete("__mastraWorflowInputData");}const stepResults={...(snapshot?.context??{}),input:runtimeContextInput??snapshot?.context?.input};let runtimeContextToUse=params.runtimeContext??new 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;});}/**
|
|
375
374
|
* Returns the current state of the workflow run
|
|
376
375
|
* @returns The current state of the workflow run
|
|
377
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??{});}}/**
|
|
@@ -405,7 +404,7 @@ var AISDKV5InputStream=class extends MastraModelInput{constructor({component,nam
|
|
|
405
404
|
function omit(obj,keys){const newObj={...obj};for(const key of keys){delete newObj[key];}return newObj;}var hasLoggedModelSettingsAbortSignalDeprecation=false;function execute({runId,model,providerOptions,inputMessages,tools,toolChoice,options,onResult,modelStreamSpan,telemetry_settings,includeRawChunks,modelSettings,structuredOutput,headers,shouldThrowError}){if(modelSettings?.abortSignal&&!hasLoggedModelSettingsAbortSignalDeprecation){console.warn("[Deprecation Warning] Using `modelSettings.abortSignal` is deprecated. Please use top-level `abortSignal` instead. The `modelSettings.abortSignal` option will be removed in a future version.");hasLoggedModelSettingsAbortSignalDeprecation=true;}const v5=new AISDKV5InputStream({component:"LLM",name:model.modelId});const toolsAndToolChoice=prepareToolsAndToolChoice({tools,toolChoice,activeTools:options?.activeTools});if(modelStreamSpan&&toolsAndToolChoice?.tools?.length&&telemetry_settings?.recordOutputs!==false){modelStreamSpan.setAttributes({"stream.prompt.tools":toolsAndToolChoice?.tools?.map(tool=>JSON.stringify(tool))});}const structuredOutputMode=structuredOutput?.schema?structuredOutput?.model?"processor":"direct":void 0;const responseFormat=structuredOutput?.schema?getResponseFormat(structuredOutput?.schema):void 0;let prompt=inputMessages;if(structuredOutputMode==="direct"&&responseFormat?.type==="json"&&structuredOutput?.jsonPromptInjection){prompt=injectJsonInstructionIntoMessages({messages:inputMessages,schema:responseFormat.schema});}if(structuredOutputMode==="processor"&&responseFormat?.type==="json"&&responseFormat?.schema){prompt=injectJsonInstructionIntoMessages({messages:inputMessages,schema:responseFormat.schema,schemaPrefix:`Your response will be processed by another agent to extract structured data. Please ensure your response contains comprehensive information for all the following fields that will be extracted:
|
|
406
405
|
`,schemaSuffix:`
|
|
407
406
|
|
|
408
|
-
You don't need to format your response as JSON unless the user asks you to. Just ensure your natural language response includes relevant information for each field in the schema above.`});}const providerOptionsToUse=model.provider.startsWith("openai")&&responseFormat?.type==="json"&&!structuredOutput?.jsonPromptInjection?{...(providerOptions??{}),openai:{strictJsonSchema:true,...(providerOptions?.openai??{})}}:providerOptions;const stream=v5.initialize({runId,onResult,createStream:async()=>{try{const filteredModelSettings=omit(modelSettings||{},["maxRetries","headers","abortSignal"]);const abortSignal=options?.abortSignal||modelSettings?.abortSignal;const pRetry=await import('p-retry');return await pRetry.default(async()=>{const streamResult=await model.doStream({...toolsAndToolChoice,prompt,providerOptions:providerOptionsToUse,abortSignal,includeRawChunks,responseFormat:structuredOutputMode==="direct"&&!structuredOutput?.jsonPromptInjection?responseFormat:void 0,...filteredModelSettings,headers});return streamResult;},{retries:modelSettings?.maxRetries??2,signal:abortSignal
|
|
407
|
+
You don't need to format your response as JSON unless the user asks you to. Just ensure your natural language response includes relevant information for each field in the schema above.`});}const providerOptionsToUse=model.provider.startsWith("openai")&&responseFormat?.type==="json"&&!structuredOutput?.jsonPromptInjection?{...(providerOptions??{}),openai:{strictJsonSchema:true,...(providerOptions?.openai??{})}}:providerOptions;const stream=v5.initialize({runId,onResult,createStream:async()=>{try{const filteredModelSettings=omit(modelSettings||{},["maxRetries","headers","abortSignal"]);const abortSignal=options?.abortSignal||modelSettings?.abortSignal;const pRetry=await import('p-retry');return await pRetry.default(async()=>{const streamResult=await model.doStream({...toolsAndToolChoice,prompt,providerOptions:providerOptionsToUse,abortSignal,includeRawChunks,responseFormat:structuredOutputMode==="direct"&&!structuredOutput?.jsonPromptInjection?responseFormat:void 0,...filteredModelSettings,headers});return streamResult;},{retries:modelSettings?.maxRetries??2,signal:abortSignal,shouldRetry(context){if(APICallError.isInstance(context.error)){return context.error.isRetryable;}return true;}});}catch(error){const abortSignal=options?.abortSignal||modelSettings?.abortSignal;if(isAbortError(error)&&abortSignal?.aborted){console.error("Abort error",error);}if(shouldThrowError){throw error;}return {stream:new ReadableStream({start:async controller=>{controller.enqueue({type:"error",error});controller.close();}}),warnings:[],request:{},rawResponse:{}};}}});return stream;}// src/stream/aisdk/v5/output-helpers.ts
|
|
409
408
|
var DefaultStepResult=class{content;finishReason;usage;warnings;request;response;providerMetadata;constructor({content,finishReason,usage,warnings,request,response,providerMetadata}){this.content=content;this.finishReason=finishReason;this.usage=usage;this.warnings=warnings;this.request=request;this.response=response;this.providerMetadata=providerMetadata;}get text(){return this.content.filter(part=>part.type==="text").map(part=>part.text).join("");}get reasoning(){return this.content.filter(part=>part.type==="reasoning");}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(part=>part.text).join("");}get files(){return this.content.filter(part=>part.type==="file").map(part=>part.file);}get sources(){return this.content.filter(part=>part.type==="source");}get toolCalls(){return this.content.filter(part=>part.type==="tool-call");}get staticToolCalls(){return this.toolCalls.filter(toolCall=>toolCall.dynamic===false);}get dynamicToolCalls(){return this.toolCalls.filter(toolCall=>toolCall.dynamic===true);}get toolResults(){return this.content.filter(part=>part.type==="tool-result");}get staticToolResults(){return this.toolResults.filter(toolResult=>toolResult.dynamic===false);}get dynamicToolResults(){return this.toolResults.filter(toolResult=>toolResult.dynamic===true);}};// src/loop/workflows/run-state.ts
|
|
410
409
|
var AgenticRunState=class{#state;constructor({_internal,model}){this.#state={responseMetadata:{id:_internal?.generateId?.(),timestamp:_internal?.currentDate?.(),modelId:model.modelId,modelVersion:model.specificationVersion,modelProvider:model.provider,headers:void 0},modelMetadata:{modelId:model.modelId,modelVersion:model.specificationVersion,modelProvider:model.provider},isReasoning:false,isStreaming:false,providerOptions:void 0,hasToolCallStreaming:false,hasErrored:false,reasoningDeltas:[],textDeltas:[],stepResult:void 0};}setState(state){this.#state={...this.#state,...state};}get state(){return this.#state;}};// src/loop/workflows/agentic-execution/llm-execution-step.ts
|
|
411
410
|
async function processOutputStream({tools,messageId,messageList,outputStream,runState,options,controller,responseFromModel,includeRawChunks}){for await(const chunk of outputStream._getBaseStream()){if(!chunk){continue;}if(chunk.type=="object"||chunk.type=="object-result"){controller.enqueue(chunk);continue;}if(chunk.type!=="text-delta"&&chunk.type!=="tool-call"&&// not 100% sure about this being the right fix.
|
|
@@ -416,10 +415,10 @@ async function processOutputStream({tools,messageId,messageList,outputStream,run
|
|
|
416
415
|
// BUT does this cause other issues?
|
|
417
416
|
// Alternative solution: in message list allow combining text deltas together when the message source is "response" and the text parts are directly next to each other
|
|
418
417
|
// simple solution for now is to not flush text deltas on response-metadata
|
|
419
|
-
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(error){console.error("Error calling onInputStart",error);}}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(error){console.error("Error calling onInputDelta",error);}}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"}});let e=chunk.payload.error;if(typeof e==="object"){const errorMessage=safeParseErrorObject(e);const originalCause=e instanceof Error?e.cause:void 0;e=new Error(errorMessage,originalCause?{cause:originalCause}:void 0);Object.assign(e,chunk.payload.error);}controller.enqueue({...chunk,payload:{...chunk.payload,error:e}});await options?.onError?.({error:e});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
|
|
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
|
|
420
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
|
|
421
|
-
function createToolCallStep({tools,messageList,options,telemetry_settings,writer,
|
|
422
|
-
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()});},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
|
|
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
|
|
423
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
|
|
424
423
|
// VNext execution as internal
|
|
425
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
|
|
@@ -429,10 +428,10 @@ function createAgenticLoopWorkflow(params){const{models,_internal,messageId,runI
|
|
|
429
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
|
|
430
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
|
|
431
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
|
|
432
|
-
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,...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,
|
|
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
|
|
433
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
|
|
434
|
-
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 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}}});return createDestructurableOutput(modelOutput);}// src/llm/model/model.loop.ts
|
|
435
|
-
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}){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:"
|
|
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
|
|
436
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
|
|
437
436
|
var PRIMITIVE_TYPES=z9.enum(["agent","workflow","none","tool"]);// src/loop/network/index.ts
|
|
438
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=`
|
|
@@ -685,9 +684,9 @@ the following messages are from ${ymd}
|
|
|
685
684
|
`)??void 0;const processedMemoryMessages=await memory.processMessages({messages:messageList.get.remembered.v1(),newMessages:messageList.get.input.v1(),systemMessage,memorySystemMessage:memorySystemMessage||void 0});const processedList=new MessageList({threadId:threadObject.id,resourceId,generateMessageId:capabilities.generateMessageId,// @ts-ignore Flag for agent network messages
|
|
686
685
|
_agentNetworkAppend:capabilities._agentNetworkAppend});addSystemMessage(processedList,instructions);processedList.addSystem(memorySystemMessage).addSystem(systemMessages).add(options.context||[],"context");addSystemMessage(processedList,options.system,"user-provided");processedList.add(processedMemoryMessages,"memory").add(messageList.get.input.v2(),"user");return {thread:threadObject,messageList:processedList,...(tripwireTriggered&&{tripwire:true,tripwireReason}),threadExists:!!existingThread};}});}// src/agent/workflows/prepare-stream/prepare-tools-step.ts
|
|
687
686
|
function createPrepareToolsStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,memory}){return createStep({id:"prepare-tools-step",inputSchema:z.object({}),outputSchema:prepareToolsStepOutputSchema,execute:async()=>{const toolEnhancements=[options?.toolsets&&Object.keys(options?.toolsets||{}).length>0?`toolsets present (${Object.keys(options?.toolsets||{}).length} tools)`:void 0,memory&&resourceId?"memory and resourceId available":void 0].filter(Boolean).join(", ");capabilities.logger.debug(`[Agent:${capabilities.agentName}] - Enhancing tools: ${toolEnhancements}`,{runId,toolsets:options?.toolsets?Object.keys(options?.toolsets):void 0,clientTools:options?.clientTools?Object.keys(options?.clientTools):void 0,hasMemory:!!memory,hasResourceId:!!resourceId});const threadId=threadFromArgs?.id;const convertedTools=await capabilities.convertTools({toolsets:options?.toolsets,clientTools:options?.clientTools,threadId,resourceId,runId,runtimeContext,tracingContext:{currentSpan:agentAISpan},writableStream:options.writableStream,methodType});return {convertedTools};}});}// src/agent/workflows/prepare-stream/stream-step.ts
|
|
688
|
-
function createStreamStep({capabilities,runId,returnScorerData,format="mastra",requireToolApproval,resumeContext,agentId}){return createStep({id:"stream-text-step",inputSchema:z.any(),// tried to type this in various ways but it's too complex
|
|
689
|
-
outputSchema:z.union([z.instanceof(MastraModelOutput),z.instanceof(AISDKV5OutputStream)]),execute:async({inputData,tracingContext})=>{const validatedInputData=inputData;capabilities.logger.debug(`Starting agent ${capabilities.agentName} llm stream call`,{runId});const processors=validatedInputData.outputProcessors||(capabilities.outputProcessors?typeof capabilities.outputProcessors==="function"?await capabilities.outputProcessors({runtimeContext:validatedInputData.runtimeContext||new RuntimeContext()}):capabilities.outputProcessors:[]);const streamResult=capabilities.llm.stream({...validatedInputData,outputProcessors:processors,returnScorerData,tracingContext,requireToolApproval,resumeContext,_internal:{generateId:capabilities.generateMessageId},agentId});if(format==="aisdk"){return streamResult.aisdk.v5;}return streamResult;}});}// src/agent/workflows/prepare-stream/index.ts
|
|
690
|
-
function createPrepareStreamWorkflow({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,format,instructions,memoryConfig,memory,saveQueueManager,returnScorerData,requireToolApproval,resumeContext,agentId}){const prepareToolsStep=createPrepareToolsStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,memory});const prepareMemoryStep2=createPrepareMemoryStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,instructions,memoryConfig,memory});const streamStep=createStreamStep({capabilities,runId,returnScorerData,format,requireToolApproval,resumeContext,agentId});const mapResultsStep=createMapResultsStep({capabilities,options,resourceId,runId,runtimeContext,memory,memoryConfig,saveQueueManager,agentAISpan,instructions,agentId});return createWorkflow({id:"execution-workflow",inputSchema:z.object({}),outputSchema:z.union([z.instanceof(MastraModelOutput),z.instanceof(AISDKV5OutputStream)]),steps:[prepareToolsStep,prepareMemoryStep2,streamStep],options:{tracingPolicy:{internal:1/* WORKFLOW */}}}).parallel([prepareToolsStep,prepareMemoryStep2]).map(mapResultsStep).then(streamStep).commit();}// src/agent/agent.ts
|
|
687
|
+
function createStreamStep({capabilities,runId,returnScorerData,format="mastra",requireToolApproval,resumeContext,agentId,toolCallId}){return createStep({id:"stream-text-step",inputSchema:z.any(),// tried to type this in various ways but it's too complex
|
|
688
|
+
outputSchema:z.union([z.instanceof(MastraModelOutput),z.instanceof(AISDKV5OutputStream)]),execute:async({inputData,tracingContext})=>{const validatedInputData=inputData;capabilities.logger.debug(`Starting agent ${capabilities.agentName} llm stream call`,{runId});const processors=validatedInputData.outputProcessors||(capabilities.outputProcessors?typeof capabilities.outputProcessors==="function"?await capabilities.outputProcessors({runtimeContext:validatedInputData.runtimeContext||new RuntimeContext()}):capabilities.outputProcessors:[]);const streamResult=capabilities.llm.stream({...validatedInputData,outputProcessors:processors,returnScorerData,tracingContext,requireToolApproval,resumeContext,_internal:{generateId:capabilities.generateMessageId},agentId,toolCallId});if(format==="aisdk"){return streamResult.aisdk.v5;}return streamResult;}});}// src/agent/workflows/prepare-stream/index.ts
|
|
689
|
+
function createPrepareStreamWorkflow({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,format,instructions,memoryConfig,memory,saveQueueManager,returnScorerData,requireToolApproval,resumeContext,agentId,toolCallId}){const prepareToolsStep=createPrepareToolsStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,memory});const prepareMemoryStep2=createPrepareMemoryStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,instructions,memoryConfig,memory});const streamStep=createStreamStep({capabilities,runId,returnScorerData,format,requireToolApproval,resumeContext,agentId,toolCallId});const mapResultsStep=createMapResultsStep({capabilities,options,resourceId,runId,runtimeContext,memory,memoryConfig,saveQueueManager,agentAISpan,instructions,agentId});return createWorkflow({id:"execution-workflow",inputSchema:z.object({}),outputSchema:z.union([z.instanceof(MastraModelOutput),z.instanceof(AISDKV5OutputStream)]),steps:[prepareToolsStep,prepareMemoryStep2,streamStep],options:{tracingPolicy:{internal:1/* WORKFLOW */}}}).parallel([prepareToolsStep,prepareMemoryStep2]).map(mapResultsStep).then(streamStep).commit();}// src/agent/agent.ts
|
|
691
690
|
function resolveMaybePromise(value,cb){if(value instanceof Promise){return value.then(cb);}return cb(value);}function resolveThreadIdFromArgs(args){if(args?.memory?.thread){if(typeof args.memory.thread==="string")return {id:args.memory.thread};if(typeof args.memory.thread==="object"&&args.memory.thread.id)return args.memory.thread;}if(args?.threadId)return {id:args.threadId};return void 0;}var _Agent_decorators,_init,_a;_Agent_decorators=[InstrumentClass({prefix:"agent",excludeMethods:["hasOwnMemory","getMemory","__primitive","__registerMastra","__registerPrimitives","__runInputProcessors","__runOutputProcessors","_wrapToolsWithAITracing","getProcessorRunner","__setTools","__setLogger","__setTelemetry","log","listAgents","getModel","getInstructions","getTools","getLLM","getWorkflows","getDefaultGenerateOptions","getDefaultStreamOptions","getDescription","getScorers","getVoice"]})];var Agent=class extends(_a=MastraBase){id;name;#instructions;#description;model;maxRetries;#mastra;#memory;#workflows;#defaultGenerateOptions;#defaultStreamOptions;#defaultVNextStreamOptions;#tools;evals;#scorers;#agents;#voice;#inputProcessors;#outputProcessors;#options;// This flag is for agent network messages. We should change the agent network formatting and remove this flag after.
|
|
692
691
|
_agentNetworkAppend=false;/**
|
|
693
692
|
* Creates a new Agent instance with the specified configuration.
|
|
@@ -967,7 +966,7 @@ _agentNetworkAppend:this._agentNetworkAppend}).add(result.response.messages,"res
|
|
|
967
966
|
*/#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions){let finalOnFinish=streamOptions?.onFinish||defaultStreamOptions.onFinish;if(streamOptions?.onFinish&&streamOptions.onFinish.__hasOriginalOnFinish===false&&defaultStreamOptions.onFinish){const telemetryWrapper=streamOptions.onFinish;const defaultCallback=defaultStreamOptions.onFinish;finalOnFinish=async data=>{await telemetryWrapper(data);await defaultCallback(data);};}return finalOnFinish;}/**
|
|
968
967
|
* Executes the agent with VNext execution model, handling tools, memory, and streaming.
|
|
969
968
|
* @internal
|
|
970
|
-
*/async#execute({methodType,format="mastra",resumeContext,...options}){const runtimeContext=options.runtimeContext||new RuntimeContext();const threadFromArgs=resolveThreadIdFromArgs({threadId:options.threadId,memory:options.memory});const resourceId=options.memory?.resource||options.resourceId;const memoryConfig=options.memory?.options;if(resourceId&&threadFromArgs&&!this.hasOwnMemory()){this.logger.warn(`[Agent:${this.name}] - No memory is configured but resourceId and threadId were passed in args. This will not work.`);}const llm=await this.getLLM({runtimeContext,model:options.model});const runId=options.runId||this.#mastra?.generateId()||randomUUID();const instructions=options.instructions||(await this.getInstructions({runtimeContext}));const agentAISpan=getOrCreateSpan({type:"agent_run"/* AGENT_RUN */,name:`agent run: '${this.id}'`,input:options.messages,attributes:{agentId:this.id,instructions:this.#convertInstructionsToString(instructions)},metadata:{runId,resourceId,threadId:threadFromArgs?.id},tracingPolicy:this.#options?.tracingPolicy,tracingOptions:options.tracingOptions,tracingContext:options.tracingContext,runtimeContext});const activeSpan=Telemetry.getActiveSpan();const baggageEntries={};if(threadFromArgs?.id){if(activeSpan){activeSpan.setAttribute("threadId",threadFromArgs.id);}baggageEntries.threadId={value:threadFromArgs.id};}if(resourceId){if(activeSpan){activeSpan.setAttribute("resourceId",resourceId);}baggageEntries.resourceId={value:resourceId};}if(Object.keys(baggageEntries).length>0){Telemetry.setBaggage(baggageEntries);}const memory=await this.getMemory({runtimeContext});const saveQueueManager=new SaveQueueManager({logger:this.logger,memory});if(process.env.NODE_ENV!=="test"){this.logger.debug(`[Agents:${this.name}] - Starting generation`,{runId});}const capabilities={agentName:this.name,logger:this.logger,getMemory:this.getMemory.bind(this),getModel:this.getModel.bind(this),generateMessageId:this.#mastra?.generateId?.bind(this.#mastra)||(()=>randomUUID()),_agentNetworkAppend:"_agentNetworkAppend"in this?Boolean(this._agentNetworkAppend):void 0,saveStepMessages:this.saveStepMessages.bind(this),convertTools:this.convertTools.bind(this),getMemoryMessages:this.getMemoryMessages.bind(this),runInputProcessors:this.__runInputProcessors.bind(this),executeOnFinish:this.#executeOnFinish.bind(this),outputProcessors:this.#outputProcessors,llm,getTelemetry:this.#mastra?.getTelemetry?.bind(this.#mastra)};const executionWorkflow=createPrepareStreamWorkflow({capabilities,options:{...options,methodType},threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,format,instructions,memoryConfig,memory,saveQueueManager,returnScorerData:options.returnScorerData,requireToolApproval:options.requireToolApproval,resumeContext,agentId:this.id});const run=await executionWorkflow.createRunAsync();const result=await run.start({tracingContext:{currentSpan:agentAISpan}});return result;}/**
|
|
969
|
+
*/async#execute({methodType,format="mastra",resumeContext,...options}){const existingSnapshot=resumeContext?.snapshot;let snapshotMemoryInfo;if(existingSnapshot){for(const key in existingSnapshot?.context){const step=existingSnapshot?.context[key];if(step&&step.status==="suspended"&&step.suspendPayload?.__streamState){snapshotMemoryInfo=step.suspendPayload?.__streamState?.messageList?.memoryInfo;break;}}}const runtimeContext=options.runtimeContext||new RuntimeContext();const threadFromArgs=resolveThreadIdFromArgs({threadId:options.threadId||snapshotMemoryInfo?.threadId,memory:options.memory});const resourceId=options.memory?.resource||options.resourceId||snapshotMemoryInfo?.resourceId;const memoryConfig=options.memory?.options;if(resourceId&&threadFromArgs&&!this.hasOwnMemory()){this.logger.warn(`[Agent:${this.name}] - No memory is configured but resourceId and threadId were passed in args. This will not work.`);}const llm=await this.getLLM({runtimeContext,model:options.model});const runId=options.runId||this.#mastra?.generateId()||randomUUID();const instructions=options.instructions||(await this.getInstructions({runtimeContext}));const agentAISpan=getOrCreateSpan({type:"agent_run"/* AGENT_RUN */,name:`agent run: '${this.id}'`,input:options.messages,attributes:{agentId:this.id,instructions:this.#convertInstructionsToString(instructions)},metadata:{runId,resourceId,threadId:threadFromArgs?.id},tracingPolicy:this.#options?.tracingPolicy,tracingOptions:options.tracingOptions,tracingContext:options.tracingContext,runtimeContext});const activeSpan=Telemetry.getActiveSpan();const baggageEntries={};if(threadFromArgs?.id){if(activeSpan){activeSpan.setAttribute("threadId",threadFromArgs.id);}baggageEntries.threadId={value:threadFromArgs.id};}if(resourceId){if(activeSpan){activeSpan.setAttribute("resourceId",resourceId);}baggageEntries.resourceId={value:resourceId};}if(Object.keys(baggageEntries).length>0){Telemetry.setBaggage(baggageEntries);}const memory=await this.getMemory({runtimeContext});const saveQueueManager=new SaveQueueManager({logger:this.logger,memory});if(process.env.NODE_ENV!=="test"){this.logger.debug(`[Agents:${this.name}] - Starting generation`,{runId});}const capabilities={agentName:this.name,logger:this.logger,getMemory:this.getMemory.bind(this),getModel:this.getModel.bind(this),generateMessageId:this.#mastra?.generateId?.bind(this.#mastra)||(()=>randomUUID()),_agentNetworkAppend:"_agentNetworkAppend"in this?Boolean(this._agentNetworkAppend):void 0,saveStepMessages:this.saveStepMessages.bind(this),convertTools:this.convertTools.bind(this),getMemoryMessages:this.getMemoryMessages.bind(this),runInputProcessors:this.__runInputProcessors.bind(this),executeOnFinish:this.#executeOnFinish.bind(this),outputProcessors:this.#outputProcessors,llm,getTelemetry:this.#mastra?.getTelemetry?.bind(this.#mastra)};const executionWorkflow=createPrepareStreamWorkflow({capabilities,options:{...options,methodType},threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,format,instructions,memoryConfig,memory,saveQueueManager,returnScorerData:options.returnScorerData,requireToolApproval:options.requireToolApproval,resumeContext,agentId:this.id,toolCallId:options.toolCallId});const run=await executionWorkflow.createRunAsync();const result=await run.start({tracingContext:{currentSpan:agentAISpan}});return result;}/**
|
|
971
970
|
* Handles post-execution tasks including memory persistence and title generation.
|
|
972
971
|
* @internal
|
|
973
972
|
*/async#executeOnFinish({result,instructions,readOnlyMemory,thread:threadAfter,threadId,resourceId,memoryConfig,outputText,runtimeContext,agentAISpan,runId,messageList,threadExists,structuredOutput=false,saveQueueManager,overrideScorers}){const resToLog={text:result.text,object:result.object,toolResults:result.toolResults,toolCalls:result.toolCalls,usage:result.usage,steps:result.steps.map(s=>{return {stepType:s.stepType,text:s.text,toolResults:s.toolResults,toolCalls:s.toolCalls,usage:s.usage};})};this.logger.debug(`[Agent:${this.name}] - Post processing LLM response`,{runId,result:resToLog,threadId,resourceId});const messageListResponses=messageList.get.response.aiV4.core();const usedWorkingMemory=messageListResponses.some(m=>m.role==="tool"&&m.content.some(c=>c.toolName==="updateWorkingMemory"));const memory=await this.getMemory({runtimeContext});const thread=usedWorkingMemory?threadId?await memory?.getThreadById({threadId}):void 0:threadAfter;if(memory&&resourceId&&thread&&!readOnlyMemory){try{let responseMessages=result.response.messages;if(!responseMessages&&result.object){responseMessages=[{id:result.response.id,role:"assistant",content:[{type:"text",text:outputText// outputText contains the stringified object
|
|
@@ -1009,7 +1008,7 @@ result.error);}throw new MastraError({id:"AGENT_STREAM_UNKNOWN_ERROR",domain:"AG
|
|
|
1009
1008
|
* { runId: 'previous-run-id' }
|
|
1010
1009
|
* );
|
|
1011
1010
|
* ```
|
|
1012
|
-
*/async
|
|
1011
|
+
*/async resumeStream(resumeData,streamOptions){const defaultStreamOptions=await this.getDefaultVNextStreamOptions({runtimeContext:streamOptions?.runtimeContext});let mergedStreamOptions={...defaultStreamOptions,...streamOptions,onFinish:this.#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions)};const llm=await this.getLLM({runtimeContext:mergedStreamOptions.runtimeContext});if(llm.getModel().specificationVersion!=="v2"){throw new MastraError({id:"AGENT_STREAM_VNEXT_V1_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"V1 models are not supported for stream. Please use streamLegacy instead."});}const existingSnapshot=await this.#mastra?.getStorage()?.loadWorkflowSnapshot({workflowName:"agentic-loop",runId:streamOptions?.runId??""});const result=await this.#execute({...mergedStreamOptions,messages:[],resumeContext:{resumeData,snapshot:existingSnapshot},methodType:"stream"});if(result.status!=="success"){if(result.status==="failed"){throw new MastraError({id:"AGENT_STREAM_VNEXT_FAILED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */},// pass original error to preserve stack trace
|
|
1013
1012
|
result.error);}throw new MastraError({id:"AGENT_STREAM_VNEXT_UNKNOWN_ERROR",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"An unknown error occurred while streaming"});}return result.result;}/**
|
|
1014
1013
|
* Approves a pending tool call and resumes execution.
|
|
1015
1014
|
* Used when `requireToolApproval` is enabled to allow the agent to proceed with a tool call.
|
|
@@ -1024,7 +1023,7 @@ result.error);}throw new MastraError({id:"AGENT_STREAM_VNEXT_UNKNOWN_ERROR",doma
|
|
|
1024
1023
|
* console.log(chunk);
|
|
1025
1024
|
* }
|
|
1026
1025
|
* ```
|
|
1027
|
-
*/async approveToolCall(options){return this.
|
|
1026
|
+
*/async approveToolCall(options){return this.resumeStream({approved:true},options);}/**
|
|
1028
1027
|
* Declines a pending tool call and resumes execution.
|
|
1029
1028
|
* Used when `requireToolApproval` is enabled to prevent the agent from executing a tool call.
|
|
1030
1029
|
*
|
|
@@ -1038,7 +1037,7 @@ result.error);}throw new MastraError({id:"AGENT_STREAM_VNEXT_UNKNOWN_ERROR",doma
|
|
|
1038
1037
|
* console.log(chunk);
|
|
1039
1038
|
* }
|
|
1040
1039
|
* ```
|
|
1041
|
-
*/async declineToolCall(options){return this.
|
|
1040
|
+
*/async declineToolCall(options){return this.resumeStream({approved:false},options);}async generateLegacy(messages,generateOptions={}){if("structuredOutput"in generateOptions&&generateOptions.structuredOutput){throw new MastraError({id:"AGENT_GENERATE_LEGACY_STRUCTURED_OUTPUT_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"This method does not support structured output. Please use generateVNext instead."});}const defaultGenerateOptions=await this.getDefaultGenerateOptions({runtimeContext:generateOptions.runtimeContext});const mergedGenerateOptions={...defaultGenerateOptions,...generateOptions,experimental_generateMessageId:defaultGenerateOptions.experimental_generateMessageId||this.#mastra?.generateId?.bind(this.#mastra)};const{llm,before,after}=await this.prepareLLMOptions(messages,mergedGenerateOptions,"generate");if(llm.getModel().specificationVersion!=="v1"){this.logger.error("V2 models are not supported for generateLegacy. Please use generate instead.",{modelId:llm.getModel().modelId});throw new MastraError({id:"AGENT_GENERATE_V2_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{modelId:llm.getModel().modelId},text:"V2 models are not supported for generateLegacy. Please use generate instead."});}let llmToUse=llm;const beforeResult=await before();const traceId=getValidTraceId(beforeResult.agentAISpan);if(beforeResult.tripwire){const tripwireResult={text:"",object:void 0,usage:{totalTokens:0,promptTokens:0,completionTokens:0},finishReason:"other",response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},responseMessages:[],toolCalls:[],toolResults:[],warnings:void 0,request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,tripwire:true,tripwireReason:beforeResult.tripwireReason,traceId};return tripwireResult;}const{experimental_output,output,agentAISpan,...llmOptions}=beforeResult;const tracingContext={currentSpan:agentAISpan};let finalOutputProcessors=mergedGenerateOptions.outputProcessors;if(!output||experimental_output){const result2=await llmToUse.__text({...llmOptions,tracingContext,experimental_output});const outputProcessorResult2=await this.__runOutputProcessors({runtimeContext:mergedGenerateOptions.runtimeContext||new RuntimeContext(),tracingContext,outputProcessorOverrides:finalOutputProcessors,messageList:new MessageList({threadId:llmOptions.threadId||"",resourceId:llmOptions.resourceId||""}).add({role:"assistant",content:[{type:"text",text:result2.text}]},"response")});if(outputProcessorResult2.tripwireTriggered){const tripwireResult={text:"",object:void 0,usage:{totalTokens:0,promptTokens:0,completionTokens:0},finishReason:"other",response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},responseMessages:[],toolCalls:[],toolResults:[],warnings:void 0,request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,tripwire:true,tripwireReason:outputProcessorResult2.tripwireReason,traceId};return tripwireResult;}const newText2=outputProcessorResult2.messageList.get.response.v2().map(msg=>msg.content.parts.map(part=>part.type==="text"?part.text:"").join("")).join("");result2.text=newText2;if(finalOutputProcessors&&finalOutputProcessors.length>0){const messages2=outputProcessorResult2.messageList.get.response.v2();this.logger.debug("Checking messages for experimentalOutput metadata:",messages2.map(m=>({role:m.role,hasContentMetadata:!!m.content.metadata,contentMetadata:m.content.metadata})));const messagesWithStructuredData=messages2.filter(msg=>msg.content.metadata&&msg.content.metadata.structuredOutput);this.logger.debug("Messages with structured data:",messagesWithStructuredData.length);if(messagesWithStructuredData[0]&&messagesWithStructuredData[0].content.metadata?.structuredOutput){result2.object=messagesWithStructuredData[0].content.metadata.structuredOutput;this.logger.debug("Using structured data from processor metadata for result.object");}else {try{const processedOutput=JSON.parse(newText2);result2.object=processedOutput;this.logger.debug("Using fallback JSON parsing for result.object");}catch(error){this.logger.warn("Failed to parse processed output as JSON, updating text only",{error});}}}const overrideScorers=mergedGenerateOptions.scorers;const afterResult2=await after({result:result2,outputText:newText2,agentAISpan,...(overrideScorers?{overrideScorers}:{})});if(generateOptions.returnScorerData){result2.scoringData=afterResult2.scoringData;}result2.traceId=traceId;return result2;}const result=await llmToUse.__textObject({...llmOptions,tracingContext,structuredOutput:output});const outputText=JSON.stringify(result.object);const outputProcessorResult=await this.__runOutputProcessors({runtimeContext:mergedGenerateOptions.runtimeContext||new RuntimeContext(),tracingContext,messageList:new MessageList({threadId:llmOptions.threadId||"",resourceId:llmOptions.resourceId||""}).add({role:"assistant",content:[{type:"text",text:outputText}]},"response")});if(outputProcessorResult.tripwireTriggered){const tripwireResult={text:"",object:void 0,usage:{totalTokens:0,promptTokens:0,completionTokens:0},finishReason:"other",response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},responseMessages:[],toolCalls:[],toolResults:[],warnings:void 0,request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,tripwire:true,tripwireReason:outputProcessorResult.tripwireReason,traceId};return tripwireResult;}const newText=outputProcessorResult.messageList.get.response.v2().map(msg=>msg.content.parts.map(part=>part.type==="text"?part.text:"").join("")).join("");try{const processedObject=JSON.parse(newText);result.object=processedObject;}catch(error){this.logger.warn("Failed to parse processed output as JSON, keeping original result",{error});}const afterResult=await after({result,outputText:newText,...(generateOptions.scorers?{overrideScorers:generateOptions.scorers}:{}),structuredOutput:true,agentAISpan});if(generateOptions.returnScorerData){result.scoringData=afterResult.scoringData;}result.traceId=traceId;return result;}async streamLegacy(messages,streamOptions={}){const defaultStreamOptions=await this.getDefaultStreamOptions({runtimeContext:streamOptions.runtimeContext});const mergedStreamOptions={...defaultStreamOptions,...streamOptions,onFinish:this.#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions),experimental_generateMessageId:defaultStreamOptions.experimental_generateMessageId||this.#mastra?.generateId?.bind(this.#mastra)};const{llm,before,after}=await this.prepareLLMOptions(messages,mergedStreamOptions,"stream");if(llm.getModel().specificationVersion!=="v1"){this.logger.error("V2 models are not supported for streamLegacy. Please use stream instead.",{modelId:llm.getModel().modelId});throw new MastraError({id:"AGENT_STREAM_V2_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{modelId:llm.getModel().modelId},text:"V2 models are not supported for streamLegacy. Please use stream instead."});}const beforeResult=await before();const traceId=getValidTraceId(beforeResult.agentAISpan);if(beforeResult.tripwire){const emptyResult={textStream:async function*(){}(),fullStream:Promise.resolve("").then(()=>{const emptyStream=new globalThis.ReadableStream({start(controller){controller.close();}});return emptyStream;}),text:Promise.resolve(""),usage:Promise.resolve({totalTokens:0,promptTokens:0,completionTokens:0}),finishReason:Promise.resolve("other"),tripwire:true,tripwireReason:beforeResult.tripwireReason,response:{id:randomUUID(),timestamp:/* @__PURE__ */new Date(),modelId:"tripwire",messages:[]},toolCalls:Promise.resolve([]),toolResults:Promise.resolve([]),warnings:Promise.resolve(void 0),request:{body:JSON.stringify({messages:[]})},experimental_output:void 0,steps:void 0,experimental_providerMetadata:void 0,traceId,toAIStream:()=>Promise.resolve("").then(()=>{const emptyStream=new globalThis.ReadableStream({start(controller){controller.close();}});return emptyStream;}),get experimental_partialOutputStream(){return async function*(){}();},pipeDataStreamToResponse:()=>Promise.resolve(),pipeTextStreamToResponse:()=>Promise.resolve(),toDataStreamResponse:()=>new Response("",{status:200,headers:{"Content-Type":"text/plain"}}),toTextStreamResponse:()=>new Response("",{status:200,headers:{"Content-Type":"text/plain"}})};return emptyResult;}const{onFinish,runId,output,experimental_output,agentAISpan,...llmOptions}=beforeResult;const overrideScorers=mergedStreamOptions.scorers;const tracingContext={currentSpan:agentAISpan};if(!output||experimental_output){this.logger.debug(`Starting agent ${this.name} llm stream call`,{runId});const streamResult=llm.__stream({...llmOptions,experimental_output,tracingContext,outputProcessors:await this.getResolvedOutputProcessors(mergedStreamOptions.runtimeContext),onFinish:async result=>{try{const outputText=result.text;await after({result,outputText,agentAISpan,...(overrideScorers?{overrideScorers}:{})});}catch(e){this.logger.error("Error saving memory on finish",{error:e,runId});}await onFinish?.({...result,runId});},runId});streamResult.traceId=traceId;return streamResult;}this.logger.debug(`Starting agent ${this.name} llm streamObject call`,{runId});const streamObjectResult=llm.__streamObject({...llmOptions,tracingContext,onFinish:async result=>{try{const outputText=JSON.stringify(result.object);await after({result,outputText,structuredOutput:true,agentAISpan,...(overrideScorers?{overrideScorers}:{})});}catch(e){this.logger.error("Error saving memory on finish",{error:e,runId});}await onFinish?.({...result,runId});},runId,structuredOutput:output});streamObjectResult.traceId=traceId;return streamObjectResult;}/**
|
|
1042
1041
|
* Convert text to speech using the configured voice provider
|
|
1043
1042
|
* @param input Text or text stream to convert to speech
|
|
1044
1043
|
* @param options Speech options including speaker and provider-specific options
|
|
@@ -1127,11 +1126,11 @@ function createDestructurableOutput(output){return new Proxy(output,{get(target,
|
|
|
1127
1126
|
* The message list for this stream.
|
|
1128
1127
|
*/messageList;/**
|
|
1129
1128
|
* Trace ID used on the execution (if the execution was traced).
|
|
1130
|
-
*/traceId;messageId;constructor({model:_model,stream,messageList,options,messageId}){super({component:"LLM",name:"MastraModelOutput"});this.#options=options;this.#returnScorerData=!!options.returnScorerData;this.runId=options.runId;this.traceId=getValidTraceId(options.tracingContext?.currentSpan);this.#model=_model;this.messageId=messageId;if(options.structuredOutput?.schema){this.#structuredOutputMode=options.structuredOutput.model?"processor":"direct";}if(options.outputProcessors?.length){this.processorRunner=new ProcessorRunner({inputProcessors:[],outputProcessors:options.outputProcessors,logger:this.logger,agentName:"MastraModelOutput"});}this.messageList=messageList;const self=this;let processedStream=stream;const processorRunner=this.processorRunner;if(processorRunner&&options.isLLMExecutionStep){const processorStates=options.processorStates||/* @__PURE__ */new Map();processedStream=stream.pipeThrough(new TransformStream({async transform(chunk,controller){if(chunk.type==="finish"&&chunk.payload?.stepResult?.reason==="tool-calls"){controller.enqueue(chunk);return;}else {if(!processorStates.has(STRUCTURED_OUTPUT_PROCESSOR_NAME)){const processorIndex=processorRunner.outputProcessors.findIndex(p=>p.name===STRUCTURED_OUTPUT_PROCESSOR_NAME);if(processorIndex!==-1){const structuredOutputProcessorState=new ProcessorState({processorName:STRUCTURED_OUTPUT_PROCESSOR_NAME,tracingContext:options.tracingContext,processorIndex});structuredOutputProcessorState.customState={controller};processorStates.set(STRUCTURED_OUTPUT_PROCESSOR_NAME,structuredOutputProcessorState);}}else {const structuredOutputProcessorState=processorStates.get(STRUCTURED_OUTPUT_PROCESSOR_NAME);if(structuredOutputProcessorState){structuredOutputProcessorState.customState.controller=controller;}}const{part:processed,blocked,reason}=await processorRunner.processPart(chunk,processorStates,options.tracingContext);if(blocked){controller.enqueue({type:"tripwire",payload:{tripwireReason:reason||"Output processor blocked content"}});return;}if(processed){controller.enqueue(processed);}}}}));}if(self.#structuredOutputMode==="direct"&&self.#options.isLLMExecutionStep){processedStream=processedStream.pipeThrough(createObjectStreamTransformer({structuredOutput:self.#options.structuredOutput,logger:self.logger}));}this.#baseStream=processedStream.pipeThrough(new TransformStream({transform:async(chunk,controller)=>{switch(chunk.type){case "tool-call-suspended":case "tool-call-approval":self.#status="suspended";self.#delayedPromises.suspendPayload.resolve(chunk.payload);break;case "raw":if(!self.#options.includeRawChunks){return;}break;case "object-result":self.#bufferedObject=chunk.object;if(self.#delayedPromises.object.status.type==="pending"){self.#delayedPromises.object.resolve(chunk.object);}break;case "source":self.#bufferedSources.push(chunk);self.#bufferedByStep.sources.push(chunk);break;case "text-delta":self.#bufferedText.push(chunk.payload.text);self.#bufferedByStep.text+=chunk.payload.text;if(chunk.payload.id){const ary=self.#bufferedTextChunks[chunk.payload.id]??[];ary.push(chunk.payload.text);self.#bufferedTextChunks[chunk.payload.id]=ary;}break;case "tool-call-input-streaming-start":self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId]=chunk.payload.toolName;break;case "tool-call-delta":if(!self.#toolCallArgsDeltas[chunk.payload.toolCallId]){self.#toolCallArgsDeltas[chunk.payload.toolCallId]=[];}self.#toolCallArgsDeltas?.[chunk.payload.toolCallId]?.push(chunk.payload.argsTextDelta);chunk.payload.toolName||=self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId];break;case "file":self.#bufferedFiles.push(chunk);self.#bufferedByStep.files.push(chunk);break;case "reasoning-start":self.#bufferedReasoningDetails[chunk.payload.id]={type:"reasoning",runId:chunk.runId,from:chunk.from,payload:{id:chunk.payload.id,providerMetadata:chunk.payload.providerMetadata,text:""}};break;case "reasoning-delta":{self.#bufferedReasoning.push({type:"reasoning",runId:chunk.runId,from:chunk.from,payload:chunk.payload});self.#bufferedByStep.reasoning.push({type:"reasoning",runId:chunk.runId,from:chunk.from,payload:chunk.payload});const bufferedReasoning=self.#bufferedReasoningDetails[chunk.payload.id];if(bufferedReasoning){bufferedReasoning.payload.text+=chunk.payload.text;if(chunk.payload.providerMetadata){bufferedReasoning.payload.providerMetadata=chunk.payload.providerMetadata;}}break;}case "reasoning-end":{const bufferedReasoning=self.#bufferedReasoningDetails[chunk.payload.id];if(chunk.payload.providerMetadata&&bufferedReasoning){bufferedReasoning.payload.providerMetadata=chunk.payload.providerMetadata;}break;}case "tool-call":self.#toolCalls.push(chunk);self.#bufferedByStep.toolCalls.push(chunk);const toolCallPayload=chunk.payload;if(toolCallPayload?.output?.from==="AGENT"&&toolCallPayload?.output?.type==="finish"){const finishPayload=toolCallPayload.output.payload;if(finishPayload?.usage){self.updateUsageCount(finishPayload.usage);}}break;case "tool-result":self.#toolResults.push(chunk);self.#bufferedByStep.toolResults.push(chunk);break;case "step-finish":{self.updateUsageCount(chunk.payload.output.usage);self.#warnings=chunk.payload.stepResult.warnings||[];if(chunk.payload.metadata.request){self.#request=chunk.payload.metadata.request;}const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;const stepResult={stepType:self.#bufferedSteps.length===0?"initial":"tool-result",sources:self.#bufferedByStep.sources,files:self.#bufferedByStep.files,toolCalls:self.#bufferedByStep.toolCalls,toolResults:self.#bufferedByStep.toolResults,content:messageList.get.response.aiV5.modelContent(-1),text:self.#bufferedByStep.text,reasoningText:self.#bufferedReasoning.map(reasoningPart=>reasoningPart.payload.text).join(""),reasoning:Object.values(self.#bufferedReasoningDetails),get staticToolCalls(){return self.#bufferedByStep.toolCalls.filter(part=>part.type==="tool-call"&&part.payload?.dynamic===false);},get dynamicToolCalls(){return self.#bufferedByStep.toolCalls.filter(part=>part.type==="tool-call"&&part.payload?.dynamic===true);},get staticToolResults(){return self.#bufferedByStep.toolResults.filter(part=>part.type==="tool-result"&&part.payload?.dynamic===false);},get dynamicToolResults(){return self.#bufferedByStep.toolResults.filter(part=>part.type==="tool-result"&&part.payload?.dynamic===true);},finishReason:chunk.payload.stepResult.reason,usage:chunk.payload.output.usage,warnings:self.#warnings,request:request||{},response:{id:chunk.payload.id||"",timestamp:chunk.payload.metadata?.timestamp||/* @__PURE__ */new Date(),modelId:chunk.payload.metadata?.modelId||chunk.payload.metadata?.model||"",...otherMetadata,messages:chunk.payload.messages?.nonUser||[],// We have to cast this until messageList can take generics also and type metadata, it was too
|
|
1129
|
+
*/traceId;messageId;constructor({model:_model,stream,messageList,options,messageId,initialState}){super({component:"LLM",name:"MastraModelOutput"});this.#options=options;this.#returnScorerData=!!options.returnScorerData;this.runId=options.runId;this.traceId=getValidTraceId(options.tracingContext?.currentSpan);this.#model=_model;this.messageId=messageId;if(options.structuredOutput?.schema){this.#structuredOutputMode=options.structuredOutput.model?"processor":"direct";}if(options.outputProcessors?.length){this.processorRunner=new ProcessorRunner({inputProcessors:[],outputProcessors:options.outputProcessors,logger:this.logger,agentName:"MastraModelOutput"});}this.messageList=messageList;const self=this;let processedStream=stream;const processorRunner=this.processorRunner;if(processorRunner&&options.isLLMExecutionStep){const processorStates=options.processorStates||/* @__PURE__ */new Map();processedStream=stream.pipeThrough(new TransformStream({async transform(chunk,controller){if(chunk.type==="finish"&&chunk.payload?.stepResult?.reason==="tool-calls"){controller.enqueue(chunk);return;}else {if(!processorStates.has(STRUCTURED_OUTPUT_PROCESSOR_NAME)){const processorIndex=processorRunner.outputProcessors.findIndex(p=>p.name===STRUCTURED_OUTPUT_PROCESSOR_NAME);if(processorIndex!==-1){const structuredOutputProcessorState=new ProcessorState({processorName:STRUCTURED_OUTPUT_PROCESSOR_NAME,tracingContext:options.tracingContext,processorIndex});structuredOutputProcessorState.customState={controller};processorStates.set(STRUCTURED_OUTPUT_PROCESSOR_NAME,structuredOutputProcessorState);}}else {const structuredOutputProcessorState=processorStates.get(STRUCTURED_OUTPUT_PROCESSOR_NAME);if(structuredOutputProcessorState){structuredOutputProcessorState.customState.controller=controller;}}const{part:processed,blocked,reason}=await processorRunner.processPart(chunk,processorStates,options.tracingContext);if(blocked){controller.enqueue({type:"tripwire",payload:{tripwireReason:reason||"Output processor blocked content"}});return;}if(processed){controller.enqueue(processed);}}}}));}if(self.#structuredOutputMode==="direct"&&self.#options.isLLMExecutionStep){processedStream=processedStream.pipeThrough(createObjectStreamTransformer({structuredOutput:self.#options.structuredOutput,logger:self.logger}));}this.#baseStream=processedStream.pipeThrough(new TransformStream({transform:async(chunk,controller)=>{switch(chunk.type){case "tool-call-suspended":case "tool-call-approval":self.#status="suspended";self.#delayedPromises.suspendPayload.resolve(chunk.payload);break;case "raw":if(!self.#options.includeRawChunks){return;}break;case "object-result":self.#bufferedObject=chunk.object;if(self.#delayedPromises.object.status.type==="pending"){self.#delayedPromises.object.resolve(chunk.object);}break;case "source":self.#bufferedSources.push(chunk);self.#bufferedByStep.sources.push(chunk);break;case "text-delta":self.#bufferedText.push(chunk.payload.text);self.#bufferedByStep.text+=chunk.payload.text;if(chunk.payload.id){const ary=self.#bufferedTextChunks[chunk.payload.id]??[];ary.push(chunk.payload.text);self.#bufferedTextChunks[chunk.payload.id]=ary;}break;case "tool-call-input-streaming-start":self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId]=chunk.payload.toolName;break;case "tool-call-delta":if(!self.#toolCallArgsDeltas[chunk.payload.toolCallId]){self.#toolCallArgsDeltas[chunk.payload.toolCallId]=[];}self.#toolCallArgsDeltas?.[chunk.payload.toolCallId]?.push(chunk.payload.argsTextDelta);chunk.payload.toolName||=self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId];break;case "file":self.#bufferedFiles.push(chunk);self.#bufferedByStep.files.push(chunk);break;case "reasoning-start":self.#bufferedReasoningDetails[chunk.payload.id]={type:"reasoning",runId:chunk.runId,from:chunk.from,payload:{id:chunk.payload.id,providerMetadata:chunk.payload.providerMetadata,text:""}};break;case "reasoning-delta":{self.#bufferedReasoning.push({type:"reasoning",runId:chunk.runId,from:chunk.from,payload:chunk.payload});self.#bufferedByStep.reasoning.push({type:"reasoning",runId:chunk.runId,from:chunk.from,payload:chunk.payload});const bufferedReasoning=self.#bufferedReasoningDetails[chunk.payload.id];if(bufferedReasoning){bufferedReasoning.payload.text+=chunk.payload.text;if(chunk.payload.providerMetadata){bufferedReasoning.payload.providerMetadata=chunk.payload.providerMetadata;}}break;}case "reasoning-end":{const bufferedReasoning=self.#bufferedReasoningDetails[chunk.payload.id];if(chunk.payload.providerMetadata&&bufferedReasoning){bufferedReasoning.payload.providerMetadata=chunk.payload.providerMetadata;}break;}case "tool-call":self.#toolCalls.push(chunk);self.#bufferedByStep.toolCalls.push(chunk);const toolCallPayload=chunk.payload;if(toolCallPayload?.output?.from==="AGENT"&&toolCallPayload?.output?.type==="finish"){const finishPayload=toolCallPayload.output.payload;if(finishPayload?.usage){self.updateUsageCount(finishPayload.usage);}}break;case "tool-result":self.#toolResults.push(chunk);self.#bufferedByStep.toolResults.push(chunk);break;case "step-finish":{self.updateUsageCount(chunk.payload.output.usage);self.#warnings=chunk.payload.stepResult.warnings||[];if(chunk.payload.metadata.request){self.#request=chunk.payload.metadata.request;}const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;const stepResult={stepType:self.#bufferedSteps.length===0?"initial":"tool-result",sources:self.#bufferedByStep.sources,files:self.#bufferedByStep.files,toolCalls:self.#bufferedByStep.toolCalls,toolResults:self.#bufferedByStep.toolResults,content:messageList.get.response.aiV5.modelContent(-1),text:self.#bufferedByStep.text,reasoningText:self.#bufferedReasoning.map(reasoningPart=>reasoningPart.payload.text).join(""),reasoning:Object.values(self.#bufferedReasoningDetails),get staticToolCalls(){return self.#bufferedByStep.toolCalls.filter(part=>part.type==="tool-call"&&part.payload?.dynamic===false);},get dynamicToolCalls(){return self.#bufferedByStep.toolCalls.filter(part=>part.type==="tool-call"&&part.payload?.dynamic===true);},get staticToolResults(){return self.#bufferedByStep.toolResults.filter(part=>part.type==="tool-result"&&part.payload?.dynamic===false);},get dynamicToolResults(){return self.#bufferedByStep.toolResults.filter(part=>part.type==="tool-result"&&part.payload?.dynamic===true);},finishReason:chunk.payload.stepResult.reason,usage:chunk.payload.output.usage,warnings:self.#warnings,request:request||{},response:{id:chunk.payload.id||"",timestamp:chunk.payload.metadata?.timestamp||/* @__PURE__ */new Date(),modelId:chunk.payload.metadata?.modelId||chunk.payload.metadata?.model||"",...otherMetadata,messages:chunk.payload.messages?.nonUser||[],// We have to cast this until messageList can take generics also and type metadata, it was too
|
|
1131
1130
|
// complicated to do this in this PR, it will require a much bigger change.
|
|
1132
|
-
uiMessages:messageList.get.response.aiV5.ui()},providerMetadata};await options?.onStepFinish?.({...(self.#model.modelId&&self.#model.provider&&self.#model.version?{model:self.#model}:{}),...stepResult});self.#bufferedSteps.push(stepResult);self.#bufferedByStep={text:"",reasoning:[],sources:[],files:[],toolCalls:[],toolResults:[],dynamicToolCalls:[],dynamicToolResults:[],staticToolCalls:[],staticToolResults:[],content:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},warnings:[],request:{},response:{id:"",timestamp:/* @__PURE__ */new Date(),modelId:"",messages:[],uiMessages:[]},reasoningText:"",providerMetadata:void 0,finishReason:void 0};break;}case "tripwire":self.#tripwire=true;self.#tripwireReason=chunk.payload?.tripwireReason||"Content blocked";self.#finishReason="other";self.#streamFinished=true;self.#delayedPromises.text.resolve(self.#bufferedText.join(""));self.#delayedPromises.finishReason.resolve("other");self.#delayedPromises.object.resolve(void 0);self.#delayedPromises.usage.resolve(self.#usageCount);self.#delayedPromises.warnings.resolve(self.#warnings);self.#delayedPromises.providerMetadata.resolve(void 0);self.#delayedPromises.response.resolve({});self.#delayedPromises.request.resolve({});self.#delayedPromises.reasoning.resolve([]);self.#delayedPromises.reasoningText.resolve(void 0);self.#delayedPromises.sources.resolve([]);self.#delayedPromises.files.resolve([]);self.#delayedPromises.toolCalls.resolve([]);self.#delayedPromises.toolResults.resolve([]);self.#delayedPromises.steps.resolve(self.#bufferedSteps);self.#delayedPromises.totalUsage.resolve(self.#usageCount);self.#delayedPromises.content.resolve([]);self.#emitChunk(chunk);controller.enqueue(chunk);self.#emitter.emit("finish");controller.terminate();return;case "finish":self.#status="success";if(chunk.payload.stepResult.reason){self.#finishReason=chunk.payload.stepResult.reason;}if(self.#bufferedObject!==void 0){const responseMessages=messageList.get.response.v2();const lastAssistantMessage=[...responseMessages].reverse().find(m=>m.role==="assistant");if(lastAssistantMessage){if(!lastAssistantMessage.content.metadata){lastAssistantMessage.content.metadata={};}lastAssistantMessage.content.metadata.structuredOutput=self.#bufferedObject;}}let response={};if(chunk.payload.metadata){const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;response={...otherMetadata,messages:messageList.get.response.aiV5.model(),uiMessages:messageList.get.response.aiV5.ui()};}this.populateUsageCount(chunk.payload.output.usage);chunk.payload.output.usage={inputTokens:self.#usageCount.inputTokens??0,outputTokens:self.#usageCount.outputTokens??0,totalTokens:self.#usageCount.totalTokens??0,...(self.#usageCount.reasoningTokens!==void 0&&{reasoningTokens:self.#usageCount.reasoningTokens}),...(self.#usageCount.cachedInputTokens!==void 0&&{cachedInputTokens:self.#usageCount.cachedInputTokens})};try{if(self.processorRunner&&!self.#options.isLLMExecutionStep){self.messageList=await self.processorRunner.runOutputProcessors(self.messageList,options.tracingContext);const outputText=self.messageList.get.response.aiV4.core().map(m=>MessageList.coreContentToString(m.content)).join("\n");self.#delayedPromises.text.resolve(outputText);self.#delayedPromises.finishReason.resolve(self.#finishReason);if(chunk.payload.metadata){const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;response={...otherMetadata,messages:messageList.get.response.aiV5.model(),uiMessages:messageList.get.response.aiV5.ui()};}}else {const textContent=self.#bufferedText.join("");self.#delayedPromises.text.resolve(textContent);self.#delayedPromises.finishReason.resolve(self.#finishReason);}}catch(error2){if(error2 instanceof TripWire){self.#tripwire=true;self.#tripwireReason=error2.message;self.#delayedPromises.finishReason.resolve("other");self.#delayedPromises.text.resolve("");}else {self.#error=error2
|
|
1131
|
+
uiMessages:messageList.get.response.aiV5.ui()},providerMetadata};await options?.onStepFinish?.({...(self.#model.modelId&&self.#model.provider&&self.#model.version?{model:self.#model}:{}),...stepResult});self.#bufferedSteps.push(stepResult);self.#bufferedByStep={text:"",reasoning:[],sources:[],files:[],toolCalls:[],toolResults:[],dynamicToolCalls:[],dynamicToolResults:[],staticToolCalls:[],staticToolResults:[],content:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},warnings:[],request:{},response:{id:"",timestamp:/* @__PURE__ */new Date(),modelId:"",messages:[],uiMessages:[]},reasoningText:"",providerMetadata:void 0,finishReason:void 0};break;}case "tripwire":self.#tripwire=true;self.#tripwireReason=chunk.payload?.tripwireReason||"Content blocked";self.#finishReason="other";self.#streamFinished=true;self.#delayedPromises.text.resolve(self.#bufferedText.join(""));self.#delayedPromises.finishReason.resolve("other");self.#delayedPromises.object.resolve(void 0);self.#delayedPromises.usage.resolve(self.#usageCount);self.#delayedPromises.warnings.resolve(self.#warnings);self.#delayedPromises.providerMetadata.resolve(void 0);self.#delayedPromises.response.resolve({});self.#delayedPromises.request.resolve({});self.#delayedPromises.reasoning.resolve([]);self.#delayedPromises.reasoningText.resolve(void 0);self.#delayedPromises.sources.resolve([]);self.#delayedPromises.files.resolve([]);self.#delayedPromises.toolCalls.resolve([]);self.#delayedPromises.toolResults.resolve([]);self.#delayedPromises.steps.resolve(self.#bufferedSteps);self.#delayedPromises.totalUsage.resolve(self.#usageCount);self.#delayedPromises.content.resolve([]);self.#emitChunk(chunk);controller.enqueue(chunk);self.#emitter.emit("finish");controller.terminate();return;case "finish":self.#status="success";if(chunk.payload.stepResult.reason){self.#finishReason=chunk.payload.stepResult.reason;}if(self.#bufferedObject!==void 0){const responseMessages=messageList.get.response.v2();const lastAssistantMessage=[...responseMessages].reverse().find(m=>m.role==="assistant");if(lastAssistantMessage){if(!lastAssistantMessage.content.metadata){lastAssistantMessage.content.metadata={};}lastAssistantMessage.content.metadata.structuredOutput=self.#bufferedObject;}}let response={};if(chunk.payload.metadata){const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;response={...otherMetadata,messages:messageList.get.response.aiV5.model(),uiMessages:messageList.get.response.aiV5.ui()};}this.populateUsageCount(chunk.payload.output.usage);chunk.payload.output.usage={inputTokens:self.#usageCount.inputTokens??0,outputTokens:self.#usageCount.outputTokens??0,totalTokens:self.#usageCount.totalTokens??0,...(self.#usageCount.reasoningTokens!==void 0&&{reasoningTokens:self.#usageCount.reasoningTokens}),...(self.#usageCount.cachedInputTokens!==void 0&&{cachedInputTokens:self.#usageCount.cachedInputTokens})};try{if(self.processorRunner&&!self.#options.isLLMExecutionStep){self.messageList=await self.processorRunner.runOutputProcessors(self.messageList,options.tracingContext);const outputText=self.messageList.get.response.aiV4.core().map(m=>MessageList.coreContentToString(m.content)).join("\n");self.#delayedPromises.text.resolve(outputText);self.#delayedPromises.finishReason.resolve(self.#finishReason);if(chunk.payload.metadata){const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;response={...otherMetadata,messages:messageList.get.response.aiV5.model(),uiMessages:messageList.get.response.aiV5.ui()};}}else {const textContent=self.#bufferedText.join("");self.#delayedPromises.text.resolve(textContent);self.#delayedPromises.finishReason.resolve(self.#finishReason);}}catch(error2){if(error2 instanceof TripWire){self.#tripwire=true;self.#tripwireReason=error2.message;self.#delayedPromises.finishReason.resolve("other");self.#delayedPromises.text.resolve("");}else {self.#error=getErrorFromUnknown(error2,{fallbackMessage:"Unknown error in stream"});self.#delayedPromises.finishReason.resolve("error");self.#delayedPromises.text.resolve("");}if(self.#delayedPromises.object.status.type!=="resolved"){self.#delayedPromises.object.resolve(void 0);}}self.#delayedPromises.usage.resolve(self.#usageCount);self.#delayedPromises.warnings.resolve(self.#warnings);self.#delayedPromises.providerMetadata.resolve(chunk.payload.metadata?.providerMetadata);self.#delayedPromises.response.resolve(response);self.#delayedPromises.request.resolve(self.#request||{});self.#delayedPromises.text.resolve(self.#bufferedText.join(""));const reasoningText=self.#bufferedReasoning.length>0?self.#bufferedReasoning.map(reasoningPart=>reasoningPart.payload.text).join(""):void 0;self.#delayedPromises.reasoningText.resolve(reasoningText);self.#delayedPromises.reasoning.resolve(Object.values(self.#bufferedReasoningDetails||{}));self.#delayedPromises.sources.resolve(self.#bufferedSources);self.#delayedPromises.files.resolve(self.#bufferedFiles);self.#delayedPromises.toolCalls.resolve(self.#toolCalls);self.#delayedPromises.toolResults.resolve(self.#toolResults);self.#delayedPromises.steps.resolve(self.#bufferedSteps);self.#delayedPromises.totalUsage.resolve(self.#getTotalUsage());self.#delayedPromises.content.resolve(messageList.get.response.aiV5.stepContent());self.#delayedPromises.suspendPayload.resolve(void 0);const baseFinishStep=self.#bufferedSteps[self.#bufferedSteps.length-1];if(baseFinishStep){const onFinishPayload={// StepResult properties from baseFinishStep
|
|
1133
1132
|
providerMetadata:baseFinishStep.providerMetadata,text:baseFinishStep.text,warnings:baseFinishStep.warnings??[],finishReason:chunk.payload.stepResult.reason,content:messageList.get.response.aiV5.stepContent(),request:await self.request,error:self.error,reasoning:await self.reasoning,reasoningText:await self.reasoningText,sources:await self.sources,files:await self.files,steps:self.#bufferedSteps,response:{...(await self.response),...baseFinishStep.response,messages:messageList.get.response.aiV5.model()},usage:chunk.payload.output.usage,totalUsage:self.#getTotalUsage(),toolCalls:await self.toolCalls,toolResults:await self.toolResults,staticToolCalls:(await self.toolCalls).filter(toolCall=>toolCall?.payload?.dynamic===false),staticToolResults:(await self.toolResults).filter(toolResult=>toolResult?.payload?.dynamic===false),dynamicToolCalls:(await self.toolCalls).filter(toolCall=>toolCall?.payload?.dynamic===true),dynamicToolResults:(await self.toolResults).filter(toolResult=>toolResult?.payload?.dynamic===true),// Custom properties (not part of standard callback)
|
|
1134
|
-
...(self.#model.modelId&&self.#model.provider&&self.#model.version?{model:self.#model}:{}),object:self.#delayedPromises.object.status.type==="rejected"?void 0:self.#delayedPromises.object.status.type==="resolved"?self.#delayedPromises.object.status.value:self.#structuredOutputMode==="direct"&&baseFinishStep.text?(()=>{try{return JSON.parse(baseFinishStep.text);}catch{return void 0;}})():void 0};await options?.onFinish?.(onFinishPayload);}if(options?.rootSpan){options.rootSpan.setAttributes({...(self.#model.modelId?{"aisdk.model.id":self.#model.modelId}:{}),...(self.#model.provider?{"aisdk.model.provider":self.#model.provider}:{}),...(baseFinishStep?.usage?.reasoningTokens?{"stream.usage.reasoningTokens":baseFinishStep.usage.reasoningTokens}:{}),...(baseFinishStep?.usage?.totalTokens?{"stream.usage.totalTokens":baseFinishStep.usage.totalTokens}:{}),...(baseFinishStep?.usage?.inputTokens?{"stream.usage.inputTokens":baseFinishStep.usage.inputTokens}:{}),...(baseFinishStep?.usage?.outputTokens?{"stream.usage.outputTokens":baseFinishStep.usage.outputTokens}:{}),...(baseFinishStep?.usage?.cachedInputTokens?{"stream.usage.cachedInputTokens":baseFinishStep.usage.cachedInputTokens}:{}),...(baseFinishStep?.providerMetadata?{"stream.response.providerMetadata":JSON.stringify(baseFinishStep?.providerMetadata)}:{}),...(baseFinishStep?.finishReason?{"stream.response.finishReason":baseFinishStep?.finishReason}:{}),...(options?.telemetry_settings?.recordOutputs!==false?{"stream.response.text":baseFinishStep?.text}:{}),...(baseFinishStep?.toolCalls&&options?.telemetry_settings?.recordOutputs!==false?{"stream.response.toolCalls":JSON.stringify(baseFinishStep?.toolCalls?.map(toolCall=>{return {type:"tool-call",toolCallId:toolCall.payload?.toolCallId,args:toolCall.payload?.args,toolName:toolCall.payload?.toolName};}).filter(Boolean))}:{})});options.rootSpan.end();}break;case "error":
|
|
1133
|
+
...(self.#model.modelId&&self.#model.provider&&self.#model.version?{model:self.#model}:{}),object:self.#delayedPromises.object.status.type==="rejected"?void 0:self.#delayedPromises.object.status.type==="resolved"?self.#delayedPromises.object.status.value:self.#structuredOutputMode==="direct"&&baseFinishStep.text?(()=>{try{return JSON.parse(baseFinishStep.text);}catch{return void 0;}})():void 0};await options?.onFinish?.(onFinishPayload);}if(options?.rootSpan){options.rootSpan.setAttributes({...(self.#model.modelId?{"aisdk.model.id":self.#model.modelId}:{}),...(self.#model.provider?{"aisdk.model.provider":self.#model.provider}:{}),...(baseFinishStep?.usage?.reasoningTokens?{"stream.usage.reasoningTokens":baseFinishStep.usage.reasoningTokens}:{}),...(baseFinishStep?.usage?.totalTokens?{"stream.usage.totalTokens":baseFinishStep.usage.totalTokens}:{}),...(baseFinishStep?.usage?.inputTokens?{"stream.usage.inputTokens":baseFinishStep.usage.inputTokens}:{}),...(baseFinishStep?.usage?.outputTokens?{"stream.usage.outputTokens":baseFinishStep.usage.outputTokens}:{}),...(baseFinishStep?.usage?.cachedInputTokens?{"stream.usage.cachedInputTokens":baseFinishStep.usage.cachedInputTokens}:{}),...(baseFinishStep?.providerMetadata?{"stream.response.providerMetadata":JSON.stringify(baseFinishStep?.providerMetadata)}:{}),...(baseFinishStep?.finishReason?{"stream.response.finishReason":baseFinishStep?.finishReason}:{}),...(options?.telemetry_settings?.recordOutputs!==false?{"stream.response.text":baseFinishStep?.text}:{}),...(baseFinishStep?.toolCalls&&options?.telemetry_settings?.recordOutputs!==false?{"stream.response.toolCalls":JSON.stringify(baseFinishStep?.toolCalls?.map(toolCall=>{return {type:"tool-call",toolCallId:toolCall.payload?.toolCallId,args:toolCall.payload?.args,toolName:toolCall.payload?.toolName};}).filter(Boolean))}:{})});options.rootSpan.end();}break;case "error":const error=getErrorFromUnknown(chunk.payload.error,{fallbackMessage:"Unknown error chunk in stream"});self.#error=error;self.#status="failed";self.#streamFinished=true;Object.values(self.#delayedPromises).forEach(promise=>{if(promise.status.type==="pending"){promise.reject(self.#error);}});break;}self.#emitChunk(chunk);controller.enqueue(chunk);},flush:()=>{if(self.#delayedPromises.object.status.type==="pending"){self.#delayedPromises.object.resolve(void 0);}Object.entries(self.#delayedPromises).forEach(([key,promise])=>{if(promise.status.type==="pending"){promise.reject(new Error(`promise '${key}' was not resolved or rejected when stream finished`));}});self.#streamFinished=true;self.#emitter.emit("finish");}}));this.#aisdkv5=new AISDKV5OutputStream({modelOutput:this,messageList,options:{toolCallStreaming:options?.toolCallStreaming,structuredOutput:options?.structuredOutput,tracingContext:options?.tracingContext}});if(initialState){this.deserializeState(initialState);}}#getDelayedPromise(promise){if(!this.#consumptionStarted){void this.consumeStream();}return promise.promise;}/**
|
|
1135
1134
|
* Resolves to the complete text response after streaming completes.
|
|
1136
1135
|
*/get text(){return this.#getDelayedPromise(this.#delayedPromises.text);}/**
|
|
1137
1136
|
* Resolves to reasoning parts array for models that support reasoning.
|
|
@@ -1157,7 +1156,7 @@ providerMetadata:baseFinishStep.providerMetadata,text:baseFinishStep.text,warnin
|
|
|
1157
1156
|
* Resolves to the complete request sent to the model.
|
|
1158
1157
|
*/get request(){return this.#getDelayedPromise(this.#delayedPromises.request);}/**
|
|
1159
1158
|
* Resolves to an error if an error occurred during streaming.
|
|
1160
|
-
*/get error(){
|
|
1159
|
+
*/get error(){return this.#error;}updateUsageCount(usage){if(!usage){return;}if(usage.inputTokens!==void 0){this.#usageCount.inputTokens=(this.#usageCount.inputTokens??0)+usage.inputTokens;}if(usage.outputTokens!==void 0){this.#usageCount.outputTokens=(this.#usageCount.outputTokens??0)+usage.outputTokens;}if(usage.totalTokens!==void 0){this.#usageCount.totalTokens=(this.#usageCount.totalTokens??0)+usage.totalTokens;}if(usage.reasoningTokens!==void 0){this.#usageCount.reasoningTokens=(this.#usageCount.reasoningTokens??0)+usage.reasoningTokens;}if(usage.cachedInputTokens!==void 0){this.#usageCount.cachedInputTokens=(this.#usageCount.cachedInputTokens??0)+usage.cachedInputTokens;}}populateUsageCount(usage){if(!usage){return;}if(usage.inputTokens!==void 0&&this.#usageCount.inputTokens===void 0){this.#usageCount.inputTokens=usage.inputTokens;}if(usage.outputTokens!==void 0&&this.#usageCount.outputTokens===void 0){this.#usageCount.outputTokens=usage.outputTokens;}if(usage.totalTokens!==void 0&&this.#usageCount.totalTokens===void 0){this.#usageCount.totalTokens=usage.totalTokens;}if(usage.reasoningTokens!==void 0&&this.#usageCount.reasoningTokens===void 0){this.#usageCount.reasoningTokens=usage.reasoningTokens;}if(usage.cachedInputTokens!==void 0&&this.#usageCount.cachedInputTokens===void 0){this.#usageCount.cachedInputTokens=usage.cachedInputTokens;}}async consumeStream(options){if(this.#consumptionStarted){return;}this.#consumptionStarted=true;try{await consumeStream({stream:this.#baseStream,onError:options?.onError});}catch(error){options?.onError?.(error);}}/**
|
|
1161
1160
|
* Returns complete output including text, usage, tool calls, and all metadata.
|
|
1162
1161
|
*/async getFullOutput(){await this.consumeStream({onError:error=>{console.error(error);throw error;}});let scoringData;if(this.#returnScorerData){scoringData={input:{inputMessages:this.messageList.getPersisted.input.ui(),rememberedMessages:this.messageList.getPersisted.remembered.ui(),systemMessages:this.messageList.getSystemMessages(),taggedSystemMessages:this.messageList.getPersisted.taggedSystemMessages},output:this.messageList.getPersisted.response.ui()};}const fullOutput={text:await this.text,usage:await this.usage,steps:await this.steps,finishReason:await this.finishReason,warnings:await this.warnings,providerMetadata:await this.providerMetadata,request:await this.request,reasoning:await this.reasoning,reasoningText:await this.reasoningText,toolCalls:await this.toolCalls,toolResults:await this.toolResults,sources:await this.sources,files:await this.files,response:await this.response,totalUsage:await this.totalUsage,object:await this.object,error:this.error,tripwire:this.#tripwire,tripwireReason:this.#tripwireReason,...(scoringData?{scoringData}:{}),traceId:this.traceId};return fullOutput;}/**
|
|
1163
1162
|
* The tripwire flag is set when the stream is aborted due to an output processor blocking the content.
|
|
@@ -1205,8 +1204,8 @@ providerMetadata:baseFinishStep.providerMetadata,text:baseFinishStep.text,warnin
|
|
|
1205
1204
|
* ```
|
|
1206
1205
|
*/get object(){if(!this.processorRunner&&!this.#options.structuredOutput?.schema&&this.#delayedPromises.object.status.type==="pending"){this.#delayedPromises.object.resolve(void 0);}return this.#getDelayedPromise(this.#delayedPromises.object);}// Internal methods for immediate values - used internally by Mastra (llm-execution.ts bailing on errors/abort signals with current state)
|
|
1207
1206
|
// These are not part of the public API
|
|
1208
|
-
/** @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};}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;}};
|
|
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);}};
|
|
1209
1208
|
|
|
1210
|
-
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, getStepResult, getStepResult2, getSuspendedPaths, isAgent, isConditionalKey, isErrorEvent, isFinalState, isLimboState, isTransitionEvent, isVariableReference, isWorkflow, loop, mapVariable, mergeChildValue, recursivelyCheckForFinalState, resolveVariables, tryGenerateWithJsonFallback, tryStreamWithJsonFallback, updateStepInHierarchy, validateStepInput, workflowToStep };
|
|
1211
|
-
//# sourceMappingURL=chunk-
|
|
1212
|
-
//# sourceMappingURL=chunk-
|
|
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
|