import "./chunk-BYW8Mqxw.js";
import { b as getEnvString, i as logger_default } from "./logger-CATn0kWr.js";
import "./esm-tl6dENiB.js";
import "./pythonUtils-D5rGzOeH.js";
import "./types-CHrVA-1r.js";
import "./util-B4XoCK-L.js";
import "./fetch-BhuDaSn5.js";
import { o as getCache, s as isCacheEnabled } from "./cache-C2ESUUfo.js";
import { t as OpenAiChatCompletionProvider } from "./chat-CL4dYB-g.js";
import "./transform-BYdhQ9OB.js";
import "./openai-BH2FsThj.js";
import "./util-DUayzR6E.js";
import { t as OpenAiEmbeddingProvider } from "./embedding-Bo_7FjBa.js";
import { t as OpenAiImageProvider } from "./image-BziLBGmy.js";
import { t as OpenAiCompletionProvider } from "./completion-CWcCXIZT.js";
import fs from "fs";
import path from "path";
import dedent from "dedent";
import crypto from "crypto";

//#region src/providers/agentic-utils.ts
/**
* Shared utilities for agentic providers (Claude Agent SDK, OpenCode SDK, etc.)
*
* These utilities handle common functionality needed by coding agent providers:
* - Working directory fingerprinting for cache key generation
* - Response caching with fingerprint support
*/
/**
* Timeout for working directory fingerprint generation (ms)
* Prevents hanging on extremely large directories
*/
const FINGERPRINT_TIMEOUT_MS = 2e3;
/**
* Get a fingerprint for a working directory to use as a cache key.
* Checks directory mtime and descendant file mtimes recursively.
*
* This allows for caching prompts that use the same working directory
* when the files haven't changed.
*
* @param workingDir - Absolute path to the working directory
* @returns SHA-256 hash fingerprint of the directory state
* @throws Error if fingerprinting times out or directory is inaccessible
*/
async function getWorkingDirFingerprint(workingDir) {
	const dirMtime = fs.statSync(workingDir).mtimeMs;
	const startTime = Date.now();
	const getAllFiles = (dir, files = []) => {
		if (Date.now() - startTime > FINGERPRINT_TIMEOUT_MS) throw new Error("Working directory fingerprint timed out");
		const entries = fs.readdirSync(dir, { withFileTypes: true });
		for (const entry of entries) {
			const fullPath = path.join(dir, entry.name);
			if (entry.isDirectory()) getAllFiles(fullPath, files);
			else if (entry.isFile()) files.push(fullPath);
		}
		return files;
	};
	const fingerprintData = `dir:${dirMtime};files:${getAllFiles(workingDir).map((file) => {
		const stat = fs.statSync(file);
		return `${path.relative(workingDir, file)}:${stat.mtimeMs}`;
	}).sort().join(",")}`;
	return crypto.createHash("sha256").update(fingerprintData).digest("hex");
}
/**
* Generate a cache key from arbitrary data using SHA-256 hash
*
* @param prefix - Cache key prefix (provider identifier)
* @param data - Data to hash for the cache key
* @returns Prefixed SHA-256 hash cache key
*/
function generateCacheKey(prefix, data) {
	const stringified = JSON.stringify(data);
	return `${prefix}:${crypto.createHash("sha256").update(stringified).digest("hex")}`;
}
/**
* Initialize cache and check for cached response
*
* This handles the common caching pattern used by agentic providers:
* 1. Check if caching is enabled
* 2. Generate working directory fingerprint if needed
* 3. Generate cache key
* 4. Return cache configuration for use by the provider
*
* @param options - Cache options including prefix and working directory
* @param cacheKeyData - Data to include in the cache key
* @returns Cache configuration and optional cached response
*/
async function initializeAgenticCache(options, cacheKeyData) {
	if (!isCacheEnabled()) return {
		shouldCache: false,
		shouldReadCache: false,
		shouldWriteCache: false
	};
	let workingDirFingerprint = null;
	if (options.workingDir) try {
		workingDirFingerprint = await getWorkingDirFingerprint(options.workingDir);
	} catch (error) {
		logger_default.error(dedent`Error getting working directory fingerprint for cache key - ${options.workingDir}: ${String(error)}

        Caching is disabled.`);
		return {
			shouldCache: false,
			shouldReadCache: false,
			shouldWriteCache: false
		};
	}
	const cache = await getCache();
	const cacheKey = generateCacheKey(options.cacheKeyPrefix, {
		...cacheKeyData,
		workingDirFingerprint
	});
	return {
		shouldCache: true,
		shouldReadCache: !options.bustCache,
		shouldWriteCache: true,
		cache,
		cacheKey,
		workingDirFingerprint
	};
}
/**
* Try to get a cached response
*
* @param cacheResult - Result from initializeAgenticCache
* @param debugContext - Context for debug logging (e.g., prompt preview)
* @returns Cached ProviderResponse if found, undefined otherwise
*/
async function getCachedResponse(cacheResult, debugContext) {
	if (!cacheResult.shouldReadCache || !cacheResult.cache || !cacheResult.cacheKey) return;
	try {
		const cachedResponse = await cacheResult.cache.get(cacheResult.cacheKey);
		if (cachedResponse) {
			logger_default.debug(`Returning cached response${debugContext ? ` for ${debugContext}` : ""} (cache key: ${cacheResult.cacheKey})`);
			return {
				...JSON.parse(cachedResponse),
				cached: true
			};
		}
	} catch (error) {
		logger_default.error(`Error getting cached response: ${String(error)}`);
	}
}
/**
* Cache a provider response
*
* @param cacheResult - Result from initializeAgenticCache
* @param response - The ProviderResponse to cache
* @param debugContext - Context for debug logging
*/
async function cacheResponse(cacheResult, response, debugContext) {
	if (!cacheResult.shouldWriteCache || !cacheResult.cache || !cacheResult.cacheKey) return;
	try {
		await cacheResult.cache.set(cacheResult.cacheKey, JSON.stringify(response));
	} catch (error) {
		logger_default.error(`Error caching response${debugContext ? ` for ${debugContext}` : ""}: ${String(error)}`);
	}
}

//#endregion
//#region src/providers/cometapi.ts
/**
* CometAPI Image Provider - extends OpenAI Image Provider for CometAPI's image generation models
*/
var CometApiImageProvider = class extends OpenAiImageProvider {
	constructor(modelName, options = {}) {
		super(modelName, {
			...options,
			config: {
				...options.config,
				apiKeyEnvar: "COMETAPI_KEY",
				apiBaseUrl: "https://api.cometapi.com/v1"
			}
		});
	}
	getApiKey() {
		if (this.config?.apiKey) return this.config.apiKey;
		return getEnvString("COMETAPI_KEY");
	}
	getApiUrlDefault() {
		return "https://api.cometapi.com/v1";
	}
};
/**
* Factory for creating CometAPI providers using OpenAI-compatible endpoints.
*/
function createCometApiProvider(providerPath, options = {}) {
	const splits = providerPath.split(":");
	const type = splits[1];
	const modelName = splits.slice(2).join(":");
	const openaiOptions = {
		...options,
		config: {
			...options.config || {},
			apiBaseUrl: "https://api.cometapi.com/v1",
			apiKeyEnvar: "COMETAPI_KEY"
		}
	};
	if (type === "chat") return new OpenAiChatCompletionProvider(modelName, openaiOptions);
	else if (type === "completion") return new OpenAiCompletionProvider(modelName, openaiOptions);
	else if (type === "embedding" || type === "embeddings") return new OpenAiEmbeddingProvider(modelName, openaiOptions);
	else if (type === "image") return new CometApiImageProvider(modelName, openaiOptions);
	return new OpenAiChatCompletionProvider(splits.slice(1).join(":"), openaiOptions);
}

//#endregion
export { createCometApiProvider, getCachedResponse as n, initializeAgenticCache as r, cacheResponse as t };
//# sourceMappingURL=cometapi-8_Ni4lN2.js.map