import { toSlug } from './chunk-CGP4FZTH.js';
import { createPagePaginationSchema, paginationInfoSchema } from './chunk-5CRPJSGU.js';
import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-D5VCL56B.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import z from 'zod';

var storedWorkspaceIdPathParams = z.object({
  storedWorkspaceId: z.string().describe("Unique identifier for the stored workspace")
});
var storageOrderBySchema = z.object({
  field: z.enum(["createdAt", "updatedAt"]).optional(),
  direction: z.enum(["ASC", "DESC"]).optional()
});
var listStoredWorkspacesQuerySchema = createPagePaginationSchema(100).extend({
  orderBy: storageOrderBySchema.optional(),
  authorId: z.string().optional().describe("Filter workspaces by author identifier"),
  metadata: z.record(z.string(), z.unknown()).optional().describe("Filter workspaces by metadata key-value pairs")
});
var filesystemConfigSchema = z.object({
  provider: z.string().describe("Filesystem provider name"),
  config: z.record(z.string(), z.unknown()).describe("Filesystem provider configuration")
});
var sandboxConfigSchema = z.object({
  provider: z.string().describe("Sandbox provider name"),
  config: z.record(z.string(), z.unknown()).describe("Sandbox provider configuration")
});
var searchConfigSchema = z.object({
  vectorProvider: z.string().optional().describe("Vector store provider identifier"),
  vectorConfig: z.record(z.string(), z.unknown()).optional().describe("Vector store provider-specific configuration"),
  embedderProvider: z.string().optional().describe("Embedder provider identifier"),
  embedderModel: z.string().optional().describe("Embedder model name"),
  embedderConfig: z.record(z.string(), z.unknown()).optional().describe("Embedder provider-specific configuration"),
  bm25: z.union([z.boolean(), z.object({ k1: z.number().optional(), b: z.number().optional() })]).optional().describe("BM25 keyword search config"),
  searchIndexName: z.string().optional().describe("Custom index name for the vector store"),
  autoIndexPaths: z.array(z.string()).optional().describe("Paths to auto-index on init")
});
var workspaceToolConfigSchema = z.object({
  enabled: z.boolean().optional().describe("Whether the tool is enabled"),
  requireApproval: z.boolean().optional().describe("Whether the tool requires user approval before execution"),
  requireReadBeforeWrite: z.boolean().optional().describe("For write tools: require reading a file before writing to it")
});
var workspaceToolsConfigSchema = z.object({
  enabled: z.boolean().optional().describe("Default: whether all tools are enabled"),
  requireApproval: z.boolean().optional().describe("Default: whether all tools require user approval"),
  tools: z.record(z.string(), workspaceToolConfigSchema).optional().describe("Per-tool overrides keyed by workspace tool name")
});
var snapshotConfigSchema = z.object({
  name: z.string().describe("Name of the workspace"),
  description: z.string().optional().describe("Description of the workspace"),
  filesystem: filesystemConfigSchema.optional().describe("Filesystem configuration"),
  sandbox: sandboxConfigSchema.optional().describe("Sandbox configuration"),
  mounts: z.record(z.string(), filesystemConfigSchema).optional().describe("Mounted filesystems keyed by mount path"),
  search: searchConfigSchema.optional().describe("Search configuration"),
  skills: z.array(z.string()).optional().describe("Array of skill IDs"),
  tools: workspaceToolsConfigSchema.optional().describe("Workspace tool configuration"),
  autoSync: z.boolean().optional().describe("Whether to automatically sync the workspace"),
  operationTimeout: z.number().optional().describe("Operation timeout in milliseconds")
});
var createStoredWorkspaceBodySchema = z.object({
  id: z.string().optional().describe("Unique identifier. If not provided, derived from name."),
  authorId: z.string().optional().describe("Author identifier for multi-tenant filtering"),
  metadata: z.record(z.string(), z.unknown()).optional().describe("Additional metadata for the workspace")
}).merge(snapshotConfigSchema);
var updateStoredWorkspaceBodySchema = z.object({
  authorId: z.string().optional(),
  metadata: z.record(z.string(), z.unknown()).optional()
}).partial().merge(snapshotConfigSchema.partial());
var storedWorkspaceSchema = z.object({
  id: z.string(),
  status: z.string().describe("Workspace status: draft, published, or archived"),
  activeVersionId: z.string().optional(),
  authorId: z.string().optional(),
  metadata: z.record(z.string(), z.unknown()).optional(),
  createdAt: z.coerce.date(),
  updatedAt: z.coerce.date(),
  name: z.string().describe("Name of the workspace"),
  description: z.string().optional().describe("Description of the workspace"),
  filesystem: filesystemConfigSchema.optional().describe("Filesystem configuration"),
  sandbox: sandboxConfigSchema.optional().describe("Sandbox configuration"),
  mounts: z.record(z.string(), filesystemConfigSchema).optional().describe("Mounted filesystems keyed by mount path"),
  search: searchConfigSchema.optional().describe("Search configuration"),
  skills: z.array(z.string()).optional().describe("Array of skill IDs"),
  tools: workspaceToolsConfigSchema.optional().describe("Workspace tool configuration"),
  autoSync: z.boolean().optional().describe("Whether to automatically sync the workspace"),
  operationTimeout: z.number().optional().describe("Operation timeout in milliseconds")
});
var listStoredWorkspacesResponseSchema = paginationInfoSchema.extend({
  workspaces: z.array(storedWorkspaceSchema)
});
var getStoredWorkspaceResponseSchema = storedWorkspaceSchema;
var createStoredWorkspaceResponseSchema = storedWorkspaceSchema;
var updateStoredWorkspaceResponseSchema = z.union([
  z.object({
    id: z.string(),
    status: z.string(),
    activeVersionId: z.string().optional(),
    authorId: z.string().optional(),
    metadata: z.record(z.string(), z.unknown()).optional(),
    createdAt: z.coerce.date(),
    updatedAt: z.coerce.date()
  }),
  storedWorkspaceSchema
]);
var deleteStoredWorkspaceResponseSchema = z.object({
  success: z.boolean(),
  message: z.string()
});

// src/server/handlers/stored-workspaces.ts
var LIST_STORED_WORKSPACES_ROUTE = createRoute({
  method: "GET",
  path: "/stored/workspaces",
  responseType: "json",
  queryParamSchema: listStoredWorkspacesQuerySchema,
  responseSchema: listStoredWorkspacesResponseSchema,
  summary: "List stored workspaces",
  description: "Returns a paginated list of all workspace configurations stored in the database",
  tags: ["Stored Workspaces"],
  requiresAuth: true,
  handler: async ({ mastra, page, perPage, orderBy, authorId, metadata }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const workspaceStore = await storage.getStore("workspaces");
      if (!workspaceStore) {
        throw new HTTPException(500, { message: "Workspaces storage domain is not available" });
      }
      const result = await workspaceStore.listResolved({
        page,
        perPage,
        orderBy,
        authorId,
        metadata
      });
      return result;
    } catch (error) {
      return handleError(error, "Error listing stored workspaces");
    }
  }
});
var GET_STORED_WORKSPACE_ROUTE = createRoute({
  method: "GET",
  path: "/stored/workspaces/:storedWorkspaceId",
  responseType: "json",
  pathParamSchema: storedWorkspaceIdPathParams,
  responseSchema: getStoredWorkspaceResponseSchema,
  summary: "Get stored workspace by ID",
  description: "Returns a specific workspace from storage by its unique identifier (resolved with active version config)",
  tags: ["Stored Workspaces"],
  requiresAuth: true,
  handler: async ({ mastra, storedWorkspaceId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const workspaceStore = await storage.getStore("workspaces");
      if (!workspaceStore) {
        throw new HTTPException(500, { message: "Workspaces storage domain is not available" });
      }
      const workspace = await workspaceStore.getByIdResolved(storedWorkspaceId);
      if (!workspace) {
        throw new HTTPException(404, { message: `Stored workspace with id ${storedWorkspaceId} not found` });
      }
      return workspace;
    } catch (error) {
      return handleError(error, "Error getting stored workspace");
    }
  }
});
var CREATE_STORED_WORKSPACE_ROUTE = createRoute({
  method: "POST",
  path: "/stored/workspaces",
  responseType: "json",
  bodySchema: createStoredWorkspaceBodySchema,
  responseSchema: createStoredWorkspaceResponseSchema,
  summary: "Create stored workspace",
  description: "Creates a new workspace configuration in storage with the provided settings",
  tags: ["Stored Workspaces"],
  requiresAuth: true,
  handler: async ({
    mastra,
    id: providedId,
    authorId,
    metadata,
    name,
    description,
    filesystem,
    sandbox,
    mounts,
    search,
    skills,
    tools,
    autoSync,
    operationTimeout
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const workspaceStore = await storage.getStore("workspaces");
      if (!workspaceStore) {
        throw new HTTPException(500, { message: "Workspaces storage domain is not available" });
      }
      const id = providedId || toSlug(name);
      if (!id) {
        throw new HTTPException(400, {
          message: "Could not derive workspace ID from name. Please provide an explicit id."
        });
      }
      const existing = await workspaceStore.getById(id);
      if (existing) {
        throw new HTTPException(409, { message: `Workspace with id ${id} already exists` });
      }
      await workspaceStore.create({
        workspace: {
          id,
          authorId,
          metadata,
          name,
          description,
          filesystem,
          sandbox,
          mounts,
          search,
          skills,
          tools,
          autoSync,
          operationTimeout
        }
      });
      const resolved = await workspaceStore.getByIdResolved(id);
      if (!resolved) {
        throw new HTTPException(500, { message: "Failed to resolve created workspace" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error creating stored workspace");
    }
  }
});
var UPDATE_STORED_WORKSPACE_ROUTE = createRoute({
  method: "PATCH",
  path: "/stored/workspaces/:storedWorkspaceId",
  responseType: "json",
  pathParamSchema: storedWorkspaceIdPathParams,
  bodySchema: updateStoredWorkspaceBodySchema,
  responseSchema: updateStoredWorkspaceResponseSchema,
  summary: "Update stored workspace",
  description: "Updates an existing workspace in storage with the provided fields",
  tags: ["Stored Workspaces"],
  requiresAuth: true,
  handler: async ({
    mastra,
    storedWorkspaceId,
    // Metadata-level fields
    authorId,
    metadata,
    // Config fields (snapshot-level)
    name,
    description,
    filesystem,
    sandbox,
    mounts,
    search,
    skills,
    tools,
    autoSync,
    operationTimeout
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const workspaceStore = await storage.getStore("workspaces");
      if (!workspaceStore) {
        throw new HTTPException(500, { message: "Workspaces storage domain is not available" });
      }
      const existing = await workspaceStore.getById(storedWorkspaceId);
      if (!existing) {
        throw new HTTPException(404, { message: `Stored workspace with id ${storedWorkspaceId} not found` });
      }
      await workspaceStore.update({
        id: storedWorkspaceId,
        authorId,
        metadata,
        name,
        description,
        filesystem,
        sandbox,
        mounts,
        search,
        skills,
        tools,
        autoSync,
        operationTimeout
      });
      const resolved = await workspaceStore.getByIdResolved(storedWorkspaceId);
      if (!resolved) {
        throw new HTTPException(500, { message: "Failed to resolve updated workspace" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error updating stored workspace");
    }
  }
});
var DELETE_STORED_WORKSPACE_ROUTE = createRoute({
  method: "DELETE",
  path: "/stored/workspaces/:storedWorkspaceId",
  responseType: "json",
  pathParamSchema: storedWorkspaceIdPathParams,
  responseSchema: deleteStoredWorkspaceResponseSchema,
  summary: "Delete stored workspace",
  description: "Deletes a workspace from storage by its unique identifier",
  tags: ["Stored Workspaces"],
  requiresAuth: true,
  handler: async ({ mastra, storedWorkspaceId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const workspaceStore = await storage.getStore("workspaces");
      if (!workspaceStore) {
        throw new HTTPException(500, { message: "Workspaces storage domain is not available" });
      }
      const existing = await workspaceStore.getById(storedWorkspaceId);
      if (!existing) {
        throw new HTTPException(404, { message: `Stored workspace with id ${storedWorkspaceId} not found` });
      }
      await workspaceStore.delete(storedWorkspaceId);
      return {
        success: true,
        message: `Workspace ${storedWorkspaceId} deleted successfully`
      };
    } catch (error) {
      return handleError(error, "Error deleting stored workspace");
    }
  }
});

export { CREATE_STORED_WORKSPACE_ROUTE, DELETE_STORED_WORKSPACE_ROUTE, GET_STORED_WORKSPACE_ROUTE, LIST_STORED_WORKSPACES_ROUTE, UPDATE_STORED_WORKSPACE_ROUTE };
//# sourceMappingURL=chunk-67C7T3N3.js.map
//# sourceMappingURL=chunk-67C7T3N3.js.map