// src/commands/uninstall.ts
import { randomUUID as randomUUID4 } from "node:crypto";

// ../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/human-in-loop/config.ts
function validateHumanInLoopOnDefine(config2) {
  const label = Array.isArray(config2.children) ? "group" : "command";
  if (config2.confirm === true && config2.humanInLoop !== void 0 && config2.humanInLoop !== null) {
    throw new Error(`${label} '${config2.name}': use either confirm or humanInLoop, not both`);
  }
  if (config2.humanInLoop === void 0 || config2.humanInLoop === null) {
    return;
  }
  if (config2.humanInLoop.mode !== "sync" && config2.humanInLoop.mode !== "async") {
    throw new Error(`${label} '${config2.name}': humanInLoop.mode must be "sync" or "async"`);
  }
  if (typeof config2.humanInLoop.message !== "function") {
    throw new Error(`${label} '${config2.name}': humanInLoop.message must be a function`);
  }
}
function mergeHumanInLoopFromGroup(groupHumanInLoop, childHumanInLoop) {
  if (childHumanInLoop !== void 0) {
    return childHumanInLoop;
  }
  return groupHumanInLoop;
}

// ../toolcraft-schema/src/json.ts
function Json() {
  return {
    kind: "json"
  };
}

// ../toolcraft-schema/src/oneof.ts
function assertValidBranches(branches, discriminator) {
  if (Object.keys(branches).length === 0) {
    throw new Error("OneOf schema requires at least one branch");
  }
  for (const [branchName, branch] of Object.entries(branches)) {
    if (Object.prototype.hasOwnProperty.call(branch.shape, discriminator)) {
      throw new Error(
        `OneOf branch "${branchName}" must not declare discriminator field "${discriminator}".`
      );
    }
  }
}
function OneOf(config2) {
  assertValidBranches(config2.branches, config2.discriminator);
  return {
    kind: "oneOf",
    discriminator: config2.discriminator,
    branches: config2.branches
  };
}

// ../toolcraft-schema/src/record.ts
function Record(value) {
  return {
    kind: "record",
    value
  };
}

// ../toolcraft-schema/src/union.ts
function isOptionalSchema(schema) {
  return schema.kind === "optional";
}
function getRequiredKeys(schema) {
  return Object.keys(schema.shape).filter((key) => !isOptionalSchema(schema.shape[key])).sort();
}
function getRequiredKeyFingerprint(schema) {
  return getRequiredKeys(schema).join("+");
}
function assertUniqueRequiredKeyFingerprints(branches) {
  const fingerprints = /* @__PURE__ */ new Map();
  branches.forEach((branch, index) => {
    const requiredKeys = getRequiredKeys(branch);
    const fingerprint = JSON.stringify(requiredKeys);
    const existing = fingerprints.get(fingerprint);
    if (existing === void 0) {
      fingerprints.set(fingerprint, {
        display: requiredKeys.join("+"),
        indices: [index]
      });
      return;
    }
    existing.indices.push(index);
  });
  for (const { display, indices } of fingerprints.values()) {
    if (indices.length > 1) {
      throw new Error(
        `Union branches [${indices.join(", ")}] share required-key fingerprint "${display}". Each branch must require a distinct set of keys.`
      );
    }
  }
}
function assertValidBranches2(branches) {
  if (branches.length === 0) {
    throw new Error("Union schema requires at least one branch");
  }
  assertUniqueRequiredKeyFingerprints(branches);
}
function Union(branches) {
  assertValidBranches2(branches);
  return {
    kind: "union",
    branches
  };
}

// ../toolcraft-schema/src/validate.ts
var missingValue = /* @__PURE__ */ Symbol("missingValue");
function validate(schema, value) {
  const state = { issues: [] };
  const result = walkSchema(schema, value, [], state);
  if (state.issues.length > 0) {
    return { ok: false, issues: state.issues };
  }
  return { ok: true, value: result.present ? result.value : void 0 };
}
function walkSchema(schema, value, path10, state) {
  if (schema.kind === "optional") {
    return walkOptional(schema, value, path10, state);
  }
  if (value === missingValue) {
    addIssue(
      state,
      path10,
      expectedFor(schema),
      "missing",
      `Expected ${expectedFor(schema)} at ${formatPath(path10)}`
    );
    return { present: false };
  }
  if (value === null && schema.nullable === true) {
    return { present: true, value };
  }
  switch (schema.kind) {
    case "string":
      return walkString(schema, value, path10, state);
    case "number":
      return walkNumber(schema, value, path10, state);
    case "boolean":
      return walkBoolean(value, path10, state);
    case "enum":
      return walkEnum(schema, value, path10, state);
    case "array":
      return walkArray(schema, value, path10, state);
    case "object":
      return walkObject(schema, value, path10, state);
    case "oneOf":
      return walkOneOf(schema, value, path10, state);
    case "union":
      return walkUnion(schema, value, path10, state);
    case "record":
      return walkRecord(schema, value, path10, state);
    case "json":
      return walkJson(value, path10, state);
  }
}
function walkOptional(schema, value, path10, state) {
  if (value === missingValue || value === void 0) {
    const defaultValue = getDefault(schema.inner);
    if (defaultValue.present) {
      return walkSchema(schema.inner, cloneDefault(defaultValue.value), path10, state);
    }
    return { present: false };
  }
  return walkSchema(schema.inner, value, path10, state);
}
function walkString(schema, value, path10, state) {
  if (typeof value !== "string") {
    addExpectedIssue(state, path10, "string", value);
    return { present: true, value };
  }
  if (schema.minLength !== void 0 && value.length < schema.minLength) {
    const expected = `string with length at least ${schema.minLength}`;
    addIssue(
      state,
      path10,
      expected,
      `string with length ${value.length}`,
      `Expected ${expected} at ${formatPath(path10)}`
    );
  }
  if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
    const expected = `string with length at most ${schema.maxLength}`;
    addIssue(
      state,
      path10,
      expected,
      `string with length ${value.length}`,
      `Expected ${expected} at ${formatPath(path10)}`
    );
  }
  if (schema.pattern !== void 0) {
    const pattern = compilePattern(schema.pattern);
    if (pattern === void 0 || !pattern.test(value)) {
      const expected = `string matching pattern ${schema.pattern}`;
      addIssue(state, path10, expected, value, `Expected ${expected} at ${formatPath(path10)}`);
    }
  }
  return { present: true, value };
}
function walkNumber(schema, value, path10, state) {
  if (typeof value !== "number" || !Number.isFinite(value)) {
    addExpectedIssue(state, path10, schema.jsonType === "integer" ? "integer" : "number", value);
    return { present: true, value };
  }
  if (schema.jsonType === "integer" && !Number.isInteger(value)) {
    addExpectedIssue(state, path10, "integer", value);
  }
  if (schema.minimum !== void 0 && value < schema.minimum) {
    const expected = `number greater than or equal to ${schema.minimum}`;
    addIssue(state, path10, expected, String(value), `Expected ${expected} at ${formatPath(path10)}`);
  }
  if (schema.maximum !== void 0 && value > schema.maximum) {
    const expected = `number less than or equal to ${schema.maximum}`;
    addIssue(state, path10, expected, String(value), `Expected ${expected} at ${formatPath(path10)}`);
  }
  return { present: true, value };
}
function walkBoolean(value, path10, state) {
  if (typeof value !== "boolean") {
    addExpectedIssue(state, path10, "boolean", value);
  }
  return { present: true, value };
}
function walkEnum(schema, value, path10, state) {
  if (!schema.values.includes(value)) {
    const expected = `one of ${schema.values.join(", ")}`;
    addIssue(
      state,
      path10,
      expected,
      receivedValue(value),
      `Expected ${expected} at ${formatPath(path10)}`
    );
  }
  return { present: true, value };
}
function walkArray(schema, value, path10, state) {
  if (!Array.isArray(value)) {
    addExpectedIssue(state, path10, "array", value);
    return { present: true, value };
  }
  if (schema.minItems !== void 0 && value.length < schema.minItems) {
    const expected = `array with at least ${schema.minItems} items`;
    addIssue(
      state,
      path10,
      expected,
      `array with ${value.length} items`,
      `Expected ${expected} at ${formatPath(path10)}`
    );
  }
  if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
    const expected = `array with at most ${schema.maxItems} items`;
    addIssue(
      state,
      path10,
      expected,
      `array with ${value.length} items`,
      `Expected ${expected} at ${formatPath(path10)}`
    );
  }
  const nextValue = value.map((item, index) => {
    const result = walkSchema(schema.item, item, [...path10, String(index)], state);
    return result.present ? result.value : item;
  });
  return { present: true, value: nextValue };
}
function walkObject(schema, value, path10, state, injectedProperties = {}) {
  if (!isPlainRecord(value)) {
    addExpectedIssue(state, path10, "object", value);
    return { present: true, value };
  }
  const nextValue = {};
  const allowedKeys = /* @__PURE__ */ new Set([...Object.keys(schema.shape), ...Object.keys(injectedProperties)]);
  for (const [key, propertySchema] of Object.entries(schema.shape)) {
    const propertyValue = Object.hasOwn(value, key) ? value[key] : missingValue;
    const result = walkSchema(propertySchema, propertyValue, [...path10, key], state);
    if (result.present) {
      setOwnValue(nextValue, key, result.value);
    }
  }
  for (const [key, injectedValue] of Object.entries(injectedProperties)) {
    if (Object.hasOwn(value, key)) {
      setOwnValue(nextValue, key, value[key]);
    } else {
      setOwnValue(nextValue, key, injectedValue);
    }
  }
  for (const [key, propertyValue] of Object.entries(value)) {
    if (allowedKeys.has(key)) {
      continue;
    }
    if (schema.additionalProperties === true) {
      setOwnValue(nextValue, key, propertyValue);
    } else {
      addUnexpectedPropertyIssue(state, [...path10, key]);
    }
  }
  return { present: true, value: nextValue };
}
function walkOneOf(schema, value, path10, state) {
  if (!isPlainRecord(value)) {
    addExpectedIssue(state, path10, "object", value);
    return { present: true, value };
  }
  const discriminatorValue = value[schema.discriminator];
  const discriminatorPath = [...path10, schema.discriminator];
  const branchValues = Object.keys(schema.branches);
  const expected = `one of ${branchValues.join(", ")}`;
  if (!Object.hasOwn(value, schema.discriminator)) {
    addIssueWithMessage(
      state,
      discriminatorPath,
      expected,
      "missing",
      `Missing discriminator "${schema.discriminator}" at ${formatPath(path10)}. Expected one of: ${branchValues.join(", ")}.`
    );
    return { present: true, value };
  }
  if (typeof discriminatorValue !== "string" || !Object.hasOwn(schema.branches, discriminatorValue)) {
    addIssueWithMessage(
      state,
      discriminatorPath,
      expected,
      receivedValue(discriminatorValue),
      `Expected ${expected} at ${formatPath(discriminatorPath)}, got ${formatReceivedDiscriminator(discriminatorValue)}`
    );
    return { present: true, value };
  }
  return walkObject(schema.branches[discriminatorValue], value, path10, state, {
    [schema.discriminator]: discriminatorValue
  });
}
function walkUnion(schema, value, path10, state) {
  if (isPlainRecord(value)) {
    const candidateBranches = schema.branches.filter((branch) => hasRequiredKeys(branch, value));
    if (candidateBranches.length === 1) {
      return walkObject(candidateBranches[0], value, path10, state);
    }
  }
  const matches = [];
  for (const branch of schema.branches) {
    const branchState = { issues: [] };
    const result = walkObject(branch, value, path10, branchState);
    if (branchState.issues.length === 0 && result.present) {
      matches.push({ fingerprint: getRequiredKeyFingerprint(branch), value: result.value });
    }
  }
  if (matches.length === 1) {
    return { present: true, value: matches[0].value };
  }
  if (matches.length === 0) {
    const branchDescriptions = schema.branches.map((branch) => getRequiredKeyFingerprint(branch));
    addIssueWithMessage(
      state,
      path10,
      "exactly one union branch",
      "0 matching branches",
      `No union branch matched at ${formatPath(path10)}. Tried ${schema.branches.length} branches. Expected one of: ${branchDescriptions.join(" | ")}.`
    );
    return { present: true, value };
  }
  addIssueWithMessage(
    state,
    path10,
    "exactly one union branch",
    `${matches.length} matching branches`,
    `Expected exactly one union branch at ${formatPath(path10)}, but matched more than one branch: ${matches.map((match) => match.fingerprint).join(" | ")}`
  );
  return { present: true, value };
}
function hasRequiredKeys(schema, value) {
  for (const [key, propertySchema] of Object.entries(schema.shape)) {
    if (propertySchema.kind !== "optional" && !Object.hasOwn(value, key)) {
      return false;
    }
  }
  return true;
}
function walkRecord(schema, value, path10, state) {
  if (!isPlainRecord(value)) {
    addExpectedIssue(state, path10, "object", value);
    return { present: true, value };
  }
  const nextValue = {};
  for (const [key, propertyValue] of Object.entries(value)) {
    const result = walkSchema(schema.value, propertyValue, [...path10, key], state);
    if (result.present) {
      setOwnValue(nextValue, key, result.value);
    }
  }
  return { present: true, value: nextValue };
}
function walkJson(value, path10, state) {
  if (isJsonValue(value)) {
    return { present: true, value };
  }
  addExpectedIssue(state, path10, "JSON value", value);
  return { present: true, value };
}
function getDefault(schema) {
  if (schema.default !== void 0) {
    return { present: true, value: schema.default };
  }
  if (schema.kind === "optional") {
    return getDefault(schema.inner);
  }
  return { present: false };
}
function isPlainRecord(value) {
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    return false;
  }
  const prototype = Object.getPrototypeOf(value);
  return prototype === Object.prototype || prototype === null;
}
function isJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
    return typeof value !== "number" || Number.isFinite(value);
  }
  if (Array.isArray(value)) {
    if (ancestors.has(value)) {
      return false;
    }
    ancestors.add(value);
    const result = value.every((item) => isJsonValue(item, ancestors));
    ancestors.delete(value);
    return result;
  }
  if (isPlainRecord(value)) {
    if (ancestors.has(value)) {
      return false;
    }
    ancestors.add(value);
    const result = Object.values(value).every((item) => isJsonValue(item, ancestors));
    ancestors.delete(value);
    return result;
  }
  return false;
}
function cloneDefault(value) {
  return structuredClone(value);
}
function setOwnValue(target, key, value) {
  Object.defineProperty(target, key, {
    configurable: true,
    enumerable: true,
    writable: true,
    value
  });
}
function expectedFor(schema) {
  switch (schema.kind) {
    case "string":
      return "string";
    case "number":
      return schema.jsonType === "integer" ? "integer" : "number";
    case "boolean":
      return "boolean";
    case "enum":
      return `one of ${schema.values.join(", ")}`;
    case "array":
      return "array";
    case "object":
    case "oneOf":
    case "record":
      return "object";
    case "union":
      return "exactly one union branch";
    case "json":
      return "JSON value";
    case "optional":
      return expectedFor(schema.inner);
  }
}
function addExpectedIssue(state, path10, expected, value) {
  addIssue(
    state,
    path10,
    expected,
    receivedType(value),
    `Expected ${expected} at ${formatPath(path10)}`
  );
}
function addUnexpectedPropertyIssue(state, path10) {
  addIssue(
    state,
    path10,
    "no additional properties",
    "unknown property",
    `Unexpected property ${formatPath(path10)}`
  );
}
function addIssue(state, path10, expected, received, _message) {
  state.issues.push({
    path: path10,
    expected,
    received,
    message: formatIssueMessage(expected, path10, received)
  });
}
function addIssueWithMessage(state, path10, expected, received, message2) {
  state.issues.push({
    path: path10,
    expected,
    received,
    message: message2
  });
}
function formatIssueMessage(expected, path10, received) {
  return `Expected ${expected} at ${formatPath(path10)}, got ${received}`;
}
function formatPath(path10) {
  return path10.length === 0 ? "value" : path10.join(".");
}
function compilePattern(pattern) {
  try {
    return new RegExp(pattern);
  } catch {
    return void 0;
  }
}
function receivedType(value) {
  if (value === null) {
    return "null";
  }
  if (Array.isArray(value)) {
    return "array";
  }
  if (typeof value === "number" && Number.isInteger(value)) {
    return "integer";
  }
  return typeof value;
}
function receivedValue(value) {
  if (typeof value === "string") {
    return value;
  }
  if (value === void 0) {
    return "undefined";
  }
  return String(value);
}
function formatReceivedDiscriminator(value) {
  if (typeof value === "string") {
    return JSON.stringify(value);
  }
  return receivedValue(value);
}

// ../toolcraft-schema/src/index.ts
function assertValidEnumValues(values) {
  if (values.length === 0) {
    throw new Error("Enum schema requires at least one value");
  }
  const uniqueValues = new Set(values);
  if (uniqueValues.size !== values.length) {
    throw new Error("Enum schema values must be unique");
  }
  if (values.some((value) => typeof value === "number" && !Number.isFinite(value))) {
    throw new Error("Enum schema numeric values must be finite");
  }
}
function assertNonNegativeInteger(value, name) {
  if (value !== void 0 && (!Number.isInteger(value) || value < 0)) {
    throw new Error(`${name} must be a non-negative integer`);
  }
}
function assertFiniteNumber(value, name) {
  if (value !== void 0 && !Number.isFinite(value)) {
    throw new Error(`${name} must be finite`);
  }
}
function assertMinMaxOrder(minimum, maximum, minimumName, maximumName) {
  if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) {
    throw new Error(`${minimumName} must be less than or equal to ${maximumName}`);
  }
}
function assertValidDefault(schema) {
  if (schema.default === void 0) {
    return;
  }
  const result = validate(schema, schema.default);
  if (!result.ok) {
    throw new Error(
      `default must satisfy schema: ${result.issues[0]?.message ?? "invalid default"}`
    );
  }
}
function assertPattern(pattern) {
  if (pattern === void 0) {
    return;
  }
  try {
    new RegExp(pattern);
  } catch {
    throw new Error("pattern must be a valid regular expression");
  }
}
var S = {
  String(options = {}) {
    assertNonNegativeInteger(options.minLength, "minLength");
    assertNonNegativeInteger(options.maxLength, "maxLength");
    assertMinMaxOrder(options.minLength, options.maxLength, "minLength", "maxLength");
    assertPattern(options.pattern);
    const schema = {
      kind: "string",
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Number(options = {}) {
    assertFiniteNumber(options.minimum, "minimum");
    assertFiniteNumber(options.maximum, "maximum");
    assertMinMaxOrder(options.minimum, options.maximum, "minimum", "maximum");
    assertFiniteNumber(options.default, "default");
    if (options.jsonType === "integer" && options.default !== void 0 && !Number.isInteger(options.default)) {
      throw new Error("default must be an integer");
    }
    const schema = {
      kind: "number",
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Boolean(options = {}) {
    const schema = {
      kind: "boolean",
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Enum(values, options = {}) {
    assertValidEnumValues(values);
    if (options.jsonType === "integer" && values.some((value) => typeof value !== "number" || !Number.isInteger(value))) {
      throw new Error("Integer enum values must be integers");
    }
    const schema = {
      kind: "enum",
      values,
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Array(item, options = {}) {
    assertNonNegativeInteger(options.minItems, "minItems");
    assertNonNegativeInteger(options.maxItems, "maxItems");
    assertMinMaxOrder(options.minItems, options.maxItems, "minItems", "maxItems");
    const schema = {
      kind: "array",
      item,
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Object(shape, options = {}) {
    const schema = {
      kind: "object",
      shape,
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Optional(inner) {
    return {
      kind: "optional",
      inner
    };
  },
  OneOf,
  Union,
  Record,
  Json
};

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

// ../toolcraft/src/index.ts
var commandConfigSymbol = /* @__PURE__ */ Symbol("toolcraft.command.config");
var commandSourcePathSymbol = /* @__PURE__ */ Symbol("toolcraft.command.sourcePath");
function cloneScope(scope) {
  return scope === void 0 ? void 0 : [...scope];
}
function cloneSecretDefinition(secret) {
  return {
    env: secret.env,
    description: secret.description,
    optional: secret.optional
  };
}
function cloneSecrets(secrets) {
  if (secrets === void 0) {
    return {};
  }
  return Object.fromEntries(
    Object.entries(secrets).map(([key, secret]) => [key, cloneSecretDefinition(secret)])
  );
}
function cloneRequires(requires) {
  if (requires === void 0) {
    return void 0;
  }
  return {
    auth: requires.auth,
    apiVersion: requires.apiVersion,
    check: requires.check
  };
}
function cloneCommandExamples(examples) {
  return (examples ?? []).map((example) => ({
    title: example.title,
    params: { ...example.params }
  }));
}
function parseStackPath(candidate) {
  if (candidate.startsWith("file://")) {
    try {
      return fileURLToPath2(candidate);
    } catch {
      return void 0;
    }
  }
  if (candidate.startsWith("/")) {
    return candidate;
  }
  return void 0;
}
function extractStackPath(line) {
  const trimmed = line.trim();
  const fileIndex = trimmed.indexOf("file://");
  if (fileIndex >= 0) {
    const location2 = trimmed.slice(fileIndex);
    const separatorIndex2 = location2.lastIndexOf(":");
    const previousSeparatorIndex2 = separatorIndex2 >= 0 ? location2.lastIndexOf(":", separatorIndex2 - 1) : -1;
    const candidate2 = separatorIndex2 >= 0 && previousSeparatorIndex2 >= 0 ? location2.slice(0, previousSeparatorIndex2) : location2;
    return parseStackPath(candidate2);
  }
  const slashIndex = trimmed.indexOf("/");
  if (slashIndex < 0) {
    return void 0;
  }
  const location = trimmed.slice(slashIndex);
  const separatorIndex = location.lastIndexOf(":");
  const previousSeparatorIndex = separatorIndex >= 0 ? location.lastIndexOf(":", separatorIndex - 1) : -1;
  const candidate = separatorIndex >= 0 && previousSeparatorIndex >= 0 ? location.slice(0, previousSeparatorIndex) : location;
  return parseStackPath(candidate);
}
function inferCommandSourcePath() {
  const stack = new Error().stack;
  if (typeof stack !== "string") {
    return void 0;
  }
  for (const line of stack.split("\n").slice(1)) {
    const candidate = extractStackPath(line);
    if (candidate === void 0) {
      continue;
    }
    if (candidate.includes("/packages/toolcraft/src/index.ts") || candidate.includes("/packages/toolcraft/dist/index.js") || candidate.includes("/node_modules/toolcraft/dist/index.js")) {
      continue;
    }
    return candidate;
  }
  return void 0;
}
function composeChecks(parentCheck, childCheck) {
  if (parentCheck === void 0) {
    return childCheck;
  }
  if (childCheck === void 0) {
    return parentCheck;
  }
  return async (ctx) => {
    const parentResult = await parentCheck(ctx);
    if (!parentResult.ok) {
      return parentResult;
    }
    return childCheck(ctx);
  };
}
function mergeRequires(parent, child) {
  if (parent === void 0 && child === void 0) {
    return void 0;
  }
  const merged = {
    auth: child?.auth ?? parent?.auth,
    apiVersion: child?.apiVersion ?? parent?.apiVersion,
    check: composeChecks(parent?.check, child?.check)
  };
  if (merged.auth === void 0 && merged.apiVersion === void 0 && merged.check === void 0) {
    return void 0;
  }
  return merged;
}
function mergeSecrets(parent, child) {
  return cloneSecrets({
    ...parent,
    ...child
  });
}
function resolveCommandScope(ownScope, inheritedScope) {
  return cloneScope(ownScope ?? inheritedScope) ?? ["cli", "sdk"];
}
function createBaseCommand(config2) {
  const command = {
    kind: "command",
    name: config2.name,
    description: config2.description,
    hidden: config2.hidden ?? false,
    examples: cloneCommandExamples(config2.examples),
    aliases: [...config2.aliases ?? []],
    positional: [...config2.positional ?? []],
    params: config2.params,
    result: config2.result,
    secrets: cloneSecrets(config2.secrets),
    scope: resolveCommandScope(config2.scope, void 0),
    confirm: config2.confirm ?? false,
    humanInLoop: config2.humanInLoop,
    requires: cloneRequires(config2.requires),
    handler: config2.handler,
    render: config2.render
  };
  Object.defineProperty(command, commandConfigSymbol, {
    value: {
      scope: cloneScope(config2.scope),
      hidden: config2.hidden ?? false,
      examples: cloneCommandExamples(config2.examples),
      result: config2.result,
      humanInLoop: config2.humanInLoop,
      secrets: cloneSecrets(config2.secrets),
      requires: cloneRequires(config2.requires),
      sourcePath: inferCommandSourcePath()
    }
  });
  return command;
}
function getInternalCommandConfig(command) {
  return command[commandConfigSymbol];
}
function materializeCommand(command, inherited) {
  const internal = getInternalCommandConfig(command);
  const materialized = {
    kind: "command",
    name: command.name,
    description: command.description,
    hidden: internal.hidden,
    examples: cloneCommandExamples(internal.examples),
    aliases: [...command.aliases],
    positional: [...command.positional],
    params: command.params,
    result: internal.result,
    secrets: mergeSecrets(inherited.secrets, internal.secrets),
    scope: resolveCommandScope(internal.scope, inherited.scope),
    confirm: command.confirm,
    humanInLoop: mergeHumanInLoopFromGroup(inherited.humanInLoop, internal.humanInLoop),
    requires: mergeRequires(inherited.requires, internal.requires),
    handler: command.handler,
    render: command.render
  };
  Object.defineProperty(materialized, commandConfigSymbol, {
    value: {
      scope: cloneScope(internal.scope),
      hidden: internal.hidden,
      examples: cloneCommandExamples(internal.examples),
      result: internal.result,
      humanInLoop: internal.humanInLoop,
      secrets: cloneSecrets(internal.secrets),
      requires: cloneRequires(internal.requires),
      sourcePath: internal.sourcePath
    }
  });
  Object.defineProperty(materialized, commandSourcePathSymbol, {
    value: internal.sourcePath
  });
  return materialized;
}
function defineCommand(config2) {
  validateHumanInLoopOnDefine(config2);
  return materializeCommand(
    createBaseCommand(config2),
    {
      scope: void 0,
      humanInLoop: void 0,
      secrets: {},
      requires: void 0
    }
  );
}

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

// 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";

// ../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/commands/installer.ts
var DEFAULT_INSTALL_AGENT = "claude-code";
var TERMINAL_PILOT_SKILL_NAME = "terminal-pilot";
var installableAgents = supportedAgents;
function isNotFoundError(error2) {
  return hasOwnErrorCode(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 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 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);
  }
}

// src/commands/uninstall.ts
var params = S.Object({
  agent: S.Enum(installableAgents, {
    description: "Agent to uninstall terminal-pilot from",
    default: DEFAULT_INSTALL_AGENT
  })
});
var uninstall = defineCommand({
  name: "uninstall",
  description: "Remove the terminal-pilot CLI skill.",
  scope: ["cli"],
  positional: ["agent"],
  params,
  handler: async ({ params: params2, terminalPilotInstaller }) => {
    const services = resolveInstallerServices(terminalPilotInstaller);
    const agent = resolveInstallableAgent(params2.agent);
    const localSkill = getSkillFolderWithHome(
      agent,
      "local",
      services.cwd,
      services.homeDir
    );
    const globalSkill = getSkillFolderWithHome(
      agent,
      "global",
      services.cwd,
      services.homeDir
    );
    const skills = [localSkill, globalSkill];
    const staged = [];
    try {
      for (const skill of skills) {
        await assertNoSymbolicLinkPath(services.fs, skill.fullPath);
        if (!await folderExists(services.fs, skill.fullPath)) {
          continue;
        }
        const stagingPath = `${skill.fullPath}.removing-${randomUUID4()}`;
        await services.fs.rename(skill.fullPath, stagingPath);
        staged.push({ ...skill, stagingPath });
      }
    } catch (error2) {
      for (const skill of staged.reverse()) {
        await services.fs.rename(skill.stagingPath, skill.fullPath);
      }
      throw error2;
    }
    if (typeof services.fs.rm === "function") {
      await Promise.allSettled(
        staged.map((skill) => services.fs.rm(skill.stagingPath, { recursive: true, force: true }))
      );
    }
    return {
      agent,
      removedSkillPaths: staged.map((skill) => skill.displayPath)
    };
  }
});
async function folderExists(fs4, folderPath) {
  try {
    await fs4.stat(folderPath);
    return true;
  } catch (error2) {
    if (hasOwnErrorCode(error2, "ENOENT")) {
      return false;
    }
    throw error2;
  }
}
export {
  uninstall
};
//# sourceMappingURL=uninstall.js.map
