@mastra/editor 0.0.0-agent-chat-ui-20260305212602

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,2059 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ CrudEditorNamespace: () => CrudEditorNamespace,
34
+ EditorAgentNamespace: () => EditorAgentNamespace,
35
+ EditorMCPNamespace: () => EditorMCPNamespace,
36
+ EditorMCPServerNamespace: () => EditorMCPServerNamespace,
37
+ EditorNamespace: () => EditorNamespace,
38
+ EditorPromptNamespace: () => EditorPromptNamespace,
39
+ EditorScorerNamespace: () => EditorScorerNamespace,
40
+ EditorSkillNamespace: () => EditorSkillNamespace,
41
+ EditorWorkspaceNamespace: () => EditorWorkspaceNamespace,
42
+ MastraEditor: () => MastraEditor,
43
+ evaluateRuleGroup: () => evaluateRuleGroup,
44
+ localFilesystemProvider: () => localFilesystemProvider,
45
+ localSandboxProvider: () => localSandboxProvider,
46
+ renderTemplate: () => renderTemplate,
47
+ resolveInstructionBlocks: () => resolveInstructionBlocks
48
+ });
49
+ module.exports = __toCommonJS(index_exports);
50
+ var import_processor_provider2 = require("@mastra/core/processor-provider");
51
+
52
+ // src/namespaces/base.ts
53
+ var EditorNamespace = class {
54
+ constructor(editor) {
55
+ this.editor = editor;
56
+ }
57
+ get mastra() {
58
+ return this.editor.__mastra;
59
+ }
60
+ get logger() {
61
+ return this.editor.__logger;
62
+ }
63
+ ensureRegistered() {
64
+ if (!this.editor.__mastra) {
65
+ throw new Error("MastraEditor is not registered with a Mastra instance");
66
+ }
67
+ }
68
+ };
69
+ var CrudEditorNamespace = class extends EditorNamespace {
70
+ constructor() {
71
+ super(...arguments);
72
+ this._cache = /* @__PURE__ */ new Map();
73
+ }
74
+ /**
75
+ * Convert a raw resolved config into a runtime primitive.
76
+ * Override in subclasses that need hydration (e.g. agents → Agent instance).
77
+ * Default implementation returns the resolved config as-is.
78
+ */
79
+ async hydrate(resolved) {
80
+ return resolved;
81
+ }
82
+ /**
83
+ * Hook called when an entity is evicted from the cache (on delete, update, or clearCache).
84
+ * Override in subclasses to also remove the entity from the Mastra runtime registry.
85
+ */
86
+ onCacheEvict(_id) {
87
+ }
88
+ async create(input) {
89
+ this.ensureRegistered();
90
+ const adapter = await this.getStorageAdapter();
91
+ await adapter.create(input);
92
+ const resolved = await adapter.getByIdResolved(input.id);
93
+ if (!resolved) {
94
+ throw new Error(`Failed to resolve entity ${input.id} after creation`);
95
+ }
96
+ const hydrated = await this.hydrate(resolved);
97
+ this._cache.set(input.id, hydrated);
98
+ return hydrated;
99
+ }
100
+ async getById(id, options) {
101
+ this.ensureRegistered();
102
+ const isVersionRequest = options?.versionId || options?.versionNumber || options?.status;
103
+ if (!isVersionRequest) {
104
+ const cached = this._cache.get(id);
105
+ if (cached) {
106
+ this.logger?.debug(`[getById] Cache hit for "${id}"`);
107
+ return cached;
108
+ }
109
+ }
110
+ this.logger?.debug(`[getById] Cache miss for "${id}", fetching from storage`);
111
+ const adapter = await this.getStorageAdapter();
112
+ const resolved = await adapter.getByIdResolved(id, options);
113
+ if (!resolved) return null;
114
+ const hydrated = await this.hydrate(resolved);
115
+ if (!isVersionRequest) {
116
+ this._cache.set(id, hydrated);
117
+ }
118
+ return hydrated;
119
+ }
120
+ async update(input) {
121
+ this.ensureRegistered();
122
+ const adapter = await this.getStorageAdapter();
123
+ await adapter.update(input);
124
+ this._cache.delete(input.id);
125
+ this.onCacheEvict(input.id);
126
+ const resolved = await adapter.getByIdResolved(input.id);
127
+ if (!resolved) {
128
+ throw new Error(`Failed to resolve entity ${input.id} after update`);
129
+ }
130
+ const hydrated = await this.hydrate(resolved);
131
+ this._cache.set(input.id, hydrated);
132
+ return hydrated;
133
+ }
134
+ async delete(id) {
135
+ this.ensureRegistered();
136
+ const adapter = await this.getStorageAdapter();
137
+ await adapter.delete(id);
138
+ this._cache.delete(id);
139
+ this.onCacheEvict(id);
140
+ }
141
+ async list(args) {
142
+ this.ensureRegistered();
143
+ const adapter = await this.getStorageAdapter();
144
+ return adapter.list(args);
145
+ }
146
+ async listResolved(args) {
147
+ this.ensureRegistered();
148
+ const adapter = await this.getStorageAdapter();
149
+ return adapter.listResolved(args);
150
+ }
151
+ /**
152
+ * Clear cached entities. If an id is provided, only that entity is cleared.
153
+ * Otherwise all cached entities in this namespace are cleared.
154
+ */
155
+ clearCache(id) {
156
+ if (id) {
157
+ const wasCached = this._cache.has(id);
158
+ this._cache.delete(id);
159
+ if (wasCached) {
160
+ this.onCacheEvict(id);
161
+ }
162
+ this.logger?.debug(`[clearCache] Cleared cache for "${id}"`);
163
+ } else {
164
+ for (const cachedId of Array.from(this._cache.keys())) {
165
+ this.onCacheEvict(cachedId);
166
+ }
167
+ this._cache.clear();
168
+ this.logger?.debug("[clearCache] Cleared all cached entities");
169
+ }
170
+ }
171
+ };
172
+
173
+ // src/namespaces/agent.ts
174
+ var import_node_crypto = require("crypto");
175
+ var import_memory = require("@mastra/memory");
176
+ var import_agent = require("@mastra/core/agent");
177
+ var import_workspace = require("@mastra/core/workspace");
178
+ var import_schema_compat = require("@mastra/schema-compat");
179
+ var import_request_context = require("@mastra/core/request-context");
180
+
181
+ // src/rule-evaluator.ts
182
+ function resolvePath(context, path) {
183
+ const segments = path.split(".");
184
+ let current = context;
185
+ for (const segment of segments) {
186
+ if (current === null || current === void 0 || typeof current !== "object") {
187
+ return void 0;
188
+ }
189
+ current = current[segment];
190
+ }
191
+ return current;
192
+ }
193
+ function evaluateRule(rule, context) {
194
+ const fieldValue = resolvePath(context, rule.field);
195
+ switch (rule.operator) {
196
+ case "equals":
197
+ return fieldValue === rule.value;
198
+ case "not_equals":
199
+ return fieldValue !== rule.value;
200
+ case "contains": {
201
+ if (typeof fieldValue === "string" && typeof rule.value === "string") {
202
+ return fieldValue.includes(rule.value);
203
+ }
204
+ if (Array.isArray(fieldValue)) {
205
+ return fieldValue.includes(rule.value);
206
+ }
207
+ return false;
208
+ }
209
+ case "not_contains": {
210
+ if (typeof fieldValue === "string" && typeof rule.value === "string") {
211
+ return !fieldValue.includes(rule.value);
212
+ }
213
+ if (Array.isArray(fieldValue)) {
214
+ return !fieldValue.includes(rule.value);
215
+ }
216
+ return true;
217
+ }
218
+ case "greater_than":
219
+ return typeof fieldValue === "number" && typeof rule.value === "number" && fieldValue > rule.value;
220
+ case "less_than":
221
+ return typeof fieldValue === "number" && typeof rule.value === "number" && fieldValue < rule.value;
222
+ case "greater_than_or_equal":
223
+ return typeof fieldValue === "number" && typeof rule.value === "number" && fieldValue >= rule.value;
224
+ case "less_than_or_equal":
225
+ return typeof fieldValue === "number" && typeof rule.value === "number" && fieldValue <= rule.value;
226
+ case "in":
227
+ return Array.isArray(rule.value) && rule.value.includes(fieldValue);
228
+ case "not_in":
229
+ return Array.isArray(rule.value) && !rule.value.includes(fieldValue);
230
+ case "exists":
231
+ return fieldValue !== void 0 && fieldValue !== null;
232
+ case "not_exists":
233
+ return fieldValue === void 0 || fieldValue === null;
234
+ default:
235
+ return false;
236
+ }
237
+ }
238
+ function evaluateRuleGroup(ruleGroup, context) {
239
+ if (ruleGroup.conditions.length === 0) {
240
+ return true;
241
+ }
242
+ const results = ruleGroup.conditions.map((condition) => {
243
+ if ("conditions" in condition) {
244
+ return evaluateRuleGroup(condition, context);
245
+ }
246
+ return evaluateRule(condition, context);
247
+ });
248
+ if (ruleGroup.operator === "AND") {
249
+ return results.every(Boolean);
250
+ }
251
+ return results.some(Boolean);
252
+ }
253
+
254
+ // src/template-engine.ts
255
+ function resolvePath2(context, path) {
256
+ const segments = path.split(".");
257
+ let current = context;
258
+ for (const segment of segments) {
259
+ if (current === null || current === void 0 || typeof current !== "object") {
260
+ return void 0;
261
+ }
262
+ current = current[segment];
263
+ }
264
+ return current;
265
+ }
266
+ var TEMPLATE_PATTERN = /\{\{\s*([a-zA-Z_][\w.]*)\s*(?:\|\|\s*(?:'([^']*)'|"([^"]*)")\s*)?\}\}/g;
267
+ function renderTemplate(template, context) {
268
+ return template.replace(
269
+ TEMPLATE_PATTERN,
270
+ (match, variablePath, singleFallback, doubleFallback) => {
271
+ const resolved = resolvePath2(context, variablePath);
272
+ if (resolved !== void 0 && resolved !== null) {
273
+ return String(resolved);
274
+ }
275
+ const fallback = singleFallback ?? doubleFallback;
276
+ if (fallback !== void 0) {
277
+ return fallback;
278
+ }
279
+ return match;
280
+ }
281
+ );
282
+ }
283
+
284
+ // src/instruction-builder.ts
285
+ async function resolveInstructionBlocks(blocks, context, deps) {
286
+ const segments = [];
287
+ const blockIds = Array.from(
288
+ new Set(
289
+ blocks.filter((b) => b.type === "prompt_block_ref").map((b) => b.id)
290
+ )
291
+ );
292
+ const resolvedBlocksMap = /* @__PURE__ */ new Map();
293
+ if (blockIds.length > 0) {
294
+ const fetchResults = await Promise.all(blockIds.map((id) => deps.promptBlocksStorage.getByIdResolved(id)));
295
+ for (let i = 0; i < blockIds.length; i++) {
296
+ const result = fetchResults[i];
297
+ if (result) {
298
+ resolvedBlocksMap.set(blockIds[i], result);
299
+ }
300
+ }
301
+ }
302
+ for (const block of blocks) {
303
+ if (block.type === "text") {
304
+ const rendered2 = renderTemplate(block.content, context);
305
+ if (rendered2.trim()) {
306
+ segments.push(rendered2);
307
+ }
308
+ continue;
309
+ }
310
+ if (block.type === "prompt_block") {
311
+ if (block.rules) {
312
+ const passes = evaluateRuleGroup(block.rules, context);
313
+ if (!passes) {
314
+ continue;
315
+ }
316
+ }
317
+ const rendered2 = renderTemplate(block.content, context);
318
+ if (rendered2.trim()) {
319
+ segments.push(rendered2);
320
+ }
321
+ continue;
322
+ }
323
+ const resolved = resolvedBlocksMap.get(block.id);
324
+ if (!resolved) {
325
+ continue;
326
+ }
327
+ if (resolved.status !== "published") {
328
+ continue;
329
+ }
330
+ if (resolved.rules) {
331
+ const passes = evaluateRuleGroup(resolved.rules, context);
332
+ if (!passes) {
333
+ continue;
334
+ }
335
+ }
336
+ const rendered = renderTemplate(resolved.content, context);
337
+ if (rendered.trim()) {
338
+ segments.push(rendered);
339
+ }
340
+ }
341
+ return segments.join("\n\n");
342
+ }
343
+
344
+ // src/processor-graph-hydrator.ts
345
+ var import_processors = require("@mastra/core/processors");
346
+ var import_processor_provider = require("@mastra/core/processor-provider");
347
+ var import_workflows = require("@mastra/core/workflows");
348
+ var PASSTHROUGH_STEP_PREFIX = "passthrough-";
349
+ function resolveStep(step, ctx) {
350
+ const provider = ctx.providers[step.providerId];
351
+ if (!provider) {
352
+ ctx.logger?.warn(`ProcessorProvider "${step.providerId}" not found for graph step "${step.id}"`);
353
+ return void 0;
354
+ }
355
+ const processor = provider.createProcessor(step.config);
356
+ const allProviderPhases = provider.availablePhases;
357
+ const enabledSet = new Set(step.enabledPhases);
358
+ const needsFiltering = allProviderPhases.some((p) => !enabledSet.has(p));
359
+ if (needsFiltering) {
360
+ const filtered = new import_processor_provider.PhaseFilteredProcessor(processor, step.enabledPhases);
361
+ if (ctx.mastra) {
362
+ filtered.__registerMastra(ctx.mastra);
363
+ }
364
+ return filtered;
365
+ }
366
+ if (ctx.mastra && processor.__registerMastra) {
367
+ processor.__registerMastra(ctx.mastra);
368
+ }
369
+ return processor;
370
+ }
371
+ function isSequentialOnly(entries) {
372
+ return entries.every((e) => e.type === "step");
373
+ }
374
+ function hydrateSequential(entries, ctx) {
375
+ const processors = [];
376
+ for (const entry of entries) {
377
+ if (entry.type !== "step") continue;
378
+ const processor = resolveStep(entry.step, ctx);
379
+ if (processor) {
380
+ processors.push(processor);
381
+ }
382
+ }
383
+ return processors;
384
+ }
385
+ async function mergeBranchOutputs({ inputData }) {
386
+ const keys = Object.keys(inputData).sort((a, b) => {
387
+ const aPass = a.startsWith(PASSTHROUGH_STEP_PREFIX) ? 1 : 0;
388
+ const bPass = b.startsWith(PASSTHROUGH_STEP_PREFIX) ? 1 : 0;
389
+ return aPass - bPass;
390
+ });
391
+ for (const key of keys) {
392
+ const val = inputData[key];
393
+ if (val && typeof val === "object" && "phase" in val) {
394
+ return {
395
+ phase: val.phase,
396
+ messages: val.messages,
397
+ messageList: val.messageList,
398
+ ...val.systemMessages ? { systemMessages: val.systemMessages } : {},
399
+ ...val.part !== void 0 ? { part: val.part } : {},
400
+ ...val.streamParts ? { streamParts: val.streamParts } : {},
401
+ ...val.state ? { state: val.state } : {},
402
+ ...val.text !== void 0 ? { text: val.text } : {},
403
+ ...val.retryCount !== void 0 ? { retryCount: val.retryCount } : {}
404
+ };
405
+ }
406
+ }
407
+ return inputData;
408
+ }
409
+ function buildWorkflow(entries, workflowId, ctx) {
410
+ let workflow = (0, import_workflows.createWorkflow)({
411
+ id: workflowId,
412
+ inputSchema: import_processors.ProcessorStepSchema,
413
+ outputSchema: import_processors.ProcessorStepSchema,
414
+ type: "processor",
415
+ options: {
416
+ validateInputs: false
417
+ }
418
+ });
419
+ let hasSteps = false;
420
+ for (const entry of entries) {
421
+ if (entry.type === "step") {
422
+ const processor = resolveStep(entry.step, ctx);
423
+ if (!processor) continue;
424
+ const step = (0, import_workflows.createStep)(processor);
425
+ workflow = workflow.then(step);
426
+ hasSteps = true;
427
+ } else if (entry.type === "parallel") {
428
+ const branchSteps = entry.branches.map((branchEntries, branchIdx) => {
429
+ if (branchEntries.length === 1 && branchEntries[0].type === "step") {
430
+ const proc = resolveStep(branchEntries[0].step, ctx);
431
+ if (!proc) return void 0;
432
+ return (0, import_workflows.createStep)(proc);
433
+ }
434
+ const subWorkflow = buildWorkflow(branchEntries, `${workflowId}-parallel-branch-${branchIdx}`, ctx);
435
+ return subWorkflow;
436
+ }).filter(Boolean);
437
+ if (branchSteps.length > 0) {
438
+ workflow = workflow.parallel(branchSteps);
439
+ workflow = workflow.map(mergeBranchOutputs);
440
+ hasSteps = true;
441
+ }
442
+ } else if (entry.type === "conditional") {
443
+ const branchTuples = [];
444
+ for (const [i, condition] of entry.conditions.entries()) {
445
+ let branchStep;
446
+ if (condition.steps.length === 1 && condition.steps[0].type === "step") {
447
+ const proc = resolveStep(condition.steps[0].step, ctx);
448
+ if (!proc) continue;
449
+ branchStep = (0, import_workflows.createStep)(proc);
450
+ } else {
451
+ branchStep = buildWorkflow(condition.steps, `${workflowId}-cond-branch-${i}`, ctx);
452
+ if (!branchStep) continue;
453
+ }
454
+ if (condition.rules) {
455
+ const rules = condition.rules;
456
+ const conditionFn = async ({ inputData }) => {
457
+ return evaluateRuleGroup(rules, inputData);
458
+ };
459
+ branchTuples.push([conditionFn, branchStep]);
460
+ } else {
461
+ branchTuples.push([async () => true, branchStep]);
462
+ }
463
+ }
464
+ if (branchTuples.length > 0) {
465
+ const passthroughStep = (0, import_workflows.createStep)({
466
+ id: `${PASSTHROUGH_STEP_PREFIX}${workflowId}`,
467
+ inputSchema: import_processors.ProcessorStepSchema,
468
+ outputSchema: import_processors.ProcessorStepSchema,
469
+ execute: async ({ inputData }) => inputData
470
+ });
471
+ branchTuples.push([async () => true, passthroughStep]);
472
+ workflow = workflow.branch(branchTuples);
473
+ workflow = workflow.map(mergeBranchOutputs);
474
+ hasSteps = true;
475
+ }
476
+ }
477
+ }
478
+ if (!hasSteps) return void 0;
479
+ return workflow.commit();
480
+ }
481
+ function hydrateProcessorGraph(graph, mode, ctx) {
482
+ if (!graph) return void 0;
483
+ if (Array.isArray(graph)) {
484
+ ctx.logger?.warn(
485
+ "Processor graph is in legacy string[] format and cannot be hydrated. Re-save the agent to migrate."
486
+ );
487
+ return void 0;
488
+ }
489
+ if (!Array.isArray(graph.steps) || graph.steps.length === 0) return void 0;
490
+ if (isSequentialOnly(graph.steps)) {
491
+ const processors = hydrateSequential(graph.steps, ctx);
492
+ if (processors.length === 0) return void 0;
493
+ if (mode === "input") {
494
+ const filtered = processors.filter((p) => p.processInput || p.processInputStep);
495
+ return filtered.length > 0 ? filtered : void 0;
496
+ } else {
497
+ const filtered = processors.filter((p) => p.processOutputStream || p.processOutputResult || p.processOutputStep);
498
+ return filtered.length > 0 ? filtered : void 0;
499
+ }
500
+ }
501
+ const workflowId = `stored-${mode}-processor-graph`;
502
+ const workflow = buildWorkflow(graph.steps, workflowId, ctx);
503
+ if (!workflow) return void 0;
504
+ return [workflow];
505
+ }
506
+ function selectFirstMatchingGraph(variants, context) {
507
+ for (const variant of variants) {
508
+ if (!variant.rules || evaluateRuleGroup(variant.rules, context)) {
509
+ return variant.value;
510
+ }
511
+ }
512
+ return void 0;
513
+ }
514
+
515
+ // src/namespaces/mcp.ts
516
+ var EditorMCPNamespace = class _EditorMCPNamespace extends CrudEditorNamespace {
517
+ onCacheEvict(_id) {
518
+ }
519
+ async getStorageAdapter() {
520
+ const storage = this.mastra?.getStorage();
521
+ if (!storage) throw new Error("Storage is not configured");
522
+ const store = await storage.getStore("mcpClients");
523
+ if (!store) throw new Error("MCP clients storage domain is not available");
524
+ return {
525
+ create: (input) => store.create({ mcpClient: input }),
526
+ getByIdResolved: (id) => store.getByIdResolved(id),
527
+ update: (input) => store.update(input),
528
+ delete: (id) => store.delete(id),
529
+ list: (args) => store.list(args),
530
+ listResolved: (args) => store.listResolved(args)
531
+ };
532
+ }
533
+ /**
534
+ * Convert a stored MCP server config into the shape expected by MCPClient.
535
+ * Converts `url` from string to URL for HTTP servers.
536
+ * Returns a plain object — callers must pass it to `new MCPClient()`.
537
+ */
538
+ static toMCPServerDefinition(serverConfig) {
539
+ if (serverConfig.type === "stdio") {
540
+ return {
541
+ command: serverConfig.command,
542
+ args: serverConfig.args,
543
+ env: serverConfig.env,
544
+ timeout: serverConfig.timeout
545
+ };
546
+ }
547
+ return {
548
+ url: new URL(serverConfig.url),
549
+ timeout: serverConfig.timeout
550
+ };
551
+ }
552
+ /**
553
+ * Convert all servers in a stored MCP client to MCPClientOptions shape.
554
+ */
555
+ static toMCPClientOptions(config) {
556
+ const servers = {};
557
+ for (const [name, serverConfig] of Object.entries(config.servers)) {
558
+ servers[name] = _EditorMCPNamespace.toMCPServerDefinition(serverConfig);
559
+ }
560
+ return { id: config.id, servers };
561
+ }
562
+ };
563
+
564
+ // src/namespaces/agent.ts
565
+ var codeDefaults = /* @__PURE__ */ new WeakMap();
566
+ var EditorAgentNamespace = class extends CrudEditorNamespace {
567
+ async getStorageAdapter() {
568
+ const storage = this.mastra?.getStorage();
569
+ if (!storage) throw new Error("Storage is not configured");
570
+ const store = await storage.getStore("agents");
571
+ if (!store) throw new Error("Agents storage domain is not available");
572
+ return {
573
+ create: (input) => store.create({ agent: input }),
574
+ getByIdResolved: async (id, options) => {
575
+ if (options?.versionId || options?.versionNumber) {
576
+ const agent = await store.getById(id);
577
+ if (!agent) return null;
578
+ const version = options.versionId ? await store.getVersion(options.versionId) : await store.getVersionByNumber(id, options.versionNumber);
579
+ if (!version) return null;
580
+ const {
581
+ id: versionId,
582
+ agentId: _aId,
583
+ versionNumber: _vn,
584
+ changedFields: _cf,
585
+ changeMessage: _cm,
586
+ createdAt: _ca,
587
+ ...snapshotConfig
588
+ } = version;
589
+ return { ...agent, ...snapshotConfig, resolvedVersionId: versionId };
590
+ }
591
+ return store.getByIdResolved(id, options?.status ? { status: options.status } : void 0);
592
+ },
593
+ update: (input) => store.update(input),
594
+ delete: (id) => store.delete(id),
595
+ list: (args) => store.list(args),
596
+ listResolved: (args) => store.listResolved(args)
597
+ };
598
+ }
599
+ /**
600
+ * Hydrate a stored agent config into a runtime Agent instance.
601
+ */
602
+ async hydrate(storedAgent) {
603
+ return this.createAgentFromStoredConfig(storedAgent);
604
+ }
605
+ onCacheEvict(id) {
606
+ try {
607
+ const existing = this.mastra?.getAgentById(id);
608
+ if (existing?.source === "stored") {
609
+ this.mastra?.removeAgent(id);
610
+ }
611
+ } catch {
612
+ }
613
+ }
614
+ /**
615
+ * Evict all cached agents that reference a given skill ID.
616
+ * Called by EditorSkillNamespace after a skill is published so that
617
+ * subsequent agent.getById() calls re-hydrate with the updated skill version.
618
+ */
619
+ invalidateAgentsReferencingSkill(skillId) {
620
+ for (const [agentId, agent] of this._cache.entries()) {
621
+ const raw = agent.toRawConfig?.();
622
+ if (!raw?.skills) continue;
623
+ const skillsField = raw.skills;
624
+ let found = false;
625
+ if (Array.isArray(skillsField)) {
626
+ found = skillsField.some(
627
+ (variant) => variant?.value && skillId in variant.value
628
+ );
629
+ } else if (typeof skillsField === "object" && skillsField !== null) {
630
+ found = skillId in skillsField;
631
+ }
632
+ if (found) {
633
+ this.logger?.debug(
634
+ `[invalidateAgentsReferencingSkill] Evicting agent "${agentId}" (references skill "${skillId}")`
635
+ );
636
+ this._cache.delete(agentId);
637
+ this.onCacheEvict(agentId);
638
+ }
639
+ }
640
+ }
641
+ /**
642
+ * Apply stored configuration overrides to a code-defined agent.
643
+ *
644
+ * When a stored config exists for the given agent's ID, the following fields
645
+ * from the stored config override the code agent's values (if explicitly set):
646
+ * - `instructions` — system prompt
647
+ * - `tools` — tool selection with description overrides (merged on top of code tools)
648
+ *
649
+ * Fields that are absent or undefined in the stored config are left untouched.
650
+ * Model, workspace, memory, and other code-defined fields are never overridden —
651
+ * they may contain SDK instances or dynamic functions that cannot be safely serialized.
652
+ * Returns the (possibly mutated) agent.
653
+ */
654
+ async applyStoredOverrides(agent) {
655
+ let storedConfig = null;
656
+ try {
657
+ this.ensureRegistered();
658
+ const adapter = await this.getStorageAdapter();
659
+ storedConfig = await adapter.getByIdResolved(agent.id, { status: "draft" });
660
+ } catch {
661
+ this.restoreCodeDefaults(agent);
662
+ return agent;
663
+ }
664
+ if (!storedConfig) {
665
+ this.restoreCodeDefaults(agent);
666
+ return agent;
667
+ }
668
+ this.saveCodeDefaults(agent);
669
+ this.restoreCodeDefaults(agent);
670
+ this.saveCodeDefaults(agent);
671
+ this.logger?.debug(`[applyStoredOverrides] Applying stored overrides to code agent "${agent.id}"`);
672
+ if (storedConfig.instructions !== void 0 && storedConfig.instructions !== null) {
673
+ const resolved = this.resolveStoredInstructions(storedConfig.instructions);
674
+ if (resolved !== void 0) {
675
+ agent.__updateInstructions(resolved);
676
+ }
677
+ }
678
+ const hasStoredTools = storedConfig.tools != null;
679
+ const hasStoredMCPClients = storedConfig.mcpClients != null;
680
+ const hasStoredIntegrationTools = storedConfig.integrationTools != null;
681
+ if (hasStoredTools || hasStoredMCPClients || hasStoredIntegrationTools) {
682
+ const hasConditionalTools = this.isConditionalVariants(storedConfig.tools);
683
+ const hasConditionalMCPClients = storedConfig.mcpClients != null && this.isConditionalVariants(storedConfig.mcpClients);
684
+ const hasConditionalIntegrationTools = storedConfig.integrationTools != null && this.isConditionalVariants(storedConfig.integrationTools);
685
+ const isDynamicTools = hasConditionalTools || hasConditionalMCPClients || hasConditionalIntegrationTools;
686
+ if (isDynamicTools) {
687
+ const originalTools = agent.listTools.bind(agent);
688
+ const toolsFn = async ({ requestContext }) => {
689
+ const codeTools = await originalTools({ requestContext });
690
+ const ctx = requestContext.toJSON();
691
+ const resolvedToolsConfig = hasConditionalTools ? this.accumulateObjectVariants(
692
+ storedConfig.tools,
693
+ ctx
694
+ ) : storedConfig.tools;
695
+ const registryTools = this.resolveStoredTools(resolvedToolsConfig);
696
+ const resolvedMCPClientsConfig = hasConditionalMCPClients ? this.accumulateObjectVariants(
697
+ storedConfig.mcpClients,
698
+ ctx
699
+ ) : storedConfig.mcpClients;
700
+ const mcpTools = await this.resolveStoredMCPTools(resolvedMCPClientsConfig);
701
+ const resolvedIntegrationToolsConfig = hasConditionalIntegrationTools ? this.accumulateObjectVariants(
702
+ storedConfig.integrationTools,
703
+ ctx
704
+ ) : storedConfig.integrationTools;
705
+ const integrationTools = await this.resolveStoredIntegrationTools(resolvedIntegrationToolsConfig, ctx);
706
+ return { ...codeTools, ...registryTools, ...mcpTools, ...integrationTools };
707
+ };
708
+ agent.__setTools(toolsFn);
709
+ } else {
710
+ const codeTools = await agent.listTools();
711
+ const registryTools = this.resolveStoredTools(
712
+ storedConfig.tools
713
+ );
714
+ const mcpTools = await this.resolveStoredMCPTools(
715
+ storedConfig.mcpClients
716
+ );
717
+ const integrationTools = await this.resolveStoredIntegrationTools(
718
+ storedConfig.integrationTools
719
+ );
720
+ agent.__setTools({ ...codeTools, ...registryTools, ...mcpTools, ...integrationTools });
721
+ }
722
+ }
723
+ return agent;
724
+ }
725
+ /**
726
+ * Save the agent's current field values to the module-level WeakMap
727
+ * so they can be restored if the stored config is later removed.
728
+ * Only saves on the first call (guards against overwriting originals with overridden values).
729
+ *
730
+ * Only instructions and tools are saved — these are the only fields
731
+ * that `applyStoredOverrides` mutates.
732
+ */
733
+ saveCodeDefaults(agent) {
734
+ if (codeDefaults.has(agent)) return;
735
+ const fields = agent.__getOverridableFields();
736
+ codeDefaults.set(agent, {
737
+ instructions: fields.instructions,
738
+ tools: fields.tools
739
+ });
740
+ }
741
+ /**
742
+ * Restore the agent's original code-defined field values from the WeakMap.
743
+ * Clears the saved snapshot afterward.
744
+ */
745
+ restoreCodeDefaults(agent) {
746
+ const saved = codeDefaults.get(agent);
747
+ if (!saved) return;
748
+ agent.__updateInstructions(saved.instructions);
749
+ agent.__setTools(saved.tools);
750
+ codeDefaults.delete(agent);
751
+ }
752
+ // ============================================================================
753
+ // Private helpers
754
+ // ============================================================================
755
+ /**
756
+ * Detect whether a StorageConditionalField value is a conditional variant array
757
+ * (as opposed to the plain static value T).
758
+ */
759
+ isConditionalVariants(field) {
760
+ return Array.isArray(field) && field.length > 0 && typeof field[0] === "object" && field[0] !== null && "value" in field[0];
761
+ }
762
+ /**
763
+ * Accumulate all matching variants for an array-typed field.
764
+ * Each matching variant's value (an array) is concatenated in order.
765
+ * Variants with no rules are treated as unconditional (always included).
766
+ */
767
+ accumulateArrayVariants(variants, context) {
768
+ const result = [];
769
+ for (const variant of variants) {
770
+ if (!variant.rules || evaluateRuleGroup(variant.rules, context)) {
771
+ result.push(...variant.value);
772
+ }
773
+ }
774
+ return result;
775
+ }
776
+ /**
777
+ * Accumulate all matching variants for an object/record-typed field.
778
+ * Each matching variant's value is shallow-merged in order, so later
779
+ * matches override keys from earlier ones.
780
+ * Variants with no rules are treated as unconditional (always included).
781
+ */
782
+ accumulateObjectVariants(variants, context) {
783
+ let result;
784
+ for (const variant of variants) {
785
+ if (!variant.rules || evaluateRuleGroup(variant.rules, context)) {
786
+ result = result ? { ...result, ...variant.value } : { ...variant.value };
787
+ }
788
+ }
789
+ return result;
790
+ }
791
+ async createAgentFromStoredConfig(storedAgent) {
792
+ if (!this.mastra) {
793
+ throw new Error("MastraEditor is not registered with a Mastra instance");
794
+ }
795
+ this.logger?.debug(`[createAgentFromStoredConfig] Creating agent from stored config "${storedAgent.id}"`);
796
+ const instructions = this.resolveStoredInstructions(storedAgent.instructions);
797
+ const hasConditionalTools = storedAgent.tools != null && this.isConditionalVariants(storedAgent.tools);
798
+ const hasConditionalMCPClients = storedAgent.mcpClients != null && this.isConditionalVariants(storedAgent.mcpClients);
799
+ const hasConditionalIntegrationTools = storedAgent.integrationTools != null && this.isConditionalVariants(storedAgent.integrationTools);
800
+ const hasConditionalWorkflows = storedAgent.workflows != null && this.isConditionalVariants(storedAgent.workflows);
801
+ const hasConditionalAgents = storedAgent.agents != null && this.isConditionalVariants(storedAgent.agents);
802
+ const hasConditionalMemory = storedAgent.memory != null && this.isConditionalVariants(storedAgent.memory);
803
+ const hasConditionalScorers = storedAgent.scorers != null && this.isConditionalVariants(storedAgent.scorers);
804
+ const hasConditionalInputProcessors = storedAgent.inputProcessors != null && this.isConditionalVariants(storedAgent.inputProcessors);
805
+ const hasConditionalOutputProcessors = storedAgent.outputProcessors != null && this.isConditionalVariants(storedAgent.outputProcessors);
806
+ const hasConditionalDefaultOptions = storedAgent.defaultOptions != null && this.isConditionalVariants(storedAgent.defaultOptions);
807
+ const hasConditionalModel = this.isConditionalVariants(storedAgent.model);
808
+ const hasConditionalWorkspace = storedAgent.workspace != null && this.isConditionalVariants(storedAgent.workspace);
809
+ const isDynamicTools = hasConditionalTools || hasConditionalMCPClients || hasConditionalIntegrationTools;
810
+ let tools;
811
+ if (isDynamicTools) {
812
+ tools = async ({ requestContext }) => {
813
+ const ctx = requestContext.toJSON();
814
+ const resolvedToolsConfig = hasConditionalTools ? this.accumulateObjectVariants(
815
+ storedAgent.tools,
816
+ ctx
817
+ ) : storedAgent.tools;
818
+ const registryTools = this.resolveStoredTools(resolvedToolsConfig);
819
+ const resolvedMCPClientsConfig = hasConditionalMCPClients ? this.accumulateObjectVariants(
820
+ storedAgent.mcpClients,
821
+ ctx
822
+ ) : storedAgent.mcpClients;
823
+ const mcpTools = await this.resolveStoredMCPTools(resolvedMCPClientsConfig);
824
+ const resolvedIntegrationToolsConfig = hasConditionalIntegrationTools ? this.accumulateObjectVariants(
825
+ storedAgent.integrationTools,
826
+ ctx
827
+ ) : storedAgent.integrationTools;
828
+ const integrationTools = await this.resolveStoredIntegrationTools(resolvedIntegrationToolsConfig, ctx);
829
+ return { ...registryTools, ...mcpTools, ...integrationTools };
830
+ };
831
+ } else {
832
+ const registryTools = this.resolveStoredTools(storedAgent.tools);
833
+ const mcpTools = await this.resolveStoredMCPTools(
834
+ storedAgent.mcpClients
835
+ );
836
+ const integrationTools = await this.resolveStoredIntegrationTools(
837
+ storedAgent.integrationTools
838
+ );
839
+ tools = { ...registryTools, ...mcpTools, ...integrationTools };
840
+ }
841
+ const workflows = hasConditionalWorkflows ? ({ requestContext }) => {
842
+ const ctx = requestContext.toJSON();
843
+ const variants = storedAgent.workflows;
844
+ const isArrayVariant = Array.isArray(variants[0]?.value);
845
+ const resolved = isArrayVariant ? this.accumulateArrayVariants(variants, ctx) : this.accumulateObjectVariants(
846
+ variants,
847
+ ctx
848
+ );
849
+ return this.resolveStoredWorkflows(resolved);
850
+ } : this.resolveStoredWorkflows(storedAgent.workflows);
851
+ const agents = hasConditionalAgents ? ({ requestContext }) => {
852
+ const ctx = requestContext.toJSON();
853
+ const variants = storedAgent.agents;
854
+ const isArrayVariant = Array.isArray(variants[0]?.value);
855
+ const resolved = isArrayVariant ? this.accumulateArrayVariants(variants, ctx) : this.accumulateObjectVariants(
856
+ variants,
857
+ ctx
858
+ );
859
+ return this.resolveStoredAgents(resolved);
860
+ } : this.resolveStoredAgents(storedAgent.agents);
861
+ const memory = hasConditionalMemory ? ({ requestContext }) => {
862
+ const ctx = requestContext.toJSON();
863
+ const resolved = this.accumulateObjectVariants(
864
+ storedAgent.memory,
865
+ ctx
866
+ );
867
+ return this.resolveStoredMemory(resolved);
868
+ } : this.resolveStoredMemory(storedAgent.memory);
869
+ const scorers = hasConditionalScorers ? async ({ requestContext }) => {
870
+ const ctx = requestContext.toJSON();
871
+ const resolved = this.accumulateObjectVariants(
872
+ storedAgent.scorers,
873
+ ctx
874
+ );
875
+ return this.resolveStoredScorers(resolved);
876
+ } : await this.resolveStoredScorers(storedAgent.scorers);
877
+ const processorProviders = this.editor.getProcessorProviders();
878
+ const hydrationCtx = { providers: processorProviders, mastra: this.mastra, logger: this.logger };
879
+ const inputProcessors = hasConditionalInputProcessors ? ({ requestContext }) => {
880
+ const ctx = requestContext.toJSON();
881
+ const graph = selectFirstMatchingGraph(
882
+ storedAgent.inputProcessors,
883
+ ctx
884
+ );
885
+ return hydrateProcessorGraph(graph, "input", hydrationCtx);
886
+ } : hydrateProcessorGraph(storedAgent.inputProcessors, "input", hydrationCtx);
887
+ const outputProcessors = hasConditionalOutputProcessors ? ({ requestContext }) => {
888
+ const ctx = requestContext.toJSON();
889
+ const graph = selectFirstMatchingGraph(
890
+ storedAgent.outputProcessors,
891
+ ctx
892
+ );
893
+ return hydrateProcessorGraph(graph, "output", hydrationCtx);
894
+ } : hydrateProcessorGraph(storedAgent.outputProcessors, "output", hydrationCtx);
895
+ let model;
896
+ let staticModelConfig;
897
+ const modelSettingsFrom = (cfg) => ({
898
+ temperature: cfg.temperature,
899
+ topP: cfg.topP,
900
+ frequencyPenalty: cfg.frequencyPenalty,
901
+ presencePenalty: cfg.presencePenalty,
902
+ maxOutputTokens: cfg.maxCompletionTokens
903
+ });
904
+ if (hasConditionalModel) {
905
+ model = ({ requestContext }) => {
906
+ const ctx = requestContext.toJSON();
907
+ const resolved = this.accumulateObjectVariants(
908
+ storedAgent.model,
909
+ ctx
910
+ );
911
+ if (!resolved || !resolved.provider || !resolved.name) {
912
+ throw new Error(
913
+ `Stored agent "${storedAgent.id}" conditional model resolved to invalid configuration. Both provider and name are required.`
914
+ );
915
+ }
916
+ return `${resolved.provider}/${resolved.name}`;
917
+ };
918
+ } else {
919
+ staticModelConfig = storedAgent.model;
920
+ if (!staticModelConfig || !staticModelConfig.provider || !staticModelConfig.name) {
921
+ throw new Error(
922
+ `Stored agent "${storedAgent.id}" has no active version or invalid model configuration. Both provider and name are required.`
923
+ );
924
+ }
925
+ model = `${staticModelConfig.provider}/${staticModelConfig.name}`;
926
+ }
927
+ const staticDefaultOptions = hasConditionalDefaultOptions || hasConditionalModel ? void 0 : storedAgent.defaultOptions;
928
+ const resolveModelSettings = (ctx) => {
929
+ const resolved = this.accumulateObjectVariants(
930
+ storedAgent.model,
931
+ ctx
932
+ );
933
+ return resolved ? modelSettingsFrom(resolved) : {};
934
+ };
935
+ let defaultOptions;
936
+ if (hasConditionalDefaultOptions || hasConditionalModel) {
937
+ defaultOptions = ({ requestContext }) => {
938
+ const ctx = requestContext.toJSON();
939
+ const baseOptions = hasConditionalDefaultOptions ? this.accumulateObjectVariants(
940
+ storedAgent.defaultOptions,
941
+ ctx
942
+ ) ?? {} : storedAgent.defaultOptions ?? {};
943
+ const mSettings = hasConditionalModel ? resolveModelSettings(ctx) : staticModelConfig ? modelSettingsFrom(staticModelConfig) : {};
944
+ return {
945
+ ...baseOptions,
946
+ modelSettings: {
947
+ ...baseOptions.modelSettings,
948
+ ...mSettings
949
+ }
950
+ };
951
+ };
952
+ } else {
953
+ defaultOptions = {
954
+ ...staticDefaultOptions,
955
+ modelSettings: {
956
+ ...staticDefaultOptions?.modelSettings,
957
+ ...staticModelConfig ? modelSettingsFrom(staticModelConfig) : void 0
958
+ }
959
+ };
960
+ }
961
+ const requestContextSchema = storedAgent.requestContextSchema ? (0, import_schema_compat.convertSchemaToZod)(storedAgent.requestContextSchema) : void 0;
962
+ const skillSource = await this.resolveAgentSkillSource(storedAgent.skills);
963
+ const workspace = hasConditionalWorkspace ? async ({ requestContext }) => {
964
+ const ctx = requestContext.toJSON();
965
+ const resolvedRef = this.accumulateObjectVariants(
966
+ storedAgent.workspace,
967
+ ctx
968
+ );
969
+ return this.resolveStoredWorkspace(resolvedRef, skillSource);
970
+ } : await this.resolveStoredWorkspace(storedAgent.workspace, skillSource);
971
+ const skillsFormat = storedAgent.skillsFormat;
972
+ const agent = new import_agent.Agent({
973
+ id: storedAgent.id,
974
+ name: storedAgent.name,
975
+ description: storedAgent.description,
976
+ instructions: instructions ?? "",
977
+ model,
978
+ memory,
979
+ tools,
980
+ workflows,
981
+ agents,
982
+ scorers,
983
+ mastra: this.mastra,
984
+ inputProcessors,
985
+ outputProcessors,
986
+ rawConfig: storedAgent,
987
+ defaultOptions,
988
+ requestContextSchema,
989
+ workspace,
990
+ ...skillsFormat && { skillsFormat }
991
+ });
992
+ const existingCodeAgent = (() => {
993
+ try {
994
+ return this.mastra?.getAgentById(storedAgent.id);
995
+ } catch {
996
+ return void 0;
997
+ }
998
+ })();
999
+ if (!existingCodeAgent || existingCodeAgent.source !== "code") {
1000
+ this.mastra?.addAgent(agent, storedAgent.id, { source: "stored" });
1001
+ }
1002
+ this.logger?.debug(`[createAgentFromStoredConfig] Successfully created agent "${storedAgent.id}"`);
1003
+ return agent;
1004
+ }
1005
+ resolveStoredInstructions(instructions) {
1006
+ if (instructions === void 0 || instructions === null) return void 0;
1007
+ if (typeof instructions === "string") return instructions;
1008
+ const blocks = instructions;
1009
+ return async ({ requestContext }) => {
1010
+ const storage = this.editor.__mastra.getStorage();
1011
+ if (!storage) throw new Error("Storage is not configured");
1012
+ const promptBlocksStore = await storage.getStore("promptBlocks");
1013
+ if (!promptBlocksStore) throw new Error("Prompt blocks storage domain is not available");
1014
+ const context = requestContext.toJSON();
1015
+ return resolveInstructionBlocks(blocks, context, { promptBlocksStorage: promptBlocksStore });
1016
+ };
1017
+ }
1018
+ /**
1019
+ * Resolve stored tool IDs to actual tool instances from Mastra's registry.
1020
+ * Applies description overrides from per-tool config when present.
1021
+ */
1022
+ resolveStoredTools(storedTools) {
1023
+ if (!storedTools || (Array.isArray(storedTools) ? storedTools.length === 0 : Object.keys(storedTools).length === 0)) {
1024
+ return {};
1025
+ }
1026
+ if (!this.mastra) {
1027
+ return {};
1028
+ }
1029
+ const normalized = Array.isArray(storedTools) ? Object.fromEntries(storedTools.map((key) => [key, {}])) : storedTools;
1030
+ const resolvedTools = {};
1031
+ for (const [toolKey, toolConfig] of Object.entries(normalized)) {
1032
+ try {
1033
+ const tool = this.mastra.getToolById(toolKey);
1034
+ if (toolConfig.description) {
1035
+ resolvedTools[toolKey] = { ...tool, description: toolConfig.description };
1036
+ } else {
1037
+ resolvedTools[toolKey] = tool;
1038
+ }
1039
+ } catch {
1040
+ this.logger?.warn(`Tool "${toolKey}" referenced in stored agent but not registered in Mastra`);
1041
+ }
1042
+ }
1043
+ return resolvedTools;
1044
+ }
1045
+ /**
1046
+ * Resolve MCP client/server references to tools.
1047
+ *
1048
+ * For each entry in `mcpClients`, resolution checks two sources in order:
1049
+ * 1. Stored MCP clients (from DB) — creates an MCPClient to fetch remote tools
1050
+ * 2. Code-defined MCP servers on the Mastra instance — uses `server.tools()` directly
1051
+ *
1052
+ * When `clientToolsConfig.tools` is absent, no tools are included (client registered but nothing selected).
1053
+ * When `clientToolsConfig.tools` is an empty object `{}`, all tools from the source are included.
1054
+ * When specified with keys, only listed tools are included with optional description overrides.
1055
+ */
1056
+ async resolveStoredMCPTools(mcpClients) {
1057
+ if (!mcpClients || Object.keys(mcpClients).length === 0) return {};
1058
+ if (!this.mastra) return {};
1059
+ const allTools = {};
1060
+ let MCPClient;
1061
+ for (const [clientId, clientToolsConfig] of Object.entries(mcpClients)) {
1062
+ try {
1063
+ if (!clientToolsConfig.tools) continue;
1064
+ let tools;
1065
+ const storedClient = await this.editor.mcp.getById(clientId);
1066
+ if (storedClient) {
1067
+ if (!MCPClient) {
1068
+ try {
1069
+ const mcpModule = await import("@mastra/mcp");
1070
+ MCPClient = mcpModule.MCPClient;
1071
+ } catch {
1072
+ this.logger?.warn(
1073
+ "Stored MCP client references found but @mastra/mcp is not installed. Install @mastra/mcp to use remote MCP tools."
1074
+ );
1075
+ continue;
1076
+ }
1077
+ }
1078
+ const clientOptions = EditorMCPNamespace.toMCPClientOptions(storedClient);
1079
+ const client = new MCPClient(clientOptions);
1080
+ tools = await client.listTools();
1081
+ this.logger?.debug(`[resolveStoredMCPTools] Loaded tools from stored MCP client "${clientId}"`);
1082
+ } else {
1083
+ const mcpServer = this.mastra.getMCPServer(clientId) ?? this.mastra.getMCPServerById(clientId);
1084
+ if (mcpServer) {
1085
+ tools = mcpServer.tools();
1086
+ this.logger?.debug(`[resolveStoredMCPTools] Loaded tools from code-defined MCP server "${clientId}"`);
1087
+ }
1088
+ }
1089
+ if (!tools) {
1090
+ this.logger?.warn(`MCP client/server "${clientId}" referenced in stored agent but not found`);
1091
+ continue;
1092
+ }
1093
+ const clientServers = storedClient?.servers;
1094
+ const agentAllowedTools = clientToolsConfig.tools;
1095
+ for (const [namespacedToolName, tool] of Object.entries(tools)) {
1096
+ const underscoreIdx = namespacedToolName.indexOf("_");
1097
+ const serverName = underscoreIdx > -1 ? namespacedToolName.slice(0, underscoreIdx) : void 0;
1098
+ const bareToolName = underscoreIdx > -1 ? namespacedToolName.slice(underscoreIdx + 1) : namespacedToolName;
1099
+ if (serverName && clientServers?.[serverName]?.tools) {
1100
+ if (!(bareToolName in clientServers[serverName].tools)) continue;
1101
+ }
1102
+ const hasAgentFilter = agentAllowedTools && Object.keys(agentAllowedTools).length > 0;
1103
+ if (hasAgentFilter && !(namespacedToolName in agentAllowedTools)) continue;
1104
+ const serverToolConfig = serverName ? clientServers?.[serverName]?.tools?.[bareToolName] : void 0;
1105
+ const description = agentAllowedTools?.[namespacedToolName]?.description ?? serverToolConfig?.description;
1106
+ if (description) {
1107
+ allTools[namespacedToolName] = { ...tool, description };
1108
+ } else {
1109
+ allTools[namespacedToolName] = tool;
1110
+ }
1111
+ }
1112
+ } catch (error) {
1113
+ this.logger?.warn(`Failed to resolve MCP tools from "${clientId}"`, { error });
1114
+ }
1115
+ }
1116
+ return allTools;
1117
+ }
1118
+ /**
1119
+ * Resolve integration tool references from tool providers.
1120
+ *
1121
+ * For each entry in `integrationTools`, looks up the tool provider by ID
1122
+ * from the editor's registered tool providers and calls `getTools()` on it.
1123
+ *
1124
+ * When `providerConfig.tools` is absent, no tools are included (provider registered but nothing selected).
1125
+ * When `providerConfig.tools` is an empty object `{}`, all tools from the provider are included.
1126
+ * When `providerConfig.tools` has specific keys, only those tools are included with optional overrides.
1127
+ */
1128
+ async resolveStoredIntegrationTools(integrationTools, requestContext) {
1129
+ if (!integrationTools || Object.keys(integrationTools).length === 0) return {};
1130
+ const allTools = {};
1131
+ for (const [providerId, providerConfig] of Object.entries(integrationTools)) {
1132
+ try {
1133
+ if (!providerConfig.tools) continue;
1134
+ const provider = this.editor.getToolProvider(providerId);
1135
+ if (!provider) {
1136
+ this.logger?.warn(
1137
+ `Tool provider "${providerId}" referenced in stored agent but not registered in the editor`
1138
+ );
1139
+ continue;
1140
+ }
1141
+ const wantedSlugs = Object.keys(providerConfig.tools);
1142
+ let slugsToResolve;
1143
+ if (wantedSlugs.length === 0) {
1144
+ const allAvailable = await provider.listTools();
1145
+ slugsToResolve = allAvailable.data.map((t) => t.slug);
1146
+ } else {
1147
+ slugsToResolve = wantedSlugs;
1148
+ }
1149
+ const providerTools = await provider.resolveTools(slugsToResolve, providerConfig.tools, { requestContext });
1150
+ for (const [toolId, tool] of Object.entries(providerTools)) {
1151
+ const description = providerConfig.tools?.[toolId]?.description;
1152
+ if (description) {
1153
+ allTools[toolId] = { ...tool, description };
1154
+ } else {
1155
+ allTools[toolId] = tool;
1156
+ }
1157
+ }
1158
+ this.logger?.debug(
1159
+ `[resolveStoredIntegrationTools] Loaded ${Object.keys(providerTools).length} tools from provider "${providerId}"`
1160
+ );
1161
+ } catch (error) {
1162
+ this.logger?.warn(`Failed to resolve integration tools from provider "${providerId}"`, { error });
1163
+ }
1164
+ }
1165
+ return allTools;
1166
+ }
1167
+ resolveStoredWorkflows(storedWorkflows) {
1168
+ if (!storedWorkflows || (Array.isArray(storedWorkflows) ? storedWorkflows.length === 0 : Object.keys(storedWorkflows).length === 0)) {
1169
+ return {};
1170
+ }
1171
+ if (!this.mastra) return {};
1172
+ const normalized = Array.isArray(storedWorkflows) ? Object.fromEntries(storedWorkflows.map((key) => [key, {}])) : storedWorkflows;
1173
+ const resolvedWorkflows = {};
1174
+ for (const workflowKey of Object.keys(normalized)) {
1175
+ try {
1176
+ resolvedWorkflows[workflowKey] = this.mastra.getWorkflow(workflowKey);
1177
+ } catch {
1178
+ try {
1179
+ resolvedWorkflows[workflowKey] = this.mastra.getWorkflowById(workflowKey);
1180
+ } catch {
1181
+ this.logger?.warn(`Workflow "${workflowKey}" referenced in stored agent but not registered in Mastra`);
1182
+ }
1183
+ }
1184
+ }
1185
+ return resolvedWorkflows;
1186
+ }
1187
+ resolveStoredAgents(storedAgents) {
1188
+ if (!storedAgents || (Array.isArray(storedAgents) ? storedAgents.length === 0 : Object.keys(storedAgents).length === 0)) {
1189
+ return {};
1190
+ }
1191
+ if (!this.mastra) return {};
1192
+ const normalized = Array.isArray(storedAgents) ? Object.fromEntries(storedAgents.map((key) => [key, {}])) : storedAgents;
1193
+ const resolvedAgents = {};
1194
+ for (const agentKey of Object.keys(normalized)) {
1195
+ try {
1196
+ resolvedAgents[agentKey] = this.mastra.getAgent(agentKey);
1197
+ } catch {
1198
+ try {
1199
+ resolvedAgents[agentKey] = this.mastra.getAgentById(agentKey);
1200
+ } catch {
1201
+ this.logger?.warn(`Agent "${agentKey}" referenced in stored agent but not registered in Mastra`);
1202
+ }
1203
+ }
1204
+ }
1205
+ return resolvedAgents;
1206
+ }
1207
+ resolveStoredMemory(memoryConfig) {
1208
+ if (!memoryConfig) {
1209
+ this.logger?.debug(`[resolveStoredMemory] No memory config provided`);
1210
+ return void 0;
1211
+ }
1212
+ if (!this.mastra) {
1213
+ this.logger?.warn("MastraEditor not registered with Mastra instance. Cannot instantiate memory.");
1214
+ return void 0;
1215
+ }
1216
+ try {
1217
+ let vector;
1218
+ if (memoryConfig.vector) {
1219
+ const vectors = this.mastra.listVectors();
1220
+ vector = vectors?.[memoryConfig.vector];
1221
+ if (!vector) {
1222
+ this.logger?.warn(`Vector provider "${memoryConfig.vector}" not found in Mastra instance`);
1223
+ }
1224
+ }
1225
+ let options = memoryConfig.options ? { ...memoryConfig.options } : void 0;
1226
+ if (memoryConfig.observationalMemory) {
1227
+ options = {
1228
+ ...options,
1229
+ observationalMemory: memoryConfig.observationalMemory
1230
+ };
1231
+ }
1232
+ if (options?.semanticRecall && (!vector || !memoryConfig.embedder)) {
1233
+ this.logger?.warn(
1234
+ "Semantic recall is enabled but no vector store or embedder are configured. Creating memory without semantic recall. To use semantic recall, configure a vector store and embedder in your Mastra instance."
1235
+ );
1236
+ const adjustedOptions = { ...options, semanticRecall: false };
1237
+ const sharedConfig2 = {
1238
+ storage: this.mastra.getStorage(),
1239
+ vector,
1240
+ options: adjustedOptions,
1241
+ embedder: memoryConfig.embedder,
1242
+ embedderOptions: memoryConfig.embedderOptions
1243
+ };
1244
+ return new import_memory.Memory(sharedConfig2);
1245
+ }
1246
+ const sharedConfig = {
1247
+ storage: this.mastra.getStorage(),
1248
+ vector,
1249
+ options,
1250
+ embedder: memoryConfig.embedder,
1251
+ embedderOptions: memoryConfig.embedderOptions
1252
+ };
1253
+ return new import_memory.Memory(sharedConfig);
1254
+ } catch (error) {
1255
+ this.logger?.error("Failed to resolve memory from config", { error });
1256
+ return void 0;
1257
+ }
1258
+ }
1259
+ async resolveStoredScorers(storedScorers) {
1260
+ if (!storedScorers || Object.keys(storedScorers).length === 0) return void 0;
1261
+ if (!this.mastra) return void 0;
1262
+ const resolvedScorers = {};
1263
+ const storage = this.mastra.getStorage();
1264
+ const scorerStore = storage ? await storage.getStore("scorerDefinitions") : null;
1265
+ for (const [scorerKey, scorerConfig] of Object.entries(storedScorers)) {
1266
+ if (scorerStore) {
1267
+ try {
1268
+ const storedDef = await scorerStore.getByIdResolved(scorerKey);
1269
+ if (storedDef) {
1270
+ const scorer = this.editor.scorer.resolve(storedDef);
1271
+ if (scorer) {
1272
+ resolvedScorers[scorerKey] = { scorer, sampling: scorerConfig.sampling };
1273
+ continue;
1274
+ }
1275
+ }
1276
+ } catch {
1277
+ }
1278
+ }
1279
+ try {
1280
+ const scorer = this.mastra.getScorer(scorerKey);
1281
+ resolvedScorers[scorerKey] = { scorer, sampling: scorerConfig.sampling };
1282
+ } catch {
1283
+ try {
1284
+ const scorer = this.mastra.getScorerById(scorerKey);
1285
+ resolvedScorers[scorerKey] = { scorer, sampling: scorerConfig.sampling };
1286
+ } catch {
1287
+ this.logger?.warn(`Scorer "${scorerKey}" referenced in stored agent but not found in registry or storage`);
1288
+ }
1289
+ }
1290
+ }
1291
+ return Object.keys(resolvedScorers).length > 0 ? resolvedScorers : void 0;
1292
+ }
1293
+ // ============================================================================
1294
+ // Clone
1295
+ // ============================================================================
1296
+ /**
1297
+ * Clone a runtime Agent instance into storage, creating a new stored agent
1298
+ * with the resolved configuration of the source agent.
1299
+ */
1300
+ async clone(agent, options) {
1301
+ const requestContext = options.requestContext ?? new import_request_context.RequestContext();
1302
+ const llm = await agent.getLLM({ requestContext });
1303
+ const provider = llm.getProvider();
1304
+ const modelId = llm.getModelId();
1305
+ const defaultOptions = await agent.getDefaultOptions({ requestContext });
1306
+ const modelSettings = defaultOptions?.modelSettings;
1307
+ const model = {
1308
+ provider,
1309
+ name: modelId,
1310
+ ...modelSettings?.temperature !== void 0 && { temperature: modelSettings.temperature },
1311
+ ...modelSettings?.topP !== void 0 && { topP: modelSettings.topP },
1312
+ ...modelSettings?.frequencyPenalty !== void 0 && { frequencyPenalty: modelSettings.frequencyPenalty },
1313
+ ...modelSettings?.presencePenalty !== void 0 && { presencePenalty: modelSettings.presencePenalty },
1314
+ ...modelSettings?.maxOutputTokens !== void 0 && { maxCompletionTokens: modelSettings.maxOutputTokens }
1315
+ };
1316
+ const instructions = await agent.getInstructions({ requestContext });
1317
+ let instructionsStr;
1318
+ if (typeof instructions === "string") {
1319
+ instructionsStr = instructions;
1320
+ } else if (Array.isArray(instructions)) {
1321
+ instructionsStr = instructions.map((msg) => {
1322
+ if (typeof msg === "string") {
1323
+ return msg;
1324
+ }
1325
+ return typeof msg.content === "string" ? msg.content : "";
1326
+ }).filter(Boolean).join("\n\n");
1327
+ } else if (instructions && typeof instructions === "object" && "content" in instructions) {
1328
+ instructionsStr = typeof instructions.content === "string" ? instructions.content : "";
1329
+ } else {
1330
+ instructionsStr = "";
1331
+ }
1332
+ const tools = await agent.listTools({ requestContext });
1333
+ const toolKeys = Object.keys(tools || {});
1334
+ const workflows = await agent.listWorkflows({ requestContext });
1335
+ const workflowKeys = Object.keys(workflows || {});
1336
+ const agentsResolved = await agent.listAgents({ requestContext });
1337
+ const agentKeys = Object.keys(agentsResolved || {});
1338
+ const memory = await agent.getMemory({ requestContext });
1339
+ const memoryConfig = memory?.getConfig();
1340
+ let storedScorers;
1341
+ const resolvedScorers = await agent.listScorers({ requestContext });
1342
+ if (resolvedScorers && Object.keys(resolvedScorers).length > 0) {
1343
+ storedScorers = {};
1344
+ for (const [key, entry] of Object.entries(resolvedScorers)) {
1345
+ storedScorers[key] = {
1346
+ ...entry.sampling && { sampling: entry.sampling }
1347
+ };
1348
+ }
1349
+ }
1350
+ const storageDefaultOptions = defaultOptions ? {
1351
+ maxSteps: defaultOptions?.maxSteps,
1352
+ runId: defaultOptions?.runId,
1353
+ savePerStep: defaultOptions?.savePerStep,
1354
+ activeTools: defaultOptions?.activeTools,
1355
+ toolChoice: defaultOptions?.toolChoice,
1356
+ modelSettings: defaultOptions?.modelSettings,
1357
+ returnScorerData: defaultOptions?.returnScorerData,
1358
+ requireToolApproval: defaultOptions?.requireToolApproval,
1359
+ autoResumeSuspendedTools: defaultOptions?.autoResumeSuspendedTools,
1360
+ toolCallConcurrency: defaultOptions?.toolCallConcurrency,
1361
+ maxProcessorRetries: defaultOptions?.maxProcessorRetries,
1362
+ includeRawChunks: defaultOptions?.includeRawChunks
1363
+ } : void 0;
1364
+ const createInput = {
1365
+ id: options.newId,
1366
+ name: options.newName || `${agent.name} (Clone)`,
1367
+ description: agent.getDescription() || void 0,
1368
+ instructions: instructionsStr,
1369
+ model,
1370
+ tools: toolKeys.length > 0 ? Object.fromEntries(toolKeys.map((key) => [key, {}])) : void 0,
1371
+ workflows: workflowKeys.length > 0 ? Object.fromEntries(workflowKeys.map((key) => [key, {}])) : void 0,
1372
+ agents: agentKeys.length > 0 ? Object.fromEntries(agentKeys.map((key) => [key, {}])) : void 0,
1373
+ memory: memoryConfig,
1374
+ scorers: storedScorers,
1375
+ defaultOptions: storageDefaultOptions,
1376
+ metadata: options.metadata,
1377
+ authorId: options.authorId
1378
+ };
1379
+ const adapter = await this.getStorageAdapter();
1380
+ await adapter.create(createInput);
1381
+ const resolved = await adapter.getByIdResolved(options.newId);
1382
+ if (!resolved) {
1383
+ throw new Error(`Failed to resolve cloned agent '${options.newId}' after creation.`);
1384
+ }
1385
+ return resolved;
1386
+ }
1387
+ // ============================================================================
1388
+ // Workspace Resolution
1389
+ // ============================================================================
1390
+ /**
1391
+ * Resolve a stored workspace reference to a runtime Workspace instance.
1392
+ * Handles both ID-based references (looked up from editor.workspace) and
1393
+ * inline workspace configurations (hydrated directly).
1394
+ *
1395
+ * When a skillSource is provided (from resolveAgentSkillSource), it is passed
1396
+ * to the workspace hydration so the workspace uses versioned blob-backed skills
1397
+ * instead of filesystem-based discovery.
1398
+ */
1399
+ async resolveStoredWorkspace(workspaceRef, skillSource) {
1400
+ if (!workspaceRef) return void 0;
1401
+ const workspaceNs = this.editor.workspace;
1402
+ if (!workspaceNs) {
1403
+ this.logger?.warn("[resolveStoredWorkspace] No workspace namespace available on editor");
1404
+ return void 0;
1405
+ }
1406
+ const hydrateOptions = skillSource ? { skillSource } : void 0;
1407
+ if (workspaceRef.type === "id") {
1408
+ const resolved = await workspaceNs.getById(workspaceRef.workspaceId);
1409
+ if (!resolved) {
1410
+ this.logger?.warn(
1411
+ `[resolveStoredWorkspace] Workspace '${workspaceRef.workspaceId}' not found in storage, skipping`
1412
+ );
1413
+ return void 0;
1414
+ }
1415
+ return workspaceNs.hydrateSnapshotToWorkspace(workspaceRef.workspaceId, resolved, hydrateOptions);
1416
+ }
1417
+ if (workspaceRef.type === "inline") {
1418
+ const configHash = (0, import_node_crypto.createHash)("sha256").update(JSON.stringify(workspaceRef.config)).digest("hex").slice(0, 12);
1419
+ return workspaceNs.hydrateSnapshotToWorkspace(`inline-${configHash}`, workspaceRef.config, hydrateOptions);
1420
+ }
1421
+ return void 0;
1422
+ }
1423
+ /**
1424
+ * Resolve agent-level skill configurations into a CompositeVersionedSkillSource.
1425
+ *
1426
+ * For each skill in the agent's `skills` map, checks the resolution strategy:
1427
+ * - `pin: '<versionId>'` → reads the specific version's tree from the DB
1428
+ * - `strategy: 'latest'` → reads the skill's active version tree
1429
+ * - `strategy: 'live'` or no strategy → skips (uses filesystem-based discovery)
1430
+ *
1431
+ * Returns a CompositeVersionedSkillSource if any versioned skills were resolved,
1432
+ * or undefined if all skills use filesystem-based discovery.
1433
+ */
1434
+ async resolveAgentSkillSource(skills) {
1435
+ if (!skills || typeof skills !== "object") return void 0;
1436
+ const skillConfigs = Array.isArray(skills) ? void 0 : skills;
1437
+ if (!skillConfigs || Object.keys(skillConfigs).length === 0) return void 0;
1438
+ const storage = this.mastra?.getStorage();
1439
+ if (!storage) return void 0;
1440
+ const skillStore = await storage.getStore("skills");
1441
+ if (!skillStore) return void 0;
1442
+ const blobStore = await this.editor.resolveBlobStore();
1443
+ if (!blobStore) return void 0;
1444
+ const versionedEntries = [];
1445
+ for (const [skillId, config] of Object.entries(skillConfigs)) {
1446
+ if (!config) continue;
1447
+ const isPinned = !!config.pin;
1448
+ const isLatest = config.strategy === "latest";
1449
+ if (!isPinned && !isLatest) {
1450
+ continue;
1451
+ }
1452
+ try {
1453
+ let version;
1454
+ let dirName;
1455
+ if (isPinned) {
1456
+ version = await skillStore.getVersion(config.pin);
1457
+ dirName = version?.name || skillId;
1458
+ } else {
1459
+ const resolved = await skillStore.getByIdResolved(skillId);
1460
+ if (resolved?.activeVersionId) {
1461
+ version = await skillStore.getVersion(resolved.activeVersionId);
1462
+ }
1463
+ if (!version) {
1464
+ version = await skillStore.getLatestVersion(skillId);
1465
+ }
1466
+ dirName = resolved?.name || version?.name || skillId;
1467
+ }
1468
+ if (!version?.tree) {
1469
+ this.logger?.warn(
1470
+ `[resolveAgentSkillSource] Skill '${skillId}' version has no tree manifest, skipping versioned resolution`
1471
+ );
1472
+ continue;
1473
+ }
1474
+ versionedEntries.push({
1475
+ dirName,
1476
+ tree: version.tree,
1477
+ versionCreatedAt: version.createdAt
1478
+ });
1479
+ } catch (error) {
1480
+ this.logger?.warn(`[resolveAgentSkillSource] Failed to resolve version for skill '${skillId}': ${error}`);
1481
+ }
1482
+ }
1483
+ if (versionedEntries.length === 0) return void 0;
1484
+ return new import_workspace.CompositeVersionedSkillSource(versionedEntries, blobStore);
1485
+ }
1486
+ };
1487
+
1488
+ // src/namespaces/mcp-server.ts
1489
+ var EditorMCPServerNamespace = class extends CrudEditorNamespace {
1490
+ onCacheEvict(_id) {
1491
+ }
1492
+ async hydrate(resolved) {
1493
+ if (!this.mastra) {
1494
+ throw new Error("MastraEditor is not registered with a Mastra instance");
1495
+ }
1496
+ const tools = this.resolveStoredTools(resolved.tools);
1497
+ const agents = this.resolveStoredAgents(resolved.agents);
1498
+ const workflows = this.resolveStoredWorkflows(resolved.workflows);
1499
+ if (!this.mcpServerCtor) {
1500
+ try {
1501
+ const mod = await import("@mastra/mcp");
1502
+ this.mcpServerCtor = mod.MCPServer;
1503
+ } catch {
1504
+ throw new Error(
1505
+ "@mastra/mcp is required to hydrate MCP server configurations. Install it with: npm install @mastra/mcp"
1506
+ );
1507
+ }
1508
+ }
1509
+ const server = new this.mcpServerCtor({
1510
+ id: resolved.id,
1511
+ name: resolved.name,
1512
+ version: resolved.version,
1513
+ description: resolved.description,
1514
+ instructions: resolved.instructions,
1515
+ repository: resolved.repository,
1516
+ releaseDate: resolved.releaseDate,
1517
+ isLatest: resolved.isLatest,
1518
+ packageCanonical: resolved.packageCanonical,
1519
+ tools,
1520
+ agents,
1521
+ workflows
1522
+ });
1523
+ this.mastra.addMCPServer(server, resolved.id);
1524
+ return server;
1525
+ }
1526
+ resolveStoredTools(storedTools) {
1527
+ if (!storedTools || Object.keys(storedTools).length === 0) return {};
1528
+ if (!this.mastra) return {};
1529
+ const resolved = {};
1530
+ for (const [toolKey, toolConfig] of Object.entries(storedTools)) {
1531
+ try {
1532
+ const tool = this.mastra.getToolById(toolKey);
1533
+ if (toolConfig.description) {
1534
+ resolved[toolKey] = { ...tool, description: toolConfig.description };
1535
+ } else {
1536
+ resolved[toolKey] = tool;
1537
+ }
1538
+ } catch {
1539
+ this.logger?.warn(`Tool "${toolKey}" referenced in stored MCP server but not registered in Mastra`);
1540
+ }
1541
+ }
1542
+ return resolved;
1543
+ }
1544
+ resolveStoredAgents(storedAgents) {
1545
+ if (!storedAgents || Object.keys(storedAgents).length === 0) return {};
1546
+ if (!this.mastra) return {};
1547
+ const resolved = {};
1548
+ for (const agentKey of Object.keys(storedAgents)) {
1549
+ try {
1550
+ resolved[agentKey] = this.mastra.getAgent(agentKey);
1551
+ } catch {
1552
+ try {
1553
+ resolved[agentKey] = this.mastra.getAgentById(agentKey);
1554
+ } catch {
1555
+ this.logger?.warn(`Agent "${agentKey}" referenced in stored MCP server but not registered in Mastra`);
1556
+ }
1557
+ }
1558
+ }
1559
+ return resolved;
1560
+ }
1561
+ resolveStoredWorkflows(storedWorkflows) {
1562
+ if (!storedWorkflows || Object.keys(storedWorkflows).length === 0) return {};
1563
+ if (!this.mastra) return {};
1564
+ const resolved = {};
1565
+ for (const workflowKey of Object.keys(storedWorkflows)) {
1566
+ try {
1567
+ resolved[workflowKey] = this.mastra.getWorkflow(workflowKey);
1568
+ } catch {
1569
+ try {
1570
+ resolved[workflowKey] = this.mastra.getWorkflowById(workflowKey);
1571
+ } catch {
1572
+ this.logger?.warn(`Workflow "${workflowKey}" referenced in stored MCP server but not registered in Mastra`);
1573
+ }
1574
+ }
1575
+ }
1576
+ return resolved;
1577
+ }
1578
+ async getStorageAdapter() {
1579
+ const storage = this.mastra?.getStorage();
1580
+ if (!storage) throw new Error("Storage is not configured");
1581
+ const store = await storage.getStore("mcpServers");
1582
+ if (!store) throw new Error("MCP servers storage domain is not available");
1583
+ return {
1584
+ create: (input) => store.create({ mcpServer: input }),
1585
+ getByIdResolved: (id) => store.getByIdResolved(id),
1586
+ update: (input) => store.update(input),
1587
+ delete: (id) => store.delete(id),
1588
+ list: (args) => store.list(args),
1589
+ listResolved: (args) => store.listResolved(args)
1590
+ };
1591
+ }
1592
+ };
1593
+
1594
+ // src/namespaces/prompt.ts
1595
+ var EditorPromptNamespace = class extends CrudEditorNamespace {
1596
+ onCacheEvict(id) {
1597
+ this.mastra?.removePromptBlock(id);
1598
+ }
1599
+ async getStorageAdapter() {
1600
+ const storage = this.mastra?.getStorage();
1601
+ if (!storage) throw new Error("Storage is not configured");
1602
+ const store = await storage.getStore("promptBlocks");
1603
+ if (!store) throw new Error("Prompt blocks storage domain is not available");
1604
+ return {
1605
+ create: (input) => store.create({ promptBlock: input }),
1606
+ getByIdResolved: (id) => store.getByIdResolved(id),
1607
+ update: (input) => store.update(input),
1608
+ delete: (id) => store.delete(id),
1609
+ list: (args) => store.list(args),
1610
+ listResolved: (args) => store.listResolved(args)
1611
+ };
1612
+ }
1613
+ async preview(blocks, context) {
1614
+ this.ensureRegistered();
1615
+ const storage = this.mastra?.getStorage();
1616
+ if (!storage) throw new Error("Storage is not configured");
1617
+ const store = await storage.getStore("promptBlocks");
1618
+ if (!store) throw new Error("Prompt blocks storage domain is not available");
1619
+ return resolveInstructionBlocks(blocks, context, { promptBlocksStorage: store });
1620
+ }
1621
+ };
1622
+
1623
+ // src/namespaces/scorer.ts
1624
+ var import_evals = require("@mastra/core/evals");
1625
+ var EditorScorerNamespace = class extends CrudEditorNamespace {
1626
+ onCacheEvict(id) {
1627
+ this.mastra?.removeScorer(id);
1628
+ }
1629
+ /**
1630
+ * Hydrate a stored scorer definition into a runtime MastraScorer instance
1631
+ * and register it on the Mastra instance so it can be discovered via
1632
+ * `mastra.getScorer()` / `mastra.getScorerById()`.
1633
+ */
1634
+ async hydrate(storedScorer) {
1635
+ const scorer = this.resolve(storedScorer);
1636
+ if (scorer && this.mastra) {
1637
+ this.mastra.addScorer(scorer, storedScorer.id, { source: "stored" });
1638
+ }
1639
+ return storedScorer;
1640
+ }
1641
+ async getStorageAdapter() {
1642
+ const storage = this.mastra?.getStorage();
1643
+ if (!storage) throw new Error("Storage is not configured");
1644
+ const store = await storage.getStore("scorerDefinitions");
1645
+ if (!store) throw new Error("Scorer definitions storage domain is not available");
1646
+ return {
1647
+ create: (input) => store.create({ scorerDefinition: input }),
1648
+ getByIdResolved: (id) => store.getByIdResolved(id),
1649
+ update: (input) => store.update(input),
1650
+ delete: (id) => store.delete(id),
1651
+ list: (args) => store.list(args),
1652
+ listResolved: (args) => store.listResolved(args)
1653
+ };
1654
+ }
1655
+ /**
1656
+ * Create a MastraScorer instance from a stored scorer definition.
1657
+ * Supports:
1658
+ * - 'llm-judge': Creates a scorer with a single LLM call using custom instructions
1659
+ * - Preset types (e.g., 'bias', 'toxicity'): Not yet supported, returns null
1660
+ */
1661
+ resolve(storedScorer) {
1662
+ if (storedScorer.type === "llm-judge") {
1663
+ if (!storedScorer.instructions) {
1664
+ this.logger?.warn(`Stored scorer "${storedScorer.id}" is llm-judge but has no instructions`);
1665
+ return null;
1666
+ }
1667
+ const modelConfig = storedScorer.model;
1668
+ if (!modelConfig?.provider || !modelConfig?.name) {
1669
+ this.logger?.warn(`Stored scorer "${storedScorer.id}" has no valid model configuration`);
1670
+ return null;
1671
+ }
1672
+ const model = `${modelConfig.provider}/${modelConfig.name}`;
1673
+ const min = storedScorer.scoreRange?.min ?? 0;
1674
+ const max = storedScorer.scoreRange?.max ?? 1;
1675
+ const scorer = (0, import_evals.createScorer)({
1676
+ id: storedScorer.id,
1677
+ name: storedScorer.name,
1678
+ description: storedScorer.description || `Custom LLM judge scorer: ${storedScorer.name}`,
1679
+ type: "agent",
1680
+ judge: {
1681
+ model,
1682
+ instructions: storedScorer.instructions
1683
+ }
1684
+ }).generateScore({
1685
+ description: `Score the output on a scale of ${min} to ${max}`,
1686
+ createPrompt: ({ run }) => {
1687
+ const input = typeof run.input === "string" ? run.input : JSON.stringify(run.input);
1688
+ const output = typeof run.output === "string" ? run.output : JSON.stringify(run.output);
1689
+ return `Evaluate the following interaction and provide a score between ${min} and ${max}.
1690
+
1691
+ Input: ${input}
1692
+
1693
+ Output: ${output}
1694
+
1695
+ Provide your score as a JSON object with a "score" field containing a number between ${min} and ${max}.`;
1696
+ }
1697
+ }).generateReason({
1698
+ description: "Explain the reasoning behind the score",
1699
+ createPrompt: ({ run, score }) => {
1700
+ const input = typeof run.input === "string" ? run.input : JSON.stringify(run.input);
1701
+ const output = typeof run.output === "string" ? run.output : JSON.stringify(run.output);
1702
+ return `You scored the following interaction ${score} out of ${max}.
1703
+
1704
+ Input: ${input}
1705
+
1706
+ Output: ${output}
1707
+
1708
+ Explain your reasoning for this score in a clear, concise paragraph.`;
1709
+ }
1710
+ });
1711
+ if (this.mastra) {
1712
+ scorer.__registerMastra(this.mastra);
1713
+ }
1714
+ return scorer;
1715
+ }
1716
+ this.logger?.warn(
1717
+ `Stored scorer "${storedScorer.id}" has type "${storedScorer.type}" which is a preset type. Preset instantiation from stored config is not yet supported.`
1718
+ );
1719
+ return null;
1720
+ }
1721
+ };
1722
+
1723
+ // src/namespaces/workspace.ts
1724
+ var import_workspace2 = require("@mastra/core/workspace");
1725
+ var EditorWorkspaceNamespace = class extends CrudEditorNamespace {
1726
+ onCacheEvict(_id) {
1727
+ }
1728
+ /**
1729
+ * Hydrate a stored workspace snapshot config into a runtime Workspace instance.
1730
+ * Resolves provider strings to actual instances using the editor's registries.
1731
+ *
1732
+ * This is NOT called from the CrudEditorNamespace flow — it is a public utility
1733
+ * used by EditorAgentNamespace during agent hydration.
1734
+ */
1735
+ async hydrateSnapshotToWorkspace(id, snapshot, options) {
1736
+ const config = {
1737
+ id,
1738
+ name: snapshot.name
1739
+ };
1740
+ if (snapshot.filesystem) {
1741
+ config.filesystem = await this.resolveFilesystem(snapshot.filesystem);
1742
+ }
1743
+ if (snapshot.sandbox) {
1744
+ config.sandbox = await this.resolveSandbox(snapshot.sandbox);
1745
+ }
1746
+ if (snapshot.mounts) {
1747
+ const mounts = {};
1748
+ for (const [path, fsConfig] of Object.entries(snapshot.mounts)) {
1749
+ mounts[path] = await this.resolveFilesystem(fsConfig);
1750
+ }
1751
+ config.mounts = mounts;
1752
+ }
1753
+ if (snapshot.search) {
1754
+ if (snapshot.search.bm25) {
1755
+ config.bm25 = snapshot.search.bm25;
1756
+ }
1757
+ if (snapshot.search.searchIndexName) {
1758
+ config.searchIndexName = snapshot.search.searchIndexName;
1759
+ }
1760
+ if (snapshot.search.autoIndexPaths) {
1761
+ config.autoIndexPaths = snapshot.search.autoIndexPaths;
1762
+ }
1763
+ if (snapshot.search.vectorProvider && this.mastra) {
1764
+ const vectors = this.mastra.listVectors();
1765
+ const vectorStore = vectors?.[snapshot.search.vectorProvider];
1766
+ if (vectorStore) {
1767
+ config.vectorStore = vectorStore;
1768
+ } else {
1769
+ this.logger?.warn(
1770
+ `Vector provider "${snapshot.search.vectorProvider}" not found in Mastra instance. Workspace search will be limited to BM25 only.`
1771
+ );
1772
+ }
1773
+ }
1774
+ if (config.vectorStore && !config.embedder) {
1775
+ this.logger?.warn(
1776
+ `Workspace has a vector store configured but no embedder. Vector/hybrid search will not be available. Configure an embedder to enable semantic search.`
1777
+ );
1778
+ }
1779
+ }
1780
+ if (options?.skillSource) {
1781
+ config.skillSource = options.skillSource;
1782
+ config.skills = ["."];
1783
+ } else if (snapshot.skills && snapshot.skills.length > 0) {
1784
+ config.skills = snapshot.skills;
1785
+ }
1786
+ if (snapshot.tools) {
1787
+ config.tools = snapshot.tools;
1788
+ }
1789
+ if (snapshot.autoSync !== void 0) {
1790
+ config.autoSync = snapshot.autoSync;
1791
+ }
1792
+ if (snapshot.operationTimeout !== void 0) {
1793
+ config.operationTimeout = snapshot.operationTimeout;
1794
+ }
1795
+ return new import_workspace2.Workspace(config);
1796
+ }
1797
+ /**
1798
+ * Resolve a stored filesystem config to a runtime WorkspaceFilesystem instance.
1799
+ * Looks up the provider by ID in the editor's registry (which includes built-in providers).
1800
+ */
1801
+ async resolveFilesystem(fsConfig) {
1802
+ const provider = this.editor.__filesystems.get(fsConfig.provider);
1803
+ if (!provider) {
1804
+ throw new Error(
1805
+ `Filesystem provider "${fsConfig.provider}" is not registered. Register it via new MastraEditor({ filesystems: [yourProvider] })`
1806
+ );
1807
+ }
1808
+ const config = { ...fsConfig.config, readOnly: fsConfig.readOnly };
1809
+ return await provider.createFilesystem(config);
1810
+ }
1811
+ /**
1812
+ * Resolve a stored sandbox config to a runtime WorkspaceSandbox instance.
1813
+ * Looks up the provider by ID in the editor's registry (which includes built-in providers).
1814
+ */
1815
+ async resolveSandbox(sandboxConfig) {
1816
+ const provider = this.editor.__sandboxes.get(sandboxConfig.provider);
1817
+ if (!provider) {
1818
+ throw new Error(
1819
+ `Sandbox provider "${sandboxConfig.provider}" is not registered. Register it via new MastraEditor({ sandboxes: [yourProvider] })`
1820
+ );
1821
+ }
1822
+ return await provider.createSandbox(sandboxConfig.config);
1823
+ }
1824
+ async getStorageAdapter() {
1825
+ const storage = this.mastra?.getStorage();
1826
+ if (!storage) throw new Error("Storage is not configured");
1827
+ const store = await storage.getStore("workspaces");
1828
+ if (!store) throw new Error("Workspaces storage domain is not available");
1829
+ return {
1830
+ create: (input) => store.create({ workspace: input }),
1831
+ getByIdResolved: (id) => store.getByIdResolved(id),
1832
+ update: (input) => store.update(input),
1833
+ delete: (id) => store.delete(id),
1834
+ list: (args) => store.list(args),
1835
+ listResolved: (args) => store.listResolved(args)
1836
+ };
1837
+ }
1838
+ };
1839
+
1840
+ // src/namespaces/skill.ts
1841
+ var import_workspace3 = require("@mastra/core/workspace");
1842
+ var EditorSkillNamespace = class extends CrudEditorNamespace {
1843
+ onCacheEvict(_id) {
1844
+ }
1845
+ async getStorageAdapter() {
1846
+ const storage = this.mastra?.getStorage();
1847
+ if (!storage) throw new Error("Storage is not configured");
1848
+ const store = await storage.getStore("skills");
1849
+ if (!store) throw new Error("Skills storage domain is not available");
1850
+ return {
1851
+ create: (input) => store.create({ skill: input }),
1852
+ getByIdResolved: (id) => store.getByIdResolved(id),
1853
+ update: (input) => store.update(input),
1854
+ delete: (id) => store.delete(id),
1855
+ list: (args) => store.list(args),
1856
+ listResolved: (args) => store.listResolved(args)
1857
+ };
1858
+ }
1859
+ /**
1860
+ * Publish a skill from a live filesystem source.
1861
+ * Walks the skill directory, hashes files into the blob store,
1862
+ * creates a new version with the tree manifest, and sets activeVersionId.
1863
+ */
1864
+ async publish(skillId, source, skillPath) {
1865
+ this.ensureRegistered();
1866
+ const storage = this.mastra?.getStorage();
1867
+ if (!storage) throw new Error("Storage is not configured");
1868
+ const skillStore = await storage.getStore("skills");
1869
+ if (!skillStore) throw new Error("Skills storage domain is not available");
1870
+ const blobStore = await this.editor.resolveBlobStore();
1871
+ if (!blobStore)
1872
+ throw new Error("No blob store is configured. Register one via new MastraEditor({ blobStores: [...] })");
1873
+ const { snapshot, tree } = await (0, import_workspace3.publishSkillFromSource)(source, skillPath, blobStore);
1874
+ await skillStore.update({
1875
+ id: skillId,
1876
+ ...snapshot,
1877
+ tree,
1878
+ status: "published"
1879
+ });
1880
+ const latestVersion = await skillStore.getLatestVersion(skillId);
1881
+ if (!latestVersion) {
1882
+ throw new Error(`Failed to retrieve version after publishing skill "${skillId}"`);
1883
+ }
1884
+ await skillStore.update({
1885
+ id: skillId,
1886
+ activeVersionId: latestVersion.id
1887
+ });
1888
+ const resolved = await skillStore.getByIdResolved(skillId);
1889
+ if (!resolved) throw new Error(`Failed to resolve skill ${skillId} after publish`);
1890
+ this.clearCache(skillId);
1891
+ this.editor.agent.invalidateAgentsReferencingSkill(skillId);
1892
+ return resolved;
1893
+ }
1894
+ };
1895
+
1896
+ // src/providers.ts
1897
+ var import_workspace5 = require("@mastra/core/workspace");
1898
+ var import_workspace6 = require("@mastra/core/workspace");
1899
+ var localFilesystemProvider = {
1900
+ id: "local",
1901
+ name: "Local Filesystem",
1902
+ description: "A folder on the local disk",
1903
+ configSchema: {
1904
+ type: "object",
1905
+ required: ["basePath"],
1906
+ properties: {
1907
+ basePath: { type: "string", description: "Base directory path on disk" },
1908
+ contained: {
1909
+ type: "boolean",
1910
+ description: "Restrict operations to stay within basePath",
1911
+ default: true
1912
+ },
1913
+ readOnly: {
1914
+ type: "boolean",
1915
+ description: "Block all write operations",
1916
+ default: false
1917
+ }
1918
+ }
1919
+ },
1920
+ createFilesystem: (config) => new import_workspace5.LocalFilesystem(config)
1921
+ };
1922
+ var localSandboxProvider = {
1923
+ id: "local",
1924
+ name: "Local Sandbox",
1925
+ description: "Execute commands on the local machine",
1926
+ configSchema: {
1927
+ type: "object",
1928
+ properties: {
1929
+ workingDirectory: { type: "string", description: "Working directory for command execution" },
1930
+ timeout: { type: "number", description: "Default timeout for operations in ms" },
1931
+ isolation: {
1932
+ type: "string",
1933
+ enum: ["none", "seatbelt", "bwrap"],
1934
+ description: "Isolation backend for sandboxed execution",
1935
+ default: "none"
1936
+ },
1937
+ env: {
1938
+ type: "object",
1939
+ description: "Environment variables for command execution",
1940
+ additionalProperties: { type: "string" }
1941
+ }
1942
+ }
1943
+ },
1944
+ createSandbox: (config) => new import_workspace6.LocalSandbox(config)
1945
+ };
1946
+
1947
+ // src/index.ts
1948
+ var MastraEditor = class {
1949
+ constructor(config) {
1950
+ this.__logger = config?.logger;
1951
+ this.__toolProviders = config?.toolProviders ?? {};
1952
+ this.__processorProviders = { ...import_processor_provider2.BUILT_IN_PROCESSOR_PROVIDERS, ...config?.processorProviders };
1953
+ this.__filesystems = /* @__PURE__ */ new Map();
1954
+ this.__filesystems.set(localFilesystemProvider.id, localFilesystemProvider);
1955
+ for (const [id, provider] of Object.entries(config?.filesystems ?? {})) {
1956
+ this.__filesystems.set(id, provider);
1957
+ }
1958
+ this.__sandboxes = /* @__PURE__ */ new Map();
1959
+ this.__sandboxes.set(localSandboxProvider.id, localSandboxProvider);
1960
+ for (const [id, provider] of Object.entries(config?.sandboxes ?? {})) {
1961
+ this.__sandboxes.set(id, provider);
1962
+ }
1963
+ this.__blobStores = /* @__PURE__ */ new Map();
1964
+ for (const [id, provider] of Object.entries(config?.blobStores ?? {})) {
1965
+ this.__blobStores.set(id, provider);
1966
+ }
1967
+ this.agent = new EditorAgentNamespace(this);
1968
+ this.mcp = new EditorMCPNamespace(this);
1969
+ this.mcpServer = new EditorMCPServerNamespace(this);
1970
+ this.prompt = new EditorPromptNamespace(this);
1971
+ this.scorer = new EditorScorerNamespace(this);
1972
+ this.workspace = new EditorWorkspaceNamespace(this);
1973
+ this.skill = new EditorSkillNamespace(this);
1974
+ }
1975
+ /**
1976
+ * Register this editor with a Mastra instance.
1977
+ * This gives the editor access to Mastra's storage, tools, workflows, etc.
1978
+ */
1979
+ registerWithMastra(mastra) {
1980
+ this.__mastra = mastra;
1981
+ if (!this.__logger) {
1982
+ this.__logger = mastra.getLogger();
1983
+ }
1984
+ }
1985
+ /** Registered tool providers */
1986
+ getToolProvider(id) {
1987
+ return this.__toolProviders[id];
1988
+ }
1989
+ /** List all registered tool providers */
1990
+ getToolProviders() {
1991
+ return this.__toolProviders;
1992
+ }
1993
+ /** Get a processor provider by ID */
1994
+ getProcessorProvider(id) {
1995
+ return this.__processorProviders[id];
1996
+ }
1997
+ /** List all registered processor providers */
1998
+ getProcessorProviders() {
1999
+ return this.__processorProviders;
2000
+ }
2001
+ /** List all registered filesystem providers */
2002
+ getFilesystemProviders() {
2003
+ return Array.from(this.__filesystems.values());
2004
+ }
2005
+ /** List all registered sandbox providers */
2006
+ getSandboxProviders() {
2007
+ return Array.from(this.__sandboxes.values());
2008
+ }
2009
+ /** List all registered blob store providers */
2010
+ getBlobStoreProviders() {
2011
+ return Array.from(this.__blobStores.values());
2012
+ }
2013
+ /**
2014
+ * Resolve a blob store from the provider registry, or fall back to the
2015
+ * storage backend's blobs domain.
2016
+ *
2017
+ * @param providerId - If specified, look up a registered provider by ID
2018
+ * and create a blob store from the given config. If omitted, falls back
2019
+ * to `storage.getStore('blobs')`.
2020
+ * @param providerConfig - Provider-specific configuration (only used when
2021
+ * `providerId` is specified).
2022
+ */
2023
+ async resolveBlobStore(providerId, providerConfig) {
2024
+ if (providerId) {
2025
+ const provider = this.__blobStores.get(providerId);
2026
+ if (!provider) {
2027
+ throw new Error(
2028
+ `Blob store provider "${providerId}" is not registered. Register it via new MastraEditor({ blobStores: { '${providerId}': yourProvider } })`
2029
+ );
2030
+ }
2031
+ const blobStore2 = await provider.createBlobStore(providerConfig ?? {});
2032
+ await blobStore2.init();
2033
+ return blobStore2;
2034
+ }
2035
+ const storage = this.__mastra?.getStorage();
2036
+ if (!storage) throw new Error("Storage is not configured");
2037
+ const blobStore = await storage.getStore("blobs");
2038
+ if (!blobStore) throw new Error("Blob storage domain is not available");
2039
+ return blobStore;
2040
+ }
2041
+ };
2042
+ // Annotate the CommonJS export names for ESM import in node:
2043
+ 0 && (module.exports = {
2044
+ CrudEditorNamespace,
2045
+ EditorAgentNamespace,
2046
+ EditorMCPNamespace,
2047
+ EditorMCPServerNamespace,
2048
+ EditorNamespace,
2049
+ EditorPromptNamespace,
2050
+ EditorScorerNamespace,
2051
+ EditorSkillNamespace,
2052
+ EditorWorkspaceNamespace,
2053
+ MastraEditor,
2054
+ evaluateRuleGroup,
2055
+ localFilesystemProvider,
2056
+ localSandboxProvider,
2057
+ renderTemplate,
2058
+ resolveInstructionBlocks
2059
+ });