"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

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

// package.json
var package_default = {
  name: "@morphllm/morphsdk",
  version: "0.2.168",
  description: "TypeScript SDK and CLI for Morph Fast Apply integration",
  type: "module",
  main: "./dist/index.cjs",
  module: "./dist/index.js",
  types: "./dist/index.d.ts",
  exports: {
    ".": {
      types: "./dist/index.d.ts",
      import: "./dist/index.js",
      require: "./dist/index.cjs"
    },
    "./logger": {
      types: "./dist/logger.d.ts",
      import: "./dist/logger.js",
      require: "./dist/logger.cjs"
    },
    "./edge": {
      types: "./dist/edge.d.ts",
      import: "./dist/edge.js",
      require: "./dist/edge.cjs"
    },
    "./tools/warp-grep": {
      types: "./dist/tools/warp_grep/index.d.ts",
      import: "./dist/tools/warp_grep/index.js",
      require: "./dist/tools/warp_grep/index.cjs"
    },
    "./tools/warp-grep/openai": {
      types: "./dist/tools/warp_grep/openai.d.ts",
      import: "./dist/tools/warp_grep/openai.js",
      require: "./dist/tools/warp_grep/openai.cjs"
    },
    "./tools/warp-grep/anthropic": {
      types: "./dist/tools/warp_grep/anthropic.d.ts",
      import: "./dist/tools/warp_grep/anthropic.js",
      require: "./dist/tools/warp_grep/anthropic.cjs"
    },
    "./tools/warp-grep/vercel": {
      types: "./dist/tools/warp_grep/vercel.d.ts",
      import: "./dist/tools/warp_grep/vercel.js",
      require: "./dist/tools/warp_grep/vercel.cjs"
    },
    "./tools/warp-grep/client": {
      types: "./dist/tools/warp_grep/client.d.ts",
      import: "./dist/tools/warp_grep/client.js",
      require: "./dist/tools/warp_grep/client.cjs"
    },
    "./tools/warp-grep/gemini": {
      types: "./dist/tools/warp_grep/gemini.d.ts",
      import: "./dist/tools/warp_grep/gemini.js",
      require: "./dist/tools/warp_grep/gemini.cjs"
    },
    "./tools/warp-grep/harness": {
      types: "./dist/tools/warp_grep/harness.d.ts",
      import: "./dist/tools/warp_grep/harness.js",
      require: "./dist/tools/warp_grep/harness.cjs"
    },
    "./tools/fastapply": {
      types: "./dist/tools/fastapply/index.d.ts",
      import: "./dist/tools/fastapply/index.js",
      require: "./dist/tools/fastapply/index.cjs"
    },
    "./tools/fastapply/anthropic": {
      types: "./dist/tools/fastapply/anthropic.d.ts",
      import: "./dist/tools/fastapply/anthropic.js",
      require: "./dist/tools/fastapply/anthropic.cjs"
    },
    "./tools/fastapply/openai": {
      types: "./dist/tools/fastapply/openai.d.ts",
      import: "./dist/tools/fastapply/openai.js",
      require: "./dist/tools/fastapply/openai.cjs"
    },
    "./tools/fastapply/vercel": {
      types: "./dist/tools/fastapply/vercel.d.ts",
      import: "./dist/tools/fastapply/vercel.js",
      require: "./dist/tools/fastapply/vercel.cjs"
    },
    "./tools/codebase-search": {
      types: "./dist/tools/codebase_search/index.d.ts",
      import: "./dist/tools/codebase_search/index.js",
      require: "./dist/tools/codebase_search/index.cjs"
    },
    "./tools/codebase-search/anthropic": {
      types: "./dist/tools/codebase_search/anthropic.d.ts",
      import: "./dist/tools/codebase_search/anthropic.js",
      require: "./dist/tools/codebase_search/anthropic.cjs"
    },
    "./tools/codebase-search/openai": {
      types: "./dist/tools/codebase_search/openai.d.ts",
      import: "./dist/tools/codebase_search/openai.js",
      require: "./dist/tools/codebase_search/openai.cjs"
    },
    "./tools/codebase-search/vercel": {
      types: "./dist/tools/codebase_search/vercel.d.ts",
      import: "./dist/tools/codebase_search/vercel.js",
      require: "./dist/tools/codebase_search/vercel.cjs"
    },
    "./tools/git": {
      types: "./dist/git/index.d.ts",
      import: "./dist/git/index.js",
      require: "./dist/git/index.cjs"
    },
    "./tools/browser": {
      types: "./dist/tools/browser/index.d.ts",
      import: "./dist/tools/browser/index.js",
      require: "./dist/tools/browser/index.cjs"
    },
    "./tools/browser/anthropic": {
      types: "./dist/tools/browser/anthropic.d.ts",
      import: "./dist/tools/browser/anthropic.js",
      require: "./dist/tools/browser/anthropic.cjs"
    },
    "./tools/browser/openai": {
      types: "./dist/tools/browser/openai.d.ts",
      import: "./dist/tools/browser/openai.js",
      require: "./dist/tools/browser/openai.cjs"
    },
    "./tools/browser/vercel": {
      types: "./dist/tools/browser/vercel.d.ts",
      import: "./dist/tools/browser/vercel.js",
      require: "./dist/tools/browser/vercel.cjs"
    },
    "./tools/browser/profiles": {
      types: "./dist/tools/browser/profiles/index.d.ts",
      import: "./dist/tools/browser/profiles/index.js",
      require: "./dist/tools/browser/profiles/index.cjs"
    },
    "./modelrouter": {
      types: "./dist/modelrouter/index.d.ts",
      import: "./dist/modelrouter/index.js",
      require: "./dist/modelrouter/index.cjs"
    },
    "./tools/compact": {
      types: "./dist/tools/compact/index.d.ts",
      import: "./dist/tools/compact/index.js",
      require: "./dist/tools/compact/index.cjs"
    },
    "./subagents": {
      types: "./dist/subagents/index.d.ts",
      import: "./dist/subagents/index.js",
      require: "./dist/subagents/index.cjs"
    },
    "./subagents/vercel": {
      types: "./dist/subagents/vercel.d.ts",
      import: "./dist/subagents/vercel.js",
      require: "./dist/subagents/vercel.cjs"
    },
    "./subagents/anthropic": {
      types: "./dist/subagents/anthropic.d.ts",
      import: "./dist/subagents/anthropic.js",
      require: "./dist/subagents/anthropic.cjs"
    }
  },
  files: [
    "dist/**/*.js",
    "dist/**/*.cjs",
    "dist/**/*.d.ts",
    "dist/**/*.map",
    "!dist/**/__tests__/**",
    "!dist/**/*.test.*"
  ],
  scripts: {
    build: "tsup version.ts index.ts edge.ts client.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/codebase_search/index.ts tools/codebase_search/core.ts tools/codebase_search/types.ts tools/codebase_search/prompts.ts tools/codebase_search/anthropic.ts tools/codebase_search/openai.ts tools/codebase_search/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts git/index.ts git/client.ts git/config.ts git/types.ts tools/browser/index.ts tools/browser/core.ts tools/browser/types.ts tools/browser/prompts.ts tools/browser/anthropic.ts tools/browser/openai.ts tools/browser/vercel.ts tools/browser/live.ts tools/browser/errors.ts tools/browser/profiles/index.ts tools/browser/profiles/core.ts tools/browser/profiles/types.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve",
    prepare: "npm run build",
    typecheck: "tsc --noEmit",
    lint: "eslint .",
    test: "vitest run",
    "test:watch": "vitest watch",
    "test:anthropic": "vitest run anthropic",
    "test:openai": "vitest run openai",
    "test:vercel": "vitest run vercel",
    "test:git": "vitest run git",
    "test:browser": "vitest run browser",
    "test:agent": "npx tsx tests/fullAgentTest.ts",
    "test:integration": "npx tsx tests/fullIntegrationTest.ts",
    "test:e2e": "vitest run --config vitest.e2e.config.ts",
    "release:patch": "npm version patch && npm publish",
    "release:minor": "npm version minor && npm publish",
    "release:major": "npm version major && npm publish"
  },
  keywords: [
    "morph",
    "fast-apply",
    "cli",
    "sdk",
    "edit-file"
  ],
  engines: {
    node: ">=18"
  },
  license: "MIT",
  dependencies: {
    "@vscode/ripgrep": "^1.17.0",
    ai: ">=5.0.0",
    diff: "^7.0.0",
    "isomorphic-git": "^1.25.10",
    openai: "^4.52.7",
    zod: ">=3.23.0"
  },
  devDependencies: {
    "@ai-sdk/anthropic": "^2.0.70",
    "@ai-sdk/openai": "^2.0.35",
    "@anthropic-ai/sdk": "^0.30.1",
    "@google/generative-ai": "^0.24.1",
    "@types/diff": "^7.0.2",
    "@types/node": "^20.14.10",
    "@typescript-eslint/eslint-plugin": "^7.18.0",
    "@typescript-eslint/parser": "^7.18.0",
    dotenv: "^16.4.5",
    eslint: "^8.57.0",
    shx: "^0.3.4",
    tsup: "^8.5.0",
    tsx: "^4.16.2",
    typescript: "^5.5.4",
    vitest: "^2.1.6"
  },
  peerDependencies: {
    "@anthropic-ai/sdk": ">=0.25.0",
    "@google/generative-ai": ">=0.21.0",
    ai: ">=5.0.0",
    zod: ">=3.23.0"
  },
  peerDependenciesMeta: {
    "@anthropic-ai/sdk": {
      optional: true
    },
    "@google/generative-ai": {
      optional: true
    },
    ai: {
      optional: true
    },
    zod: {
      optional: true
    }
  },
  publishConfig: {
    access: "public"
  }
};

// version.ts
var SDK_VERSION = package_default.version;

// 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;
  options = { ...options, headers: { "X-Morph-SDK-Version": SDK_VERSION, ...options.headers } };
  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));
}

// logger.ts
var MorphLogger = class {
  enabled;
  fileStream;
  /** Resolves once the file stream is initialized (or immediately if no file logging). */
  ready;
  constructor() {
    this.enabled = typeof process !== "undefined" && (process.env.MORPH_DEBUG === "1" || !!process.env.MORPH_LOG_FILE);
    this.fileStream = null;
    const f = typeof process !== "undefined" ? process.env.MORPH_LOG_FILE : void 0;
    if (f) {
      this.ready = import("fs").then((fs) => {
        this.fileStream = fs.createWriteStream(f, { flags: "a" });
      }).catch(() => {
      });
    } else {
      this.ready = Promise.resolve();
    }
  }
  debug(component, msg, data) {
    this._log("debug", component, msg, data);
  }
  info(component, msg, data) {
    this._log("info", component, msg, data);
  }
  warn(component, msg, data) {
    this._log("warn", component, msg, data);
  }
  error(component, msg, data) {
    this._log("error", component, msg, data);
  }
  enable() {
    this.enabled = true;
  }
  get isEnabled() {
    return this.enabled;
  }
  _log(level, component, msg, data) {
    if (level !== "error" && !this.enabled) return;
    const ts = (/* @__PURE__ */ new Date()).toISOString();
    const prefix = `[${ts}] [${level.toUpperCase()}] [${component}]`;
    console.error(data ? `${prefix} ${msg} ${JSON.stringify(data)}` : `${prefix} ${msg}`);
    this.fileStream?.write(JSON.stringify({ ts, level, component, msg, ...data && { data } }) + "\n");
  }
};
var logger = new MorphLogger();

// 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
    };
    logger.debug("ModelRouter", "request", { provider: this.provider, mode, input_len: input.input.length, url });
    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
      };
      logger.debug("ModelRouter", "selected", { provider: this.provider, model: apiResult.model, confidence: apiResult.confidence });
      return result;
    } catch (error) {
      logger.error("ModelRouter", "error", { provider: this.provider, error: error instanceof Error ? error.message : String(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
    };
    logger.debug("RawRouter", "request", { mode, input_len: input.input.length, url });
    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
      };
      logger.debug("RawRouter", "classified", { difficulty });
      return result;
    } catch (error) {
      logger.error("RawRouter", "error", { error: error instanceof Error ? error.message : String(error) });
      throw error;
    }
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AnthropicRouter,
  GeminiRouter,
  OpenAIRouter,
  RawRouter
});
//# sourceMappingURL=core.cjs.map