"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);

// tools/browser/anthropic.ts
var anthropic_exports = {};
__export(anthropic_exports, {
  browserTool: () => browserTool,
  createBrowserTool: () => createBrowserTool
});
module.exports = __toCommonJS(anthropic_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));
}

// tools/browser/profiles/core.ts
var DEFAULT_API_URL = process.env.MORPH_ENVIRONMENT === "DEV" ? "http://localhost:8000" : "https://browser.morphllm.com";

// tools/browser/core.ts
var DEFAULT_CONFIG = {
  apiUrl: process.env.MORPH_ENVIRONMENT === "DEV" ? "http://localhost:8000" : "https://browser.morphllm.com",
  timeout: 1e6,
  // 10 minutes for complex tasks
  debug: false
};
async function executeBrowserTask(input, config = {}) {
  const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;
  const timeout = config.timeout || DEFAULT_CONFIG.timeout;
  const debug = config.debug || false;
  if (!input.task || input.task.trim().length === 0) {
    return {
      success: false,
      error: 'Task description is required. Example: "Go to example.com and click the login button"'
    };
  }
  if (input.maxSteps !== void 0 && (input.maxSteps < 1 || input.maxSteps > 50)) {
    return {
      success: false,
      error: "maxSteps must be between 1 and 50. Use more steps for complex multi-page flows."
    };
  }
  if (debug) {
    console.log(`[Browser] Task: "${input.task.slice(0, 60)}..." url=${input.url || "none"} maxSteps=${input.maxSteps ?? 10}`);
    console.log(`[Browser] Recording: ${input.recordVideo ? "yes" : "no"} | Calling ${apiUrl}/browser-task`);
  }
  const startTime = Date.now();
  try {
    const headers = { "Content-Type": "application/json" };
    if (config.apiKey) headers["Authorization"] = `Bearer ${config.apiKey}`;
    const fetchPromise = fetchWithRetry(
      `${apiUrl}/browser-task`,
      {
        method: "POST",
        headers,
        body: JSON.stringify({
          task: input.task,
          url: input.url,
          max_steps: input.maxSteps ?? 10,
          model: input.model ?? "morph-computer-use-v0",
          viewport_width: input.viewportWidth ?? 1280,
          viewport_height: input.viewportHeight ?? 720,
          external_id: input.externalId,
          repo_id: input.repoId,
          commit_id: input.commitId,
          record_video: input.recordVideo ?? false,
          video_width: input.videoWidth ?? input.viewportWidth ?? 1280,
          video_height: input.videoHeight ?? input.viewportHeight ?? 720,
          allow_resizing: input.allowResizing ?? false,
          structured_output: input.structuredOutput,
          auth: input.auth,
          profile_id: input.profileId,
          force_query_params: input.forceQueryParams
        })
      },
      config.retryConfig
    );
    const response = await withTimeout(
      fetchPromise,
      timeout,
      `Browser task timed out after ${timeout}ms. Consider increasing timeout or reducing maxSteps.`
    );
    if (!response.ok) {
      const errorText = await response.text().catch(() => response.statusText);
      if (debug) console.error(`[Browser] Error: ${response.status} - ${errorText}`);
      throw new Error(`HTTP ${response.status}: ${errorText}`);
    }
    const result = mapTaskResult(await response.json());
    const elapsed = Date.now() - startTime;
    if (debug) {
      console.log(`[Browser] \u2705 ${result.success ? "Success" : "Failed"} in ${elapsed}ms | steps=${result.stepsTaken ?? 0} recordingId=${result.recordingId ?? "none"}`);
    }
    return result;
  } catch (error) {
    if (error instanceof Error) {
      if (error.message.includes("ECONNREFUSED") || error.message.includes("fetch failed")) {
        return {
          success: false,
          error: `Cannot connect to browser worker at ${apiUrl}. Ensure the service is running and accessible. For local dev, set MORPH_ENVIRONMENT=DEV.`
        };
      }
      return {
        success: false,
        error: error.message
      };
    }
    return {
      success: false,
      error: String(error)
    };
  }
}
function mapTaskResult(api) {
  if (!api || typeof api !== "object") {
    return api;
  }
  return {
    success: api.success,
    result: api.result,
    error: api.error,
    stepsTaken: api.steps_taken,
    executionTimeMs: api.execution_time_ms,
    urls: api.urls,
    actionNames: api.action_names,
    errors: api.errors,
    modelActions: api.model_actions,
    isDone: api.is_done,
    actionHistory: api.action_history,
    actionResults: api.action_results,
    hasErrors: api.has_errors,
    numberOfSteps: api.number_of_steps,
    judgement: api.judgement,
    isValidated: api.is_validated,
    replayId: api.replay_id,
    replayUrl: api.replay_url,
    recordingId: api.recording_id,
    recordingStatus: api.recording_status,
    taskId: api.task_id,
    status: api.status,
    output: api.output,
    debugUrl: api.debug_url
  };
}

// tools/browser/prompts.ts
var BROWSER_TOOL_DESCRIPTION = `Test and verify your implemented code in a live browser. This tool executes natural language test instructions and returns a video recording plus detailed logs to help you debug issues.

## When to Use
Use this AFTER coding is complete to verify your implementation:
- You've finished writing/modifying code and need to verify it works
- You need to test user interactions end-to-end (clicks, forms, navigation)
- You want to catch runtime errors, console warnings, or network failures
- You need visual confirmation that UI elements render and behave correctly

## What You Get Back
The tool returns debugging artifacts to help you identify and fix issues:
- **Video recording**: Watch exactly what happened in the browser session
- **Console logs**: All console.log, warnings, and errors with timestamps
- **Network logs**: Failed requests, 404s, API errors with screenshots
- **Error screenshots**: Visual snapshots captured when errors occur

## How to Write Good Tests
Be specific about the user journey you're testing:
\u274C Bad: "Test the login feature"
\u2705 Good: "Navigate to /login, enter 'test@example.com' and 'password123', click the Login button, verify we reach the /dashboard page"

Include verification steps:
\u2705 "Click the Add Item button, verify the item appears in the list"
\u2705 "Submit the form, verify a success message is displayed"

## Iterating on Failures
1. Run the test and review the video + logs
2. Identify the specific issue (console error, failed request, wrong behavior)
3. Fix the code based on the evidence
4. Re-run the test to verify the fix
5. Repeat until test passes

## Requirements
- **URL**: Must be publicly accessible (use tunnels like ngrok, Cloudflare, or deploy to staging)
- **Timing**: Use this after implementation, not during coding
- **Complexity**: Set maxSteps higher (20-30) for multi-step user workflows`;
var BROWSER_SYSTEM_PROMPT = `You are an AI agent designed to automate browser tasks to accomplish the <user_request>. Respond with a valid JSON object in the format: {"thinking": "Reason step-by-step about your current state, history, and the user request to decide your next goal and action. Analyze the browser state and screenshot to confirm the outcome of your last action.", "evaluation_previous_goal": "A concise, one-sentence evaluation of your last action's outcome (e.g., Success, Failure, or Uncertain).", "memory": "1-3 sentences summarizing key information and progress so far. This helps you track progress across multiple steps (e.g., items collected, pages visited).", "next_goal": "A clear, one-sentence description of your immediate next objective.", "action": [{"action_name": {"parameter": "value"}}]}`;

// tools/browser/anthropic.ts
var browserTool = {
  name: "browser_task",
  description: BROWSER_TOOL_DESCRIPTION,
  input_schema: {
    type: "object",
    properties: {
      task: {
        type: "string",
        description: 'Natural language description of what to do (e.g., "Test checkout flow for buying a pineapple")'
      },
      url: {
        type: "string",
        description: "Starting URL (e.g., https://3000-xyz.e2b.dev). Required if navigating to a specific page."
      },
      maxSteps: {
        type: "number",
        description: "Maximum number of browser actions to take (1-50). Default: 10. Use 15-30 for complex flows.",
        default: 10
      },
      region: {
        type: "string",
        enum: ["sfo", "lon"],
        description: "Browserless region: sfo (US West Coast) or lon (Europe). Default: sfo.",
        default: "sfo"
      }
    },
    required: ["task"]
  }
};
function formatResult(result) {
  if (result.success) {
    const parts = [
      "\u2705 Browser task completed successfully",
      `Steps taken: ${result.stepsTaken ?? 0}`,
      result.executionTimeMs ? `Execution time: ${result.executionTimeMs}ms` : null,
      "",
      "Result:",
      result.result || "Task completed"
    ];
    return parts.filter(Boolean).join("\n");
  }
  return `\u274C Browser task failed: ${result.error || "Unknown error"}`;
}
function createBrowserTool(config) {
  return Object.assign({}, browserTool, {
    execute: async (input) => {
      return executeBrowserTask(input, config);
    },
    formatResult: (result) => {
      return formatResult(result);
    },
    getSystemPrompt: () => {
      return BROWSER_SYSTEM_PROMPT;
    }
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  browserTool,
  createBrowserTool
});
//# sourceMappingURL=anthropic.cjs.map