@scoutqa/mastra-core 0.24.6-fork.1 → 0.24.6-fork.2
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/dist/agent/index.cjs +10 -10
- package/dist/agent/index.js +1 -1
- package/dist/agent/input-processor/index.cjs +6 -6
- package/dist/agent/input-processor/index.js +1 -1
- package/dist/{chunk-N2ILP2YD.js → chunk-3VORBZVV.js} +3 -3
- package/dist/{chunk-N2ILP2YD.js.map → chunk-3VORBZVV.js.map} +1 -1
- package/dist/{chunk-NSIYMRY7.cjs → chunk-HU4P5YH2.cjs} +4 -4
- package/dist/{chunk-NSIYMRY7.cjs.map → chunk-HU4P5YH2.cjs.map} +1 -1
- package/dist/{chunk-TEORHM5O.js → chunk-NP5UN7L2.js} +4 -4
- package/dist/{chunk-TEORHM5O.js.map → chunk-NP5UN7L2.js.map} +1 -1
- package/dist/{chunk-4L63C6E5.cjs → chunk-RJNHOF2L.cjs} +12 -12
- package/dist/{chunk-4L63C6E5.cjs.map → chunk-RJNHOF2L.cjs.map} +1 -1
- package/dist/{chunk-G3KSVDML.cjs → chunk-RRIJDCDD.cjs} +4 -4
- package/dist/{chunk-G3KSVDML.cjs.map → chunk-RRIJDCDD.cjs.map} +1 -1
- package/dist/{chunk-WNV57BEW.cjs → chunk-S7LRIWQZ.cjs} +5 -5
- package/dist/{chunk-WNV57BEW.cjs.map → chunk-S7LRIWQZ.cjs.map} +1 -1
- package/dist/{chunk-YFKTLS32.js → chunk-U5EUSAHW.js} +4 -4
- package/dist/{chunk-YFKTLS32.js.map → chunk-U5EUSAHW.js.map} +1 -1
- package/dist/{chunk-QLMWFSDC.js → chunk-VMZHOPZX.js} +3 -3
- package/dist/{chunk-QLMWFSDC.js.map → chunk-VMZHOPZX.js.map} +1 -1
- package/dist/{chunk-WMTXUQC4.cjs → chunk-YKDQU67S.cjs} +9 -9
- package/dist/{chunk-WMTXUQC4.cjs.map → chunk-YKDQU67S.cjs.map} +1 -1
- package/dist/{chunk-LZPOIBOR.js → chunk-ZTSW5XGP.js} +3 -3
- package/dist/{chunk-LZPOIBOR.js.map → chunk-ZTSW5XGP.js.map} +1 -1
- package/dist/index.cjs +39 -39
- package/dist/index.js +5 -5
- package/dist/loop/index.cjs +2 -2
- package/dist/loop/index.js +1 -1
- package/dist/mastra/index.cjs +2 -2
- package/dist/mastra/index.js +1 -1
- package/dist/processors/index.cjs +11 -11
- package/dist/processors/index.js +1 -1
- package/dist/relevance/index.cjs +4 -4
- package/dist/relevance/index.js +1 -1
- package/dist/scores/index.cjs +4 -4
- package/dist/scores/index.js +1 -1
- package/dist/scores/scoreTraces/index.cjs +3 -3
- package/dist/scores/scoreTraces/index.js +1 -1
- package/dist/stream/index.cjs +8 -8
- package/dist/stream/index.js +1 -1
- package/dist/workflows/evented/index.cjs +10 -10
- package/dist/workflows/evented/index.js +1 -1
- package/dist/workflows/index.cjs +14 -14
- package/dist/workflows/index.js +1 -1
- package/dist/workflows/legacy/index.cjs +22 -22
- package/dist/workflows/legacy/index.js +1 -1
- package/package.json +2 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkRRIJDCDD_cjs = require('./chunk-RRIJDCDD.cjs');
|
|
4
4
|
|
|
5
5
|
// src/relevance/cohere/index.ts
|
|
6
6
|
var CohereRelevanceScorer = class {
|
|
@@ -54,7 +54,7 @@ Relevance score (0-1):`;
|
|
|
54
54
|
var MastraAgentRelevanceScorer = class {
|
|
55
55
|
agent;
|
|
56
56
|
constructor(name, model) {
|
|
57
|
-
this.agent = new
|
|
57
|
+
this.agent = new chunkRRIJDCDD_cjs.Agent({
|
|
58
58
|
name: `Relevance Scorer ${name}`,
|
|
59
59
|
instructions: `You are a specialized agent for evaluating the relevance of text to queries.
|
|
60
60
|
Your task is to rate how well a text passage answers a given query.
|
|
@@ -87,5 +87,5 @@ Always return just the number, no explanation.`,
|
|
|
87
87
|
exports.CohereRelevanceScorer = CohereRelevanceScorer;
|
|
88
88
|
exports.MastraAgentRelevanceScorer = MastraAgentRelevanceScorer;
|
|
89
89
|
exports.createSimilarityPrompt = createSimilarityPrompt;
|
|
90
|
-
//# sourceMappingURL=chunk-
|
|
91
|
-
//# sourceMappingURL=chunk-
|
|
90
|
+
//# sourceMappingURL=chunk-HU4P5YH2.cjs.map
|
|
91
|
+
//# sourceMappingURL=chunk-HU4P5YH2.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/relevance/cohere/index.ts","../src/relevance/relevance-score-provider.ts","../src/relevance/mastra-agent/index.ts"],"names":["Agent"],"mappings":";;;;;AAoBO,IAAM,wBAAN,MAA8D;AAAA,EAC3D,KAAA;AAAA,EACA,MAAA;AAAA,EACR,WAAA,CAAY,OAAe,MAAA,EAAiB;AAC1C,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN;AAAA,KACF;AACA,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACf;AAAA,EACA,MAAM,iBAAA,CAAkB,KAAA,EAAe,IAAA,EAA+B;AACpE,IAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,CAAA,gCAAA,CAAA,EAAoC;AAAA,MAC/D,MAAA,EAAQ,MAAA;AAAA,MACR,OAAA,EAAS;AAAA,QACP,cAAA,EAAgB,kBAAA;AAAA,QAChB,aAAA,EAAe,CAAA,OAAA,EAAU,IAAA,CAAK,MAAM,CAAA;AAAA,OACtC;AAAA,MACA,IAAA,EAAM,KAAK,SAAA,CAAU;AAAA,QACnB,KAAA;AAAA,QACA,SAAA,EAAW,CAAC,IAAI,CAAA;AAAA,QAChB,OAAO,IAAA,CAAK,KAAA;AAAA,QACZ,KAAA,EAAO;AAAA,OACR;AAAA,KACF,CAAA;AAED,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,MAAA,MAAM,IAAI,KAAA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ACrD,MAAA,QAAA,GAAW,YAAA,CAAa,IAAA;AAAA,IAC1B,CAAA,MAAO;AACL,MAAA,MAAM,YAAA,GAAe,MAAM,IAAA,CAAK,KAAA,CAAM,eAAe,MAAM,CAAA;AAC3D,MAAA,QAAA,GAAW,YAAA,CAAa,IAAA;AAAA,IAC1B;AACA,IAAA,OAAO,WAAW,QAAQ,CAAA;AAAA,EAC5B;AACF","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/relevance/cohere/index.ts","../src/relevance/relevance-score-provider.ts","../src/relevance/mastra-agent/index.ts"],"names":["Agent"],"mappings":";;;;;AAoBO,IAAM,wBAAN,MAA8D;AAAA,EAC3D,KAAA;AAAA,EACA,MAAA;AAAA,EACR,WAAA,CAAY,OAAe,MAAA,EAAiB;AAC1C,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN;AAAA,KACF;AACA,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACf;AAAA,EACA,MAAM,iBAAA,CAAkB,KAAA,EAAe,IAAA,EAA+B;AACpE,IAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,CAAA,gCAAA,CAAA,EAAoC;AAAA,MAC/D,MAAA,EAAQ,MAAA;AAAA,MACR,OAAA,EAAS;AAAA,QACP,cAAA,EAAgB,kBAAA;AAAA,QAChB,aAAA,EAAe,CAAA,OAAA,EAAU,IAAA,CAAK,MAAM,CAAA;AAAA,OACtC;AAAA,MACA,IAAA,EAAM,KAAK,SAAA,CAAU;AAAA,QACnB,KAAA;AAAA,QACA,SAAA,EAAW,CAAC,IAAI,CAAA;AAAA,QAChB,OAAO,IAAA,CAAK,KAAA;AAAA,QACZ,KAAA,EAAO;AAAA,OACR;AAAA,KACF,CAAA;AAED,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kBAAA,EAAqB,QAAA,CAAS,MAAM,I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IAC1B,CAAA,MAAO;AACL,MAAA,MAAM,YAAA,GAAe,MAAM,IAAA,CAAK,KAAA,CAAM,eAAe,MAAM,CAAA;AAC3D,MAAA,QAAA,GAAW,YAAA,CAAa,IAAA;AAAA,IAC1B;AACA,IAAA,OAAO,WAAW,QAAQ,CAAA;AAAA,EAC5B;AACF","file":"chunk-HU4P5YH2.cjs","sourcesContent":["import type { RelevanceScoreProvider } from '../relevance-score-provider';\n\ninterface CohereRerankingResponse {\n results: Array<{\n index: number;\n relevance_score: number;\n }>;\n id: string;\n meta: {\n api_version: {\n version: string;\n is_experimental: boolean;\n };\n billed_units: {\n search_units: number;\n };\n };\n}\n\n/** @deprecated Import from `@mastra/rag` instead */\nexport class CohereRelevanceScorer implements RelevanceScoreProvider {\n private model: string;\n private apiKey?: string;\n constructor(model: string, apiKey?: string) {\n console.warn(\n 'CohereRelevanceScorer exported from @mastra/core is deprecated. Please import from \"@mastra/rag\" instead.',\n );\n this.apiKey = apiKey;\n this.model = model;\n }\n async getRelevanceScore(query: string, text: string): Promise<number> {\n const response = await fetch(`https://api.cohere.com/v2/rerank`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({\n query,\n documents: [text],\n model: this.model,\n top_n: 1,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Cohere API error: ${response.status} ${await response.text()}`);\n }\n\n const data = (await response.json()) as CohereRerankingResponse;\n const relevanceScore = data.results[0]?.relevance_score;\n\n if (!relevanceScore) {\n throw new Error('No relevance score found on Cohere response');\n }\n\n return relevanceScore;\n }\n}\n","// Provider interfaces\nexport interface RelevanceScoreProvider {\n getRelevanceScore(text1: string, text2: string): Promise<number>;\n}\n\n// Helper function used by providers\nexport function createSimilarityPrompt(query: string, text: string): string {\n return `Rate the semantic similarity between the following the query and the text on a scale from 0 to 1 (decimals allowed), where 1 means exactly the same meaning and 0 means completely different:\n\nQuery: ${query}\n\nText: ${text}\n\nRelevance score (0-1):`;\n}\n","import { Agent } from '../../agent';\nimport type { MastraModelConfig } from '../../llm/model/shared.types';\nimport { createSimilarityPrompt } from '../relevance-score-provider';\nimport type { RelevanceScoreProvider } from '../relevance-score-provider';\n\n// Mastra Agent implementation\nexport class MastraAgentRelevanceScorer implements RelevanceScoreProvider {\n private agent: Agent;\n\n constructor(name: string, model: MastraModelConfig) {\n this.agent = new Agent({\n name: `Relevance Scorer ${name}`,\n instructions: `You are a specialized agent for evaluating the relevance of text to queries.\nYour task is to rate how well a text passage answers a given query.\nOutput only a number between 0 and 1, where:\n1.0 = Perfectly relevant, directly answers the query\n0.0 = Completely irrelevant\nConsider:\n- Direct relevance to the question\n- Completeness of information\n- Quality and specificity\nAlways return just the number, no explanation.`,\n model,\n });\n }\n\n async getRelevanceScore(query: string, text: string): Promise<number> {\n const prompt = createSimilarityPrompt(query, text);\n\n const model = await this.agent.getModel();\n\n let response: string;\n if (model.specificationVersion === 'v2') {\n const responseText = await this.agent.generate(prompt);\n response = responseText.text;\n } else {\n const responseText = await this.agent.generateLegacy(prompt);\n response = responseText.text;\n }\n return parseFloat(response);\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { DefaultVoice } from './chunk-HCCXJ5YJ.js';
|
|
2
1
|
import { STREAM_FORMAT_SYMBOL, EMITTER_SYMBOL } from './chunk-NLNKQD2T.js';
|
|
2
|
+
import { DefaultVoice } from './chunk-HCCXJ5YJ.js';
|
|
3
3
|
import { InstrumentClass, Telemetry } from './chunk-BLUDYAPI.js';
|
|
4
4
|
import { MessageList, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-Q6LWNLAJ.js';
|
|
5
5
|
import { executeHook } from './chunk-TTELJD4F.js';
|
|
@@ -420,7 +420,7 @@ chunk.type!=="response-metadata"&&runState.state.isStreaming){if(runState.state.
|
|
|
420
420
|
...(toolCall.providerMetadata?{providerMetadata:toolCall.providerMetadata}:{})};})},createdAt:/* @__PURE__ */new Date()};messageList.add(message,"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
|
|
421
421
|
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);});const msg={id:toolResultMessageId,role:"assistant",content:{format:2,parts:errorResults.map(toolCallErrorResult=>{return {type:"tool-invocation",toolInvocation:{state:"result",toolCallId:toolCallErrorResult.toolCallId,toolName:toolCallErrorResult.toolName,args:toolCallErrorResult.args,result:toolCallErrorResult.error?.message??toolCallErrorResult.error},...(toolCallErrorResult.providerMetadata?{providerMetadata:toolCallErrorResult.providerMetadata}:{})};})},createdAt:/* @__PURE__ */new Date()};rest.messageList.add(msg,"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?.();const toolResultMessage={id:toolResultMessageId,role:"assistant",content:{format:2,parts:inputData.map(toolCall2=>{return {type:"tool-invocation",toolInvocation:{state:"result",toolCallId:toolCall2.toolCallId,toolName:toolCall2.toolName,args:toolCall2.args,result:toolCall2.result},...(toolCall2.providerMetadata?{providerMetadata:toolCall2.providerMetadata}:{})};})},createdAt:/* @__PURE__ */new Date()};rest.messageList.add(toolResultMessage,"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
|
|
422
422
|
function createToolCallStep({tools,messageList,options,telemetry_settings,writer,controller,runId,streamState,modelSpanTracker,_internal}){return createStep({id:"toolCallStep",inputSchema:toolCallInputSchema,outputSchema:toolCallOutputSchema,execute:async({inputData,suspend,resumeData,runtimeContext})=>{const addToolApprovalMetadata=(toolCallId,toolName,args)=>{const responseMessages=messageList.get.response.v2();const lastAssistantMessage=[...responseMessages].reverse().find(msg=>msg.role==="assistant");if(lastAssistantMessage){const content=lastAssistantMessage.content;if(!content)return;const metadata=typeof lastAssistantMessage.content.metadata==="object"&&lastAssistantMessage.content.metadata!==null?lastAssistantMessage.content.metadata:{};metadata.pendingToolApprovals=metadata.pendingToolApprovals||{};metadata.pendingToolApprovals[toolCallId]={toolName,args,type:"approval",runId// Store the runId so we can resume after page refresh
|
|
423
|
-
};lastAssistantMessage.content.metadata=metadata;}};const removeToolApprovalMetadata=async toolCallId=>{const{saveQueueManager,memoryConfig,threadId}=_internal||{};if(!saveQueueManager||!threadId){return;}const getMetadata=message=>{const content=message.content;if(!content)return void 0;const metadata=typeof content.metadata==="object"&&content.metadata!==null?content.metadata:void 0;return metadata;};const allMessages=messageList.get.all.v2();const lastAssistantMessage=[...allMessages].reverse().find(msg=>{const metadata=getMetadata(msg);const pendingToolApprovals=metadata?.pendingToolApprovals;return !!pendingToolApprovals?.[toolCallId];});if(lastAssistantMessage){const metadata=getMetadata(lastAssistantMessage);const pendingToolApprovals=metadata?.pendingToolApprovals;if(pendingToolApprovals&&typeof pendingToolApprovals==="object"){delete pendingToolApprovals[toolCallId];if(metadata&&Object.keys(pendingToolApprovals).length===0){delete metadata.pendingToolApprovals;}try{await saveQueueManager.flushMessages(messageList,threadId,memoryConfig);}catch(error){console.error("Error removing tool approval metadata:",error);}}}};const flushMessagesBeforeSuspension=async()=>{const{saveQueueManager,memoryConfig,threadId,resourceId,memory}=_internal||{};if(!saveQueueManager||!threadId){return;}try{if(memory&&!_internal.threadExists&&resourceId){const thread=await memory.getThreadById?.({threadId});if(!thread){await memory.createThread?.({threadId,resourceId,memoryConfig});}_internal.threadExists=true;}await saveQueueManager.flushMessages(messageList,threadId,memoryConfig);}catch(error){console.error("Error flushing messages before suspension:",error);}};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){return {
|
|
423
|
+
};lastAssistantMessage.content.metadata=metadata;}};const removeToolApprovalMetadata=async toolCallId=>{const{saveQueueManager,memoryConfig,threadId}=_internal||{};if(!saveQueueManager||!threadId){return;}const getMetadata=message=>{const content=message.content;if(!content)return void 0;const metadata=typeof content.metadata==="object"&&content.metadata!==null?content.metadata:void 0;return metadata;};const allMessages=messageList.get.all.v2();const lastAssistantMessage=[...allMessages].reverse().find(msg=>{const metadata=getMetadata(msg);const pendingToolApprovals=metadata?.pendingToolApprovals;return !!pendingToolApprovals?.[toolCallId];});if(lastAssistantMessage){const metadata=getMetadata(lastAssistantMessage);const pendingToolApprovals=metadata?.pendingToolApprovals;if(pendingToolApprovals&&typeof pendingToolApprovals==="object"){delete pendingToolApprovals[toolCallId];if(metadata&&Object.keys(pendingToolApprovals).length===0){delete metadata.pendingToolApprovals;}try{await saveQueueManager.flushMessages(messageList,threadId,memoryConfig);}catch(error){console.error("Error removing tool approval metadata:",error);}}}};const flushMessagesBeforeSuspension=async()=>{const{saveQueueManager,memoryConfig,threadId,resourceId,memory}=_internal||{};if(!saveQueueManager||!threadId){return;}try{if(memory&&!_internal.threadExists&&resourceId){const thread=await memory.getThreadById?.({threadId});if(!thread){await memory.createThread?.({threadId,resourceId,memoryConfig});}_internal.threadExists=true;}await saveQueueManager.flushMessages(messageList,threadId,memoryConfig);}catch(error){console.error("Error flushing messages before suspension:",error);}};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){return {result:`Tool ${inputData.toolName} not found`,...inputData};}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}});addToolApprovalMetadata(inputData.toolCallId,inputData.toolName,inputData.args);await flushMessagesBeforeSuspension();return suspend({requireToolApproval:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,args:inputData.args},__streamState:streamState.serialize()},{resumeLabel:inputData.toolCallId});}else {await removeToolApprovalMetadata(inputData.toolCallId);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
|
|
424
424
|
tracingContext:modelSpanTracker?.getTracingContext(),suspend:async suspendPayload=>{controller.enqueue({type:"tool-call-suspended",runId,from:"AGENT"/* AGENT */,payload:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,suspendPayload}});await flushMessagesBeforeSuspension();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
|
|
425
425
|
function createAgenticExecutionWorkflow({models,telemetry_settings,_internal,modelStreamSpan,...rest}){const llmExecutionStep=createLLMExecutionStep({models,_internal,modelStreamSpan,telemetry_settings,...rest});const toolCallStep=createToolCallStep({telemetry_settings,_internal,...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
|
|
426
426
|
// VNext execution as internal
|
|
@@ -1218,5 +1218,5 @@ providerMetadata:baseFinishStep.providerMetadata,text:baseFinishStep.text,warnin
|
|
|
1218
1218
|
/** @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);}};
|
|
1219
1219
|
|
|
1220
1220
|
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, getZodErrors, isAgent, isConditionalKey, isErrorEvent, isFinalState, isLimboState, isTransitionEvent, isVariableReference, isWorkflow, loop, mapVariable, mergeChildValue, recursivelyCheckForFinalState, resolveVariables, tryGenerateWithJsonFallback, tryStreamWithJsonFallback, updateStepInHierarchy, validateStepInput, workflowToStep };
|
|
1221
|
-
//# sourceMappingURL=chunk-
|
|
1222
|
-
//# sourceMappingURL=chunk-
|
|
1221
|
+
//# sourceMappingURL=chunk-NP5UN7L2.js.map
|
|
1222
|
+
//# sourceMappingURL=chunk-NP5UN7L2.js.map
|