import {
  createGitHubSearchTool,
  createWarpGrepTool
} from "./chunk-TOL62PTK.js";
import {
  createGitHubSearchTool as createGitHubSearchTool3,
  createWarpGrepTool as createWarpGrepTool3
} from "./chunk-22QLJ2YB.js";
import {
  createGitHubSearchTool as createGitHubSearchTool2,
  createWarpGrepTool as createWarpGrepTool2
} from "./chunk-PGQQKNPT.js";
import {
  createCodebaseSearchTool as createCodebaseSearchTool3
} from "./chunk-PPXY4ZCE.js";
import {
  createCodebaseSearchTool as createCodebaseSearchTool2
} from "./chunk-43MMMNOD.js";
import {
  createCodebaseSearchTool
} from "./chunk-BUS463TO.js";
import {
  CodebaseSearchClient
} from "./chunk-S4IHNTCC.js";
import {
  createEditFileTool
} from "./chunk-7JVW5IHP.js";
import {
  createEditFileTool as createEditFileTool3
} from "./chunk-23FOG3FG.js";
import {
  createEditFileTool as createEditFileTool2
} from "./chunk-NICCCJAA.js";
import {
  FastApplyClient
} from "./chunk-SFIMDGVL.js";
import {
  BrowserClient
} from "./chunk-RDMI5MI7.js";
import {
  createExploreSubagent
} from "./chunk-GF3IGJ77.js";
import {
  createExploreSubagent as createExploreSubagent2
} from "./chunk-S6UA55CG.js";
import {
  WarpGrepClient
} from "./chunk-75F5XTPD.js";
import {
  AnthropicRouter,
  GeminiRouter,
  OpenAIRouter,
  RawRouter
} from "./chunk-EV4HZQEJ.js";
import {
  CompactClient
} from "./chunk-SCVWDNQP.js";
import {
  logger
} from "./chunk-F3NCFNUX.js";
import {
  MorphGit
} from "./chunk-LE66XCOI.js";

// tools/github/types.ts
var GitHubError = class extends Error {
  /** HTTP status code */
  status;
  /** Error code from API */
  code;
  constructor(message, status, code) {
    super(message);
    this.name = "GitHubError";
    this.status = status;
    this.code = code;
  }
};
var NoInstallationError = class extends GitHubError {
  constructor(message = "No GitHub installation found. Connect GitHub at morphllm.com/dashboard/integrations/github") {
    super(message, 404, "NO_INSTALLATION");
  }
};
var NotFoundError = class extends GitHubError {
  constructor(resource) {
    super(`${resource} not found`, 404, "NOT_FOUND");
  }
};
var PermissionError = class extends GitHubError {
  constructor(message = "Insufficient permissions for this operation") {
    super(message, 403, "PERMISSION_DENIED");
  }
};

// tools/github/core.ts
var DEFAULT_BASE_URL = "https://api.morphllm.com";
var DEFAULT_TIMEOUT = 3e4;
var GitHubClient = class {
  apiKey;
  baseUrl;
  timeout;
  debug;
  defaultInstallationId;
  /** Installation operations */
  installations;
  /** Repository operations */
  repos;
  /** Project operations (monorepo sub-projects) */
  projects;
  /** Pull request operations */
  pullRequests;
  /** Deployment operations */
  deployments;
  /** Comment operations */
  comments;
  /** Check run operations */
  checkRuns;
  /**
   * Get the GitHub App installation URL.
   * Users visit this URL once to install the Morph GitHub App on their account/org.
   */
  getInstallUrl() {
    return "https://github.com/apps/morph-subagents/installations/new";
  }
  constructor(config = {}) {
    this.apiKey = config.apiKey || process.env.MORPH_API_KEY || "";
    this.baseUrl = config.baseUrl || DEFAULT_BASE_URL;
    this.timeout = config.timeout || DEFAULT_TIMEOUT;
    this.debug = config.debug || false;
    this.defaultInstallationId = config.installationId;
    if (!this.apiKey) {
      throw new Error("API key required. Set MORPH_API_KEY or pass apiKey in config.");
    }
    this.installations = {
      list: this.listInstallations.bind(this),
      get: this.getInstallation.bind(this),
      update: this.updateInstallation.bind(this),
      disconnect: this.disconnectInstallation.bind(this)
    };
    this.repos = {
      list: this.listRepos.bind(this),
      get: this.getRepo.bind(this),
      update: this.updateRepo.bind(this),
      remove: this.removeRepo.bind(this),
      sync: this.syncRepos.bind(this)
    };
    this.projects = {
      list: this.listProjects.bind(this),
      create: this.createProject.bind(this),
      update: this.updateProject.bind(this),
      delete: this.deleteProject.bind(this)
    };
    this.pullRequests = {
      list: this.listPullRequests.bind(this),
      get: this.getPullRequest.bind(this)
    };
    this.deployments = {
      list: this.listDeployments.bind(this)
    };
    this.comments = {
      list: this.listComments.bind(this),
      create: this.createComment.bind(this),
      update: this.updateComment.bind(this),
      delete: this.deleteComment.bind(this)
    };
    this.checkRuns = {
      create: this.createCheckRun.bind(this),
      update: this.updateCheckRun.bind(this)
    };
  }
  /**
   * Make an authenticated API request
   */
  async request(method, path, body) {
    const url = `${this.baseUrl}${path}`;
    if (this.debug) {
      console.log(`[GitHub SDK] ${method} ${path}`, body || "");
    }
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.timeout);
    try {
      const response = await fetch(url, {
        method,
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${this.apiKey}`
        },
        body: body ? JSON.stringify(body) : void 0,
        signal: controller.signal
      });
      clearTimeout(timeoutId);
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        const message = errorData.error || errorData.detail || errorData.message || response.statusText;
        if (this.debug) {
          console.error(`[GitHub SDK] Error ${response.status}:`, message);
        }
        if (response.status === 404) {
          if (message.includes("installation")) {
            throw new NoInstallationError(message);
          }
          throw new NotFoundError(message);
        }
        if (response.status === 403) {
          throw new PermissionError(message);
        }
        throw new GitHubError(message, response.status, errorData.code);
      }
      const data = await response.json();
      if (this.debug) {
        console.log(`[GitHub SDK] Response:`, JSON.stringify(data).slice(0, 200));
      }
      return data;
    } catch (error) {
      clearTimeout(timeoutId);
      if (error instanceof GitHubError) {
        throw error;
      }
      if (error instanceof Error && error.name === "AbortError") {
        throw new GitHubError("Request timeout", 408, "TIMEOUT");
      }
      throw new GitHubError(
        error instanceof Error ? error.message : "Unknown error",
        500,
        "UNKNOWN"
      );
    }
  }
  /**
   * Get the installation ID to use for a request
   */
  getInstallationId(input) {
    return input?.installationId || this.defaultInstallationId;
  }
  // ==========================================================================
  // Installations
  // ==========================================================================
  async listInstallations() {
    return this.request("GET", "/api/v1/github/installations");
  }
  async getInstallation(installationId) {
    return this.request("GET", `/api/v1/github/installations/${installationId}`);
  }
  async updateInstallation(input) {
    if (this.debug) console.log("[GitHub SDK] updateInstallation", input.installationId);
    const { installationId, ...body } = input;
    return this.request("PATCH", `/api/v1/github/installations/${installationId}`, body);
  }
  async disconnectInstallation(installationId) {
    if (this.debug) console.log("[GitHub SDK] disconnectInstallation", installationId);
    return this.request("DELETE", `/api/v1/github/installations/${installationId}`);
  }
  // ==========================================================================
  // Repositories
  // ==========================================================================
  async listRepos(input) {
    const installationId = input.installationId || this.defaultInstallationId;
    if (!installationId) {
      throw new NoInstallationError("installationId required. Call installations.list() first.");
    }
    return this.request("GET", `/api/v1/github/installations/${installationId}/repos`);
  }
  async getRepo(repoId) {
    if (this.debug) console.log("[GitHub SDK] getRepo", repoId);
    return this.request("GET", `/api/v1/github/repos/${repoId}`);
  }
  async updateRepo(input) {
    if (this.debug) console.log("[GitHub SDK] updateRepo", input.repoId);
    const { repoId, ...body } = input;
    return this.request("PATCH", `/api/v1/github/repos/${repoId}`, body);
  }
  async removeRepo(repoId) {
    if (this.debug) console.log("[GitHub SDK] removeRepo", repoId);
    return this.request("DELETE", `/api/v1/github/repos/${repoId}`);
  }
  async syncRepos(input) {
    const installationId = input.installationId || this.defaultInstallationId;
    if (!installationId) {
      throw new NoInstallationError("installationId required. Call installations.list() first.");
    }
    if (this.debug) console.log("[GitHub SDK] syncRepos", installationId);
    return this.request("POST", `/api/v1/github/installations/${installationId}/repos/sync`);
  }
  // ==========================================================================
  // Projects (monorepo sub-projects)
  // ==========================================================================
  async listProjects(input) {
    if (this.debug) console.log("[GitHub SDK] listProjects", input.repoId);
    return this.request("GET", `/api/v1/github/repos/${input.repoId}/projects`);
  }
  async createProject(input) {
    if (this.debug) console.log("[GitHub SDK] createProject", input.repoId, input.name);
    const { repoId, ...body } = input;
    return this.request("POST", `/api/v1/github/repos/${repoId}/projects`, body);
  }
  async updateProject(input) {
    if (this.debug) console.log("[GitHub SDK] updateProject", input.projectId);
    const { projectId, ...body } = input;
    return this.request("PATCH", `/api/v1/github/projects/${projectId}`, body);
  }
  async deleteProject(projectId) {
    if (this.debug) console.log("[GitHub SDK] deleteProject", projectId);
    return this.request("DELETE", `/api/v1/github/projects/${projectId}`);
  }
  // ==========================================================================
  // Pull Requests
  // ==========================================================================
  async listPullRequests(input) {
    const installationId = this.getInstallationId(input);
    const params = new URLSearchParams({
      owner: input.owner,
      repo: input.repo,
      ...input.state && { state: input.state },
      ...installationId && { installationId }
    });
    return this.request("GET", `/api/v1/github/pulls?${params}`);
  }
  async getPullRequest(input) {
    const installationId = this.getInstallationId(input);
    const params = new URLSearchParams({
      owner: input.owner,
      repo: input.repo,
      ...installationId && { installationId }
    });
    return this.request(
      "GET",
      `/api/v1/github/pulls/${input.number}?${params}`
    );
  }
  // ==========================================================================
  // Deployments
  // ==========================================================================
  async listDeployments(input) {
    const installationId = this.getInstallationId(input);
    const params = new URLSearchParams({
      owner: input.owner,
      repo: input.repo,
      ...input.sha && { sha: input.sha },
      ...input.environment && { environment: input.environment },
      ...installationId && { installationId }
    });
    return this.request("GET", `/api/v1/github/deployments?${params}`);
  }
  // ==========================================================================
  // Comments
  // ==========================================================================
  async listComments(input) {
    const installationId = this.getInstallationId(input);
    const params = new URLSearchParams({
      owner: input.owner,
      repo: input.repo,
      pr: String(input.pr),
      ...installationId && { installationId }
    });
    return this.request("GET", `/api/v1/github/comments?${params}`);
  }
  async createComment(input) {
    const installationId = this.getInstallationId(input);
    return this.request("POST", "/api/v1/github/comments", {
      owner: input.owner,
      repo: input.repo,
      pr: input.pr,
      body: input.body,
      ...installationId && { installationId }
    });
  }
  async updateComment(input) {
    const installationId = this.getInstallationId(input);
    return this.request("PATCH", `/api/v1/github/comments/${input.commentId}`, {
      owner: input.owner,
      repo: input.repo,
      body: input.body,
      ...installationId && { installationId }
    });
  }
  async deleteComment(input) {
    const installationId = this.getInstallationId(input);
    const params = new URLSearchParams({
      owner: input.owner,
      repo: input.repo,
      ...installationId && { installationId }
    });
    await this.request("DELETE", `/api/v1/github/comments/${input.commentId}?${params}`);
  }
  // ==========================================================================
  // Check Runs
  // ==========================================================================
  async createCheckRun(input) {
    const installationId = this.getInstallationId(input);
    return this.request("POST", "/api/v1/github/check-runs", {
      owner: input.owner,
      repo: input.repo,
      sha: input.sha,
      name: input.name,
      status: input.status,
      ...input.title && { title: input.title },
      ...input.summary && { summary: input.summary },
      ...installationId && { installationId }
    });
  }
  async updateCheckRun(input) {
    const installationId = this.getInstallationId(input);
    return this.request("PATCH", `/api/v1/github/check-runs/${input.checkRunId}`, {
      owner: input.owner,
      repo: input.repo,
      ...input.status && { status: input.status },
      ...input.conclusion && { conclusion: input.conclusion },
      ...input.title && { title: input.title },
      ...input.summary && { summary: input.summary },
      ...input.text && { text: input.text },
      ...installationId && { installationId }
    });
  }
};

// factories/openai.ts
var OpenAIToolFactory = class {
  constructor(config) {
    this.config = config;
  }
  /**
   * Create an OpenAI-compatible warp grep tool
   * 
   * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
   * @returns OpenAI ChatCompletionTool with execute and formatResult methods
   */
  createWarpGrepTool(toolConfig) {
    return createWarpGrepTool({
      ...toolConfig,
      morphApiKey: this.config.apiKey
    });
  }
  /**
   * Create an OpenAI-compatible codebase search tool
   * 
   * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)
   * @returns OpenAI ChatCompletionTool with execute and formatResult methods
   */
  createCodebaseSearchTool(toolConfig) {
    return createCodebaseSearchTool({
      ...toolConfig,
      apiKey: this.config.apiKey
    });
  }
  /**
   * Create an OpenAI-compatible edit file tool
   * 
   * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
   * @returns OpenAI ChatCompletionTool with execute and formatResult methods
   */
  createEditFileTool(toolConfig = {}) {
    return createEditFileTool({
      ...toolConfig,
      morphApiKey: this.config.apiKey
    });
  }
  /**
   * Create an OpenAI-compatible GitHub search tool
   *
   * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
   * @returns OpenAI ChatCompletionTool with execute and formatResult methods
   */
  createGitHubSearchTool(toolConfig) {
    return createGitHubSearchTool({
      ...toolConfig,
      morphApiKey: this.config.apiKey
    });
  }
};

// factories/anthropic.ts
var AnthropicToolFactory = class {
  constructor(config) {
    this.config = config;
  }
  /**
   * Create an Anthropic-compatible warp grep tool
   * 
   * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
   * @returns Anthropic Tool with execute and formatResult methods
   */
  createWarpGrepTool(toolConfig) {
    return createWarpGrepTool2({
      ...toolConfig,
      morphApiKey: this.config.apiKey
    });
  }
  /**
   * Create an Anthropic-compatible codebase search tool
   * 
   * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)
   * @returns Anthropic Tool with execute and formatResult methods
   */
  createCodebaseSearchTool(toolConfig) {
    return createCodebaseSearchTool2({
      ...toolConfig,
      apiKey: this.config.apiKey
    });
  }
  /**
   * Create an Anthropic-compatible edit file tool
   * 
   * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
   * @returns Anthropic Tool with execute and formatResult methods
   */
  createEditFileTool(toolConfig = {}) {
    return createEditFileTool2({
      ...toolConfig,
      morphApiKey: this.config.apiKey
    });
  }
  /**
   * Create an Anthropic-compatible GitHub search tool
   *
   * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
   * @returns Anthropic Tool with execute and formatResult methods
   */
  createGitHubSearchTool(toolConfig) {
    return createGitHubSearchTool2({
      ...toolConfig,
      morphApiKey: this.config.apiKey
    });
  }
  /**
   * Create an Explore subagent that searches the codebase and returns summaries
   *
   * @param config - Subagent configuration including client and model (morphApiKey inherited from MorphClient)
   * @returns Explore subagent with .tool, .run(), and .stream() methods
   */
  createExploreSubagent(config) {
    return createExploreSubagent({
      ...config,
      morphApiKey: this.config.apiKey
    });
  }
};

// factories/vercel.ts
var VercelToolFactory = class {
  constructor(config) {
    this.config = config;
  }
  /**
   * Create a Vercel AI SDK-compatible warp grep tool
   * 
   * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
   * @returns Vercel AI SDK tool
   */
  createWarpGrepTool(toolConfig) {
    return createWarpGrepTool3({
      ...toolConfig,
      morphApiKey: this.config.apiKey
    });
  }
  /**
   * Create a Vercel AI SDK-compatible codebase search tool
   * 
   * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)
   * @returns Vercel AI SDK tool
   */
  createCodebaseSearchTool(toolConfig) {
    return createCodebaseSearchTool3({
      ...toolConfig,
      apiKey: this.config.apiKey
    });
  }
  /**
   * Create a Vercel AI SDK-compatible edit file tool
   * 
   * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
   * @returns Vercel AI SDK tool
   */
  createEditFileTool(toolConfig = {}) {
    return createEditFileTool3({
      ...toolConfig,
      morphApiKey: this.config.apiKey
    });
  }
  /**
   * Create a Vercel AI SDK-compatible GitHub search tool
   *
   * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
   * @returns Vercel AI SDK tool
   */
  createGitHubSearchTool(toolConfig) {
    return createGitHubSearchTool3({
      ...toolConfig,
      morphApiKey: this.config.apiKey
    });
  }
  /**
   * Create an Explore subagent that searches the codebase and returns summaries
   *
   * @param config - Subagent configuration including model (morphApiKey inherited from MorphClient)
   * @returns Explore subagent with .tool, .run(), and .stream() methods
   */
  createExploreSubagent(config) {
    return createExploreSubagent2({
      ...config,
      morphApiKey: this.config.apiKey
    });
  }
};

// client.ts
var MorphClient = class {
  /** Client configuration */
  config;
  /** FastApply tool for editing files with AI-powered merge */
  fastApply;
  /** CodebaseSearch tool for semantic code search */
  codebaseSearch;
  /** WarpGrep tool for fast code search using ripgrep */
  warpGrep;
  /** Browser tool for AI-powered browser automation */
  browser;
  /** GitHub tool for PR context, comments, and check runs */
  github;
  /** Git tool for version control operations */
  git;
  /** Model routers for intelligent model selection */
  routers;
  /** OpenAI-compatible tool factories */
  openai;
  /** Anthropic-compatible tool factories */
  anthropic;
  /** Vercel AI SDK tool factories */
  vercel;
  /** Compact context with line ranges */
  compact;
  /**
   * Create a new Morph SDK client
   * 
   * @param config - Client configuration (apiKey, debug, timeout, retryConfig)
   * 
   * @example
   * ```typescript
   * const morph = new MorphClient({ 
   *   apiKey: process.env.MORPH_API_KEY,
   *   debug: true,
   *   timeout: 60000
   * });
   * ```
   */
  constructor(config = {}) {
    this.config = config;
    if (config.debug) {
      logger.enable();
    }
    logger.debug("MorphClient", "initialized", { debug: !!config.debug, timeout: config.timeout });
    this.fastApply = new FastApplyClient({
      apiKey: config.apiKey,
      debug: config.debug,
      timeout: config.timeout,
      retryConfig: config.retryConfig
    });
    this.codebaseSearch = new CodebaseSearchClient({
      apiKey: config.apiKey,
      debug: config.debug,
      timeout: config.timeout,
      retryConfig: config.retryConfig
    });
    this.warpGrep = new WarpGrepClient({
      morphApiKey: config.apiKey,
      debug: config.debug,
      timeout: config.timeout,
      retryConfig: config.retryConfig
    });
    this.browser = new BrowserClient({
      apiKey: config.apiKey,
      debug: config.debug,
      timeout: config.timeout,
      retryConfig: config.retryConfig
    });
    this.github = new GitHubClient({
      apiKey: config.apiKey,
      debug: config.debug,
      timeout: config.timeout,
      installationId: config.github?.installationId
    });
    this.git = new MorphGit({
      apiKey: config.apiKey,
      retryConfig: config.retryConfig
    });
    this.routers = {
      openai: new OpenAIRouter({
        apiKey: config.apiKey,
        debug: config.debug,
        timeout: config.timeout,
        retryConfig: config.retryConfig
      }),
      anthropic: new AnthropicRouter({
        apiKey: config.apiKey,
        debug: config.debug,
        timeout: config.timeout,
        retryConfig: config.retryConfig
      }),
      gemini: new GeminiRouter({
        apiKey: config.apiKey,
        debug: config.debug,
        timeout: config.timeout,
        retryConfig: config.retryConfig
      }),
      raw: new RawRouter({
        apiKey: config.apiKey,
        debug: config.debug,
        timeout: config.timeout,
        retryConfig: config.retryConfig
      })
    };
    const compactClient = new CompactClient({
      morphApiKey: config.apiKey,
      timeout: config.timeout,
      retryConfig: config.retryConfig,
      debug: config.debug
    });
    this.compact = compactClient.compact.bind(compactClient);
    this.openai = new OpenAIToolFactory(config);
    this.anthropic = new AnthropicToolFactory(config);
    this.vercel = new VercelToolFactory(config);
  }
};

export {
  GitHubError,
  NoInstallationError,
  NotFoundError,
  PermissionError,
  GitHubClient,
  OpenAIToolFactory,
  AnthropicToolFactory,
  VercelToolFactory,
  MorphClient
};
//# sourceMappingURL=chunk-G4GCW3NI.js.map