async function loadSpecVerseAPI() {
  const { createRequire } = await import("module");
  const { fileURLToPath } = await import("url");
  const { join: join2, dirname } = await import("path");
  const require2 = createRequire(import.meta.url);
  const publishedPackage = "@specverse/engine-entities";
  const __filename = fileURLToPath(import.meta.url);
  const __dirname = dirname(__filename);
  const isInDist = __dirname.includes("/dist/");
  const levelsUp = isInDist ? 5 : 4;
  const pathParts = Array(levelsUp).fill("..").concat(["dist", "index.js"]);
  const localPath = join2(__dirname, ...pathParts);
  try {
    return await import(localPath);
  } catch (localError) {
    try {
      require2.resolve(publishedPackage);
      return await import(publishedPackage);
    } catch (publishedError) {
      throw new Error(`Failed to load SpecVerse API: local (${localError.message}) and published (${publishedError.message})`);
    }
  }
}
let specverseAPI = null;
import { writeFileSync, unlinkSync, mkdtempSync } from "fs";
import { join } from "path";
import { tmpdir } from "os";
class CLIProxyService {
  constructor(workingDirectory) {
    this.workingDirectory = workingDirectory;
  }
  capabilities = null;
  cliPath = null;
  lastDiscovery = 0;
  DISCOVERY_CACHE_TTL = 5 * 60 * 1e3;
  // 5 minutes
  initialized = false;
  /**
   * Initialize the API - called once before first use
   */
  async init() {
    if (this.initialized) return;
    specverseAPI = await loadSpecVerseAPI();
    this.cliPath = specverseAPI.getCliPath(this.workingDirectory);
    if (!this.cliPath && process.env.MCP_DEBUG) {
      console.error("\u26A0\uFE0F SpecVerse CLI not found. CLI proxy functionality will be limited.");
    }
    this.initialized = true;
  }
  /**
   * Discover CLI capabilities (cached for performance)
   */
  async discoverCapabilities() {
    await this.init();
    const now = Date.now();
    if (this.capabilities && now - this.lastDiscovery < this.DISCOVERY_CACHE_TTL) {
      return this.capabilities;
    }
    try {
      this.capabilities = specverseAPI.getAllCliCapabilities(this.cliPath || void 0);
      this.lastDiscovery = now;
      if (process.env.MCP_DEBUG) {
        console.error(`\u{1F50D} Discovered ${this.capabilities.coreCommands.length} core commands, ${this.capabilities.groupedCommands.length} grouped commands, ${this.capabilities.aiCommands.length} AI commands`);
      }
      return this.capabilities;
    } catch (error) {
      if (process.env.MCP_DEBUG) {
        console.error("\u274C Failed to discover CLI capabilities:", error);
      }
      return {
        coreCommands: [],
        groupedCommands: [],
        aiCommands: []
      };
    }
  }
  /**
   * Generate MCP tool definitions from CLI capabilities
   */
  async generateMCPTools() {
    const capabilities = await this.discoverCapabilities();
    const tools = [];
    tools.push({
      name: "specverse_mcp_debug",
      description: "Show MCP server diagnostic information including SpecVerse installation details, path resolution, and environment analysis",
      inputSchema: {
        type: "object",
        properties: {
          verbose: {
            type: "boolean",
            description: "Show detailed path resolution information"
          }
        },
        required: []
      }
    });
    for (const cmd of capabilities.coreCommands) {
      tools.push(this.createMCPToolFromCommand(cmd));
    }
    for (const cmd of capabilities.groupedCommands) {
      tools.push(this.createMCPToolFromGroupedCommand(cmd));
    }
    for (const cmd of capabilities.aiCommands) {
      tools.push(...this.createAIMCPTools());
      break;
    }
    tools.push(...this.createContentBasedTools());
    return tools;
  }
  /**
   * Execute a CLI command via the proxy
   */
  async executeCommand(toolName, args) {
    try {
      await this.init();
      if (toolName === "specverse_mcp_debug") {
        return await this.executeMCPDebugTool(args.verbose || false);
      }
      if (!this.cliPath) {
        return {
          content: [{
            type: "text",
            text: "SpecVerse CLI not found. Please ensure SpecVerse is installed and accessible."
          }],
          isError: true
        };
      }
      if (toolName.endsWith("_content")) {
        return await this.handleContentBasedCommand(toolName, args);
      }
      const baseCommand = this.mapToolNameToCommand(toolName);
      let command = baseCommand;
      let commandArgs = { ...args };
      if (baseCommand.startsWith("ai ") && args.operation) {
        command = `${baseCommand} ${args.operation}`;
        const { operation, ...remainingArgs } = args;
        commandArgs = remainingArgs;
      } else if (baseCommand.startsWith("lib ")) {
        if (baseCommand === "lib search" && args.query) {
          command = `${baseCommand} "${args.query}"`;
          const { query, ...remainingArgs } = args;
          commandArgs = remainingArgs;
        } else if (baseCommand === "lib info" && args.name) {
          command = `${baseCommand} "${args.name}"`;
          const { name, ...remainingArgs } = args;
          commandArgs = remainingArgs;
        }
      } else if (baseCommand === "init") {
        console.error(`MCP Debug: Received args.name: "${args.name}"`);
        console.error(`MCP Debug: Full args object:`, JSON.stringify(args, null, 2));
        if (args.name) {
          const fullPath = args.name;
          const projectName = args.name.includes("/") ? args.name.split("/").pop() : args.name;
          command = `${baseCommand} "${projectName}"`;
          const { name, ...remainingArgs } = args;
          commandArgs = { ...remainingArgs, fullPath };
        }
        try {
          const result2 = await this.executeInitCommand(command, commandArgs);
          return {
            content: [{
              type: "text",
              text: JSON.stringify(result2, null, 2)
            }]
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          return {
            content: [{
              type: "text",
              text: JSON.stringify({
                status: "error",
                message: "Init command failed",
                details: errorMessage,
                timestamp: (/* @__PURE__ */ new Date()).toISOString()
              }, null, 2)
            }],
            isError: true
          };
        }
      } else if (args.file) {
        command = `${baseCommand} "${args.file}"`;
        const { file, ...remainingArgs } = args;
        commandArgs = remainingArgs;
      }
      const result = await specverseAPI.executeCliCommand(command, commandArgs, {
        cliPath: this.cliPath,
        timeout: 6e4
        // 1 minute timeout
      });
      return {
        content: [{
          type: "text",
          text: JSON.stringify(result, null, 2)
        }]
      };
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      try {
        const parsedError = JSON.parse(errorMessage);
        return {
          content: [{
            type: "text",
            text: JSON.stringify(parsedError, null, 2)
          }],
          isError: true
        };
      } catch {
        return {
          content: [{
            type: "text",
            text: JSON.stringify({
              status: "error",
              message: "CLI command execution failed",
              details: errorMessage,
              timestamp: (/* @__PURE__ */ new Date()).toISOString()
            }, null, 2)
          }],
          isError: true
        };
      }
    }
  }
  /**
   * Create MCP tool definition from core CLI command
   */
  createMCPToolFromCommand(cmd) {
    const properties = {};
    const required = [];
    if (cmd.args) {
      if (cmd.args.includes("<file>")) {
        properties.file = {
          type: "string",
          description: "SpecVerse specification file path"
        };
        required.push("file");
      }
      if (cmd.args.includes("[name]")) {
        properties.name = {
          type: "string",
          description: "Project name (optional)"
        };
      }
    }
    if (cmd.command === "init") {
      properties.name = {
        type: "string",
        description: "Project name"
      };
      properties.template = {
        type: "string",
        description: 'Template to use (default: "default")'
      };
      properties.zip = {
        type: "boolean",
        description: "Return project as ZIP file"
      };
      properties.json = {
        type: "boolean",
        description: "Return project as JSON file structure"
      };
    } else if (cmd.command === "validate" || cmd.command === "infer") {
      properties.verbose = {
        type: "boolean",
        description: "Show detailed output"
      };
    }
    if (this.isFileGeneratingCommand(cmd.command)) {
      properties.zip = {
        type: "boolean",
        description: "Return files as ZIP package instead of creating locally (useful for remote servers or consistent delivery)"
      };
    }
    return {
      name: `specverse_${cmd.command}`,
      description: cmd.description,
      inputSchema: {
        type: "object",
        properties,
        required
      }
    };
  }
  /**
   * Check if a command generates files that could benefit from ZIP packaging
   */
  isFileGeneratingCommand(command) {
    return ["init"].includes(command);
  }
  /**
   * Check if a grouped command generates files that could benefit from ZIP packaging
   */
  isFileGeneratingGroupedCommand(cmd) {
    if (cmd.group === "gen") {
      return true;
    }
    return false;
  }
  /**
   * Create MCP tool definition from grouped command
   */
  createMCPToolFromGroupedCommand(cmd) {
    const properties = {};
    const required = [];
    if (cmd.args?.includes("<file>")) {
      properties.file = {
        type: "string",
        description: "SpecVerse specification file path"
      };
      required.push("file");
    }
    if (cmd.group === "gen") {
      properties.output = {
        type: "string",
        description: "Output file or directory path"
      };
    } else if (cmd.group === "dev" && cmd.subcommand === "watch") {
      properties.directory = {
        type: "string",
        description: "Directory to watch for changes"
      };
    } else if (cmd.group === "lib") {
      if (cmd.subcommand === "search") {
        if (cmd.args?.includes("[query]")) {
          properties.query = {
            type: "string",
            description: "Search term (name, description, tags)"
          };
        }
        properties.type = {
          type: "string",
          enum: ["component", "deployment", "manifest"],
          description: "Filter by type"
        };
        properties.category = {
          type: "string",
          description: "Filter by category"
        };
        properties.tags = {
          type: "string",
          description: "Filter by tags (comma-separated: auth,jwt,session)"
        };
        properties.limit = {
          type: "number",
          description: "Results limit (default: 20)"
        };
        properties.format = {
          type: "string",
          enum: ["table", "json"],
          description: "Output format (default: table)"
        };
      } else if (cmd.subcommand === "info") {
        if (cmd.args?.includes("<name>")) {
          properties.name = {
            type: "string",
            description: "Library name"
          };
          required.push("name");
        }
        properties.version = {
          type: "string",
          description: "Specific version (default: latest)"
        };
        properties.format = {
          type: "string",
          enum: ["table", "json"],
          description: "Output format (default: table)"
        };
        properties.content = {
          type: "boolean",
          description: "Show library content"
        };
      } else if (cmd.subcommand === "list") {
        properties.cached = {
          type: "boolean",
          description: "Show locally cached libraries"
        };
        properties.used = {
          type: "boolean",
          description: "Show libraries used in current project"
        };
        properties.format = {
          type: "string",
          enum: ["table", "json"],
          description: "Output format (default: table)"
        };
      } else if (cmd.subcommand === "tags") {
        properties.format = {
          type: "string",
          enum: ["table", "json"],
          description: "Output format (default: table)"
        };
      }
    }
    if (this.isFileGeneratingGroupedCommand(cmd)) {
      properties.zip = {
        type: "boolean",
        description: "Return files as ZIP package instead of creating locally (useful for remote servers or consistent delivery)"
      };
    }
    return {
      name: `specverse_${cmd.command.replace(/\s+/g, "_")}`,
      description: cmd.description,
      inputSchema: {
        type: "object",
        properties,
        required
      }
    };
  }
  /**
   * Create MCP tools for AI commands
   */
  createAIMCPTools() {
    return [
      {
        name: "specverse_ai_template",
        description: "Get AI prompt templates for SpecVerse operations",
        inputSchema: {
          type: "object",
          properties: {
            operation: {
              type: "string",
              enum: ["analyse", "create", "materialise", "realize"],
              description: "AI operation type"
            },
            pver: {
              type: "string",
              description: "Prompt version (v1|v2|v3|v4|v5|v6|v7) (default: v1)"
            },
            output: {
              type: "string",
              description: "Output file path"
            },
            copy: {
              type: "boolean",
              description: "Copy result to clipboard"
            }
          },
          required: ["operation"]
        }
      },
      {
        name: "specverse_ai_fill",
        description: "Fill AI prompt templates with requirements",
        inputSchema: {
          type: "object",
          properties: {
            operation: {
              type: "string",
              enum: ["analyse", "create", "materialise", "realize"],
              description: "AI operation type"
            },
            requirements: {
              type: "string",
              description: "Project requirements"
            },
            scale: {
              type: "string",
              enum: ["personal", "business", "enterprise"],
              description: "Project scale (default: business)"
            },
            framework: {
              type: "string",
              description: "Framework preference"
            },
            domain: {
              type: "string",
              description: "Project domain"
            },
            compliance: {
              type: "string",
              description: "Compliance requirements (comma-separated)"
            },
            tech: {
              type: "string",
              description: "Technology preferences (comma-separated)"
            },
            pver: {
              type: "string",
              description: "Prompt version (v1|v2|v3|v4|v5|v6|v7) (default: v1)"
            },
            output: {
              type: "string",
              description: "Output file path"
            },
            copy: {
              type: "boolean",
              description: "Copy result to clipboard"
            }
          },
          required: ["operation", "requirements"]
        }
      },
      {
        name: "specverse_ai_suggest",
        description: "Get AI library suggestions for project requirements",
        inputSchema: {
          type: "object",
          properties: {
            requirements: {
              type: "string",
              description: "Project requirements"
            },
            domain: {
              type: "string",
              description: "Project domain"
            },
            scale: {
              type: "string",
              enum: ["personal", "business", "enterprise"],
              default: "business",
              description: "Project scale"
            }
          },
          required: ["requirements"]
        }
      },
      {
        name: "specverse_ai_enhance",
        description: "Get enhanced AI prompts with library context (BEST)",
        inputSchema: {
          type: "object",
          properties: {
            operation: {
              type: "string",
              enum: ["analyse", "create", "materialise", "realize"],
              description: "AI operation type"
            },
            requirements: {
              type: "string",
              description: "Project requirements"
            },
            scale: {
              type: "string",
              enum: ["personal", "business", "enterprise"],
              description: "Project scale (default: business)"
            },
            framework: {
              type: "string",
              description: "Framework preference"
            },
            domain: {
              type: "string",
              description: "Project domain"
            },
            compliance: {
              type: "string",
              description: "Compliance requirements (comma-separated)"
            },
            tech: {
              type: "string",
              description: "Technology preferences (comma-separated)"
            },
            pver: {
              type: "string",
              description: "Prompt version (v1|v2|v3|v4|v5|v6|v7) (default: v1)"
            },
            output: {
              type: "string",
              description: "Output file path"
            },
            copy: {
              type: "boolean",
              description: "Copy result to clipboard"
            }
          },
          required: ["operation", "requirements"]
        }
      }
    ];
  }
  /**
   * Create content-based tools for direct LLM interaction
   */
  createContentBasedTools() {
    return [
      {
        name: "specverse_validate_content",
        description: "Validate SpecVerse specification content directly (no file required)",
        inputSchema: {
          type: "object",
          properties: {
            content: {
              type: "string",
              description: "SpecVerse specification content (.specly format)"
            },
            filename: {
              type: "string",
              description: "Optional filename for error reporting (default: temp.specly)"
            },
            verbose: {
              type: "boolean",
              description: "Show detailed validation results"
            }
          },
          required: ["content"]
        }
      },
      {
        name: "specverse_infer_content",
        description: "Generate complete specification from content using AI inference",
        inputSchema: {
          type: "object",
          properties: {
            content: {
              type: "string",
              description: "Minimal SpecVerse specification content (.specly format)"
            },
            filename: {
              type: "string",
              description: "Optional filename (default: temp.specly)"
            },
            controllers: {
              type: "boolean",
              description: "Generate controllers (default: true)"
            },
            services: {
              type: "boolean",
              description: "Generate services (default: true)"
            },
            events: {
              type: "boolean",
              description: "Generate events (default: true)"
            },
            views: {
              type: "boolean",
              description: "Generate views (default: true)"
            },
            deployment: {
              type: "boolean",
              description: "Generate deployment specification (default: false)"
            },
            environment: {
              type: "string",
              enum: ["development", "staging", "production"],
              description: "Target environment for deployment"
            },
            verbose: {
              type: "boolean",
              description: "Show detailed inference process"
            }
          },
          required: ["content"]
        }
      },
      {
        name: "specverse_gen_yaml_content",
        description: "Generate YAML from SpecVerse specification content",
        inputSchema: {
          type: "object",
          properties: {
            content: {
              type: "string",
              description: "SpecVerse specification content (.specly format)"
            },
            filename: {
              type: "string",
              description: "Optional filename (default: temp.specly)"
            }
          },
          required: ["content"]
        }
      }
    ];
  }
  /**
   * Handle content-based commands by creating temporary files
   */
  async handleContentBasedCommand(toolName, args) {
    const { content, filename = "temp.specly", ...otherArgs } = args;
    if (!content) {
      return {
        content: [{
          type: "text",
          text: JSON.stringify({
            status: "error",
            message: "Content is required for content-based commands",
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          }, null, 2)
        }],
        isError: true
      };
    }
    let tempDir;
    let tempFile;
    try {
      tempDir = mkdtempSync(join(tmpdir(), "specverse-mcp-"));
      tempFile = join(tempDir, filename);
      writeFileSync(tempFile, content, "utf8");
      const cliCommand = this.mapContentToolToCommand(toolName);
      const result = await specverseAPI.executeCliCommand(`${cliCommand} "${tempFile}"`, otherArgs, {
        cliPath: this.cliPath,
        timeout: 6e4
      });
      return {
        content: [{
          type: "text",
          text: JSON.stringify(result, null, 2)
        }]
      };
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      try {
        const parsedError = JSON.parse(errorMessage);
        return {
          content: [{
            type: "text",
            text: JSON.stringify(parsedError, null, 2)
          }],
          isError: true
        };
      } catch {
        return {
          content: [{
            type: "text",
            text: JSON.stringify({
              status: "error",
              message: "Content-based command execution failed",
              details: errorMessage,
              timestamp: (/* @__PURE__ */ new Date()).toISOString()
            }, null, 2)
          }],
          isError: true
        };
      }
    } finally {
      try {
        if (tempFile) unlinkSync(tempFile);
      } catch {
      }
    }
  }
  /**
   * Map content-based tool names to CLI commands
   */
  mapContentToolToCommand(toolName) {
    const mapping = {
      "specverse_validate_content": "validate",
      "specverse_infer_content": "infer",
      "specverse_gen_yaml_content": "gen yaml"
    };
    return mapping[toolName] || toolName.replace(/^specverse_/, "").replace(/_content$/, "").replace(/_/g, " ");
  }
  /**
   * Check if we're running in a remote environment where local file creation won't work
   */
  async isRemoteEnvironment() {
    if (process.env.MCP_FORCE_LOCAL === "true") {
      return false;
    }
    return (
      // Vercel/Netlify/similar serverless
      process.env.VERCEL === "1" || process.env.NETLIFY === "true" || process.env.AWS_LAMBDA_FUNCTION_NAME !== void 0 || // Web deployment mode indicators
      process.env.NODE_ENV === "production" && (process.env.PORT !== void 0 || process.env.HOST !== void 0) || // Environment explicitly marked as remote
      process.env.MCP_REMOTE === "true" || // Detect if we can't write to current directory (more reliable than just checking root)
      await this.isDirectoryReadOnly()
    );
  }
  /**
   * Check if we should use remote environment detection specifically for root directory
   * Only triggers if running from root AND no full paths are provided
   */
  isProblematicRootEnvironment(args) {
    if (process.cwd() !== "/") {
      return false;
    }
    const hasFullPaths = args.name && args.name.startsWith("/") || // /full/path/project
    args.file && args.file.startsWith("/") || // /full/path/file.specly  
    args.output && args.output.startsWith("/") || // /full/path/output
    args.directory && args.directory.startsWith("/");
    if (hasFullPaths) {
      return false;
    }
    const hasRelativeName = args.name && !args.name.startsWith("/");
    return hasRelativeName;
  }
  /**
   * Check if current directory is read-only
   */
  async isDirectoryReadOnly() {
    try {
      const { writeFileSync: writeFileSync2, unlinkSync: unlinkSync2 } = await import("fs");
      const testFile = ".mcp-write-test-" + Date.now();
      writeFileSync2(testFile, "test");
      unlinkSync2(testFile);
      return false;
    } catch {
      return true;
    }
  }
  /**
   * Read project files into structured format for direct delivery
   */
  async readProjectFilesStructured(projectPath) {
    const { readdir, readFile, stat } = await import("fs/promises");
    const { join: join2, relative, extname } = await import("path");
    const files = [];
    let totalSize = 0;
    const directories = [];
    const readDirectory = async (dirPath) => {
      const entries = await readdir(dirPath, { withFileTypes: true });
      for (const entry of entries) {
        const fullPath = join2(dirPath, entry.name);
        const relativePath = relative(projectPath, fullPath);
        if (entry.isDirectory()) {
          directories.push(relativePath + "/");
          await readDirectory(fullPath);
        } else if (entry.isFile()) {
          try {
            const content = await readFile(fullPath, "utf8");
            const stats = await stat(fullPath);
            const extension = extname(entry.name).toLowerCase();
            let fileType = "text";
            if (extension === ".js" || extension === ".ts") fileType = "javascript";
            else if (extension === ".py") fileType = "python";
            else if (extension === ".md") fileType = "markdown";
            else if (extension === ".json") fileType = "json";
            else if (extension === ".yaml" || extension === ".yml") fileType = "yaml";
            else if (extension === ".specly") fileType = "specverse";
            else if (extension === ".sh") fileType = "shell";
            else if (extension === ".html") fileType = "html";
            else if (extension === ".css") fileType = "css";
            files.push({
              path: relativePath,
              content,
              type: fileType,
              size: stats.size,
              encoding: "utf-8"
            });
            totalSize += stats.size;
          } catch (error) {
            console.error(`Failed to read file ${fullPath}:`, error);
          }
        }
      }
    };
    await readDirectory(projectPath);
    return {
      files,
      summary: {
        total_files: files.length,
        total_size: totalSize < 1024 ? `${totalSize}B` : totalSize < 1024 * 1024 ? `${(totalSize / 1024).toFixed(1)}KB` : `${(totalSize / 1024 / 1024).toFixed(2)}MB`,
        directories: [...new Set(directories)].sort(),
        file_types: [...new Set(files.map((f) => f.type))].sort()
      }
    };
  }
  /**
   * Package project files into ZIP for remote delivery (DEPRECATED - keeping for fallback)
   */
  async packageProjectFiles(projectPath) {
    const { execSync } = await import("child_process");
    const { readFile, unlink } = await import("fs/promises");
    const { basename, dirname, join: join2 } = await import("path");
    const { tmpdir: tmpdir2 } = await import("os");
    const projectName = basename(projectPath);
    const parentDir = dirname(projectPath);
    const tempZipPath = join2(tmpdir2(), `${projectName}-${Date.now()}.zip`);
    console.error(`MCP Packaging Debug: Project path: ${projectPath}`);
    console.error(`MCP Packaging Debug: Project name: ${projectName}`);
    console.error(`MCP Packaging Debug: Parent dir: ${parentDir}`);
    console.error(`MCP Packaging Debug: Temp ZIP path: ${tempZipPath}`);
    try {
      const zipCommand = `cd "${parentDir}" && zip -r "${tempZipPath}" "${projectName}"`;
      console.error(`MCP Packaging Debug: Running command: ${zipCommand}`);
      execSync(zipCommand, {
        encoding: "utf8",
        stdio: "pipe"
      });
      console.error(`MCP Packaging Debug: ZIP file created successfully`);
      const zipBuffer = await readFile(tempZipPath);
      console.error(`MCP Packaging Debug: ZIP buffer size: ${zipBuffer.length} bytes`);
      console.error(`MCP Packaging Debug: ZIP buffer size: ${(zipBuffer.length / 1024 / 1024).toFixed(2)} MB`);
      const zipData = zipBuffer.toString("base64");
      console.error(`MCP Packaging Debug: Base64 string length: ${zipData.length} chars`);
      await unlink(tempZipPath);
      console.error(`MCP Packaging Debug: Temp file cleaned up`);
      return {
        zipData,
        fileName: `${projectName}.zip`,
        size: zipBuffer.length
      };
    } catch (error) {
      console.error(`MCP Packaging Debug: ZIP command failed, trying fallback:`, error);
      return await this.createZipFallback(projectPath);
    }
  }
  /**
   * Fallback ZIP creation using pure Node.js
   */
  async createZipFallback(projectPath) {
    const { execSync } = await import("child_process");
    const { readFile, unlink } = await import("fs/promises");
    const { basename, dirname, join: join2 } = await import("path");
    const { tmpdir: tmpdir2 } = await import("os");
    const projectName = basename(projectPath);
    const parentDir = dirname(projectPath);
    const tempTarPath = join2(tmpdir2(), `${projectName}-${Date.now()}.tar.gz`);
    try {
      execSync(`cd "${parentDir}" && tar -czf "${tempTarPath}" "${projectName}"`, {
        encoding: "utf8",
        stdio: "pipe"
      });
      const tarBuffer = await readFile(tempTarPath);
      const tarData = tarBuffer.toString("base64");
      await unlink(tempTarPath);
      return {
        zipData: tarData,
        fileName: `${projectName}.tar.gz`,
        size: tarBuffer.length
      };
    } catch (error) {
      throw new Error(`Failed to create project archive: ${error}`);
    }
  }
  /**
   * Execute init command without --json flag (not supported)
   * For remote deployments, returns project files as JSON structure
   */
  async executeInitCommand(command, args) {
    const { execSync } = await import("child_process");
    const argString = Object.entries(args).filter(
      ([key, value]) => value !== void 0 && value !== null && key !== "zip" && // ZIP is handled by MCP service, not CLI
      key !== "local" && // Local is MCP server flag, not CLI flag
      key !== "fullPath" && // fullPath is used internally for directory handling
      key !== "name"
      // name is passed as positional argument, not flag
    ).map(([key, value]) => {
      if (typeof value === "boolean") {
        return value ? `--${key}` : "";
      } else {
        return `--${key} "${value}"`;
      }
    }).filter(Boolean).join(" ");
    const baseCommand = this.cliPath === "specverse" ? "specverse" : `node ${this.cliPath}`;
    const fullCommand = `${baseCommand} ${command} ${argString}`.trim();
    const rawName = args.fullPath || command.match(/"([^"]+)"/)?.[1] || args.name || "project";
    let projectName;
    let targetWorkingDir;
    if (rawName.startsWith("/")) {
      const { dirname, basename } = await import("path");
      projectName = basename(rawName);
      targetWorkingDir = dirname(rawName);
    } else {
      projectName = rawName;
      targetWorkingDir = process.cwd();
    }
    const forceZip = args.zip === true;
    const forceJson = args.json === true;
    console.error(`MCP Init Debug: Working directory: ${process.cwd()}`);
    console.error(`MCP Init Debug: Target working directory: ${targetWorkingDir}`);
    console.error(`MCP Init Debug: Raw name: ${rawName}`);
    console.error(`MCP Init Debug: Project name: ${projectName}`);
    console.error(`MCP Init Debug: Force ZIP: ${forceZip}`);
    console.error(`MCP Init Debug: Force JSON: ${forceJson}`);
    console.error(`MCP Init Debug: Executing command: ${fullCommand}`);
    if (forceZip) {
      console.error(`MCP Init Debug: ZIP requested - will return ZIP file`);
      return await this.executeInitWithZip(fullCommand, projectName, args);
    } else if (forceJson) {
      console.error(`MCP Init Debug: JSON requested - will return JSON structure`);
      return await this.executeInitWithJson(fullCommand, projectName, args);
    } else if (await this.canCreateLocalFiles(projectName, targetWorkingDir)) {
      console.error(`MCP Init Debug: Local filesystem - will create files locally`);
      return await this.executeInitLocal(fullCommand, projectName, targetWorkingDir);
    } else {
      console.error(`MCP Init Debug: Cannot create local files - will return JSON structure`);
      return await this.executeInitWithJson(fullCommand, projectName, args);
    }
  }
  async canCreateLocalFiles(projectName, targetWorkingDir) {
    try {
      const targetDir = targetWorkingDir || await (async () => {
        const cwd = process.cwd();
        if (projectName.startsWith("/")) {
          const { dirname } = await import("path");
          return dirname(projectName);
        } else {
          if (cwd === "/") {
            return null;
          }
          return cwd;
        }
      })();
      if (!targetDir) {
        return false;
      }
      const { writeFileSync: writeFileSync2, unlinkSync: unlinkSync2 } = await import("fs");
      const { join: join2 } = await import("path");
      const testFile = join2(targetDir, ".mcp-write-test-" + Date.now());
      writeFileSync2(testFile, "test");
      unlinkSync2(testFile);
      return true;
    } catch {
      return false;
    }
  }
  async executeInitLocal(fullCommand, projectName, targetWorkingDir) {
    const { execSync } = await import("child_process");
    const { join: join2 } = await import("path");
    const workingDir = targetWorkingDir || process.cwd();
    try {
      const result = execSync(fullCommand, {
        encoding: "utf8",
        timeout: 3e4,
        stdio: "pipe",
        cwd: workingDir
      });
      return {
        status: "success",
        message: `Project '${projectName}' created successfully`,
        project_path: join2(workingDir, projectName),
        delivery_method: "local_filesystem",
        created: true
      };
    } catch (error) {
      const errorOutput = error.stdout || error.stderr || error.message;
      throw new Error(`Failed to create project '${projectName}': ${errorOutput}`);
    }
  }
  async executeInitWithZip(fullCommand, projectName, args) {
    const { execSync } = await import("child_process");
    const { mkdtemp, rm } = await import("fs/promises");
    const { tmpdir: tmpdir2 } = await import("os");
    const { join: join2 } = await import("path");
    const tempDir = await mkdtemp(join2(tmpdir2(), "specverse-zip-"));
    try {
      const result = execSync(fullCommand, {
        encoding: "utf8",
        timeout: 3e4,
        stdio: "pipe",
        cwd: tempDir
      });
      const projectPath = join2(tempDir, projectName);
      const zipData = await this.packageProjectFiles(projectPath);
      await rm(tempDir, { recursive: true, force: true });
      return {
        status: "success",
        message: `Project '${projectName}' packaged as ZIP`,
        delivery_method: "zip_file",
        zip_data: zipData.zipData,
        file_name: zipData.fileName,
        size: zipData.size
      };
    } catch (error) {
      await rm(tempDir, { recursive: true, force: true }).catch(() => {
      });
      const errorOutput = error.stdout || error.stderr || error.message;
      throw new Error(`Failed to create project '${projectName}': ${errorOutput}`);
    }
  }
  async executeInitWithJson(fullCommand, projectName, args) {
    const { execSync } = await import("child_process");
    const { mkdtemp, rm } = await import("fs/promises");
    const { tmpdir: tmpdir2 } = await import("os");
    const { join: join2 } = await import("path");
    const tempDir = await mkdtemp(join2(tmpdir2(), "specverse-json-"));
    try {
      const result = execSync(fullCommand, {
        encoding: "utf8",
        timeout: 3e4,
        stdio: "pipe",
        cwd: tempDir
      });
      const projectPath = join2(tempDir, projectName);
      const structuredFiles = await this.readProjectFilesStructured(projectPath);
      await rm(tempDir, { recursive: true, force: true });
      return {
        status: "success",
        instruction: "create_file_attachments_for_each_file_described_in_files",
        message: `Project '${projectName}' created successfully`,
        project: projectName,
        files: structuredFiles.files,
        summary: structuredFiles.summary,
        delivery_method: "json_structure"
      };
    } catch (error) {
      await rm(tempDir, { recursive: true, force: true }).catch(() => {
      });
      const errorOutput = error.stdout || error.stderr || error.message;
      throw new Error(`Failed to create project '${projectName}': ${errorOutput}`);
    }
  }
  /**
   * Map MCP tool name back to CLI command
   */
  mapToolNameToCommand(toolName) {
    const command = toolName.replace(/^specverse_/, "").replace(/_/g, " ");
    if (command.startsWith("ai ")) {
      return command;
    }
    return command;
  }
  /**
   * Get MCP package version using Node.js built-in package resolution
   */
  async getMCPVersion() {
    try {
      const { readFile } = await import("fs/promises");
      const { join: join2, dirname } = await import("path");
      const { fileURLToPath } = await import("url");
      const __filename = fileURLToPath(import.meta.url);
      const __dirname = dirname(__filename);
      const packagePaths = [
        join2(__dirname, "..", "..", "package.json"),
        // dist/services -> root
        join2(__dirname, "..", "..", "..", "package.json")
        // dist/target/services -> root
      ];
      for (const packagePath of packagePaths) {
        try {
          const content = await readFile(packagePath, "utf8");
          const packageInfo = JSON.parse(content);
          if (packageInfo.name === "@specverse/mcp") {
            return packageInfo.version;
          }
        } catch {
          continue;
        }
      }
      try {
        const { createRequire } = await import("module");
        const require2 = createRequire(import.meta.url);
        const packageInfo = require2("@specverse/mcp/package.json");
        return packageInfo.version;
      } catch {
        try {
          const packageJsonUrl = import.meta.resolve("@specverse/mcp/package.json");
          const content = await readFile(new URL(packageJsonUrl), "utf8");
          const packageInfo = JSON.parse(content);
          return packageInfo.version;
        } catch {
          return process.env.MCP_VERSION || "unknown";
        }
      }
    } catch {
      return process.env.MCP_VERSION || "unknown";
    }
  }
  /**
   * Execute MCP-specific debug tool
   */
  async executeMCPDebugTool(verbose) {
    try {
      const mcpVersion = await this.getMCPVersion();
      const diagnostics = {
        timestamp: (/* @__PURE__ */ new Date()).toISOString(),
        mcp_server: {
          version: mcpVersion,
          mode: "diagnostic"
        }
      };
      try {
        const { resolvePackageRoot } = specverseAPI;
        const packageRoot = resolvePackageRoot();
        const { readFile } = await import("fs/promises");
        const { join: join2 } = await import("path");
        const packageJsonPath = join2(packageRoot, "package.json");
        const packageContent = await readFile(packageJsonPath, "utf8");
        const packageData = JSON.parse(packageContent);
        diagnostics.specverse_installation = {
          type: "npm_package",
          version: packageData.version,
          location: packageRoot,
          package_name: packageData.name,
          status: "found"
        };
      } catch (error) {
        diagnostics.specverse_installation = {
          status: "error",
          error: error instanceof Error ? error.message : String(error)
        };
      }
      diagnostics.cli_detection = {
        cli_path: this.cliPath,
        working_directory: this.workingDirectory || process.cwd(),
        status: this.cliPath ? "found" : "not_found"
      };
      diagnostics.health_check = {
        can_import_specverse: !!diagnostics.specverse_installation.version,
        cli_accessible: !!this.cliPath,
        capabilities_loaded: !!this.capabilities,
        overall_status: !!diagnostics.specverse_installation.version && !!this.cliPath ? "healthy" : "degraded"
      };
      return {
        content: [{
          type: "text",
          text: JSON.stringify(diagnostics, null, 2)
        }]
      };
    } catch (error) {
      return {
        content: [{
          type: "text",
          text: JSON.stringify({
            status: "error",
            message: "MCP debug tool execution failed",
            error: error instanceof Error ? error.message : String(error),
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          }, null, 2)
        }],
        isError: true
      };
    }
  }
}
export {
  CLIProxyService
};
