// src/commands/installer.ts
import os2 from "node:os";
import path9 from "node:path";
import * as nodeFs from "node:fs/promises";
import { readFile as readFile2 } from "node:fs/promises";

// ../toolcraft/src/index.ts
import { fileURLToPath as fileURLToPath2 } from "node:url";

// ../toolcraft/src/user-error.ts
var UserError = class extends Error {
  constructor(message2, options) {
    super(message2, options);
    this.name = "UserError";
  }
};

// ../toolcraft/src/package-metadata.ts
import { existsSync, readFileSync, statSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

// ../agent-skill-config/src/configs.ts
import os from "node:os";
import path2 from "node:path";

// ../agent-defs/src/agents/claude-code.ts
var claudeCodeAgent = {
  id: "claude-code",
  name: "claude-code",
  label: "Claude Code",
  summary: "Configure Claude Code to route through Poe.",
  aliases: ["claude"],
  binaryName: "claude",
  apiShapes: ["anthropic-messages"],
  otelCapture: {
    env: {
      CLAUDE_CODE_ENABLE_TELEMETRY: "1"
    }
  },
  configPath: "~/.claude.json",
  branding: {
    colors: {
      dark: "#C15F3C",
      light: "#C15F3C"
    }
  }
};

// ../agent-defs/src/agents/claude-desktop.ts
var claudeDesktopAgent = {
  id: "claude-desktop",
  name: "claude-desktop",
  label: "Claude Desktop",
  summary: "Anthropic's official desktop application for Claude",
  configPath: "~/.config/Claude/claude_desktop_config.json",
  configPaths: {
    darwin: "~/Library/Application Support/Claude/claude_desktop_config.json",
    linux: "~/.config/Claude/claude_desktop_config.json",
    win32: "~/AppData/Roaming/Claude/claude_desktop_config.json"
  },
  branding: {
    colors: {
      dark: "#D97757",
      light: "#D97757"
    }
  }
};

// ../agent-defs/src/agents/codex.ts
var codexAgent = {
  id: "codex",
  name: "codex",
  label: "Codex",
  summary: "Configure Codex to use Poe as the model provider.",
  binaryName: "codex",
  apiShapes: ["openai-responses"],
  otelCapture: {
    args: (endpoint, content) => [
      "-c",
      `otel.trace_exporter={"otlp-http"={endpoint=${JSON.stringify(`${endpoint}/v1/traces`)},protocol="json"}}`,
      "-c",
      `otel.exporter={"otlp-http"={endpoint=${JSON.stringify(`${endpoint}/v1/logs`)},protocol="json"}}`,
      "-c",
      `otel.log_user_prompt=${content}`
    ]
  },
  configPath: "~/.codex/config.toml",
  branding: {
    colors: {
      dark: "#D5D9DF",
      light: "#7A7F86"
    }
  }
};

// ../agent-defs/src/agents/cursor.ts
var cursorAgent = {
  id: "cursor",
  name: "cursor",
  aliases: ["cursor-agent"],
  label: "Cursor",
  summary: "Cursor's CLI coding agent.",
  binaryName: "cursor-agent",
  configPath: "~/.cursor/mcp.json",
  branding: {
    colors: {
      dark: "#FFFFFF",
      light: "#000000"
    }
  }
};

// ../agent-defs/src/agents/gemini-cli.ts
var geminiCliAgent = {
  id: "gemini-cli",
  name: "gemini-cli",
  aliases: ["gemini"],
  label: "Gemini CLI",
  summary: "Configure Google's Gemini CLI to use a compatible Google generations API.",
  binaryName: "gemini",
  configPath: "~/.gemini/settings.json",
  apiShapes: ["google-generations"],
  branding: {
    colors: {
      dark: "#8AB4F8",
      light: "#1A73E8"
    }
  }
};

// ../agent-defs/src/agents/opencode.ts
var openCodeAgent = {
  id: "opencode",
  name: "opencode",
  label: "OpenCode CLI",
  summary: "Configure OpenCode CLI to use the Poe API.",
  binaryName: "opencode",
  apiShapes: ["openai-chat-completions"],
  otelCapture: {
    env: {
      OPENCODE_CONFIG_CONTENT: '{"experimental":{"openTelemetry":true}}'
    }
  },
  configPath: "~/.config/opencode/opencode.json",
  branding: {
    colors: {
      dark: "#4A4F55",
      light: "#2F3338"
    }
  }
};

// ../agent-defs/src/agents/kimi.ts
var kimiAgent = {
  id: "kimi",
  name: "kimi",
  label: "Kimi",
  summary: "Configure Kimi CLI to use Poe API",
  aliases: ["kimi-cli"],
  binaryName: "kimi",
  apiShapes: ["openai-chat-completions"],
  configPath: "~/.kimi/mcp.json",
  branding: {
    colors: {
      dark: "#7B68EE",
      light: "#6A5ACD"
    }
  }
};

// ../agent-defs/src/agents/goose.ts
var gooseAgent = {
  id: "goose",
  name: "goose",
  label: "Goose",
  summary: "Block's open-source AI agent with ACP support.",
  binaryName: "goose",
  apiShapes: ["openai-chat-completions"],
  otelCapture: {},
  configPath: "~/.config/goose/config.yaml",
  branding: {
    colors: {
      dark: "#FF6B35",
      light: "#E85D26"
    }
  }
};

// ../agent-defs/src/agents/poe-agent.ts
var poeAgentAgent = {
  id: "poe-agent",
  name: "poe-agent",
  label: "Poe Agent",
  summary: "Run one-shot prompts with the built-in Poe agent runtime.",
  apiShapes: ["openai-responses", "openai-chat-completions"],
  configPath: "~/.poe-code/config.json",
  branding: {
    colors: {
      dark: "#A465F7",
      light: "#7A3FD3"
    }
  }
};

// ../agent-defs/src/registry.ts
function freezeAgent(agent) {
  if (agent.aliases !== void 0) {
    Object.freeze(agent.aliases);
  }
  if (agent.apiShapes !== void 0) {
    Object.freeze(agent.apiShapes);
  }
  if (agent.otelCapture?.env !== void 0) {
    Object.freeze(agent.otelCapture.env);
  }
  if (agent.otelCapture !== void 0) {
    Object.freeze(agent.otelCapture);
  }
  Object.freeze(agent.branding.colors);
  Object.freeze(agent.branding);
  return Object.freeze(agent);
}
var allAgents = Object.freeze([
  freezeAgent(claudeCodeAgent),
  freezeAgent(claudeDesktopAgent),
  freezeAgent(codexAgent),
  freezeAgent(cursorAgent),
  freezeAgent(geminiCliAgent),
  freezeAgent(openCodeAgent),
  freezeAgent(kimiAgent),
  freezeAgent(gooseAgent),
  freezeAgent(poeAgentAgent)
]);
var lookup = /* @__PURE__ */ new Map();
for (const agent of allAgents) {
  const values = [agent.id, agent.name, ...agent.aliases ?? []];
  for (const value of values) {
    const normalized = value.toLowerCase();
    if (!lookup.has(normalized)) {
      lookup.set(normalized, agent.id);
    }
  }
}
function resolveAgentId(input) {
  if (!input) {
    return void 0;
  }
  return lookup.get(input.trim().toLowerCase());
}

// ../agent-skill-config/src/configs.ts
var agentSkillConfigs = {
  "claude-code": {
    globalSkillDir: "~/.claude/skills",
    localSkillDir: ".claude/skills"
  },
  codex: {
    globalSkillDir: "~/.codex/skills",
    localSkillDir: ".codex/skills"
  },
  cursor: {
    globalSkillDir: "~/.cursor/skills-cursor",
    localSkillDir: ".cursor/skills"
  },
  "gemini-cli": {
    globalSkillDir: "~/.gemini/skills",
    localSkillDir: ".gemini/skills"
  },
  opencode: {
    globalSkillDir: "~/.config/opencode/skills",
    localSkillDir: ".opencode/skills"
  },
  goose: {
    globalSkillDir: "~/.agents/skills",
    localSkillDir: ".agents/skills"
  }
};
var supportedAgents = Object.freeze(Object.keys(agentSkillConfigs));
function resolveAgentSupport(input, registry = agentSkillConfigs) {
  const resolvedId = resolveAgentId(input);
  if (!resolvedId) {
    return { status: "unknown", input };
  }
  const config2 = registry[resolvedId];
  if (!config2) {
    return { status: "unsupported", input, id: resolvedId };
  }
  return { status: "supported", input, id: resolvedId, config: { ...config2 } };
}
function getAgentConfig(agentId) {
  const support = resolveAgentSupport(agentId);
  return support.status === "supported" ? support.config : void 0;
}

// ../config-mutations/src/execution/apply-mutation.ts
import { randomUUID } from "node:crypto";
import path4 from "node:path";

// ../toolcraft-design/src/internal/color-support.ts
function supportsColor(env = process.env, stream = process.stdout) {
  if (env.FORCE_COLOR !== void 0 && env.FORCE_COLOR !== "0") {
    return true;
  }
  if (env.NO_COLOR !== void 0) {
    return false;
  }
  if (stream.isTTY !== true) {
    return false;
  }
  return typeof env.TERM === "string" && env.TERM.length > 0 && env.TERM !== "dumb";
}

// ../toolcraft-design/src/components/color.ts
var reset = "\x1B[0m";
var ansiStyles = {
  reset: { open: reset },
  bold: { open: "\x1B[1m" },
  dim: { open: "\x1B[2m" },
  italic: { open: "\x1B[3m" },
  underline: { open: "\x1B[4m" },
  inverse: { open: "\x1B[7m" },
  strikethrough: { open: "\x1B[9m" },
  black: { open: "\x1B[30m" },
  red: { open: "\x1B[31m" },
  green: { open: "\x1B[32m" },
  yellow: { open: "\x1B[33m" },
  blue: { open: "\x1B[34m" },
  magenta: { open: "\x1B[35m" },
  cyan: { open: "\x1B[36m" },
  white: { open: "\x1B[37m" },
  gray: { open: "\x1B[90m" },
  magentaBright: { open: "\x1B[95m" },
  cyanBright: { open: "\x1B[96m" },
  bgRed: { open: "\x1B[41m" },
  bgGreen: { open: "\x1B[42m" },
  bgYellow: { open: "\x1B[43m" },
  bgBlue: { open: "\x1B[44m" },
  bgMagenta: { open: "\x1B[45m" }
};
var styleNames = Object.keys(ansiStyles);
function replaceAll(value, search, replacement) {
  return value.split(search).join(replacement);
}
function applyStyles(text3, styles) {
  if (!supportsColor() || styles.length === 0) {
    return text3;
  }
  const open = styles.map((style) => style.open).join("");
  const output = text3.includes(reset) ? replaceAll(text3, reset, `${reset}${open}`) : text3;
  return `${open}${output}${reset}`;
}
function clampRgb(value) {
  if (Number.isNaN(value)) {
    return 0;
  }
  return Math.min(255, Math.max(0, Math.round(value)));
}
function hexChannel(value, offset) {
  return Number.parseInt(value.slice(offset, offset + 2), 16);
}
function normalizeHex(value) {
  const normalized = value.startsWith("#") ? value.slice(1) : value;
  if (normalized.length !== 3 && normalized.length !== 6 || Array.from(normalized).some((char) => !"0123456789abcdefABCDEF".includes(char))) {
    throw new Error(`Invalid hexadecimal color: ${value}`);
  }
  if (normalized.length === 3) {
    const red = normalized[0];
    const green = normalized[1];
    const blue = normalized[2];
    return [
      Number.parseInt(`${red}${red}`, 16),
      Number.parseInt(`${green}${green}`, 16),
      Number.parseInt(`${blue}${blue}`, 16)
    ];
  }
  return [
    hexChannel(normalized, 0),
    hexChannel(normalized, 2),
    hexChannel(normalized, 4)
  ];
}
function rgbStyle(red, green, blue) {
  return {
    open: `\x1B[38;2;${clampRgb(red)};${clampRgb(green)};${clampRgb(blue)}m`
  };
}
function bgRgbStyle(red, green, blue) {
  return {
    open: `\x1B[48;2;${clampRgb(red)};${clampRgb(green)};${clampRgb(blue)}m`
  };
}
function createColor(styles = []) {
  const builder = ((text3) => applyStyles(String(text3), styles));
  for (const name of styleNames) {
    Object.defineProperty(builder, name, {
      configurable: true,
      enumerable: true,
      get: () => createColor([...styles, ansiStyles[name]])
    });
  }
  builder.hex = (value) => {
    const [red, green, blue] = normalizeHex(value);
    return createColor([...styles, rgbStyle(red, green, blue)]);
  };
  builder.rgb = (red, green, blue) => createColor([...styles, rgbStyle(red, green, blue)]);
  builder.bgHex = (value) => {
    const [red, green, blue] = normalizeHex(value);
    return createColor([...styles, bgRgbStyle(red, green, blue)]);
  };
  builder.bgRgb = (red, green, blue) => createColor([...styles, bgRgbStyle(red, green, blue)]);
  return builder;
}
var color = createColor();

// ../toolcraft-design/src/tokens/brand.ts
var brands = {
  purple: { name: "purple", primary: "#a200ff" },
  blue: { name: "blue", primary: "#2f6fed" },
  green: { name: "green", primary: "#1f9d57" }
};

// ../toolcraft-design/src/internal/theme-state.ts
var defaults = {
  brand: "purple",
  label: "Poe"
};
var config = { ...defaults };
var revision = 0;
var brandConfigured = false;
function getThemeConfig() {
  return { ...config };
}
function getThemeRevision() {
  return revision;
}
function isThemeBrandConfigured() {
  return brandConfigured;
}

// ../toolcraft-design/src/tokens/colors.ts
var brand = brands.purple.primary;
function withStyles(palette, styles) {
  return Object.defineProperty(palette, "styles", {
    value: styles,
    enumerable: false
  });
}
function brandColor(activeBrand, purple) {
  return activeBrand.name === "purple" ? purple : color.hex(activeBrand.primary);
}
function brandBackground(activeBrand, purple) {
  return activeBrand.name === "purple" ? purple : color.bgHex(activeBrand.primary);
}
function createPalette(activeBrand, mode) {
  const isPurple = activeBrand.name === "purple";
  if (mode === "light") {
    const active2 = color.hex(activeBrand.primary);
    const prompt2 = isPurple ? color.hex("#006699") : active2;
    const number2 = isPurple ? color.hex("#0077cc") : active2;
    return withStyles(
      {
        header: (text3) => active2.bold(text3),
        divider: (text3) => color.hex("#666666")(text3),
        prompt: (text3) => prompt2.bold(text3),
        number: (text3) => number2.bold(text3),
        intro: (text3) => color.bgHex(activeBrand.primary).white(` ${getThemeConfig().label} - ${text3} `),
        get resolvedSymbol() {
          return active2("\u25C7");
        },
        get errorSymbol() {
          return color.hex("#cc0000")("\u25A0");
        },
        accent: (text3) => prompt2.bold(text3),
        muted: (text3) => color.hex("#666666")(text3),
        success: (text3) => color.hex("#008800")(text3),
        warning: (text3) => color.hex("#cc6600")(text3),
        error: (text3) => color.hex("#cc0000")(text3),
        info: (text3) => active2(text3),
        badge: (text3) => color.bgHex("#cc6600").white(` ${text3} `)
      },
      {
        accent: { fg: isPurple ? "#006699" : activeBrand.primary, bold: true },
        muted: { fg: "#666666" },
        success: { fg: "#008800" },
        warning: { fg: "#cc6600" },
        error: { fg: "#cc0000" },
        info: { fg: activeBrand.primary }
      }
    );
  }
  const active = brandColor(activeBrand, color.magenta);
  const activeBright = brandColor(activeBrand, color.magentaBright);
  const activeBackground = brandBackground(activeBrand, color.bgMagenta);
  const prompt = isPurple ? color.cyan : active;
  const number = isPurple ? color.cyanBright : active;
  return withStyles(
    {
      header: (text3) => activeBright.bold(text3),
      divider: (text3) => color.dim(text3),
      prompt: (text3) => prompt(text3),
      number: (text3) => number(text3),
      intro: (text3) => activeBackground.white(` ${getThemeConfig().label} - ${text3} `),
      get resolvedSymbol() {
        return active("\u25C7");
      },
      get errorSymbol() {
        return color.red("\u25A0");
      },
      accent: (text3) => prompt(text3),
      muted: (text3) => color.dim(text3),
      success: (text3) => color.green(text3),
      warning: (text3) => color.yellow(text3),
      error: (text3) => color.red(text3),
      info: (text3) => active(text3),
      badge: (text3) => color.bgYellow.black(` ${text3} `)
    },
    {
      accent: { fg: isPurple ? "cyan" : activeBrand.primary, bold: true },
      muted: { dim: true },
      success: { fg: "green" },
      warning: { fg: "yellow" },
      error: { fg: "red" },
      info: { fg: isPurple ? "magenta" : activeBrand.primary }
    }
  );
}
var dark = createPalette(brands.purple, "dark");
var light = createPalette(brands.purple, "light");

// ../toolcraft-design/src/internal/output-format.ts
import { AsyncLocalStorage } from "node:async_hooks";
var VALID_FORMATS = /* @__PURE__ */ new Set(["terminal", "markdown", "json"]);
var formatStorage = new AsyncLocalStorage();
var cached;
function resolveOutputFormat(env = process.env) {
  const scoped = formatStorage.getStore();
  if (scoped) {
    return scoped;
  }
  if (cached) {
    return cached;
  }
  const raw = env.OUTPUT_FORMAT?.toLowerCase();
  cached = VALID_FORMATS.has(raw) ? raw : "terminal";
  return cached;
}

// ../toolcraft-design/src/internal/theme-detect.ts
function detectThemeFromEnv(env) {
  const apple = env.APPLE_INTERFACE_STYLE;
  if (typeof apple === "string") {
    return apple.toLowerCase() === "dark" ? "dark" : "light";
  }
  const vscodeKind = env.VSCODE_COLOR_THEME_KIND;
  if (typeof vscodeKind === "string") {
    const normalized = vscodeKind.toLowerCase();
    if (normalized.includes("light")) {
      return "light";
    }
    if (normalized.includes("dark")) {
      return "dark";
    }
  }
  const colorFGBG = env.COLORFGBG;
  if (typeof colorFGBG === "string") {
    const parts = colorFGBG.split(";").map((part) => Number.parseInt(part, 10));
    const background = parts.at(-1);
    if (Number.isFinite(background)) {
      return background >= 8 ? "light" : "dark";
    }
  }
  return void 0;
}
function resolveThemeName(env = process.env) {
  const raw = (env.POE_CODE_THEME ?? env.POE_THEME)?.toLowerCase();
  if (raw === "light" || raw === "dark") {
    return raw;
  }
  const detected = detectThemeFromEnv(env);
  if (detected) {
    return detected;
  }
  return "dark";
}
var themeCache = /* @__PURE__ */ new Map();
var cachedRevision = -1;
function getTheme(env) {
  const themeName = resolveThemeName(env);
  const config2 = getThemeConfig();
  const requestedBrand = env?.POE_BRAND?.toLowerCase();
  const activeBrandName = !isThemeBrandConfigured() && requestedBrand && Object.hasOwn(brands, requestedBrand) ? requestedBrand : config2.brand;
  const revision2 = getThemeRevision();
  if (revision2 !== cachedRevision) {
    themeCache.clear();
    cachedRevision = revision2;
  }
  const cacheKey = `${activeBrandName}:${themeName}`;
  const cachedTheme = themeCache.get(cacheKey);
  if (cachedTheme) {
    return cachedTheme;
  }
  const activeBrand = brands[activeBrandName];
  const theme = activeBrandName === "purple" ? themeName === "light" ? light : dark : createPalette(activeBrand, themeName);
  themeCache.set(cacheKey, theme);
  return theme;
}

// ../toolcraft-design/src/components/symbols.ts
var symbols = {
  get info() {
    const format = resolveOutputFormat();
    if (format === "json") return "info";
    if (format === "markdown") return "(i)";
    return color.magenta("\u25CF");
  },
  get success() {
    const format = resolveOutputFormat();
    if (format === "json") return "success";
    if (format === "markdown") return "[ok]";
    return color.magenta("\u25C6");
  },
  get resolved() {
    const format = resolveOutputFormat();
    if (format === "json") return "resolved";
    if (format === "markdown") return ">";
    return getTheme().resolvedSymbol;
  },
  get errorResolved() {
    const format = resolveOutputFormat();
    if (format === "json") return "error";
    if (format === "markdown") return "[!]";
    return getTheme().errorSymbol;
  },
  get bar() {
    const format = resolveOutputFormat();
    if (format === "json") return "";
    if (format === "markdown") return "|";
    return "\u2502";
  },
  cornerTopRight: "\u256E",
  cornerBottomRight: "\u256F",
  get warning() {
    const format = resolveOutputFormat();
    if (format === "json") return "warning";
    if (format === "markdown") return "[!]";
    return "\u25B2";
  },
  get active() {
    const format = resolveOutputFormat();
    if (format === "json") return "active";
    if (format === "markdown") return "[x]";
    return "\u25C6";
  },
  get inactive() {
    const format = resolveOutputFormat();
    if (format === "json") return "inactive";
    if (format === "markdown") return "[ ]";
    return "\u25CB";
  }
};

// ../toolcraft-design/src/internal/strip-ansi.ts
function stripAnsi(value) {
  let output = "";
  let index = 0;
  while (index < value.length) {
    const char = value[index];
    if (char === "\x1B") {
      index = skipEscapeSequence(value, index);
      continue;
    }
    if (char === "\x9B") {
      index = skipCsiSequence(value, index + 1);
      continue;
    }
    output += char;
    index += char.length;
  }
  return output;
}
function skipEscapeSequence(value, index) {
  const next = value[index + 1];
  if (next === "[") {
    return skipCsiSequence(value, index + 2);
  }
  if (next === "]") {
    return skipOscSequence(value, index + 2);
  }
  return Math.min(value.length, index + 2);
}
function skipCsiSequence(value, index) {
  while (index < value.length) {
    const codePoint = value.charCodeAt(index);
    index += 1;
    if (codePoint >= 64 && codePoint <= 126) {
      break;
    }
  }
  return index;
}
function skipOscSequence(value, index) {
  while (index < value.length) {
    if (value[index] === "\x07") {
      return index + 1;
    }
    if (value[index] === "\x1B" && value[index + 1] === "\\") {
      return index + 2;
    }
    index += 1;
  }
  return index;
}

// ../toolcraft-design/src/prompts/primitives/log.ts
function renderMarkdownInline(value) {
  return stripAnsi(value).replaceAll("\r\n", " ").replaceAll("\n", " ").replaceAll("\r", " ");
}
function writeTerminalMessage(msg, {
  symbol: symbol2 = color.gray("\u2502"),
  secondarySymbol = color.gray("\u2502"),
  spacing: spacing2 = 1,
  withGuide = true
} = {}) {
  const lines = [];
  const showGuide = withGuide !== false;
  const contentLines = msg.split("\n");
  const prefix = showGuide ? `${symbol2}  ` : "";
  const continuationPrefix = showGuide ? `${secondarySymbol}  ` : "";
  const emptyGuide = showGuide ? secondarySymbol : "";
  for (let index = 0; index < spacing2; index += 1) {
    lines.push(emptyGuide);
  }
  if (contentLines.length === 0) {
    process.stdout.write("\n");
    return;
  }
  const [firstLine = "", ...continuationLines] = contentLines;
  if (firstLine.length > 0) {
    lines.push(`${prefix}${firstLine}`);
  } else {
    lines.push(showGuide ? symbol2 : "");
  }
  for (const line of continuationLines) {
    if (line.length > 0) {
      lines.push(`${continuationPrefix}${line}`);
      continue;
    }
    lines.push(emptyGuide);
  }
  process.stdout.write(`${lines.join("\n")}
`);
}
function message(msg, options) {
  const format = resolveOutputFormat();
  if (format === "markdown") {
    process.stdout.write(`- ${renderMarkdownInline(msg)}
`);
    return;
  }
  if (format === "json") {
    process.stdout.write(
      `${JSON.stringify({ level: "message", message: stripAnsi(msg) })}
`
    );
    return;
  }
  writeTerminalMessage(msg, options);
}
function info(msg) {
  const format = resolveOutputFormat();
  if (format === "markdown") {
    process.stdout.write(`- **info:** ${renderMarkdownInline(msg)}
`);
    return;
  }
  if (format === "json") {
    process.stdout.write(
      `${JSON.stringify({ level: "info", message: stripAnsi(msg) })}
`
    );
    return;
  }
  message(msg, { symbol: symbols.info });
}
function success(msg) {
  const format = resolveOutputFormat();
  if (format === "markdown") {
    process.stdout.write(`- **success:** ${renderMarkdownInline(msg)}
`);
    return;
  }
  if (format === "json") {
    process.stdout.write(
      `${JSON.stringify({ level: "success", message: stripAnsi(msg) })}
`
    );
    return;
  }
  message(msg, { symbol: symbols.success });
}
function warn(msg) {
  const format = resolveOutputFormat();
  if (format === "markdown") {
    process.stdout.write(`- **warning:** ${renderMarkdownInline(msg)}
`);
    return;
  }
  if (format === "json") {
    process.stdout.write(
      `${JSON.stringify({ level: "warn", message: stripAnsi(msg) })}
`
    );
    return;
  }
  message(msg, { symbol: color.yellow("\u25B2") });
}
function error(msg) {
  const format = resolveOutputFormat();
  if (format === "markdown") {
    process.stdout.write(`- **error:** ${renderMarkdownInline(msg)}
`);
    return;
  }
  if (format === "json") {
    process.stdout.write(
      `${JSON.stringify({ level: "error", message: stripAnsi(msg) })}
`
    );
    return;
  }
  message(msg, { symbol: color.red("\u25A0") });
}
var log = {
  info,
  success,
  message,
  warn,
  error
};

// ../toolcraft-design/src/components/logger.ts
function createLogger(emitter) {
  const emit = (level, message2) => {
    if (emitter) {
      emitter(message2);
      return;
    }
    if (level === "success") {
      log.success(message2);
      return;
    }
    if (level === "warn") {
      log.warn(message2);
      return;
    }
    if (level === "error") {
      log.error(message2);
      return;
    }
    log.info(message2);
  };
  return {
    info(message2) {
      emit("info", message2);
    },
    success(message2) {
      emit("success", message2);
    },
    warn(message2) {
      emit("warn", message2);
    },
    error(message2) {
      emit("error", message2);
    },
    resolved(label, value) {
      if (emitter) {
        emitter(`${label}: ${value}`);
        return;
      }
      log.message(`${label}
   ${value}`, { symbol: symbols.resolved });
    },
    errorResolved(label, value) {
      if (emitter) {
        emitter(`${label}: ${value}`);
        return;
      }
      log.message(`${label}
   ${value}`, { symbol: symbols.errorResolved });
    },
    message(message2, symbol2) {
      if (emitter) {
        emitter(message2);
        return;
      }
      log.message(message2, { symbol: symbol2 ?? color.gray("\u2502") });
    }
  };
}
var logger = createLogger();

// ../toolcraft-design/src/components/help-formatter.ts
var graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });

// ../toolcraft-design/src/components/table.ts
var graphemeSegmenter2 = new Intl.Segmenter(void 0, { granularity: "grapheme" });

// ../toolcraft-design/src/components/detail-card.ts
import stringWidth from "fast-string-width";
import { wrapAnsi } from "fast-wrap-ansi";

// ../toolcraft-design/src/components/browser.ts
import { spawn } from "node:child_process";
import process2 from "node:process";

// ../frontmatter/src/parse.ts
import { LineCounter, parse, parseDocument } from "yaml";

// ../frontmatter/src/stringify.ts
import { stringify } from "yaml";

// ../toolcraft-design/src/dashboard/terminal-width.ts
var graphemeSegmenter3 = new Intl.Segmenter(void 0, { granularity: "grapheme" });

// ../toolcraft-design/src/acp/writer.ts
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
var storage = new AsyncLocalStorage2();

// ../toolcraft-design/src/dashboard/terminal.ts
import readline from "node:readline";
import { PassThrough } from "node:stream";

// ../toolcraft-design/src/explorer/state.ts
var REGION_HEADER = 1 << 0;
var REGION_LIST = 1 << 1;
var REGION_DETAIL = 1 << 2;
var REGION_FOOTER = 1 << 3;
var REGION_MODAL = 1 << 4;
var REGION_TOAST = 1 << 5;
var REGION_ALL = REGION_HEADER | REGION_LIST | REGION_DETAIL | REGION_FOOTER | REGION_MODAL | REGION_TOAST;

// ../toolcraft-design/src/prompts/interactive/glyphs.ts
function supportsUnicode() {
  if (!process.platform.startsWith("win")) {
    return process.env.TERM !== "linux";
  }
  return Boolean(
    process.env.CI || process.env.WT_SESSION || process.env.TERMINUS_SUBLIME || process.env.ConEmuTask === "{cmd::Cmder}" || process.env.TERM_PROGRAM === "Terminus-Sublime" || process.env.TERM_PROGRAM === "vscode" || process.env.TERM === "xterm-256color" || process.env.TERM === "alacritty" || process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm"
  );
}
var UNICODE = supportsUnicode();
function glyph(unicode, ascii) {
  return UNICODE ? unicode : ascii;
}
var GLYPHS = {
  stepActive: glyph("\u25C6", "*"),
  stepCancel: glyph("\u25A0", "x"),
  stepError: glyph("\u25B2", "x"),
  stepSubmit: glyph("\u25C7", "o"),
  barStart: glyph("\u250C", "T"),
  bar: glyph("\u2502", "|"),
  barEnd: glyph("\u2514", "-"),
  radioActive: glyph("\u25CF", ">"),
  radioInactive: glyph("\u25CB", " "),
  checkboxActive: glyph("\u25FB", "[ ]"),
  checkboxSelected: glyph("\u25FC", "[+]"),
  checkboxInactive: glyph("\u25FB", "[ ]"),
  passwordMask: glyph("\u2022", "*"),
  ellipsis: "..."
};

// ../toolcraft-design/src/prompts/interactive/core.ts
import { EventEmitter } from "node:events";
import * as readline2 from "node:readline";

// ../toolcraft-design/src/prompts/interactive/wrap.ts
import { wrapAnsi as wrapAnsi2 } from "fast-wrap-ansi";
import stringWidth2 from "fast-string-width";

// ../toolcraft-design/src/prompts/interactive/pagination.ts
import { wrapAnsi as wrapAnsi3 } from "fast-wrap-ansi";

// ../toolcraft-design/src/static/spinner.ts
var SPINNER_FRAMES = Object.freeze(["\u25D2", "\u25D0", "\u25D3", "\u25D1"]);

// ../config-mutations/src/formats/json.ts
import * as jsonc from "jsonc-parser";

// ../config-mutations/src/formats/toml.ts
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";

// ../config-mutations/src/formats/yaml.ts
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";

// ../config-mutations/src/execution/path-utils.ts
import path3 from "node:path";

// ../agent-skill-config/src/templates.ts
import { readFile, stat } from "node:fs/promises";
import path5 from "node:path";
import { fileURLToPath as fileURLToPath3 } from "node:url";

// ../agent-skill-config/src/resolve-skill-reference.ts
import * as fs from "node:fs";
import path6 from "node:path";

// ../agent-skill-config/src/git-exclude.ts
import { execFileSync } from "node:child_process";
import { randomUUID as randomUUID2 } from "node:crypto";
import * as fs2 from "node:fs";
import path7 from "node:path";

// ../agent-skill-config/src/bridge-active-skills.ts
import * as fs3 from "node:fs";
import { createHash, randomUUID as randomUUID3 } from "node:crypto";
import path8 from "node:path";

// src/errors.ts
function hasOwnErrorCode3(error2, code) {
  return error2 instanceof Error && Object.prototype.hasOwnProperty.call(error2, "code") && error2.code === code;
}

// src/commands/installer.ts
var DEFAULT_INSTALL_AGENT = "claude-code";
var DEFAULT_INSTALL_SCOPE = "local";
var TERMINAL_PILOT_SKILL_NAME = "terminal-pilot";
var installableAgents = supportedAgents;
function isNotFoundError(error2) {
  return hasOwnErrorCode3(error2, "ENOENT");
}
function resolveInstallerServices(installer) {
  return {
    fs: installer?.fs ?? nodeFs,
    cwd: installer?.cwd ?? process.cwd(),
    homeDir: installer?.homeDir ?? os2.homedir(),
    platform: installer?.platform ?? process.platform
  };
}
function throwUnsupportedAgent(agent) {
  throw new UserError(`Unsupported agent: ${agent}`);
}
function resolveInstallableAgent(agent) {
  const skillSupport = resolveAgentSupport(agent);
  if (skillSupport.status !== "supported" || !skillSupport.id) {
    throwUnsupportedAgent(agent);
  }
  return skillSupport.id;
}
function resolveInstallScope(input) {
  if (input.local && input.global) {
    throw new UserError("Use either --local or --global, not both.");
  }
  if (input.local) {
    return "local";
  }
  if (input.global) {
    return "global";
  }
  return DEFAULT_INSTALL_SCOPE;
}
var terminalPilotTemplateCache;
async function loadTerminalPilotTemplate() {
  if (terminalPilotTemplateCache !== void 0) {
    return terminalPilotTemplateCache;
  }
  const candidates = [
    new URL("./templates/terminal-pilot.md", import.meta.url),
    new URL("../templates/terminal-pilot.md", import.meta.url),
    new URL("../../../agent-skill-config/src/templates/terminal-pilot.md", import.meta.url)
  ];
  for (const candidate of candidates) {
    try {
      terminalPilotTemplateCache = await readFile2(candidate, "utf8");
      return terminalPilotTemplateCache;
    } catch (error2) {
      if (!isNotFoundError(error2)) {
        throw error2;
      }
    }
  }
  throw new UserError("terminal-pilot skill template is missing.");
}
function resolveHomeRelativePath(targetPath, homeDir) {
  if (targetPath === "~") {
    return homeDir;
  }
  if (targetPath.startsWith("~/")) {
    return path9.join(homeDir, targetPath.slice(2));
  }
  return targetPath;
}
function getSkillFolderWithHome(agent, scope, cwd, homeDir) {
  const config2 = getAgentConfig(agent);
  if (!config2) {
    throwUnsupportedAgent(agent);
  }
  return {
    displayPath: path9.join(
      scope === "global" ? config2.globalSkillDir : config2.localSkillDir,
      TERMINAL_PILOT_SKILL_NAME
    ),
    fullPath: path9.join(
      scope === "global" ? resolveHomeRelativePath(config2.globalSkillDir, homeDir) : path9.resolve(cwd, config2.localSkillDir),
      TERMINAL_PILOT_SKILL_NAME
    )
  };
}
async function removeSkillFolder(fs4, folderPath) {
  await assertNoSymbolicLinkPath(fs4, folderPath);
  try {
    await fs4.stat(folderPath);
  } catch (error2) {
    if (isNotFoundError(error2)) {
      return false;
    }
    throw error2;
  }
  if (typeof fs4.rm !== "function") {
    throw new UserError("The configured filesystem does not support removing directories.");
  }
  await fs4.rm(folderPath, { recursive: true, force: true });
  return true;
}
async function assertNoSymbolicLinkPath(fs4, targetPath) {
  const rootPath = path9.parse(targetPath).root;
  let currentPath = targetPath;
  while (currentPath !== rootPath) {
    try {
      if ((await fs4.lstat(currentPath)).isSymbolicLink()) {
        throw new UserError(`Refusing terminal-pilot skill operation through symbolic link: ${currentPath}`);
      }
    } catch (error2) {
      if (!isNotFoundError(error2)) {
        throw error2;
      }
    }
    currentPath = path9.dirname(currentPath);
  }
}
export {
  DEFAULT_INSTALL_AGENT,
  DEFAULT_INSTALL_SCOPE,
  TERMINAL_PILOT_SKILL_NAME,
  assertNoSymbolicLinkPath,
  getSkillFolderWithHome,
  installableAgents,
  loadTerminalPilotTemplate,
  removeSkillFolder,
  resolveInstallScope,
  resolveInstallableAgent,
  resolveInstallerServices
};
//# sourceMappingURL=installer.js.map
