// 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/lib/reporting/runWithEnvelope.ts
import { performance as performance2 } from "node:perf_hooks";

// src/lib/reporting/xyReporter.ts
import { performance } from "node:perf_hooks";
var jsonMode = false;
var originalStdoutWrite;
var envelopeEmitted = false;
var currentCommand = "unknown";
var startTime = 0;
function isJsonMode() {
  return jsonMode;
}
function setCurrentCommand(name) {
  currentCommand = name;
  startTime = performance.now();
  envelopeEmitted = false;
}
function emitJson(envelope) {
  if (envelopeEmitted) return;
  envelopeEmitted = true;
  const json = JSON.stringify(envelope) + "\n";
  if (originalStdoutWrite) {
    originalStdoutWrite(json);
  } else {
    process.stdout.write(json);
  }
}

// src/lib/reporting/runWithEnvelope.ts
async function runWithEnvelope(command, action) {
  setCurrentCommand(command);
  const start = performance2.now();
  let exitCode;
  let envelope;
  try {
    const ret = await action();
    if (typeof ret === "number") {
      exitCode = ret;
    } else {
      exitCode = ret.exitCode;
      envelope = ret.envelope;
    }
  } catch (ex) {
    exitCode = 1;
    const message = ex instanceof Error ? ex.message : String(ex);
    envelope = {
      errorCount: 1,
      errors: [{ message }]
    };
    if (!isJsonMode()) {
      console.error(message);
    }
  }
  if (isJsonMode()) {
    emitJson({
      command,
      data: envelope?.data,
      durationMs: Math.round(performance2.now() - start),
      errorCount: envelope?.errorCount ?? (exitCode === 0 ? 0 : 1),
      errors: envelope?.errors,
      exitCode,
      schemaVersion: 1,
      success: exitCode === 0,
      warningCount: envelope?.warningCount ?? 0,
      warnings: envelope?.warnings
    });
  }
  return exitCode;
}
async function withEnvelope(command, action) {
  process.exitCode = await runWithEnvelope(command, action);
}

// src/actions/skills/passthrough.ts
import chalk from "chalk";
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 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));
};

// src/xy/common/skills/index.ts
var CUSTOM_SKILLS_COMMANDS = /* @__PURE__ */ new Set(["defaults", "lint", "updo"]);
var HELP_FLAGS = /* @__PURE__ */ new Set(["--help", "-h"]);
var hasHelpFlag = (args) => args.some((arg) => HELP_FLAGS.has(arg));
var printDefaultsHelp = () => {
  console.log(`xy skills defaults

Install the XY/XYO/XL1 default skill stack from XYOracleNetwork/xyo-skills.

Usage:
  xy skills defaults [options]

Options:
  -g, --global          Install globally instead of project-locally
  -a, --agent <agent>   Install all default skills to specific agents
  --copy                Copy files instead of symlinking
  -h, --help            Show this help
`);
};
var printLintHelp = () => {
  console.log(`xy skills lint

Check for skills installed in both project and global scopes.

Usage:
  xy skills lint
`);
};
var printUpdoHelp = () => {
  console.log(`xy skills updo

Update installed Skills.sh skills. Defaults to project scope.

Usage:
  xy skills updo [skills..] [options]

Options:
  -g, --global          Update global skills instead of project skills
  -p, --project         Update project skills (default)
  -y, --yes             Skip confirmation prompts
  -h, --help            Show this help
`);
};
var runSkillsTail = (tail) => {
  const [subcommand, ...args] = tail;
  if (subcommand === "defaults" && hasHelpFlag(args)) {
    printDefaultsHelp();
    return 0;
  }
  if (subcommand === "lint" && hasHelpFlag(args)) {
    printLintHelp();
    return 0;
  }
  if (subcommand === "updo" && hasHelpFlag(args)) {
    printUpdoHelp();
    return 0;
  }
  if (subcommand === "defaults") return skillsDefaults(args);
  if (subcommand === "lint") return skillsLint();
  if (subcommand === "updo") return skillsUpdo(args);
  return runSkills(tail);
};
var skillsCommand = {
  builder: (yargs) => {
    return yargs.parserConfiguration({ "unknown-options-as-args": true }).positional("args", {
      array: true,
      describe: "Arguments forwarded to Skills.sh",
      type: "string"
    }).help(false).strict(false).version(false);
  },
  command: "skills [args..]",
  describe: "Manage agent skills via Skills.sh; forwards unknown commands and adds XY conveniences: defaults, lint, updo",
  handler: async () => {
    const tail = argvAfterCommand("skills");
    const commandName = CUSTOM_SKILLS_COMMANDS.has(tail[0] ?? "") ? `skills ${tail[0]}` : "skills";
    await withEnvelope(commandName, () => runSkillsTail(tail));
  }
};
export {
  skillsCommand
};
//# sourceMappingURL=index.mjs.map
