@mastra/core 0.2.0-alpha.99 → 0.2.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/agent/index.d.ts +6 -8
  2. package/dist/agent/index.js +1 -7
  3. package/dist/{telemetry-oCUM52DG.d.ts → base-BbtPAA6f.d.ts} +50 -8
  4. package/dist/{index-Cwb-5AzX.d.ts → base-C7R9FwZ6.d.ts} +450 -403
  5. package/dist/base.d.ts +3 -43
  6. package/dist/base.js +1 -3
  7. package/dist/bundler/index.d.ts +3 -4
  8. package/dist/bundler/index.js +1 -4
  9. package/dist/{chunk-MCB4M5W4.js → chunk-22LC46YN.js} +3 -9
  10. package/dist/chunk-4ZRHVG25.js +402 -0
  11. package/dist/{chunk-KNPBNSJ7.js → chunk-55GTEVHJ.js} +13 -14
  12. package/dist/chunk-5HXXWLRX.js +626 -0
  13. package/dist/chunk-6TCTOQ3G.js +1204 -0
  14. package/dist/{chunk-ZJOMHCWE.js → chunk-AN562ICT.js} +98 -151
  15. package/dist/chunk-AWEACB2T.js +66 -0
  16. package/dist/chunk-BB4KXGBU.js +83 -0
  17. package/dist/chunk-C6A6W6XS.js +77 -0
  18. package/dist/{chunk-EO3TIPGQ.js → chunk-CUIUUULJ.js} +375 -254
  19. package/dist/chunk-HT63PEVD.js +37 -0
  20. package/dist/chunk-K36NSQWH.js +10 -0
  21. package/dist/chunk-NUDAZEOG.js +35 -0
  22. package/dist/{chunk-ICMEXHKD.js → chunk-O2VP5JBC.js} +48 -55
  23. package/dist/{chunk-42DYOLDV.js → chunk-PNZK456O.js} +13 -21
  24. package/dist/chunk-RG66XEJT.js +8 -0
  25. package/dist/chunk-SIFBBGY6.js +190 -0
  26. package/dist/{chunk-A7SNFYQB.js → chunk-V4WSAQOP.js} +7 -15
  27. package/dist/chunk-V5UMPUKC.js +218 -0
  28. package/dist/{chunk-DHCULRJM.js → chunk-VE4JJJSW.js} +126 -78
  29. package/dist/chunk-ZINPRHAN.js +22 -0
  30. package/dist/{chunk-C55JWGDU.js → chunk-ZJOXJFJI.js} +42 -15
  31. package/dist/deployer/index.d.ts +3 -5
  32. package/dist/deployer/index.js +1 -5
  33. package/dist/eval/index.d.ts +8 -13
  34. package/dist/eval/index.js +1 -3
  35. package/dist/filter/index.js +1 -2
  36. package/dist/hooks/index.d.ts +13 -18
  37. package/dist/hooks/index.js +1 -2
  38. package/dist/{index-CBZ2mk2H.d.ts → index-B2JCcAQt.d.ts} +1 -1
  39. package/dist/index.d.ts +16 -16
  40. package/dist/index.js +37 -67
  41. package/dist/integration/index.d.ts +8 -10
  42. package/dist/integration/index.js +1 -3
  43. package/dist/llm/index.d.ts +6 -8
  44. package/dist/llm/index.js +1 -1
  45. package/dist/logger/index.d.ts +1 -1
  46. package/dist/logger/index.js +1 -2
  47. package/dist/mastra/index.d.ts +23 -25
  48. package/dist/mastra/index.js +1 -9
  49. package/dist/memory/index.d.ts +8 -10
  50. package/dist/memory/index.js +1 -9
  51. package/dist/relevance/index.js +1 -8
  52. package/dist/storage/index.d.ts +21 -10
  53. package/dist/storage/index.js +3 -7
  54. package/dist/telemetry/index.d.ts +35 -5
  55. package/dist/telemetry/index.js +1 -2
  56. package/dist/telemetry/otel-vendor.d.ts +7 -0
  57. package/dist/telemetry/otel-vendor.js +7 -0
  58. package/dist/tools/index.d.ts +6 -8
  59. package/dist/tools/index.js +1 -2
  60. package/dist/tts/index.d.ts +2 -4
  61. package/dist/tts/index.js +1 -5
  62. package/dist/{metric-BWeQNZt6.d.ts → types-m9RryK9a.d.ts} +6 -1
  63. package/dist/utils.js +1 -2
  64. package/dist/vector/index.d.ts +4 -6
  65. package/dist/vector/index.js +1 -4
  66. package/dist/vector/libsql/index.d.ts +2 -4
  67. package/dist/vector/libsql/index.js +1 -6
  68. package/dist/{workflow-DTtv7_Eq.d.ts → workflow-7xHmmFH5.d.ts} +3 -6
  69. package/dist/workflows/index.d.ts +7 -9
  70. package/dist/workflows/index.js +1 -4
  71. package/package.json +22 -18
  72. package/dist/chunk-4LJFWC2Q.js +0 -216
  73. package/dist/chunk-4ZUSEHLH.js +0 -285
  74. package/dist/chunk-AJJZUHB4.js +0 -14
  75. package/dist/chunk-G4MCO7XF.js +0 -70
  76. package/dist/chunk-HBTQNIAX.js +0 -90
  77. package/dist/chunk-HPXWJBQK.js +0 -222
  78. package/dist/chunk-JJ57BXQR.js +0 -16
  79. package/dist/chunk-JP37ODNX.js +0 -36
  80. package/dist/chunk-K3N7KJHH.js +0 -52
  81. package/dist/chunk-MDM2JS2U.js +0 -1288
  82. package/dist/chunk-VOUPGVRD.js +0 -27
  83. package/dist/chunk-Z7JFMQZZ.js +0 -551
  84. /package/dist/{chunk-AE3H2QEY.js → chunk-ZDWFBE5L.js} +0 -0
@@ -1,285 +0,0 @@
1
- import { __name, __publicField } from './chunk-AJJZUHB4.js';
2
- import { trace, context, SpanStatusCode, SpanKind } from '@opentelemetry/api';
3
- import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
4
- import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
5
- import { Resource } from '@opentelemetry/resources';
6
- import { NodeSDK } from '@opentelemetry/sdk-node';
7
- import { ConsoleSpanExporter, AlwaysOnSampler, AlwaysOffSampler, TraceIdRatioBasedSampler, ParentBasedSampler } from '@opentelemetry/sdk-trace-base';
8
- import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
9
-
10
- function hasActiveTelemetry() {
11
- try {
12
- return !!trace.getTracer("default-tracer");
13
- } catch {
14
- return false;
15
- }
16
- }
17
- __name(hasActiveTelemetry, "hasActiveTelemetry");
18
-
19
- // src/telemetry/telemetry.decorators.ts
20
- function withSpan(options) {
21
- return function(_target, propertyKey, descriptor) {
22
- if (!descriptor || typeof descriptor === "number") return;
23
- const originalMethod = descriptor.value;
24
- const methodName = String(propertyKey);
25
- descriptor.value = function(...args) {
26
- if (options?.skipIfNoTelemetry && !hasActiveTelemetry()) {
27
- return originalMethod.apply(this, args);
28
- }
29
- const tracer = trace.getTracer("default-tracer");
30
- let spanName;
31
- let spanKind;
32
- if (typeof options === "string") {
33
- spanName = options;
34
- } else if (options) {
35
- spanName = options.spanName || methodName;
36
- spanKind = options.spanKind;
37
- } else {
38
- spanName = methodName;
39
- }
40
- const span = tracer.startSpan(spanName, {
41
- kind: spanKind
42
- });
43
- const ctx = trace.setSpan(context.active(), span);
44
- args.forEach((arg, index) => {
45
- try {
46
- span.setAttribute(`${spanName}.argument.${index}`, JSON.stringify(arg));
47
- } catch (e) {
48
- span.setAttribute(`${spanName}.argument.${index}`, "[Not Serializable]");
49
- }
50
- });
51
- let result;
52
- try {
53
- result = context.with(ctx, () => originalMethod.apply(this, args));
54
- if (result instanceof Promise) {
55
- return result.then((resolvedValue) => {
56
- try {
57
- span.setAttribute(`${spanName}.result`, JSON.stringify(resolvedValue));
58
- } catch (e) {
59
- span.setAttribute(`${spanName}.result`, "[Not Serializable]");
60
- }
61
- return resolvedValue;
62
- }).finally(() => span.end());
63
- }
64
- try {
65
- span.setAttribute(`${spanName}.result`, JSON.stringify(result));
66
- } catch (e) {
67
- span.setAttribute(`${spanName}.result`, "[Not Serializable]");
68
- }
69
- return result;
70
- } catch (error) {
71
- span.setStatus({
72
- code: SpanStatusCode.ERROR,
73
- message: error instanceof Error ? error.message : "Unknown error"
74
- });
75
- if (error instanceof Error) {
76
- span.recordException(error);
77
- }
78
- throw error;
79
- } finally {
80
- if (!(result instanceof Promise)) {
81
- span.end();
82
- }
83
- }
84
- };
85
- return descriptor;
86
- };
87
- }
88
- __name(withSpan, "withSpan");
89
- function InstrumentClass(options) {
90
- return function(target) {
91
- const methods = Object.getOwnPropertyNames(target.prototype);
92
- methods.forEach((method) => {
93
- if (options?.excludeMethods?.includes(method) || method === "constructor") return;
94
- if (options?.methodFilter && !options.methodFilter(method)) return;
95
- const descriptor = Object.getOwnPropertyDescriptor(target.prototype, method);
96
- if (descriptor && typeof descriptor.value === "function") {
97
- Object.defineProperty(target.prototype, method, withSpan({
98
- spanName: options?.prefix ? `${options.prefix}.${method}` : method,
99
- skipIfNoTelemetry: true,
100
- spanKind: options?.spanKind || SpanKind.INTERNAL
101
- })(target, method, descriptor));
102
- }
103
- });
104
- return target;
105
- };
106
- }
107
- __name(InstrumentClass, "InstrumentClass");
108
- var sdkInstance = null;
109
- var _Telemetry = class _Telemetry {
110
- constructor(config) {
111
- __publicField(this, "sdk", null);
112
- __publicField(this, "tracer", trace.getTracer("default"));
113
- __publicField(this, "name", "default-service");
114
- this.name = config.serviceName ?? "default-service";
115
- if (typeof window === "undefined") {
116
- if (process.env.NODE_ENV === "development" || !sdkInstance) {
117
- if (sdkInstance) {
118
- this.shutdown();
119
- }
120
- const exporter = config.export?.type === "otlp" ? new OTLPTraceExporter({
121
- url: config.export.endpoint,
122
- headers: config.export.headers
123
- }) : config.export?.type === "custom" ? config.export.exporter : new ConsoleSpanExporter();
124
- const sampler = this.getSampler(config);
125
- sdkInstance = new NodeSDK({
126
- resource: new Resource({
127
- [ATTR_SERVICE_NAME]: this.name
128
- }),
129
- traceExporter: exporter,
130
- sampler,
131
- instrumentations: [
132
- getNodeAutoInstrumentations()
133
- ]
134
- });
135
- try {
136
- sdkInstance.start();
137
- this.sdk = sdkInstance;
138
- _Telemetry.isInitialized = true;
139
- } catch (error) {
140
- console.warn("Failed to initialize OpenTelemetry:", error);
141
- }
142
- }
143
- }
144
- this.tracer = trace.getTracer(this.name);
145
- }
146
- getSampler(config) {
147
- if (!config.sampling) {
148
- return new AlwaysOnSampler();
149
- }
150
- if (!config.enabled) {
151
- return new AlwaysOffSampler();
152
- }
153
- switch (config.sampling.type) {
154
- case "ratio":
155
- return new TraceIdRatioBasedSampler(config.sampling.probability);
156
- case "always_on":
157
- return new AlwaysOnSampler();
158
- case "always_off":
159
- return new AlwaysOffSampler();
160
- case "parent_based":
161
- const rootSampler = new TraceIdRatioBasedSampler(config.sampling.root?.probability || 1);
162
- return new ParentBasedSampler({
163
- root: rootSampler
164
- });
165
- default:
166
- return new AlwaysOnSampler();
167
- }
168
- }
169
- async shutdown() {
170
- if (this.sdk && _Telemetry.isInitialized) {
171
- try {
172
- await this.sdk.shutdown();
173
- _Telemetry.isInitialized = false;
174
- global.__OTEL_SDK__ = void 0;
175
- global.__TELEMETRY__ = void 0;
176
- } catch (error) {
177
- console.warn("Error shutting down OpenTelemetry:", error);
178
- }
179
- }
180
- }
181
- /**
182
- * Initialize telemetry with the given configuration
183
- * @param config - Optional telemetry configuration object
184
- * @returns Telemetry instance that can be used for tracing
185
- */
186
- static init(config = {}) {
187
- try {
188
- if (!global.__TELEMETRY__) {
189
- global.__TELEMETRY__ = new _Telemetry(config);
190
- }
191
- return global.__TELEMETRY__;
192
- } catch (error) {
193
- console.error("Failed to initialize telemetry:", error);
194
- throw error;
195
- }
196
- }
197
- /**
198
- * Get the global telemetry instance
199
- * @throws {Error} If telemetry has not been initialized
200
- * @returns {Telemetry} The global telemetry instance
201
- */
202
- static get() {
203
- if (!global.__TELEMETRY__) {
204
- throw new Error("Telemetry not initialized");
205
- }
206
- return global.__TELEMETRY__;
207
- }
208
- /**
209
- * Wraps a class instance with telemetry tracing
210
- * @param instance The class instance to wrap
211
- * @param options Optional configuration for tracing
212
- * @returns Wrapped instance with all methods traced
213
- */
214
- traceClass(instance, options = {}) {
215
- const { skipIfNoTelemetry = true } = options;
216
- if (skipIfNoTelemetry && !hasActiveTelemetry()) {
217
- return instance;
218
- }
219
- const { spanNamePrefix = instance.constructor.name.toLowerCase(), attributes = {}, excludeMethods = [] } = options;
220
- return new Proxy(instance, {
221
- get: /* @__PURE__ */ __name((target, prop) => {
222
- const value = target[prop];
223
- if (typeof value === "function" && prop !== "constructor" && !prop.toString().startsWith("_") && !excludeMethods.includes(prop.toString())) {
224
- return this.traceMethod(value.bind(target), {
225
- spanName: `${spanNamePrefix}.${prop.toString()}`,
226
- attributes: {
227
- ...attributes,
228
- [`${spanNamePrefix}.name`]: target.constructor.name,
229
- [`${spanNamePrefix}.method.name`]: prop.toString()
230
- }
231
- });
232
- }
233
- return value;
234
- }, "get")
235
- });
236
- }
237
- /**
238
- * method to trace individual methods with proper context
239
- * @param method The method to trace
240
- * @param context Additional context for the trace
241
- * @returns Wrapped method with tracing
242
- */
243
- traceMethod(method, context2) {
244
- const { skipIfNoTelemetry = true } = context2;
245
- if (skipIfNoTelemetry && !hasActiveTelemetry()) {
246
- return method;
247
- }
248
- return async (...args) => {
249
- const span = this.tracer.startSpan(context2.spanName);
250
- try {
251
- if (context2.attributes) {
252
- span.setAttributes(context2.attributes);
253
- }
254
- args.forEach((arg, index) => {
255
- try {
256
- span.setAttribute(`${context2.spanName}.argument.${index}`, JSON.stringify(arg));
257
- } catch (e) {
258
- span.setAttribute(`${context2.spanName}.argument.${index}`, "[Not Serializable]");
259
- }
260
- });
261
- const result = await method(...args);
262
- try {
263
- span.setAttribute(`${context2.spanName}.result`, JSON.stringify(result));
264
- } catch (e) {
265
- span.setAttribute(`${context2.spanName}.result`, "[Not Serializable]");
266
- }
267
- span.end();
268
- return result;
269
- } catch (error) {
270
- span.recordException(error);
271
- span.setStatus({
272
- code: SpanStatusCode.ERROR,
273
- message: error.message
274
- });
275
- span.end();
276
- throw error;
277
- }
278
- };
279
- }
280
- };
281
- __name(_Telemetry, "Telemetry");
282
- __publicField(_Telemetry, "isInitialized", false);
283
- var Telemetry = _Telemetry;
284
-
285
- export { InstrumentClass, Telemetry, hasActiveTelemetry, withSpan };
@@ -1,14 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __typeError = (msg) => {
3
- throw TypeError(msg);
4
- };
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
9
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
10
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
11
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
12
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
13
-
14
- export { __name, __privateAdd, __privateGet, __privateMethod, __privateSet, __publicField };
@@ -1,70 +0,0 @@
1
- import { RegisteredLogger, createLogger } from './chunk-ICMEXHKD.js';
2
- import { __name, __publicField } from './chunk-AJJZUHB4.js';
3
-
4
- // src/base.ts
5
- var _MastraBase = class _MastraBase {
6
- constructor({ component, name }) {
7
- __publicField(this, "component", RegisteredLogger.LLM);
8
- __publicField(this, "logger");
9
- __publicField(this, "name");
10
- __publicField(this, "telemetry");
11
- this.component = component || RegisteredLogger.LLM;
12
- this.name = name;
13
- this.logger = createLogger({
14
- name: `${this.component} - ${this.name}`
15
- });
16
- }
17
- /**
18
- * Set the logger for the agent
19
- * @param logger
20
- */
21
- __setLogger(logger) {
22
- this.logger = logger;
23
- this.logger.debug(`Logger updated for ${this.component}:${this.name}`);
24
- }
25
- /**
26
- * Internal logging helper that formats and sends logs to the configured logger
27
- * @param level - Severity level of the log
28
- * @param message - Main log message
29
- * @param opts - Optional object for the log
30
- */
31
- log(level, message, opts) {
32
- if (!this.logger) return;
33
- const logMessage = {
34
- type: this.component,
35
- message,
36
- destinationPath: this.name ? `${this.component}/${this.name}` : this.component,
37
- ...opts || {}
38
- };
39
- const logMethod = level.toLowerCase();
40
- this.logger[logMethod]?.(logMessage);
41
- }
42
- /**
43
- * Set the telemetry for the
44
- * @param telemetry
45
- */
46
- __setTelemetry(telemetry) {
47
- this.telemetry = telemetry;
48
- this.logger.debug(`Telemetry updated for ${this.component} ${this.telemetry.tracer}`);
49
- }
50
- /**
51
- * Get the telemetry on the vector
52
- * @returns telemetry
53
- */
54
- __getTelemetry() {
55
- return this.telemetry;
56
- }
57
- /*
58
- get experimental_telemetry config
59
- */
60
- get experimental_telemetry() {
61
- return this.telemetry ? {
62
- tracer: this.telemetry.tracer,
63
- isEnabled: !!this.telemetry.tracer
64
- } : undefined;
65
- }
66
- };
67
- __name(_MastraBase, "MastraBase");
68
- var MastraBase = _MastraBase;
69
-
70
- export { MastraBase };
@@ -1,90 +0,0 @@
1
- import { __name } from './chunk-AJJZUHB4.js';
2
-
3
- // src/hooks/mitt.ts
4
- function mitt(all) {
5
- all = all || /* @__PURE__ */ new Map();
6
- return {
7
- /**
8
- * A Map of event names to registered handler functions.
9
- */
10
- all,
11
- /**
12
- * Register an event handler for the given type.
13
- * @param {string|symbol} type Type of event to listen for, or `'*'` for all events
14
- * @param {Function} handler Function to call in response to given event
15
- * @memberOf mitt
16
- */
17
- on(type, handler) {
18
- const handlers = all.get(type);
19
- if (handlers) {
20
- handlers.push(handler);
21
- } else {
22
- all.set(type, [
23
- handler
24
- ]);
25
- }
26
- },
27
- /**
28
- * Remove an event handler for the given type.
29
- * If `handler` is omitted, all handlers of the given type are removed.
30
- * @param {string|symbol} type Type of event to unregister `handler` from (`'*'` to remove a wildcard handler)
31
- * @param {Function} [handler] Handler function to remove
32
- * @memberOf mitt
33
- */
34
- off(type, handler) {
35
- const handlers = all.get(type);
36
- if (handlers) {
37
- if (handler) {
38
- handlers.splice(handlers.indexOf(handler) >>> 0, 1);
39
- } else {
40
- all.set(type, []);
41
- }
42
- }
43
- },
44
- /**
45
- * Invoke all handlers for the given type.
46
- * If present, `'*'` handlers are invoked after type-matched handlers.
47
- *
48
- * Note: Manually firing '*' handlers is not supported.
49
- *
50
- * @param {string|symbol} type The event type to invoke
51
- * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
52
- * @memberOf mitt
53
- */
54
- emit(type, evt) {
55
- let handlers = all.get(type);
56
- if (handlers) {
57
- handlers.slice().map((handler) => {
58
- handler(evt);
59
- });
60
- }
61
- handlers = all.get("*");
62
- if (handlers) {
63
- handlers.slice().map((handler) => {
64
- handler(type, evt);
65
- });
66
- }
67
- }
68
- };
69
- }
70
- __name(mitt, "mitt");
71
-
72
- // src/hooks/index.ts
73
- var AvailableHooks = /* @__PURE__ */ function(AvailableHooks2) {
74
- AvailableHooks2["ON_EVALUATION"] = "onEvaluation";
75
- AvailableHooks2["ON_GENERATION"] = "onGeneration";
76
- return AvailableHooks2;
77
- }({});
78
- var hooks = mitt();
79
- function registerHook(hook, action) {
80
- hooks.on(hook, action);
81
- }
82
- __name(registerHook, "registerHook");
83
- function executeHook(hook, data) {
84
- setImmediate(() => {
85
- hooks.emit(hook, data);
86
- });
87
- }
88
- __name(executeHook, "executeHook");
89
-
90
- export { AvailableHooks, executeHook, registerHook };
@@ -1,222 +0,0 @@
1
- import { DefaultStorage } from './chunk-Z7JFMQZZ.js';
2
- import { deepMerge } from './chunk-KNPBNSJ7.js';
3
- import { MastraBase } from './chunk-G4MCO7XF.js';
4
- import { __name, __publicField } from './chunk-AJJZUHB4.js';
5
-
6
- // src/memory/index.ts
7
- var _MastraMemory = class _MastraMemory extends MastraBase {
8
- constructor(config) {
9
- super({
10
- component: "MEMORY",
11
- name: config.name
12
- });
13
- __publicField(this, "MAX_CONTEXT_TOKENS");
14
- __publicField(this, "storage");
15
- __publicField(this, "vector");
16
- __publicField(this, "embedder");
17
- __publicField(this, "threadConfig", {
18
- lastMessages: 40,
19
- semanticRecall: false
20
- });
21
- this.storage = config.storage || new DefaultStorage({
22
- config: {
23
- url: "file:memory.db"
24
- }
25
- });
26
- if (config.vector) {
27
- this.vector = config.vector;
28
- this.threadConfig.semanticRecall = true;
29
- }
30
- if (config.embedder) {
31
- this.embedder = config.embedder;
32
- }
33
- if (config.options) {
34
- this.threadConfig = this.getMergedThreadConfig(config.options);
35
- }
36
- }
37
- /**
38
- * Get a system message to inject into the conversation.
39
- * This will be called before each conversation turn.
40
- * Implementations can override this to inject custom system messages.
41
- */
42
- async getSystemMessage(_input) {
43
- return null;
44
- }
45
- async createEmbeddingIndex() {
46
- if (!this.vector) {
47
- throw new Error(`Cannot call MastraMemory.createEmbeddingIndex() without a vector db attached.`);
48
- }
49
- const defaultDimensions = 1536;
50
- const dimensionsByModelId = {
51
- "bge-small-en-v1.5": 384,
52
- "bge-base-en-v1.5": 768
53
- };
54
- const dimensions = dimensionsByModelId[this.getEmbedder().modelId] || defaultDimensions;
55
- const isDefault = dimensions === defaultDimensions;
56
- const indexName = isDefault ? "memory_messages" : `memory_messages_${dimensions}`;
57
- await this.vector.createIndex(indexName, dimensions);
58
- return {
59
- indexName
60
- };
61
- }
62
- getEmbedder() {
63
- if (!this.embedder) {
64
- throw new Error(`Cannot use vector features without setting new Memory({ embedder: embedderInstance })
65
-
66
- For example:
67
-
68
- new Memory({
69
- vector,
70
- embedder: openai("text-embedding-3-small") // example
71
- });
72
- `);
73
- }
74
- return this.embedder;
75
- }
76
- getMergedThreadConfig(config) {
77
- return deepMerge(this.threadConfig, config || {});
78
- }
79
- estimateTokens(text) {
80
- return Math.ceil(text.split(" ").length * 1.3);
81
- }
82
- parseMessages(messages) {
83
- return messages.map((msg) => ({
84
- ...msg,
85
- content: typeof msg.content === "string" && (msg.content.startsWith("[") || msg.content.startsWith("{")) ? JSON.parse(msg.content) : msg.content
86
- }));
87
- }
88
- convertToUIMessages(messages) {
89
- function addToolMessageToChat({ toolMessage, messages: messages2, toolResultContents }) {
90
- const chatMessages2 = messages2.map((message) => {
91
- if (message.toolInvocations) {
92
- return {
93
- ...message,
94
- toolInvocations: message.toolInvocations.map((toolInvocation) => {
95
- const toolResult = toolMessage.content.find((tool) => tool.toolCallId === toolInvocation.toolCallId);
96
- if (toolResult) {
97
- return {
98
- ...toolInvocation,
99
- state: "result",
100
- result: toolResult.result
101
- };
102
- }
103
- return toolInvocation;
104
- })
105
- };
106
- }
107
- return message;
108
- });
109
- const resultContents = [
110
- ...toolResultContents,
111
- ...toolMessage.content
112
- ];
113
- return {
114
- chatMessages: chatMessages2,
115
- toolResultContents: resultContents
116
- };
117
- }
118
- __name(addToolMessageToChat, "addToolMessageToChat");
119
- const { chatMessages } = messages.reduce((obj, message) => {
120
- if (message.role === "tool") {
121
- return addToolMessageToChat({
122
- toolMessage: message,
123
- messages: obj.chatMessages,
124
- toolResultContents: obj.toolResultContents
125
- });
126
- }
127
- let textContent = "";
128
- let toolInvocations = [];
129
- if (typeof message.content === "string") {
130
- textContent = message.content;
131
- } else if (Array.isArray(message.content)) {
132
- for (const content of message.content) {
133
- if (content.type === "text") {
134
- textContent += content.text;
135
- } else if (content.type === "tool-call") {
136
- const toolResult = obj.toolResultContents.find((tool) => tool.toolCallId === content.toolCallId);
137
- toolInvocations.push({
138
- state: toolResult ? "result" : "call",
139
- toolCallId: content.toolCallId,
140
- toolName: content.toolName,
141
- args: content.args,
142
- result: toolResult?.result
143
- });
144
- }
145
- }
146
- }
147
- obj.chatMessages.push({
148
- id: message.id,
149
- role: message.role,
150
- content: textContent,
151
- toolInvocations
152
- });
153
- return obj;
154
- }, {
155
- chatMessages: [],
156
- toolResultContents: []
157
- });
158
- return chatMessages;
159
- }
160
- /**
161
- * Helper method to create a new thread
162
- * @param title - Optional title for the thread
163
- * @param metadata - Optional metadata for the thread
164
- * @returns Promise resolving to the created thread
165
- */
166
- async createThread({ threadId, resourceId, title, metadata, memoryConfig }) {
167
- const thread = {
168
- id: threadId || this.generateId(),
169
- title: title || "New Thread",
170
- resourceId,
171
- createdAt: /* @__PURE__ */ new Date(),
172
- updatedAt: /* @__PURE__ */ new Date(),
173
- metadata
174
- };
175
- return this.saveThread({
176
- thread,
177
- memoryConfig
178
- });
179
- }
180
- /**
181
- * Helper method to add a single message to a thread
182
- * @param threadId - The thread to add the message to
183
- * @param content - The message content
184
- * @param role - The role of the message sender
185
- * @param type - The type of the message
186
- * @param toolNames - Optional array of tool names that were called
187
- * @param toolCallArgs - Optional array of tool call arguments
188
- * @param toolCallIds - Optional array of tool call ids
189
- * @returns Promise resolving to the saved message
190
- */
191
- async addMessage({ threadId, config, content, role, type, toolNames, toolCallArgs, toolCallIds }) {
192
- const message = {
193
- id: this.generateId(),
194
- content,
195
- role,
196
- createdAt: /* @__PURE__ */ new Date(),
197
- threadId,
198
- type,
199
- toolNames,
200
- toolCallArgs,
201
- toolCallIds
202
- };
203
- const savedMessages = await this.saveMessages({
204
- messages: [
205
- message
206
- ],
207
- memoryConfig: config
208
- });
209
- return savedMessages[0];
210
- }
211
- /**
212
- * Generates a unique identifier
213
- * @returns A unique string ID
214
- */
215
- generateId() {
216
- return crypto.randomUUID();
217
- }
218
- };
219
- __name(_MastraMemory, "MastraMemory");
220
- var MastraMemory = _MastraMemory;
221
-
222
- export { MastraMemory };
@@ -1,16 +0,0 @@
1
- import { MastraBundler } from './chunk-MCB4M5W4.js';
2
- import { __name } from './chunk-AJJZUHB4.js';
3
-
4
- // src/deployer/index.ts
5
- var _MastraDeployer = class _MastraDeployer extends MastraBundler {
6
- constructor({ name }) {
7
- super({
8
- component: "DEPLOYER",
9
- name
10
- });
11
- }
12
- };
13
- __name(_MastraDeployer, "MastraDeployer");
14
- var MastraDeployer = _MastraDeployer;
15
-
16
- export { MastraDeployer };