@mastra/core 0.23.2 → 0.23.3
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 +68 -0
- package/dist/agent/index.cjs +10 -10
- package/dist/agent/index.js +1 -1
- package/dist/agent/input-processor/index.cjs +6 -6
- package/dist/agent/input-processor/index.js +1 -1
- package/dist/{chunk-F7DVKNKD.cjs → chunk-5KNLBUBH.cjs} +15 -15
- package/dist/chunk-5KNLBUBH.cjs.map +1 -0
- package/dist/{chunk-JZGCSEW5.js → chunk-6C7VGVK4.js} +3 -3
- package/dist/{chunk-JZGCSEW5.js.map → chunk-6C7VGVK4.js.map} +1 -1
- package/dist/{chunk-5YHNPD6A.cjs → chunk-6KO3VDTF.cjs} +4 -4
- package/dist/{chunk-5YHNPD6A.cjs.map → chunk-6KO3VDTF.cjs.map} +1 -1
- package/dist/{chunk-CL6Z33KH.cjs → chunk-7J3XX4AO.cjs} +86 -12
- package/dist/chunk-7J3XX4AO.cjs.map +1 -0
- package/dist/{chunk-ML3WETVK.js → chunk-EEPYVE6F.js} +14 -14
- package/dist/chunk-EEPYVE6F.js.map +1 -0
- package/dist/{chunk-ICGCDCJE.js → chunk-FHVFGVIO.js} +85 -11
- package/dist/chunk-FHVFGVIO.js.map +1 -0
- package/dist/{chunk-WCTRQHTG.cjs → chunk-HEQTUMUA.cjs} +4 -4
- package/dist/{chunk-WCTRQHTG.cjs.map → chunk-HEQTUMUA.cjs.map} +1 -1
- package/dist/{chunk-4RWU3F4F.js → chunk-MDOGD62Q.js} +3 -3
- package/dist/{chunk-4RWU3F4F.js.map → chunk-MDOGD62Q.js.map} +1 -1
- package/dist/{chunk-PHMC6B3L.cjs → chunk-MXJRZZEC.cjs} +11 -11
- package/dist/{chunk-PHMC6B3L.cjs.map → chunk-MXJRZZEC.cjs.map} +1 -1
- package/dist/{chunk-OSAYWQD3.js → chunk-NDKL6C5J.js} +4 -4
- package/dist/{chunk-OSAYWQD3.js.map → chunk-NDKL6C5J.js.map} +1 -1
- package/dist/{chunk-EV64MRWJ.cjs → chunk-NGT4TTOQ.cjs} +4 -4
- package/dist/{chunk-EV64MRWJ.cjs.map → chunk-NGT4TTOQ.cjs.map} +1 -1
- package/dist/{chunk-ELFP5KHN.js → chunk-PXP7ESSG.js} +3 -3
- package/dist/{chunk-ELFP5KHN.js.map → chunk-PXP7ESSG.js.map} +1 -1
- package/dist/{chunk-Q7Y7FU4Y.js → chunk-TIH46IMO.js} +3 -3
- package/dist/{chunk-Q7Y7FU4Y.js.map → chunk-TIH46IMO.js.map} +1 -1
- package/dist/{chunk-OLFLBDUQ.cjs → chunk-X2HARMRO.cjs} +12 -12
- package/dist/{chunk-OLFLBDUQ.cjs.map → chunk-X2HARMRO.cjs.map} +1 -1
- package/dist/index.cjs +32 -32
- package/dist/index.js +7 -7
- package/dist/llm/index.cjs +7 -7
- package/dist/llm/index.js +1 -1
- package/dist/llm/model/provider-types.generated.d.ts +36 -3
- package/dist/loop/index.cjs +2 -2
- package/dist/loop/index.js +1 -1
- package/dist/mastra/index.cjs +2 -2
- package/dist/mastra/index.js +1 -1
- package/dist/memory/index.cjs +4 -4
- package/dist/memory/index.js +1 -1
- package/dist/processors/index.cjs +11 -11
- package/dist/processors/index.js +1 -1
- package/dist/processors/runner.d.ts.map +1 -1
- package/dist/provider-registry.json +83 -9
- package/dist/relevance/index.cjs +4 -4
- package/dist/relevance/index.js +1 -1
- package/dist/scores/index.cjs +4 -4
- package/dist/scores/index.js +1 -1
- package/dist/scores/scoreTraces/index.cjs +3 -3
- package/dist/scores/scoreTraces/index.js +1 -1
- package/dist/stream/RunOutput.d.ts.map +1 -1
- package/dist/stream/index.cjs +8 -8
- package/dist/stream/index.js +1 -1
- package/dist/workflows/default.d.ts +9 -4
- package/dist/workflows/default.d.ts.map +1 -1
- package/dist/workflows/evented/index.cjs +10 -10
- package/dist/workflows/evented/index.js +1 -1
- package/dist/workflows/index.cjs +14 -14
- package/dist/workflows/index.js +1 -1
- package/dist/workflows/legacy/index.cjs +22 -22
- package/dist/workflows/legacy/index.js +1 -1
- package/dist/workflows/types.d.ts +16 -4
- package/dist/workflows/types.d.ts.map +1 -1
- package/dist/workflows/workflow.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/llm/model/provider-types.generated.d.ts +36 -3
- package/dist/chunk-CL6Z33KH.cjs.map +0 -1
- package/dist/chunk-F7DVKNKD.cjs.map +0 -1
- package/dist/chunk-ICGCDCJE.js.map +0 -1
- package/dist/chunk-ML3WETVK.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,73 @@
|
|
|
1
1
|
# @mastra/core
|
|
2
2
|
|
|
3
|
+
## 0.23.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Allow resuming nested workflow step with chained id ([#9464](https://github.com/mastra-ai/mastra/pull/9464))
|
|
8
|
+
|
|
9
|
+
Example, you have a workflow like this
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
export const supportWorkflow = mainWorkflow.then(nestedWorkflow).commit();
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
And a step in `nestedWorkflow` is supsended, you can now also resume it any of these ways:
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
run.resume({
|
|
19
|
+
step: "nestedWorkflow.suspendedStep", //chained nested workflow step id and suspended step id
|
|
20
|
+
//other resume params
|
|
21
|
+
})
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
OR
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
run.resume({
|
|
28
|
+
step: "nestedWorkflow", // just the nested workflow step/step id
|
|
29
|
+
//other resume params
|
|
30
|
+
})
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
- Fix creating system messages from inside processors using processInput. ([#9476](https://github.com/mastra-ai/mastra/pull/9476))
|
|
34
|
+
|
|
35
|
+
- Prevent changing workflow status to suspended when some parallel steps are still running ([#9460](https://github.com/mastra-ai/mastra/pull/9460))
|
|
36
|
+
|
|
37
|
+
## 0.23.3-alpha.0
|
|
38
|
+
|
|
39
|
+
### Patch Changes
|
|
40
|
+
|
|
41
|
+
- Allow resuming nested workflow step with chained id ([#9464](https://github.com/mastra-ai/mastra/pull/9464))
|
|
42
|
+
|
|
43
|
+
Example, you have a workflow like this
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
export const supportWorkflow = mainWorkflow.then(nestedWorkflow).commit();
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
And a step in `nestedWorkflow` is supsended, you can now also resume it any of these ways:
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
run.resume({
|
|
53
|
+
step: "nestedWorkflow.suspendedStep", //chained nested workflow step id and suspended step id
|
|
54
|
+
//other resume params
|
|
55
|
+
})
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
OR
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
run.resume({
|
|
62
|
+
step: "nestedWorkflow", // just the nested workflow step/step id
|
|
63
|
+
//other resume params
|
|
64
|
+
})
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
- Fix creating system messages from inside processors using processInput. ([#9476](https://github.com/mastra-ai/mastra/pull/9476))
|
|
68
|
+
|
|
69
|
+
- Prevent changing workflow status to suspended when some parallel steps are still running ([#9460](https://github.com/mastra-ai/mastra/pull/9460))
|
|
70
|
+
|
|
3
71
|
## 0.23.2
|
|
4
72
|
|
|
5
73
|
### Patch Changes
|
package/dist/agent/index.cjs
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunk5KNLBUBH_cjs = require('../chunk-5KNLBUBH.cjs');
|
|
4
4
|
var chunkMJMID7LX_cjs = require('../chunk-MJMID7LX.cjs');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
Object.defineProperty(exports, "Agent", {
|
|
9
9
|
enumerable: true,
|
|
10
|
-
get: function () { return
|
|
10
|
+
get: function () { return chunk5KNLBUBH_cjs.Agent; }
|
|
11
11
|
});
|
|
12
12
|
Object.defineProperty(exports, "LanguageDetectorInputProcessor", {
|
|
13
13
|
enumerable: true,
|
|
14
|
-
get: function () { return
|
|
14
|
+
get: function () { return chunk5KNLBUBH_cjs.LanguageDetectorInputProcessor; }
|
|
15
15
|
});
|
|
16
16
|
Object.defineProperty(exports, "ModerationInputProcessor", {
|
|
17
17
|
enumerable: true,
|
|
18
|
-
get: function () { return
|
|
18
|
+
get: function () { return chunk5KNLBUBH_cjs.ModerationInputProcessor; }
|
|
19
19
|
});
|
|
20
20
|
Object.defineProperty(exports, "PIIDetectorInputProcessor", {
|
|
21
21
|
enumerable: true,
|
|
22
|
-
get: function () { return
|
|
22
|
+
get: function () { return chunk5KNLBUBH_cjs.PIIDetectorInputProcessor; }
|
|
23
23
|
});
|
|
24
24
|
Object.defineProperty(exports, "PromptInjectionDetectorInputProcessor", {
|
|
25
25
|
enumerable: true,
|
|
26
|
-
get: function () { return
|
|
26
|
+
get: function () { return chunk5KNLBUBH_cjs.PromptInjectionDetectorInputProcessor; }
|
|
27
27
|
});
|
|
28
28
|
Object.defineProperty(exports, "TripWire", {
|
|
29
29
|
enumerable: true,
|
|
30
|
-
get: function () { return
|
|
30
|
+
get: function () { return chunk5KNLBUBH_cjs.TripWire; }
|
|
31
31
|
});
|
|
32
32
|
Object.defineProperty(exports, "UnicodeNormalizerInputProcessor", {
|
|
33
33
|
enumerable: true,
|
|
34
|
-
get: function () { return
|
|
34
|
+
get: function () { return chunk5KNLBUBH_cjs.UnicodeNormalizerInputProcessor; }
|
|
35
35
|
});
|
|
36
36
|
Object.defineProperty(exports, "tryGenerateWithJsonFallback", {
|
|
37
37
|
enumerable: true,
|
|
38
|
-
get: function () { return
|
|
38
|
+
get: function () { return chunk5KNLBUBH_cjs.tryGenerateWithJsonFallback; }
|
|
39
39
|
});
|
|
40
40
|
Object.defineProperty(exports, "tryStreamWithJsonFallback", {
|
|
41
41
|
enumerable: true,
|
|
42
|
-
get: function () { return
|
|
42
|
+
get: function () { return chunk5KNLBUBH_cjs.tryStreamWithJsonFallback; }
|
|
43
43
|
});
|
|
44
44
|
Object.defineProperty(exports, "MessageList", {
|
|
45
45
|
enumerable: true,
|
package/dist/agent/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { Agent, LanguageDetectorInputProcessor, ModerationInputProcessor, PIIDetectorInputProcessor, PromptInjectionDetectorInputProcessor, TripWire, UnicodeNormalizerInputProcessor, tryGenerateWithJsonFallback, tryStreamWithJsonFallback } from '../chunk-
|
|
1
|
+
export { Agent, LanguageDetectorInputProcessor, ModerationInputProcessor, PIIDetectorInputProcessor, PromptInjectionDetectorInputProcessor, TripWire, UnicodeNormalizerInputProcessor, tryGenerateWithJsonFallback, tryStreamWithJsonFallback } from '../chunk-EEPYVE6F.js';
|
|
2
2
|
export { MessageList, convertMessages } from '../chunk-E3PG7G6E.js';
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunk5KNLBUBH_cjs = require('../../chunk-5KNLBUBH.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
Object.defineProperty(exports, "LanguageDetectorInputProcessor", {
|
|
8
8
|
enumerable: true,
|
|
9
|
-
get: function () { return
|
|
9
|
+
get: function () { return chunk5KNLBUBH_cjs.LanguageDetectorInputProcessor; }
|
|
10
10
|
});
|
|
11
11
|
Object.defineProperty(exports, "ModerationInputProcessor", {
|
|
12
12
|
enumerable: true,
|
|
13
|
-
get: function () { return
|
|
13
|
+
get: function () { return chunk5KNLBUBH_cjs.ModerationInputProcessor; }
|
|
14
14
|
});
|
|
15
15
|
Object.defineProperty(exports, "PIIDetectorInputProcessor", {
|
|
16
16
|
enumerable: true,
|
|
17
|
-
get: function () { return
|
|
17
|
+
get: function () { return chunk5KNLBUBH_cjs.PIIDetectorInputProcessor; }
|
|
18
18
|
});
|
|
19
19
|
Object.defineProperty(exports, "PromptInjectionDetectorInputProcessor", {
|
|
20
20
|
enumerable: true,
|
|
21
|
-
get: function () { return
|
|
21
|
+
get: function () { return chunk5KNLBUBH_cjs.PromptInjectionDetectorInputProcessor; }
|
|
22
22
|
});
|
|
23
23
|
Object.defineProperty(exports, "UnicodeNormalizerInputProcessor", {
|
|
24
24
|
enumerable: true,
|
|
25
|
-
get: function () { return
|
|
25
|
+
get: function () { return chunk5KNLBUBH_cjs.UnicodeNormalizerInputProcessor; }
|
|
26
26
|
});
|
|
27
27
|
//# sourceMappingURL=index.cjs.map
|
|
28
28
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { LanguageDetectorInputProcessor, ModerationInputProcessor, PIIDetectorInputProcessor, PromptInjectionDetectorInputProcessor, UnicodeNormalizerInputProcessor } from '../../chunk-
|
|
1
|
+
export { LanguageDetectorInputProcessor, ModerationInputProcessor, PIIDetectorInputProcessor, PromptInjectionDetectorInputProcessor, UnicodeNormalizerInputProcessor } from '../../chunk-EEPYVE6F.js';
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
@@ -4,7 +4,7 @@ var chunkWBAXXG34_cjs = require('./chunk-WBAXXG34.cjs');
|
|
|
4
4
|
var chunkABJOUEVA_cjs = require('./chunk-ABJOUEVA.cjs');
|
|
5
5
|
var chunkAQGLVU53_cjs = require('./chunk-AQGLVU53.cjs');
|
|
6
6
|
var chunkMJMID7LX_cjs = require('./chunk-MJMID7LX.cjs');
|
|
7
|
-
var
|
|
7
|
+
var chunk7J3XX4AO_cjs = require('./chunk-7J3XX4AO.cjs');
|
|
8
8
|
var chunkMCASUJWY_cjs = require('./chunk-MCASUJWY.cjs');
|
|
9
9
|
var chunkTSNDVBUU_cjs = require('./chunk-TSNDVBUU.cjs');
|
|
10
10
|
var chunk4WQYXT2I_cjs = require('./chunk-4WQYXT2I.cjs');
|
|
@@ -229,18 +229,18 @@ function prepareToolsAndToolChoice({tools,toolChoice,activeTools}){if(Object.key
|
|
|
229
229
|
id:sdkTool.id,args:sdkTool.args};default:{const exhaustiveCheck=toolType;throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);}}}catch(e){console.error("Error preparing tool",e);return null;}}).filter(tool=>tool!==null),toolChoice:toolChoice==null?{type:"auto"}:typeof toolChoice==="string"?{type:toolChoice}:{type:"tool",toolName:toolChoice.toolName}};}// src/stream/aisdk/v5/compat/consume-stream.ts
|
|
230
230
|
async function consumeStream({stream,onError}){const reader=stream.getReader();try{while(true){const{done}=await reader.read();if(done)break;}}catch(error){console.error("consumeStream error",error);onError?.(error);}finally{reader.releaseLock();}}// src/agent/agent.ts
|
|
231
231
|
var import_fast_deep_equal2=chunkEBVYYC2Q_cjs.__toESM(require_fast_deep_equal(),1);async function consumeStream2({stream,onError}){const reader=stream.getReader();try{while(true){const{done}=await reader.read();if(done)break;}}catch(error){onError==null?void 0:onError(error);}finally{reader.releaseLock();}}// src/stream/RunOutput.ts
|
|
232
|
-
var WorkflowRunOutput=class{#status="running";#usageCount={inputTokens:0,outputTokens:0,totalTokens:0,cachedInputTokens:0,reasoningTokens:0};#consumptionStarted=false;#baseStream;#emitter=new EventEmitter__default.default();#bufferedChunks=[];#streamFinished=false;#delayedPromises={usage:new DelayedPromise(),result:new DelayedPromise()};/**
|
|
232
|
+
var WorkflowRunOutput=class{#status="running";#usageCount={inputTokens:0,outputTokens:0,totalTokens:0,cachedInputTokens:0,reasoningTokens:0};#consumptionStarted=false;#baseStream;#emitter=new EventEmitter__default.default();#bufferedChunks=[];#streamFinished=false;#streamError;#delayedPromises={usage:new DelayedPromise(),result:new DelayedPromise()};/**
|
|
233
233
|
* Unique identifier for this workflow run
|
|
234
234
|
*/runId;/**
|
|
235
235
|
* Unique identifier for this workflow
|
|
236
|
-
*/workflowId;constructor({runId,workflowId,stream}){const self=this;this.runId=runId;this.workflowId=workflowId;this.#baseStream=stream;stream.pipeTo(new WritableStream({start(){const chunk={type:"workflow-start",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowId:self.workflowId}};self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);},write(chunk){if(chunk.type!=="workflow-step-finish"){self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);}if(chunk.type==="workflow-step-finish"&&chunk.payload.usage){self.#updateUsageCount(chunk.payload.usage);}else if(chunk.type==="workflow-canceled"){self.#status="canceled";}else if(chunk.type==="workflow-step-suspended"){self.#status="suspended";}else if(chunk.type==="workflow-step-result"&&chunk.payload.status==="failed"){self.#status="failed";}},close(){if(self.#status==="running"){self.#status="success";}self.#emitter.emit("chunk",{type:"workflow-finish",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowStatus:self.#status,metadata:{},output:{// @ts-ignore
|
|
236
|
+
*/workflowId;constructor({runId,workflowId,stream}){const self=this;this.runId=runId;this.workflowId=workflowId;this.#baseStream=stream;stream.pipeTo(new WritableStream({start(){const chunk={type:"workflow-start",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowId:self.workflowId}};self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);},write(chunk){if(chunk.type!=="workflow-step-finish"){self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);}if(chunk.type==="workflow-step-finish"&&chunk.payload.usage){self.#updateUsageCount(chunk.payload.usage);}else if(chunk.type==="workflow-canceled"){self.#status="canceled";}else if(chunk.type==="workflow-step-suspended"){self.#status="suspended";}else if(chunk.type==="workflow-step-result"&&chunk.payload.status==="failed"){self.#status="failed";}},close(){if(self.#status==="running"){self.#status="success";}self.#emitter.emit("chunk",{type:"workflow-finish",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowStatus:self.#status,metadata:self.#streamError?{error:self.#streamError,errorMessage:self.#streamError?.message}:{},output:{// @ts-ignore
|
|
237
237
|
usage:self.#usageCount}}});self.#delayedPromises.usage.resolve(self.#usageCount);Object.entries(self.#delayedPromises).forEach(([key,promise])=>{if(promise.status.type==="pending"){promise.reject(new Error(`promise '${key}' was not resolved or rejected when stream finished`));}});self.#streamFinished=true;self.#emitter.emit("finish");}})).catch(reason=>{console.log(" something went wrong",reason);});}#getDelayedPromise(promise){if(!this.#consumptionStarted){void this.consumeStream();}return promise.promise;}#updateUsageCount(usage){let totalUsage={inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0};if("inputTokens"in usage){totalUsage.inputTokens+=parseInt(usage?.inputTokens?.toString()??"0",10);totalUsage.outputTokens+=parseInt(usage?.outputTokens?.toString()??"0",10);}else if("promptTokens"in usage){totalUsage.inputTokens+=parseInt(usage?.promptTokens?.toString()??"0",10);totalUsage.outputTokens+=parseInt(usage?.completionTokens?.toString()??"0",10);}totalUsage.totalTokens+=parseInt(usage?.totalTokens?.toString()??"0",10);totalUsage.reasoningTokens+=parseInt(usage?.reasoningTokens?.toString()??"0",10);totalUsage.cachedInputTokens+=parseInt(usage?.cachedInputTokens?.toString()??"0",10);this.#usageCount=totalUsage;}/**
|
|
238
238
|
* @internal
|
|
239
239
|
*/updateResults(results){this.#delayedPromises.result.resolve(results);}/**
|
|
240
240
|
* @internal
|
|
241
|
-
*/rejectResults(error){this.#delayedPromises.result.reject(error);}/**
|
|
241
|
+
*/rejectResults(error){this.#delayedPromises.result.reject(error);this.#status="failed";this.#streamError=error;}/**
|
|
242
242
|
* @internal
|
|
243
|
-
*/resume(stream){this.#baseStream=stream;this.#streamFinished=false;this.#consumptionStarted=false;this.#status="running";this.#delayedPromises={usage:new DelayedPromise(),result:new DelayedPromise()};const self=this;stream.pipeTo(new WritableStream({start(){const chunk={type:"workflow-start",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowId:self.workflowId}};self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);},write(chunk){if(chunk.type!=="workflow-step-finish"){self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);}if(chunk.type==="workflow-step-finish"&&chunk.payload.usage){self.#updateUsageCount(chunk.payload.usage);}else if(chunk.type==="workflow-canceled"){self.#status="canceled";}else if(chunk.type==="workflow-step-suspended"){self.#status="suspended";}else if(chunk.type==="workflow-step-result"&&chunk.payload.status==="failed"){self.#status="failed";}},close(){if(self.#status==="running"){self.#status="success";}self.#emitter.emit("chunk",{type:"workflow-finish",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowStatus:self.#status,metadata:{},output:{// @ts-ignore
|
|
243
|
+
*/resume(stream){this.#baseStream=stream;this.#streamFinished=false;this.#consumptionStarted=false;this.#status="running";this.#delayedPromises={usage:new DelayedPromise(),result:new DelayedPromise()};const self=this;stream.pipeTo(new WritableStream({start(){const chunk={type:"workflow-start",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowId:self.workflowId}};self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);},write(chunk){if(chunk.type!=="workflow-step-finish"){self.#bufferedChunks.push(chunk);self.#emitter.emit("chunk",chunk);}if(chunk.type==="workflow-step-finish"&&chunk.payload.usage){self.#updateUsageCount(chunk.payload.usage);}else if(chunk.type==="workflow-canceled"){self.#status="canceled";}else if(chunk.type==="workflow-step-suspended"){self.#status="suspended";}else if(chunk.type==="workflow-step-result"&&chunk.payload.status==="failed"){self.#status="failed";}},close(){if(self.#status==="running"){self.#status="success";}self.#emitter.emit("chunk",{type:"workflow-finish",runId:self.runId,from:"WORKFLOW"/* WORKFLOW */,payload:{workflowStatus:self.#status,metadata:self.#streamError?{error:self.#streamError,errorMessage:self.#streamError?.message}:{},output:{// @ts-ignore
|
|
244
244
|
usage:self.#usageCount}}});self.#streamFinished=true;self.#emitter.emit("finish");}})).catch(reason=>{console.log(" something went wrong",reason);});}async consumeStream(options){if(this.#consumptionStarted){return;}this.#consumptionStarted=true;try{await consumeStream2({stream:this.#baseStream,onError:options?.onError});}catch(error){options?.onError?.(error);}}get fullStream(){const self=this;return new web.ReadableStream({start(controller){self.#bufferedChunks.forEach(chunk=>{controller.enqueue(chunk);});if(self.#streamFinished){controller.close();return;}const chunkHandler=chunk=>{controller.enqueue(chunk);};const finishHandler=()=>{self.#emitter.off("chunk",chunkHandler);self.#emitter.off("finish",finishHandler);controller.close();};self.#emitter.on("chunk",chunkHandler);self.#emitter.on("finish",finishHandler);},pull(_controller){if(!self.#consumptionStarted){void self.consumeStream();}},cancel(){self.#emitter.removeAllListeners();}});}get status(){return this.#status;}get result(){return this.#getDelayedPromise(this.#delayedPromises.result);}get usage(){return this.#getDelayedPromise(this.#delayedPromises.usage);}/**
|
|
245
245
|
* @deprecated Use `fullStream.locked` instead
|
|
246
246
|
*/get locked(){console.warn("WorkflowRunOutput.locked is deprecated. Use fullStream.locked instead.");return this.fullStream.locked;}/**
|
|
@@ -283,16 +283,16 @@ var DefaultExecutionEngine=class extends ExecutionEngine{/**
|
|
|
283
283
|
* @param graph The execution graph to execute
|
|
284
284
|
* @param input The input data for the workflow
|
|
285
285
|
* @returns A promise that resolves to the workflow output
|
|
286
|
-
*/async execute(params){const{workflowId,runId,resourceId,graph,input,initialState,resume,retryConfig,workflowAISpan,disableScorers}=params;const{attempts=0,delay:delay2=0}=retryConfig??{};const steps=graph.steps;this.runCounts.clear();if(steps.length===0){const empty_graph_error=new chunk5NTO7S5I_cjs.MastraError({id:"WORKFLOW_EXECUTE_EMPTY_GRAPH",text:"Workflow must have at least one step",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */});workflowAISpan?.error({error:empty_graph_error});throw empty_graph_error;}const executionSpan=this.mastra?.getTelemetry()?.tracer.startSpan(`workflow.${workflowId}.execute`,{attributes:{componentName:workflowId,runId,resourceId}});let startIdx=0;if(resume?.resumePath){startIdx=resume.resumePath[0];resume.resumePath.shift();}const stepResults=resume?.stepResults||{input};let lastOutput;let lastState=initialState??{};for(let i=startIdx;i<steps.length;i++){const entry=steps[i];const executionContext={workflowId,runId,executionPath:[i],suspendedPaths:{},resumeLabels:{},retryConfig:{attempts,delay:delay2},executionSpan,format:params.format,state:lastState??initialState};try{lastOutput=await this.executeEntry({workflowId,runId,resourceId,entry,executionContext,serializedStepGraph:params.serializedStepGraph,prevStep:steps[i-1],stepResults,resume,tracingContext:{currentSpan:workflowAISpan},abortController:params.abortController,emitter:params.emitter,runtimeContext:params.runtimeContext,writableStream:params.writableStream,disableScorers});if(lastOutput.executionContext?.state){lastState=lastOutput.executionContext.state;}if(lastOutput.result.status!=="success"){if(lastOutput.result.status==="bailed"){lastOutput.result.status="success";}const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});if(result2.error){workflowAISpan?.error({error:result2.error,attributes:{status:result2.status}});}else {workflowAISpan?.end({output:result2.result,attributes:{status:result2.status}});}if(lastOutput.result.status==="suspended"&¶ms.outputOptions?.includeResumeLabels){return {...result2,resumeLabels:lastOutput.executionContext?.resumeLabels};}return result2;}}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_ENGINE_STEP_EXECUTION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error executing step: ");const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result,e);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});workflowAISpan?.error({error,attributes:{status:result2.status}});return result2;}}const result=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result.status,result:result.result,error:result.error,runtimeContext:params.runtimeContext});workflowAISpan?.end({output:result.result,attributes:{status:result.status}});if(params.outputOptions?.includeState){return {...result,state:lastState};}return result;}getStepOutput(stepResults,step){if(!step){return stepResults.input;}else if(step.type==="step"||step.type==="waitForEvent"){return stepResults[step.step.id]?.output;}else if(step.type==="sleep"||step.type==="sleepUntil"){return stepResults[step.id]?.output;}else if(step.type==="parallel"||step.type==="conditional"){return step.steps.reduce((acc,entry)=>{
|
|
286
|
+
*/async execute(params){const{workflowId,runId,resourceId,graph,input,initialState,resume,retryConfig,workflowAISpan,disableScorers}=params;const{attempts=0,delay:delay2=0}=retryConfig??{};const steps=graph.steps;this.runCounts.clear();if(steps.length===0){const empty_graph_error=new chunk5NTO7S5I_cjs.MastraError({id:"WORKFLOW_EXECUTE_EMPTY_GRAPH",text:"Workflow must have at least one step",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */});workflowAISpan?.error({error:empty_graph_error});throw empty_graph_error;}const executionSpan=this.mastra?.getTelemetry()?.tracer.startSpan(`workflow.${workflowId}.execute`,{attributes:{componentName:workflowId,runId,resourceId}});let startIdx=0;if(resume?.resumePath){startIdx=resume.resumePath[0];resume.resumePath.shift();}const stepResults=resume?.stepResults||{input};let lastOutput;let lastState=initialState??{};for(let i=startIdx;i<steps.length;i++){const entry=steps[i];const executionContext={workflowId,runId,executionPath:[i],suspendedPaths:{},resumeLabels:{},retryConfig:{attempts,delay:delay2},executionSpan,format:params.format,state:lastState??initialState};try{lastOutput=await this.executeEntry({workflowId,runId,resourceId,entry,executionContext,serializedStepGraph:params.serializedStepGraph,prevStep:steps[i-1],stepResults,resume,tracingContext:{currentSpan:workflowAISpan},abortController:params.abortController,emitter:params.emitter,runtimeContext:params.runtimeContext,writableStream:params.writableStream,disableScorers});if(lastOutput.executionContext?.state){lastState=lastOutput.executionContext.state;}if(lastOutput.result.status!=="success"){if(lastOutput.result.status==="bailed"){lastOutput.result.status="success";}const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});if(result2.error){workflowAISpan?.error({error:result2.error,attributes:{status:result2.status}});}else {workflowAISpan?.end({output:result2.result,attributes:{status:result2.status}});}if(lastOutput.result.status==="suspended"&¶ms.outputOptions?.includeResumeLabels){return {...result2,resumeLabels:lastOutput.executionContext?.resumeLabels};}return result2;}}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_ENGINE_STEP_EXECUTION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error executing step: ");const result2=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result,e);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result2.status,result:result2.result,error:result2.error,runtimeContext:params.runtimeContext});workflowAISpan?.error({error,attributes:{status:result2.status}});return result2;}}const result=await this.fmtReturnValue(executionSpan,params.emitter,stepResults,lastOutput.result);await this.persistStepUpdate({workflowId,runId,resourceId,stepResults:lastOutput.stepResults,serializedStepGraph:params.serializedStepGraph,executionContext:lastOutput.executionContext,workflowStatus:result.status,result:result.result,error:result.error,runtimeContext:params.runtimeContext});workflowAISpan?.end({output:result.result,attributes:{status:result.status}});if(params.outputOptions?.includeState){return {...result,state:lastState};}return result;}getStepOutput(stepResults,step){if(!step){return stepResults.input;}else if(step.type==="step"||step.type==="waitForEvent"){return stepResults[step.step.id]?.output;}else if(step.type==="sleep"||step.type==="sleepUntil"){return stepResults[step.id]?.output;}else if(step.type==="parallel"||step.type==="conditional"){return step.steps.reduce((acc,entry)=>{acc[entry.step.id]=stepResults[entry.step.id]?.output;return acc;},{});}else if(step.type==="loop"){return stepResults[step.step.id]?.output;}else if(step.type==="foreach"){return stepResults[step.step.id]?.output;}}async executeSleep({workflowId,runId,entry,prevOutput,stepResults,emitter,abortController,runtimeContext,executionContext,writableStream,tracingContext}){let{duration,fn}=entry;const sleepSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_sleep"/* WORKFLOW_SLEEP */,name:`sleep: ${duration?`${duration}ms`:"dynamic"}`,attributes:{durationMs:duration,sleepType:fn?"dynamic":"fixed"},tracingPolicy:this.options?.tracingPolicy});if(fn){const stepCallId=crypto2.randomUUID();duration=await fn({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:sleepSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
|
|
287
287
|
suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:stepCallId,name:"sleep",runId},writableStream)});sleepSpan?.update({attributes:{durationMs:duration}});}try{await new Promise(resolve=>setTimeout(resolve,!duration||duration<0?0:duration));sleepSpan?.end();}catch(e){sleepSpan?.error({error:e});}}async executeSleepUntil({workflowId,runId,entry,prevOutput,stepResults,emitter,abortController,runtimeContext,executionContext,writableStream,tracingContext}){let{date,fn}=entry;const sleepUntilSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_sleep"/* WORKFLOW_SLEEP */,name:`sleepUntil: ${date?date.toISOString():"dynamic"}`,attributes:{untilDate:date,durationMs:date?Math.max(0,date.getTime()-Date.now()):void 0,sleepType:fn?"dynamic":"fixed"},tracingPolicy:this.options?.tracingPolicy});if(fn){const stepCallId=crypto2.randomUUID();date=await fn({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:sleepUntilSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
|
|
288
288
|
suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:stepCallId,name:"sleepUntil",runId},writableStream)});const time2=!date?0:date.getTime()-Date.now();sleepUntilSpan?.update({attributes:{durationMs:Math.max(0,time2)}});}const time=!date?0:date?.getTime()-Date.now();try{await new Promise(resolve=>setTimeout(resolve,time<0?0:time));sleepUntilSpan?.end();}catch(e){sleepUntilSpan?.error({error:e});}}async executeWaitForEvent({event,emitter,timeout,tracingContext}){const waitSpan=tracingContext?.currentSpan?.createChildSpan({type:"workflow_wait_event"/* WORKFLOW_WAIT_EVENT */,name:`wait: ${event}`,attributes:{eventName:event,timeoutMs:timeout},tracingPolicy:this.options?.tracingPolicy});const startTime=Date.now();return new Promise((resolve,reject)=>{const cb=eventData=>{waitSpan?.end({output:eventData,attributes:{eventReceived:true,waitDurationMs:Date.now()-startTime}});resolve(eventData);};if(timeout){setTimeout(()=>{emitter.off(`user-event-${event}`,cb);const error=new Error("Timeout waiting for event");waitSpan?.error({error,attributes:{eventReceived:false,waitDurationMs:Date.now()-startTime}});reject(error);},timeout);}emitter.once(`user-event-${event}`,cb);});}async executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume,prevOutput,emitter,abortController,runtimeContext,skipEmits=false,writableStream,disableScorers,serializedStepGraph,tracingContext,iterationCount}){const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepCallId=crypto2.randomUUID();const{inputData,validationError}=await validateStepInput({prevOutput,step,validateInputs:this.options?.validateInputs??false});const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:inputData}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{}),status:"running",...(iterationCount?{metadata:{iterationCount}}:{})};const stepAISpan=tracingContext.currentSpan?.createChildSpan({name:`workflow step: '${step.id}'`,type:"workflow_step"/* WORKFLOW_STEP */,input:inputData,attributes:{stepId:step.id},tracingPolicy:this.options?.tracingPolicy});if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,stepCallId,...stepInfo}});}await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults:{...stepResults,[step.id]:stepInfo},executionContext,workflowStatus:"running",runtimeContext});const _runStep=(step2,spanName,attributes)=>{return async data=>{const telemetry=this.mastra?.getTelemetry();const span=executionContext.executionSpan;if(!telemetry||!span){return step2.execute(data);}return api.context.with(api.trace.setSpan(api.context.active(),span),async()=>{return telemetry.traceMethod(step2.execute.bind(step2),{spanName,attributes})(data);});};};const runStep=_runStep(step,`workflow.${workflowId}.step.${step.id}`,{componentName:workflowId,runId,resourceId:resourceId??""});let execResults;const retries=step.retries??executionContext.retryConfig.attempts??0;const delay2=executionContext.retryConfig.delay??0;for(let i=0;i<retries+1;i++){if(i>0&&delay2){await new Promise(resolve=>setTimeout(resolve,delay2));}try{let suspended;let bailed;if(validationError){throw validationError;}const result=await runStep({runId,resourceId,workflowId,mastra:this.mastra?chunkP35FNLTQ_cjs.wrapMastra(this.mastra,{currentSpan:stepAISpan}):void 0,runtimeContext,inputData,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:this.getOrGenerateRunCount(step.id),resumeData:resume?.steps[0]===step.id?resume?.resumePayload:void 0,tracingContext:{currentSpan:stepAISpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),suspend:async(suspendPayload,suspendOptions)=>{executionContext.suspendedPaths[step.id]=executionContext.executionPath;if(suspendOptions?.resumeLabel){const resumeLabel=Array.isArray(suspendOptions.resumeLabel)?suspendOptions.resumeLabel:[suspendOptions.resumeLabel];for(const label of resumeLabel){executionContext.resumeLabels[label]={stepId:step.id,foreachIndex:executionContext.foreachIndex};}}suspended={payload:suspendPayload};},bail:result2=>{bailed={payload:result2};},abort:()=>{abortController?.abort();},// Only pass resume data if this step was actually suspended before
|
|
289
289
|
// This prevents pending nested workflows from trying to resume instead of start
|
|
290
290
|
resume:stepResults[step.id]?.status==="suspended"?{steps:resume?.steps?.slice(1)||[],resumePayload:resume?.resumePayload,// @ts-ignore
|
|
291
291
|
runId:stepResults[step.id]?.suspendPayload?.__workflow_meta?.runId,label:resume?.label,forEachIndex:resume?.forEachIndex}:void 0,[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:stepCallId,name:step.id,runId},writableStream),// Disable scorers must be explicitly set to false they are on by default
|
|
292
|
-
scorers:disableScorers===false?void 0:step.scorers,validateInputs:this.options?.validateInputs});if(step.scorers){await this.runScorers({scorers:step.scorers,runId,input:inputData,output:result,workflowId,stepId:step.id,runtimeContext,disableScorers,tracingContext:{currentSpan:stepAISpan}});}if(suspended){execResults={status:"suspended",suspendPayload:suspended.payload,suspendedAt:Date.now()};}else if(bailed){execResults={status:"bailed",output:bailed.payload,endedAt:Date.now()};}else {execResults={status:"success",output:result,endedAt:Date.now()};}break;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_STEP_INVOKE_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId,stepId:step.id}},`Error executing step ${step.id}: `);stepAISpan?.error({error,attributes:{status:"failed"}});execResults={status:"failed",error:error?.stack,endedAt:Date.now()};}}if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,stepCallId,...execResults}});}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,stepCallId,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,stepCallId,metadata:{}}});}}if(execResults.status!="failed"){stepAISpan?.end({output:execResults.output,attributes:{status:execResults.status}});}return {...stepInfo,...execResults};}async runScorers({scorers,runId,input,output,workflowId,stepId,runtimeContext,disableScorers,tracingContext}){let scorersToUse=scorers;if(typeof scorersToUse==="function"){try{scorersToUse=await scorersToUse({runtimeContext});}catch(error){this.preprocessExecutionError(error,{id:"WORKFLOW_FAILED_TO_FETCH_SCORERS",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{runId,workflowId,stepId}},"Error fetching scorers: ");}}if(!disableScorers&&scorersToUse&&Object.keys(scorersToUse||{}).length>0){for(const[_id,scorerObject]of Object.entries(scorersToUse||{})){runScorer({scorerId:scorerObject.name,scorerObject,runId,input,output,runtimeContext,entity:{id:workflowId,stepId},structuredOutput:true,source:"LIVE",entityType:"WORKFLOW",tracingContext});}}}async executeParallel({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const parallelSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_parallel"/* WORKFLOW_PARALLEL */,name:`parallel: '${entry.steps.length} branches'`,input:this.getStepOutput(stepResults,prevStep),attributes:{branchCount:entry.steps.length,parallelSteps:entry.steps.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)},tracingPolicy:this.options?.tracingPolicy});const prevOutput=this.getStepOutput(stepResults,prevStep);for(const step of entry.steps){if(step.type==="step"){const startTime=resume?.steps[0]===step.step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.step.id?Date.now():void 0;stepResults[step.step.id]={...stepResults[step.step.id],status:"running",...(resumeTime?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{})};}}let execResults;const results=await Promise.all(entry.steps.map((step,i)=>this.
|
|
293
|
-
suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:crypto2.randomUUID(),name:"conditional",runId},writableStream)});evalSpan?.end({output:result,attributes:{result:!!result}});return result?index:null;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_CONDITION_EVALUATION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error evaluating condition: ");evalSpan?.error({error,attributes:{result:false}});return null;}}))).filter(index=>index!==null);const stepsToRun=entry.steps.filter((_,index)=>truthyIndexes.includes(index));conditionalSpan?.update({attributes:{truthyIndexes,selectedSteps:stepsToRun.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)}});const stepsToExecute=stepsToRun.filter(step=>{if(resume&&step.type==="step"){const existingResult=stepResults[step.step.id];return !existingResult||existingResult.status==="suspended"||existingResult.status==="failed";}return true;});const results=await Promise.all(stepsToExecute.map((step,_index)=>this.executeEntry({workflowId,runId,resourceId,entry:step,prevStep,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,stepsToRun.indexOf(step)],suspendedPaths:executionContext.suspendedPaths,resumeLabels:executionContext.resumeLabels,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext:{currentSpan:conditionalSpan},emitter,abortController,runtimeContext,writableStream,disableScorers})));const mergedStepResults={...stepResults};results.forEach(result=>{if("stepResults"in result&&result.stepResults){Object.assign(mergedStepResults,result.stepResults);}});const allResults=stepsToRun.map(step=>{if(step.type==="step"){const stepResult=mergedStepResults[step.step.id];if(stepResult){return {result:stepResult};}}return {result:{status:"success",output:{}}};}).filter(Boolean);const hasFailed=allResults.find(result=>result.result.status==="failed");const hasSuspended=allResults.find(result=>result.result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.result.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.result.suspendPayload};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:allResults.reduce((acc,result,index)=>{if(result.result.status==="success"){acc[stepsToRun[index].step.id]=result.result.output;}return acc;},{})};}if(execResults.status==="failed"){conditionalSpan?.error({error:new Error(execResults.error)});}else {conditionalSpan?.end({output:execResults.output||execResults});}return execResults;}async executeLoop({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,condition}=entry;const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: '${entry.loopType}'`,input:prevOutput,attributes:{loopType:entry.loopType},tracingPolicy:this.options?.tracingPolicy});let isTrue=true;const prevIterationCount=stepResults[step.id]?.metadata?.iterationCount;let iteration=prevIterationCount?prevIterationCount-1:0;const prevPayload=stepResults[step.id]?.payload;let result={status:"success",output:prevPayload??prevOutput};let currentResume=resume;do{result=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume:currentResume,prevOutput:result.output,tracingContext:{currentSpan:loopSpan},emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph,iterationCount:iteration+1});if(currentResume&&result.status!=="suspended"){currentResume=void 0;}if(result.status!=="success"){loopSpan?.end({attributes:{totalIterations:iteration}});return result;}const evalSpan=loopSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition: '${entry.loopType}'`,input:chunkP35FNLTQ_cjs.selectFields(result.output,["stepResult","output.text","output.object","messages"]),attributes:{conditionIndex:iteration},tracingPolicy:this.options?.tracingPolicy});isTrue=await condition({workflowId,runId,mastra:this.mastra,runtimeContext,inputData:result.output,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:evalSpan},iterationCount:iteration+1,getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:crypto2.randomUUID(),name:"loop",runId},writableStream)});evalSpan?.end({output:isTrue});iteration++;}while(entry.loopType==="dowhile"?isTrue:!isTrue);loopSpan?.end({output:result.output,attributes:{totalIterations:iteration}});return result;}async executeForeach({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,opts}=entry;const results=[];const concurrency=opts.concurrency;const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{})};const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: 'foreach'`,input:prevOutput,attributes:{loopType:"foreach",concurrency},tracingPolicy:this.options?.tracingPolicy});await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,status:"running",...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{status:"running",...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,...stepInfo,status:"running"}});const prevPayload=stepResults[step.id];const foreachIndexObj={};const resumeIndex=prevPayload?.status==="suspended"?prevPayload?.suspendPayload?.__workflow_meta?.foreachIndex||0:0;const prevForeachOutput=prevPayload?.suspendPayload?.__workflow_meta?.foreachOutput||[];const prevResumeLabels=prevPayload?.suspendPayload?.__workflow_meta?.resumeLabels||{};const resumeLabels=getResumeLabelsByStepId(prevResumeLabels,step.id);for(let i=0;i<prevOutput.length;i+=concurrency){const items=prevOutput.slice(i,i+concurrency);const itemsResults=await Promise.all(items.map((item,j)=>{const k=i+j;const prevItemResult=prevForeachOutput[k];if(prevItemResult?.status==="success"||prevItemResult?.status==="suspended"&&resume?.forEachIndex!==k&&resume?.forEachIndex!==void 0){return prevItemResult;}let resumeToUse=void 0;if(resume?.forEachIndex!==void 0){resumeToUse=resume.forEachIndex===k?resume:void 0;}else {const isIndexSuspended=prevItemResult?.status==="suspended"||resumeIndex===k;if(isIndexSuspended){resumeToUse=resume;}}return this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext:{...executionContext,foreachIndex:k},resume:resumeToUse,prevOutput:item,tracingContext:{currentSpan:loopSpan},emitter,abortController,runtimeContext,skipEmits:true,writableStream,disableScorers,serializedStepGraph});}));for(const[resultIndex,result]of itemsResults.entries()){if(result.status!=="success"){const{status,error,suspendPayload,suspendedAt,endedAt,output}=result;const execResults={status,error,suspendPayload,suspendedAt,endedAt,output};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){foreachIndexObj[i+resultIndex]=execResults;}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});return result;}}else {const indexResumeLabel=Object.keys(resumeLabels).find(key=>resumeLabels[key]?.foreachIndex===i+resultIndex);delete resumeLabels[indexResumeLabel];}if(result?.output){results[i+resultIndex]=result?.output;}prevForeachOutput[i+resultIndex]={...result,suspendPayload:{}};}if(Object.keys(foreachIndexObj).length>0){const suspendedIndices=Object.keys(foreachIndexObj).map(Number);const foreachIndex=suspendedIndices[0];await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,...foreachIndexObj[foreachIndex]}});executionContext.suspendedPaths[step.id]=executionContext.executionPath;executionContext.resumeLabels={...resumeLabels,...executionContext.resumeLabels};return {...stepInfo,suspendedAt:Date.now(),status:"suspended",suspendPayload:{...foreachIndexObj[foreachIndex].suspendPayload,__workflow_meta:{...foreachIndexObj[foreachIndex].suspendPayload?.__workflow_meta,foreachIndex,foreachOutput:prevForeachOutput,resumeLabels:executionContext.resumeLabels}}};}}await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,status:"success",output:results,endedAt:Date.now()},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,status:"success",output:results,endedAt:Date.now()}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,status:"success",output:results,endedAt:Date.now()}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});loopSpan?.end({output:results});return {...stepInfo,status:"success",output:results,//@ts-ignore
|
|
292
|
+
scorers:disableScorers===false?void 0:step.scorers,validateInputs:this.options?.validateInputs});if(step.scorers){await this.runScorers({scorers:step.scorers,runId,input:inputData,output:result,workflowId,stepId:step.id,runtimeContext,disableScorers,tracingContext:{currentSpan:stepAISpan}});}if(suspended){execResults={status:"suspended",suspendPayload:suspended.payload,suspendedAt:Date.now()};}else if(bailed){execResults={status:"bailed",output:bailed.payload,endedAt:Date.now()};}else {execResults={status:"success",output:result,endedAt:Date.now()};}break;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_STEP_INVOKE_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId,stepId:step.id}},`Error executing step ${step.id}: `);stepAISpan?.error({error,attributes:{status:"failed"}});execResults={status:"failed",error:error?.stack,endedAt:Date.now()};}}if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,stepCallId,...execResults}});}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,stepCallId,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,stepCallId,metadata:{}}});}}if(execResults.status!="failed"){stepAISpan?.end({output:execResults.output,attributes:{status:execResults.status}});}return {...stepInfo,...execResults};}async runScorers({scorers,runId,input,output,workflowId,stepId,runtimeContext,disableScorers,tracingContext}){let scorersToUse=scorers;if(typeof scorersToUse==="function"){try{scorersToUse=await scorersToUse({runtimeContext});}catch(error){this.preprocessExecutionError(error,{id:"WORKFLOW_FAILED_TO_FETCH_SCORERS",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{runId,workflowId,stepId}},"Error fetching scorers: ");}}if(!disableScorers&&scorersToUse&&Object.keys(scorersToUse||{}).length>0){for(const[_id,scorerObject]of Object.entries(scorersToUse||{})){runScorer({scorerId:scorerObject.name,scorerObject,runId,input,output,runtimeContext,entity:{id:workflowId,stepId},structuredOutput:true,source:"LIVE",entityType:"WORKFLOW",tracingContext});}}}async executeParallel({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const parallelSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_parallel"/* WORKFLOW_PARALLEL */,name:`parallel: '${entry.steps.length} branches'`,input:this.getStepOutput(stepResults,prevStep),attributes:{branchCount:entry.steps.length,parallelSteps:entry.steps.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)},tracingPolicy:this.options?.tracingPolicy});const prevOutput=this.getStepOutput(stepResults,prevStep);for(const step of entry.steps){if(step.type==="step"){const startTime=resume?.steps[0]===step.step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.step.id?Date.now():void 0;stepResults[step.step.id]={...stepResults[step.step.id],status:"running",...(resumeTime?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{})};}}let execResults;const results=await Promise.all(entry.steps.map(async(step,i)=>{const result=await this.executeStep({workflowId,runId,resourceId,step:step.step,prevOutput,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,i],suspendedPaths:executionContext.suspendedPaths,resumeLabels:executionContext.resumeLabels,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext:{currentSpan:parallelSpan},emitter,abortController,runtimeContext,writableStream,disableScorers});stepResults[step.step.id]=result;return result;}));const hasFailed=results.find(result=>result.status==="failed");const hasSuspended=results.find(result=>result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.suspendPayload};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:results.reduce((acc,result,index)=>{if(result.status==="success"){acc[entry.steps[index].step.id]=result.output;}return acc;},{})};}if(execResults.status==="failed"){parallelSpan?.error({error:new Error(execResults.error)});}else {parallelSpan?.end({output:execResults.output||execResults});}return execResults;}async executeConditional({workflowId,runId,resourceId,entry,prevOutput,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const conditionalSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_conditional"/* WORKFLOW_CONDITIONAL */,name:`conditional: '${entry.conditions.length} conditions'`,input:prevOutput,attributes:{conditionCount:entry.conditions.length},tracingPolicy:this.options?.tracingPolicy});let execResults;const truthyIndexes=(await Promise.all(entry.conditions.map(async(cond,index)=>{const evalSpan=conditionalSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition '${index}'`,input:prevOutput,attributes:{conditionIndex:index},tracingPolicy:this.options?.tracingPolicy});try{const result=await cond({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:evalSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
|
|
293
|
+
suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:crypto2.randomUUID(),name:"conditional",runId},writableStream)});evalSpan?.end({output:result,attributes:{result:!!result}});return result?index:null;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_CONDITION_EVALUATION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error evaluating condition: ");evalSpan?.error({error,attributes:{result:false}});return null;}}))).filter(index=>index!==null);const stepsToRun=entry.steps.filter((_,index)=>truthyIndexes.includes(index));conditionalSpan?.update({attributes:{truthyIndexes,selectedSteps:stepsToRun.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)}});const results=await Promise.all(stepsToRun.map(async(step,index)=>{const currStepResult=stepResults[step.step.id];if(currStepResult&&currStepResult.status==="success"){return currStepResult;}const result=await this.executeStep({workflowId,runId,resourceId,step:step.step,prevOutput,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,index],suspendedPaths:executionContext.suspendedPaths,resumeLabels:executionContext.resumeLabels,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext:{currentSpan:conditionalSpan},emitter,abortController,runtimeContext,writableStream,disableScorers});stepResults[step.step.id]=result;return result;}));const hasFailed=results.find(result=>result.status==="failed");const hasSuspended=results.find(result=>result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.suspendPayload,suspendedAt:Date.now()};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:results.reduce((acc,result,index)=>{if(result.status==="success"){acc[stepsToRun[index].step.id]=result.output;}return acc;},{})};}if(execResults.status==="failed"){conditionalSpan?.error({error:new Error(execResults.error)});}else {conditionalSpan?.end({output:execResults.output||execResults});}return execResults;}async executeLoop({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,condition}=entry;const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: '${entry.loopType}'`,input:prevOutput,attributes:{loopType:entry.loopType},tracingPolicy:this.options?.tracingPolicy});let isTrue=true;const prevIterationCount=stepResults[step.id]?.metadata?.iterationCount;let iteration=prevIterationCount?prevIterationCount-1:0;const prevPayload=stepResults[step.id]?.payload;let result={status:"success",output:prevPayload??prevOutput};let currentResume=resume;do{result=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume:currentResume,prevOutput:result.output,tracingContext:{currentSpan:loopSpan},emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph,iterationCount:iteration+1});if(currentResume&&result.status!=="suspended"){currentResume=void 0;}if(result.status!=="success"){loopSpan?.end({attributes:{totalIterations:iteration}});return result;}const evalSpan=loopSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition: '${entry.loopType}'`,input:chunkP35FNLTQ_cjs.selectFields(result.output,["stepResult","output.text","output.object","messages"]),attributes:{conditionIndex:iteration},tracingPolicy:this.options?.tracingPolicy});isTrue=await condition({workflowId,runId,mastra:this.mastra,runtimeContext,inputData:result.output,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:evalSpan},iterationCount:iteration+1,getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,[chunkABJOUEVA_cjs.STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new chunkLRSB62Z6_cjs.ToolStream({prefix:"workflow-step",callId:crypto2.randomUUID(),name:"loop",runId},writableStream)});evalSpan?.end({output:isTrue});iteration++;}while(entry.loopType==="dowhile"?isTrue:!isTrue);loopSpan?.end({output:result.output,attributes:{totalIterations:iteration}});return result;}async executeForeach({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,opts}=entry;const results=[];const concurrency=opts.concurrency;const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{})};const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: 'foreach'`,input:prevOutput,attributes:{loopType:"foreach",concurrency},tracingPolicy:this.options?.tracingPolicy});await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,status:"running",...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{status:"running",...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,...stepInfo,status:"running"}});const prevPayload=stepResults[step.id];const foreachIndexObj={};const resumeIndex=prevPayload?.status==="suspended"?prevPayload?.suspendPayload?.__workflow_meta?.foreachIndex||0:0;const prevForeachOutput=prevPayload?.suspendPayload?.__workflow_meta?.foreachOutput||[];const prevResumeLabels=prevPayload?.suspendPayload?.__workflow_meta?.resumeLabels||{};const resumeLabels=getResumeLabelsByStepId(prevResumeLabels,step.id);for(let i=0;i<prevOutput.length;i+=concurrency){const items=prevOutput.slice(i,i+concurrency);const itemsResults=await Promise.all(items.map((item,j)=>{const k=i+j;const prevItemResult=prevForeachOutput[k];if(prevItemResult?.status==="success"||prevItemResult?.status==="suspended"&&resume?.forEachIndex!==k&&resume?.forEachIndex!==void 0){return prevItemResult;}let resumeToUse=void 0;if(resume?.forEachIndex!==void 0){resumeToUse=resume.forEachIndex===k?resume:void 0;}else {const isIndexSuspended=prevItemResult?.status==="suspended"||resumeIndex===k;if(isIndexSuspended){resumeToUse=resume;}}return this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext:{...executionContext,foreachIndex:k},resume:resumeToUse,prevOutput:item,tracingContext:{currentSpan:loopSpan},emitter,abortController,runtimeContext,skipEmits:true,writableStream,disableScorers,serializedStepGraph});}));for(const[resultIndex,result]of itemsResults.entries()){if(result.status!=="success"){const{status,error,suspendPayload,suspendedAt,endedAt,output}=result;const execResults={status,error,suspendPayload,suspendedAt,endedAt,output};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){foreachIndexObj[i+resultIndex]=execResults;}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});return result;}}else {const indexResumeLabel=Object.keys(resumeLabels).find(key=>resumeLabels[key]?.foreachIndex===i+resultIndex);delete resumeLabels[indexResumeLabel];}if(result?.output){results[i+resultIndex]=result?.output;}prevForeachOutput[i+resultIndex]={...result,suspendPayload:{}};}if(Object.keys(foreachIndexObj).length>0){const suspendedIndices=Object.keys(foreachIndexObj).map(Number);const foreachIndex=suspendedIndices[0];await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,...foreachIndexObj[foreachIndex]}});executionContext.suspendedPaths[step.id]=executionContext.executionPath;executionContext.resumeLabels={...resumeLabels,...executionContext.resumeLabels};return {...stepInfo,suspendedAt:Date.now(),status:"suspended",suspendPayload:{...foreachIndexObj[foreachIndex].suspendPayload,__workflow_meta:{...foreachIndexObj[foreachIndex].suspendPayload?.__workflow_meta,foreachIndex,foreachOutput:prevForeachOutput,resumeLabels:executionContext.resumeLabels}}};}}await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,status:"success",output:results,endedAt:Date.now()},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,status:"success",output:results,endedAt:Date.now()}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,status:"success",output:results,endedAt:Date.now()}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});loopSpan?.end({output:results});return {...stepInfo,status:"success",output:results,//@ts-ignore
|
|
294
294
|
endedAt:Date.now()};}async persistStepUpdate({workflowId,runId,resourceId,stepResults,serializedStepGraph,executionContext,workflowStatus,result,error,runtimeContext}){const shouldPersistSnapshot=this.options?.shouldPersistSnapshot?.({stepResults,workflowStatus});if(!shouldPersistSnapshot){return;}const runtimeContextObj={};runtimeContext.forEach((value,key)=>{runtimeContextObj[key]=value;});await this.mastra?.getStorage()?.persistWorkflowSnapshot({workflowName:workflowId,runId,resourceId,snapshot:{runId,status:workflowStatus,value:executionContext.state,context:stepResults,activePaths:[],serializedStepGraph,suspendedPaths:executionContext.suspendedPaths,waitingPaths:{},resumeLabels:executionContext.resumeLabels,result,error,runtimeContext:runtimeContextObj,// @ts-ignore
|
|
295
|
-
timestamp:Date.now()}});}async executeEntry({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const prevOutput=this.getStepOutput(stepResults,prevStep);let execResults;if(entry.type==="step"){const{step}=entry;execResults=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume,prevOutput,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(resume?.resumePath?.length&&entry.type==="parallel"){const idx=resume.resumePath.shift();const resumedStepResult=await this.executeEntry({workflowId,runId,resourceId,entry:entry.steps[idx],prevStep,serializedStepGraph,stepResults,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,idx],suspendedPaths:executionContext.suspendedPaths,resumeLabels:executionContext.resumeLabels,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});if(resumedStepResult.stepResults){Object.assign(stepResults,resumedStepResult.stepResults);}const allParallelStepsComplete=entry.steps.every(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="success";}return true;});if(allParallelStepsComplete){execResults={status:"success",output:entry.steps.reduce((acc,parallelStep)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="success"){acc[parallelStep.step.id]=stepResult.output;}}return acc;},{})};}else {const stillSuspended=entry.steps.find(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="suspended";}return false;});execResults={status:"suspended",payload:stillSuspended&&stillSuspended.type==="step"?stepResults[stillSuspended.step.id]?.suspendPayload:{}};}const updatedExecutionContext={...executionContext,...resumedStepResult.executionContext,suspendedPaths:{...executionContext.suspendedPaths,...resumedStepResult.executionContext?.suspendedPaths}};if(execResults.status==="suspended"){entry.steps.forEach((parallelStep,stepIndex)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="suspended"){updatedExecutionContext.suspendedPaths[parallelStep.step.id]=[...executionContext.executionPath,stepIndex];}}});}return {result:execResults,stepResults:resumedStepResult.stepResults,executionContext:updatedExecutionContext};}else if(entry.type==="parallel"){execResults=await this.executeParallel({workflowId,runId,entry,prevStep,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});}else if(entry.type==="conditional"){execResults=await this.executeConditional({workflowId,runId,entry,
|
|
295
|
+
timestamp:Date.now()}});}async executeEntry({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const prevOutput=this.getStepOutput(stepResults,prevStep);let execResults;if(entry.type==="step"){const{step}=entry;execResults=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume,prevOutput,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(resume?.resumePath?.length&&entry.type==="parallel"){const idx=resume.resumePath.shift();const resumedStepResult=await this.executeEntry({workflowId,runId,resourceId,entry:entry.steps[idx],prevStep,serializedStepGraph,stepResults,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,idx],suspendedPaths:executionContext.suspendedPaths,resumeLabels:executionContext.resumeLabels,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});if(resumedStepResult.stepResults){Object.assign(stepResults,resumedStepResult.stepResults);}const allParallelStepsComplete=entry.steps.every(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="success";}return true;});if(allParallelStepsComplete){execResults={status:"success",output:entry.steps.reduce((acc,parallelStep)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="success"){acc[parallelStep.step.id]=stepResult.output;}}return acc;},{})};}else {const stillSuspended=entry.steps.find(parallelStep=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];return stepResult&&stepResult.status==="suspended";}return false;});execResults={status:"suspended",payload:stillSuspended&&stillSuspended.type==="step"?stepResults[stillSuspended.step.id]?.suspendPayload:{}};}const updatedExecutionContext={...executionContext,...resumedStepResult.executionContext,suspendedPaths:{...executionContext.suspendedPaths,...resumedStepResult.executionContext?.suspendedPaths}};if(execResults.status==="suspended"){entry.steps.forEach((parallelStep,stepIndex)=>{if(parallelStep.type==="step"){const stepResult=stepResults[parallelStep.step.id];if(stepResult&&stepResult.status==="suspended"){updatedExecutionContext.suspendedPaths[parallelStep.step.id]=[...executionContext.executionPath,stepIndex];}}});}return {result:execResults,stepResults:resumedStepResult.stepResults,executionContext:updatedExecutionContext};}else if(entry.type==="parallel"){execResults=await this.executeParallel({workflowId,runId,entry,prevStep,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});}else if(entry.type==="conditional"){execResults=await this.executeConditional({workflowId,runId,entry,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers});}else if(entry.type==="loop"){execResults=await this.executeLoop({workflowId,runId,entry,prevStep,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(entry.type==="foreach"){execResults=await this.executeForeach({workflowId,runId,entry,prevStep,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}else if(entry.type==="sleep"){const startedAt=Date.now();await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.id,payload:prevOutput,startedAt,status:"waiting"}});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});await this.executeSleep({workflowId,runId,entry,prevStep,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"running",runtimeContext});const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...stepInfo,status:"success",output:prevOutput};stepResults[entry.id]={...stepInfo,status:"success",output:prevOutput};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,...execResults},workflowState:{status:"running",steps:{...stepResults,[entry.id]:{...execResults}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:entry.id,endedAt,status:"success",output:prevOutput}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:entry.id,metadata:{}}});}else if(entry.type==="sleepUntil"){const startedAt=Date.now();await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.id,payload:prevOutput,startedAt,status:"waiting"}});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});await this.executeSleepUntil({workflowId,runId,entry,prevStep,prevOutput,stepResults,serializedStepGraph,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream});await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"running",runtimeContext});const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...stepInfo,status:"success",output:prevOutput};stepResults[entry.id]={...stepInfo,status:"success",output:prevOutput};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.id,...execResults},workflowState:{status:"running",steps:{...stepResults,[entry.id]:{...execResults}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:entry.id,endedAt,status:"success",output:prevOutput}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:entry.id,metadata:{}}});}else if(entry.type==="waitForEvent"){const startedAt=Date.now();let eventData;await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:entry.step.id,status:"waiting",payload:prevOutput,startedAt},workflowState:{status:"waiting",steps:{...stepResults,[entry.step.id]:{status:"waiting",payload:prevOutput,startedAt}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-waiting",payload:{id:entry.step.id,payload:prevOutput,startedAt,status:"waiting"}});stepResults[entry.step.id]={status:"waiting",payload:prevOutput,startedAt};await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:"waiting",runtimeContext});try{eventData=await this.executeWaitForEvent({event:entry.event,emitter,timeout:entry.timeout,tracingContext});const{step}=entry;execResults=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume:{resumePayload:eventData,steps:[entry.step.id]},prevOutput,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph});}catch(error){execResults={status:"failed",error};}const endedAt=Date.now();const stepInfo={payload:prevOutput,startedAt,endedAt};execResults={...execResults,...stepInfo};}if(entry.type==="step"||entry.type==="waitForEvent"||entry.type==="loop"||entry.type==="foreach"){stepResults[entry.step.id]=execResults;}if(abortController?.signal?.aborted){execResults={...execResults,status:"canceled"};}await this.persistStepUpdate({workflowId,runId,resourceId,serializedStepGraph,stepResults,executionContext,workflowStatus:execResults.status==="success"?"running":execResults.status,runtimeContext});if(execResults.status==="canceled"){await emitter.emit("watch-v2",{type:"workflow-canceled",payload:{}});}return {result:execResults,stepResults,executionContext};}};// src/workflows/workflow.ts
|
|
296
296
|
function mapVariable(config){return config;}function createStep(params,agentOptions){if(params instanceof exports.Agent){return {id:params.name,description:params.getDescription(),// @ts-ignore
|
|
297
297
|
inputSchema:z9.z.object({prompt:z9.z.string()// resourceId: z.string().optional(),
|
|
298
298
|
// threadId: z.string().optional(),
|
|
@@ -339,7 +339,7 @@ condition,loopType:"dountil",serializedCondition:{id:`${step.id}-condition`,fn:c
|
|
|
339
339
|
*/async createRunAsync(options){if(this.stepFlow.length===0){throw new Error("Execution flow of workflow is not defined. Add steps to the workflow via .then(), .branch(), etc.");}if(!this.executionGraph.steps){throw new Error("Uncommitted step flow changes detected. Call .commit() to register the steps.");}const runIdToUse=options?.runId||this.#mastra?.generateId()||crypto2.randomUUID();const run=this.#runs.get(runIdToUse)??new Run({workflowId:this.id,stateSchema:this.stateSchema,runId:runIdToUse,resourceId:options?.resourceId,executionEngine:this.executionEngine,executionGraph:this.executionGraph,mastra:this.#mastra,retryConfig:this.retryConfig,serializedStepGraph:this.serializedStepGraph,disableScorers:options?.disableScorers,cleanup:()=>this.#runs.delete(runIdToUse),tracingPolicy:this.#options?.tracingPolicy,workflowSteps:this.steps,validateInputs:this.#options?.validateInputs});this.#runs.set(runIdToUse,run);const shouldPersistSnapshot=this.#options.shouldPersistSnapshot({workflowStatus:run.workflowRunStatus,stepResults:{}});const workflowSnapshotInStorage=await this.getWorkflowRunExecutionResult(runIdToUse,false);if(!workflowSnapshotInStorage&&shouldPersistSnapshot){await this.mastra?.getStorage()?.persistWorkflowSnapshot({workflowName:this.id,runId:runIdToUse,resourceId:options?.resourceId,snapshot:{runId:runIdToUse,status:"pending",value:{},context:{},activePaths:[],serializedStepGraph:this.serializedStepGraph,suspendedPaths:{},resumeLabels:{},waitingPaths:{},result:void 0,error:void 0,// @ts-ignore
|
|
340
340
|
timestamp:Date.now()}});}return run;}async getScorers({runtimeContext=new chunkGPWMM745_cjs.RuntimeContext()}={}){const steps=this.steps;if(!steps||Object.keys(steps).length===0){return {};}const scorers={};for(const step of Object.values(steps)){if(step.scorers){let scorersToUse=step.scorers;if(typeof scorersToUse==="function"){scorersToUse=await scorersToUse({runtimeContext});}for(const[id,scorer]of Object.entries(scorersToUse)){scorers[id]=scorer;}}}return scorers;}// This method should only be called internally for nested workflow execution, as well as from mastra server handlers
|
|
341
341
|
// To run a workflow use `.createRunAsync` and then `.start` or `.resume`
|
|
342
|
-
async execute({runId,inputData,resumeData,state,setState,suspend,resume,[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,mastra,runtimeContext,abort,abortSignal,runCount,tracingContext,writer,validateInputs}){this.__registerMastra(mastra);if(validateInputs){this.#options={...(this.#options||{}),validateInputs};}this.executionEngine.options={...(this.executionEngine.options||{}),validateInputs:validateInputs??false};const isResume=!!(resume?.steps&&resume.steps.length>0)||!!resume?.label;const run=isResume?await this.createRunAsync({runId:resume.runId}):await this.createRunAsync({runId});const nestedAbortCb=()=>{abort();};run.abortController.signal.addEventListener("abort",nestedAbortCb);abortSignal.addEventListener("abort",async()=>{run.abortController.signal.removeEventListener("abort",nestedAbortCb);await run.cancel();});const unwatchV2=run.watch(event=>{emitter.emit("nested-watch-v2",{event,workflowId:this.id});},"watch-v2");const unwatch=run.watch(event=>{emitter.emit("nested-watch",{event,workflowId:this.id,runId:run.runId,isResume:!!resume?.steps?.length});},"watch");if(runCount&&runCount>0&&
|
|
342
|
+
async execute({runId,inputData,resumeData,state,setState,suspend,resume,[chunkABJOUEVA_cjs.EMITTER_SYMBOL]:emitter,mastra,runtimeContext,abort,abortSignal,runCount,tracingContext,writer,validateInputs}){this.__registerMastra(mastra);if(validateInputs){this.#options={...(this.#options||{}),validateInputs};}this.executionEngine.options={...(this.executionEngine.options||{}),validateInputs:validateInputs??false};const isResume=!!(resume?.steps&&resume.steps.length>0)||!!resume?.label||!!(resume?.steps&&resume.steps.length===0&&(!runCount||runCount===0));const run=isResume?await this.createRunAsync({runId:resume.runId}):await this.createRunAsync({runId});const nestedAbortCb=()=>{abort();};run.abortController.signal.addEventListener("abort",nestedAbortCb);abortSignal.addEventListener("abort",async()=>{run.abortController.signal.removeEventListener("abort",nestedAbortCb);await run.cancel();});const unwatchV2=run.watch(event=>{emitter.emit("nested-watch-v2",{event,workflowId:this.id});},"watch-v2");const unwatch=run.watch(event=>{emitter.emit("nested-watch",{event,workflowId:this.id,runId:run.runId,isResume:!!resume?.steps?.length});},"watch");if(runCount&&runCount>0&&isResume&&runtimeContext){runtimeContext.set("__mastraWorflowInputData",inputData);}const res=isResume?await run.resume({resumeData,step:resume.steps?.length>0?resume.steps:void 0,runtimeContext,tracingContext,outputOptions:{includeState:true,includeResumeLabels:true},label:resume.label}):await run.start({inputData,runtimeContext,tracingContext,writableStream:writer,initialState:state,outputOptions:{includeState:true,includeResumeLabels:true}});unwatch();unwatchV2();const suspendedSteps=Object.entries(res.steps).filter(([_stepName,stepResult])=>{const stepRes=stepResult;return stepRes?.status==="suspended";});if(res.state){setState(res.state);}if(suspendedSteps?.length){for(const[stepName,stepResult]of suspendedSteps){const suspendPath=[stepName,...(stepResult?.suspendPayload?.__workflow_meta?.path??[])];await suspend({...stepResult?.suspendPayload,__workflow_meta:{runId:run.runId,path:suspendPath}},{resumeLabel:Object.keys(res.resumeLabels??{})});}}if(res.status==="failed"){throw res.error;}return res.status==="success"?res.result:void 0;}async getWorkflowRuns(args){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow runs. Mastra storage is not initialized");return {runs:[],total:0};}return storage.getWorkflowRuns({workflowName:this.id,...(args??{})});}async getWorkflowRunById(runId){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow runs from storage. Mastra storage is not initialized");return this.#runs.get(runId)?{...this.#runs.get(runId),workflowName:this.id}:null;}const run=await storage.getWorkflowRunById({runId,workflowName:this.id});return run??(this.#runs.get(runId)?{...this.#runs.get(runId),workflowName:this.id}:null);}async getWorkflowRunSteps({runId,workflowId}){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow run steps. Mastra storage is not initialized");return {};}const run=await storage.getWorkflowRunById({runId,workflowName:workflowId});let snapshot=run?.snapshot;if(!snapshot){return {};}if(typeof snapshot==="string"){try{snapshot=JSON.parse(snapshot);}catch(e){this.logger.debug("Cannot get workflow run execution result. Snapshot is not a valid JSON string",e);return {};}}const{serializedStepGraph,context}=snapshot;const{input,...steps}=context;let finalSteps={};for(const step of Object.keys(steps)){const stepGraph=serializedStepGraph.find(stepGraph2=>stepGraph2?.step?.id===step);finalSteps[step]=steps[step];if(stepGraph&&stepGraph?.step?.component==="WORKFLOW"){const nestedSteps=await this.getWorkflowRunSteps({runId,workflowId:step});if(nestedSteps){const updatedNestedSteps=Object.entries(nestedSteps).reduce((acc,[key,value])=>{acc[`${step}.${key}`]=value;return acc;},{});finalSteps={...finalSteps,...updatedNestedSteps};}}}return finalSteps;}async getWorkflowRunExecutionResult(runId,withNestedWorkflows=true){const storage=this.#mastra?.getStorage();if(!storage){this.logger.debug("Cannot get workflow run execution result. Mastra storage is not initialized");return null;}const run=await storage.getWorkflowRunById({runId,workflowName:this.id});let snapshot=run?.snapshot;if(!snapshot){return null;}if(typeof snapshot==="string"){try{snapshot=JSON.parse(snapshot);}catch(e){this.logger.debug("Cannot get workflow run execution result. Snapshot is not a valid JSON string",e);return null;}}const fullSteps=withNestedWorkflows?await this.getWorkflowRunSteps({runId,workflowId:this.id}):snapshot.context;return {status:snapshot.status,result:snapshot.result,error:snapshot.error,payload:snapshot.context?.input,steps:fullSteps};}};var Run=class{#abortController;emitter;/**
|
|
343
343
|
* Unique identifier for this workflow
|
|
344
344
|
*/workflowId;/**
|
|
345
345
|
* Unique identifier for this run
|
|
@@ -398,7 +398,7 @@ async execute({runId,inputData,resumeData,state,setState,suspend,resume,[chunkAB
|
|
|
398
398
|
* Resumes the workflow execution with the provided input as a stream
|
|
399
399
|
* @param input The input data for the workflow
|
|
400
400
|
* @returns A promise that resolves to the workflow output
|
|
401
|
-
*/resumeStreamVNext({step,resumeData,runtimeContext,tracingContext,tracingOptions,forEachIndex}={}){this.closeStreamAction=async()=>{};const self=this;const stream=new web.ReadableStream({async start(controller){const unwatch=self.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{controller.enqueue({type,runId:self.runId,from,payload:{stepName:payload.id,...payload}});},"watch-v2");self.closeStreamAction=async()=>{unwatch();try{await controller.close();}catch(err){console.error("Error closing stream:",err);}};const executionResultsPromise=self._resume({resumeData,step,runtimeContext,tracingContext,tracingOptions,writableStream:new web.WritableStream({write(chunk){controller.enqueue(chunk);}}),isVNext:true,forEachIndex});self.executionResults=executionResultsPromise;
|
|
401
|
+
*/resumeStreamVNext({step,resumeData,runtimeContext,tracingContext,tracingOptions,forEachIndex}={}){this.closeStreamAction=async()=>{};const self=this;const stream=new web.ReadableStream({async start(controller){const unwatch=self.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{controller.enqueue({type,runId:self.runId,from,payload:{stepName:payload.id,...payload}});},"watch-v2");self.closeStreamAction=async()=>{unwatch();try{await controller.close();}catch(err){console.error("Error closing stream:",err);}};const executionResultsPromise=self._resume({resumeData,step,runtimeContext,tracingContext,tracingOptions,writableStream:new web.WritableStream({write(chunk){controller.enqueue(chunk);}}),isVNext:true,forEachIndex});self.executionResults=executionResultsPromise;let executionResults;try{executionResults=await executionResultsPromise;self.closeStreamAction?.().catch(()=>{});if(self.#streamOutput){self.#streamOutput.updateResults(executionResults);}}catch(err){self.#streamOutput?.rejectResults(err);self.closeStreamAction?.().catch(()=>{});}}});this.#streamOutput=new WorkflowRunOutput({runId:this.runId,workflowId:this.workflowId,stream});return this.#streamOutput;}watch(cb,type="watch"){const watchCb=event=>{this.updateState(event.payload);cb({type:event.type,payload:this.getState(),eventTimestamp:event.eventTimestamp});};const nestedWatchCb=({event,workflowId})=>{try{const{type:type2,payload,eventTimestamp}=event;const prefixedSteps=Object.fromEntries(Object.entries(payload?.workflowState?.steps??{}).map(([stepId,step])=>[`${workflowId}.${stepId}`,step]));const newPayload={currentStep:{...payload?.currentStep,id:`${workflowId}.${payload?.currentStep?.id}`},workflowState:{steps:prefixedSteps}};this.updateState(newPayload);cb({type:type2,payload:this.getState(),eventTimestamp});}catch(e){console.error(e);}};const nestedWatchV2Cb=({event,workflowId})=>{this.emitter.emit("watch-v2",{...event,...(event.payload?.id?{payload:{...event.payload,id:`${workflowId}.${event.payload.id}`}}:{})});};if(type==="watch"){this.emitter.on("watch",watchCb);this.emitter.on("nested-watch",nestedWatchCb);}else if(type==="watch-v2"){this.emitter.on("watch-v2",cb);this.emitter.on("nested-watch-v2",nestedWatchV2Cb);}return ()=>{if(type==="watch-v2"){this.emitter.off("watch-v2",cb);this.emitter.off("nested-watch-v2",nestedWatchV2Cb);}else {this.emitter.off("watch",watchCb);this.emitter.off("nested-watch",nestedWatchCb);}};}async watchAsync(cb,type="watch"){return this.watch(cb,type);}async resume(params){return this._resume(params);}async _resume(params){const snapshot=await this.#mastra?.getStorage()?.loadWorkflowSnapshot({workflowName:this.workflowId,runId:this.runId});if(!snapshot){throw new Error("No snapshot found for this workflow run: "+this.workflowId+" "+this.runId);}if(snapshot.status!=="suspended"){throw new Error("This workflow run was not suspended");}const snapshotResumeLabel=params.label?snapshot?.resumeLabels?.[params.label]:void 0;const stepParam=snapshotResumeLabel?.stepId??params.step;let steps;if(stepParam){let newStepParam=stepParam;if(typeof stepParam==="string"){newStepParam=stepParam.split(".");}steps=(Array.isArray(newStepParam)?newStepParam:[newStepParam]).map(step=>typeof step==="string"?step:step?.id);}else {const suspendedStepPaths=[];Object.entries(snapshot?.suspendedPaths??{}).forEach(([stepId,_executionPath])=>{const stepResult=snapshot?.context?.[stepId];if(stepResult&&typeof stepResult==="object"&&"status"in stepResult){const stepRes=stepResult;if(stepRes.status==="suspended"){const nestedPath=stepRes.suspendPayload?.__workflow_meta?.path;if(nestedPath&&Array.isArray(nestedPath)){suspendedStepPaths.push([stepId,...nestedPath]);}else {suspendedStepPaths.push([stepId]);}}}});if(suspendedStepPaths.length===0){throw new Error("No suspended steps found in this workflow run");}if(suspendedStepPaths.length===1){steps=suspendedStepPaths[0];}else {const pathStrings=suspendedStepPaths.map(path=>`[${path.join(", ")}]`);throw new Error(`Multiple suspended steps found: ${pathStrings.join(", ")}. Please specify which step to resume using the "step" parameter.`);}}if(!params.runCount){const suspendedStepIds=Object.keys(snapshot?.suspendedPaths??{});const isStepSuspended=suspendedStepIds.includes(steps?.[0]??"");if(!isStepSuspended){throw new Error(`This workflow step "${steps?.[0]}" was not suspended. Available suspended steps: [${suspendedStepIds.join(", ")}]`);}}const suspendedStep=this.workflowSteps[steps?.[0]??""];const resumeDataToUse=await this._validateResumeData(params.resumeData,suspendedStep);let runtimeContextInput;if(params.runCount&¶ms.runCount>0&¶ms.runtimeContext){runtimeContextInput=params.runtimeContext.get("__mastraWorflowInputData");params.runtimeContext.delete("__mastraWorflowInputData");}const stepResults={...(snapshot?.context??{}),input:runtimeContextInput??snapshot?.context?.input};let runtimeContextToUse=params.runtimeContext??new chunkGPWMM745_cjs.RuntimeContext();Object.entries(snapshot?.runtimeContext??{}).forEach(([key,value])=>{if(!runtimeContextToUse.has(key)){runtimeContextToUse.set(key,value);}});const workflowAISpan=chunkP35FNLTQ_cjs.getOrCreateSpan({type:"workflow_run"/* WORKFLOW_RUN */,name:`workflow run: '${this.workflowId}'`,input:resumeDataToUse,attributes:{workflowId:this.workflowId},metadata:{resourceId:this.resourceId,runId:this.runId},tracingPolicy:this.tracingPolicy,tracingOptions:params.tracingOptions,tracingContext:params.tracingContext,runtimeContext:runtimeContextToUse});const traceId=chunkP35FNLTQ_cjs.getValidTraceId(workflowAISpan);const executionResultPromise=this.executionEngine.execute({workflowId:this.workflowId,runId:this.runId,resourceId:this.resourceId,graph:this.executionGraph,serializedStepGraph:this.serializedStepGraph,input:snapshot?.context?.input,initialState:snapshot?.value??{},resume:{steps,stepResults,resumePayload:resumeDataToUse,// @ts-ignore
|
|
402
402
|
resumePath:snapshot?.suspendedPaths?.[steps?.[0]],forEachIndex:params.forEachIndex??snapshotResumeLabel?.foreachIndex,label:params.label},format:params.format,emitter:{emit:(event,data)=>{this.emitter.emit(event,data);return Promise.resolve();},on:(event,callback)=>{this.emitter.on(event,callback);},off:(event,callback)=>{this.emitter.off(event,callback);},once:(event,callback)=>{this.emitter.once(event,callback);}},runtimeContext:runtimeContextToUse,abortController:this.abortController,workflowAISpan,outputOptions:params.outputOptions,writableStream:params.writableStream}).then(result=>{if(!params.isVNext&&result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}result.traceId=traceId;return result;});this.executionResults=executionResultPromise;return executionResultPromise.then(result=>{this.#streamOutput?.updateResults(result);return result;});}/**
|
|
403
403
|
* Returns the current state of the workflow run
|
|
404
404
|
* @returns The current state of the workflow run
|
|
@@ -539,7 +539,7 @@ tracingContext:{currentSpan:void 0},writer},{toolCallId,messages:[]});await memo
|
|
|
539
539
|
var ProcessorState=class{accumulatedText="";customState={};streamParts=[];span;constructor(options){const{processorName,tracingContext,processorIndex}=options;const currentSpan=tracingContext?.currentSpan;const parentSpan=currentSpan?.findParent("agent_run"/* AGENT_RUN */)||currentSpan?.parent||currentSpan;this.span=parentSpan?.createChildSpan({type:"processor_run"/* PROCESSOR_RUN */,name:`output processor: ${processorName}`,attributes:{processorName,processorType:"output",processorIndex:processorIndex??0},input:{streamParts:[],state:{},totalChunks:0}});}// Internal methods for the runner
|
|
540
540
|
addPart(part){if(part.type==="text-delta"){this.accumulatedText+=part.payload.text;}this.streamParts.push(part);if(this.span){this.span.input={streamParts:this.streamParts,state:this.customState,totalChunks:this.streamParts.length,accumulatedText:this.accumulatedText};}}};var ProcessorRunner=class{inputProcessors;outputProcessors;logger;agentName;constructor({inputProcessors,outputProcessors,logger,agentName}){this.inputProcessors=inputProcessors??[];this.outputProcessors=outputProcessors??[];this.logger=logger;this.agentName=agentName;}async runOutputProcessors(messageList,tracingContext,telemetry){const responseMessages=messageList.clear.response.v2();let processableMessages=[...responseMessages];const ctx={abort:()=>{throw new TripWire("Tripwire triggered");}};for(const[index,processor]of this.outputProcessors.entries()){const abort=reason=>{throw new TripWire(reason||`Tripwire triggered by ${processor.name}`);};ctx.abort=abort;const processMethod=processor.processOutputResult?.bind(processor);if(!processMethod){continue;}const currentSpan=tracingContext?.currentSpan;const parentSpan=currentSpan?.findParent("agent_run"/* AGENT_RUN */)||currentSpan?.parent||currentSpan;const processorSpan=parentSpan?.createChildSpan({type:"processor_run"/* PROCESSOR_RUN */,name:`output processor: ${processor.name}`,attributes:{processorName:processor.name,processorType:"output",processorIndex:index},input:processableMessages});if(!telemetry){processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});}else {await telemetry.traceMethod(async()=>{processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});return processableMessages;},{spanName:`agent.outputProcessor.${processor.name}`,attributes:{"processor.name":processor.name,"processor.index":index.toString(),"processor.total":this.outputProcessors.length.toString()}})();}processorSpan?.end({output:processableMessages});}if(processableMessages.length>0){messageList.add(processableMessages,"response");}return messageList;}/**
|
|
541
541
|
* Process a stream part through all output processors with state management
|
|
542
|
-
*/async processPart(part,processorStates,tracingContext){if(!this.outputProcessors.length){return {part,blocked:false};}try{let processedPart=part;const isFinishChunk=part.type==="finish";for(const[index,processor]of this.outputProcessors.entries()){try{if(processor.processOutputStream&&processedPart){let state=processorStates.get(processor.name);if(!state){state=new ProcessorState({processorName:processor.name,tracingContext,processorIndex:index});processorStates.set(processor.name,state);}state.addPart(processedPart);const result=await processor.processOutputStream({part:processedPart,streamParts:state.streamParts,state:state.customState,abort:reason=>{throw new TripWire(reason||`Stream part blocked by ${processor.name}`);},tracingContext:{currentSpan:state.span}});if(state.span&&!state.span.isEvent){state.span.output=result;}processedPart=result;}}catch(error){if(error instanceof TripWire){const state2=processorStates.get(processor.name);state2?.span?.end({metadata:{blocked:true,reason:error.message}});return {part:null,blocked:true,reason:error.message};}const state=processorStates.get(processor.name);state?.span?.error({error,endSpan:true});this.logger.error(`[Agent:${this.agentName}] - Output processor ${processor.name} failed:`,error);}}if(isFinishChunk){for(const state of processorStates.values()){if(state.span){const finalOutput={...state.span.output,totalChunks:state.streamParts.length,finalState:state.customState};state.span.end({output:finalOutput});}}}return {part:processedPart,blocked:false};}catch(error){this.logger.error(`[Agent:${this.agentName}] - Stream part processing failed:`,error);for(const state of processorStates.values()){state.span?.error({error,endSpan:true});}return {part,blocked:false};}}async runOutputProcessorsForStream(streamResult,tracingContext){return new ReadableStream({start:async controller=>{const reader=streamResult.fullStream.getReader();const processorStates=/* @__PURE__ */new Map();try{while(true){const{done,value}=await reader.read();if(done){controller.close();break;}const{part:processedPart,blocked,reason}=await this.processPart(value,processorStates,tracingContext);if(blocked){void this.logger.debug(`[Agent:${this.agentName}] - Stream part blocked by output processor`,{reason,originalPart:value});controller.enqueue({type:"tripwire",tripwireReason:reason||"Output processor blocked content"});controller.close();break;}else if(processedPart!==null){controller.enqueue(processedPart);}}}catch(error){controller.error(error);}}});}async runInputProcessors(messageList,tracingContext,telemetry){const userMessages=messageList.clear.input.v2();let processableMessages=[...userMessages];const ctx={abort:()=>{throw new TripWire("Tripwire triggered");}};for(const[index,processor]of this.inputProcessors.entries()){const abort=reason=>{throw new TripWire(reason||`Tripwire triggered by ${processor.name}`);};ctx.abort=abort;const processMethod=processor.processInput?.bind(processor);if(!processMethod){continue;}const currentSpan=tracingContext?.currentSpan;const parentSpan=currentSpan?.findParent("agent_run"/* AGENT_RUN */)||currentSpan?.parent||currentSpan;const processorSpan=parentSpan?.createChildSpan({type:"processor_run"/* PROCESSOR_RUN */,name:`input processor: ${processor.name}`,attributes:{processorName:processor.name,processorType:"input",processorIndex:index},input:processableMessages});if(!telemetry){processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});}else {await telemetry.traceMethod(async()=>{processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});return processableMessages;},{spanName:`agent.inputProcessor.${processor.name}`,attributes:{"processor.name":processor.name,"processor.index":index.toString(),"processor.total":this.inputProcessors.length.toString()}})();}processorSpan?.end({output:processableMessages});}if(processableMessages.length>0){messageList.add(
|
|
542
|
+
*/async processPart(part,processorStates,tracingContext){if(!this.outputProcessors.length){return {part,blocked:false};}try{let processedPart=part;const isFinishChunk=part.type==="finish";for(const[index,processor]of this.outputProcessors.entries()){try{if(processor.processOutputStream&&processedPart){let state=processorStates.get(processor.name);if(!state){state=new ProcessorState({processorName:processor.name,tracingContext,processorIndex:index});processorStates.set(processor.name,state);}state.addPart(processedPart);const result=await processor.processOutputStream({part:processedPart,streamParts:state.streamParts,state:state.customState,abort:reason=>{throw new TripWire(reason||`Stream part blocked by ${processor.name}`);},tracingContext:{currentSpan:state.span}});if(state.span&&!state.span.isEvent){state.span.output=result;}processedPart=result;}}catch(error){if(error instanceof TripWire){const state2=processorStates.get(processor.name);state2?.span?.end({metadata:{blocked:true,reason:error.message}});return {part:null,blocked:true,reason:error.message};}const state=processorStates.get(processor.name);state?.span?.error({error,endSpan:true});this.logger.error(`[Agent:${this.agentName}] - Output processor ${processor.name} failed:`,error);}}if(isFinishChunk){for(const state of processorStates.values()){if(state.span){const finalOutput={...state.span.output,totalChunks:state.streamParts.length,finalState:state.customState};state.span.end({output:finalOutput});}}}return {part:processedPart,blocked:false};}catch(error){this.logger.error(`[Agent:${this.agentName}] - Stream part processing failed:`,error);for(const state of processorStates.values()){state.span?.error({error,endSpan:true});}return {part,blocked:false};}}async runOutputProcessorsForStream(streamResult,tracingContext){return new ReadableStream({start:async controller=>{const reader=streamResult.fullStream.getReader();const processorStates=/* @__PURE__ */new Map();try{while(true){const{done,value}=await reader.read();if(done){controller.close();break;}const{part:processedPart,blocked,reason}=await this.processPart(value,processorStates,tracingContext);if(blocked){void this.logger.debug(`[Agent:${this.agentName}] - Stream part blocked by output processor`,{reason,originalPart:value});controller.enqueue({type:"tripwire",tripwireReason:reason||"Output processor blocked content"});controller.close();break;}else if(processedPart!==null){controller.enqueue(processedPart);}}}catch(error){controller.error(error);}}});}async runInputProcessors(messageList,tracingContext,telemetry){const userMessages=messageList.clear.input.v2();let processableMessages=[...userMessages];const ctx={abort:()=>{throw new TripWire("Tripwire triggered");}};for(const[index,processor]of this.inputProcessors.entries()){const abort=reason=>{throw new TripWire(reason||`Tripwire triggered by ${processor.name}`);};ctx.abort=abort;const processMethod=processor.processInput?.bind(processor);if(!processMethod){continue;}const currentSpan=tracingContext?.currentSpan;const parentSpan=currentSpan?.findParent("agent_run"/* AGENT_RUN */)||currentSpan?.parent||currentSpan;const processorSpan=parentSpan?.createChildSpan({type:"processor_run"/* PROCESSOR_RUN */,name:`input processor: ${processor.name}`,attributes:{processorName:processor.name,processorType:"input",processorIndex:index},input:processableMessages});if(!telemetry){processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});}else {await telemetry.traceMethod(async()=>{processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext:{currentSpan:processorSpan}});return processableMessages;},{spanName:`agent.inputProcessor.${processor.name}`,attributes:{"processor.name":processor.name,"processor.index":index.toString(),"processor.total":this.inputProcessors.length.toString()}})();}processorSpan?.end({output:processableMessages});}if(processableMessages.length>0){const systemMessages=processableMessages.filter(m=>m.role==="system");const nonSystemMessages=processableMessages.filter(m=>m.role!=="system");for(const sysMsg of systemMessages){messageList.addSystem(sysMsg.content.content||sysMsg.content.parts.map(p=>p.type==="text"?p.text:"").join("\n"));}if(nonSystemMessages.length>0){messageList.add(nonSystemMessages,"input");}}return messageList;}};// src/workflows/legacy/workflow.ts
|
|
543
543
|
var LegacyStep=class{id;description;inputSchema;outputSchema;payload;execute;retryConfig;mastra;constructor({id,description,execute:execute2,payload,outputSchema,inputSchema,retryConfig}){this.id=id;this.description=description??"";this.inputSchema=inputSchema;this.payload=payload;this.outputSchema=outputSchema;this.execute=execute2;this.retryConfig=retryConfig;}};// src/workflows/legacy/types.ts
|
|
544
544
|
var WhenConditionReturnValue=/* @__PURE__ */(WhenConditionReturnValue2=>{WhenConditionReturnValue2["CONTINUE"]="continue";WhenConditionReturnValue2["CONTINUE_FAILED"]="continue_failed";WhenConditionReturnValue2["ABORT"]="abort";WhenConditionReturnValue2["LIMBO"]="limbo";return WhenConditionReturnValue2;})(WhenConditionReturnValue||{});// src/workflows/legacy/utils.ts
|
|
545
545
|
function isErrorEvent(stateEvent){return stateEvent.type.startsWith("xstate.error.actor.");}function isTransitionEvent(stateEvent){return stateEvent.type.startsWith("xstate.done.actor.");}function isVariableReference(value){return typeof value==="object"&&"step"in value&&"path"in value;}function getStepResult2(result){if(result?.status==="success")return result.output;return void 0;}function getSuspendedPaths({value,path,suspendedPaths}){if(typeof value==="string"){if(value==="suspended"){suspendedPaths.add(path);}}else {Object.keys(value).forEach(key=>getSuspendedPaths({value:value[key],path:path?`${path}.${key}`:key,suspendedPaths}));}}function isFinalState(status){return ["completed","failed"].includes(status);}function isLimboState(status){return status==="limbo";}function recursivelyCheckForFinalState({value,suspendedPaths,path}){if(typeof value==="string"){return isFinalState(value)||isLimboState(value)||suspendedPaths.has(path);}return Object.keys(value).every(key=>recursivelyCheckForFinalState({value:value[key],suspendedPaths,path:path?`${path}.${key}`:key}));}function getActivePathsAndStatus(value){const paths=[];const traverse=(current,path=[])=>{for(const[key,value2]of Object.entries(current)){const currentPath=[...path,key];if(typeof value2==="string"){paths.push({stepPath:currentPath,stepId:key,status:value2});}else if(typeof value2==="object"&&value2!==null){traverse(value2,currentPath);}}};traverse(value);return paths;}function mergeChildValue(startStepId,parent,child){const traverse=current=>{const obj={};for(const[key,value]of Object.entries(current)){if(key===startStepId){obj[key]={...child};}else if(typeof value==="string"){obj[key]=value;}else if(typeof value==="object"&&value!==null){obj[key]=traverse(value);}}return obj;};return traverse(parent);}var updateStepInHierarchy=(value,targetStepId)=>{const result={};for(const key of Object.keys(value)){const currentValue=value[key];if(key===targetStepId){result[key]="pending";}else if(typeof currentValue==="object"&¤tValue!==null){result[key]=updateStepInHierarchy(currentValue,targetStepId);}else {result[key]=currentValue;}}return result;};function getResultActivePaths(state){const activePaths=getActivePathsAndStatus(state.value);const activePathsAndStatus=activePaths.reduce((acc,curr)=>{const entry={status:curr.status,stepPath:curr.stepPath};if(curr.status==="suspended"){entry.suspendPayload=state.context.steps[curr.stepId].suspendPayload;entry.stepPath=curr.stepPath;}acc.set(curr.stepId,entry);return acc;},/* @__PURE__ */new Map());return activePathsAndStatus;}function isWorkflow(step){return step instanceof LegacyWorkflow;}function isAgent(step){return step instanceof exports.Agent;}function resolveVariables({runId,logger,variables,context}){const resolvedData={};for(const[key,variable]of Object.entries(variables)){const sourceData=variable.step==="trigger"?context.triggerData:getStepResult2(context.steps[variable.step.id??variable.step.name]);logger.debug(`Got source data for ${key} variable from ${variable.step==="trigger"?"trigger":variable.step.id??variable.step.name}`,{sourceData,path:variable.path,runId});if(!sourceData&&variable.step!=="trigger"){resolvedData[key]=void 0;continue;}const value=variable.path===""||variable.path==="."?sourceData:radash.get(sourceData,variable.path);logger.debug(`Resolved variable ${key}`,{value,runId});resolvedData[key]=value;}return resolvedData;}function agentToStep(agent,{mastra}={}){return {id:agent.name,inputSchema:z9.z.object({prompt:z9.z.string(),resourceId:z9.z.string().optional(),threadId:z9.z.string().optional()}),outputSchema:z9.z.object({text:z9.z.string()}),execute:async({context,runId,mastra:mastraFromExecute})=>{const realMastra=mastraFromExecute??mastra;if(!realMastra){throw new Error("Mastra instance not found");}agent.__registerMastra(realMastra);agent.__registerPrimitives({logger:realMastra.getLogger(),telemetry:realMastra.getTelemetry()});const result=await agent.generateLegacy(context.inputData.prompt,{runId,resourceId:context.inputData.resourceId,threadId:context.inputData.threadId});return {text:result.text};}};}function workflowToStep(workflow,{mastra}){workflow.setNested(true);return {id:workflow.name,workflow,workflowId:toCamelCaseWithRandomSuffix(workflow.name),execute:async({context,suspend,emit,mastra:mastraFromExecute,runtimeContext})=>{const realMastra=mastraFromExecute??mastra;if(realMastra){workflow.__registerMastra(realMastra);workflow.__registerPrimitives({logger:realMastra.getLogger(),telemetry:realMastra.getTelemetry()});}const run=context.isResume?workflow.createRun({runId:context.isResume.runId}):workflow.createRun();const unwatch=run.watch(state=>{emit("state-update",workflow.name,state.results,{...context,...{[workflow.name]:state.results}});});const awaitedResult=context.isResume&&context.isResume.stepId.includes(".")?await run.resume({stepId:context.isResume.stepId.split(".").slice(1).join("."),context:context.inputData,runtimeContext}):await run.start({triggerData:context.inputData,runtimeContext});unwatch();if(!awaitedResult){throw new Error("LegacyWorkflow run failed");}if(awaitedResult.activePaths?.size>0){const suspendedStep=[...awaitedResult.activePaths.entries()].find(([,{status}])=>{return status==="suspended";});if(suspendedStep){await suspend(suspendedStep[1].suspendPayload,{...awaitedResult,runId:run.runId});}}return {...awaitedResult,runId:run.runId};}};}function toCamelCaseWithRandomSuffix(str){if(!str)return "";const normalizedStr=str.replace(/[-_]/g," ");const words=normalizedStr.split(" ").filter(word=>word.length>0);const camelCase=words.map((word,index)=>{word=word.replace(/[^a-zA-Z0-9]/g,"");if(index===0){return word.toLowerCase();}return word.charAt(0).toUpperCase()+word.slice(1).toLowerCase();}).join("");const randomString=generateRandomLetters(3);return camelCase+randomString;}function generateRandomLetters(length){const characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let result="";for(let i=0;i<length;i++){const randomIndex=Math.floor(Math.random()*characters.length);result+=characters.charAt(randomIndex);}return result;}function isConditionalKey(key){return key.startsWith("__")&&(key.includes("_if")||key.includes("_else"));}// src/workflows/legacy/workflow-instance.ts
|
|
@@ -866,7 +866,7 @@ _agentNetworkAppend=false;/**
|
|
|
866
866
|
* @param modelConfig The model configuration (magic string, config object, or LanguageModel)
|
|
867
867
|
* @returns A LanguageModel instance
|
|
868
868
|
* @internal
|
|
869
|
-
*/async resolveModelConfig(modelConfig,runtimeContext){try{return await
|
|
869
|
+
*/async resolveModelConfig(modelConfig,runtimeContext){try{return await chunk7J3XX4AO_cjs.resolveModelConfig(modelConfig,runtimeContext,this.#mastra);}catch(error){const mastraError=new chunk5NTO7S5I_cjs.MastraError({id:"AGENT_GET_MODEL_MISSING_MODEL_INSTANCE",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name,originalError:error instanceof Error?error.message:String(error)},text:`[Agent:${this.name}] - Failed to resolve model configuration`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}}/**
|
|
870
870
|
* Gets the model instance, resolving it if it's a function or model configuration.
|
|
871
871
|
* When the agent has multiple models configured, returns the first enabled model.
|
|
872
872
|
*
|
|
@@ -1295,5 +1295,5 @@ exports.tryStreamWithJsonFallback = tryStreamWithJsonFallback;
|
|
|
1295
1295
|
exports.updateStepInHierarchy = updateStepInHierarchy;
|
|
1296
1296
|
exports.validateStepInput = validateStepInput;
|
|
1297
1297
|
exports.workflowToStep = workflowToStep;
|
|
1298
|
-
//# sourceMappingURL=chunk-
|
|
1299
|
-
//# sourceMappingURL=chunk-
|
|
1298
|
+
//# sourceMappingURL=chunk-5KNLBUBH.cjs.map
|
|
1299
|
+
//# sourceMappingURL=chunk-5KNLBUBH.cjs.map
|