#!/usr/bin/env node
import {
  isClaudeCLIAvailable
} from "../../chunk-CLHBKFHU.js";
import {
  BaseCommand,
  EXIT_CODES
} from "../../chunk-SRFNNOLC.js";
import {
  fetchFromSource,
  resolveSource
} from "../../chunk-ZECXM7LP.js";
import "../../chunk-T4EXUIBY.js";
import {
  fileExists,
  readFile
} from "../../chunk-473YHDYQ.js";
import {
  CLAUDE_DIR,
  CLI_COLORS
} from "../../chunk-FVN5PFFY.js";
import {
  init_esm_shims
} from "../../chunk-DHET7RCE.js";

// src/cli/commands/new/agent.tsx
init_esm_shims();
import { useState } from "react";
import { Args, Flags } from "@oclif/core";
import { TextInput } from "@inkjs/ui";
import { spawn } from "child_process";
import matter from "gray-matter";
import { render, Box, Text, useInput } from "ink";
import path from "path";
import { jsx, jsxs } from "react/jsx-runtime";
var META_AGENT_NAME = "agent-summoner";
var AGENTS_SUBDIR = ".claude/agents";
var PurposeInput = ({ onSubmit, onCancel }) => {
  const [error, setError] = useState(null);
  useInput((_input, key) => {
    if (key.escape) {
      onCancel();
    }
  });
  const handleSubmit = (value) => {
    const trimmed = value.trim();
    if (!trimmed) {
      setError("Purpose is required");
      return;
    }
    onSubmit(trimmed);
  };
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
    /* @__PURE__ */ jsx(Text, { bold: true, children: "Create New Agent" }),
    /* @__PURE__ */ jsx(Text, { children: "What should this agent do?" }),
    /* @__PURE__ */ jsx(Text, { dimColor: true, children: "e.g., Manages database migrations with rollback support" }),
    /* @__PURE__ */ jsx(Text, { children: " " }),
    /* @__PURE__ */ jsx(TextInput, { placeholder: "Enter agent purpose...", onSubmit: handleSubmit }),
    error && /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: CLI_COLORS.ERROR, children: error }) })
  ] });
};
async function fetchMetaAgent(source, forceRefresh) {
  const result = await fetchFromSource(source, {
    forceRefresh,
    subdir: AGENTS_SUBDIR
  });
  const agentPath = path.join(result.path, `${META_AGENT_NAME}.md`);
  if (!await fileExists(agentPath)) {
    throw new Error(
      `Meta-agent not found: ${META_AGENT_NAME}.md

Expected at: ${agentPath}
The source repository may not contain the agent-summoner agent.`
    );
  }
  const content = await readFile(agentPath);
  const { data: frontmatter, content: body } = matter(content);
  const fm = frontmatter;
  const tools = fm.tools ? fm.tools.split(",").map((t) => t.trim()) : void 0;
  return {
    description: fm.description || "Creates new agents",
    prompt: body,
    model: fm.model,
    tools
  };
}
function buildAgentPrompt(agentName, purpose, outputDir) {
  return `Create a new Claude Code agent named "${agentName}" in the directory "${outputDir}".

Agent Purpose: ${purpose}

Requirements:
1. Create the agent directory structure at ${outputDir}/${agentName}/
2. Create agent.yaml with appropriate configuration
3. Create intro.md with the agent's role and context
4. Create workflow.md with the agent's operational process
5. Optionally create examples.md if relevant examples would help
6. Optionally create critical-requirements.md for important rules

Follow the existing agent patterns in the codebase. Keep the agent focused and practical.`;
}
async function invokeMetaAgent(agentDef, prompt, nonInteractive) {
  const agentsJson = JSON.stringify({
    [META_AGENT_NAME]: {
      description: agentDef.description,
      prompt: agentDef.prompt,
      model: agentDef.model,
      tools: agentDef.tools
    }
  });
  const args = ["--agents", agentsJson, "--agent", META_AGENT_NAME];
  if (nonInteractive) {
    args.push("-p", prompt);
  } else {
    args.push("--prompt", prompt);
  }
  return new Promise((resolve, reject) => {
    const child = spawn("claude", args, {
      stdio: "inherit",
      shell: true
    });
    child.on("error", (error) => {
      reject(new Error(`Failed to spawn claude CLI: ${error.message}`));
    });
    child.on("close", (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject(new Error(`Claude CLI exited with code ${code}`));
      }
    });
  });
}
var NewAgent = class _NewAgent extends BaseCommand {
  static summary = "Create a new custom agent using AI generation";
  static description = "Uses the agent-summoner meta-agent to scaffold a new agent with proper structure and documentation.";
  static args = {
    name: Args.string({
      description: "Name of the agent to create",
      required: true
    })
  };
  static flags = {
    ...BaseCommand.baseFlags,
    purpose: Flags.string({
      char: "p",
      description: "Purpose/description of the agent",
      required: false
    }),
    refresh: Flags.boolean({
      char: "r",
      description: "Force refresh remote source",
      default: false
    }),
    "non-interactive": Flags.boolean({
      char: "n",
      description: "Run in non-interactive mode",
      default: false
    })
  };
  async run() {
    const { args, flags } = await this.parse(_NewAgent);
    const projectDir = process.cwd();
    const cliAvailable = await isClaudeCLIAvailable();
    if (!cliAvailable) {
      this.error(
        "Claude CLI not found. Please install it first:\n  npm install -g @anthropic-ai/claude-code",
        { exit: EXIT_CODES.ERROR }
      );
    }
    const sourceConfig = await resolveSource(flags.source, projectDir);
    const source = sourceConfig.source;
    let purpose = flags.purpose;
    if (!purpose) {
      let inputResult = null;
      let cancelled = false;
      const { waitUntilExit } = render(
        /* @__PURE__ */ jsx(
          PurposeInput,
          {
            onSubmit: (value) => {
              inputResult = value;
            },
            onCancel: () => {
              cancelled = true;
            }
          }
        )
      );
      await waitUntilExit();
      if (cancelled || !inputResult) {
        this.log("Cancelled");
        this.exit(EXIT_CODES.CANCELLED);
      }
      purpose = inputResult;
    }
    const outputDir = path.join(projectDir, CLAUDE_DIR, "agents", "_custom");
    this.log("");
    this.log(`Agent name: ${args.name}`);
    this.log(`Purpose: ${purpose}`);
    this.log(`Output: ${outputDir}`);
    this.log("");
    this.log("Fetching agent-summoner from source...");
    try {
      const agentDef = await fetchMetaAgent(source, flags.refresh);
      this.log("Meta-agent loaded");
      this.log("");
      const agentPrompt = buildAgentPrompt(args.name, purpose, outputDir);
      this.log("Invoking agent-summoner to create your agent...");
      this.log("\u2500".repeat(60));
      this.log("");
      await invokeMetaAgent(agentDef, agentPrompt, flags["non-interactive"]);
      this.log("");
      this.log("\u2500".repeat(60));
      this.logSuccess("Agent creation complete!");
    } catch (error) {
      this.handleError(error);
    }
  }
};
export {
  NewAgent as default
};
//# sourceMappingURL=agent.js.map