// src/actions/skills/passthrough.ts
import chalk from "chalk";

// src/lib/crossSpawn.ts
import crossSpawn from "cross-spawn";
function spawn(command, args, options) {
  return crossSpawn(command, args, options);
}
function spawnSync(command, args, options) {
  return crossSpawn.sync(command, args, options);
}

// src/lib/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/actions/skills/passthrough.ts
var ANSI_PREFIX = String.raw`\x1B\[[\d;]*m`;
var COMMAND_PREFIX = String.raw`(^|[\s$()\x60>]|${ANSI_PREFIX})`;
var SKILLS_COMMANDS = [
  "<command>",
  "add",
  "a",
  "use",
  "remove",
  "rm",
  "list",
  "ls",
  "find",
  "update",
  "upgrade",
  "experimental_install",
  "init",
  "experimental_sync",
  "defaults",
  "lint",
  "updo"
].join("|");
var NPX_SKILLS_PATTERN = new RegExp(String.raw`${COMMAND_PREFIX}npx(?:\s+-y)?\s+skills(?:@latest)?(?=\W|$)`, "g");
var BARE_USAGE_SKILLS_PATTERN = new RegExp(
  String.raw`^(\s*(?:${ANSI_PREFIX})*Usage:(?:${ANSI_PREFIX})*\s*)skills(?=\s+<command>)`,
  "gm"
);
var BARE_PROMPT_SKILLS_PATTERN = new RegExp(
  String.raw`^(\s*(?:${ANSI_PREFIX})*\$(?:${ANSI_PREFIX})*\s*)skills(?=\s+(?:${SKILLS_COMMANDS})(?:\W|$))`,
  "gm"
);
var NPM_INSTALL_SKILLS = "npm install -g skills@latest";
var NPX_SKILLS_ARGS = ["-y", "skills@latest"];
var rewriteSkillsRefs = (text) => {
  const withNpx = text.replaceAll(NPX_SKILLS_PATTERN, (_match, prefix) => `${prefix}xy skills`);
  return withNpx.replaceAll(BARE_USAGE_SKILLS_PATTERN, "$1xy skills").replaceAll(BARE_PROMPT_SKILLS_PATTERN, "$1xy skills");
};
var isMissingCommandError = (result) => {
  const error = result.error;
  return error != null && "code" in error && error.code === "ENOENT";
};
var commandExists = (command) => {
  const result = spawnSync(command, ["--version"], { stdio: "ignore" });
  return !isMissingCommandError(result);
};
var resolveSkillsInvocation = async (args, options = {}) => {
  const exists = options.commandExists ?? commandExists;
  if (exists("skills")) {
    return {
      args,
      command: "skills",
      fallback: false
    };
  }
  const writeNotice = options.writeNotice ?? ((message) => console.error(message));
  if (!exists("npx")) {
    writeNotice(chalk.red(`skills command not found and npx is unavailable. Install Skills.sh with \`${NPM_INSTALL_SKILLS}\`.`));
    return void 0;
  }
  writeNotice(chalk.gray("skills command not found; using npx -y skills@latest for this invocation."));
  return {
    args: [...NPX_SKILLS_ARGS, ...args],
    command: "npx",
    fallback: true
  };
};
var runSkills = async (args, options = {}) => {
  const invocation = await resolveSkillsInvocation(args, options);
  if (invocation === void 0) return 1;
  const interactive = options.interactive ?? false;
  const stdio = interactive ? "inherit" : ["inherit", "pipe", "pipe"];
  return new Promise((resolve) => {
    const child = spawn(invocation.command, invocation.args, {
      env: { FORCE_COLOR: "3", ...process.env },
      stdio
    });
    if (!interactive) {
      child.stdout?.setEncoding("utf8");
      child.stderr?.setEncoding("utf8");
      child.stdout?.on("data", (chunk) => {
        process.stdout.write(rewriteSkillsRefs(chunk));
      });
      child.stderr?.on("data", (chunk) => {
        process.stderr.write(rewriteSkillsRefs(chunk));
      });
    }
    child.on("error", () => resolve(1));
    child.on("close", (code) => resolve(code ?? 1));
  });
};
var argvAfterCommand = (command) => {
  const argv = process.argv;
  const commandIdx = argv.indexOf(command);
  if (commandIdx === -1) return [];
  return argv.slice(commandIdx + 1);
};

// src/actions/skills/defaults.ts
var XYO_SKILLS_SOURCE = "XYOracleNetwork/xyo-skills";
var XYO_DEFAULT_SKILLS = [
  "xl1-build",
  "xl1-knowledge",
  "xl1-patterns",
  "xl1-scaffold",
  "xy-development",
  "xy-toolchain",
  "xyo-knowledge"
];
var AGENT_FLAGS = /* @__PURE__ */ new Set(["-a", "--agent"]);
var hasSkillsAgentFlag = (args) => {
  return args.some((arg) => AGENT_FLAGS.has(arg) || arg.startsWith("--agent="));
};
var skillsDefaultsArgs = (args) => {
  const installSelector = hasSkillsAgentFlag(args) ? ["--skill", "*"] : ["--all"];
  return ["add", XYO_SKILLS_SOURCE, ...installSelector, ...args];
};
var skillsDefaults = (args) => {
  return runSkills(skillsDefaultsArgs(args));
};

// src/actions/skills/lint.ts
import {
  existsSync,
  readdirSync,
  statSync
} from "node:fs";
import OS from "node:os";
import PATH from "node:path";
import chalk2 from "chalk";
var listSkillDirs = (root) => {
  if (!existsSync(root)) return [];
  return readdirSync(root).filter(
    (f) => statSync(PATH.resolve(root, f)).isDirectory()
  );
};
var skillsLint = (options = {}) => {
  const projectDir = options.projectDir ?? PATH.resolve(INIT_CWD(), ".claude", "skills");
  const globalDir = options.globalDir ?? PATH.resolve(OS.homedir(), ".claude", "skills");
  const projectSkills = listSkillDirs(projectDir);
  const globalSkills = new Set(listSkillDirs(globalDir));
  const duplicates = projectSkills.filter((name) => globalSkills.has(name)).toSorted((a, b) => a.localeCompare(b));
  if (duplicates.length === 0) {
    console.log(chalk2.gray("skills: no project/global duplicates"));
    return 0;
  }
  for (const name of duplicates) {
    console.log(chalk2.yellow(`skills: '${name}' is installed in both project and global scope`));
  }
  console.log(chalk2.yellow(`skills: ${duplicates.length} duplicate(s) found`));
  return 1;
};

// src/actions/skills/updo.ts
var SCOPE_FLAGS = /* @__PURE__ */ new Set(["-g", "--global", "-p", "--project"]);
var hasSkillsScopeFlag = (args) => args.some((a) => SCOPE_FLAGS.has(a));
var skillsUpdoArgs = (args) => {
  const finalArgs = hasSkillsScopeFlag(args) ? args : ["-p", ...args];
  return ["update", ...finalArgs];
};
var skillsUpdo = (args) => {
  return runSkills(skillsUpdoArgs(args));
};
export {
  XYO_DEFAULT_SKILLS,
  XYO_SKILLS_SOURCE,
  argvAfterCommand,
  commandExists,
  hasSkillsAgentFlag,
  hasSkillsScopeFlag,
  resolveSkillsInvocation,
  rewriteSkillsRefs,
  runSkills,
  skillsDefaults,
  skillsDefaultsArgs,
  skillsLint,
  skillsUpdo,
  skillsUpdoArgs
};
//# sourceMappingURL=index.mjs.map
