'use strict'; var chunkZCX2J552_cjs = require('./chunk-ZCX2J552.cjs'); var chunkM2ZGNEQS_cjs = require('./chunk-M2ZGNEQS.cjs'); var chunk3ARFTVAY_cjs = require('./chunk-3ARFTVAY.cjs'); var chunkM3UP3Z3G_cjs = require('./chunk-M3UP3Z3G.cjs'); var chunkKGUHJRHZ_cjs = require('./chunk-KGUHJRHZ.cjs'); var chunk2XZ2466F_cjs = require('./chunk-2XZ2466F.cjs'); var chunkTIWGWGIO_cjs = require('./chunk-TIWGWGIO.cjs'); var chunkDIG2K5CV_cjs = require('./chunk-DIG2K5CV.cjs'); var chunkGZ4HWZWE_cjs = require('./chunk-GZ4HWZWE.cjs'); var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs'); var chunkG54X6VE6_cjs = require('./chunk-G54X6VE6.cjs'); var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs'); // src/server/handlers/stored-agents.ts async function resolveBrowserField(browser, mastra) { if (browser === true) { const editor = mastra.getEditor?.(); const builder = await editor?.resolveBuilder?.(); const defaultBrowser = builder?.getConfiguration?.()?.agent?.browser; if (!defaultBrowser) { console.warn( "[mastra:server] Browser enabled (browser: true) but no default browser config found in builder configuration. The agent will be created/updated without browser access. Set `editor.builder.configuration.agent.browser` to fix this." ); } return defaultBrowser ?? void 0; } if (browser === false) { return null; } return browser; } var AGENT_SNAPSHOT_CONFIG_FIELDS = [ "name", "description", "instructions", "model", "tools", "defaultOptions", "workflows", "agents", "integrationTools", "toolProviders", "inputProcessors", "outputProcessors", "memory", "scorers", "requestContextSchema", "mcpClients", "skills", "workspace", "browser" ]; var CODE_AGENT_OVERRIDE_FIELDS = [ "instructions", "tools", "integrationTools", "mcpClients", "requestContextSchema" ]; function getCodeAgentOwnership(editorConfig) { if (editorConfig === false) { return { ownsInstructions: false, ownsTools: false, ownsToolDescriptionsOnly: false }; } if (editorConfig === void 0 || editorConfig === null) { return { ownsInstructions: true, ownsTools: true, ownsToolDescriptionsOnly: false }; } if (typeof editorConfig !== "object") { return { ownsInstructions: false, ownsTools: false, ownsToolDescriptionsOnly: false }; } const cfg = editorConfig; const ownsInstructions = cfg.instructions === true; const toolsCfg = cfg.tools; const ownsTools = toolsCfg === true; const ownsToolDescriptionsOnly = typeof toolsCfg === "object" && toolsCfg !== null && toolsCfg.description === true; return { ownsInstructions, ownsTools, ownsToolDescriptionsOnly }; } function hasNonEmptyInstructions(value) { if (typeof value === "string") { return value.trim().length > 0; } if (!Array.isArray(value)) { return false; } return value.some((block) => { if (!block || typeof block !== "object") { return false; } const typedBlock = block; if (typedBlock.type === "prompt_block_ref") { return typeof typedBlock.id === "string" && typedBlock.id.length > 0; } return typeof typedBlock.content === "string" && typedBlock.content.trim().length > 0; }); } function assertOwnedInstructionsNotEmpty(instructions) { if (!hasNonEmptyInstructions(instructions)) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Instructions are required" }); } } function sortForStableJson(value) { if (Array.isArray(value)) { return value.map(sortForStableJson); } if (value && typeof value === "object" && !(value instanceof Date)) { return Object.fromEntries( Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => [key, sortForStableJson(entry)]) ); } return value; } function buildExportConfig(input, agent) { const editorConfig = agent?.__getEditorConfig?.(); const isCodeAgent = agent?.source === "code"; const allowedFields = isCodeAgent ? CODE_AGENT_OVERRIDE_FIELDS : AGENT_SNAPSHOT_CONFIG_FIELDS; const ownership = isCodeAgent ? getCodeAgentOwnership(editorConfig) : null; const config = {}; for (const field of allowedFields) { if (input[field] === void 0) continue; if (ownership) { if (field === "instructions" && !ownership.ownsInstructions) continue; if ((field === "tools" || field === "integrationTools" || field === "mcpClients") && !ownership.ownsTools && !ownership.ownsToolDescriptionsOnly) { continue; } } config[field] = input[field]; } return sortForStableJson(config); } function agentExportFilename(agentId) { return `agents/${encodeURIComponent(agentId)}.json`; } function sourceChangeRequestHeadRef(agentId) { const safeAgentId = agentId.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "agent"; return `mastra/${safeAgentId}`; } function sourceChangeRequestMessage(agentId, userName, changeMessage) { const normalizedUserName = userName?.replace(/\s+/g, " ").trim(); const normalizedMessage = changeMessage?.replace(/\s+/g, " ").trim(); const message = normalizedMessage || `Update ${agentId} agent override`; return normalizedUserName ? `${message} by ${normalizedUserName}` : message; } var LIST_STORED_AGENTS_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "GET", path: "/stored/agents", responseType: "json", queryParamSchema: chunkTIWGWGIO_cjs.listStoredAgentsQuerySchema, responseSchema: chunkTIWGWGIO_cjs.listStoredAgentsResponseSchema, summary: "List stored agents", description: "Returns a paginated list of all agents stored in the database", tags: ["Stored Agents"], requiresAuth: true, handler: async ({ mastra, requestContext, page, perPage, orderBy, status, authorId, visibility, metadata, favoritedOnly, pinFavoritedFor }) => { try { const storage = mastra.getStorage(); if (!storage) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" }); } const agentsStore = await storage.getStore("agents"); if (!agentsStore) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Agents storage domain is not available" }); } const filter = chunkKGUHJRHZ_cjs.resolveAuthorFilter({ requestContext, resource: "stored-agents", queryAuthorId: authorId, queryVisibility: visibility === "public" ? "public" : void 0 }); const scope = await chunkGZ4HWZWE_cjs.getStoredResourceScope(mastra, requestContext); const scopedMetadata = chunkGZ4HWZWE_cjs.scopeStoredResourceMetadata(metadata, scope); const callerId = chunkKGUHJRHZ_cjs.getCallerAuthorId(requestContext); const favoritesEnabled = await chunk3ARFTVAY_cjs.isBuilderFeatureEnabled(mastra, "favorites"); const honoredStarredOnly = favoritesEnabled && favoritedOnly === true; const favoriteSubjectId = pinFavoritedFor ?? callerId; if (honoredStarredOnly) { const effectivePerPage = perPage ?? 100; if (!favoriteSubjectId) { return { agents: [], total: 0, page, perPage: effectivePerPage, hasMore: false }; } const favoritesStore = await storage.getStore("favorites"); if (!favoritesStore) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Favorites storage domain is not available" }); } const starredIds = await favoritesStore.listFavoritedIds({ userId: favoriteSubjectId, entityType: "agent" }); if (starredIds.length === 0) { return { agents: [], total: 0, page, perPage: effectivePerPage, hasMore: false }; } const allMatching = await agentsStore.listResolved({ perPage: false, orderBy, status, authorId: filter.kind === "exact" ? filter.authorId : void 0, metadata: scopedMetadata, entityIds: starredIds }); const visible = allMatching.agents.filter((record) => chunkKGUHJRHZ_cjs.matchesAuthorFilter(record, filter)); const total = visible.length; const startIdx = effectivePerPage === 0 ? 0 : page * effectivePerPage; const endIdx = effectivePerPage === 0 ? 0 : startIdx + effectivePerPage; const sliced = effectivePerPage === 0 ? [] : visible.slice(startIdx, endIdx); const annotated2 = sliced.map((record) => ({ ...record, isFavorited: true })); const authors2 = await chunkM3UP3Z3G_cjs.prepareAuthorEnrichment( mastra, requestContext, annotated2.map((a) => a.authorId) ); const withAuthors2 = authors2 ? annotated2.map((record) => chunkM3UP3Z3G_cjs.attachAuthor(record, authors2)) : annotated2; const hasMore = effectivePerPage > 0 && endIdx < total; return { agents: withAuthors2, total, page, perPage: effectivePerPage, hasMore }; } const result = await agentsStore.listResolved({ page, perPage, orderBy, status, authorId: filter.kind === "exact" ? filter.authorId : void 0, metadata: scopedMetadata }); const visibleAgents = result.agents.filter((record) => chunkKGUHJRHZ_cjs.matchesAuthorFilter(record, filter)); const authors = await chunkM3UP3Z3G_cjs.prepareAuthorEnrichment( mastra, requestContext, visibleAgents.map((a) => a.authorId) ); if (!favoritesEnabled) { const stripped = visibleAgents.map(chunkM2ZGNEQS_cjs.stripFavoriteFields); const withAuthors2 = authors ? stripped.map((record) => chunkM3UP3Z3G_cjs.attachAuthor(record, authors)) : stripped; return { ...result, agents: withAuthors2 }; } const enrichment = await chunkM2ZGNEQS_cjs.prepareFavoritesEnrichment( mastra, requestContext, "agent", visibleAgents.map((a) => a.id) ); const annotated = enrichment ? visibleAgents.map((record) => ({ ...record, isFavorited: enrichment.starredIds.has(record.id) })) : visibleAgents.map(chunkM2ZGNEQS_cjs.stripFavoriteFields); const withAuthors = authors ? annotated.map((record) => chunkM3UP3Z3G_cjs.attachAuthor(record, authors)) : annotated; return { ...result, agents: withAuthors }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error listing stored agents"); } } }); async function buildStoredAgentExport({ mastra, requestContext, storedAgentId, body }) { const storage = mastra.getStorage(); const agentsStore = storage ? await storage.getStore("agents") : void 0; const storedAgent = await agentsStore?.getByIdResolved(storedAgentId, { status: "draft" }); if (storedAgent) { chunkGZ4HWZWE_cjs.assertStoredResourceScope(storedAgent, await chunkGZ4HWZWE_cjs.getStoredResourceScope(mastra, requestContext)); chunkKGUHJRHZ_cjs.assertReadAccess({ requestContext, resource: "stored-agents", resourceId: storedAgentId, record: storedAgent }); } let codeAgent; try { codeAgent = mastra.getAgentById?.(storedAgentId); } catch { codeAgent = void 0; } if (!storedAgent && !codeAgent) { throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Agent with id ${storedAgentId} not found` }); } const config = buildExportConfig(body, codeAgent); const content = `${JSON.stringify(config, null, 2)} `; return { agentId: storedAgentId, fileName: agentExportFilename(storedAgentId), content, config }; } var EXPORT_STORED_AGENT_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/stored/agents/:storedAgentId/export", responseType: "json", pathParamSchema: chunkTIWGWGIO_cjs.storedAgentIdPathParams, bodySchema: chunkTIWGWGIO_cjs.exportStoredAgentBodySchema, responseSchema: chunkTIWGWGIO_cjs.exportStoredAgentResponseSchema, summary: "Export stored agent override JSON", description: "Returns deterministic JSON for an agent configuration or code-agent override without mutating storage", tags: ["Stored Agents"], requiresAuth: true, handler: async ({ mastra, requestContext, storedAgentId, ...body }) => { try { return await buildStoredAgentExport({ mastra, requestContext, storedAgentId, body }); } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error exporting stored agent"); } } }); var OPEN_STORED_AGENT_CHANGE_REQUEST_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/stored/agents/:storedAgentId/change-request", responseType: "json", pathParamSchema: chunkTIWGWGIO_cjs.storedAgentIdPathParams, bodySchema: chunkTIWGWGIO_cjs.openStoredAgentChangeRequestBodySchema, responseSchema: chunkTIWGWGIO_cjs.openStoredAgentChangeRequestResponseSchema, summary: "Open stored agent source change request", description: "Opens a source-provider change request for deterministic agent override JSON without mutating storage", tags: ["Stored Agents"], requiresAuth: true, handler: async ({ mastra, requestContext, storedAgentId, ...body }) => { try { const provider = mastra.getEditor?.()?.getSourceControlProvider?.(); if (!provider?.openChangeRequest) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Source control provider cannot open change requests" }); } const openChangeRequest = provider.openChangeRequest.bind(provider); const { changeMessage, userName, inspectOnly, ...exportBody } = body; const headRef = sourceChangeRequestHeadRef(storedAgentId); const title = `Update ${storedAgentId} agent override`; const result = inspectOnly ? await openChangeRequest({ title, headRef, files: [] }) : await (async () => { const response = await buildStoredAgentExport({ mastra, requestContext, storedAgentId, body: exportBody }); const message = sourceChangeRequestMessage(storedAgentId, userName, changeMessage); return openChangeRequest({ title, body: `Updates ${response.fileName} from Mastra Studio.`, headRef, files: [ { path: response.fileName, content: response.content, message } ] }); })(); const storage = mastra.getStorage(); const agentsStore = storage ? await storage.getStore("agents") : void 0; await agentsStore?.useProviderRef?.(storedAgentId, result.ref ?? headRef); mastra.getEditor?.()?.agent?.clearCache?.(storedAgentId); return result; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error opening stored agent change request"); } } }); var GET_STORED_AGENT_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "GET", path: "/stored/agents/:storedAgentId", responseType: "json", pathParamSchema: chunkTIWGWGIO_cjs.storedAgentIdPathParams, queryParamSchema: chunkDIG2K5CV_cjs.statusQuerySchema, responseSchema: chunkTIWGWGIO_cjs.getStoredAgentResponseSchema, summary: "Get stored agent by ID", description: "Returns a specific agent from storage by its unique identifier. Use ?status=draft to resolve with the latest (draft) version, or ?status=published (default) for the active published version.", tags: ["Stored Agents"], requiresAuth: true, handler: async ({ mastra, requestContext, storedAgentId, status }) => { try { const storage = mastra.getStorage(); if (!storage) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" }); } const agentsStore = await storage.getStore("agents"); if (!agentsStore) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Agents storage domain is not available" }); } const agent = await agentsStore.getByIdResolved(storedAgentId, { status }); if (!agent) { throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` }); } chunkGZ4HWZWE_cjs.assertStoredResourceScope(agent, await chunkGZ4HWZWE_cjs.getStoredResourceScope(mastra, requestContext)); chunkKGUHJRHZ_cjs.assertReadAccess({ requestContext, resource: "stored-agents", resourceId: storedAgentId, record: agent }); const authors = await chunkM3UP3Z3G_cjs.prepareAuthorEnrichment(mastra, requestContext, [agent.authorId]); const withFavorite = await chunkM2ZGNEQS_cjs.enrichOrStripFavorites(mastra, requestContext, "agent", agent); return chunkM3UP3Z3G_cjs.attachAuthor(withFavorite, authors); } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error getting stored agent"); } } }); var CREATE_STORED_AGENT_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/stored/agents", responseType: "json", bodySchema: chunkTIWGWGIO_cjs.createStoredAgentBodySchema, responseSchema: chunkTIWGWGIO_cjs.createStoredAgentResponseSchema, summary: "Create stored agent", description: "Creates a new agent in storage with the provided configuration", tags: ["Stored Agents"], requiresAuth: true, handler: async ({ mastra, requestContext, id: providedId, metadata, visibility: bodyVisibility, name, description, instructions, model, tools, defaultOptions, workflows, agents, integrationTools, toolProviders, mcpClients, inputProcessors, outputProcessors, memory, scorers, skills, workspace, browser, requestContextSchema }) => { try { const storage = mastra.getStorage(); if (!storage) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" }); } const agentsStore = await storage.getStore("agents"); if (!agentsStore) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Agents storage domain is not available" }); } const id = providedId || chunkGZ4HWZWE_cjs.toSlug(name); if (!id) { throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Could not derive agent ID from name. Please provide an explicit id." }); } const existing = await agentsStore.getById(id); if (existing) { throw new chunk64ITUOXI_cjs.HTTPException(409, { message: `Agent with id ${id} already exists` }); } const authorId = chunkKGUHJRHZ_cjs.getCallerAuthorId(requestContext) ?? void 0; const visibility = authorId ? bodyVisibility ?? "private" : "public"; chunkZCX2J552_cjs.validateMetadataAvatarUrl(metadata); const resolvedBrowser = await resolveBrowserField(browser, mastra); let createInstructions = instructions; let createTools = tools; let createIntegrationTools = integrationTools; let createMcpClients = mcpClients; let codeAgentForCreate; try { codeAgentForCreate = mastra.getAgentById?.(id); } catch { codeAgentForCreate = void 0; } if (codeAgentForCreate?.source === "code") { const ownership = getCodeAgentOwnership(codeAgentForCreate.__getEditorConfig?.()); if (ownership.ownsInstructions) { assertOwnedInstructionsNotEmpty(createInstructions); } else { createInstructions = void 0; } if (!ownership.ownsTools && !ownership.ownsToolDescriptionsOnly) { createTools = void 0; createIntegrationTools = void 0; createMcpClients = void 0; } } const input = { id, authorId, visibility, metadata: chunkGZ4HWZWE_cjs.scopeStoredResourceMetadata(metadata, await chunkGZ4HWZWE_cjs.getStoredResourceScope(mastra, requestContext)), name, description, instructions: createInstructions, model, tools: createTools, defaultOptions, workflows, agents, integrationTools: createIntegrationTools, toolProviders, mcpClients: createMcpClients, inputProcessors, outputProcessors, memory, scorers, skills, workspace, browser: resolvedBrowser, requestContextSchema }; const editor = mastra.getEditor?.(); if (editor) { await editor.agent.create(input); } else { await agentsStore.create({ agent: input }); } const { versions } = await agentsStore.listVersions({ agentId: id, perPage: 1 }); const initialVersion = versions[0]; if (initialVersion) { await agentsStore.update({ id, activeVersionId: initialVersion.id, status: "published" }); editor?.agent.clearCache(id); } const resolved = await agentsStore.getByIdResolved(id, { status: "published" }); if (!resolved) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve created agent" }); } return chunkM2ZGNEQS_cjs.enrichOrStripFavorites(mastra, requestContext, "agent", resolved); } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error creating stored agent"); } } }); var UPDATE_STORED_AGENT_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "PATCH", path: "/stored/agents/:storedAgentId", responseType: "json", pathParamSchema: chunkTIWGWGIO_cjs.storedAgentIdPathParams, bodySchema: chunkTIWGWGIO_cjs.updateStoredAgentBodySchema, responseSchema: chunkTIWGWGIO_cjs.updateStoredAgentResponseSchema, summary: "Update stored agent", description: "Updates an existing agent in storage with the provided fields", tags: ["Stored Agents"], requiresAuth: true, handler: async ({ mastra, requestContext, storedAgentId, // Metadata-level fields authorId, metadata, visibility, // Config fields (snapshot-level) name, description, instructions, model, tools, defaultOptions, workflows, agents, integrationTools, toolProviders, mcpClients, inputProcessors, outputProcessors, memory, scorers, skills, workspace, browser, requestContextSchema, // Version metadata changeMessage }) => { try { const storage = mastra.getStorage(); if (!storage) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" }); } const agentsStore = await storage.getStore("agents"); if (!agentsStore) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Agents storage domain is not available" }); } const existing = await agentsStore.getById(storedAgentId); if (!existing) { throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` }); } const scope = await chunkGZ4HWZWE_cjs.getStoredResourceScope(mastra, requestContext); chunkGZ4HWZWE_cjs.assertStoredResourceScope(existing, scope); chunkKGUHJRHZ_cjs.assertWriteAccess({ requestContext, resource: "stored-agents", resourceId: storedAgentId, action: "edit", record: existing }); chunkZCX2J552_cjs.validateMetadataAvatarUrl(metadata); const callerAuthorId = chunkKGUHJRHZ_cjs.getCallerAuthorId(requestContext) ?? void 0; const resolvedVisibility = callerAuthorId ? visibility : visibility != null ? "public" : void 0; const resolvedBrowser = await resolveBrowserField(browser, mastra); let codeAgentForUpdate; try { codeAgentForUpdate = mastra.getAgentById?.(storedAgentId); } catch { codeAgentForUpdate = void 0; } if (codeAgentForUpdate?.source === "code") { const ownership = getCodeAgentOwnership(codeAgentForUpdate.__getEditorConfig?.()); if (ownership.ownsInstructions) { if (instructions !== void 0) { assertOwnedInstructionsNotEmpty(instructions); } } else { instructions = void 0; } if (!ownership.ownsTools && !ownership.ownsToolDescriptionsOnly) { tools = void 0; integrationTools = void 0; mcpClients = void 0; } } const mergedMetadata = { ...existing.metadata ?? {}, ...metadata ?? {} }; const scopedMetadata = chunkGZ4HWZWE_cjs.scopeStoredResourceMetadata(mergedMetadata, scope); const updatedAgent = await agentsStore.update({ id: storedAgentId, authorId, metadata: scopedMetadata, visibility: resolvedVisibility, name, description, instructions, model, tools, defaultOptions, workflows, agents, integrationTools, toolProviders, mcpClients, inputProcessors, outputProcessors, memory, scorers, skills, workspace, browser: resolvedBrowser, requestContextSchema }); const configFields = { name, description, instructions, model, tools, defaultOptions, workflows, agents, integrationTools, toolProviders, mcpClients, inputProcessors, outputProcessors, memory, scorers, skills, workspace, browser: resolvedBrowser, requestContextSchema }; const providedConfigFields = Object.fromEntries(Object.entries(configFields).filter(([_, v]) => v !== void 0)); const autoVersionResult = await chunk2XZ2466F_cjs.handleAutoVersioning( agentsStore, storedAgentId, "agentId", AGENT_SNAPSHOT_CONFIG_FIELDS, existing, updatedAgent, providedConfigFields, changeMessage ? { changeMessage } : void 0 ); if (!autoVersionResult) { throw new Error("handleAutoVersioning returned undefined"); } const isCodeSource = mastra.getEditor?.()?.getSource?.() === "code"; if (isCodeSource && autoVersionResult.versionCreated && !changeMessage) { const { versions } = await agentsStore.listVersions({ agentId: storedAgentId, perPage: 2 }); const previousVersion = versions[1]; if (previousVersion) { await agentsStore.deleteVersion(previousVersion.id); } } if (autoVersionResult.versionCreated) { const { versions } = await agentsStore.listVersions({ agentId: storedAgentId, perPage: 1 }); const latestVersion = versions[0]; if (latestVersion) { await agentsStore.update({ id: storedAgentId, activeVersionId: latestVersion.id }); } } const editor = mastra.getEditor(); if (editor) { editor.agent.clearCache(storedAgentId); } const resolved = await agentsStore.getByIdResolved(storedAgentId, { status: "draft" }); if (!resolved) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve updated agent" }); } return chunkM2ZGNEQS_cjs.enrichOrStripFavorites(mastra, requestContext, "agent", resolved); } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error updating stored agent"); } } }); var DELETE_STORED_AGENT_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "DELETE", path: "/stored/agents/:storedAgentId", responseType: "json", pathParamSchema: chunkTIWGWGIO_cjs.storedAgentIdPathParams, responseSchema: chunkTIWGWGIO_cjs.deleteStoredAgentResponseSchema, summary: "Delete stored agent", description: "Deletes an agent from storage by its unique identifier", tags: ["Stored Agents"], requiresAuth: true, handler: async ({ mastra, requestContext, storedAgentId }) => { try { const storage = mastra.getStorage(); if (!storage) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" }); } const agentsStore = await storage.getStore("agents"); if (!agentsStore) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Agents storage domain is not available" }); } const existing = await agentsStore.getById(storedAgentId); if (!existing) { throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` }); } chunkGZ4HWZWE_cjs.assertStoredResourceScope(existing, await chunkGZ4HWZWE_cjs.getStoredResourceScope(mastra, requestContext)); chunkKGUHJRHZ_cjs.assertWriteAccess({ requestContext, resource: "stored-agents", resourceId: storedAgentId, action: "delete", record: existing }); await agentsStore.delete(storedAgentId); try { const favoritesStore = await storage.getStore("favorites"); await favoritesStore?.deleteFavoritesForEntity({ entityType: "agent", entityId: storedAgentId }); } catch (cascadeError) { mastra.getLogger?.()?.warn?.("Failed to cascade-delete favorites for agent", { storedAgentId, error: cascadeError }); } mastra.getEditor()?.agent.clearCache(storedAgentId); return { success: true, message: `Agent ${storedAgentId} deleted successfully` }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error deleting stored agent"); } } }); var GET_STORED_AGENT_DEPENDENTS_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "GET", path: "/stored/agents/:storedAgentId/dependents", responseType: "json", pathParamSchema: chunkTIWGWGIO_cjs.storedAgentIdPathParams, responseSchema: chunkTIWGWGIO_cjs.getStoredAgentDependentsResponseSchema, summary: "List dependents of a stored agent", description: "Returns agents that reference the target as a sub-agent. Used to warn before deleting or unsharing. Caller-readable references appear in `dependents` (id + name); cross-workspace references the caller cannot read are aggregated in `hiddenCount` and only surfaced when the target is public.", tags: ["Stored Agents"], requiresAuth: true, handler: async ({ mastra, requestContext, storedAgentId }) => { try { const storage = mastra.getStorage(); if (!storage) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" }); } const agentsStore = await storage.getStore("agents"); if (!agentsStore) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Agents storage domain is not available" }); } const target = await agentsStore.getById(storedAgentId); if (!target) { throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored agent with id ${storedAgentId} not found` }); } chunkGZ4HWZWE_cjs.assertStoredResourceScope(target, await chunkGZ4HWZWE_cjs.getStoredResourceScope(mastra, requestContext)); chunkKGUHJRHZ_cjs.assertReadAccess({ requestContext, resource: "stored-agents", resourceId: storedAgentId, record: target }); const filter = chunkKGUHJRHZ_cjs.resolveAuthorFilter({ requestContext, resource: "stored-agents" }); const all = await agentsStore.listResolved({ perPage: false, status: "published" }); const targetIsPublic = target.visibility === "public"; const dependents = []; let hiddenCount = 0; for (const record of all.agents) { if (record.id === storedAgentId) continue; if (!referencesTarget(record.agents, storedAgentId)) continue; if (chunkKGUHJRHZ_cjs.matchesAuthorFilter(record, filter)) { dependents.push({ id: record.id, name: record.name ?? record.id }); } else if (targetIsPublic) { hiddenCount += 1; } } return { dependents, hiddenCount }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error listing stored agent dependents"); } } }); function referencesTarget(subAgents, targetId) { if (!subAgents) return false; if (Array.isArray(subAgents)) { return subAgents.some((variant) => { const value = variant?.value; return Boolean(value && typeof value === "object" && Object.prototype.hasOwnProperty.call(value, targetId)); }); } if (typeof subAgents === "object") { return Object.prototype.hasOwnProperty.call(subAgents, targetId); } return false; } var PREVIEW_INSTRUCTIONS_ROUTE = chunkG54X6VE6_cjs.createRoute({ method: "POST", path: "/stored/agents/preview-instructions", responseType: "json", bodySchema: chunkTIWGWGIO_cjs.previewInstructionsBodySchema, responseSchema: chunkTIWGWGIO_cjs.previewInstructionsResponseSchema, summary: "Preview resolved instructions", description: "Resolves an array of instruction blocks against a request context, evaluating rules, fetching prompt block references, and rendering template variables. Returns the final concatenated instruction string.", tags: ["Stored Agents"], requiresAuth: true, handler: async ({ mastra, blocks, context }) => { try { const editor = mastra.getEditor(); if (!editor) { throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Editor is not configured" }); } const result = await editor.prompt.preview(blocks, context ?? {}); return { result }; } catch (error) { return chunkZ7LCIYK7_cjs.handleError(error, "Error previewing instructions"); } } }); exports.CREATE_STORED_AGENT_ROUTE = CREATE_STORED_AGENT_ROUTE; exports.DELETE_STORED_AGENT_ROUTE = DELETE_STORED_AGENT_ROUTE; exports.EXPORT_STORED_AGENT_ROUTE = EXPORT_STORED_AGENT_ROUTE; exports.GET_STORED_AGENT_DEPENDENTS_ROUTE = GET_STORED_AGENT_DEPENDENTS_ROUTE; exports.GET_STORED_AGENT_ROUTE = GET_STORED_AGENT_ROUTE; exports.LIST_STORED_AGENTS_ROUTE = LIST_STORED_AGENTS_ROUTE; exports.OPEN_STORED_AGENT_CHANGE_REQUEST_ROUTE = OPEN_STORED_AGENT_CHANGE_REQUEST_ROUTE; exports.PREVIEW_INSTRUCTIONS_ROUTE = PREVIEW_INSTRUCTIONS_ROUTE; exports.UPDATE_STORED_AGENT_ROUTE = UPDATE_STORED_AGENT_ROUTE; //# sourceMappingURL=chunk-HGFJZ44K.cjs.map //# sourceMappingURL=chunk-HGFJZ44K.cjs.map