import {
  __esm,
  __export
} from "./chunk-4CV4JOE5.js";

// src/credentials/keychain.ts
var keychain_exports = {};
__export(keychain_exports, {
  deleteApiKey: () => deleteApiKey,
  getApiKey: () => getApiKey,
  getProviderConfig: () => getProviderConfig,
  hasProviderConfigured: () => hasProviderConfigured,
  listCredentials: () => listCredentials,
  setApiKey: () => setApiKey,
  setAzureConfig: () => setAzureConfig
});
import { execFileSync } from "child_process";
function getApiKey(provider) {
  const cfg = getProviderConfig(provider);
  return cfg ? cfg.key : null;
}
function getProviderConfig(provider) {
  if (provider === "azure-openai") return readAzureConfig();
  const key = readSimpleKey(provider);
  return key ? { provider, key } : null;
}
function hasProviderConfigured(provider) {
  return getProviderConfig(provider) != null;
}
function setApiKey(provider, key) {
  if (process.platform !== "darwin") {
    throw new Error(
      `Keychain storage is only supported on macOS. Set the ${SIMPLE_ENV_FALLBACK[provider]} environment variable instead.`
    );
  }
  if (!key || key.trim().length === 0) {
    throw new Error("Refusing to store an empty API key");
  }
  writeKeychain(provider, key.trim());
}
function setAzureConfig(config) {
  if (process.platform !== "darwin") {
    throw new Error(
      "Keychain storage is only supported on macOS. Set the AZURE_OPENAI_* env vars instead."
    );
  }
  const normalized = {
    endpoint: config.endpoint.trim().replace(/\/+$/, ""),
    deployment: config.deployment.trim(),
    api_version: config.api_version.trim(),
    key: config.key.trim()
  };
  if (!normalized.endpoint || !/^https?:\/\//.test(normalized.endpoint)) {
    throw new Error("Azure endpoint must be an http(s) URL like https://<resource>.openai.azure.com");
  }
  if (!normalized.deployment) throw new Error("Azure deployment name is required");
  if (!normalized.api_version) throw new Error("Azure api_version is required (e.g. 2024-10-21)");
  if (!normalized.key) throw new Error("Azure api key is required");
  writeKeychain("azure-openai", JSON.stringify(normalized));
}
function deleteApiKey(provider) {
  if (process.platform !== "darwin") return false;
  try {
    execFileSync(
      "security",
      ["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", provider],
      { stdio: "ignore" }
    );
    return true;
  } catch {
    return false;
  }
}
function listCredentials() {
  const results = [];
  for (const provider of ["openai", "anthropic"]) {
    const fromChain = process.platform === "darwin" ? readSimpleKeychain(provider) : null;
    if (fromChain) {
      results.push({ provider, source: "keychain", preview: previewKey(fromChain) });
      continue;
    }
    const fromEnv = process.env[SIMPLE_ENV_FALLBACK[provider]];
    if (fromEnv && fromEnv.trim().length > 0) {
      results.push({ provider, source: "env", preview: previewKey(fromEnv) });
    }
  }
  const azure = readAzureConfig();
  if (azure) {
    results.push({
      provider: "azure-openai",
      source: azureSource(),
      preview: previewKey(azure.key),
      detail: `${azure.endpoint} \xB7 ${azure.deployment} \xB7 api-version=${azure.api_version}`
    });
  }
  return results;
}
function readSimpleKey(provider) {
  if (process.platform === "darwin") {
    const fromChain = readSimpleKeychain(provider);
    if (fromChain) return fromChain;
  }
  const fromEnv = process.env[SIMPLE_ENV_FALLBACK[provider]];
  return fromEnv && fromEnv.trim().length > 0 ? fromEnv.trim() : null;
}
function readSimpleKeychain(provider) {
  try {
    const output = execFileSync(
      "security",
      ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", provider, "-w"],
      { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }
    );
    const trimmed = output.trim();
    return trimmed.length > 0 ? trimmed : null;
  } catch {
    return null;
  }
}
function readAzureConfig() {
  if (process.platform === "darwin") {
    try {
      const raw = execFileSync(
        "security",
        ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", "azure-openai", "-w"],
        { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }
      );
      const trimmed = raw.trim();
      if (trimmed.length > 0) {
        const parsed = JSON.parse(trimmed);
        if (parsed.endpoint && parsed.deployment && parsed.api_version && parsed.key) {
          return { provider: "azure-openai", ...parsed };
        }
      }
    } catch {
    }
  }
  const endpoint = process.env.AZURE_OPENAI_ENDPOINT?.trim();
  const deployment = process.env.AZURE_OPENAI_DEPLOYMENT?.trim();
  const api_version = process.env.AZURE_OPENAI_API_VERSION?.trim();
  const key = process.env.AZURE_OPENAI_API_KEY?.trim();
  if (endpoint && deployment && api_version && key) {
    return { provider: "azure-openai", endpoint: endpoint.replace(/\/+$/, ""), deployment, api_version, key };
  }
  return null;
}
function azureSource() {
  if (process.platform !== "darwin") return "env";
  try {
    execFileSync(
      "security",
      ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", "azure-openai", "-w"],
      { stdio: "ignore" }
    );
    return "keychain";
  } catch {
    return "env";
  }
}
function writeKeychain(provider, value) {
  execFileSync(
    "security",
    [
      "add-generic-password",
      "-U",
      "-s",
      KEYCHAIN_SERVICE,
      "-a",
      provider,
      "-w",
      value,
      "-T",
      ""
    ],
    { stdio: "ignore" }
  );
}
function previewKey(key) {
  const trimmed = key.trim();
  if (trimmed.length <= 8) return "***";
  return `${trimmed.slice(0, 4)}\u2026${trimmed.slice(-4)}`;
}
var KEYCHAIN_SERVICE, SIMPLE_ENV_FALLBACK;
var init_keychain = __esm({
  "src/credentials/keychain.ts"() {
    KEYCHAIN_SERVICE = "com.recall.llm";
    SIMPLE_ENV_FALLBACK = {
      openai: "OPENAI_API_KEY",
      anthropic: "ANTHROPIC_API_KEY"
    };
  }
});

export {
  getApiKey,
  getProviderConfig,
  hasProviderConfigured,
  setApiKey,
  setAzureConfig,
  deleteApiKey,
  listCredentials,
  keychain_exports,
  init_keychain
};
//# sourceMappingURL=chunk-DNFKAHS6.js.map