// 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/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/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/install/upskillsCommand.ts
var upskillsCommand = {
  builder: (yargs) => yargs.parserConfiguration({ "unknown-options-as-args": true }).positional("skills", {
    array: true,
    describe: "Specific skills to update (omit to update all project skills)",
    type: "string"
  }).option("global", {
    alias: "g",
    describe: "Update global skills instead of project skills",
    type: "boolean"
  }).option("project", {
    describe: "Update project skills (default; raw -p is also forwarded to Skills.sh)",
    type: "boolean"
  }).option("yes", {
    alias: "y",
    describe: "Skip confirmation prompts",
    type: "boolean"
  }).strict(false),
  command: "upskills [skills..]",
  describe: "Update installed Skills.sh skills (defaults to project scope)",
  handler: async () => {
    await withEnvelope("upskills", () => skillsUpdo(argvAfterCommand("upskills")));
  }
};
export {
  upskillsCommand
};
//# sourceMappingURL=upskillsCommand.mjs.map
