#!/usr/bin/env node
import {
  buildSkillRefsFromConfig,
  compileAgentForPlugin,
  computeStringHash,
  createLiquidEngine,
  deriveInstallMode,
  determinePluginVersion,
  discoverAllPluginSkills,
  extractFrontmatter,
  fetchFromSource,
  generateAgentPluginManifest,
  getPluginAgentsDir,
  getPluginManifestPath,
  loadProjectConfig,
  loadProjectSourceConfig,
  resolveAgents,
  writeContentHash,
  writePluginManifest
} from "./chunk-TZXYBG3R.js";
import {
  loadAllAgents,
  loadProjectAgents
} from "./chunk-OCEFD7V6.js";
import {
  typedEntries,
  typedKeys
} from "./chunk-T4EXUIBY.js";
import {
  agentFrontmatterValidationSchema,
  copy,
  directoryExists,
  ensureDir,
  formatZodErrors,
  getErrorMessage,
  glob,
  log,
  readFile,
  verbose,
  warn,
  writeFile
} from "./chunk-LWXRUR6B.js";
import {
  CLAUDE_DIR,
  DIRS,
  PROJECT_ROOT
} from "./chunk-6OWHQ7HM.js";
import {
  init_esm_shims
} from "./chunk-DHET7RCE.js";

// src/cli/lib/agents/agent-fetcher.ts
init_esm_shims();
import path from "path";
async function getAgentDefinitions(remoteSource, options = {}) {
  if (remoteSource) {
    return fetchAgentDefinitionsFromRemote(remoteSource, options);
  }
  return getLocalAgentDefinitions(options);
}
async function getLocalAgentDefinitions(options = {}) {
  const agentsDir = path.join(PROJECT_ROOT, DIRS.agents);
  let templatesDir = path.join(PROJECT_ROOT, DIRS.templates);
  if (!await directoryExists(agentsDir)) {
    throw new Error(
      `Agent partials not found at '${agentsDir}'. Ensure the CLI is properly installed.`
    );
  }
  if (options.projectDir) {
    const localTemplatesDir = path.join(options.projectDir, CLAUDE_DIR, "templates");
    if (await directoryExists(localTemplatesDir)) {
      verbose(`Using local templates from: ${localTemplatesDir}`);
      templatesDir = localTemplatesDir;
    }
  }
  if (!await directoryExists(templatesDir)) {
    verbose(`Templates directory not found: ${templatesDir}`);
  }
  verbose(`Agent partials loaded from CLI: ${agentsDir}`);
  verbose(`Templates directory: ${templatesDir}`);
  return {
    agentsDir,
    templatesDir,
    sourcePath: PROJECT_ROOT
  };
}
async function fetchAgentDefinitionsFromRemote(source, options = {}) {
  verbose(`Fetching agent partials from remote: ${source}`);
  const result = await fetchFromSource(source, {
    forceRefresh: options.forceRefresh,
    subdir: ""
  });
  let agentsDirRelPath = options.agentsDir;
  if (!agentsDirRelPath) {
    const sourceProjectConfig = await loadProjectSourceConfig(result.path);
    agentsDirRelPath = sourceProjectConfig?.agentsDir ?? DIRS.agents;
    if (sourceProjectConfig?.agentsDir) {
      verbose(`Using agentsDir from source config: ${sourceProjectConfig.agentsDir}`);
    }
  }
  const agentsDir = path.join(result.path, agentsDirRelPath);
  const templatesDir = path.join(agentsDir, "_templates");
  if (!await directoryExists(agentsDir)) {
    throw new Error(`Agent partials not found at '${agentsDir}'`);
  }
  if (!await directoryExists(templatesDir)) {
    verbose(`Templates directory not found: ${templatesDir}`);
  }
  verbose(`Agent partials fetched from: ${result.path}`);
  return {
    agentsDir,
    templatesDir,
    sourcePath: result.path
  };
}

// src/cli/lib/agents/agent-recompiler.ts
init_esm_shims();
import path2 from "path";
async function getExistingAgentNames(pluginDir) {
  const agentsDir = getPluginAgentsDir(pluginDir);
  const files = await glob("*.md", agentsDir);
  return files.map((f) => path2.basename(f, ".md"));
}
async function resolveAgentNames(params) {
  const { specifiedAgents, projectConfig, allAgents, outputDir, pluginDir } = params;
  if (specifiedAgents) {
    return specifiedAgents;
  }
  if (projectConfig?.agents?.length) {
    const agentNames = projectConfig.agents.map((a) => a.name);
    verbose(`Using agents from config: ${agentNames.join(", ")}`);
    return agentNames;
  }
  if (outputDir) {
    const names = typedKeys(allAgents);
    verbose(`Using all available agents from source: ${names.join(", ")}`);
    return names;
  }
  return getExistingAgentNames(pluginDir);
}
function buildCompileConfig(params) {
  const { agentNames, allAgents, projectConfig, pluginDir } = params;
  const warnings = [];
  const compileAgents = {};
  for (const agentName of agentNames) {
    if (allAgents[agentName]) {
      const agentStack = projectConfig?.stack?.[agentName];
      compileAgents[agentName] = agentStack ? { skills: buildSkillRefsFromConfig(agentStack) } : {};
    } else {
      warnings.push(`Agent "${agentName}" not found in source definitions`);
    }
  }
  const compileConfig = {
    name: projectConfig?.name || path2.basename(pluginDir),
    description: projectConfig?.description || "Recompiled plugin",
    agents: compileAgents
  };
  return { compileConfig, warnings };
}
async function compileAndWriteAgents(params, result) {
  const { resolvedAgents, agentsDir, sourcePath, engine, installMode } = params;
  for (const [agentName, agent] of typedEntries(resolvedAgents)) {
    try {
      const output = await compileAgentForPlugin(agentName, agent, sourcePath, engine, installMode);
      await writeFile(path2.join(agentsDir, `${agentName}.md`), output);
      result.compiled.push(agentName);
      verbose(`  Recompiled: ${agentName}`);
    } catch (error) {
      result.failed.push(agentName);
      result.warnings.push(`Failed to compile ${agentName}: ${getErrorMessage(error)}`);
    }
  }
}
async function recompileAgents(options) {
  const { pluginDir, sourcePath, skills: providedSkills, projectDir, outputDir } = options;
  const result = {
    compiled: [],
    failed: [],
    warnings: []
  };
  const configDir = projectDir ?? pluginDir;
  const loadedConfig = await loadProjectConfig(configDir);
  const projectConfig = loadedConfig?.config ?? null;
  const builtinAgents = await loadAllAgents(sourcePath);
  const projectAgents = projectDir ? await loadProjectAgents(projectDir) : {};
  const allAgents = {
    ...builtinAgents,
    ...projectAgents
  };
  const agentNames = await resolveAgentNames({
    specifiedAgents: options.agents,
    projectConfig,
    allAgents,
    outputDir,
    pluginDir
  });
  if (agentNames.length === 0) {
    result.warnings.push("No agents found to recompile");
    return result;
  }
  verbose(`Recompiling ${agentNames.length} agents in ${outputDir ?? pluginDir}`);
  let pluginSkills;
  if (providedSkills) {
    pluginSkills = providedSkills;
  } else {
    pluginSkills = await discoverAllPluginSkills(projectDir ?? pluginDir);
  }
  const { compileConfig, warnings } = buildCompileConfig({
    agentNames,
    allAgents,
    projectConfig,
    pluginDir
  });
  result.warnings.push(...warnings);
  const engine = await createLiquidEngine(projectDir);
  const resolvedAgents = await resolveAgents(allAgents, pluginSkills, compileConfig, sourcePath);
  const agentsDir = outputDir ?? getPluginAgentsDir(pluginDir);
  await ensureDir(agentsDir);
  await compileAndWriteAgents(
    {
      resolvedAgents,
      agentsDir,
      sourcePath,
      engine,
      installMode: options.installMode ?? deriveInstallMode(projectConfig?.skills ?? [])
    },
    result
  );
  return result;
}

// src/cli/lib/agents/agent-plugin-compiler.ts
init_esm_shims();
import path3 from "path";
function parseAgentFrontmatter(content, filePath) {
  const raw = extractFrontmatter(content);
  if (!raw) {
    return null;
  }
  const result = agentFrontmatterValidationSchema.safeParse(raw);
  if (!result.success) {
    warn(`Invalid agent frontmatter in ${filePath}: ${formatZodErrors(result.error.issues)}`);
    return null;
  }
  return { name: result.data.name, description: result.data.description };
}
async function compileAgentPlugin(options) {
  const { agentPath, outputDir } = options;
  const fileName = path3.basename(agentPath);
  const content = await readFile(agentPath);
  const frontmatter = parseAgentFrontmatter(content, agentPath);
  if (!frontmatter) {
    throw new Error(
      `Agent '${fileName}' has invalid or missing YAML frontmatter. Required fields: 'name' and 'description'. File: ${agentPath}`
    );
  }
  const agentName = frontmatter.name;
  verbose(`Compiling agent plugin: ${agentName} from ${agentPath}`);
  const pluginDir = path3.join(outputDir, `agent-${agentName}`);
  const agentsDir = path3.join(pluginDir, "agents");
  await ensureDir(pluginDir);
  await ensureDir(agentsDir);
  const newHash = computeStringHash(content);
  const { version, contentHash } = await determinePluginVersion(
    newHash,
    pluginDir,
    getPluginManifestPath
  );
  const manifest = generateAgentPluginManifest({
    agentName,
    description: frontmatter.description,
    version
  });
  await writePluginManifest(pluginDir, manifest);
  await writeContentHash(pluginDir, contentHash, getPluginManifestPath);
  verbose(`  Wrote plugin.json for ${agentName} (v${version})`);
  await copy(agentPath, path3.join(agentsDir, `${agentName}.md`));
  verbose(`  Copied agent ${fileName} -> agents/${agentName}.md`);
  return {
    pluginPath: pluginDir,
    manifest,
    agentName
  };
}
async function compileAllAgentPlugins(agentsDir, outputDir) {
  const results = [];
  const agentMdFiles = await glob("*.md", agentsDir);
  for (const agentFile of agentMdFiles) {
    const agentPath = path3.join(agentsDir, agentFile);
    try {
      const result = await compileAgentPlugin({
        agentPath,
        outputDir
      });
      results.push(result);
      log(`  [OK] agent-${result.agentName}`);
    } catch (error) {
      const errorMessage = getErrorMessage(error);
      warn(`Failed to compile agent from '${agentFile}': ${errorMessage}`);
    }
  }
  return results;
}
function printAgentCompilationSummary(results) {
  log(`
Compiled ${results.length} agent plugins:`);
  for (const result of results) {
    log(`  - agent-${result.agentName} (v${result.manifest.version})`);
  }
}

// src/cli/lib/agents/index.ts
init_esm_shims();

export {
  getAgentDefinitions,
  recompileAgents,
  compileAllAgentPlugins,
  printAgentCompilationSummary
};
//# sourceMappingURL=chunk-YHCYKUA3.js.map