'use strict';

var chunkJ5IJWZEA_cjs = require('./chunk-J5IJWZEA.cjs');
var chunkRWLJZWDL_cjs = require('./chunk-RWLJZWDL.cjs');
var chunkSUKFO7UM_cjs = require('./chunk-SUKFO7UM.cjs');
var chunk4LVJBXI2_cjs = require('./chunk-4LVJBXI2.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var workspace = require('@mastra/core/workspace');
var z = require('zod');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var z__default = /*#__PURE__*/_interopDefault(z);

var storedSkillIdPathParams = z__default.default.object({
  storedSkillId: z__default.default.string().describe("Unique identifier for the stored skill")
});
var storageOrderBySchema = z__default.default.object({
  field: z__default.default.enum(["createdAt", "updatedAt"]).optional(),
  direction: z__default.default.enum(["ASC", "DESC"]).optional()
});
var listStoredSkillsQuerySchema = chunkRWLJZWDL_cjs.createPagePaginationSchema(100).extend({
  orderBy: storageOrderBySchema.optional(),
  authorId: z__default.default.string().optional().describe("Filter skills by author identifier"),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Filter skills by metadata key-value pairs")
});
var sourceSchema = z__default.default.discriminatedUnion("type", [
  z__default.default.object({
    type: z__default.default.literal("external"),
    packagePath: z__default.default.string().describe("Package path for external source")
  }),
  z__default.default.object({
    type: z__default.default.literal("local"),
    projectPath: z__default.default.string().describe("Project path for local source")
  }),
  z__default.default.object({
    type: z__default.default.literal("managed"),
    mastraPath: z__default.default.string().describe("Mastra path for managed source")
  })
]);
var snapshotConfigSchema = z__default.default.object({
  name: z__default.default.string().describe("Name of the skill"),
  description: z__default.default.string().describe("Description of what the skill does and when to use it"),
  instructions: z__default.default.string().describe("Markdown instructions for the skill"),
  license: z__default.default.string().optional().describe("License identifier for the skill"),
  compatibility: z__default.default.unknown().optional().describe("Compatibility requirements"),
  source: sourceSchema.optional().describe("Source location of the skill"),
  references: z__default.default.array(z__default.default.string()).optional().describe("List of reference file paths"),
  scripts: z__default.default.array(z__default.default.string()).optional().describe("List of script file paths"),
  assets: z__default.default.array(z__default.default.string()).optional().describe("List of asset file paths"),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Additional metadata for the skill")
});
var createStoredSkillBodySchema = z__default.default.object({
  id: z__default.default.string().optional().describe("Unique identifier. If not provided, derived from name."),
  authorId: z__default.default.string().optional().describe("Author identifier for multi-tenant filtering")
}).merge(snapshotConfigSchema);
var updateStoredSkillBodySchema = z__default.default.object({
  authorId: z__default.default.string().optional()
}).partial().merge(snapshotConfigSchema.partial());
var storedSkillSchema = z__default.default.object({
  id: z__default.default.string(),
  status: z__default.default.string().describe("Skill status: draft, published, or archived"),
  activeVersionId: z__default.default.string().optional(),
  authorId: z__default.default.string().optional(),
  createdAt: z__default.default.coerce.date(),
  updatedAt: z__default.default.coerce.date(),
  name: z__default.default.string().describe("Name of the skill"),
  description: z__default.default.string().describe("Description of what the skill does and when to use it"),
  instructions: z__default.default.string().describe("Markdown instructions for the skill"),
  license: z__default.default.string().optional().describe("License identifier for the skill"),
  compatibility: z__default.default.unknown().optional().describe("Compatibility requirements"),
  source: sourceSchema.optional().describe("Source location of the skill"),
  references: z__default.default.array(z__default.default.string()).optional().describe("List of reference file paths"),
  scripts: z__default.default.array(z__default.default.string()).optional().describe("List of script file paths"),
  assets: z__default.default.array(z__default.default.string()).optional().describe("List of asset file paths"),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Additional metadata for the skill")
});
var listStoredSkillsResponseSchema = chunkRWLJZWDL_cjs.paginationInfoSchema.extend({
  skills: z__default.default.array(storedSkillSchema)
});
var getStoredSkillResponseSchema = storedSkillSchema;
var createStoredSkillResponseSchema = storedSkillSchema;
var updateStoredSkillResponseSchema = z__default.default.union([
  z__default.default.object({
    id: z__default.default.string(),
    status: z__default.default.string(),
    activeVersionId: z__default.default.string().optional(),
    authorId: z__default.default.string().optional(),
    createdAt: z__default.default.coerce.date(),
    updatedAt: z__default.default.coerce.date()
  }),
  storedSkillSchema
]);
var deleteStoredSkillResponseSchema = z__default.default.object({
  success: z__default.default.boolean(),
  message: z__default.default.string()
});
var publishStoredSkillBodySchema = z__default.default.object({
  skillPath: z__default.default.string().describe("Path to the skill directory on the server filesystem (containing SKILL.md)")
});
var publishStoredSkillResponseSchema = storedSkillSchema;

// src/server/handlers/stored-skills.ts
var LIST_STORED_SKILLS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/skills",
  responseType: "json",
  queryParamSchema: listStoredSkillsQuerySchema,
  responseSchema: 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, page, perPage, orderBy, authorId, 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 result = await skillStore.listResolved({
        page,
        perPage,
        orderBy,
        authorId,
        metadata
      });
      return result;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error listing stored skills");
    }
  }
});
var GET_STORED_SKILL_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/skills/:storedSkillId",
  responseType: "json",
  pathParamSchema: storedSkillIdPathParams,
  responseSchema: 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, 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` });
      }
      return skill;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error getting stored skill");
    }
  }
});
var CREATE_STORED_SKILL_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/skills",
  responseType: "json",
  bodySchema: createStoredSkillBodySchema,
  responseSchema: 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,
    id: providedId,
    authorId,
    name,
    description,
    instructions,
    license,
    compatibility,
    source,
    references,
    scripts,
    assets,
    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 id = providedId || chunkJ5IJWZEA_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` });
      }
      await skillStore.create({
        skill: {
          id,
          authorId,
          name,
          description,
          instructions,
          license,
          compatibility,
          source,
          references,
          scripts,
          assets,
          metadata
        }
      });
      const resolved = await skillStore.getByIdResolved(id);
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve created skill" });
      }
      return resolved;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error creating stored skill");
    }
  }
});
var UPDATE_STORED_SKILL_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "PATCH",
  path: "/stored/skills/:storedSkillId",
  responseType: "json",
  pathParamSchema: storedSkillIdPathParams,
  bodySchema: updateStoredSkillBodySchema,
  responseSchema: updateStoredSkillResponseSchema,
  summary: "Update stored skill",
  description: "Updates an existing skill in storage with the provided fields",
  tags: ["Stored Skills"],
  requiresAuth: true,
  handler: async ({
    mastra,
    storedSkillId,
    // Entity-level fields
    authorId,
    // Config fields (snapshot-level)
    name,
    description,
    instructions,
    license,
    compatibility,
    source,
    references,
    scripts,
    assets,
    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.getById(storedSkillId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored skill with id ${storedSkillId} not found` });
      }
      await skillStore.update({
        id: storedSkillId,
        authorId,
        name,
        description,
        instructions,
        license,
        compatibility,
        source,
        references,
        scripts,
        assets,
        metadata
      });
      const resolved = await skillStore.getByIdResolved(storedSkillId);
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve updated skill" });
      }
      return resolved;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error updating stored skill");
    }
  }
});
var DELETE_STORED_SKILL_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "DELETE",
  path: "/stored/skills/:storedSkillId",
  responseType: "json",
  pathParamSchema: storedSkillIdPathParams,
  responseSchema: deleteStoredSkillResponseSchema,
  summary: "Delete stored skill",
  description: "Deletes a skill from storage by its unique identifier",
  tags: ["Stored Skills"],
  requiresAuth: true,
  handler: async ({ mastra, 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.getById(storedSkillId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored skill with id ${storedSkillId} not found` });
      }
      await skillStore.delete(storedSkillId);
      return {
        success: true,
        message: `Skill ${storedSkillId} deleted successfully`
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error deleting stored skill");
    }
  }
});
var PUBLISH_STORED_SKILL_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/skills/:storedSkillId/publish",
  responseType: "json",
  pathParamSchema: storedSkillIdPathParams,
  bodySchema: publishStoredSkillBodySchema,
  responseSchema: 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, 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.getById(storedSkillId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored skill with id ${storedSkillId} not found` });
      }
      const path = await import('path');
      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}`
        });
      }
      const source = new workspace.LocalSkillSource();
      const { publishSkillFromSource } = await import('@mastra/core/workspace');
      const { snapshot, tree } = await publishSkillFromSource(source, resolvedPath, blobStore);
      await skillStore.update({
        id: storedSkillId,
        ...snapshot,
        tree,
        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 resolved;
    } catch (error) {
      return chunkSUKFO7UM_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-5CHFOOQN.cjs.map
//# sourceMappingURL=chunk-5CHFOOQN.cjs.map