'use strict';

var chunkZCX2J552_cjs = require('./chunk-ZCX2J552.cjs');
var chunkULYIMS6J_cjs = require('./chunk-ULYIMS6J.cjs');
var chunkKSN5CWZ7_cjs = require('./chunk-KSN5CWZ7.cjs');
var chunk2XZ2466F_cjs = require('./chunk-2XZ2466F.cjs');
var chunk5SY2ZQ3R_cjs = require('./chunk-5SY2ZQ3R.cjs');
var chunkHDIYJI2Z_cjs = require('./chunk-HDIYJI2Z.cjs');
var chunkTIWGWGIO_cjs = require('./chunk-TIWGWGIO.cjs');
var chunkDIG2K5CV_cjs = require('./chunk-DIG2K5CV.cjs');
var chunkDRDVJ35H_cjs = require('./chunk-DRDVJ35H.cjs');
var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs');
var chunkN54Q3AQR_cjs = require('./chunk-N54Q3AQR.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 = chunkN54Q3AQR_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 = chunkHDIYJI2Z_cjs.resolveAuthorFilter({
        requestContext,
        resource: "stored-agents",
        queryAuthorId: authorId,
        queryVisibility: visibility === "public" ? "public" : void 0
      });
      const scope = await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext);
      const scopedMetadata = chunkDRDVJ35H_cjs.scopeStoredResourceMetadata(metadata, scope);
      const callerId = chunkHDIYJI2Z_cjs.getCallerAuthorId(requestContext);
      const favoritesEnabled = await chunkKSN5CWZ7_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) => chunkHDIYJI2Z_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 chunk5SY2ZQ3R_cjs.prepareAuthorEnrichment(
          mastra,
          requestContext,
          annotated2.map((a) => a.authorId)
        );
        const withAuthors2 = authors2 ? annotated2.map((record) => chunk5SY2ZQ3R_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) => chunkHDIYJI2Z_cjs.matchesAuthorFilter(record, filter));
      const authors = await chunk5SY2ZQ3R_cjs.prepareAuthorEnrichment(
        mastra,
        requestContext,
        visibleAgents.map((a) => a.authorId)
      );
      if (!favoritesEnabled) {
        const stripped = visibleAgents.map(chunkULYIMS6J_cjs.stripFavoriteFields);
        const withAuthors2 = authors ? stripped.map((record) => chunk5SY2ZQ3R_cjs.attachAuthor(record, authors)) : stripped;
        return { ...result, agents: withAuthors2 };
      }
      const enrichment = await chunkULYIMS6J_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(chunkULYIMS6J_cjs.stripFavoriteFields);
      const withAuthors = authors ? annotated.map((record) => chunk5SY2ZQ3R_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) {
    chunkDRDVJ35H_cjs.assertStoredResourceScope(storedAgent, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
    chunkHDIYJI2Z_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 = chunkN54Q3AQR_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 = chunkN54Q3AQR_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 = chunkN54Q3AQR_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` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(agent, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      chunkHDIYJI2Z_cjs.assertReadAccess({ requestContext, resource: "stored-agents", resourceId: storedAgentId, record: agent });
      const authors = await chunk5SY2ZQ3R_cjs.prepareAuthorEnrichment(mastra, requestContext, [agent.authorId]);
      const withFavorite = await chunkULYIMS6J_cjs.enrichOrStripFavorites(mastra, requestContext, "agent", agent);
      return chunk5SY2ZQ3R_cjs.attachAuthor(withFavorite, authors);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting stored agent");
    }
  }
});
var CREATE_STORED_AGENT_ROUTE = chunkN54Q3AQR_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 || chunkDRDVJ35H_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 = chunkHDIYJI2Z_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: chunkDRDVJ35H_cjs.scopeStoredResourceMetadata(metadata, await chunkDRDVJ35H_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 chunkULYIMS6J_cjs.enrichOrStripFavorites(mastra, requestContext, "agent", resolved);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error creating stored agent");
    }
  }
});
var UPDATE_STORED_AGENT_ROUTE = chunkN54Q3AQR_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 chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext);
      chunkDRDVJ35H_cjs.assertStoredResourceScope(existing, scope);
      chunkHDIYJI2Z_cjs.assertWriteAccess({
        requestContext,
        resource: "stored-agents",
        resourceId: storedAgentId,
        action: "edit",
        record: existing
      });
      chunkZCX2J552_cjs.validateMetadataAvatarUrl(metadata);
      const callerAuthorId = chunkHDIYJI2Z_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 = chunkDRDVJ35H_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 chunkULYIMS6J_cjs.enrichOrStripFavorites(mastra, requestContext, "agent", resolved);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error updating stored agent");
    }
  }
});
var DELETE_STORED_AGENT_ROUTE = chunkN54Q3AQR_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` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(existing, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      chunkHDIYJI2Z_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 = chunkN54Q3AQR_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` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(target, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      chunkHDIYJI2Z_cjs.assertReadAccess({ requestContext, resource: "stored-agents", resourceId: storedAgentId, record: target });
      const filter = chunkHDIYJI2Z_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 (chunkHDIYJI2Z_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 = chunkN54Q3AQR_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-GK23JHRL.cjs.map
//# sourceMappingURL=chunk-GK23JHRL.cjs.map