'use strict';

var chunkT3C54LPX_cjs = require('./chunk-T3C54LPX.cjs');
var chunkULYIMS6J_cjs = require('./chunk-ULYIMS6J.cjs');
var chunkKSN5CWZ7_cjs = require('./chunk-KSN5CWZ7.cjs');
var chunkHDIYJI2Z_cjs = require('./chunk-HDIYJI2Z.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');
var workspace = require('@mastra/core/workspace');

var INDEXED_FOLDERS = ["references", "scripts", "assets"];
function extractIndexedPathsFromFiles(files, existing) {
  if (!files || files.length === 0) return {};
  const root = files.find((n) => n.type === "folder");
  if (!root?.children) return {};
  const result = {};
  for (const folderName of INDEXED_FOLDERS) {
    const folder = root.children.find((n) => n.type === "folder" && n.name === folderName);
    if (!folder?.children || folder.children.length === 0) continue;
    const existingPaths = new Set(existing[folderName] ?? []);
    const paths = [...existingPaths];
    collectFilePaths(folder.children, folderName, existingPaths, paths);
    if (paths.length > 0) {
      result[folderName] = paths;
    }
  }
  return result;
}
function collectFilePaths(nodes, prefix, existingPaths, out) {
  for (const node of nodes) {
    if (node.type === "file") {
      const relativePath = `${prefix}/${node.name}`;
      if (!existingPaths.has(relativePath)) {
        out.push(relativePath);
      }
    } else if (node.type === "folder" && node.children) {
      collectFilePaths(node.children, `${prefix}/${node.name}`, existingPaths, out);
    }
  }
}
var LIST_STORED_SKILLS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/stored/skills",
  responseType: "json",
  queryParamSchema: chunkT3C54LPX_cjs.listStoredSkillsQuerySchema,
  responseSchema: chunkT3C54LPX_cjs.listStoredSkillsResponseSchema,
  summary: "List stored skills",
  description: "Returns a paginated list of all skill configurations stored in the database",
  tags: ["Stored Skills"],
  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 skillStore = await storage.getStore("skills");
      if (!skillStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Skills storage domain is not available" });
      }
      const filter = chunkHDIYJI2Z_cjs.resolveAuthorFilter({
        requestContext,
        resource: "stored-skills",
        queryAuthorId: authorId,
        queryVisibility: visibility
      });
      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 { skills: [], 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: "skill" });
        if (starredIds.length === 0) {
          return { skills: [], total: 0, page, perPage: effectivePerPage, hasMore: false };
        }
        const allMatching = await skillStore.listResolved({
          perPage: false,
          orderBy,
          status,
          authorId: filter.kind === "exact" ? filter.authorId : void 0,
          metadata: scopedMetadata,
          entityIds: starredIds
        });
        const visible = allMatching.skills.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 hasMore = effectivePerPage > 0 && endIdx < total;
        return {
          skills: annotated2,
          total,
          page,
          perPage: effectivePerPage,
          hasMore
        };
      }
      const result = await skillStore.listResolved({
        page,
        perPage,
        orderBy,
        status,
        authorId: filter.kind === "exact" ? filter.authorId : void 0,
        metadata: scopedMetadata
      });
      const visibleSkills = result.skills.filter((record) => chunkHDIYJI2Z_cjs.matchesAuthorFilter(record, filter));
      if (!favoritesEnabled) {
        return { ...result, skills: visibleSkills.map(chunkULYIMS6J_cjs.stripFavoriteFields) };
      }
      const enrichment = await chunkULYIMS6J_cjs.prepareFavoritesEnrichment(
        mastra,
        requestContext,
        "skill",
        visibleSkills.map((s) => s.id)
      );
      const annotated = enrichment ? visibleSkills.map((record) => ({ ...record, isFavorited: enrichment.starredIds.has(record.id) })) : visibleSkills.map(chunkULYIMS6J_cjs.stripFavoriteFields);
      return { ...result, skills: annotated };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error listing stored skills");
    }
  }
});
var GET_STORED_SKILL_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/stored/skills/:storedSkillId",
  responseType: "json",
  pathParamSchema: chunkT3C54LPX_cjs.storedSkillIdPathParams,
  responseSchema: chunkT3C54LPX_cjs.getStoredSkillResponseSchema,
  summary: "Get stored skill by ID",
  description: "Returns a specific skill from storage by its unique identifier (resolved with active version config)",
  tags: ["Stored Skills"],
  requiresAuth: true,
  handler: async ({ mastra, requestContext, storedSkillId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const skillStore = await storage.getStore("skills");
      if (!skillStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Skills storage domain is not available" });
      }
      const skill = await skillStore.getByIdResolved(storedSkillId);
      if (!skill) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored skill with id ${storedSkillId} not found` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(skill, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      chunkHDIYJI2Z_cjs.assertReadAccess({ requestContext, resource: "stored-skills", resourceId: storedSkillId, record: skill });
      return chunkULYIMS6J_cjs.enrichOrStripFavorites(mastra, requestContext, "skill", skill);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting stored skill");
    }
  }
});
var CREATE_STORED_SKILL_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/stored/skills",
  responseType: "json",
  bodySchema: chunkT3C54LPX_cjs.createStoredSkillBodySchema,
  responseSchema: chunkT3C54LPX_cjs.createStoredSkillResponseSchema,
  summary: "Create stored skill",
  description: "Creates a new skill configuration in storage with the provided details",
  tags: ["Stored Skills"],
  requiresAuth: true,
  handler: async ({
    mastra,
    requestContext,
    id: providedId,
    name,
    description,
    instructions,
    license,
    compatibility,
    source,
    references,
    scripts,
    assets,
    files,
    metadata,
    visibility: bodyVisibility
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const skillStore = await storage.getStore("skills");
      if (!skillStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Skills storage domain is not available" });
      }
      const id = providedId || chunkDRDVJ35H_cjs.toSlug(name);
      if (!id) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: "Could not derive skill ID from name. Please provide an explicit id."
        });
      }
      const existing = await skillStore.getById(id);
      if (existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(409, { message: `Skill with id ${id} already exists` });
      }
      const authorId = chunkHDIYJI2Z_cjs.getCallerAuthorId(requestContext) ?? void 0;
      const visibility = authorId ? bodyVisibility ?? "private" : "public";
      const indexedPaths = extractIndexedPathsFromFiles(files, { references, scripts, assets });
      await skillStore.create({
        skill: {
          id,
          authorId,
          visibility,
          name,
          description,
          instructions,
          license,
          compatibility,
          source,
          references: indexedPaths.references ?? references,
          scripts: indexedPaths.scripts ?? scripts,
          assets: indexedPaths.assets ?? assets,
          files,
          metadata: chunkDRDVJ35H_cjs.scopeStoredResourceMetadata(metadata, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext))
        }
      });
      const resolved = await skillStore.getByIdResolved(id);
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve created skill" });
      }
      return chunkULYIMS6J_cjs.enrichOrStripFavorites(mastra, requestContext, "skill", resolved);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error creating stored skill");
    }
  }
});
var UPDATE_STORED_SKILL_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "PATCH",
  path: "/stored/skills/:storedSkillId",
  responseType: "json",
  pathParamSchema: chunkT3C54LPX_cjs.storedSkillIdPathParams,
  bodySchema: chunkT3C54LPX_cjs.updateStoredSkillBodySchema,
  responseSchema: chunkT3C54LPX_cjs.updateStoredSkillResponseSchema,
  summary: "Update stored skill",
  description: "Updates an existing skill in storage with the provided fields",
  tags: ["Stored Skills"],
  requiresAuth: true,
  handler: async ({
    mastra,
    requestContext,
    storedSkillId,
    // Entity-level fields
    authorId,
    visibility,
    // Config fields (snapshot-level)
    name,
    description,
    instructions,
    license,
    compatibility,
    source,
    references,
    scripts,
    assets,
    files,
    metadata
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const skillStore = await storage.getStore("skills");
      if (!skillStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Skills storage domain is not available" });
      }
      const existing = await skillStore.getByIdResolved(storedSkillId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored skill with id ${storedSkillId} not found` });
      }
      const scope = await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext);
      chunkDRDVJ35H_cjs.assertStoredResourceScope(existing, scope);
      chunkHDIYJI2Z_cjs.assertWriteAccess({
        requestContext,
        resource: "stored-skills",
        resourceId: storedSkillId,
        action: "edit",
        record: existing
      });
      const callerAuthorId = chunkHDIYJI2Z_cjs.getCallerAuthorId(requestContext) ?? void 0;
      const resolvedVisibility = callerAuthorId ? visibility : visibility != null ? "public" : void 0;
      const indexedPaths = files ? extractIndexedPathsFromFiles(files, { references, scripts, assets }) : {};
      const update = { id: storedSkillId };
      if (authorId !== void 0) update.authorId = authorId;
      if (resolvedVisibility !== void 0) update.visibility = resolvedVisibility;
      if (name !== void 0) update.name = name;
      if (description !== void 0) update.description = description;
      if (instructions !== void 0) update.instructions = instructions;
      if (license !== void 0) update.license = license;
      if (compatibility !== void 0) update.compatibility = compatibility;
      if (source !== void 0) update.source = source;
      const resolvedReferences = indexedPaths.references ?? references;
      const resolvedScripts = indexedPaths.scripts ?? scripts;
      const resolvedAssets = indexedPaths.assets ?? assets;
      if (resolvedReferences !== void 0) update.references = resolvedReferences;
      if (resolvedScripts !== void 0) update.scripts = resolvedScripts;
      if (resolvedAssets !== void 0) update.assets = resolvedAssets;
      if (files !== void 0) update.files = files;
      if (metadata !== void 0) {
        update.metadata = chunkDRDVJ35H_cjs.scopeStoredResourceMetadata({ ...existing.metadata ?? {}, ...metadata }, scope);
      }
      await skillStore.update(update);
      const resolved = await skillStore.getByIdResolved(storedSkillId);
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve updated skill" });
      }
      return chunkULYIMS6J_cjs.enrichOrStripFavorites(mastra, requestContext, "skill", resolved);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error updating stored skill");
    }
  }
});
var DELETE_STORED_SKILL_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "DELETE",
  path: "/stored/skills/:storedSkillId",
  responseType: "json",
  pathParamSchema: chunkT3C54LPX_cjs.storedSkillIdPathParams,
  responseSchema: chunkT3C54LPX_cjs.deleteStoredSkillResponseSchema,
  summary: "Delete stored skill",
  description: "Deletes a skill from storage by its unique identifier",
  tags: ["Stored Skills"],
  requiresAuth: true,
  handler: async ({ mastra, requestContext, storedSkillId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const skillStore = await storage.getStore("skills");
      if (!skillStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Skills storage domain is not available" });
      }
      const existing = await skillStore.getByIdResolved(storedSkillId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored skill with id ${storedSkillId} not found` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(existing, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      chunkHDIYJI2Z_cjs.assertWriteAccess({
        requestContext,
        resource: "stored-skills",
        resourceId: storedSkillId,
        action: "delete",
        record: existing
      });
      await skillStore.delete(storedSkillId);
      try {
        const favoritesStore = await storage.getStore("favorites");
        await favoritesStore?.deleteFavoritesForEntity({ entityType: "skill", entityId: storedSkillId });
      } catch (cascadeError) {
        mastra.getLogger?.()?.warn?.("Failed to cascade-delete favorites for skill", { storedSkillId, error: cascadeError });
      }
      return {
        success: true,
        message: `Skill ${storedSkillId} deleted successfully`
      };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error deleting stored skill");
    }
  }
});
var PUBLISH_STORED_SKILL_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/stored/skills/:storedSkillId/publish",
  responseType: "json",
  pathParamSchema: chunkT3C54LPX_cjs.storedSkillIdPathParams,
  bodySchema: chunkT3C54LPX_cjs.publishStoredSkillBodySchema,
  responseSchema: chunkT3C54LPX_cjs.publishStoredSkillResponseSchema,
  summary: "Publish stored skill",
  description: "Snapshots the skill directory from the filesystem into content-addressable blob storage, creates a new version with a tree manifest, and marks the skill as published",
  tags: ["Stored Skills"],
  requiresAuth: true,
  handler: async ({ mastra, requestContext, storedSkillId, skillPath }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const skillStore = await storage.getStore("skills");
      if (!skillStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Skills storage domain is not available" });
      }
      const blobStore = await storage.getStore("blobs");
      if (!blobStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Blob storage domain is not available" });
      }
      const existing = await skillStore.getByIdResolved(storedSkillId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored skill with id ${storedSkillId} not found` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(existing, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      chunkHDIYJI2Z_cjs.assertWriteAccess({
        requestContext,
        resource: "stored-skills",
        resourceId: storedSkillId,
        action: "edit",
        record: existing
      });
      const path = await import('path');
      const fs = await import('fs/promises');
      const resolvedPath = path.default.resolve(skillPath);
      const allowedBase = path.default.resolve(process.env.SKILLS_BASE_DIR || process.cwd());
      if (!resolvedPath.startsWith(allowedBase + path.default.sep) && resolvedPath !== allowedBase) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: `skillPath must be within the allowed directory: ${allowedBase}`
        });
      }
      try {
        const stat = await fs.stat(resolvedPath);
        if (!stat.isDirectory()) {
          throw new chunk64ITUOXI_cjs.HTTPException(400, { message: `skillPath is not a directory: ${resolvedPath}` });
        }
      } catch (err) {
        if (err instanceof chunk64ITUOXI_cjs.HTTPException) throw err;
        if (err?.code === "ENOENT") {
          throw new chunk64ITUOXI_cjs.HTTPException(400, {
            message: `skillPath does not exist on the server filesystem: ${resolvedPath}. Create the skill directory (with a SKILL.md) before publishing, or use a skill that was materialized to disk.`
          });
        }
        throw err;
      }
      try {
        await fs.stat(path.default.join(resolvedPath, "SKILL.md"));
      } catch (err) {
        if (err?.code === "ENOENT") {
          throw new chunk64ITUOXI_cjs.HTTPException(400, {
            message: `skillPath is missing SKILL.md: ${resolvedPath}`
          });
        }
        throw err;
      }
      const source = new workspace.LocalSkillSource();
      const { publishSkillFromSource } = await import('@mastra/core/workspace');
      const { snapshot, tree, files } = await publishSkillFromSource(source, resolvedPath, blobStore);
      const snapshotUpdate = {};
      for (const [key, value] of Object.entries(snapshot)) {
        if (value !== void 0) snapshotUpdate[key] = value;
      }
      await skillStore.update({
        id: storedSkillId,
        ...snapshotUpdate,
        tree,
        files,
        status: "published"
      });
      const latestVersion = await skillStore.getLatestVersion(storedSkillId);
      if (latestVersion) {
        await skillStore.update({
          id: storedSkillId,
          activeVersionId: latestVersion.id
        });
      }
      const resolved = await skillStore.getByIdResolved(storedSkillId);
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve skill after publish" });
      }
      return chunkULYIMS6J_cjs.enrichOrStripFavorites(mastra, requestContext, "skill", resolved);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error publishing stored skill");
    }
  }
});

exports.CREATE_STORED_SKILL_ROUTE = CREATE_STORED_SKILL_ROUTE;
exports.DELETE_STORED_SKILL_ROUTE = DELETE_STORED_SKILL_ROUTE;
exports.GET_STORED_SKILL_ROUTE = GET_STORED_SKILL_ROUTE;
exports.LIST_STORED_SKILLS_ROUTE = LIST_STORED_SKILLS_ROUTE;
exports.PUBLISH_STORED_SKILL_ROUTE = PUBLISH_STORED_SKILL_ROUTE;
exports.UPDATE_STORED_SKILL_ROUTE = UPDATE_STORED_SKILL_ROUTE;
//# sourceMappingURL=chunk-45SRRAK2.cjs.map
//# sourceMappingURL=chunk-45SRRAK2.cjs.map