import {
  StateMachineLoader,
  WorkflowManager,
  generateSystemPrompt
} from "./chunk-SB3HRQCH.js";
import "./chunk-R5U7XKVJ.js";

// src/cli.ts
import { fileURLToPath as fileURLToPath3 } from "url";
import { dirname as dirname3, join as join5 } from "path";
import {
  existsSync as existsSync3,
  mkdirSync,
  writeFileSync,
  readFileSync,
  readdirSync
} from "fs";

// src/visualization-launcher.ts
import { spawn } from "child_process";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
var __filename = fileURLToPath(import.meta.url);
var __dirname = dirname(__filename);
function startVisualizationTool() {
  console.log(`
\u{1F389} Starting Workflow Visualizer...

The interactive workflow visualizer provides a web-based interface for
exploring and understanding workflow state machines with beautiful PlantUML diagrams.

Starting development server...
`);
  try {
    const docsPath = join(__dirname, "..", "..", "docs");
    const isDev = process.env["NODE_ENV"] !== "production";
    if (isDev) {
      console.log("\u{1F4E6} Installing dependencies...");
      const install = spawn("npm", ["install"], {
        cwd: docsPath,
        stdio: "inherit",
        shell: true
      });
      install.on("close", (code) => {
        if (code === 0) {
          console.log("\u{1F680} Starting development server...");
          const dev = spawn("npm", ["run", "dev"], {
            cwd: docsPath,
            stdio: "inherit",
            shell: true
          });
          dev.on("close", (code2) => {
            if (code2 !== 0) {
              console.error("\u274C Failed to start development server");
              process.exit(1);
            }
          });
        } else {
          console.error("\u274C Failed to install dependencies");
          process.exit(1);
        }
      });
    } else {
      console.log("\u{1F3D7}\uFE0F  Building visualizer...");
      const build = spawn("npm", ["run", "build"], {
        cwd: docsPath,
        stdio: "inherit",
        shell: true
      });
      build.on("close", (code) => {
        if (code === 0) {
          console.log("\u{1F310} Starting production server...");
          const serve = spawn("npm", ["run", "preview"], {
            cwd: docsPath,
            stdio: "inherit",
            shell: true
          });
          serve.on("close", (code2) => {
            if (code2 !== 0) {
              console.error("\u274C Failed to start production server");
              process.exit(1);
            }
          });
        } else {
          console.error("\u274C Failed to build visualizer");
          process.exit(1);
        }
      });
    }
  } catch (error) {
    console.error("\u274C Error starting workflow visualizer:", error);
    console.log(`
\u{1F4A1} Manual start instructions:
   cd packages/docs
   npm install
   npm run dev
   
   Then open http://localhost:5173/ in your browser.
`);
    process.exit(1);
  }
}

// src/config-generator.ts
import { writeFile, mkdir, readFile } from "fs/promises";
import { join as join2 } from "path";
import { existsSync } from "fs";
function deepMerge(target, source) {
  if (!source || typeof source !== "object") {
    return source;
  }
  if (!target || typeof target !== "object") {
    return source;
  }
  const result = { ...target };
  for (const key of Object.keys(source)) {
    const sourceValue = source[key];
    const targetValue = target[key];
    if (sourceValue && typeof sourceValue === "object" && !Array.isArray(sourceValue) && targetValue && typeof targetValue === "object" && !Array.isArray(targetValue)) {
      result[key] = deepMerge(
        targetValue,
        sourceValue
      );
    } else {
      result[key] = sourceValue;
    }
  }
  return result;
}
var ConfigGenerator = class {
  /**
   * Get the system prompt using existing generation logic
   * Suppresses info logs during CLI operations
   */
  getSystemPrompt() {
    try {
      const loader = new StateMachineLoader();
      const stateMachine = loader.loadStateMachine(process.cwd());
      return generateSystemPrompt(stateMachine);
    } catch (error) {
      throw new Error(`Failed to generate system prompt: ${error}`);
    }
  }
  /**
   * Write file with proper error handling
   */
  async writeFile(filePath, content) {
    try {
      await writeFile(filePath, content, "utf-8");
      console.log(`\u2713 Generated: ${filePath}`);
    } catch (error) {
      throw new Error(`Failed to write file ${filePath}: ${error}`);
    }
  }
  /**
   * Read and merge with existing JSON config file if it exists
   * Returns merged config with new config taking precedence
   */
  async mergeWithExistingConfig(filePath, newConfig) {
    if (!existsSync(filePath)) {
      return newConfig;
    }
    try {
      const existingContent = await readFile(filePath, "utf-8");
      const existingConfig = JSON.parse(existingContent);
      console.log("\u2713 Merged with existing configuration");
      return deepMerge(existingConfig, newConfig);
    } catch (error) {
      if (error instanceof SyntaxError) {
        throw new Error(
          `Existing ${filePath} contains invalid JSON. Please fix the file or remove it to generate a new configuration. Error: ${error.message}`
        );
      }
      throw error;
    }
  }
  /**
   * We'll be using the reduced deployable which only contains the mcp server, not the CLI
   * On Windows, npx commands need to be prefixed with "cmd /c"
   */
  getDefaultMcpConfig() {
    const isWindows = process.platform.startsWith("win");
    if (isWindows) {
      return {
        workflows: {
          command: "cmd",
          args: ["/c", "npx", "@codemcp/workflows-server@latest"]
        }
      };
    }
    return {
      workflows: {
        command: "npx",
        args: ["@codemcp/workflows-server@latest"]
      }
    };
  }
  /**
   * Get default allowed tools for workflows
   */
  getDefaultAllowedTools() {
    return ["whats_next", "conduct_review", "list_workflows", "get_tool_info"];
  }
};
var KiroConfigGenerator = class extends ConfigGenerator {
  async generate(outputDir) {
    const systemPrompt = this.getSystemPrompt();
    const mcpServers = this.getDefaultMcpConfig();
    const newConfig = {
      name: "vibe",
      description: "Responsible vibe development",
      prompt: systemPrompt,
      mcpServers,
      tools: [
        "execute_bash",
        "fs_read",
        "fs_write",
        "report_issue",
        "knowledge",
        "thinking",
        "use_aws",
        "@workflows"
      ],
      allowedTools: [
        "fs_read",
        "fs_write",
        "@workflows/whats_next",
        "@workflows/conduct_review",
        "@workflows/list_workflows",
        "@workflows/get_tool_info"
      ],
      toolsSettings: {
        execute_bash: {
          alwaysAllow: [
            {
              preset: "readOnly"
            }
          ]
        },
        use_aws: {
          alwaysAllow: [
            {
              preset: "readOnly"
            }
          ]
        }
      },
      resources: ["file://README.md", "file://.kiro/rules/**/*.md"],
      hooks: {}
    };
    const kiroDir = join2(outputDir, ".kiro", "agents");
    await mkdir(kiroDir, { recursive: true });
    const configPath = join2(kiroDir, "vibe.json");
    const finalConfig = await this.mergeWithExistingConfig(
      configPath,
      newConfig
    );
    await this.writeFile(configPath, JSON.stringify(finalConfig, null, 2));
  }
};
var ClaudeConfigGenerator = class extends ConfigGenerator {
  async generate(outputDir) {
    const systemPrompt = this.getSystemPrompt();
    const mcpServers = this.getDefaultMcpConfig();
    const claudeDir = join2(outputDir, ".claude");
    const agentsDir = join2(claudeDir, "agents");
    await mkdir(agentsDir, { recursive: true });
    const agentContent = `---
name: Responsible Vibe
description: AI assistant that helps users develop software features using structured development workflows.
---

${systemPrompt}`;
    const agentPath = join2(agentsDir, "vibe.md");
    await this.writeFile(agentPath, agentContent);
    const mcpConfig = {
      mcpServers
    };
    const mcpJsonPath = join2(outputDir, ".mcp.json");
    const finalMcpConfig = await this.mergeWithExistingConfig(
      mcpJsonPath,
      mcpConfig
    );
    await this.writeFile(mcpJsonPath, JSON.stringify(finalMcpConfig, null, 2));
    const settings = {
      permissions: {
        allow: [
          "MCP(workflows:whats_next)",
          "MCP(workflows:conduct_review)",
          "MCP(workflows:list_workflows)",
          "MCP(workflows:get_tool_info)",
          "Read(README.md)",
          "Read(./.vibe/**)",
          "Write(./.vibe/**)"
        ],
        ask: ["Bash(*)", "Write(**)"],
        deny: ["Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)"]
      }
    };
    const settingsPath = join2(claudeDir, "settings.json");
    const finalSettings = await this.mergeWithExistingConfig(
      settingsPath,
      settings
    );
    await this.writeFile(settingsPath, JSON.stringify(finalSettings, null, 2));
  }
};
var GeminiConfigGenerator = class extends ConfigGenerator {
  async generate(outputDir) {
    const systemPrompt = this.getSystemPrompt();
    const mcpServers = this.getDefaultMcpConfig();
    const allowedTools = this.getDefaultAllowedTools();
    const settings = {
      contextFileName: "GEMINI.md",
      autoAccept: false,
      theme: "Default",
      vimMode: false,
      sandbox: false,
      mcpServers,
      allowMCPServers: ["workflows"],
      coreTools: ["ReadFileTool", "WriteFileTool", "GlobTool", "ShellTool"],
      telemetry: {
        enabled: false,
        target: "local",
        otlpEndpoint: "http://localhost:4317",
        logPrompts: false
      },
      usageStatisticsEnabled: false,
      hideTips: false,
      hideBanner: false
    };
    const settingsPath = join2(outputDir, "settings.json");
    const finalSettings = await this.mergeWithExistingConfig(
      settingsPath,
      settings
    );
    await this.writeFile(settingsPath, JSON.stringify(finalSettings, null, 2));
    const geminiMdContent = `# Vibe Development Agent

${systemPrompt}

## Project Context

This agent is configured to work with the workflows server for structured development workflows.

## Available Tools

The following tools are available for development tasks:
${allowedTools.map((tool) => `- ${tool}`).join("\n")}
`;
    const geminiMdPath = join2(outputDir, "GEMINI.md");
    await this.writeFile(geminiMdPath, geminiMdContent);
  }
};
var OpencodeConfigGenerator = class extends ConfigGenerator {
  async generate(outputDir) {
    const systemPrompt = this.getSystemPrompt();
    const configPath = join2(outputDir, "opencode.json");
    const isWindows = process.platform.startsWith("win");
    const newConfig = {
      $schema: "https://opencode.ai/config.json",
      mcp: {
        workflows: {
          type: "local",
          command: isWindows ? ["cmd", "/c", "npx", "@codemcp/workflows-server@latest"] : ["npx", "@codemcp/workflows-server@latest"]
        }
      },
      agent: {
        vibe: {
          description: "Responsible vibe development agent with structured workflows",
          mode: "primary",
          prompt: systemPrompt,
          permission: {
            workflows_reset_development: "ask",
            workflows_start_development: "ask",
            workflows_proceed_to_phase: "ask"
          }
        }
      }
    };
    const finalConfig = await this.mergeWithExistingConfig(
      configPath,
      newConfig
    );
    await this.writeFile(configPath, JSON.stringify(finalConfig, null, 2));
  }
};
var VSCodeConfigGenerator = class extends ConfigGenerator {
  async generate(outputDir) {
    const systemPrompt = this.getSystemPrompt();
    const mcpServers = this.getDefaultMcpConfig();
    const vscodeDir = join2(outputDir, ".vscode");
    await mkdir(vscodeDir, { recursive: true });
    const mcpConfig = {
      servers: mcpServers
    };
    const mcpJsonPath = join2(vscodeDir, "mcp.json");
    await this.writeFile(mcpJsonPath, JSON.stringify(mcpConfig, null, 2));
    const githubAgentsDir = join2(outputDir, ".github", "agents");
    await mkdir(githubAgentsDir, { recursive: true });
    const agentContent = `---
description: AI assistant that helps users develop software features using the workflows server.
tools: ['edit', 'runNotebooks', 'search', 'new', 'runCommands', 'runTasks', 'workflows/*', 'usages', 'vscodeAPI', 'problems', 'changes', 'testFailure', 'openSimpleBrowser', 'fetch', 'githubRepo', 'extensions', 'runSubagent']
---

${systemPrompt}
`;
    const agentPath = join2(githubAgentsDir, "Vibe.agent.md");
    await this.writeFile(agentPath, agentContent);
  }
};
var GeneratorRegistry = class {
  static generators = /* @__PURE__ */ new Map();
  /**
   * Register a generator with its metadata
   */
  static register(metadata) {
    this.generators.set(metadata.name.toLowerCase(), metadata);
    if (metadata.aliases) {
      for (const alias of metadata.aliases) {
        this.generators.set(alias.toLowerCase(), metadata);
      }
    }
  }
  /**
   * Create a generator instance by name or alias
   */
  static createGenerator(name) {
    const metadata = this.generators.get(name.toLowerCase());
    if (!metadata) {
      const available = this.getGeneratorNames().join(", ");
      throw new Error(
        `Unsupported agent: ${name}. Supported agents: ${available}`
      );
    }
    return new metadata.generatorClass();
  }
  /**
   * Get all unique registered generators (without duplicates from aliases)
   */
  static getAllGenerators() {
    const unique = /* @__PURE__ */ new Map();
    for (const metadata of this.generators.values()) {
      unique.set(metadata.name, metadata);
    }
    return Array.from(unique.values());
  }
  /**
   * Get list of primary generator names
   */
  static getGeneratorNames() {
    return this.getAllGenerators().map((g) => g.name);
  }
  /**
   * Get formatted help text for all generators
   */
  static getHelpText() {
    return this.getAllGenerators().map((g) => `  ${g.name.padEnd(20)} ${g.description}`).join("\n");
  }
  /**
   * Check if a generator exists by name or alias
   */
  static exists(name) {
    return this.generators.has(name.toLowerCase());
  }
};
GeneratorRegistry.register({
  name: "kiro",
  description: "Generate .kiro/agents/vibe.json (Kiro)",
  aliases: ["kiro-cli"],
  generatorClass: KiroConfigGenerator
});
GeneratorRegistry.register({
  name: "claude",
  description: "Generate CLAUDE.md, .mcp.json, settings.json",
  generatorClass: ClaudeConfigGenerator
});
GeneratorRegistry.register({
  name: "gemini",
  description: "Generate settings.json, GEMINI.md",
  generatorClass: GeminiConfigGenerator
});
GeneratorRegistry.register({
  name: "opencode",
  description: "Generate opencode.json",
  generatorClass: OpencodeConfigGenerator
});
GeneratorRegistry.register({
  name: "copilot",
  description: "Generate .vscode/mcp.json, .github/agents/Vibe.agent.md",
  aliases: ["copilot-vscode", "vscode"],
  generatorClass: VSCodeConfigGenerator
});
var ConfigGeneratorFactory = class {
  static createGenerator(agent) {
    return GeneratorRegistry.createGenerator(agent);
  }
};
async function generateConfig(agent, outputDir = ".") {
  console.log(`Generating configuration for ${agent}...`);
  const generator = ConfigGeneratorFactory.createGenerator(agent);
  await generator.generate(outputDir);
  console.log(`\u2705 Configuration generated successfully for ${agent}`);
}

// src/skill-generator.ts
import { writeFile as writeFile2, mkdir as mkdir2, readFile as readFile2 } from "fs/promises";
import { join as join4, dirname as dirname2 } from "path";
import { existsSync as existsSync2 } from "fs";
import { fileURLToPath as fileURLToPath2 } from "url";

// src/skill-paths.ts
import { join as join3 } from "path";
function getSkillPaths(platform, outputDir) {
  const normalizedPlatform = platform.toLowerCase();
  switch (normalizedPlatform) {
    case "claude": {
      const skillDir = join3(outputDir, ".claude", "skills", "responsible-vibe");
      return {
        skillDir,
        skillFile: join3(skillDir, "SKILL.md"),
        mcpConfigPath: join3(outputDir, ".mcp.json"),
        mcpConfigKey: "mcpServers",
        isKiroPower: false
      };
    }
    case "opencode": {
      const skillDir = join3(
        outputDir,
        ".opencode",
        "skills",
        "responsible-vibe"
      );
      return {
        skillDir,
        skillFile: join3(skillDir, "SKILL.md"),
        mcpConfigPath: join3(outputDir, "opencode.json"),
        mcpConfigKey: "mcp",
        isKiroPower: false
      };
    }
    case "kiro": {
      const skillDir = join3(outputDir, ".kiro", "powers", "responsible-vibe");
      return {
        skillDir,
        skillFile: join3(skillDir, "POWER.md"),
        mcpConfigPath: join3(skillDir, "mcp.json"),
        // mcpConfigKey omitted - MCP config is at root level
        isKiroPower: true
      };
    }
    case "kiro-cli": {
      const skillDir = join3(outputDir, ".kiro", "skills", "responsible-vibe");
      return {
        skillDir,
        skillFile: join3(skillDir, "SKILL.md"),
        mcpConfigPath: join3(outputDir, ".kiro", "settings", "mcp.json"),
        mcpConfigKey: "mcpServers",
        isKiroPower: false
      };
    }
    case "copilot": {
      const skillDir = join3(outputDir, ".github", "skills", "responsible-vibe");
      return {
        skillDir,
        skillFile: join3(skillDir, "SKILL.md"),
        mcpConfigPath: join3(outputDir, ".vscode", "mcp.json"),
        mcpConfigKey: "servers",
        isKiroPower: false
      };
    }
    case "gemini": {
      const skillDir = join3(outputDir, ".gemini", "skills", "responsible-vibe");
      return {
        skillDir,
        skillFile: join3(skillDir, "SKILL.md"),
        mcpConfigPath: join3(outputDir, "settings.json"),
        mcpConfigKey: "mcpServers",
        isKiroPower: false
      };
    }
    default:
      throw new Error(
        `Unsupported skill platform: ${platform}. Supported platforms: claude, opencode, kiro, kiro-cli, copilot, gemini`
      );
  }
}

// src/skill-generator.ts
var __filename2 = fileURLToPath2(import.meta.url);
var __dirname2 = dirname2(__filename2);
async function getVersion() {
  const possiblePaths = [
    join4(__dirname2, "..", "..", "package.json"),
    // cli package
    join4(__dirname2, "..", "..", "..", "package.json")
    // root package
  ];
  for (const packagePath of possiblePaths) {
    if (existsSync2(packagePath)) {
      try {
        const content = await readFile2(packagePath, "utf-8");
        const pkg = JSON.parse(content);
        if (pkg.version) {
          return pkg.version;
        }
      } catch {
      }
    }
  }
  return "0.0.0";
}
var SkillGenerator = class {
  /**
   * Write file with proper error handling
   */
  async writeFile(filePath, content) {
    try {
      const dir = dirname2(filePath);
      await mkdir2(dir, { recursive: true });
      await writeFile2(filePath, content, "utf-8");
      console.log(`\u2713 Generated: ${filePath}`);
    } catch (error) {
      throw new Error(`Failed to write file ${filePath}: ${error}`);
    }
  }
  /**
   * We'll be using the reduced deployable which only contains the mcp server, not the CLI
   * On Windows, npx commands need to be prefixed with "cmd /c"
   */
  getDefaultMcpConfig() {
    const isWindows = process.platform.startsWith("win");
    if (isWindows) {
      return {
        workflows: {
          command: "cmd",
          args: ["/c", "npx", "@codemcp/workflows-server@latest"]
        }
      };
    }
    return {
      workflows: {
        command: "npx",
        args: ["@codemcp/workflows-server@latest"]
      }
    };
  }
  /**
   * Get MCP config in command + args format (used by Kiro/Amazon Q CLI)
   */
  getKiroMcpConfig() {
    const isWindows = process.platform.startsWith("win");
    if (isWindows) {
      return {
        workflows: {
          command: "cmd",
          args: ["/c", "npx", "@codemcp/workflows-server@latest"]
        }
      };
    }
    return {
      workflows: {
        command: "npx",
        args: ["@codemcp/workflows-server@latest"]
      }
    };
  }
  /**
   * Write MCP configuration file for the platform
   */
  async writeMcpConfig(paths) {
    const mcpConfig = this.getDefaultMcpConfig();
    let configContent;
    if (paths.mcpConfigKey) {
      configContent = { [paths.mcpConfigKey]: mcpConfig };
    } else {
      configContent = { mcpServers: mcpConfig };
    }
    await this.writeFile(
      paths.mcpConfigPath,
      JSON.stringify(configContent, null, 2)
    );
  }
  /**
   * Copy all skill templates to the output directory
   */
  async copySkillTemplates(outputDir) {
    const skillTemplates = [
      "starting-project.md",
      "architecture.md",
      "application-design.md",
      "coding.md",
      "testing.md",
      "task-handling.md"
    ];
    for (const template of skillTemplates) {
      try {
        const templatePath = this.resolveSkillTemplatePath(template);
        const content = await readFile2(templatePath, "utf-8");
        const outputPath = join4(outputDir, "skills", template);
        await this.writeFile(outputPath, content);
      } catch (error) {
        console.warn(`\u26A0 Could not copy skill template ${template}: ${error}`);
      }
    }
  }
  /**
   * Get the system prompt using existing generation logic
   * Same approach as config-generator.ts
   */
  getSystemPrompt() {
    try {
      const loader = new StateMachineLoader();
      const stateMachine = loader.loadStateMachine(process.cwd());
      return generateSystemPrompt(stateMachine);
    } catch (error) {
      throw new Error(`Failed to generate system prompt: ${error}`);
    }
  }
  /**
   * Get the skill content by combining frontmatter template with dynamic system prompt
   * The frontmatter is loaded from resources/templates/skills/SKILL.md
   * The body is generated dynamically from generateSystemPrompt()
   */
  async getSkillTemplate() {
    const frontmatterPath = this.resolveSkillTemplatePath("SKILL.md");
    const frontmatter = await this.loadAndProcessTemplate(frontmatterPath);
    const systemPrompt = this.getSystemPrompt();
    return `${frontmatter}

${systemPrompt}`;
  }
  /**
   * Get the power content by combining frontmatter template with dynamic system prompt
   * (Used by Kiro which uses a different frontmatter format)
   * The frontmatter is loaded from resources/templates/skills/POWER.md
   * The body is generated dynamically from generateSystemPrompt()
   */
  async getPowerTemplate() {
    const frontmatterPath = this.resolveSkillTemplatePath("POWER.md");
    const frontmatter = await this.loadAndProcessTemplate(frontmatterPath);
    const systemPrompt = this.getSystemPrompt();
    return `${frontmatter}

${systemPrompt}`;
  }
  /**
   * Resolve the path to a skill template file
   */
  resolveSkillTemplatePath(filename) {
    const possiblePaths = [
      // Local development - resources symlinked
      join4(__dirname2, "..", "resources", "templates", "skills", filename),
      // From dist directory
      join4(__dirname2, "..", "..", "resources", "templates", "skills", filename),
      // Root resources
      join4(
        __dirname2,
        "..",
        "..",
        "..",
        "resources",
        "templates",
        "skills",
        filename
      ),
      // From core package
      join4(
        __dirname2,
        "..",
        "..",
        "core",
        "resources",
        "templates",
        "skills",
        filename
      )
    ];
    for (const templatePath of possiblePaths) {
      if (existsSync2(templatePath)) {
        return templatePath;
      }
    }
    throw new Error(
      `Skill template not found: ${filename}. Searched paths: ${possiblePaths.join(", ")}`
    );
  }
  /**
   * Load and process a template file, substituting version placeholders
   */
  async loadAndProcessTemplate(templatePath) {
    try {
      const content = await readFile2(templatePath, "utf-8");
      const version = await getVersion();
      return content.replace(/\$\{VERSION\}/g, version);
    } catch (error) {
      throw new Error(`Failed to load skill template: ${error}`);
    }
  }
};
var ClaudeSkillGenerator = class extends SkillGenerator {
  async generate(outputDir) {
    const paths = getSkillPaths("claude", outputDir);
    const skillContent = await this.getSkillTemplate();
    await this.writeFile(paths.skillFile, skillContent);
    await this.writeMcpConfig(paths);
    await this.copySkillTemplates(outputDir);
  }
};
var GeminiSkillGenerator = class extends SkillGenerator {
  async generate(outputDir) {
    const paths = getSkillPaths("gemini", outputDir);
    const skillContent = await this.getSkillTemplate();
    await this.writeFile(paths.skillFile, skillContent);
    await this.writeMcpConfig(paths);
    await this.copySkillTemplates(outputDir);
  }
};
var OpenCodeSkillGenerator = class extends SkillGenerator {
  async generate(outputDir) {
    const paths = getSkillPaths("opencode", outputDir);
    const skillContent = await this.getSkillTemplate();
    await this.writeFile(paths.skillFile, skillContent);
    await this.writeOpencodeMcpConfig(paths);
    await this.copySkillTemplates(outputDir);
  }
  /**
   * Write OpenCode-specific MCP configuration
   * OpenCode uses a different format: type: "local" and command as array
   */
  async writeOpencodeMcpConfig(paths) {
    const isWindows = process.platform.startsWith("win");
    const mcpConfig = {
      workflows: {
        type: "local",
        command: isWindows ? ["cmd", "/c", "npx", "@codemcp/workflows-server@latest"] : ["npx", "@codemcp/workflows-server@latest"]
      }
    };
    const configContent = {
      $schema: "https://opencode.ai/config.json",
      mcp: mcpConfig
    };
    await this.writeFile(
      paths.mcpConfigPath,
      JSON.stringify(configContent, null, 2)
    );
  }
};
var CopilotSkillGenerator = class extends SkillGenerator {
  async generate(outputDir) {
    const paths = getSkillPaths("copilot", outputDir);
    const skillContent = await this.getSkillTemplate();
    await this.writeFile(paths.skillFile, skillContent);
    await this.writeMcpConfig(paths);
    await this.copySkillTemplates(outputDir);
  }
};
var KiroSkillGenerator = class extends SkillGenerator {
  async generate(outputDir) {
    const paths = getSkillPaths("kiro", outputDir);
    const skillContent = await this.getPowerTemplate();
    await this.writeFile(paths.skillFile, skillContent);
    await this.writeKiroMcpConfig(paths);
    await this.copySkillTemplates(outputDir);
  }
  /**
   * Write Kiro-specific MCP configuration (command + args format)
   */
  async writeKiroMcpConfig(paths) {
    const mcpConfig = this.getKiroMcpConfig();
    const configContent = { mcpServers: mcpConfig };
    await this.writeFile(
      paths.mcpConfigPath,
      JSON.stringify(configContent, null, 2)
    );
  }
};
var KiroCliSkillGenerator = class extends SkillGenerator {
  async generate(outputDir) {
    const paths = getSkillPaths("kiro-cli", outputDir);
    const skillContent = await this.getSkillTemplate();
    await this.writeFile(paths.skillFile, skillContent);
    await this.writeKiroMcpConfig(paths);
    await this.copySkillTemplates(outputDir);
  }
  /**
   * Write Kiro-specific MCP configuration (command + args format)
   */
  async writeKiroMcpConfig(paths) {
    const mcpConfig = this.getKiroMcpConfig();
    const configContent = { mcpServers: mcpConfig };
    await this.writeFile(
      paths.mcpConfigPath,
      JSON.stringify(configContent, null, 2)
    );
  }
};
var SkillGeneratorRegistry = class {
  static generators = /* @__PURE__ */ new Map();
  /**
   * Register a generator with its metadata
   */
  static register(metadata) {
    this.generators.set(metadata.name.toLowerCase(), metadata);
    if (metadata.aliases) {
      for (const alias of metadata.aliases) {
        this.generators.set(alias.toLowerCase(), metadata);
      }
    }
  }
  /**
   * Create a generator instance by name or alias
   */
  static createGenerator(name) {
    const metadata = this.generators.get(name.toLowerCase());
    if (!metadata) {
      const available = this.getGeneratorNames().join(", ");
      throw new Error(
        `Unsupported platform: ${name}. Supported platforms: ${available}`
      );
    }
    return new metadata.generatorClass();
  }
  /**
   * Get all unique registered generators (without duplicates from aliases)
   */
  static getAllGenerators() {
    const unique = /* @__PURE__ */ new Map();
    for (const metadata of this.generators.values()) {
      unique.set(metadata.name, metadata);
    }
    return Array.from(unique.values());
  }
  /**
   * Get list of primary generator names
   */
  static getGeneratorNames() {
    return this.getAllGenerators().map((g) => g.name);
  }
  /**
   * Get formatted help text for all generators
   */
  static getHelpText() {
    return this.getAllGenerators().map((g) => `  ${g.name.padEnd(20)} ${g.description}`).join("\n");
  }
  /**
   * Check if a generator exists by name or alias
   */
  static exists(name) {
    return this.generators.has(name.toLowerCase());
  }
};
SkillGeneratorRegistry.register({
  name: "claude",
  description: "Generate skill for Claude Code / Claude Desktop",
  aliases: ["claude-code", "claude-desktop"],
  generatorClass: ClaudeSkillGenerator
});
SkillGeneratorRegistry.register({
  name: "gemini",
  description: "Generate skill for Gemini CLI",
  aliases: ["gemini-cli"],
  generatorClass: GeminiSkillGenerator
});
SkillGeneratorRegistry.register({
  name: "opencode",
  description: "Generate skill for OpenCode",
  generatorClass: OpenCodeSkillGenerator
});
SkillGeneratorRegistry.register({
  name: "copilot",
  description: "Generate skill for GitHub Copilot",
  aliases: ["github-copilot", "copilot-vscode", "vscode"],
  generatorClass: CopilotSkillGenerator
});
SkillGeneratorRegistry.register({
  name: "kiro",
  description: "Generate power for Kiro IDE (POWER.md + bundled mcp.json)",
  generatorClass: KiroSkillGenerator
});
SkillGeneratorRegistry.register({
  name: "kiro-cli",
  description: "Generate skill for Kiro/Amazon Q CLI (SKILL.md + mcp.json)",
  aliases: [],
  generatorClass: KiroCliSkillGenerator
});
async function generateSkill(platform, outputDir = ".") {
  console.log(`Generating skill for ${platform}...`);
  const generator = SkillGeneratorRegistry.createGenerator(platform);
  await generator.generate(outputDir);
  console.log(`\u2705 Skill generated successfully for ${platform}`);
}

// src/cli.ts
var __filename3 = fileURLToPath3(import.meta.url);
var __dirname3 = dirname3(__filename3);
var isLocal = existsSync3(join5(__dirname3, "../../core/dist/index.js"));
var generateSystemPrompt2;
var StateMachineLoader2;
if (isLocal) {
  const coreModule = await import("./dist-FTEFRIPR.js");
  generateSystemPrompt2 = coreModule.generateSystemPrompt;
  StateMachineLoader2 = coreModule.StateMachineLoader;
} else {
  const coreModule = await import("./dist-FTEFRIPR.js");
  generateSystemPrompt2 = coreModule.generateSystemPrompt;
  StateMachineLoader2 = coreModule.StateMachineLoader;
}
function parseFlag(args, flag) {
  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    if (arg.startsWith(`${flag}=`)) {
      return arg.slice(flag.length + 1);
    }
    if (arg === flag && i + 1 < args.length) {
      return args[i + 1];
    }
  }
  return void 0;
}
async function parseCliArgs() {
  const args = process.argv.slice(2);
  if (args.includes("--help") || args.includes("-h")) {
    showHelp();
    return { shouldExit: true };
  }
  const command = args[0];
  if (command === "setup") {
    const subcommand = args[1];
    if (subcommand === "list") {
      handleSetupList();
      return { shouldExit: true };
    } else if (subcommand) {
      const mode = parseFlag(args, "--mode") ?? "config";
      if (mode !== "skill" && mode !== "config") {
        console.error('\u274C Error: --mode must be "skill" or "config"');
        process.exit(1);
      }
      await handleSetup(subcommand, mode);
      return { shouldExit: true };
    } else {
      console.error("\u274C Error: setup requires a target");
      console.error("Usage: setup <target> [--mode config|skill]");
      console.error("       setup list");
      process.exit(1);
    }
  }
  if (command === "workflow") {
    const subcommand = args[1];
    if (subcommand === "list") {
      handleWorkflowList();
      return { shouldExit: true };
    } else if (subcommand === "copy") {
      const sourceWorkflow = args[2];
      const customName = args[3];
      if (!sourceWorkflow || !customName) {
        console.error(
          "\u274C Error: workflow copy requires source workflow and custom name"
        );
        console.error("Usage: workflow copy <source-workflow> <custom-name>");
        process.exit(1);
      }
      handleWorkflowCopy(sourceWorkflow, customName);
      return { shouldExit: true };
    } else {
      console.error("\u274C Unknown workflow subcommand:", subcommand);
      console.error("Available: workflow list, workflow copy <source> <name>");
      process.exit(1);
    }
  }
  if (command === "crowd") {
    const subcommand = args[1];
    if (subcommand === "list") {
      handleCrowdList();
      return { shouldExit: true };
    } else if (subcommand === "copy") {
      const outputDir = parseFlag(args, "--output-dir");
      handleCrowdCopy(outputDir);
      return { shouldExit: true };
    } else {
      console.error("\u274C Unknown crowd subcommand:", subcommand);
      console.error("Available: crowd list, crowd copy [--output-dir DIR]");
      process.exit(1);
    }
  }
  if (command === "visualize" || args.length === 0) {
    startVisualizationTool();
    return { shouldExit: true };
  }
  if (command === "validate") {
    const workflowPath = args[1];
    if (!workflowPath) {
      console.error("\u274C Error: validate requires a workflow file path");
      console.error("Usage: validate <workflow-file.yaml>");
      process.exit(1);
    }
    handleValidateWorkflow(workflowPath);
    return { shouldExit: true };
  }
  if (command === "system-prompt") {
    showSystemPrompt();
    return { shouldExit: true };
  }
  if (args.includes("--generate-config")) {
    const targetIndex = args.findIndex((arg) => arg === "--generate-config") + 1;
    const target = args[targetIndex] || "<target>";
    console.warn("\u26A0\uFE0F  DEPRECATED: --generate-config is deprecated.");
    console.warn(`   Use instead: setup ${target} --mode config`);
    console.warn("");
    console.warn('   Run "setup list" to see available targets.');
    return { shouldExit: true };
  }
  if (args.includes("--validate")) {
    const fileIndex = args.findIndex((arg) => arg === "--validate") + 1;
    const file = args[fileIndex] || "<workflow.yaml>";
    console.warn("\u26A0\uFE0F  DEPRECATED: --validate is deprecated.");
    console.warn(`   Use instead: validate ${file}`);
    return { shouldExit: true };
  }
  if (args.includes("--system-prompt")) {
    console.warn("\u26A0\uFE0F  DEPRECATED: --system-prompt is deprecated.");
    console.warn("   Use instead: system-prompt");
    return { shouldExit: true };
  }
  if (args.includes("--visualize") || args.includes("--viz")) {
    console.warn("\u26A0\uFE0F  DEPRECATED: --visualize/--viz is deprecated.");
    console.warn("   Use instead: visualize");
    console.warn("   Or simply run with no arguments (default behavior).");
    return { shouldExit: true };
  }
  if (command === "agents") {
    const subcommand = args[1] || "";
    console.warn('\u26A0\uFE0F  DEPRECATED: "agents" subcommand is renamed to "crowd".');
    console.warn(`   Use instead: crowd ${subcommand}`);
    return { shouldExit: true };
  }
  if (command === "skill") {
    const subcommand = args[1];
    if (subcommand === "list") {
      console.warn('\u26A0\uFE0F  DEPRECATED: "skill list" is deprecated.');
      console.warn("   Use instead: setup list");
    } else {
      console.warn(
        '\u26A0\uFE0F  DEPRECATED: "skill" subcommand is merged into "setup".'
      );
      console.warn(`   Use instead: setup ${subcommand || "<target>"}`);
    }
    return { shouldExit: true };
  }
  console.error("\u274C Unknown command:", args.join(" "));
  showHelp();
  return { shouldExit: true };
}
function handleValidateWorkflow(workflowPath) {
  try {
    console.log(`\u{1F50D} Validating workflow: ${workflowPath}`);
    const loader = new StateMachineLoader2();
    const workflow = loader.loadFromFile(workflowPath);
    console.log("\u2705 Workflow validation successful!");
    console.log(`\u{1F4CB} Workflow: ${workflow.name}`);
    console.log(`\u{1F4DD} Description: ${workflow.description}`);
    console.log(`\u{1F3C1} Initial state: ${workflow.initial_state}`);
    console.log(`\u{1F504} States: ${Object.keys(workflow.states).join(", ")}`);
    if (workflow.metadata) {
      console.log(`\u{1F3F7}\uFE0F  Domain: ${workflow.metadata.domain || "not specified"}`);
      console.log(
        `\u26A1 Complexity: ${workflow.metadata.complexity || "not specified"}`
      );
    }
  } catch (error) {
    console.error("\u274C Workflow validation failed:");
    console.error(error.message);
    process.exit(1);
  }
}
function handleWorkflowList() {
  try {
    const workflowManager = new WorkflowManager();
    const workflows = workflowManager.getAvailableWorkflowsForProject(
      process.cwd()
    );
    console.log("\u{1F4CB} Available workflows:");
    for (const w of workflows) {
      console.log(`  ${w.name.padEnd(12)} - ${w.description}`);
    }
  } catch (error) {
    console.error("Error listing workflows:", error);
    process.exit(1);
  }
}
function handleWorkflowCopy(sourceWorkflow, customName) {
  try {
    const workflowManager = new WorkflowManager();
    const allWorkflows = workflowManager.getAllAvailableWorkflows();
    const validWorkflow = allWorkflows.find((w) => w.name === sourceWorkflow);
    if (!validWorkflow) {
      console.error(`\u274C Invalid source workflow: ${sourceWorkflow}`);
      console.error(
        `Available workflows: ${allWorkflows.map((w) => w.name).join(", ")}`
      );
      process.exit(1);
    }
    const possibleSourcePaths = [
      join5(
        __dirname3,
        "..",
        "..",
        "..",
        "resources",
        "workflows",
        `${sourceWorkflow}.yaml`
      ),
      join5(
        __dirname3,
        "..",
        "..",
        "core",
        "resources",
        "workflows",
        `${sourceWorkflow}.yaml`
      ),
      join5(process.cwd(), "resources", "workflows", `${sourceWorkflow}.yaml`)
    ];
    const foundPath = possibleSourcePaths.find((p) => existsSync3(p));
    if (!foundPath) {
      console.error(`\u274C Could not find source workflow: ${sourceWorkflow}`);
      process.exit(1);
    }
    const sourceContent = readFileSync(foundPath, "utf8");
    const vibeDir = join5(process.cwd(), ".vibe");
    const workflowsDir = join5(vibeDir, "workflows");
    if (!existsSync3(vibeDir)) {
      mkdirSync(vibeDir, { recursive: true });
    }
    if (!existsSync3(workflowsDir)) {
      mkdirSync(workflowsDir, { recursive: true });
    }
    const customContent = sourceContent.replace(
      new RegExp(`name: '${sourceWorkflow}'`, "g"),
      `name: '${customName}'`
    );
    const workflowPath = join5(workflowsDir, `${customName}.yaml`);
    if (existsSync3(workflowPath)) {
      console.error(
        `\u274C Workflow '${customName}' already exists at ${workflowPath}`
      );
      process.exit(1);
    }
    writeFileSync(workflowPath, customContent);
    console.log(
      `\u2705 Copied '${sourceWorkflow}' workflow to '${customName}' at ${workflowPath}`
    );
    console.log("\u{1F4A1} Edit the file to customize your workflow");
  } catch (error) {
    console.error("Error copying workflow:", error);
    process.exit(1);
  }
}
async function handleSetup(target, mode) {
  try {
    const isSkillTarget = SkillGeneratorRegistry.exists(target);
    const isConfigTarget = GeneratorRegistry.exists(target);
    if (!isSkillTarget && !isConfigTarget) {
      const skillTargets = SkillGeneratorRegistry.getGeneratorNames();
      const configTargets = GeneratorRegistry.getGeneratorNames();
      const allTargets = [.../* @__PURE__ */ new Set([...skillTargets, ...configTargets])];
      console.error(`\u274C Unknown target: ${target}`);
      console.error(`Available targets: ${allTargets.join(", ")}`);
      process.exit(1);
    }
    if (mode === "config") {
      if (!isConfigTarget) {
        const configTargets = GeneratorRegistry.getGeneratorNames();
        console.error(`\u274C Target "${target}" does not support config mode`);
        console.error(`Config mode targets: ${configTargets.join(", ")}`);
        process.exit(1);
      }
      await generateConfig(target, process.cwd());
    } else {
      if (!isSkillTarget) {
        const skillTargets = SkillGeneratorRegistry.getGeneratorNames();
        console.error(`\u274C Target "${target}" does not support skill mode`);
        console.error(`Skill mode targets: ${skillTargets.join(", ")}`);
        console.error(`\u{1F4A1} Try: setup ${target} --mode config`);
        process.exit(1);
      }
      await generateSkill(target, process.cwd());
    }
  } catch (error) {
    console.error(`\u274C Failed to generate ${mode}: ${error}`);
    process.exit(1);
  }
}
function handleSetupList() {
  const skillTargets = SkillGeneratorRegistry.getGeneratorNames();
  const configTargets = GeneratorRegistry.getGeneratorNames();
  const allTargets = [.../* @__PURE__ */ new Set([...skillTargets, ...configTargets])].sort();
  console.log("\u{1F4CB} Available setup targets:\n");
  console.log("  Target".padEnd(20) + "Modes");
  console.log("  " + "-".repeat(35));
  for (const target of allTargets) {
    const modes = [];
    if (skillTargets.includes(target)) modes.push("skill");
    if (configTargets.includes(target)) modes.push("config");
    console.log(`  ${target.padEnd(18)} ${modes.join(", ")}`);
  }
  console.log("\n\u{1F4A1} Usage:");
  console.log(
    "   setup <target>              Generate full agent configuration (default)"
  );
  console.log(
    "   setup <target> --mode config  Generate full agent configuration"
  );
  console.log("   setup <target> --mode skill   Generate skill files only");
}
function handleCrowdList() {
  try {
    const possibleAgentsPaths = [
      join5(__dirname3, "..", "..", "..", "resources", "agents"),
      join5(__dirname3, "..", "..", "core", "resources", "agents")
    ];
    let agentsDir = null;
    for (const path of possibleAgentsPaths) {
      if (existsSync3(path)) {
        agentsDir = path;
        break;
      }
    }
    if (!agentsDir) {
      console.error("\u274C Could not find agents directory");
      process.exit(1);
    }
    const files = readdirSync(agentsDir).filter(
      (f) => f.endsWith(".yaml") || f.endsWith(".yml")
    );
    if (files.length === 0) {
      console.log("\u{1F4CB} No crowd agent configurations found");
      return;
    }
    console.log("\u{1F4CB} Available crowd agent configurations:\n");
    for (const file of files) {
      const agentPath = join5(agentsDir, file);
      const content = readFileSync(agentPath, "utf8");
      const nameMatch = content.match(/^name:\s*(.+)$/m);
      const displayNameMatch = content.match(/^displayName:\s*(.+)$/m);
      const name = nameMatch ? nameMatch[1]?.trim() ?? file.replace(/\.ya?ml$/, "") : file.replace(/\.ya?ml$/, "");
      const displayName = displayNameMatch?.[1]?.trim() ?? name;
      console.log(`  ${name.padEnd(18)} ${displayName}`);
    }
    console.log(
      '\n\u{1F4A1} Use "crowd copy" to copy these configurations to your project'
    );
  } catch (error) {
    console.error("Error listing crowd agents:", error);
    process.exit(1);
  }
}
function handleCrowdCopy(outputDir) {
  try {
    const possibleAgentsPaths = [
      join5(__dirname3, "..", "..", "..", "resources", "agents"),
      join5(__dirname3, "..", "..", "core", "resources", "agents")
    ];
    let sourceAgentsDir = null;
    for (const path of possibleAgentsPaths) {
      if (existsSync3(path)) {
        sourceAgentsDir = path;
        break;
      }
    }
    if (!sourceAgentsDir) {
      console.error("\u274C Could not find source agents directory");
      process.exit(1);
    }
    const targetDir = outputDir || join5(process.cwd(), ".crowd", "agents");
    if (!existsSync3(targetDir)) {
      mkdirSync(targetDir, { recursive: true });
    }
    const files = readdirSync(sourceAgentsDir).filter(
      (f) => f.endsWith(".yaml") || f.endsWith(".yml")
    );
    if (files.length === 0) {
      console.error("\u274C No crowd agent configurations found to copy");
      process.exit(1);
    }
    console.log(
      `\u{1F4CB} Copying ${files.length} crowd agent configuration(s) to ${targetDir}
`
    );
    let copiedCount = 0;
    let skippedCount = 0;
    for (const file of files) {
      const sourcePath = join5(sourceAgentsDir, file);
      const targetPath = join5(targetDir, file);
      if (existsSync3(targetPath)) {
        console.log(`\u23ED\uFE0F  ${file} (already exists, skipping)`);
        skippedCount++;
      } else {
        const content = readFileSync(sourcePath, "utf8");
        writeFileSync(targetPath, content);
        console.log(`\u2705 ${file}`);
        copiedCount++;
      }
    }
    console.log(
      `
\u{1F389} Copied ${copiedCount} crowd agent configuration(s)${skippedCount > 0 ? ` (skipped ${skippedCount} existing)` : ""}`
    );
    console.log(`
\u{1F4A1} Crowd agent configurations are now in: ${targetDir}`);
    console.log("\u{1F4A1} Configure these agents in your crowd-mcp setup");
  } catch (error) {
    console.error("Error copying crowd agents:", error);
    process.exit(1);
  }
}
function showHelp() {
  const skillTargets = SkillGeneratorRegistry.getGeneratorNames();
  const configTargets = GeneratorRegistry.getGeneratorNames();
  const allTargets = [.../* @__PURE__ */ new Set([...skillTargets, ...configTargets])].sort();
  console.log(`
Responsible Vibe CLI Tools

USAGE:
  npx @codemcp/workflows [COMMAND]
  npx @codemcp/workflows             Start the interactive visualizer (default)

SETUP COMMANDS:
  setup <target>                Generate full agent configuration (default mode)
  setup <target> --mode config  Generate full agent configuration
  setup <target> --mode skill   Generate skill files only
  setup list                    List available targets

WORKFLOW COMMANDS:
  workflow list                 List available workflows
  workflow copy <source> <name> Copy a workflow with custom name

CROWD AGENT COMMANDS:
  crowd list                    List available crowd agent configurations
  crowd copy [--output-dir DIR] Copy crowd agent configs to project

UTILITY COMMANDS:
  visualize                     Start the interactive workflow visualizer
  validate <workflow.yaml>      Validate a workflow file
  system-prompt                 Show the system prompt for LLM integration

OPTIONS:
  --help, -h                    Show this help message

AVAILABLE TARGETS:
  ${allTargets.join(", ")}

DESCRIPTION:
  CLI tools for the responsible-vibe development workflow system.
  By default, starts the interactive workflow visualizer.

MORE INFO:
  GitHub: https://github.com/codemcp/workflows
  npm: https://www.npmjs.com/package/@codemcp/workflows
`);
}
function showSystemPrompt() {
  try {
    const loader = new StateMachineLoader2();
    const stateMachine = loader.loadStateMachine(process.cwd());
    const systemPrompt = generateSystemPrompt2(stateMachine);
    console.log(systemPrompt);
  } catch (error) {
    console.error("Error generating system prompt:", error);
    process.exit(1);
  }
}
async function runCli() {
  const { shouldExit } = await parseCliArgs();
  if (shouldExit) {
    return;
  }
}
export {
  parseFlag,
  runCli
};
