@mastra/editor 0.0.0-om-20260204032032

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 ADDED
@@ -0,0 +1,67 @@
1
+ # @mastra/editor
2
+
3
+ ## 0.0.0-om-20260204032032
4
+
5
+ ### Minor Changes
6
+
7
+ - Created @mastra/editor package for managing and resolving stored agent configurations ([#12631](https://github.com/mastra-ai/mastra/pull/12631))
8
+
9
+ This major addition introduces the editor package, which provides a complete solution for storing, versioning, and instantiating agent configurations from a database. The editor seamlessly integrates with Mastra's storage layer to enable dynamic agent management.
10
+
11
+ **Key Features:**
12
+ - **Agent Storage & Retrieval**: Store complete agent configurations including instructions, model settings, tools, workflows, nested agents, scorers, processors, and memory configuration
13
+ - **Version Management**: Create and manage multiple versions of agents, with support for activating specific versions
14
+ - **Dependency Resolution**: Automatically resolves and instantiates all agent dependencies (tools, workflows, sub-agents, etc.) from the Mastra registry
15
+ - **Caching**: Built-in caching for improved performance when repeatedly accessing stored agents
16
+ - **Type Safety**: Full TypeScript support with proper typing for stored configurations
17
+
18
+ **Usage Example:**
19
+
20
+ ```typescript
21
+ import { MastraEditor } from '@mastra/editor';
22
+ import { Mastra } from '@mastra/core';
23
+
24
+ // Initialize editor with Mastra
25
+ const mastra = new Mastra({
26
+ /* config */
27
+ editor: new MastraEditor(),
28
+ });
29
+
30
+ // Store an agent configuration
31
+ const agentId = await mastra.storage.stores?.agents?.createAgent({
32
+ name: 'customer-support',
33
+ instructions: 'Help customers with inquiries',
34
+ model: { provider: 'openai', name: 'gpt-4' },
35
+ tools: ['search-kb', 'create-ticket'],
36
+ workflows: ['escalation-flow'],
37
+ memory: { vector: 'pinecone-db' },
38
+ });
39
+
40
+ // Retrieve and use the stored agent
41
+ const agent = await mastra.getEditor()?.getStoredAgentById(agentId);
42
+ const response = await agent?.generate('How do I reset my password?');
43
+
44
+ // List all stored agents
45
+ const agents = await mastra.getEditor()?.listStoredAgents({ pageSize: 10 });
46
+ ```
47
+
48
+ **Storage Improvements:**
49
+ - Fixed JSONB handling in LibSQL, PostgreSQL, and MongoDB adapters
50
+ - Improved agent resolution queries to properly merge version data
51
+ - Enhanced type safety for serialized configurations
52
+
53
+ ### Patch Changes
54
+
55
+ - Updated dependencies [[`e6fc281`](https://github.com/mastra-ai/mastra/commit/e6fc281896a3584e9e06465b356a44fe7faade65), [`97be6c8`](https://github.com/mastra-ai/mastra/commit/97be6c8963130fca8a664fcf99d7b3a38e463595), [`e41c549`](https://github.com/mastra-ai/mastra/commit/e41c549e51f45ecdfa12473b7d97ce29d3fa7fd2), [`b1695db`](https://github.com/mastra-ai/mastra/commit/b1695db2d7be0c329d499619c7881899649188d0), [`5fe1fe0`](https://github.com/mastra-ai/mastra/commit/5fe1fe0109faf2c87db34b725d8a4571a594f80e), [`13e0a2a`](https://github.com/mastra-ai/mastra/commit/13e0a2a2bcec01ff4d701274b3727d5e907a6a01), [`f6673b8`](https://github.com/mastra-ai/mastra/commit/f6673b893b65b7d273ad25ead42e990704cc1e17), [`cd6be8a`](https://github.com/mastra-ai/mastra/commit/cd6be8ad32741cd41cabf508355bb31b71e8a5bd), [`9eb4e8e`](https://github.com/mastra-ai/mastra/commit/9eb4e8e39efbdcfff7a40ff2ce07ce2714c65fa8), [`aa37c84`](https://github.com/mastra-ai/mastra/commit/aa37c84d29b7db68c72517337932ef486c316275), [`47eba72`](https://github.com/mastra-ai/mastra/commit/47eba72f0397d0d14fbe324b97940c3d55e5a525)]:
56
+ - @mastra/core@0.0.0-om-20260204032032
57
+ - @mastra/memory@0.0.0-om-20260204032032
58
+
59
+ ## 0.1.0
60
+
61
+ ### Minor Changes
62
+
63
+ - Initial release of @mastra/editor
64
+ - Agent storage and retrieval from database
65
+ - Dynamic agent creation from stored configurations
66
+ - Support for tools, workflows, nested agents, memory, and scorers
67
+ - Integration with Mastra core for seamless agent management
package/LICENSE.md ADDED
@@ -0,0 +1,15 @@
1
+ # Apache License 2.0
2
+
3
+ Copyright (c) 2025 Kepler Software, Inc.
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
package/dist/index.cjs ADDED
@@ -0,0 +1,424 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ MastraEditor: () => MastraEditor
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+ var import_memory = require("@mastra/memory");
27
+ var import_core = require("@mastra/core");
28
+ var MastraEditor = class {
29
+ constructor(config) {
30
+ this.logger = config?.logger;
31
+ }
32
+ /**
33
+ * Register this editor with a Mastra instance.
34
+ * This gives the editor access to Mastra's storage, tools, workflows, etc.
35
+ */
36
+ registerWithMastra(mastra) {
37
+ this.mastra = mastra;
38
+ if (!this.logger) {
39
+ this.logger = mastra.getLogger();
40
+ }
41
+ }
42
+ /**
43
+ * Get the agents storage domain from the Mastra storage.
44
+ */
45
+ async getAgentsStore() {
46
+ const storage = this.mastra.getStorage();
47
+ if (!storage) throw new Error("Storage is not configured");
48
+ const agentsStore = await storage.getStore("agents");
49
+ if (!agentsStore) throw new Error("Agents storage domain is not available");
50
+ return agentsStore;
51
+ }
52
+ async getStoredAgentById(id, options) {
53
+ if (!this.mastra) {
54
+ throw new Error("MastraEditor is not registered with a Mastra instance");
55
+ }
56
+ const agentsStore = await this.getAgentsStore();
57
+ if (options?.versionId && options?.versionNumber !== void 0) {
58
+ this.logger?.warn(`Both versionId and versionNumber provided for agent "${id}". Using versionId.`);
59
+ }
60
+ if (options?.versionId) {
61
+ const version = await agentsStore.getVersion(options.versionId);
62
+ if (!version) {
63
+ return null;
64
+ }
65
+ if (version.agentId !== id) {
66
+ return null;
67
+ }
68
+ const {
69
+ id: _versionId,
70
+ agentId: _agentId,
71
+ versionNumber: _versionNumber,
72
+ changedFields: _changedFields,
73
+ changeMessage: _changeMessage,
74
+ createdAt: _createdAt,
75
+ ...snapshotConfig
76
+ } = version;
77
+ const agentRecord = await agentsStore.getAgentById({ id });
78
+ if (!agentRecord) {
79
+ return null;
80
+ }
81
+ const { activeVersionId: _activeVersionId, ...agentRecordWithoutActiveVersion } = agentRecord;
82
+ const resolvedAgent = { ...agentRecordWithoutActiveVersion, ...snapshotConfig };
83
+ if (options?.returnRaw) {
84
+ return resolvedAgent;
85
+ }
86
+ return this.createAgentFromStoredConfig(resolvedAgent);
87
+ }
88
+ if (options?.versionNumber !== void 0) {
89
+ const version = await agentsStore.getVersionByNumber(id, options.versionNumber);
90
+ if (!version) {
91
+ return null;
92
+ }
93
+ const {
94
+ id: _versionId,
95
+ agentId: _agentId,
96
+ versionNumber: _versionNumber,
97
+ changedFields: _changedFields,
98
+ changeMessage: _changeMessage,
99
+ createdAt: _createdAt,
100
+ ...snapshotConfig
101
+ } = version;
102
+ const agentRecord = await agentsStore.getAgentById({ id });
103
+ if (!agentRecord) {
104
+ return null;
105
+ }
106
+ const { activeVersionId: _activeVersionId, ...agentRecordWithoutActiveVersion } = agentRecord;
107
+ const resolvedAgent = { ...agentRecordWithoutActiveVersion, ...snapshotConfig };
108
+ if (options?.returnRaw) {
109
+ return resolvedAgent;
110
+ }
111
+ return this.createAgentFromStoredConfig(resolvedAgent);
112
+ }
113
+ if (!options?.returnRaw) {
114
+ const agentCache2 = this.mastra.getStoredAgentCache();
115
+ if (agentCache2) {
116
+ const cached = agentCache2.get(id);
117
+ if (cached) {
118
+ this.logger?.debug(`[getStoredAgentById] Returning cached agent "${id}"`);
119
+ return cached;
120
+ }
121
+ this.logger?.debug(`[getStoredAgentById] Cache miss for agent "${id}", fetching from storage`);
122
+ }
123
+ }
124
+ const storedAgent = await agentsStore.getAgentByIdResolved({ id });
125
+ if (!storedAgent) {
126
+ return null;
127
+ }
128
+ if (options?.returnRaw) {
129
+ return storedAgent;
130
+ }
131
+ const agent = this.createAgentFromStoredConfig(storedAgent);
132
+ const agentCache = this.mastra.getStoredAgentCache();
133
+ if (agentCache) {
134
+ agentCache.set(id, agent);
135
+ }
136
+ return agent;
137
+ }
138
+ async listStoredAgents(options) {
139
+ if (!this.mastra) {
140
+ throw new Error("MastraEditor is not registered with a Mastra instance");
141
+ }
142
+ const agentsStore = await this.getAgentsStore();
143
+ const result = await agentsStore.listAgentsResolved({
144
+ page: options?.page,
145
+ perPage: options?.pageSize,
146
+ orderBy: { field: "createdAt", direction: "DESC" }
147
+ });
148
+ if (options?.returnRaw) {
149
+ return result;
150
+ }
151
+ const agents = result.agents.map(
152
+ (storedAgent) => this.createAgentFromStoredConfig(storedAgent)
153
+ );
154
+ return {
155
+ agents,
156
+ total: result.total,
157
+ page: result.page,
158
+ perPage: result.perPage,
159
+ hasMore: result.hasMore
160
+ };
161
+ }
162
+ /**
163
+ * Clear the stored agent cache for a specific agent ID, or all cached agents.
164
+ */
165
+ clearStoredAgentCache(agentId) {
166
+ if (!this.mastra) return;
167
+ const agentCache = this.mastra.getStoredAgentCache();
168
+ if (!agentCache) return;
169
+ if (agentId) {
170
+ agentCache.delete(agentId);
171
+ this.logger?.debug(`[clearStoredAgentCache] Cleared cache for agent "${agentId}"`);
172
+ } else {
173
+ agentCache.clear();
174
+ this.logger?.debug("[clearStoredAgentCache] Cleared all cached agents");
175
+ }
176
+ }
177
+ /**
178
+ * Create an Agent instance from stored configuration.
179
+ * Resolves all stored references (tools, workflows, agents, memory, scorers)
180
+ * and registers the agent with the Mastra instance.
181
+ */
182
+ createAgentFromStoredConfig(storedAgent) {
183
+ if (!this.mastra) {
184
+ throw new Error("MastraEditor is not registered with a Mastra instance");
185
+ }
186
+ this.logger?.debug(`[createAgentFromStoredConfig] Creating agent from stored config "${storedAgent.id}"`);
187
+ const tools = this.resolveStoredTools(storedAgent.tools);
188
+ const workflows = this.resolveStoredWorkflows(storedAgent.workflows);
189
+ const agents = this.resolveStoredAgents(storedAgent.agents);
190
+ const memory = this.resolveStoredMemory(storedAgent.memory);
191
+ console.log(
192
+ `[createAgentFromStoredConfig] Resolved memory: ${memory ? "Memory instance created" : "No memory"} for agent "${storedAgent.id}"`,
193
+ { memory }
194
+ );
195
+ const scorers = this.resolveStoredScorers(storedAgent.scorers);
196
+ const inputProcessors = this.resolveStoredInputProcessors(storedAgent.inputProcessors);
197
+ const outputProcessors = this.resolveStoredOutputProcessors(storedAgent.outputProcessors);
198
+ const modelConfig = storedAgent.model;
199
+ if (!modelConfig || !modelConfig.provider || !modelConfig.name) {
200
+ throw new Error(
201
+ `Stored agent "${storedAgent.id}" has no active version or invalid model configuration. Both provider and name are required.`
202
+ );
203
+ }
204
+ const model = `${modelConfig.provider}/${modelConfig.name}`;
205
+ const defaultOptions = storedAgent.defaultOptions;
206
+ const agent = new import_core.Agent({
207
+ id: storedAgent.id,
208
+ name: storedAgent.name,
209
+ description: storedAgent.description,
210
+ instructions: storedAgent.instructions,
211
+ model,
212
+ memory,
213
+ tools,
214
+ workflows,
215
+ agents,
216
+ scorers,
217
+ mastra: this.mastra,
218
+ inputProcessors,
219
+ outputProcessors,
220
+ defaultOptions: {
221
+ maxSteps: defaultOptions?.maxSteps,
222
+ modelSettings: {
223
+ temperature: modelConfig.temperature,
224
+ topP: modelConfig.topP,
225
+ frequencyPenalty: modelConfig.frequencyPenalty,
226
+ presencePenalty: modelConfig.presencePenalty,
227
+ maxOutputTokens: modelConfig.maxCompletionTokens
228
+ }
229
+ }
230
+ });
231
+ this.mastra?.addAgent(agent, storedAgent.id, { source: "stored" });
232
+ this.logger?.debug(`[createAgentFromStoredConfig] Successfully created agent "${storedAgent.id}"`);
233
+ return agent;
234
+ }
235
+ /**
236
+ * Resolve stored tool IDs to actual tool instances from Mastra's registry.
237
+ */
238
+ resolveStoredTools(storedTools) {
239
+ if (!storedTools || storedTools.length === 0) {
240
+ return {};
241
+ }
242
+ if (!this.mastra) {
243
+ return {};
244
+ }
245
+ const resolvedTools = {};
246
+ for (const toolKey of storedTools) {
247
+ try {
248
+ const tool = this.mastra.getToolById(toolKey);
249
+ resolvedTools[toolKey] = tool;
250
+ } catch {
251
+ this.logger?.warn(`Tool "${toolKey}" referenced in stored agent but not registered in Mastra`);
252
+ }
253
+ }
254
+ return resolvedTools;
255
+ }
256
+ /**
257
+ * Resolve stored workflow IDs to actual workflow instances from Mastra's registry.
258
+ */
259
+ resolveStoredWorkflows(storedWorkflows) {
260
+ if (!storedWorkflows || storedWorkflows.length === 0) {
261
+ return {};
262
+ }
263
+ if (!this.mastra) {
264
+ return {};
265
+ }
266
+ const resolvedWorkflows = {};
267
+ for (const workflowKey of storedWorkflows) {
268
+ try {
269
+ const workflow = this.mastra.getWorkflow(workflowKey);
270
+ resolvedWorkflows[workflowKey] = workflow;
271
+ } catch {
272
+ try {
273
+ const workflow = this.mastra.getWorkflowById(workflowKey);
274
+ resolvedWorkflows[workflowKey] = workflow;
275
+ } catch {
276
+ this.logger?.warn(`Workflow "${workflowKey}" referenced in stored agent but not registered in Mastra`);
277
+ }
278
+ }
279
+ }
280
+ return resolvedWorkflows;
281
+ }
282
+ /**
283
+ * Resolve stored agent IDs to actual agent instances from Mastra's registry.
284
+ */
285
+ resolveStoredAgents(storedAgents) {
286
+ if (!storedAgents || storedAgents.length === 0) {
287
+ return {};
288
+ }
289
+ if (!this.mastra) {
290
+ return {};
291
+ }
292
+ const resolvedAgents = {};
293
+ for (const agentKey of storedAgents) {
294
+ try {
295
+ const agent = this.mastra.getAgent(agentKey);
296
+ resolvedAgents[agentKey] = agent;
297
+ } catch {
298
+ try {
299
+ const agent = this.mastra.getAgentById(agentKey);
300
+ resolvedAgents[agentKey] = agent;
301
+ } catch {
302
+ this.logger?.warn(`Agent "${agentKey}" referenced in stored agent but not registered in Mastra`);
303
+ }
304
+ }
305
+ }
306
+ return resolvedAgents;
307
+ }
308
+ /**
309
+ * Resolve stored memory config to a MastraMemory instance.
310
+ * Uses @mastra/memory Memory class to instantiate from serialized config.
311
+ */
312
+ resolveStoredMemory(memoryConfig) {
313
+ this.logger?.debug(`[resolveStoredMemory] Called with config:`, { memoryConfig });
314
+ if (!memoryConfig) {
315
+ this.logger?.debug(`[resolveStoredMemory] No memory config provided`);
316
+ return void 0;
317
+ }
318
+ if (!this.mastra) {
319
+ this.logger?.warn("MastraEditor not registered with Mastra instance. Cannot instantiate memory.");
320
+ return void 0;
321
+ }
322
+ try {
323
+ let vector;
324
+ if (memoryConfig.vector) {
325
+ const vectors = this.mastra.listVectors();
326
+ vector = vectors?.[memoryConfig.vector];
327
+ if (!vector) {
328
+ this.logger?.warn(`Vector provider "${memoryConfig.vector}" not found in Mastra instance`);
329
+ }
330
+ }
331
+ const sharedConfig = {
332
+ storage: this.mastra.getStorage(),
333
+ vector,
334
+ options: memoryConfig.options,
335
+ embedder: memoryConfig.embedder,
336
+ embedderOptions: memoryConfig.embedderOptions
337
+ };
338
+ return new import_memory.Memory(sharedConfig);
339
+ } catch (error) {
340
+ this.logger?.error("Failed to resolve memory from config", { error });
341
+ return void 0;
342
+ }
343
+ }
344
+ /**
345
+ * Resolve stored scorer configs to MastraScorers instances.
346
+ */
347
+ resolveStoredScorers(storedScorers) {
348
+ if (!storedScorers || Object.keys(storedScorers).length === 0) {
349
+ return void 0;
350
+ }
351
+ if (!this.mastra) {
352
+ return void 0;
353
+ }
354
+ const resolvedScorers = {};
355
+ for (const [scorerKey, scorerConfig] of Object.entries(storedScorers)) {
356
+ try {
357
+ const scorer = this.mastra.getScorer(scorerKey);
358
+ resolvedScorers[scorerKey] = {
359
+ scorer,
360
+ sampling: scorerConfig.sampling
361
+ };
362
+ } catch {
363
+ try {
364
+ const scorer = this.mastra.getScorerById(scorerKey);
365
+ resolvedScorers[scorerKey] = {
366
+ scorer,
367
+ sampling: scorerConfig.sampling
368
+ };
369
+ } catch {
370
+ this.logger?.warn(`Scorer "${scorerKey}" referenced in stored agent but not registered in Mastra`);
371
+ }
372
+ }
373
+ }
374
+ return Object.keys(resolvedScorers).length > 0 ? resolvedScorers : void 0;
375
+ }
376
+ /**
377
+ * Look up a processor by key or ID from Mastra's registry.
378
+ */
379
+ findProcessor(processorKey) {
380
+ if (!this.mastra) return void 0;
381
+ try {
382
+ return this.mastra.getProcessor(processorKey);
383
+ } catch {
384
+ try {
385
+ return this.mastra.getProcessorById(processorKey);
386
+ } catch {
387
+ this.logger?.warn(`Processor "${processorKey}" referenced in stored agent but not registered in Mastra`);
388
+ return void 0;
389
+ }
390
+ }
391
+ }
392
+ /**
393
+ * Resolve stored input processor keys to actual processor instances.
394
+ */
395
+ resolveStoredInputProcessors(storedProcessors) {
396
+ if (!storedProcessors || storedProcessors.length === 0) return void 0;
397
+ const resolved = [];
398
+ for (const key of storedProcessors) {
399
+ const processor = this.findProcessor(key);
400
+ if (processor && (processor.processInput || processor.processInputStep)) {
401
+ resolved.push(processor);
402
+ }
403
+ }
404
+ return resolved.length > 0 ? resolved : void 0;
405
+ }
406
+ /**
407
+ * Resolve stored output processor keys to actual processor instances.
408
+ */
409
+ resolveStoredOutputProcessors(storedProcessors) {
410
+ if (!storedProcessors || storedProcessors.length === 0) return void 0;
411
+ const resolved = [];
412
+ for (const key of storedProcessors) {
413
+ const processor = this.findProcessor(key);
414
+ if (processor && (processor.processOutputStream || processor.processOutputResult || processor.processOutputStep)) {
415
+ resolved.push(processor);
416
+ }
417
+ }
418
+ return resolved.length > 0 ? resolved : void 0;
419
+ }
420
+ };
421
+ // Annotate the CommonJS export names for ESM import in node:
422
+ 0 && (module.exports = {
423
+ MastraEditor
424
+ });
@@ -0,0 +1,102 @@
1
+ import { IMastraEditor, MastraEditorConfig, Mastra, Agent, StorageResolvedAgentType } from '@mastra/core';
2
+ export { MastraEditorConfig } from '@mastra/core';
3
+
4
+ declare class MastraEditor implements IMastraEditor {
5
+ private logger?;
6
+ private mastra?;
7
+ constructor(config?: MastraEditorConfig);
8
+ /**
9
+ * Register this editor with a Mastra instance.
10
+ * This gives the editor access to Mastra's storage, tools, workflows, etc.
11
+ */
12
+ registerWithMastra(mastra: Mastra): void;
13
+ /**
14
+ * Get the agents storage domain from the Mastra storage.
15
+ */
16
+ private getAgentsStore;
17
+ /**
18
+ * Get a stored agent by its ID.
19
+ * Returns null when agent is not found. Returns an Agent instance by default,
20
+ * or raw StorageResolvedAgentType when raw option is true.
21
+ */
22
+ getStoredAgentById(id: string, options?: {
23
+ returnRaw?: false;
24
+ versionId?: string;
25
+ versionNumber?: number;
26
+ }): Promise<Agent | null>;
27
+ getStoredAgentById(id: string, options: {
28
+ returnRaw: true;
29
+ versionId?: string;
30
+ versionNumber?: number;
31
+ }): Promise<StorageResolvedAgentType | null>;
32
+ /**
33
+ * List all stored agents with page-based pagination.
34
+ */
35
+ listStoredAgents(options?: {
36
+ returnRaw?: false;
37
+ page?: number;
38
+ pageSize?: number;
39
+ }): Promise<{
40
+ agents: Agent[];
41
+ total: number;
42
+ page: number;
43
+ perPage: number;
44
+ hasMore: boolean;
45
+ }>;
46
+ listStoredAgents(options: {
47
+ returnRaw: true;
48
+ page?: number;
49
+ pageSize?: number;
50
+ }): Promise<{
51
+ agents: StorageResolvedAgentType[];
52
+ total: number;
53
+ page: number;
54
+ perPage: number;
55
+ hasMore: boolean;
56
+ }>;
57
+ /**
58
+ * Clear the stored agent cache for a specific agent ID, or all cached agents.
59
+ */
60
+ clearStoredAgentCache(agentId?: string): void;
61
+ /**
62
+ * Create an Agent instance from stored configuration.
63
+ * Resolves all stored references (tools, workflows, agents, memory, scorers)
64
+ * and registers the agent with the Mastra instance.
65
+ */
66
+ private createAgentFromStoredConfig;
67
+ /**
68
+ * Resolve stored tool IDs to actual tool instances from Mastra's registry.
69
+ */
70
+ private resolveStoredTools;
71
+ /**
72
+ * Resolve stored workflow IDs to actual workflow instances from Mastra's registry.
73
+ */
74
+ private resolveStoredWorkflows;
75
+ /**
76
+ * Resolve stored agent IDs to actual agent instances from Mastra's registry.
77
+ */
78
+ private resolveStoredAgents;
79
+ /**
80
+ * Resolve stored memory config to a MastraMemory instance.
81
+ * Uses @mastra/memory Memory class to instantiate from serialized config.
82
+ */
83
+ private resolveStoredMemory;
84
+ /**
85
+ * Resolve stored scorer configs to MastraScorers instances.
86
+ */
87
+ private resolveStoredScorers;
88
+ /**
89
+ * Look up a processor by key or ID from Mastra's registry.
90
+ */
91
+ private findProcessor;
92
+ /**
93
+ * Resolve stored input processor keys to actual processor instances.
94
+ */
95
+ private resolveStoredInputProcessors;
96
+ /**
97
+ * Resolve stored output processor keys to actual processor instances.
98
+ */
99
+ private resolveStoredOutputProcessors;
100
+ }
101
+
102
+ export { MastraEditor };
@@ -0,0 +1,102 @@
1
+ import { IMastraEditor, MastraEditorConfig, Mastra, Agent, StorageResolvedAgentType } from '@mastra/core';
2
+ export { MastraEditorConfig } from '@mastra/core';
3
+
4
+ declare class MastraEditor implements IMastraEditor {
5
+ private logger?;
6
+ private mastra?;
7
+ constructor(config?: MastraEditorConfig);
8
+ /**
9
+ * Register this editor with a Mastra instance.
10
+ * This gives the editor access to Mastra's storage, tools, workflows, etc.
11
+ */
12
+ registerWithMastra(mastra: Mastra): void;
13
+ /**
14
+ * Get the agents storage domain from the Mastra storage.
15
+ */
16
+ private getAgentsStore;
17
+ /**
18
+ * Get a stored agent by its ID.
19
+ * Returns null when agent is not found. Returns an Agent instance by default,
20
+ * or raw StorageResolvedAgentType when raw option is true.
21
+ */
22
+ getStoredAgentById(id: string, options?: {
23
+ returnRaw?: false;
24
+ versionId?: string;
25
+ versionNumber?: number;
26
+ }): Promise<Agent | null>;
27
+ getStoredAgentById(id: string, options: {
28
+ returnRaw: true;
29
+ versionId?: string;
30
+ versionNumber?: number;
31
+ }): Promise<StorageResolvedAgentType | null>;
32
+ /**
33
+ * List all stored agents with page-based pagination.
34
+ */
35
+ listStoredAgents(options?: {
36
+ returnRaw?: false;
37
+ page?: number;
38
+ pageSize?: number;
39
+ }): Promise<{
40
+ agents: Agent[];
41
+ total: number;
42
+ page: number;
43
+ perPage: number;
44
+ hasMore: boolean;
45
+ }>;
46
+ listStoredAgents(options: {
47
+ returnRaw: true;
48
+ page?: number;
49
+ pageSize?: number;
50
+ }): Promise<{
51
+ agents: StorageResolvedAgentType[];
52
+ total: number;
53
+ page: number;
54
+ perPage: number;
55
+ hasMore: boolean;
56
+ }>;
57
+ /**
58
+ * Clear the stored agent cache for a specific agent ID, or all cached agents.
59
+ */
60
+ clearStoredAgentCache(agentId?: string): void;
61
+ /**
62
+ * Create an Agent instance from stored configuration.
63
+ * Resolves all stored references (tools, workflows, agents, memory, scorers)
64
+ * and registers the agent with the Mastra instance.
65
+ */
66
+ private createAgentFromStoredConfig;
67
+ /**
68
+ * Resolve stored tool IDs to actual tool instances from Mastra's registry.
69
+ */
70
+ private resolveStoredTools;
71
+ /**
72
+ * Resolve stored workflow IDs to actual workflow instances from Mastra's registry.
73
+ */
74
+ private resolveStoredWorkflows;
75
+ /**
76
+ * Resolve stored agent IDs to actual agent instances from Mastra's registry.
77
+ */
78
+ private resolveStoredAgents;
79
+ /**
80
+ * Resolve stored memory config to a MastraMemory instance.
81
+ * Uses @mastra/memory Memory class to instantiate from serialized config.
82
+ */
83
+ private resolveStoredMemory;
84
+ /**
85
+ * Resolve stored scorer configs to MastraScorers instances.
86
+ */
87
+ private resolveStoredScorers;
88
+ /**
89
+ * Look up a processor by key or ID from Mastra's registry.
90
+ */
91
+ private findProcessor;
92
+ /**
93
+ * Resolve stored input processor keys to actual processor instances.
94
+ */
95
+ private resolveStoredInputProcessors;
96
+ /**
97
+ * Resolve stored output processor keys to actual processor instances.
98
+ */
99
+ private resolveStoredOutputProcessors;
100
+ }
101
+
102
+ export { MastraEditor };
package/dist/index.js ADDED
@@ -0,0 +1,399 @@
1
+ // src/index.ts
2
+ import { Memory } from "@mastra/memory";
3
+ import { Agent } from "@mastra/core";
4
+ var MastraEditor = class {
5
+ constructor(config) {
6
+ this.logger = config?.logger;
7
+ }
8
+ /**
9
+ * Register this editor with a Mastra instance.
10
+ * This gives the editor access to Mastra's storage, tools, workflows, etc.
11
+ */
12
+ registerWithMastra(mastra) {
13
+ this.mastra = mastra;
14
+ if (!this.logger) {
15
+ this.logger = mastra.getLogger();
16
+ }
17
+ }
18
+ /**
19
+ * Get the agents storage domain from the Mastra storage.
20
+ */
21
+ async getAgentsStore() {
22
+ const storage = this.mastra.getStorage();
23
+ if (!storage) throw new Error("Storage is not configured");
24
+ const agentsStore = await storage.getStore("agents");
25
+ if (!agentsStore) throw new Error("Agents storage domain is not available");
26
+ return agentsStore;
27
+ }
28
+ async getStoredAgentById(id, options) {
29
+ if (!this.mastra) {
30
+ throw new Error("MastraEditor is not registered with a Mastra instance");
31
+ }
32
+ const agentsStore = await this.getAgentsStore();
33
+ if (options?.versionId && options?.versionNumber !== void 0) {
34
+ this.logger?.warn(`Both versionId and versionNumber provided for agent "${id}". Using versionId.`);
35
+ }
36
+ if (options?.versionId) {
37
+ const version = await agentsStore.getVersion(options.versionId);
38
+ if (!version) {
39
+ return null;
40
+ }
41
+ if (version.agentId !== id) {
42
+ return null;
43
+ }
44
+ const {
45
+ id: _versionId,
46
+ agentId: _agentId,
47
+ versionNumber: _versionNumber,
48
+ changedFields: _changedFields,
49
+ changeMessage: _changeMessage,
50
+ createdAt: _createdAt,
51
+ ...snapshotConfig
52
+ } = version;
53
+ const agentRecord = await agentsStore.getAgentById({ id });
54
+ if (!agentRecord) {
55
+ return null;
56
+ }
57
+ const { activeVersionId: _activeVersionId, ...agentRecordWithoutActiveVersion } = agentRecord;
58
+ const resolvedAgent = { ...agentRecordWithoutActiveVersion, ...snapshotConfig };
59
+ if (options?.returnRaw) {
60
+ return resolvedAgent;
61
+ }
62
+ return this.createAgentFromStoredConfig(resolvedAgent);
63
+ }
64
+ if (options?.versionNumber !== void 0) {
65
+ const version = await agentsStore.getVersionByNumber(id, options.versionNumber);
66
+ if (!version) {
67
+ return null;
68
+ }
69
+ const {
70
+ id: _versionId,
71
+ agentId: _agentId,
72
+ versionNumber: _versionNumber,
73
+ changedFields: _changedFields,
74
+ changeMessage: _changeMessage,
75
+ createdAt: _createdAt,
76
+ ...snapshotConfig
77
+ } = version;
78
+ const agentRecord = await agentsStore.getAgentById({ id });
79
+ if (!agentRecord) {
80
+ return null;
81
+ }
82
+ const { activeVersionId: _activeVersionId, ...agentRecordWithoutActiveVersion } = agentRecord;
83
+ const resolvedAgent = { ...agentRecordWithoutActiveVersion, ...snapshotConfig };
84
+ if (options?.returnRaw) {
85
+ return resolvedAgent;
86
+ }
87
+ return this.createAgentFromStoredConfig(resolvedAgent);
88
+ }
89
+ if (!options?.returnRaw) {
90
+ const agentCache2 = this.mastra.getStoredAgentCache();
91
+ if (agentCache2) {
92
+ const cached = agentCache2.get(id);
93
+ if (cached) {
94
+ this.logger?.debug(`[getStoredAgentById] Returning cached agent "${id}"`);
95
+ return cached;
96
+ }
97
+ this.logger?.debug(`[getStoredAgentById] Cache miss for agent "${id}", fetching from storage`);
98
+ }
99
+ }
100
+ const storedAgent = await agentsStore.getAgentByIdResolved({ id });
101
+ if (!storedAgent) {
102
+ return null;
103
+ }
104
+ if (options?.returnRaw) {
105
+ return storedAgent;
106
+ }
107
+ const agent = this.createAgentFromStoredConfig(storedAgent);
108
+ const agentCache = this.mastra.getStoredAgentCache();
109
+ if (agentCache) {
110
+ agentCache.set(id, agent);
111
+ }
112
+ return agent;
113
+ }
114
+ async listStoredAgents(options) {
115
+ if (!this.mastra) {
116
+ throw new Error("MastraEditor is not registered with a Mastra instance");
117
+ }
118
+ const agentsStore = await this.getAgentsStore();
119
+ const result = await agentsStore.listAgentsResolved({
120
+ page: options?.page,
121
+ perPage: options?.pageSize,
122
+ orderBy: { field: "createdAt", direction: "DESC" }
123
+ });
124
+ if (options?.returnRaw) {
125
+ return result;
126
+ }
127
+ const agents = result.agents.map(
128
+ (storedAgent) => this.createAgentFromStoredConfig(storedAgent)
129
+ );
130
+ return {
131
+ agents,
132
+ total: result.total,
133
+ page: result.page,
134
+ perPage: result.perPage,
135
+ hasMore: result.hasMore
136
+ };
137
+ }
138
+ /**
139
+ * Clear the stored agent cache for a specific agent ID, or all cached agents.
140
+ */
141
+ clearStoredAgentCache(agentId) {
142
+ if (!this.mastra) return;
143
+ const agentCache = this.mastra.getStoredAgentCache();
144
+ if (!agentCache) return;
145
+ if (agentId) {
146
+ agentCache.delete(agentId);
147
+ this.logger?.debug(`[clearStoredAgentCache] Cleared cache for agent "${agentId}"`);
148
+ } else {
149
+ agentCache.clear();
150
+ this.logger?.debug("[clearStoredAgentCache] Cleared all cached agents");
151
+ }
152
+ }
153
+ /**
154
+ * Create an Agent instance from stored configuration.
155
+ * Resolves all stored references (tools, workflows, agents, memory, scorers)
156
+ * and registers the agent with the Mastra instance.
157
+ */
158
+ createAgentFromStoredConfig(storedAgent) {
159
+ if (!this.mastra) {
160
+ throw new Error("MastraEditor is not registered with a Mastra instance");
161
+ }
162
+ this.logger?.debug(`[createAgentFromStoredConfig] Creating agent from stored config "${storedAgent.id}"`);
163
+ const tools = this.resolveStoredTools(storedAgent.tools);
164
+ const workflows = this.resolveStoredWorkflows(storedAgent.workflows);
165
+ const agents = this.resolveStoredAgents(storedAgent.agents);
166
+ const memory = this.resolveStoredMemory(storedAgent.memory);
167
+ console.log(
168
+ `[createAgentFromStoredConfig] Resolved memory: ${memory ? "Memory instance created" : "No memory"} for agent "${storedAgent.id}"`,
169
+ { memory }
170
+ );
171
+ const scorers = this.resolveStoredScorers(storedAgent.scorers);
172
+ const inputProcessors = this.resolveStoredInputProcessors(storedAgent.inputProcessors);
173
+ const outputProcessors = this.resolveStoredOutputProcessors(storedAgent.outputProcessors);
174
+ const modelConfig = storedAgent.model;
175
+ if (!modelConfig || !modelConfig.provider || !modelConfig.name) {
176
+ throw new Error(
177
+ `Stored agent "${storedAgent.id}" has no active version or invalid model configuration. Both provider and name are required.`
178
+ );
179
+ }
180
+ const model = `${modelConfig.provider}/${modelConfig.name}`;
181
+ const defaultOptions = storedAgent.defaultOptions;
182
+ const agent = new Agent({
183
+ id: storedAgent.id,
184
+ name: storedAgent.name,
185
+ description: storedAgent.description,
186
+ instructions: storedAgent.instructions,
187
+ model,
188
+ memory,
189
+ tools,
190
+ workflows,
191
+ agents,
192
+ scorers,
193
+ mastra: this.mastra,
194
+ inputProcessors,
195
+ outputProcessors,
196
+ defaultOptions: {
197
+ maxSteps: defaultOptions?.maxSteps,
198
+ modelSettings: {
199
+ temperature: modelConfig.temperature,
200
+ topP: modelConfig.topP,
201
+ frequencyPenalty: modelConfig.frequencyPenalty,
202
+ presencePenalty: modelConfig.presencePenalty,
203
+ maxOutputTokens: modelConfig.maxCompletionTokens
204
+ }
205
+ }
206
+ });
207
+ this.mastra?.addAgent(agent, storedAgent.id, { source: "stored" });
208
+ this.logger?.debug(`[createAgentFromStoredConfig] Successfully created agent "${storedAgent.id}"`);
209
+ return agent;
210
+ }
211
+ /**
212
+ * Resolve stored tool IDs to actual tool instances from Mastra's registry.
213
+ */
214
+ resolveStoredTools(storedTools) {
215
+ if (!storedTools || storedTools.length === 0) {
216
+ return {};
217
+ }
218
+ if (!this.mastra) {
219
+ return {};
220
+ }
221
+ const resolvedTools = {};
222
+ for (const toolKey of storedTools) {
223
+ try {
224
+ const tool = this.mastra.getToolById(toolKey);
225
+ resolvedTools[toolKey] = tool;
226
+ } catch {
227
+ this.logger?.warn(`Tool "${toolKey}" referenced in stored agent but not registered in Mastra`);
228
+ }
229
+ }
230
+ return resolvedTools;
231
+ }
232
+ /**
233
+ * Resolve stored workflow IDs to actual workflow instances from Mastra's registry.
234
+ */
235
+ resolveStoredWorkflows(storedWorkflows) {
236
+ if (!storedWorkflows || storedWorkflows.length === 0) {
237
+ return {};
238
+ }
239
+ if (!this.mastra) {
240
+ return {};
241
+ }
242
+ const resolvedWorkflows = {};
243
+ for (const workflowKey of storedWorkflows) {
244
+ try {
245
+ const workflow = this.mastra.getWorkflow(workflowKey);
246
+ resolvedWorkflows[workflowKey] = workflow;
247
+ } catch {
248
+ try {
249
+ const workflow = this.mastra.getWorkflowById(workflowKey);
250
+ resolvedWorkflows[workflowKey] = workflow;
251
+ } catch {
252
+ this.logger?.warn(`Workflow "${workflowKey}" referenced in stored agent but not registered in Mastra`);
253
+ }
254
+ }
255
+ }
256
+ return resolvedWorkflows;
257
+ }
258
+ /**
259
+ * Resolve stored agent IDs to actual agent instances from Mastra's registry.
260
+ */
261
+ resolveStoredAgents(storedAgents) {
262
+ if (!storedAgents || storedAgents.length === 0) {
263
+ return {};
264
+ }
265
+ if (!this.mastra) {
266
+ return {};
267
+ }
268
+ const resolvedAgents = {};
269
+ for (const agentKey of storedAgents) {
270
+ try {
271
+ const agent = this.mastra.getAgent(agentKey);
272
+ resolvedAgents[agentKey] = agent;
273
+ } catch {
274
+ try {
275
+ const agent = this.mastra.getAgentById(agentKey);
276
+ resolvedAgents[agentKey] = agent;
277
+ } catch {
278
+ this.logger?.warn(`Agent "${agentKey}" referenced in stored agent but not registered in Mastra`);
279
+ }
280
+ }
281
+ }
282
+ return resolvedAgents;
283
+ }
284
+ /**
285
+ * Resolve stored memory config to a MastraMemory instance.
286
+ * Uses @mastra/memory Memory class to instantiate from serialized config.
287
+ */
288
+ resolveStoredMemory(memoryConfig) {
289
+ this.logger?.debug(`[resolveStoredMemory] Called with config:`, { memoryConfig });
290
+ if (!memoryConfig) {
291
+ this.logger?.debug(`[resolveStoredMemory] No memory config provided`);
292
+ return void 0;
293
+ }
294
+ if (!this.mastra) {
295
+ this.logger?.warn("MastraEditor not registered with Mastra instance. Cannot instantiate memory.");
296
+ return void 0;
297
+ }
298
+ try {
299
+ let vector;
300
+ if (memoryConfig.vector) {
301
+ const vectors = this.mastra.listVectors();
302
+ vector = vectors?.[memoryConfig.vector];
303
+ if (!vector) {
304
+ this.logger?.warn(`Vector provider "${memoryConfig.vector}" not found in Mastra instance`);
305
+ }
306
+ }
307
+ const sharedConfig = {
308
+ storage: this.mastra.getStorage(),
309
+ vector,
310
+ options: memoryConfig.options,
311
+ embedder: memoryConfig.embedder,
312
+ embedderOptions: memoryConfig.embedderOptions
313
+ };
314
+ return new Memory(sharedConfig);
315
+ } catch (error) {
316
+ this.logger?.error("Failed to resolve memory from config", { error });
317
+ return void 0;
318
+ }
319
+ }
320
+ /**
321
+ * Resolve stored scorer configs to MastraScorers instances.
322
+ */
323
+ resolveStoredScorers(storedScorers) {
324
+ if (!storedScorers || Object.keys(storedScorers).length === 0) {
325
+ return void 0;
326
+ }
327
+ if (!this.mastra) {
328
+ return void 0;
329
+ }
330
+ const resolvedScorers = {};
331
+ for (const [scorerKey, scorerConfig] of Object.entries(storedScorers)) {
332
+ try {
333
+ const scorer = this.mastra.getScorer(scorerKey);
334
+ resolvedScorers[scorerKey] = {
335
+ scorer,
336
+ sampling: scorerConfig.sampling
337
+ };
338
+ } catch {
339
+ try {
340
+ const scorer = this.mastra.getScorerById(scorerKey);
341
+ resolvedScorers[scorerKey] = {
342
+ scorer,
343
+ sampling: scorerConfig.sampling
344
+ };
345
+ } catch {
346
+ this.logger?.warn(`Scorer "${scorerKey}" referenced in stored agent but not registered in Mastra`);
347
+ }
348
+ }
349
+ }
350
+ return Object.keys(resolvedScorers).length > 0 ? resolvedScorers : void 0;
351
+ }
352
+ /**
353
+ * Look up a processor by key or ID from Mastra's registry.
354
+ */
355
+ findProcessor(processorKey) {
356
+ if (!this.mastra) return void 0;
357
+ try {
358
+ return this.mastra.getProcessor(processorKey);
359
+ } catch {
360
+ try {
361
+ return this.mastra.getProcessorById(processorKey);
362
+ } catch {
363
+ this.logger?.warn(`Processor "${processorKey}" referenced in stored agent but not registered in Mastra`);
364
+ return void 0;
365
+ }
366
+ }
367
+ }
368
+ /**
369
+ * Resolve stored input processor keys to actual processor instances.
370
+ */
371
+ resolveStoredInputProcessors(storedProcessors) {
372
+ if (!storedProcessors || storedProcessors.length === 0) return void 0;
373
+ const resolved = [];
374
+ for (const key of storedProcessors) {
375
+ const processor = this.findProcessor(key);
376
+ if (processor && (processor.processInput || processor.processInputStep)) {
377
+ resolved.push(processor);
378
+ }
379
+ }
380
+ return resolved.length > 0 ? resolved : void 0;
381
+ }
382
+ /**
383
+ * Resolve stored output processor keys to actual processor instances.
384
+ */
385
+ resolveStoredOutputProcessors(storedProcessors) {
386
+ if (!storedProcessors || storedProcessors.length === 0) return void 0;
387
+ const resolved = [];
388
+ for (const key of storedProcessors) {
389
+ const processor = this.findProcessor(key);
390
+ if (processor && (processor.processOutputStream || processor.processOutputResult || processor.processOutputStep)) {
391
+ resolved.push(processor);
392
+ }
393
+ }
394
+ return resolved.length > 0 ? resolved : void 0;
395
+ }
396
+ };
397
+ export {
398
+ MastraEditor
399
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@mastra/editor",
3
+ "version": "0.0.0-om-20260204032032",
4
+ "description": "Mastra Editor for agent management and instantiation",
5
+ "main": "dist/index.cjs",
6
+ "module": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "type": "module",
9
+ "files": [
10
+ "dist",
11
+ "CHANGELOG.md"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/mastra-ai/mastra.git",
16
+ "directory": "packages/editor"
17
+ },
18
+ "homepage": "https://mastra.ai",
19
+ "bugs": {
20
+ "url": "https://github.com/mastra-ai/mastra/issues"
21
+ },
22
+ "dependencies": {
23
+ "@mastra/memory": "0.0.0-om-20260204032032"
24
+ },
25
+ "devDependencies": {
26
+ "tsup": "^8.0.2",
27
+ "typescript": "^5.3.3",
28
+ "vitest": "4.0.16",
29
+ "zod": "^3.25.76",
30
+ "@internal/ai-sdk-v4": "0.0.0-om-20260204032032",
31
+ "@internal/ai-sdk-v5": "0.0.0-om-20260204032032",
32
+ "@internal/ai-v6": "0.0.0-om-20260204032032",
33
+ "@mastra/core": "0.0.0-om-20260204032032",
34
+ "@mastra/libsql": "0.0.0-om-20260204032032"
35
+ },
36
+ "peerDependencies": {
37
+ "zod": "^3.25.0 || ^4.0.0",
38
+ "@mastra/core": "0.0.0-om-20260204032032"
39
+ },
40
+ "engines": {
41
+ "node": ">=22.13.0"
42
+ },
43
+ "scripts": {
44
+ "build": "tsup src/index.ts --format cjs,esm --dts",
45
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
46
+ "clean": "rm -rf dist",
47
+ "typecheck": "tsc --noEmit",
48
+ "test": "vitest run",
49
+ "validate:package": "echo 'Validating package.json...'"
50
+ }
51
+ }