import {
  readEnvVar
} from "./chunk-MARWOCVP.js";
import {
  log
} from "./chunk-2ODBA7MQ.js";

// src/resolve-provider-secret.ts
import path from "path";
import os from "os";
var _resolveApiKeyForProvider = null;
var _getRuntimeAuthForModel = null;
var _resolverLoaded = false;
var _resolverNextRetryAt = 0;
var RESOLVER_RETRY_BACKOFF_MS = 6e4;
var resolvedCache = /* @__PURE__ */ new Map();
async function getGatewayResolver() {
  if (_resolverLoaded) {
    return _resolveApiKeyForProvider;
  }
  if (_resolverNextRetryAt > 0 && Date.now() < _resolverNextRetryAt) {
    return null;
  }
  try {
    const candidates = [
      // Try glob-matching the runtime module name (hash varies per build)
      ...await findRuntimeModules()
    ];
    const { pathToFileURL } = await import("url");
    for (const candidate of candidates) {
      try {
        const importUrl = pathToFileURL(candidate).href;
        const mod = await import(importUrl);
        if (typeof mod.resolveApiKeyForProvider === "function") {
          _resolveApiKeyForProvider = mod.resolveApiKeyForProvider;
          if (typeof mod.getRuntimeAuthForModel === "function") {
            _getRuntimeAuthForModel = mod.getRuntimeAuthForModel;
            log.debug("loaded gateway getRuntimeAuthForModel from runtime module");
          }
          _resolverLoaded = true;
          log.debug("loaded gateway resolveApiKeyForProvider from runtime module");
          return _resolveApiKeyForProvider;
        }
      } catch {
      }
    }
  } catch {
  }
  _resolverNextRetryAt = Date.now() + RESOLVER_RETRY_BACKOFF_MS;
  log.debug(`gateway resolveApiKeyForProvider not available \u2014 will retry after ${RESOLVER_RETRY_BACKOFF_MS / 1e3}s`);
  return null;
}
async function findRuntimeModules() {
  return findGatewayRuntimeModules("runtime-model-auth.runtime-");
}
async function findGatewayRuntimeModules(filePrefix) {
  const { accessSync, constants, readdirSync, realpathSync, statSync } = await import("fs");
  const { createRequire } = await import("module");
  const candidates = [];
  const distDirs = [];
  const pushDistDirs = (entryPath) => {
    const resolvedEntryDir = path.dirname(entryPath);
    const packageRoot = path.basename(resolvedEntryDir) === "dist" ? path.resolve(resolvedEntryDir, "..") : resolvedEntryDir;
    const candidateDistDirs = [
      path.join(packageRoot, "dist"),
      path.join(packageRoot, "..", "dist")
    ];
    for (const candidate of candidateDistDirs) {
      const resolved = path.resolve(candidate);
      if (!distDirs.includes(resolved)) distDirs.push(resolved);
    }
  };
  try {
    const req = createRequire(import.meta.url);
    const openclawMain = req.resolve("openclaw");
    pushDistDirs(openclawMain);
  } catch {
  }
  try {
    const mainScript = process.argv[1];
    if (mainScript) {
      const realScript = realpathSync(mainScript);
      if (realScript.includes("openclaw")) {
        pushDistDirs(realScript);
      }
    }
  } catch {
  }
  try {
    const openclawBin = findExecutableOnPath("openclaw", accessSync, statSync, constants.X_OK);
    if (openclawBin) {
      pushDistDirs(realpathSync(openclawBin));
    }
  } catch {
  }
  for (const dir of distDirs) {
    try {
      const files = readdirSync(dir);
      for (const f of files) {
        if (f.startsWith(filePrefix) && f.endsWith(".js")) {
          candidates.push(path.join(dir, f));
        }
      }
    } catch {
    }
  }
  return candidates;
}
function findExecutableOnPath(executableName, access, stat, executableMode) {
  const pathEnv = readEnvVar("PATH");
  if (!pathEnv) return void 0;
  const pathExts = process.platform === "win32" ? (readEnvVar("PATHEXT") ?? ".EXE;.CMD;.BAT;.COM").split(";").filter((ext) => ext.length > 0) : [""];
  const hasExtension = path.extname(executableName).length > 0;
  for (const dir of pathEnv.split(path.delimiter)) {
    if (!dir) continue;
    const candidateNames = process.platform === "win32" && !hasExtension ? pathExts.map((ext) => `${executableName}${ext}`) : [executableName];
    for (const candidateName of candidateNames) {
      const candidate = path.join(dir, candidateName);
      try {
        access(candidate, executableMode);
        if (!stat(candidate).isFile()) continue;
        return candidate;
      } catch {
      }
    }
  }
  return void 0;
}
var __findExecutableOnPathForTest = findExecutableOnPath;
async function resolveProviderApiKey(providerId, apiKeyValue, gatewayConfig, agentDir) {
  const resolvedAgentDir = path.resolve(
    agentDir ?? path.join(os.homedir(), ".openclaw", "agents", "main", "agent")
  );
  const cacheKey = `provider:${providerId}:agentDir:${resolvedAgentDir}`;
  if (resolvedCache.has(cacheKey)) {
    return resolvedCache.get(cacheKey);
  }
  let resolved;
  if (typeof apiKeyValue === "string" && apiKeyValue.trim().length > 0) {
    if (apiKeyValue === "secretref-managed" || apiKeyValue.endsWith("-oauth") || apiKeyValue.endsWith("-local") || apiKeyValue === "lm-studio" || apiKeyValue.startsWith("gcp-")) {
    } else {
      resolved = apiKeyValue;
      resolvedCache.set(cacheKey, resolved);
      return resolved;
    }
  }
  const resolver = await getGatewayResolver();
  if (resolver) {
    try {
      const auth = await resolver({ provider: providerId, cfg: gatewayConfig, agentDir: resolvedAgentDir });
      if (auth?.apiKey) {
        resolved = auth.apiKey;
        log.debug(`resolved API key for provider "${providerId}" via gateway auth (source: ${auth.source ?? "unknown"}, mode: ${auth.mode ?? "unknown"})`);
        resolvedCache.set(cacheKey, resolved);
        return resolved;
      }
    } catch (err) {
      log.debug(
        `gateway auth resolution failed for provider "${providerId}": ${err instanceof Error ? err.message : String(err)}`
      );
    }
  }
  resolved = resolveFromEnv(providerId);
  if (resolved) {
    log.debug(`resolved API key for provider "${providerId}" from environment variable`);
  } else {
    log.debug(`could not resolve API key for provider "${providerId}" \u2014 skipping`);
  }
  if (resolved) {
    resolvedCache.set(cacheKey, resolved);
  }
  return resolved;
}
function resolveFromEnv(providerId) {
  const normalized = providerId.toUpperCase().replace(/[^A-Z0-9]/g, "_");
  const candidates = [
    `${normalized}_API_KEY`,
    `${normalized}_TOKEN`
  ];
  for (const envVar of candidates) {
    const value = readEnvVar(envVar);
    if (value && value.trim().length > 0) {
      return value.trim();
    }
  }
  return void 0;
}
async function getGatewayRuntimeAuthForModel() {
  await getGatewayResolver();
  return _getRuntimeAuthForModel;
}
function clearSecretCache() {
  resolvedCache.clear();
  _resolveApiKeyForProvider = null;
  _getRuntimeAuthForModel = null;
  _resolverLoaded = false;
  _resolverNextRetryAt = 0;
}
function __setGatewayResolverForTest(resolver) {
  _resolveApiKeyForProvider = resolver;
  _resolverLoaded = resolver !== null;
  _resolverNextRetryAt = 0;
}
function __setGatewayRuntimeAuthForModelForTest(resolver) {
  _getRuntimeAuthForModel = resolver;
  _resolverLoaded = resolver !== null || _resolveApiKeyForProvider !== null;
  _resolverNextRetryAt = 0;
}

export {
  findGatewayRuntimeModules,
  __findExecutableOnPathForTest,
  resolveProviderApiKey,
  getGatewayRuntimeAuthForModel,
  clearSecretCache,
  __setGatewayResolverForTest,
  __setGatewayRuntimeAuthForModelForTest
};
//# sourceMappingURL=chunk-S3IP6R6K.js.map