"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// modelrouter/index.ts
var modelrouter_exports = {};
__export(modelrouter_exports, {
  AnthropicRouter: () => AnthropicRouter,
  GeminiRouter: () => GeminiRouter,
  OpenAIRouter: () => OpenAIRouter,
  RawRouter: () => RawRouter
});
module.exports = __toCommonJS(modelrouter_exports);

// tools/utils/resilience.ts
var DEFAULT_RETRY_CONFIG = {
  maxRetries: 3,
  initialDelay: 1e3,
  maxDelay: 3e4,
  backoffMultiplier: 2,
  retryableErrors: ["ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND"]
};
async function fetchWithRetry(url, options, retryConfig = {}) {
  const {
    maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,
    initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,
    maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,
    backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,
    retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,
    onRetry
  } = retryConfig;
  let lastError = null;
  let delay = initialDelay;
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);
      if (response.status === 429 || response.status === 503) {
        if (attempt < maxRetries) {
          const retryAfter = response.headers.get("Retry-After");
          const waitTime = retryAfter ? parseInt(retryAfter) * 1e3 : Math.min(delay, maxDelay);
          const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);
          if (onRetry) {
            onRetry(attempt + 1, error);
          }
          await sleep(waitTime);
          delay *= backoffMultiplier;
          continue;
        }
      }
      return response;
    } catch (error) {
      lastError = error;
      const isRetryable = retryableErrors.some(
        (errType) => lastError?.message?.includes(errType)
      );
      if (!isRetryable || attempt === maxRetries) {
        throw lastError;
      }
      const waitTime = Math.min(delay, maxDelay);
      if (onRetry) {
        onRetry(attempt + 1, lastError);
      }
      await sleep(waitTime);
      delay *= backoffMultiplier;
    }
  }
  throw lastError || new Error("Max retries exceeded");
}
async function withTimeout(promise, timeoutMs, errorMessage) {
  let timeoutId;
  const timeoutPromise = new Promise((_, reject) => {
    timeoutId = setTimeout(() => {
      reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));
    }, timeoutMs);
  });
  try {
    const result = await Promise.race([promise, timeoutPromise]);
    clearTimeout(timeoutId);
    return result;
  } catch (error) {
    clearTimeout(timeoutId);
    throw error;
  }
}
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

// modelrouter/core.ts
var DEFAULT_CONFIG = {
  apiUrl: "https://api.morphllm.com",
  timeout: 5e3,
  // 5 seconds (responses typically <500ms)
  debug: false
};
var BaseRouter = class {
  config;
  provider;
  constructor(provider, config = {}) {
    this.provider = provider;
    this.config = {
      apiKey: config.apiKey,
      apiUrl: config.apiUrl || DEFAULT_CONFIG.apiUrl,
      timeout: config.timeout || DEFAULT_CONFIG.timeout,
      debug: config.debug || DEFAULT_CONFIG.debug,
      retryConfig: config.retryConfig
    };
  }
  /**
   * Select the optimal model for a given input and mode
   */
  async selectModel(input) {
    const mode = input.mode || "balanced";
    const apiKey = this.config.apiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
    if (!apiKey) {
      throw new Error(
        "Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config."
      );
    }
    const url = `${this.config.apiUrl}/v1/router/${this.provider}`;
    const payload = {
      input: input.input,
      mode
    };
    if (this.config.debug) {
      console.log(`[ModelRouter] Requesting ${this.provider} model selection:`, {
        mode,
        inputLength: input.input.length
      });
    }
    try {
      const fetchPromise = fetchWithRetry(
        url,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${apiKey}`
          },
          body: JSON.stringify(payload)
        },
        this.config.retryConfig
      );
      const response = await withTimeout(
        fetchPromise,
        this.config.timeout,
        `Router API request timed out after ${this.config.timeout}ms`
      );
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(
          `Router API error (${response.status}): ${errorText || response.statusText}`
        );
      }
      const apiResult = await response.json();
      const result = {
        model: apiResult.model
      };
      if (this.config.debug) {
        console.log(`[ModelRouter] Selected model: ${apiResult.model}, Confidence: ${apiResult.confidence?.toFixed(3)}`);
      }
      return result;
    } catch (error) {
      if (this.config.debug) {
        console.error(`[ModelRouter] Error selecting model:`, error);
      }
      throw error;
    }
  }
};
var OpenAIRouter = class extends BaseRouter {
  constructor(config = {}) {
    super("openai", config);
  }
  /**
   * Select optimal GPT-5 model
   * 
   * @param input - User input and mode
   * @returns Selected model name (gpt-5-mini | gpt-5-low | gpt-5-medium | gpt-5-high)
   */
  async selectModel(input) {
    return super.selectModel(input);
  }
};
var AnthropicRouter = class extends BaseRouter {
  constructor(config = {}) {
    super("anthropic", config);
  }
  /**
   * Select optimal Claude model
   * 
   * @param input - User input and mode
   * @returns Selected model name (claude-4.5-haiku | claude-4.5-sonnet)
   */
  async selectModel(input) {
    return super.selectModel(input);
  }
};
var GeminiRouter = class extends BaseRouter {
  constructor(config = {}) {
    super("gemini", config);
  }
  /**
   * Select optimal Gemini model
   * 
   * @param input - User input and mode
   * @returns Selected model name (gemini-2.5-flash | gemini-2.5-pro)
   */
  async selectModel(input) {
    return super.selectModel(input);
  }
};
var RawRouter = class extends BaseRouter {
  constructor(config = {}) {
    super("raw", config);
  }
  /**
   * Get raw difficulty classification
   * 
   * @param input - User input and mode
   * @returns Raw difficulty (easy | medium | hard | needs_info)
   */
  async classify(input) {
    const mode = input.mode || "balanced";
    const apiKey = this.config.apiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
    if (!apiKey) {
      throw new Error(
        "Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config."
      );
    }
    const url = `${this.config.apiUrl}/v1/router/raw`;
    const payload = {
      input: input.input,
      mode
    };
    if (this.config.debug) {
      console.log(`[RawRouter] Requesting raw difficulty classification:`, {
        mode,
        inputLength: input.input.length
      });
    }
    try {
      const fetchPromise = fetchWithRetry(
        url,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${apiKey}`
          },
          body: JSON.stringify(payload)
        },
        this.config.retryConfig
      );
      const response = await withTimeout(
        fetchPromise,
        this.config.timeout,
        `Router API request timed out after ${this.config.timeout}ms`
      );
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(
          `Router API error (${response.status}): ${errorText || response.statusText}`
        );
      }
      const apiResult = await response.json();
      let difficulty;
      if (apiResult.difficulty === "") {
        difficulty = "medium";
      } else {
        difficulty = apiResult.difficulty || apiResult.model;
      }
      const result = {
        difficulty
      };
      if (this.config.debug) {
        console.log(`[RawRouter] Classified as: ${difficulty}`);
      }
      return result;
    } catch (error) {
      if (this.config.debug) {
        console.error(`[RawRouter] Error classifying:`, error);
      }
      throw error;
    }
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AnthropicRouter,
  GeminiRouter,
  OpenAIRouter,
  RawRouter
});
//# sourceMappingURL=index.cjs.map