@morphllm/morphsdk 0.2.28 → 0.2.38

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.
Files changed (76) hide show
  1. package/README.md +7 -12
  2. package/dist/anthropic-DpEAqqZF.d.ts +88 -0
  3. package/dist/{chunk-S3HTYGYF.js → chunk-B4H7N4GZ.js} +14 -2
  4. package/dist/chunk-B4H7N4GZ.js.map +1 -0
  5. package/dist/{chunk-CMKITT6X.js → chunk-DJSQUQGY.js} +4 -4
  6. package/dist/client.d.ts +114 -0
  7. package/dist/client.js +2 -2
  8. package/dist/git/client.d.ts +261 -0
  9. package/dist/git/config.d.ts +11 -0
  10. package/dist/git/index.d.ts +5 -0
  11. package/dist/git/types.d.ts +102 -0
  12. package/dist/index.d.ts +14 -0
  13. package/dist/index.js +4 -4
  14. package/dist/modelrouter/core.d.ts +56 -0
  15. package/dist/modelrouter/index.d.ts +2 -0
  16. package/dist/modelrouter/types.d.ts +35 -0
  17. package/dist/openai-BkKsS30n.d.ts +111 -0
  18. package/dist/tools/browser/anthropic.d.ts +51 -0
  19. package/dist/tools/browser/core.d.ts +203 -0
  20. package/dist/tools/browser/index.d.ts +72 -0
  21. package/dist/tools/browser/openai.d.ts +73 -0
  22. package/dist/tools/browser/prompts.d.ts +7 -0
  23. package/dist/tools/browser/types.d.ts +255 -0
  24. package/dist/tools/browser/vercel.d.ts +69 -0
  25. package/dist/tools/codebase_search/anthropic.d.ts +40 -0
  26. package/dist/tools/codebase_search/core.d.ts +40 -0
  27. package/dist/tools/codebase_search/index.d.ts +10 -0
  28. package/dist/tools/codebase_search/openai.d.ts +87 -0
  29. package/dist/tools/codebase_search/prompts.d.ts +7 -0
  30. package/dist/tools/codebase_search/types.d.ts +50 -0
  31. package/dist/tools/codebase_search/vercel.d.ts +65 -0
  32. package/dist/tools/fastapply/anthropic.cjs +14 -2
  33. package/dist/tools/fastapply/anthropic.cjs.map +1 -1
  34. package/dist/tools/fastapply/anthropic.d.ts +4 -0
  35. package/dist/tools/fastapply/anthropic.js +9 -3
  36. package/dist/tools/fastapply/core.d.ts +41 -0
  37. package/dist/tools/fastapply/index.cjs +18 -9
  38. package/dist/tools/fastapply/index.cjs.map +1 -1
  39. package/dist/tools/fastapply/index.d.ts +10 -0
  40. package/dist/tools/fastapply/index.js +4 -4
  41. package/dist/tools/fastapply/openai.d.ts +4 -0
  42. package/dist/tools/fastapply/prompts.d.ts +7 -0
  43. package/dist/tools/fastapply/types.d.ts +77 -0
  44. package/dist/tools/fastapply/vercel.d.ts +4 -0
  45. package/dist/tools/index.cjs +18 -9
  46. package/dist/tools/index.cjs.map +1 -1
  47. package/dist/tools/index.d.ts +10 -0
  48. package/dist/tools/index.js +4 -4
  49. package/dist/tools/utils/resilience.d.ts +58 -0
  50. package/dist/tools/warp_grep/agent/config.d.ts +8 -0
  51. package/dist/tools/warp_grep/agent/formatter.d.ts +14 -0
  52. package/dist/tools/warp_grep/agent/grep_helpers.d.ts +16 -0
  53. package/dist/tools/warp_grep/agent/parser.d.ts +16 -0
  54. package/dist/tools/warp_grep/agent/prompt.d.ts +4 -0
  55. package/dist/tools/warp_grep/agent/runner.d.ts +10 -0
  56. package/dist/tools/warp_grep/agent/types.cjs.map +1 -1
  57. package/dist/tools/warp_grep/agent/types.d.ts +44 -0
  58. package/dist/tools/warp_grep/anthropic.d.ts +14 -0
  59. package/dist/tools/warp_grep/index.d.ts +11 -0
  60. package/dist/tools/warp_grep/openai.d.ts +33 -0
  61. package/dist/tools/warp_grep/providers/command.d.ts +48 -0
  62. package/dist/tools/warp_grep/providers/local.d.ts +30 -0
  63. package/dist/tools/warp_grep/providers/types.d.ts +49 -0
  64. package/dist/tools/warp_grep/tools/analyse.d.ts +10 -0
  65. package/dist/tools/warp_grep/tools/finish.d.ts +10 -0
  66. package/dist/tools/warp_grep/tools/grep.d.ts +8 -0
  67. package/dist/tools/warp_grep/tools/read.d.ts +9 -0
  68. package/dist/tools/warp_grep/utils/files.d.ts +3 -0
  69. package/dist/tools/warp_grep/utils/format.d.ts +4 -0
  70. package/dist/tools/warp_grep/utils/paths.d.ts +7 -0
  71. package/dist/tools/warp_grep/utils/ripgrep.d.ts +11 -0
  72. package/dist/tools/warp_grep/vercel.d.ts +33 -0
  73. package/dist/vercel-B1GZ_g9N.d.ts +69 -0
  74. package/package.json +1 -1
  75. package/dist/chunk-S3HTYGYF.js.map +0 -1
  76. /package/dist/{chunk-CMKITT6X.js.map → chunk-DJSQUQGY.js.map} +0 -0
@@ -0,0 +1,73 @@
1
+ import { ChatCompletionTool } from 'openai/resources/chat/completions.mjs';
2
+ import { BrowserTaskInput, BrowserConfig, BrowserTaskResult } from './types.js';
3
+ import '../utils/resilience.js';
4
+
5
+ /**
6
+ * OpenAI SDK adapter for browser automation tool
7
+ */
8
+
9
+ /**
10
+ * OpenAI tool definition for browser automation
11
+ */
12
+ declare const browserTool: ChatCompletionTool;
13
+ /**
14
+ * Execute a browser task (for use in tool call handling)
15
+ *
16
+ * @param input - Tool input parameters (may be JSON string)
17
+ * @param config - Optional browser worker configuration
18
+ * @returns Task execution result
19
+ */
20
+ declare function execute(input: BrowserTaskInput | string, config?: BrowserConfig): Promise<BrowserTaskResult>;
21
+ /**
22
+ * Format browser task result for OpenAI tool result
23
+ *
24
+ * Returns a concise summary suitable for agent context. The full result object
25
+ * (with urls, errors, action_history, judgement, etc.) is available when calling
26
+ * execute() directly, but this formatted string omits those details to save tokens.
27
+ *
28
+ * @param result - Browser task result with full history data
29
+ * @returns Formatted string summary for tool result
30
+ */
31
+ declare function formatResult(result: BrowserTaskResult): string;
32
+ /**
33
+ * Get system prompt for browser automation
34
+ */
35
+ declare function getSystemPrompt(): string;
36
+ /**
37
+ * Create a configured browser tool with execute and formatResult methods
38
+ *
39
+ * @param config - Browser worker configuration
40
+ * @returns Tool definition with execute and formatResult methods
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * import OpenAI from 'openai';
45
+ * import { createBrowserTool } from 'morphsdk/tools/browser/openai';
46
+ *
47
+ * const tool = createBrowserTool({
48
+ * apiUrl: 'https://browser-worker.example.com'
49
+ * });
50
+ *
51
+ * const client = new OpenAI();
52
+ *
53
+ * const response = await client.chat.completions.create({
54
+ * model: 'gpt-4o',
55
+ * tools: [tool], // tool itself is the ChatCompletionTool
56
+ * messages: [{
57
+ * role: 'user',
58
+ * content: 'Test the checkout at https://3000-abc.e2b.dev'
59
+ * }]
60
+ * });
61
+ *
62
+ * // Execute and format
63
+ * const result = await tool.execute(toolCallArgs);
64
+ * const formatted = tool.formatResult(result);
65
+ * ```
66
+ */
67
+ declare function createBrowserTool(config?: BrowserConfig): ChatCompletionTool & {
68
+ execute: (input: BrowserTaskInput | string) => Promise<BrowserTaskResult>;
69
+ formatResult: (result: BrowserTaskResult) => string;
70
+ getSystemPrompt: () => string;
71
+ };
72
+
73
+ export { browserTool, createBrowserTool, execute, formatResult, getSystemPrompt };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Tool descriptions and prompts for AI models
3
+ */
4
+ declare const 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.\n\n## When to Use\nUse this AFTER coding is complete to verify your implementation:\n- You've finished writing/modifying code and need to verify it works\n- You need to test user interactions end-to-end (clicks, forms, navigation)\n- You want to catch runtime errors, console warnings, or network failures\n- You need visual confirmation that UI elements render and behave correctly\n\n## What You Get Back\nThe tool returns debugging artifacts to help you identify and fix issues:\n- **Video recording**: Watch exactly what happened in the browser session\n- **Console logs**: All console.log, warnings, and errors with timestamps\n- **Network logs**: Failed requests, 404s, API errors with screenshots\n- **Error screenshots**: Visual snapshots captured when errors occur\n\n## How to Write Good Tests\nBe specific about the user journey you're testing:\n\u274C Bad: \"Test the login feature\"\n\u2705 Good: \"Navigate to /login, enter 'test@example.com' and 'password123', click the Login button, verify we reach the /dashboard page\"\n\nInclude verification steps:\n\u2705 \"Click the Add Item button, verify the item appears in the list\"\n\u2705 \"Submit the form, verify a success message is displayed\"\n\n## Iterating on Failures\n1. Run the test and review the video + logs\n2. Identify the specific issue (console error, failed request, wrong behavior)\n3. Fix the code based on the evidence\n4. Re-run the test to verify the fix\n5. Repeat until test passes\n\n## Requirements\n- **URL**: Must be publicly accessible (use tunnels like ngrok, Cloudflare, or deploy to staging)\n- **Timing**: Use this after implementation, not during coding\n- **Complexity**: Set max_steps higher (20-30) for multi-step user workflows";
5
+ declare const 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\"}}]}";
6
+
7
+ export { BROWSER_SYSTEM_PROMPT, BROWSER_TOOL_DESCRIPTION };
@@ -0,0 +1,255 @@
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: 1000000) */
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
+ /** All URLs visited during execution */
83
+ urls?: (string | null)[];
84
+ /** Names of all actions executed */
85
+ action_names?: string[];
86
+ /** Per-step errors (null for steps without errors) */
87
+ errors?: (string | null)[];
88
+ /** All model actions with parameters */
89
+ model_actions?: any[];
90
+ /** Whether agent marked task as done */
91
+ is_done?: boolean;
92
+ /** Truncated action history with essential fields */
93
+ action_history?: any[][];
94
+ /** All action results */
95
+ action_results?: any[];
96
+ /** Whether any errors occurred */
97
+ has_errors?: boolean;
98
+ /** Total number of steps executed */
99
+ number_of_steps?: number;
100
+ /** Judge validation result if available */
101
+ judgement?: {
102
+ reasoning?: string;
103
+ verdict: boolean;
104
+ failure_reason?: string;
105
+ impossible_task?: boolean;
106
+ reached_captcha?: boolean;
107
+ };
108
+ /** Whether judge validated the execution */
109
+ is_validated?: boolean;
110
+ /** UUID of saved replay record (if session replay enabled) */
111
+ replay_id?: string;
112
+ /** Browserless replay URL (if session replay enabled) */
113
+ replay_url?: string;
114
+ /** Recording ID (if record_video=true) */
115
+ recording_id?: string;
116
+ /** Recording status: PENDING, PROCESSING, COMPLETED, ERROR */
117
+ recording_status?: string;
118
+ /** Task ID for async task tracking */
119
+ task_id?: string;
120
+ /** Task status: pending, running, completed, failed */
121
+ status?: string;
122
+ /** Structured output (JSON string) */
123
+ output?: string;
124
+ /** Live session debug URL for real-time viewing (WebRTC streaming) */
125
+ debugUrl?: string;
126
+ }
127
+ /**
128
+ * Configuration for live session viewing
129
+ */
130
+ interface LiveSessionOptions {
131
+ /** Enable or disable remote control (default: true for headful, varies for headless) */
132
+ interactive?: boolean;
133
+ /** UI theme: 'dark' or 'light' (headless only, default: 'dark') */
134
+ theme?: 'dark' | 'light';
135
+ /** Show or hide navigation controls (headless only, default: true) */
136
+ showControls?: boolean;
137
+ /** Focus view on specific page/tab ID (headless only) */
138
+ pageId?: string;
139
+ /** Display specific tab by index (headless only) */
140
+ pageIndex?: string;
141
+ }
142
+ /**
143
+ * Configuration for iframe generation
144
+ */
145
+ interface IframeOptions extends LiveSessionOptions {
146
+ /** Iframe width (default: '100%') */
147
+ width?: string | number;
148
+ /** Iframe height (default: '600px') */
149
+ height?: string | number;
150
+ /** Additional inline styles */
151
+ style?: string;
152
+ /** CSS class name */
153
+ className?: string;
154
+ }
155
+ /**
156
+ * Task result with convenience methods for async execution
157
+ */
158
+ interface BrowserTaskWithPromise extends BrowserTaskResult {
159
+ task_id: string;
160
+ /** Live URL to watch task execution in real-time */
161
+ liveUrl: string;
162
+ /** Wait for task completion */
163
+ complete: (pollConfig?: {
164
+ interval?: number;
165
+ timeout?: number;
166
+ }) => Promise<BrowserTaskResult>;
167
+ /** Get live session URL with optional parameters (Steel.dev) - throws if debugUrl not available */
168
+ getLiveUrl: (options?: LiveSessionOptions) => string;
169
+ /** Get iframe HTML for embedding live session - throws if debugUrl not available */
170
+ getLiveIframe: (optionsOrPreset?: string | IframeOptions) => string;
171
+ /** Get complete embed code snippet - throws if debugUrl not available */
172
+ getEmbedCode: () => string;
173
+ }
174
+ /**
175
+ * Task result with schema validation
176
+ */
177
+ interface BrowserTaskWithPromiseAndSchema<T> extends BrowserTaskResult {
178
+ task_id: string;
179
+ /** Live URL to watch task execution in real-time */
180
+ liveUrl: string;
181
+ /** Parsed and validated output */
182
+ parsed: T | null;
183
+ /** Wait for task completion with schema validation */
184
+ complete: (pollConfig?: {
185
+ interval?: number;
186
+ timeout?: number;
187
+ }) => Promise<BrowserTaskResult & {
188
+ parsed: T | null;
189
+ }>;
190
+ /** Get live session URL with optional parameters - throws if debugUrl not available */
191
+ getLiveUrl: (options?: LiveSessionOptions) => string;
192
+ /** Get iframe HTML for embedding live session - throws if debugUrl not available */
193
+ getLiveIframe: (optionsOrPreset?: string | IframeOptions) => string;
194
+ /** Get complete embed code snippet - throws if debugUrl not available */
195
+ getEmbedCode: () => string;
196
+ }
197
+ /**
198
+ * Recording status and metadata
199
+ */
200
+ interface RecordingStatus {
201
+ /** Recording ID */
202
+ id: string;
203
+ /** Current status */
204
+ status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'ERROR';
205
+ /** Presigned S3 URL for rrweb replay JSON (interactive DOM replay) */
206
+ replay_url?: string;
207
+ /** Presigned S3 URL for network logs (NDJSON format) */
208
+ network_url?: string;
209
+ /** Presigned S3 URL for console logs (NDJSON format) */
210
+ console_url?: string;
211
+ /** Presigned S3 URL for native browser video (WebM or MP4 format, real-time recording) */
212
+ video_url?: string;
213
+ /** Total rrweb events captured */
214
+ total_events?: number;
215
+ /** Total bytes of all files */
216
+ file_size?: number;
217
+ /** Duration in milliseconds */
218
+ duration?: number;
219
+ /** Error message if status=ERROR */
220
+ error?: string;
221
+ /** When recording was created */
222
+ created_at: string;
223
+ }
224
+ /**
225
+ * Browser error with screenshot captured at error time
226
+ */
227
+ interface BrowserError {
228
+ /** Error type: console error or network error */
229
+ type: 'console' | 'network';
230
+ /** Error message */
231
+ message: string;
232
+ /** URL where error occurred */
233
+ url?: string;
234
+ /** CDP timestamp in seconds since browser start */
235
+ timestamp: number;
236
+ /** Presigned S3 URL to screenshot JPEG (captured 500ms after error) */
237
+ screenshot_url?: string;
238
+ /** When screenshot was captured (Unix timestamp) */
239
+ captured_at?: number;
240
+ /** HTTP status code (for network errors) */
241
+ status?: number;
242
+ }
243
+ /**
244
+ * Response from getErrors()
245
+ */
246
+ interface ErrorsResponse {
247
+ /** Recording ID */
248
+ recording_id: string;
249
+ /** Total number of errors */
250
+ total_errors: number;
251
+ /** Errors with real-time screenshots */
252
+ errors: BrowserError[];
253
+ }
254
+
255
+ export type { BrowserConfig, BrowserError, BrowserModel, BrowserTaskInput, BrowserTaskInputWithSchema, BrowserTaskResult, BrowserTaskWithPromise, BrowserTaskWithPromiseAndSchema, ErrorsResponse, IframeOptions, LiveSessionOptions, RecordingStatus };
@@ -0,0 +1,69 @@
1
+ import * as ai from 'ai';
2
+ import { BrowserConfig } from './types.js';
3
+ import '../utils/resilience.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 };
@@ -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 };
@@ -0,0 +1,10 @@
1
+ export { executeCodebaseSearch } from './core.js';
2
+ export { CODEBASE_SEARCH_DESCRIPTION, CODEBASE_SEARCH_SYSTEM_PROMPT } from './prompts.js';
3
+ export { CodeSearchResult, CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult, SearchStats } from './types.js';
4
+ export { createCodebaseSearchTool as anthropicCodebaseSearchTool } from './anthropic.js';
5
+ export { createCodebaseSearchTool as openaiCodebaseSearchTool } from './openai.js';
6
+ export { createCodebaseSearchTool as vercelCodebaseSearchTool } from './vercel.js';
7
+ import '../utils/resilience.js';
8
+ import '@anthropic-ai/sdk/resources/messages';
9
+ import 'openai/resources/chat/completions';
10
+ import 'ai';
@@ -0,0 +1,87 @@
1
+ import { ChatCompletionTool } from 'openai/resources/chat/completions';
2
+ import { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';
3
+ import '../utils/resilience.js';
4
+
5
+ /**
6
+ * OpenAI SDK adapter for codebase_search tool
7
+ */
8
+
9
+ /**
10
+ * Direct codebase_search tool definition
11
+ * Use this when you want to pass config at execute time
12
+ */
13
+ declare const codebaseSearchTool: ChatCompletionTool;
14
+ /**
15
+ * Create OpenAI-native codebase_search tool with execute and formatResult methods
16
+ *
17
+ * @param config - Configuration with repoId
18
+ * @returns OpenAI ChatCompletionTool definition with methods
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import OpenAI from 'openai';
23
+ * import { createCodebaseSearchTool } from 'morphsdk/tools/openai';
24
+ *
25
+ * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
26
+ * const tool = createCodebaseSearchTool({ repoId: 'my-project' });
27
+ *
28
+ * const response = await client.chat.completions.create({
29
+ * model: "gpt-4o",
30
+ * tools: [tool], // tool itself is the ChatCompletionTool
31
+ * messages: [{ role: "user", content: "Find authentication code" }]
32
+ * });
33
+ *
34
+ * // Execute and format
35
+ * const result = await tool.execute(toolCallArgs);
36
+ * const formatted = tool.formatResult(result);
37
+ * ```
38
+ */
39
+ declare function createCodebaseSearchTool(config: CodebaseSearchConfig): ChatCompletionTool & {
40
+ execute: (input: CodebaseSearchInput | string) => Promise<CodebaseSearchResult>;
41
+ formatResult: (result: CodebaseSearchResult) => string;
42
+ getSystemPrompt: () => string;
43
+ };
44
+ /**
45
+ * Execute codebase_search tool call
46
+ *
47
+ * @param input - Tool input from GPT (parsed from tool_calls)
48
+ * @param config - Configuration with repoId (REQUIRED)
49
+ * @returns Search results
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * // Handle tool calls from GPT:
54
+ * if (response.choices[0].message.tool_calls) {
55
+ * for (const toolCall of response.choices[0].message.tool_calls) {
56
+ * const args = JSON.parse(toolCall.function.arguments);
57
+ * const result = await execute(args, { repoId: 'my-project' });
58
+ * console.log(`Found ${result.results.length} matches`);
59
+ * }
60
+ * }
61
+ * ```
62
+ */
63
+ declare function execute(input: CodebaseSearchInput, config: CodebaseSearchConfig): Promise<CodebaseSearchResult>;
64
+ /**
65
+ * Format search results for GPT
66
+ *
67
+ * @param result - Search result from endpoint
68
+ * @returns Formatted string for tool message
69
+ */
70
+ declare function formatResult(result: CodebaseSearchResult): string;
71
+ /**
72
+ * Get the system prompt for codebase_search usage
73
+ *
74
+ * @returns System prompt to guide GPT
75
+ */
76
+ declare function getSystemPrompt(): string;
77
+ /**
78
+ * Default export for convenience
79
+ */
80
+ declare const _default: {
81
+ createCodebaseSearchTool: typeof createCodebaseSearchTool;
82
+ execute: typeof execute;
83
+ formatResult: typeof formatResult;
84
+ getSystemPrompt: typeof getSystemPrompt;
85
+ };
86
+
87
+ export { codebaseSearchTool, createCodebaseSearchTool, _default as default, execute, formatResult, getSystemPrompt };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Tool descriptions and system prompts for codebase search
3
+ */
4
+ declare const CODEBASE_SEARCH_DESCRIPTION = "Semantic search that finds code by meaning, not exact text.\n\nUse this to explore unfamiliar codebases or ask \"how/where/what\" questions:\n- \"How does X work?\" - Find implementation details\n- \"Where is Y handled?\" - Locate specific functionality\n- \"What happens when Z?\" - Understand flow\n\nThe tool uses two-stage retrieval (embedding similarity + reranking) to find the most semantically relevant code chunks.\n\nReturns code chunks with file paths, line ranges, and full content ranked by relevance.";
5
+ declare const CODEBASE_SEARCH_SYSTEM_PROMPT = "You have access to the codebase_search tool that performs semantic code search.\n\nWhen searching:\n- Use natural language queries describing what you're looking for\n- Be specific about functionality, not variable names\n- Use target_directories to narrow search if you know the area\n- Results are ranked by relevance (rerank score is most important)\n\nThe tool returns:\n- File paths with symbol names (e.g. \"src/auth.ts::AuthService@L1-L17\")\n- Line ranges for precise navigation\n- Full code content for each match\n- Dual relevance scores: embedding similarity + rerank score\n\nUse results to understand code or answer questions. The content is provided in full - avoid re-reading unless you need more context.";
6
+
7
+ export { CODEBASE_SEARCH_DESCRIPTION, CODEBASE_SEARCH_SYSTEM_PROMPT };
@@ -0,0 +1,50 @@
1
+ import { RetryConfig } from '../utils/resilience.js';
2
+
3
+ /**
4
+ * Type definitions for codebase search tool
5
+ */
6
+
7
+ interface CodebaseSearchConfig {
8
+ repoId: string;
9
+ /** Optional branch name (e.g., 'main', 'develop'). Uses latest commit for that branch. */
10
+ branch?: string;
11
+ /** Optional commit hash. If specified, uses this exact commit. Takes precedence over branch. */
12
+ commitHash?: string;
13
+ searchUrl?: string;
14
+ apiKey?: string;
15
+ /** Timeout for search requests in ms (default: 30000) */
16
+ timeout?: number;
17
+ /** Retry configuration for API calls */
18
+ retryConfig?: RetryConfig;
19
+ /** Enable debug logging (default: false) */
20
+ debug?: boolean;
21
+ }
22
+ interface CodebaseSearchInput {
23
+ query: string;
24
+ target_directories?: string[];
25
+ explanation?: string;
26
+ limit?: number;
27
+ }
28
+ interface CodeSearchResult {
29
+ filepath: string;
30
+ symbolPath: string;
31
+ content: string;
32
+ language: string;
33
+ startLine: number;
34
+ endLine: number;
35
+ embeddingSimilarity: number;
36
+ rerankScore: number;
37
+ }
38
+ interface SearchStats {
39
+ totalResults: number;
40
+ candidatesRetrieved: number;
41
+ searchTimeMs: number;
42
+ }
43
+ interface CodebaseSearchResult {
44
+ success: boolean;
45
+ results: CodeSearchResult[];
46
+ stats: SearchStats;
47
+ error?: string;
48
+ }
49
+
50
+ export type { CodeSearchResult, CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult, SearchStats };