@morphllm/morphsdk 0.2.18 → 0.2.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anthropic-CknfcMoO.d.ts +64 -0
- package/dist/{chunk-UFIIEUGW.js → chunk-OSJBHKA2.js} +9 -9
- package/dist/{chunk-VONZKK4S.js → chunk-YVGRWE7D.js} +1 -1
- package/dist/chunk-YVGRWE7D.js.map +1 -0
- package/dist/client.d.ts +114 -0
- package/dist/client.js +4 -4
- package/dist/git/client.d.ts +230 -0
- package/dist/git/config.d.ts +11 -0
- package/dist/git/index.d.ts +5 -0
- package/dist/git/types.d.ts +91 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +10 -10
- package/dist/modelrouter/core.d.ts +56 -0
- package/dist/modelrouter/index.d.ts +2 -0
- package/dist/modelrouter/types.d.ts +35 -0
- package/dist/openai-BkKsS30n.d.ts +111 -0
- package/dist/tools/browser/anthropic.d.ts +51 -0
- package/dist/tools/browser/core.d.ts +196 -0
- package/dist/tools/browser/index.d.ts +72 -0
- package/dist/tools/browser/openai.d.ts +69 -0
- package/dist/tools/browser/prompts.d.ts +7 -0
- package/dist/tools/browser/types.d.ts +227 -0
- package/dist/tools/browser/vercel.cjs +1 -1
- package/dist/tools/browser/vercel.cjs.map +1 -1
- package/dist/tools/browser/vercel.d.ts +69 -0
- package/dist/tools/browser/vercel.js +1 -1
- package/dist/tools/browser/vercel.js.map +1 -1
- package/dist/tools/codebase_search/anthropic.d.ts +40 -0
- package/dist/tools/codebase_search/core.d.ts +40 -0
- package/dist/tools/codebase_search/index.cjs.map +1 -1
- package/dist/tools/codebase_search/index.d.ts +10 -0
- package/dist/tools/codebase_search/index.js +4 -4
- package/dist/tools/codebase_search/openai.d.ts +87 -0
- package/dist/tools/codebase_search/prompts.d.ts +7 -0
- package/dist/tools/codebase_search/types.d.ts +46 -0
- package/dist/tools/codebase_search/vercel.cjs.map +1 -1
- package/dist/tools/codebase_search/vercel.d.ts +65 -0
- package/dist/tools/codebase_search/vercel.js +1 -1
- package/dist/tools/fastapply/anthropic.d.ts +4 -0
- package/dist/tools/fastapply/core.d.ts +41 -0
- package/dist/tools/fastapply/index.d.ts +10 -0
- package/dist/tools/fastapply/index.js +3 -3
- package/dist/tools/fastapply/openai.d.ts +4 -0
- package/dist/tools/fastapply/prompts.d.ts +7 -0
- package/dist/tools/fastapply/types.d.ts +77 -0
- package/dist/tools/fastapply/vercel.d.ts +4 -0
- package/dist/tools/index.d.ts +10 -0
- package/dist/tools/index.js +3 -3
- package/dist/tools/utils/resilience.d.ts +58 -0
- package/dist/vercel-B1GZ_g9N.d.ts +69 -0
- package/package.json +1 -1
- package/dist/chunk-VONZKK4S.js.map +0 -1
- /package/dist/{chunk-UFIIEUGW.js.map → chunk-OSJBHKA2.js.map} +0 -0
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { RetryConfig } from '../utils/resilience.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Type definitions for browser automation tool
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Available browser automation models
|
|
9
|
+
*/
|
|
10
|
+
type BrowserModel = 'gemini-flash-latest' | 'morph-computer-use-v0';
|
|
11
|
+
/**
|
|
12
|
+
* Configuration for the browser worker service
|
|
13
|
+
*/
|
|
14
|
+
interface BrowserConfig {
|
|
15
|
+
/** Browser worker API URL (default: https://browser.morphllm.com) */
|
|
16
|
+
apiUrl?: string;
|
|
17
|
+
/** Morph API key for authentication (required in production) */
|
|
18
|
+
apiKey?: string;
|
|
19
|
+
/** Request timeout in milliseconds (default: 120000) */
|
|
20
|
+
timeout?: number;
|
|
21
|
+
/** Retry configuration for API calls */
|
|
22
|
+
retryConfig?: RetryConfig;
|
|
23
|
+
/** Enable debug logging (default: false) */
|
|
24
|
+
debug?: boolean;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Input parameters for browser automation task
|
|
28
|
+
*/
|
|
29
|
+
interface BrowserTaskInput {
|
|
30
|
+
/** Natural language description of what to do */
|
|
31
|
+
task: string;
|
|
32
|
+
/** Starting URL (e.g., https://3000-xyz.e2b.dev) */
|
|
33
|
+
url?: string;
|
|
34
|
+
/** Maximum number of browser actions to take (1-50, default: 10) */
|
|
35
|
+
max_steps?: number;
|
|
36
|
+
/** Model to use for task execution (default: morph-computer-use-v0) */
|
|
37
|
+
model?: BrowserModel;
|
|
38
|
+
/** Browserless region: 'sfo' (US West) or 'lon' (Europe) */
|
|
39
|
+
region?: 'sfo' | 'lon';
|
|
40
|
+
/** Enable stealth mode to avoid bot detection (default: true) */
|
|
41
|
+
stealth?: boolean;
|
|
42
|
+
/** Browser viewport width (default: 1280) */
|
|
43
|
+
viewport_width?: number;
|
|
44
|
+
/** Browser viewport height (default: 720) */
|
|
45
|
+
viewport_height?: number;
|
|
46
|
+
/** User-defined reference/tracking ID (e.g., "PR-1234", "jira-PROJ-567") */
|
|
47
|
+
external_id?: string;
|
|
48
|
+
/** Optional repository ID to associate with this session */
|
|
49
|
+
repo_id?: string;
|
|
50
|
+
/** Optional commit UUID to associate with this session */
|
|
51
|
+
commit_id?: string;
|
|
52
|
+
/** Record session video to S3 (default: false) */
|
|
53
|
+
record_video?: boolean;
|
|
54
|
+
/** Video width (default: 1280) */
|
|
55
|
+
video_width?: number;
|
|
56
|
+
/** Video height (default: 720) */
|
|
57
|
+
video_height?: number;
|
|
58
|
+
/** Serialized structured output schema (internal use) */
|
|
59
|
+
structured_output?: string;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Input with Zod schema for structured output
|
|
63
|
+
*/
|
|
64
|
+
interface BrowserTaskInputWithSchema<T> extends Omit<BrowserTaskInput, 'structured_output'> {
|
|
65
|
+
/** Zod schema for structured output */
|
|
66
|
+
schema: any;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Result from executing a browser task
|
|
70
|
+
*/
|
|
71
|
+
interface BrowserTaskResult {
|
|
72
|
+
/** Whether the task completed successfully */
|
|
73
|
+
success: boolean;
|
|
74
|
+
/** Task result or findings */
|
|
75
|
+
result?: string;
|
|
76
|
+
/** Error message if task failed */
|
|
77
|
+
error?: string;
|
|
78
|
+
/** Number of browser actions taken */
|
|
79
|
+
steps_taken?: number;
|
|
80
|
+
/** Total execution time in milliseconds */
|
|
81
|
+
execution_time_ms?: number;
|
|
82
|
+
/** UUID of saved replay record (if session replay enabled) */
|
|
83
|
+
replay_id?: string;
|
|
84
|
+
/** Browserless replay URL (if session replay enabled) */
|
|
85
|
+
replay_url?: string;
|
|
86
|
+
/** Recording ID (if record_video=true) */
|
|
87
|
+
recording_id?: string;
|
|
88
|
+
/** Recording status: PENDING, PROCESSING, COMPLETED, ERROR */
|
|
89
|
+
recording_status?: string;
|
|
90
|
+
/** Task ID for async task tracking */
|
|
91
|
+
task_id?: string;
|
|
92
|
+
/** Task status: pending, running, completed, failed */
|
|
93
|
+
status?: string;
|
|
94
|
+
/** Structured output (JSON string) */
|
|
95
|
+
output?: string;
|
|
96
|
+
/** Live session debug URL for real-time viewing (WebRTC streaming) */
|
|
97
|
+
debugUrl?: string;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Configuration for live session viewing
|
|
101
|
+
*/
|
|
102
|
+
interface LiveSessionOptions {
|
|
103
|
+
/** Enable or disable remote control (default: true for headful, varies for headless) */
|
|
104
|
+
interactive?: boolean;
|
|
105
|
+
/** UI theme: 'dark' or 'light' (headless only, default: 'dark') */
|
|
106
|
+
theme?: 'dark' | 'light';
|
|
107
|
+
/** Show or hide navigation controls (headless only, default: true) */
|
|
108
|
+
showControls?: boolean;
|
|
109
|
+
/** Focus view on specific page/tab ID (headless only) */
|
|
110
|
+
pageId?: string;
|
|
111
|
+
/** Display specific tab by index (headless only) */
|
|
112
|
+
pageIndex?: string;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Configuration for iframe generation
|
|
116
|
+
*/
|
|
117
|
+
interface IframeOptions extends LiveSessionOptions {
|
|
118
|
+
/** Iframe width (default: '100%') */
|
|
119
|
+
width?: string | number;
|
|
120
|
+
/** Iframe height (default: '600px') */
|
|
121
|
+
height?: string | number;
|
|
122
|
+
/** Additional inline styles */
|
|
123
|
+
style?: string;
|
|
124
|
+
/** CSS class name */
|
|
125
|
+
className?: string;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Task result with convenience methods for async execution
|
|
129
|
+
*/
|
|
130
|
+
interface BrowserTaskWithPromise extends BrowserTaskResult {
|
|
131
|
+
task_id: string;
|
|
132
|
+
/** Live URL to watch task execution in real-time */
|
|
133
|
+
liveUrl: string;
|
|
134
|
+
/** Wait for task completion */
|
|
135
|
+
complete: (pollConfig?: {
|
|
136
|
+
interval?: number;
|
|
137
|
+
timeout?: number;
|
|
138
|
+
}) => Promise<BrowserTaskResult>;
|
|
139
|
+
/** Get live session URL with optional parameters (Steel.dev) - throws if debugUrl not available */
|
|
140
|
+
getLiveUrl: (options?: LiveSessionOptions) => string;
|
|
141
|
+
/** Get iframe HTML for embedding live session - throws if debugUrl not available */
|
|
142
|
+
getLiveIframe: (optionsOrPreset?: string | IframeOptions) => string;
|
|
143
|
+
/** Get complete embed code snippet - throws if debugUrl not available */
|
|
144
|
+
getEmbedCode: () => string;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Task result with schema validation
|
|
148
|
+
*/
|
|
149
|
+
interface BrowserTaskWithPromiseAndSchema<T> extends BrowserTaskResult {
|
|
150
|
+
task_id: string;
|
|
151
|
+
/** Live URL to watch task execution in real-time */
|
|
152
|
+
liveUrl: string;
|
|
153
|
+
/** Parsed and validated output */
|
|
154
|
+
parsed: T | null;
|
|
155
|
+
/** Wait for task completion with schema validation */
|
|
156
|
+
complete: (pollConfig?: {
|
|
157
|
+
interval?: number;
|
|
158
|
+
timeout?: number;
|
|
159
|
+
}) => Promise<BrowserTaskResult & {
|
|
160
|
+
parsed: T | null;
|
|
161
|
+
}>;
|
|
162
|
+
/** Get live session URL with optional parameters - throws if debugUrl not available */
|
|
163
|
+
getLiveUrl: (options?: LiveSessionOptions) => string;
|
|
164
|
+
/** Get iframe HTML for embedding live session - throws if debugUrl not available */
|
|
165
|
+
getLiveIframe: (optionsOrPreset?: string | IframeOptions) => string;
|
|
166
|
+
/** Get complete embed code snippet - throws if debugUrl not available */
|
|
167
|
+
getEmbedCode: () => string;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Recording status and metadata
|
|
171
|
+
*/
|
|
172
|
+
interface RecordingStatus {
|
|
173
|
+
/** Recording ID */
|
|
174
|
+
id: string;
|
|
175
|
+
/** Current status */
|
|
176
|
+
status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'ERROR';
|
|
177
|
+
/** Presigned S3 URL for rrweb replay JSON (interactive DOM replay) */
|
|
178
|
+
replay_url?: string;
|
|
179
|
+
/** Presigned S3 URL for network logs (NDJSON format) */
|
|
180
|
+
network_url?: string;
|
|
181
|
+
/** Presigned S3 URL for console logs (NDJSON format) */
|
|
182
|
+
console_url?: string;
|
|
183
|
+
/** Presigned S3 URL for native browser video (WebM or MP4 format, real-time recording) */
|
|
184
|
+
video_url?: string;
|
|
185
|
+
/** Total rrweb events captured */
|
|
186
|
+
total_events?: number;
|
|
187
|
+
/** Total bytes of all files */
|
|
188
|
+
file_size?: number;
|
|
189
|
+
/** Duration in milliseconds */
|
|
190
|
+
duration?: number;
|
|
191
|
+
/** Error message if status=ERROR */
|
|
192
|
+
error?: string;
|
|
193
|
+
/** When recording was created */
|
|
194
|
+
created_at: string;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Browser error with screenshot captured at error time
|
|
198
|
+
*/
|
|
199
|
+
interface BrowserError {
|
|
200
|
+
/** Error type: console error or network error */
|
|
201
|
+
type: 'console' | 'network';
|
|
202
|
+
/** Error message */
|
|
203
|
+
message: string;
|
|
204
|
+
/** URL where error occurred */
|
|
205
|
+
url?: string;
|
|
206
|
+
/** CDP timestamp in seconds since browser start */
|
|
207
|
+
timestamp: number;
|
|
208
|
+
/** Presigned S3 URL to screenshot JPEG (captured 500ms after error) */
|
|
209
|
+
screenshot_url?: string;
|
|
210
|
+
/** When screenshot was captured (Unix timestamp) */
|
|
211
|
+
captured_at?: number;
|
|
212
|
+
/** HTTP status code (for network errors) */
|
|
213
|
+
status?: number;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Response from getErrors()
|
|
217
|
+
*/
|
|
218
|
+
interface ErrorsResponse {
|
|
219
|
+
/** Recording ID */
|
|
220
|
+
recording_id: string;
|
|
221
|
+
/** Total number of errors */
|
|
222
|
+
total_errors: number;
|
|
223
|
+
/** Errors with real-time screenshots */
|
|
224
|
+
errors: BrowserError[];
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export type { BrowserConfig, BrowserError, BrowserModel, BrowserTaskInput, BrowserTaskInputWithSchema, BrowserTaskResult, BrowserTaskWithPromise, BrowserTaskWithPromiseAndSchema, ErrorsResponse, IframeOptions, LiveSessionOptions, RecordingStatus };
|
|
@@ -218,7 +218,7 @@ function createBrowserTool(config) {
|
|
|
218
218
|
});
|
|
219
219
|
return (0, import_ai.tool)({
|
|
220
220
|
description: BROWSER_TOOL_DESCRIPTION,
|
|
221
|
-
|
|
221
|
+
inputSchema: schema,
|
|
222
222
|
execute: async (params) => {
|
|
223
223
|
const { task, url, max_steps, region } = params;
|
|
224
224
|
const result = await executeBrowserTask(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../tools/browser/vercel.ts","../../../tools/utils/resilience.ts","../../../tools/browser/core.ts","../../../tools/browser/prompts.ts"],"sourcesContent":["/**\n * Vercel AI SDK adapter for browser automation tool\n */\n\nimport { tool as createTool } from 'ai';\nimport { z } from 'zod';\nimport { executeBrowserTask } from './core.js';\nimport type { BrowserConfig } from './types.js';\nimport { BROWSER_TOOL_DESCRIPTION } from './prompts.js';\n\n/**\n * Create Vercel AI SDK tool for browser automation\n * \n * @param config - Optional browser worker configuration\n * @returns Vercel AI SDK tool\n * \n * @example\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createBrowserTool } from 'morphsdk/tools/browser/vercel';\n * \n * const browserTool = createBrowserTool({\n * apiUrl: 'https://browser-worker.example.com'\n * });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { browserTask: browserTool },\n * prompt: 'Test the checkout flow at https://3000-abc.e2b.dev',\n * maxSteps: 5\n * });\n * ```\n */\nexport function createBrowserTool(config?: BrowserConfig) {\n const schema = z.object({\n task: z.string().describe('Natural language description of what to do (e.g., \"Test checkout flow for buying a pineapple\")'),\n url: z.string().optional().describe('Starting URL (e.g., https://3000-xyz.e2b.dev)'),\n max_steps: z.number().min(1).max(50).default(10).describe('Maximum number of browser actions to take'),\n region: z.enum(['sfo', 'lon']).default('sfo').describe('Browserless region: sfo (US West) or lon (Europe)'),\n });\n\n return createTool({\n description: BROWSER_TOOL_DESCRIPTION,\n parameters: schema,\n execute: async (params) => {\n const { task, url, max_steps, region } = params;\n const result = await executeBrowserTask(\n { task, url, max_steps, region },\n config\n );\n\n if (result.success) {\n return {\n success: true,\n result: result.result,\n steps_taken: result.steps_taken,\n execution_time_ms: result.execution_time_ms,\n };\n }\n\n return {\n success: false,\n error: result.error,\n };\n },\n });\n}\n\n/**\n * Default browser tool for Vercel AI SDK\n */\nexport const browserTool = createBrowserTool();\n\n","/**\n * Resilience utilities for retry logic and timeout handling\n */\n\nexport interface RetryConfig {\n maxRetries?: number; // Default: 3\n initialDelay?: number; // Default: 1000ms\n maxDelay?: number; // Default: 30000ms\n backoffMultiplier?: number; // Default: 2\n retryableErrors?: string[]; // Default: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND']\n onRetry?: (attempt: number, error: Error) => void;\n}\n\nconst DEFAULT_RETRY_CONFIG: Required<Omit<RetryConfig, 'onRetry'>> = {\n maxRetries: 3,\n initialDelay: 1000,\n maxDelay: 30000,\n backoffMultiplier: 2,\n retryableErrors: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'],\n};\n\n/**\n * Retry a fetch request with exponential backoff\n * \n * @param url - Request URL\n * @param options - Fetch options\n * @param retryConfig - Retry configuration\n * @returns Response from fetch\n * \n * @example\n * ```typescript\n * const response = await fetchWithRetry(\n * 'https://api.example.com/data',\n * { method: 'POST', body: JSON.stringify(data) },\n * { maxRetries: 5, initialDelay: 500 }\n * );\n * ```\n */\nexport async function fetchWithRetry(\n url: string,\n options: RequestInit,\n retryConfig: RetryConfig = {}\n): Promise<Response> {\n const {\n maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,\n initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,\n maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,\n backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,\n retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,\n onRetry,\n } = retryConfig;\n\n let lastError: Error | null = null;\n let delay = initialDelay;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n \n // Retry on 429 (rate limit) or 503 (service unavailable)\n if (response.status === 429 || response.status === 503) {\n if (attempt < maxRetries) {\n // Check for Retry-After header\n const retryAfter = response.headers.get('Retry-After');\n const waitTime = retryAfter \n ? parseInt(retryAfter) * 1000 \n : Math.min(delay, maxDelay);\n \n const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);\n if (onRetry) {\n onRetry(attempt + 1, error);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n continue;\n }\n }\n\n return response;\n } catch (error) {\n lastError = error as Error;\n \n // Check if error is retryable\n const isRetryable = retryableErrors.some(errType => \n lastError?.message?.includes(errType)\n );\n\n if (!isRetryable || attempt === maxRetries) {\n throw lastError;\n }\n\n // Exponential backoff\n const waitTime = Math.min(delay, maxDelay);\n if (onRetry) {\n onRetry(attempt + 1, lastError);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n }\n }\n\n throw lastError || new Error('Max retries exceeded');\n}\n\n/**\n * Add timeout to any promise\n * \n * @param promise - Promise to wrap with timeout\n * @param timeoutMs - Timeout in milliseconds\n * @param errorMessage - Optional custom error message\n * @returns Promise that rejects if timeout is reached\n * \n * @example\n * ```typescript\n * const result = await withTimeout(\n * fetchData(),\n * 5000,\n * 'Data fetch timed out'\n * );\n * ```\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n errorMessage?: string\n): Promise<T> {\n let timeoutId: NodeJS.Timeout | number;\n \n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n\n try {\n const result = await Promise.race([promise, timeoutPromise]);\n clearTimeout(timeoutId!);\n return result;\n } catch (error) {\n clearTimeout(timeoutId!);\n throw error;\n }\n}\n\n/**\n * Sleep for specified milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Unified error type for all tools\n */\nexport class MorphError extends Error {\n constructor(\n message: string,\n public code: string,\n public statusCode?: number,\n public retryable: boolean = false\n ) {\n super(message);\n this.name = 'MorphError';\n }\n}\n\n\n","/**\n * Core implementation for browser automation tasks\n */\n\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport type {\n BrowserConfig,\n BrowserTaskInput,\n BrowserTaskInputWithSchema,\n BrowserTaskResult,\n BrowserTaskWithPromise,\n BrowserTaskWithPromiseAndSchema,\n RecordingStatus,\n ErrorsResponse,\n LiveSessionOptions,\n IframeOptions,\n} from './types.js';\nimport { buildLiveUrl, buildLiveIframe, buildEmbedCode, resolvePreset } from './live.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: process.env.MORPH_ENVIRONMENT === 'DEV' \n ? 'http://localhost:8000'\n : 'https://browser.morphllm.com',\n timeout: 120000, // 2 minutes for complex tasks\n debug: false,\n};\n\n/**\n * BrowserClient class for easier usage with instance configuration\n */\nexport class BrowserClient {\n private config: BrowserConfig;\n\n constructor(config: BrowserConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n }\n\n /**\n * Execute a browser automation task\n */\n async execute(input: BrowserTaskInput): Promise<BrowserTaskResult> {\n return executeBrowserTask(input, this.config);\n }\n\n async createTask(input: BrowserTaskInput): Promise<BrowserTaskWithPromise>;\n async createTask<T>(input: BrowserTaskInputWithSchema<T>): Promise<BrowserTaskWithPromiseAndSchema<T>>;\n async createTask<T>(\n input: BrowserTaskInput | BrowserTaskInputWithSchema<T>\n ): Promise<BrowserTaskWithPromise | BrowserTaskWithPromiseAndSchema<T>> {\n if ('schema' in input) {\n const taskInput: BrowserTaskInput = {\n ...input,\n structured_output: stringifyStructuredOutput(input.schema),\n };\n const result = await executeBrowserTask(taskInput, this.config);\n return wrapTaskResponseWithSchema(result, this.config, input.schema);\n } else {\n const result = await executeBrowserTask(input, this.config);\n return wrapTaskResponse(result, this.config);\n }\n }\n\n /**\n * Execute task with recording and wait for video to be ready\n */\n async executeWithRecording(\n input: BrowserTaskInput & { record_video: true }\n ): Promise<BrowserTaskResult & { recording?: RecordingStatus }> {\n return executeWithRecording(input, this.config);\n }\n\n /**\n * Get recording status and URLs\n */\n async getRecording(recordingId: string): Promise<RecordingStatus> {\n return getRecording(recordingId, this.config);\n }\n\n /**\n * Wait for recording to complete with automatic polling\n */\n async waitForRecording(\n recordingId: string,\n options?: { timeout?: number; pollInterval?: number }\n ): Promise<RecordingStatus> {\n return waitForRecording(recordingId, this.config, options);\n }\n\n /**\n * Get errors from recording with screenshots\n */\n async getErrors(recordingId: string): Promise<ErrorsResponse> {\n return getErrors(recordingId, this.config);\n }\n\n /**\n * Check if browser worker service is healthy\n */\n async checkHealth(): Promise<{\n ok: boolean;\n google_configured: boolean;\n database_configured: boolean;\n s3_configured: boolean;\n error?: string;\n }> {\n return checkHealth(this.config);\n }\n}\n\n/**\n * Execute a natural language browser automation task\n * \n * @param input - Task parameters\n * @param config - Optional configuration (apiKey, apiUrl to override default)\n * @returns Task result with success status and findings\n * \n * @example\n * ```typescript\n * const result = await executeBrowserTask(\n * {\n * task: \"Test checkout flow for buying a pineapple\",\n * url: \"https://3000-abc.e2b.dev\",\n * max_steps: 20,\n * repo_id: \"my-project\",\n * commit_id: \"uuid-here\"\n * },\n * {\n * apiKey: process.env.MORPH_API_KEY,\n * // apiUrl: 'http://localhost:8001' // Override for local testing\n * }\n * );\n * \n * if (result.success) {\n * console.log('Task completed:', result.result);\n * console.log('Replay:', result.replay_url);\n * }\n * ```\n */\nexport async function executeBrowserTask(\n input: BrowserTaskInput,\n config: BrowserConfig = {}\n): Promise<BrowserTaskResult> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const timeout = config.timeout || DEFAULT_CONFIG.timeout;\n const debug = config.debug || false;\n\n if (!input.task || input.task.trim().length === 0) {\n return { \n success: false, \n error: 'Task description is required. Example: \"Go to example.com and click the login button\"' \n };\n }\n\n if (input.max_steps !== undefined && (input.max_steps < 1 || input.max_steps > 50)) {\n return { \n success: false, \n error: 'max_steps must be between 1 and 50. Use more steps for complex multi-page flows.' \n };\n }\n\n if (debug) {\n console.log(`[Browser] Task: \"${input.task.slice(0, 60)}...\" url=${input.url || 'none'} maxSteps=${input.max_steps ?? 10}`);\n console.log(`[Browser] Recording: ${input.record_video ? 'yes' : 'no'} | Calling ${apiUrl}/browser-task`);\n }\n\n const startTime = Date.now();\n\n try {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) headers['Authorization'] = `Bearer ${config.apiKey}`;\n\n const fetchPromise = fetchWithRetry(\n `${apiUrl}/browser-task`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n task: input.task,\n url: input.url,\n max_steps: input.max_steps ?? 10,\n model: input.model ?? 'morph-computer-use-v0',\n viewport_width: input.viewport_width ?? 1280,\n viewport_height: input.viewport_height ?? 720,\n external_id: input.external_id,\n repo_id: input.repo_id,\n commit_id: input.commit_id,\n record_video: input.record_video ?? false,\n video_width: input.video_width ?? input.viewport_width ?? 1280,\n video_height: input.video_height ?? input.viewport_height ?? 720,\n structured_output: input.structured_output,\n }),\n },\n config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n timeout,\n `Browser task timed out after ${timeout}ms. Consider increasing timeout or reducing max_steps.`\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] Error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result: BrowserTaskResult = await response.json();\n const elapsed = Date.now() - startTime;\n \n if (debug) {\n console.log(`[Browser] ✅ ${result.success ? 'Success' : 'Failed'} in ${elapsed}ms | steps=${result.steps_taken ?? 0} recordingId=${result.recording_id ?? 'none'}`);\n }\n\n return result;\n\n } catch (error) {\n if (error instanceof Error) {\n // Handle network errors\n if (error.message.includes('ECONNREFUSED') || error.message.includes('fetch failed')) {\n return {\n success: false,\n error: `Cannot connect to browser worker at ${apiUrl}. Ensure the service is running and accessible. For local dev, set MORPH_ENVIRONMENT=DEV.`,\n };\n }\n\n return {\n success: false,\n error: error.message,\n };\n }\n\n return {\n success: false,\n error: String(error),\n };\n }\n}\n\n/**\n * Get recording status and video URL\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @returns Recording status with video URL when ready\n * \n * @example\n * ```typescript\n * const status = await getRecording('uuid-here', { apiKey: 'key' });\n * if (status.status === 'COMPLETED' && status.video_url) {\n * console.log('Video ready:', status.video_url);\n * }\n * ```\n */\nexport async function getRecording(\n recordingId: string,\n config: BrowserConfig = {}\n): Promise<RecordingStatus> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getRecording');\n }\n\n if (debug) console.log(`[Browser] getRecording: ${recordingId}`);\n\n const response = await fetch(`${apiUrl}/recordings/${recordingId}`, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getRecording error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const recording = await response.json();\n if (debug) console.log(`[Browser] Recording status: ${recording.status}`);\n\n return recording;\n}\n\n/**\n * Wait for recording to complete with automatic polling\n * \n * @param recordingId - Recording UUID\n * @param config - Configuration with apiKey\n * @param options - Polling options\n * @returns Recording status when completed or errored\n * \n * @example\n * ```typescript\n * const result = await executeBrowserTask({ task: '...', record_video: true }, config);\n * if (result.recording_id) {\n * const recording = await waitForRecording(result.recording_id, config, {\n * timeout: 60000, // 1 minute\n * pollInterval: 2000 // Check every 2 seconds\n * });\n * console.log('Video URL:', recording.video_url);\n * }\n * ```\n */\nexport async function waitForRecording(\n recordingId: string,\n config: BrowserConfig = {},\n options: { timeout?: number; pollInterval?: number } = {}\n): Promise<RecordingStatus> {\n const timeout = options.timeout ?? 60000; // Default 1 minute\n const pollInterval = options.pollInterval ?? 2000; // Default 2 seconds\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const status = await getRecording(recordingId, config);\n \n if (status.status === 'COMPLETED' || status.status === 'ERROR') {\n return status;\n }\n\n // Wait before next poll\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error(`Recording timeout after ${timeout}ms - status still pending`);\n}\n\n/**\n * Execute task with recording and wait for video to be ready\n * \n * @param input - Task parameters with record_video=true\n * @param config - Configuration with apiKey\n * @returns Task result with ready video URL\n * \n * @example\n * ```typescript\n * const result = await executeWithRecording(\n * {\n * task: \"Test checkout flow\",\n * url: \"https://example.com\",\n * record_video: true,\n * repo_id: \"my-project\"\n * },\n * { apiKey: process.env.MORPH_API_KEY }\n * );\n * \n * console.log('Task result:', result.result);\n * console.log('Video URL:', result.recording?.video_url);\n * ```\n */\nexport async function executeWithRecording(\n input: BrowserTaskInput & { record_video: true },\n config: BrowserConfig = {}\n): Promise<BrowserTaskResult & { recording?: RecordingStatus }> {\n // Execute task with recording\n const taskResult = await executeBrowserTask(input, config);\n\n // If recording was created, wait for it to complete\n if (taskResult.recording_id) {\n try {\n const recording = await waitForRecording(\n taskResult.recording_id,\n config,\n { timeout: 60000, pollInterval: 2000 }\n );\n return {\n ...taskResult,\n recording,\n };\n } catch (error) {\n // Return task result even if recording fails\n return {\n ...taskResult,\n recording: {\n id: taskResult.recording_id,\n status: 'ERROR',\n error: error instanceof Error ? error.message : String(error),\n created_at: new Date().toISOString(),\n },\n };\n }\n }\n\n return taskResult;\n}\n\n/**\n * Get errors from recording with screenshots\n * \n * Screenshots are captured in real-time (500ms after error occurs) during the browser session.\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @returns Errors with real-time screenshots\n * \n * @example\n * ```typescript\n * const { errors, total_errors } = await getErrors('uuid-here', { apiKey: 'key' });\n * \n * console.log(`Found ${total_errors} errors`);\n * \n * errors.forEach(err => {\n * console.log(`[${err.type}] ${err.message}`);\n * if (err.url) console.log(` URL: ${err.url}`);\n * if (err.screenshot_url) console.log(` Screenshot: ${err.screenshot_url}`);\n * \n * // Download screenshot\n * if (err.screenshot_url) {\n * const response = await fetch(err.screenshot_url);\n * const screenshot = await response.arrayBuffer();\n * // Save or process screenshot\n * }\n * });\n * ```\n */\nexport async function getErrors(\n recordingId: string,\n config: BrowserConfig = {}\n): Promise<ErrorsResponse> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getErrors');\n }\n\n if (debug) console.log(`[Browser] getErrors: ${recordingId}`);\n\n const response = await fetch(`${apiUrl}/recordings/${recordingId}/errors`, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getErrors error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const errors = await response.json();\n if (debug) console.log(`[Browser] Found ${errors.total_errors} errors`);\n\n return errors;\n}\n\n/**\n * Helper to serialize Zod schema for API\n */\nfunction stringifyStructuredOutput(schema: any): string {\n try {\n return JSON.stringify({\n type: 'object',\n description: 'Zod schema definition (Zod v3)',\n zodDef: schema._def,\n });\n } catch (error) {\n console.warn('[Browser] Failed to serialize Zod schema:', error);\n return JSON.stringify({\n type: 'object',\n description: 'Schema serialization failed',\n });\n }\n}\n\n/**\n * Parse and validate structured task output\n */\nfunction parseStructuredTaskOutput<T>(\n result: BrowserTaskResult,\n schema: any\n): BrowserTaskResult & { parsed: T | null } {\n if (!result.output) {\n return { ...result, parsed: null };\n }\n\n try {\n const parsed = JSON.parse(result.output);\n const validated = schema.parse(parsed) as T;\n return { ...result, parsed: validated };\n } catch (error) {\n if (error instanceof SyntaxError) {\n return { ...result, parsed: null };\n }\n throw error;\n }\n}\n\n/**\n * Get current task status\n */\nasync function getTaskStatus(\n taskId: string,\n config: BrowserConfig\n): Promise<BrowserTaskResult> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (debug) console.log(`[Browser] getTaskStatus: ${taskId}`);\n\n const headers: Record<string, string> = {};\n if (config.apiKey) headers['Authorization'] = `Bearer ${config.apiKey}`;\n\n const response = await fetch(`${apiUrl}/tasks/${taskId}`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getTaskStatus error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result: BrowserTaskResult = await response.json();\n if (debug) console.log(`[Browser] Task status: ${result.status}`);\n\n return result;\n}\n\n/**\n * Generate live URL for watching task execution in real-time\n */\nfunction generateLiveUrl(taskId: string, config: BrowserConfig): string {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const baseUrl = apiUrl.replace('/api', '');\n return `${baseUrl}/tasks/${taskId}/live`;\n}\n\n/**\n * Poll task until completion\n */\nasync function pollTaskUntilComplete(\n taskId: string,\n config: BrowserConfig,\n pollConfig: { interval?: number; timeout?: number } = {}\n): Promise<BrowserTaskResult> {\n const interval = pollConfig.interval ?? 2000; // 2 seconds\n const timeout = pollConfig.timeout ?? 300000; // 5 minutes\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const status = await getTaskStatus(taskId, config);\n \n if (status.status === 'completed' || status.status === 'failed') {\n return status;\n }\n\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n\n throw new Error(`Task polling timeout after ${timeout}ms`);\n}\n\n/**\n * Wrap task response with convenience methods\n */\nfunction wrapTaskResponse(\n result: BrowserTaskResult,\n config: BrowserConfig\n): BrowserTaskWithPromise {\n if (!result.task_id) {\n throw new Error('task_id is required to wrap response');\n }\n\n const wrapped: BrowserTaskWithPromise = {\n ...result,\n task_id: result.task_id,\n liveUrl: generateLiveUrl(result.task_id, config),\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n return pollTaskUntilComplete(result.task_id!, config, pollConfig);\n },\n // Add Steel live session helpers - either functional or error-throwing\n getLiveUrl: result.debugUrl\n ? (options?: LiveSessionOptions) => buildLiveUrl(result.debugUrl!, options)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n getLiveIframe: result.debugUrl\n ? (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(result.debugUrl!, options);\n }\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n getEmbedCode: result.debugUrl\n ? () => buildEmbedCode(result.debugUrl!)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n };\n\n return wrapped;\n}\n\n/**\n * Wrap task response with schema validation\n */\nfunction wrapTaskResponseWithSchema<T>(\n result: BrowserTaskResult,\n config: BrowserConfig,\n schema: any\n): BrowserTaskWithPromiseAndSchema<T> {\n if (!result.task_id) {\n throw new Error('task_id is required to wrap response');\n }\n\n const parsed = result.output\n ? parseStructuredTaskOutput<T>(result, schema)\n : { ...result, parsed: null };\n\n const wrapped: BrowserTaskWithPromiseAndSchema<T> = {\n ...parsed,\n task_id: result.task_id,\n liveUrl: generateLiveUrl(result.task_id, config),\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n const finalResult = await pollTaskUntilComplete(result.task_id!, config, pollConfig);\n return parseStructuredTaskOutput<T>(finalResult, schema);\n },\n // Add Steel live session helpers - either functional or error-throwing\n getLiveUrl: result.debugUrl\n ? (options?: LiveSessionOptions) => buildLiveUrl(result.debugUrl!, options)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions. '\n );\n },\n getLiveIframe: result.debugUrl\n ? (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(result.debugUrl!, options);\n }\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions.'\n );\n },\n getEmbedCode: result.debugUrl\n ? () => buildEmbedCode(result.debugUrl!)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions.'\n );\n },\n };\n\n return wrapped;\n}\n\n/**\n * Check if browser worker service is healthy\n * \n * @param config - Optional configuration\n * @returns Health status\n */\nexport async function checkHealth(config: BrowserConfig = {}): Promise<{\n ok: boolean;\n google_configured: boolean;\n database_configured: boolean;\n s3_configured: boolean;\n error?: string;\n}> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n\n try {\n const response = await fetch(`${apiUrl}/health`, {\n method: 'GET',\n headers: config.apiKey\n ? { 'Authorization': `Bearer ${config.apiKey}` }\n : {},\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n\n const data = await response.json();\n return {\n ok: true,\n google_configured: data.google_configured ?? false,\n database_configured: data.database_configured ?? false,\n s3_configured: data.s3_configured ?? false,\n };\n } catch (error) {\n return {\n ok: false,\n google_configured: false,\n database_configured: false,\n s3_configured: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n","/**\n * Tool descriptions and prompts for AI models\n */\n\nexport const BROWSER_TOOL_DESCRIPTION = `Execute natural language browser automation tasks using an AI-powered agent. The agent can navigate websites, interact with elements, fill forms, click buttons, and verify functionality.\n\nUse this tool to:\n- Test web applications end-to-end\n- Verify UI functionality\n- Automate user workflows\n- Extract information from web pages\n\nThe agent uses GPT-4o-mini to interpret your task and execute the necessary browser actions. It runs in a remote browser via Browserless.io, so it can access any publicly accessible URL.\n\nImportant:\n- Provide clear, specific task descriptions\n- Include the starting URL if navigating to a specific page\n- Use remote URLs (e.g., https://3000-xyz.e2b.dev) not localhost\n- Complex tasks may require more max_steps`;\n\nexport const BROWSER_SYSTEM_PROMPT = `You have access to browser automation capabilities. When testing or interacting with web applications:\n\n1. Be specific about what you're testing or verifying\n2. Break complex tasks into clear steps\n3. Always provide the full URL including protocol (https://)\n4. For localhost apps, use the remote tunnel URL (e.g., e2b.dev URLs)\n5. Specify the number of steps needed - simple tasks use 5-10, complex flows use 15-30\n\nExample good tasks:\n- \"Go to https://3000-abc.e2b.dev and verify the landing page loads with a hero section\"\n- \"Test guest checkout: add a pineapple to cart, proceed to checkout, fill shipping info, and verify order summary\"\n- \"Navigate to the dashboard and click on the settings tab, then verify the API keys section is visible\"\n\nExample bad tasks:\n- \"test the app\" (too vague)\n- \"go to localhost:3000\" (use remote URL instead)\n- \"do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AAE,MAAM,KAAK,WAAW,OAAO,IAAI;AACzC,YAAM,SAAS,MAAM;AAAA,QACnB,EAAE,MAAM,KAAK,WAAW,OAAO;AAAA,QAC/B;AAAA,MACF;AAEA,UAAI,OAAO,SAAS;AAClB,eAAO;AAAA,UACL,SAAS;AAAA,UACT,QAAQ,OAAO;AAAA,UACf,aAAa,OAAO;AAAA,UACpB,mBAAmB,OAAO;AAAA,QAC5B;AAAA,MACF;AAEA,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,OAAO;AAAA,MAChB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAKO,IAAM,cAAc,kBAAkB;","names":["createTool"]}
|
|
1
|
+
{"version":3,"sources":["../../../tools/browser/vercel.ts","../../../tools/utils/resilience.ts","../../../tools/browser/core.ts","../../../tools/browser/prompts.ts"],"sourcesContent":["/**\n * Vercel AI SDK adapter for browser automation tool\n */\n\nimport { tool as createTool } from 'ai';\nimport { z } from 'zod';\nimport { executeBrowserTask } from './core.js';\nimport type { BrowserConfig } from './types.js';\nimport { BROWSER_TOOL_DESCRIPTION } from './prompts.js';\n\n/**\n * Create Vercel AI SDK tool for browser automation\n * \n * @param config - Optional browser worker configuration\n * @returns Vercel AI SDK tool\n * \n * @example\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createBrowserTool } from 'morphsdk/tools/browser/vercel';\n * \n * const browserTool = createBrowserTool({\n * apiUrl: 'https://browser-worker.example.com'\n * });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { browserTask: browserTool },\n * prompt: 'Test the checkout flow at https://3000-abc.e2b.dev',\n * maxSteps: 5\n * });\n * ```\n */\nexport function createBrowserTool(config?: BrowserConfig) {\n const schema = z.object({\n task: z.string().describe('Natural language description of what to do (e.g., \"Test checkout flow for buying a pineapple\")'),\n url: z.string().optional().describe('Starting URL (e.g., https://3000-xyz.e2b.dev)'),\n max_steps: z.number().min(1).max(50).default(10).describe('Maximum number of browser actions to take'),\n region: z.enum(['sfo', 'lon']).default('sfo').describe('Browserless region: sfo (US West) or lon (Europe)'),\n });\n\n return createTool({\n description: BROWSER_TOOL_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const { task, url, max_steps, region } = params;\n const result = await executeBrowserTask(\n { task, url, max_steps, region },\n config\n );\n\n if (result.success) {\n return {\n success: true,\n result: result.result,\n steps_taken: result.steps_taken,\n execution_time_ms: result.execution_time_ms,\n };\n }\n\n return {\n success: false,\n error: result.error,\n };\n },\n });\n}\n\n/**\n * Default browser tool for Vercel AI SDK\n */\nexport const browserTool = createBrowserTool();\n\n","/**\n * Resilience utilities for retry logic and timeout handling\n */\n\nexport interface RetryConfig {\n maxRetries?: number; // Default: 3\n initialDelay?: number; // Default: 1000ms\n maxDelay?: number; // Default: 30000ms\n backoffMultiplier?: number; // Default: 2\n retryableErrors?: string[]; // Default: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND']\n onRetry?: (attempt: number, error: Error) => void;\n}\n\nconst DEFAULT_RETRY_CONFIG: Required<Omit<RetryConfig, 'onRetry'>> = {\n maxRetries: 3,\n initialDelay: 1000,\n maxDelay: 30000,\n backoffMultiplier: 2,\n retryableErrors: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'],\n};\n\n/**\n * Retry a fetch request with exponential backoff\n * \n * @param url - Request URL\n * @param options - Fetch options\n * @param retryConfig - Retry configuration\n * @returns Response from fetch\n * \n * @example\n * ```typescript\n * const response = await fetchWithRetry(\n * 'https://api.example.com/data',\n * { method: 'POST', body: JSON.stringify(data) },\n * { maxRetries: 5, initialDelay: 500 }\n * );\n * ```\n */\nexport async function fetchWithRetry(\n url: string,\n options: RequestInit,\n retryConfig: RetryConfig = {}\n): Promise<Response> {\n const {\n maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,\n initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,\n maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,\n backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,\n retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,\n onRetry,\n } = retryConfig;\n\n let lastError: Error | null = null;\n let delay = initialDelay;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n \n // Retry on 429 (rate limit) or 503 (service unavailable)\n if (response.status === 429 || response.status === 503) {\n if (attempt < maxRetries) {\n // Check for Retry-After header\n const retryAfter = response.headers.get('Retry-After');\n const waitTime = retryAfter \n ? parseInt(retryAfter) * 1000 \n : Math.min(delay, maxDelay);\n \n const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);\n if (onRetry) {\n onRetry(attempt + 1, error);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n continue;\n }\n }\n\n return response;\n } catch (error) {\n lastError = error as Error;\n \n // Check if error is retryable\n const isRetryable = retryableErrors.some(errType => \n lastError?.message?.includes(errType)\n );\n\n if (!isRetryable || attempt === maxRetries) {\n throw lastError;\n }\n\n // Exponential backoff\n const waitTime = Math.min(delay, maxDelay);\n if (onRetry) {\n onRetry(attempt + 1, lastError);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n }\n }\n\n throw lastError || new Error('Max retries exceeded');\n}\n\n/**\n * Add timeout to any promise\n * \n * @param promise - Promise to wrap with timeout\n * @param timeoutMs - Timeout in milliseconds\n * @param errorMessage - Optional custom error message\n * @returns Promise that rejects if timeout is reached\n * \n * @example\n * ```typescript\n * const result = await withTimeout(\n * fetchData(),\n * 5000,\n * 'Data fetch timed out'\n * );\n * ```\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n errorMessage?: string\n): Promise<T> {\n let timeoutId: NodeJS.Timeout | number;\n \n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n\n try {\n const result = await Promise.race([promise, timeoutPromise]);\n clearTimeout(timeoutId!);\n return result;\n } catch (error) {\n clearTimeout(timeoutId!);\n throw error;\n }\n}\n\n/**\n * Sleep for specified milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Unified error type for all tools\n */\nexport class MorphError extends Error {\n constructor(\n message: string,\n public code: string,\n public statusCode?: number,\n public retryable: boolean = false\n ) {\n super(message);\n this.name = 'MorphError';\n }\n}\n\n\n","/**\n * Core implementation for browser automation tasks\n */\n\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport type {\n BrowserConfig,\n BrowserTaskInput,\n BrowserTaskInputWithSchema,\n BrowserTaskResult,\n BrowserTaskWithPromise,\n BrowserTaskWithPromiseAndSchema,\n RecordingStatus,\n ErrorsResponse,\n LiveSessionOptions,\n IframeOptions,\n} from './types.js';\nimport { buildLiveUrl, buildLiveIframe, buildEmbedCode, resolvePreset } from './live.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: process.env.MORPH_ENVIRONMENT === 'DEV' \n ? 'http://localhost:8000'\n : 'https://browser.morphllm.com',\n timeout: 120000, // 2 minutes for complex tasks\n debug: false,\n};\n\n/**\n * BrowserClient class for easier usage with instance configuration\n */\nexport class BrowserClient {\n private config: BrowserConfig;\n\n constructor(config: BrowserConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n }\n\n /**\n * Execute a browser automation task\n */\n async execute(input: BrowserTaskInput): Promise<BrowserTaskResult> {\n return executeBrowserTask(input, this.config);\n }\n\n async createTask(input: BrowserTaskInput): Promise<BrowserTaskWithPromise>;\n async createTask<T>(input: BrowserTaskInputWithSchema<T>): Promise<BrowserTaskWithPromiseAndSchema<T>>;\n async createTask<T>(\n input: BrowserTaskInput | BrowserTaskInputWithSchema<T>\n ): Promise<BrowserTaskWithPromise | BrowserTaskWithPromiseAndSchema<T>> {\n if ('schema' in input) {\n const taskInput: BrowserTaskInput = {\n ...input,\n structured_output: stringifyStructuredOutput(input.schema),\n };\n const result = await executeBrowserTask(taskInput, this.config);\n return wrapTaskResponseWithSchema(result, this.config, input.schema);\n } else {\n const result = await executeBrowserTask(input, this.config);\n return wrapTaskResponse(result, this.config);\n }\n }\n\n /**\n * Execute task with recording and wait for video to be ready\n */\n async executeWithRecording(\n input: BrowserTaskInput & { record_video: true }\n ): Promise<BrowserTaskResult & { recording?: RecordingStatus }> {\n return executeWithRecording(input, this.config);\n }\n\n /**\n * Get recording status and URLs\n */\n async getRecording(recordingId: string): Promise<RecordingStatus> {\n return getRecording(recordingId, this.config);\n }\n\n /**\n * Wait for recording to complete with automatic polling\n */\n async waitForRecording(\n recordingId: string,\n options?: { timeout?: number; pollInterval?: number }\n ): Promise<RecordingStatus> {\n return waitForRecording(recordingId, this.config, options);\n }\n\n /**\n * Get errors from recording with screenshots\n */\n async getErrors(recordingId: string): Promise<ErrorsResponse> {\n return getErrors(recordingId, this.config);\n }\n\n /**\n * Check if browser worker service is healthy\n */\n async checkHealth(): Promise<{\n ok: boolean;\n google_configured: boolean;\n database_configured: boolean;\n s3_configured: boolean;\n error?: string;\n }> {\n return checkHealth(this.config);\n }\n}\n\n/**\n * Execute a natural language browser automation task\n * \n * @param input - Task parameters\n * @param config - Optional configuration (apiKey, apiUrl to override default)\n * @returns Task result with success status and findings\n * \n * @example\n * ```typescript\n * const result = await executeBrowserTask(\n * {\n * task: \"Test checkout flow for buying a pineapple\",\n * url: \"https://3000-abc.e2b.dev\",\n * max_steps: 20,\n * repo_id: \"my-project\",\n * commit_id: \"uuid-here\"\n * },\n * {\n * apiKey: process.env.MORPH_API_KEY,\n * // apiUrl: 'http://localhost:8001' // Override for local testing\n * }\n * );\n * \n * if (result.success) {\n * console.log('Task completed:', result.result);\n * console.log('Replay:', result.replay_url);\n * }\n * ```\n */\nexport async function executeBrowserTask(\n input: BrowserTaskInput,\n config: BrowserConfig = {}\n): Promise<BrowserTaskResult> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const timeout = config.timeout || DEFAULT_CONFIG.timeout;\n const debug = config.debug || false;\n\n if (!input.task || input.task.trim().length === 0) {\n return { \n success: false, \n error: 'Task description is required. Example: \"Go to example.com and click the login button\"' \n };\n }\n\n if (input.max_steps !== undefined && (input.max_steps < 1 || input.max_steps > 50)) {\n return { \n success: false, \n error: 'max_steps must be between 1 and 50. Use more steps for complex multi-page flows.' \n };\n }\n\n if (debug) {\n console.log(`[Browser] Task: \"${input.task.slice(0, 60)}...\" url=${input.url || 'none'} maxSteps=${input.max_steps ?? 10}`);\n console.log(`[Browser] Recording: ${input.record_video ? 'yes' : 'no'} | Calling ${apiUrl}/browser-task`);\n }\n\n const startTime = Date.now();\n\n try {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) headers['Authorization'] = `Bearer ${config.apiKey}`;\n\n const fetchPromise = fetchWithRetry(\n `${apiUrl}/browser-task`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n task: input.task,\n url: input.url,\n max_steps: input.max_steps ?? 10,\n model: input.model ?? 'morph-computer-use-v0',\n viewport_width: input.viewport_width ?? 1280,\n viewport_height: input.viewport_height ?? 720,\n external_id: input.external_id,\n repo_id: input.repo_id,\n commit_id: input.commit_id,\n record_video: input.record_video ?? false,\n video_width: input.video_width ?? input.viewport_width ?? 1280,\n video_height: input.video_height ?? input.viewport_height ?? 720,\n structured_output: input.structured_output,\n }),\n },\n config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n timeout,\n `Browser task timed out after ${timeout}ms. Consider increasing timeout or reducing max_steps.`\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] Error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result: BrowserTaskResult = await response.json();\n const elapsed = Date.now() - startTime;\n \n if (debug) {\n console.log(`[Browser] ✅ ${result.success ? 'Success' : 'Failed'} in ${elapsed}ms | steps=${result.steps_taken ?? 0} recordingId=${result.recording_id ?? 'none'}`);\n }\n\n return result;\n\n } catch (error) {\n if (error instanceof Error) {\n // Handle network errors\n if (error.message.includes('ECONNREFUSED') || error.message.includes('fetch failed')) {\n return {\n success: false,\n error: `Cannot connect to browser worker at ${apiUrl}. Ensure the service is running and accessible. For local dev, set MORPH_ENVIRONMENT=DEV.`,\n };\n }\n\n return {\n success: false,\n error: error.message,\n };\n }\n\n return {\n success: false,\n error: String(error),\n };\n }\n}\n\n/**\n * Get recording status and video URL\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @returns Recording status with video URL when ready\n * \n * @example\n * ```typescript\n * const status = await getRecording('uuid-here', { apiKey: 'key' });\n * if (status.status === 'COMPLETED' && status.video_url) {\n * console.log('Video ready:', status.video_url);\n * }\n * ```\n */\nexport async function getRecording(\n recordingId: string,\n config: BrowserConfig = {}\n): Promise<RecordingStatus> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getRecording');\n }\n\n if (debug) console.log(`[Browser] getRecording: ${recordingId}`);\n\n const response = await fetch(`${apiUrl}/recordings/${recordingId}`, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getRecording error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const recording = await response.json();\n if (debug) console.log(`[Browser] Recording status: ${recording.status}`);\n\n return recording;\n}\n\n/**\n * Wait for recording to complete with automatic polling\n * \n * @param recordingId - Recording UUID\n * @param config - Configuration with apiKey\n * @param options - Polling options\n * @returns Recording status when completed or errored\n * \n * @example\n * ```typescript\n * const result = await executeBrowserTask({ task: '...', record_video: true }, config);\n * if (result.recording_id) {\n * const recording = await waitForRecording(result.recording_id, config, {\n * timeout: 60000, // 1 minute\n * pollInterval: 2000 // Check every 2 seconds\n * });\n * console.log('Video URL:', recording.video_url);\n * }\n * ```\n */\nexport async function waitForRecording(\n recordingId: string,\n config: BrowserConfig = {},\n options: { timeout?: number; pollInterval?: number } = {}\n): Promise<RecordingStatus> {\n const timeout = options.timeout ?? 60000; // Default 1 minute\n const pollInterval = options.pollInterval ?? 2000; // Default 2 seconds\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const status = await getRecording(recordingId, config);\n \n if (status.status === 'COMPLETED' || status.status === 'ERROR') {\n return status;\n }\n\n // Wait before next poll\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error(`Recording timeout after ${timeout}ms - status still pending`);\n}\n\n/**\n * Execute task with recording and wait for video to be ready\n * \n * @param input - Task parameters with record_video=true\n * @param config - Configuration with apiKey\n * @returns Task result with ready video URL\n * \n * @example\n * ```typescript\n * const result = await executeWithRecording(\n * {\n * task: \"Test checkout flow\",\n * url: \"https://example.com\",\n * record_video: true,\n * repo_id: \"my-project\"\n * },\n * { apiKey: process.env.MORPH_API_KEY }\n * );\n * \n * console.log('Task result:', result.result);\n * console.log('Video URL:', result.recording?.video_url);\n * ```\n */\nexport async function executeWithRecording(\n input: BrowserTaskInput & { record_video: true },\n config: BrowserConfig = {}\n): Promise<BrowserTaskResult & { recording?: RecordingStatus }> {\n // Execute task with recording\n const taskResult = await executeBrowserTask(input, config);\n\n // If recording was created, wait for it to complete\n if (taskResult.recording_id) {\n try {\n const recording = await waitForRecording(\n taskResult.recording_id,\n config,\n { timeout: 60000, pollInterval: 2000 }\n );\n return {\n ...taskResult,\n recording,\n };\n } catch (error) {\n // Return task result even if recording fails\n return {\n ...taskResult,\n recording: {\n id: taskResult.recording_id,\n status: 'ERROR',\n error: error instanceof Error ? error.message : String(error),\n created_at: new Date().toISOString(),\n },\n };\n }\n }\n\n return taskResult;\n}\n\n/**\n * Get errors from recording with screenshots\n * \n * Screenshots are captured in real-time (500ms after error occurs) during the browser session.\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @returns Errors with real-time screenshots\n * \n * @example\n * ```typescript\n * const { errors, total_errors } = await getErrors('uuid-here', { apiKey: 'key' });\n * \n * console.log(`Found ${total_errors} errors`);\n * \n * errors.forEach(err => {\n * console.log(`[${err.type}] ${err.message}`);\n * if (err.url) console.log(` URL: ${err.url}`);\n * if (err.screenshot_url) console.log(` Screenshot: ${err.screenshot_url}`);\n * \n * // Download screenshot\n * if (err.screenshot_url) {\n * const response = await fetch(err.screenshot_url);\n * const screenshot = await response.arrayBuffer();\n * // Save or process screenshot\n * }\n * });\n * ```\n */\nexport async function getErrors(\n recordingId: string,\n config: BrowserConfig = {}\n): Promise<ErrorsResponse> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getErrors');\n }\n\n if (debug) console.log(`[Browser] getErrors: ${recordingId}`);\n\n const response = await fetch(`${apiUrl}/recordings/${recordingId}/errors`, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getErrors error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const errors = await response.json();\n if (debug) console.log(`[Browser] Found ${errors.total_errors} errors`);\n\n return errors;\n}\n\n/**\n * Helper to serialize Zod schema for API\n */\nfunction stringifyStructuredOutput(schema: any): string {\n try {\n return JSON.stringify({\n type: 'object',\n description: 'Zod schema definition (Zod v3)',\n zodDef: schema._def,\n });\n } catch (error) {\n console.warn('[Browser] Failed to serialize Zod schema:', error);\n return JSON.stringify({\n type: 'object',\n description: 'Schema serialization failed',\n });\n }\n}\n\n/**\n * Parse and validate structured task output\n */\nfunction parseStructuredTaskOutput<T>(\n result: BrowserTaskResult,\n schema: any\n): BrowserTaskResult & { parsed: T | null } {\n if (!result.output) {\n return { ...result, parsed: null };\n }\n\n try {\n const parsed = JSON.parse(result.output);\n const validated = schema.parse(parsed) as T;\n return { ...result, parsed: validated };\n } catch (error) {\n if (error instanceof SyntaxError) {\n return { ...result, parsed: null };\n }\n throw error;\n }\n}\n\n/**\n * Get current task status\n */\nasync function getTaskStatus(\n taskId: string,\n config: BrowserConfig\n): Promise<BrowserTaskResult> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (debug) console.log(`[Browser] getTaskStatus: ${taskId}`);\n\n const headers: Record<string, string> = {};\n if (config.apiKey) headers['Authorization'] = `Bearer ${config.apiKey}`;\n\n const response = await fetch(`${apiUrl}/tasks/${taskId}`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getTaskStatus error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result: BrowserTaskResult = await response.json();\n if (debug) console.log(`[Browser] Task status: ${result.status}`);\n\n return result;\n}\n\n/**\n * Generate live URL for watching task execution in real-time\n */\nfunction generateLiveUrl(taskId: string, config: BrowserConfig): string {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const baseUrl = apiUrl.replace('/api', '');\n return `${baseUrl}/tasks/${taskId}/live`;\n}\n\n/**\n * Poll task until completion\n */\nasync function pollTaskUntilComplete(\n taskId: string,\n config: BrowserConfig,\n pollConfig: { interval?: number; timeout?: number } = {}\n): Promise<BrowserTaskResult> {\n const interval = pollConfig.interval ?? 2000; // 2 seconds\n const timeout = pollConfig.timeout ?? 300000; // 5 minutes\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const status = await getTaskStatus(taskId, config);\n \n if (status.status === 'completed' || status.status === 'failed') {\n return status;\n }\n\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n\n throw new Error(`Task polling timeout after ${timeout}ms`);\n}\n\n/**\n * Wrap task response with convenience methods\n */\nfunction wrapTaskResponse(\n result: BrowserTaskResult,\n config: BrowserConfig\n): BrowserTaskWithPromise {\n if (!result.task_id) {\n throw new Error('task_id is required to wrap response');\n }\n\n const wrapped: BrowserTaskWithPromise = {\n ...result,\n task_id: result.task_id,\n liveUrl: generateLiveUrl(result.task_id, config),\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n return pollTaskUntilComplete(result.task_id!, config, pollConfig);\n },\n // Add Steel live session helpers - either functional or error-throwing\n getLiveUrl: result.debugUrl\n ? (options?: LiveSessionOptions) => buildLiveUrl(result.debugUrl!, options)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n getLiveIframe: result.debugUrl\n ? (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(result.debugUrl!, options);\n }\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n getEmbedCode: result.debugUrl\n ? () => buildEmbedCode(result.debugUrl!)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n };\n\n return wrapped;\n}\n\n/**\n * Wrap task response with schema validation\n */\nfunction wrapTaskResponseWithSchema<T>(\n result: BrowserTaskResult,\n config: BrowserConfig,\n schema: any\n): BrowserTaskWithPromiseAndSchema<T> {\n if (!result.task_id) {\n throw new Error('task_id is required to wrap response');\n }\n\n const parsed = result.output\n ? parseStructuredTaskOutput<T>(result, schema)\n : { ...result, parsed: null };\n\n const wrapped: BrowserTaskWithPromiseAndSchema<T> = {\n ...parsed,\n task_id: result.task_id,\n liveUrl: generateLiveUrl(result.task_id, config),\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n const finalResult = await pollTaskUntilComplete(result.task_id!, config, pollConfig);\n return parseStructuredTaskOutput<T>(finalResult, schema);\n },\n // Add Steel live session helpers - either functional or error-throwing\n getLiveUrl: result.debugUrl\n ? (options?: LiveSessionOptions) => buildLiveUrl(result.debugUrl!, options)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions. '\n );\n },\n getLiveIframe: result.debugUrl\n ? (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(result.debugUrl!, options);\n }\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions.'\n );\n },\n getEmbedCode: result.debugUrl\n ? () => buildEmbedCode(result.debugUrl!)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions.'\n );\n },\n };\n\n return wrapped;\n}\n\n/**\n * Check if browser worker service is healthy\n * \n * @param config - Optional configuration\n * @returns Health status\n */\nexport async function checkHealth(config: BrowserConfig = {}): Promise<{\n ok: boolean;\n google_configured: boolean;\n database_configured: boolean;\n s3_configured: boolean;\n error?: string;\n}> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n\n try {\n const response = await fetch(`${apiUrl}/health`, {\n method: 'GET',\n headers: config.apiKey\n ? { 'Authorization': `Bearer ${config.apiKey}` }\n : {},\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n\n const data = await response.json();\n return {\n ok: true,\n google_configured: data.google_configured ?? false,\n database_configured: data.database_configured ?? false,\n s3_configured: data.s3_configured ?? false,\n };\n } catch (error) {\n return {\n ok: false,\n google_configured: false,\n database_configured: false,\n s3_configured: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n","/**\n * Tool descriptions and prompts for AI models\n */\n\nexport const BROWSER_TOOL_DESCRIPTION = `Execute natural language browser automation tasks using an AI-powered agent. The agent can navigate websites, interact with elements, fill forms, click buttons, and verify functionality.\n\nUse this tool to:\n- Test web applications end-to-end\n- Verify UI functionality\n- Automate user workflows\n- Extract information from web pages\n\nThe agent uses GPT-4o-mini to interpret your task and execute the necessary browser actions. It runs in a remote browser via Browserless.io, so it can access any publicly accessible URL.\n\nImportant:\n- Provide clear, specific task descriptions\n- Include the starting URL if navigating to a specific page\n- Use remote URLs (e.g., https://3000-xyz.e2b.dev) not localhost\n- Complex tasks may require more max_steps`;\n\nexport const BROWSER_SYSTEM_PROMPT = `You have access to browser automation capabilities. When testing or interacting with web applications:\n\n1. Be specific about what you're testing or verifying\n2. Break complex tasks into clear steps\n3. Always provide the full URL including protocol (https://)\n4. For localhost apps, use the remote tunnel URL (e.g., e2b.dev URLs)\n5. Specify the number of steps needed - simple tasks use 5-10, complex flows use 15-30\n\nExample good tasks:\n- \"Go to https://3000-abc.e2b.dev and verify the landing page loads with a hero section\"\n- \"Test guest checkout: add a pineapple to cart, proceed to checkout, fill shipping info, and verify order summary\"\n- \"Navigate to the dashboard and click on the settings tab, then verify the API keys section is visible\"\n\nExample bad tasks:\n- \"test the app\" (too vague)\n- \"go to localhost:3000\" (use remote URL instead)\n- \"do everything\" (not specific enough)`;\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,gBAAmC;AACnC,iBAAkB;;;ACQlB,IAAM,uBAA+D;AAAA,EACnE,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,iBAAiB,CAAC,gBAAgB,aAAa,WAAW;AAC5D;AAmBA,eAAsB,eACpB,KACA,SACA,cAA2B,CAAC,GACT;AACnB,QAAM;AAAA,IACJ,aAAa,qBAAqB;AAAA,IAClC,eAAe,qBAAqB;AAAA,IACpC,WAAW,qBAAqB;AAAA,IAChC,oBAAoB,qBAAqB;AAAA,IACzC,kBAAkB,qBAAqB;AAAA,IACvC;AAAA,EACF,IAAI;AAEJ,MAAI,YAA0B;AAC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.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Create Vercel AI SDK tool for browser automation
|
|
7
|
+
*
|
|
8
|
+
* @param config - Optional browser worker configuration
|
|
9
|
+
* @returns Vercel AI SDK tool
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```typescript
|
|
13
|
+
* import { generateText } from 'ai';
|
|
14
|
+
* import { anthropic } from '@ai-sdk/anthropic';
|
|
15
|
+
* import { createBrowserTool } from 'morphsdk/tools/browser/vercel';
|
|
16
|
+
*
|
|
17
|
+
* const browserTool = createBrowserTool({
|
|
18
|
+
* apiUrl: 'https://browser-worker.example.com'
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* const result = await generateText({
|
|
22
|
+
* model: anthropic('claude-sonnet-4-5-20250929'),
|
|
23
|
+
* tools: { browserTask: browserTool },
|
|
24
|
+
* prompt: 'Test the checkout flow at https://3000-abc.e2b.dev',
|
|
25
|
+
* maxSteps: 5
|
|
26
|
+
* });
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
declare function createBrowserTool(config?: BrowserConfig): ai.Tool<{
|
|
30
|
+
task: string;
|
|
31
|
+
max_steps: number;
|
|
32
|
+
region: "sfo" | "lon";
|
|
33
|
+
url?: string | undefined;
|
|
34
|
+
}, {
|
|
35
|
+
success: boolean;
|
|
36
|
+
result: string | undefined;
|
|
37
|
+
steps_taken: number | undefined;
|
|
38
|
+
execution_time_ms: number | undefined;
|
|
39
|
+
error?: undefined;
|
|
40
|
+
} | {
|
|
41
|
+
success: boolean;
|
|
42
|
+
error: string | undefined;
|
|
43
|
+
result?: undefined;
|
|
44
|
+
steps_taken?: undefined;
|
|
45
|
+
execution_time_ms?: undefined;
|
|
46
|
+
}>;
|
|
47
|
+
/**
|
|
48
|
+
* Default browser tool for Vercel AI SDK
|
|
49
|
+
*/
|
|
50
|
+
declare const browserTool: ai.Tool<{
|
|
51
|
+
task: string;
|
|
52
|
+
max_steps: number;
|
|
53
|
+
region: "sfo" | "lon";
|
|
54
|
+
url?: string | undefined;
|
|
55
|
+
}, {
|
|
56
|
+
success: boolean;
|
|
57
|
+
result: string | undefined;
|
|
58
|
+
steps_taken: number | undefined;
|
|
59
|
+
execution_time_ms: number | undefined;
|
|
60
|
+
error?: undefined;
|
|
61
|
+
} | {
|
|
62
|
+
success: boolean;
|
|
63
|
+
error: string | undefined;
|
|
64
|
+
result?: undefined;
|
|
65
|
+
steps_taken?: undefined;
|
|
66
|
+
execution_time_ms?: undefined;
|
|
67
|
+
}>;
|
|
68
|
+
|
|
69
|
+
export { browserTool, createBrowserTool };
|
|
@@ -19,7 +19,7 @@ function createBrowserTool(config) {
|
|
|
19
19
|
});
|
|
20
20
|
return createTool({
|
|
21
21
|
description: BROWSER_TOOL_DESCRIPTION,
|
|
22
|
-
|
|
22
|
+
inputSchema: schema,
|
|
23
23
|
execute: async (params) => {
|
|
24
24
|
const { task, url, max_steps, region } = params;
|
|
25
25
|
const result = await executeBrowserTask(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../tools/browser/vercel.ts"],"sourcesContent":["/**\n * Vercel AI SDK adapter for browser automation tool\n */\n\nimport { tool as createTool } from 'ai';\nimport { z } from 'zod';\nimport { executeBrowserTask } from './core.js';\nimport type { BrowserConfig } from './types.js';\nimport { BROWSER_TOOL_DESCRIPTION } from './prompts.js';\n\n/**\n * Create Vercel AI SDK tool for browser automation\n * \n * @param config - Optional browser worker configuration\n * @returns Vercel AI SDK tool\n * \n * @example\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createBrowserTool } from 'morphsdk/tools/browser/vercel';\n * \n * const browserTool = createBrowserTool({\n * apiUrl: 'https://browser-worker.example.com'\n * });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { browserTask: browserTool },\n * prompt: 'Test the checkout flow at https://3000-abc.e2b.dev',\n * maxSteps: 5\n * });\n * ```\n */\nexport function createBrowserTool(config?: BrowserConfig) {\n const schema = z.object({\n task: z.string().describe('Natural language description of what to do (e.g., \"Test checkout flow for buying a pineapple\")'),\n url: z.string().optional().describe('Starting URL (e.g., https://3000-xyz.e2b.dev)'),\n max_steps: z.number().min(1).max(50).default(10).describe('Maximum number of browser actions to take'),\n region: z.enum(['sfo', 'lon']).default('sfo').describe('Browserless region: sfo (US West) or lon (Europe)'),\n });\n\n return createTool({\n description: BROWSER_TOOL_DESCRIPTION,\n
|
|
1
|
+
{"version":3,"sources":["../../../tools/browser/vercel.ts"],"sourcesContent":["/**\n * Vercel AI SDK adapter for browser automation tool\n */\n\nimport { tool as createTool } from 'ai';\nimport { z } from 'zod';\nimport { executeBrowserTask } from './core.js';\nimport type { BrowserConfig } from './types.js';\nimport { BROWSER_TOOL_DESCRIPTION } from './prompts.js';\n\n/**\n * Create Vercel AI SDK tool for browser automation\n * \n * @param config - Optional browser worker configuration\n * @returns Vercel AI SDK tool\n * \n * @example\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createBrowserTool } from 'morphsdk/tools/browser/vercel';\n * \n * const browserTool = createBrowserTool({\n * apiUrl: 'https://browser-worker.example.com'\n * });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { browserTask: browserTool },\n * prompt: 'Test the checkout flow at https://3000-abc.e2b.dev',\n * maxSteps: 5\n * });\n * ```\n */\nexport function createBrowserTool(config?: BrowserConfig) {\n const schema = z.object({\n task: z.string().describe('Natural language description of what to do (e.g., \"Test checkout flow for buying a pineapple\")'),\n url: z.string().optional().describe('Starting URL (e.g., https://3000-xyz.e2b.dev)'),\n max_steps: z.number().min(1).max(50).default(10).describe('Maximum number of browser actions to take'),\n region: z.enum(['sfo', 'lon']).default('sfo').describe('Browserless region: sfo (US West) or lon (Europe)'),\n });\n\n return createTool({\n description: BROWSER_TOOL_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const { task, url, max_steps, region } = params;\n const result = await executeBrowserTask(\n { task, url, max_steps, region },\n config\n );\n\n if (result.success) {\n return {\n success: true,\n result: result.result,\n steps_taken: result.steps_taken,\n execution_time_ms: result.execution_time_ms,\n };\n }\n\n return {\n success: false,\n error: result.error,\n };\n },\n });\n}\n\n/**\n * Default browser tool for Vercel AI SDK\n */\nexport const browserTool = createBrowserTool();\n\n"],"mappings":";;;;;;;;;;AAIA,SAAS,QAAQ,kBAAkB;AACnC,SAAS,SAAS;AA6BX,SAAS,kBAAkB,QAAwB;AACxD,QAAM,SAAS,EAAE,OAAO;AAAA,IACtB,MAAM,EAAE,OAAO,EAAE,SAAS,gGAAgG;AAAA,IAC1H,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,+CAA+C;AAAA,IACnF,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,EAAE,SAAS,2CAA2C;AAAA,IACrG,QAAQ,EAAE,KAAK,CAAC,OAAO,KAAK,CAAC,EAAE,QAAQ,KAAK,EAAE,SAAS,mDAAmD;AAAA,EAC5G,CAAC;AAED,SAAO,WAAW;AAAA,IAChB,aAAa;AAAA,IACb,aAAa;AAAA,IACb,SAAS,OAAO,WAAW;AACzB,YAAM,EAAE,MAAM,KAAK,WAAW,OAAO,IAAI;AACzC,YAAM,SAAS,MAAM;AAAA,QACnB,EAAE,MAAM,KAAK,WAAW,OAAO;AAAA,QAC/B;AAAA,MACF;AAEA,UAAI,OAAO,SAAS;AAClB,eAAO;AAAA,UACL,SAAS;AAAA,UACT,QAAQ,OAAO;AAAA,UACf,aAAa,OAAO;AAAA,UACpB,mBAAmB,OAAO;AAAA,QAC5B;AAAA,MACF;AAEA,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,OAAO;AAAA,MAChB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAKO,IAAM,cAAc,kBAAkB;","names":[]}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { Tool } from '@anthropic-ai/sdk/resources/messages';
|
|
2
|
+
import { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';
|
|
3
|
+
import '../utils/resilience.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Anthropic SDK adapter for codebase_search tool
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Create Anthropic-native codebase_search tool with execute and formatResult methods
|
|
11
|
+
*
|
|
12
|
+
* @param config - Configuration with repoId
|
|
13
|
+
* @returns Anthropic Tool definition with execute and formatResult methods
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* import Anthropic from '@anthropic-ai/sdk';
|
|
18
|
+
* import { createCodebaseSearchTool } from 'morphsdk/tools/anthropic';
|
|
19
|
+
*
|
|
20
|
+
* const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
|
|
21
|
+
* const tool = createCodebaseSearchTool({ repoId: 'my-project' });
|
|
22
|
+
*
|
|
23
|
+
* const response = await client.messages.create({
|
|
24
|
+
* model: "claude-sonnet-4-5-20250929",
|
|
25
|
+
* tools: [tool], // tool itself is the Tool definition
|
|
26
|
+
* messages: [{ role: "user", content: "Find authentication code" }]
|
|
27
|
+
* });
|
|
28
|
+
*
|
|
29
|
+
* // Execute tool and format result
|
|
30
|
+
* const result = await tool.execute(toolUseBlock.input);
|
|
31
|
+
* const formatted = tool.formatResult(result);
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
declare function createCodebaseSearchTool(config: CodebaseSearchConfig): Tool & {
|
|
35
|
+
execute: (input: CodebaseSearchInput) => Promise<CodebaseSearchResult>;
|
|
36
|
+
formatResult: (result: CodebaseSearchResult) => string;
|
|
37
|
+
getSystemPrompt: () => string;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export { createCodebaseSearchTool };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { CodebaseSearchResult, CodebaseSearchInput, CodebaseSearchConfig } from './types.js';
|
|
2
|
+
import '../utils/resilience.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Core implementation for codebase search
|
|
6
|
+
* Calls Morph rerank service for two-stage semantic search
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* CodebaseSearch client for programmatic semantic search
|
|
11
|
+
*/
|
|
12
|
+
declare class CodebaseSearchClient {
|
|
13
|
+
private config;
|
|
14
|
+
constructor(config?: {
|
|
15
|
+
apiKey?: string;
|
|
16
|
+
debug?: boolean;
|
|
17
|
+
timeout?: number;
|
|
18
|
+
retryConfig?: any;
|
|
19
|
+
});
|
|
20
|
+
/**
|
|
21
|
+
* Execute a semantic code search
|
|
22
|
+
*
|
|
23
|
+
* @param input - Search parameters including query, repoId, and target directories
|
|
24
|
+
* @param overrides - Optional config overrides for this operation
|
|
25
|
+
* @returns Search results with ranked code matches
|
|
26
|
+
*/
|
|
27
|
+
search(input: {
|
|
28
|
+
query: string;
|
|
29
|
+
repoId: string;
|
|
30
|
+
target_directories?: string[];
|
|
31
|
+
explanation?: string;
|
|
32
|
+
limit?: number;
|
|
33
|
+
}, overrides?: any): Promise<CodebaseSearchResult>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Execute semantic code search
|
|
37
|
+
*/
|
|
38
|
+
declare function executeCodebaseSearch(input: CodebaseSearchInput, config: CodebaseSearchConfig): Promise<CodebaseSearchResult>;
|
|
39
|
+
|
|
40
|
+
export { CodebaseSearchClient, executeCodebaseSearch };
|