@morphllm/morphsdk 0.2.57 → 0.2.59
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-CaFUHxBW.d.ts +89 -0
- package/dist/{chunk-6X5UOY7B.js → chunk-2CASO3ZO.js} +46 -79
- package/dist/chunk-2CASO3ZO.js.map +1 -0
- package/dist/chunk-374N3GIA.js +118 -0
- package/dist/chunk-374N3GIA.js.map +1 -0
- package/dist/chunk-3IQIT6MC.js +65 -0
- package/dist/chunk-3IQIT6MC.js.map +1 -0
- package/dist/chunk-4VGOBA2J.js +57 -0
- package/dist/chunk-4VGOBA2J.js.map +1 -0
- package/dist/chunk-527P5X2E.js +98 -0
- package/dist/chunk-527P5X2E.js.map +1 -0
- package/dist/chunk-6N6ZYZYD.js +74 -0
- package/dist/chunk-6N6ZYZYD.js.map +1 -0
- package/dist/chunk-6Y5JB4JC.js +195 -0
- package/dist/chunk-6Y5JB4JC.js.map +1 -0
- package/dist/{chunk-TICMYDII.js → chunk-APP75CBN.js} +33 -16
- package/dist/chunk-APP75CBN.js.map +1 -0
- package/dist/{chunk-QFIHUCTF.js → chunk-FN4EP3WY.js} +19 -19
- package/dist/chunk-FN4EP3WY.js.map +1 -0
- package/dist/chunk-ILJ3J5IA.js +72 -0
- package/dist/chunk-ILJ3J5IA.js.map +1 -0
- package/dist/chunk-ISWL67SF.js +1 -0
- package/dist/chunk-KW7OEGZK.js +9 -0
- package/dist/chunk-KW7OEGZK.js.map +1 -0
- package/dist/chunk-Q5AHGIQO.js +205 -0
- package/dist/chunk-Q5AHGIQO.js.map +1 -0
- package/dist/{chunk-OXHGFHEU.js → chunk-VJU3BRET.js} +3 -3
- package/dist/chunk-VJU3BRET.js.map +1 -0
- package/dist/{chunk-TJIUA27P.js → chunk-XT5ZO6ES.js} +9 -5
- package/dist/chunk-XT5ZO6ES.js.map +1 -0
- package/dist/{chunk-LVPVVLTI.js → chunk-YV75OQTE.js} +105 -17
- package/dist/chunk-YV75OQTE.js.map +1 -0
- package/dist/{chunk-ZJIIICRA.js → chunk-ZO4PPFCZ.js} +60 -29
- package/dist/chunk-ZO4PPFCZ.js.map +1 -0
- package/dist/{client-CFoR--IU.d.ts → client-CextMMm9.d.ts} +10 -15
- package/dist/client.cjs +689 -343
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.ts +3 -2
- package/dist/client.js +15 -15
- package/dist/finish-kXAcUJyB.d.ts +33 -0
- package/dist/gemini-CE80Pbdy.d.ts +117 -0
- package/dist/git/client.cjs +2 -2
- package/dist/git/client.cjs.map +1 -1
- package/dist/git/client.d.ts +1 -1
- package/dist/git/client.js +1 -1
- package/dist/git/index.cjs +2 -2
- package/dist/git/index.cjs.map +1 -1
- package/dist/git/index.js +1 -1
- package/dist/git/types.cjs.map +1 -1
- package/dist/git/types.d.ts +1 -1
- package/dist/index.cjs +702 -343
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +17 -16
- package/dist/openai-Fvpqln7F.d.ts +89 -0
- package/dist/tools/warp_grep/agent/config.cjs +8 -4
- package/dist/tools/warp_grep/agent/config.cjs.map +1 -1
- package/dist/tools/warp_grep/agent/config.d.ts +7 -2
- package/dist/tools/warp_grep/agent/config.js +1 -1
- package/dist/tools/warp_grep/agent/formatter.cjs +32 -15
- package/dist/tools/warp_grep/agent/formatter.cjs.map +1 -1
- package/dist/tools/warp_grep/agent/formatter.d.ts +1 -1
- package/dist/tools/warp_grep/agent/formatter.js +1 -1
- package/dist/tools/warp_grep/agent/parser.cjs +104 -17
- package/dist/tools/warp_grep/agent/parser.cjs.map +1 -1
- package/dist/tools/warp_grep/agent/parser.d.ts +3 -5
- package/dist/tools/warp_grep/agent/parser.js +1 -3
- package/dist/tools/warp_grep/agent/prompt.cjs +132 -56
- package/dist/tools/warp_grep/agent/prompt.cjs.map +1 -1
- package/dist/tools/warp_grep/agent/prompt.d.ts +1 -1
- package/dist/tools/warp_grep/agent/prompt.js +1 -1
- package/dist/tools/warp_grep/agent/runner.cjs +459 -192
- package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
- package/dist/tools/warp_grep/agent/runner.d.ts +1 -0
- package/dist/tools/warp_grep/agent/runner.js +6 -8
- package/dist/tools/warp_grep/agent/types.cjs.map +1 -1
- package/dist/tools/warp_grep/agent/types.d.ts +9 -2
- package/dist/tools/warp_grep/anthropic.cjs +650 -260
- package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
- package/dist/tools/warp_grep/anthropic.d.ts +4 -74
- package/dist/tools/warp_grep/anthropic.js +13 -15
- package/dist/tools/warp_grep/client.cjs +1593 -0
- package/dist/tools/warp_grep/client.cjs.map +1 -0
- package/dist/tools/warp_grep/client.d.ts +87 -0
- package/dist/tools/warp_grep/client.js +26 -0
- package/dist/tools/warp_grep/gemini.cjs +1587 -0
- package/dist/tools/warp_grep/gemini.cjs.map +1 -0
- package/dist/tools/warp_grep/gemini.d.ts +7 -0
- package/dist/tools/warp_grep/gemini.js +34 -0
- package/dist/tools/warp_grep/harness.cjs +556 -220
- package/dist/tools/warp_grep/harness.cjs.map +1 -1
- package/dist/tools/warp_grep/harness.d.ts +50 -119
- package/dist/tools/warp_grep/harness.js +33 -41
- package/dist/tools/warp_grep/harness.js.map +1 -1
- package/dist/tools/warp_grep/index.cjs +812 -346
- package/dist/tools/warp_grep/index.cjs.map +1 -1
- package/dist/tools/warp_grep/index.d.ts +11 -6
- package/dist/tools/warp_grep/index.js +43 -22
- package/dist/tools/warp_grep/openai.cjs +650 -258
- package/dist/tools/warp_grep/openai.cjs.map +1 -1
- package/dist/tools/warp_grep/openai.d.ts +4 -74
- package/dist/tools/warp_grep/openai.js +13 -13
- package/dist/tools/warp_grep/providers/local.cjs +66 -27
- package/dist/tools/warp_grep/providers/local.cjs.map +1 -1
- package/dist/tools/warp_grep/providers/local.d.ts +4 -9
- package/dist/tools/warp_grep/providers/local.js +2 -2
- package/dist/tools/warp_grep/providers/remote.cjs +211 -0
- package/dist/tools/warp_grep/providers/remote.cjs.map +1 -0
- package/dist/tools/warp_grep/providers/remote.d.ts +67 -0
- package/dist/tools/warp_grep/providers/remote.js +9 -0
- package/dist/tools/warp_grep/providers/types.cjs.map +1 -1
- package/dist/tools/warp_grep/providers/types.d.ts +7 -15
- package/dist/tools/warp_grep/vercel.cjs +662 -277
- package/dist/tools/warp_grep/vercel.cjs.map +1 -1
- package/dist/tools/warp_grep/vercel.d.ts +4 -51
- package/dist/tools/warp_grep/vercel.js +16 -14
- package/dist/types-a_hxdPI6.d.ts +144 -0
- package/dist/vercel-3yjvfmVB.d.ts +66 -0
- package/package.json +12 -2
- package/dist/chunk-6X5UOY7B.js.map +0 -1
- package/dist/chunk-73RQWOQC.js +0 -16
- package/dist/chunk-73RQWOQC.js.map +0 -1
- package/dist/chunk-7OQOOB3R.js +0 -1
- package/dist/chunk-CFF636UC.js +0 -70
- package/dist/chunk-CFF636UC.js.map +0 -1
- package/dist/chunk-EK7OQPWD.js +0 -44
- package/dist/chunk-EK7OQPWD.js.map +0 -1
- package/dist/chunk-GJ5TYNRD.js +0 -107
- package/dist/chunk-GJ5TYNRD.js.map +0 -1
- package/dist/chunk-HQO45BAJ.js +0 -14
- package/dist/chunk-HQO45BAJ.js.map +0 -1
- package/dist/chunk-IMYQOKFO.js +0 -83
- package/dist/chunk-IMYQOKFO.js.map +0 -1
- package/dist/chunk-KBQWGT5L.js +0 -77
- package/dist/chunk-KBQWGT5L.js.map +0 -1
- package/dist/chunk-LVPVVLTI.js.map +0 -1
- package/dist/chunk-OXHGFHEU.js.map +0 -1
- package/dist/chunk-QFIHUCTF.js.map +0 -1
- package/dist/chunk-TICMYDII.js.map +0 -1
- package/dist/chunk-TJIUA27P.js.map +0 -1
- package/dist/chunk-WETRQJGU.js +0 -129
- package/dist/chunk-WETRQJGU.js.map +0 -1
- package/dist/chunk-ZJIIICRA.js.map +0 -1
- package/dist/core-CpkYEi_T.d.ts +0 -158
- package/dist/tools/warp_grep/tools/analyse.cjs +0 -40
- package/dist/tools/warp_grep/tools/analyse.cjs.map +0 -1
- package/dist/tools/warp_grep/tools/analyse.d.ts +0 -10
- package/dist/tools/warp_grep/tools/analyse.js +0 -8
- package/dist/tools/warp_grep/tools/finish.cjs +0 -69
- package/dist/tools/warp_grep/tools/finish.cjs.map +0 -1
- package/dist/tools/warp_grep/tools/finish.d.ts +0 -10
- package/dist/tools/warp_grep/tools/finish.js +0 -10
- package/dist/tools/warp_grep/tools/grep.cjs +0 -38
- package/dist/tools/warp_grep/tools/grep.cjs.map +0 -1
- package/dist/tools/warp_grep/tools/grep.d.ts +0 -8
- package/dist/tools/warp_grep/tools/grep.js +0 -15
- package/dist/tools/warp_grep/tools/grep.js.map +0 -1
- package/dist/tools/warp_grep/tools/read.cjs +0 -38
- package/dist/tools/warp_grep/tools/read.cjs.map +0 -1
- package/dist/tools/warp_grep/tools/read.d.ts +0 -9
- package/dist/tools/warp_grep/tools/read.js +0 -8
- package/dist/tools/warp_grep/utils/format.cjs +0 -42
- package/dist/tools/warp_grep/utils/format.cjs.map +0 -1
- package/dist/tools/warp_grep/utils/format.d.ts +0 -4
- package/dist/tools/warp_grep/utils/format.js +0 -18
- package/dist/tools/warp_grep/utils/format.js.map +0 -1
- /package/dist/{chunk-7OQOOB3R.js.map → chunk-ISWL67SF.js.map} +0 -0
- /package/dist/tools/warp_grep/{tools/analyse.js.map → client.js.map} +0 -0
- /package/dist/tools/warp_grep/{tools/finish.js.map → gemini.js.map} +0 -0
- /package/dist/tools/warp_grep/{tools/read.js.map → providers/remote.js.map} +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../index.ts","../tools/fastapply/core.ts","../tools/utils/resilience.ts","../tools/codebase_search/core.ts","../tools/browser/live.ts","../tools/browser/core.ts","../tools/warp_grep/agent/config.ts","../tools/warp_grep/agent/prompt.ts","../tools/warp_grep/agent/parser.ts","../tools/warp_grep/tools/read.ts","../tools/warp_grep/tools/analyse.ts","../tools/warp_grep/agent/formatter.ts","../tools/warp_grep/tools/finish.ts","../tools/warp_grep/agent/runner.ts","../tools/warp_grep/providers/local.ts","../tools/warp_grep/utils/ripgrep.ts","../tools/warp_grep/utils/paths.ts","../tools/warp_grep/utils/files.ts","../tools/warp_grep/core.ts","../git/client.ts","../git/index.ts","../modelrouter/core.ts","../tools/warp_grep/prompts.ts","../tools/warp_grep/openai.ts","../tools/codebase_search/prompts.ts","../tools/codebase_search/openai.ts","../tools/fastapply/prompts.ts","../tools/fastapply/openai.ts","../factories/openai.ts","../tools/warp_grep/anthropic.ts","../tools/codebase_search/anthropic.ts","../tools/fastapply/anthropic.ts","../factories/anthropic.ts","../tools/warp_grep/vercel.ts","../tools/codebase_search/vercel.ts","../tools/fastapply/vercel.ts","../factories/vercel.ts","../client.ts"],"sourcesContent":["/**\n * Morph SDK - Main Entry Point\n * \n * Provides two ways to use the SDK:\n * 1. MorphClient - Unified client with all tools and tool factories\n * 2. Individual tool clients - FastApplyClient, CodebaseSearchClient, WarpGrepClient, BrowserClient, etc.\n * \n * @example\n * ```typescript\n * // Unified client approach (recommended)\n * import { MorphClient } from '@morphllm/morphsdk';\n * \n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY \n * });\n * \n * // Direct execution\n * await morph.fastApply.execute({ ... });\n * await morph.warpGrep.execute({ query: 'Find auth', repoRoot: '.' });\n * \n * // Tool creation for AI agents (API key inherited)\n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.anthropic.createCodebaseSearchTool({ repoId: 'x' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * ```\n */\n\n// Export unified client\nexport { MorphClient } from './client.js';\nexport type { MorphClientConfig } from './client.js';\n\n// Export individual tool clients\nexport { FastApplyClient } from './tools/fastapply/core.js';\nexport { CodebaseSearchClient } from './tools/codebase_search/core.js';\nexport { WarpGrepClient } from './tools/warp_grep/core.js';\nexport { BrowserClient } from './tools/browser/core.js';\nexport { MorphGit } from './git/index.js';\n\n// Export WarpGrep providers\nexport { LocalRipgrepProvider } from './tools/warp_grep/index.js';\n\n// Export model routers\nexport { OpenAIRouter, AnthropicRouter, GeminiRouter, RawRouter } from './modelrouter/core.js';\n\n// Export tool factories\nexport { OpenAIToolFactory, AnthropicToolFactory, VercelToolFactory } from './factories/index.js';\n\n// Export applyEdit function for code-in/code-out workflow\nexport { applyEdit } from './tools/fastapply/core.js';\n\n// Re-export core types\nexport type {\n // FastApply types\n EditFileConfig,\n EditFileInput,\n EditFileResult,\n EditChanges,\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n} from './tools/fastapply/types.js';\n\nexport type {\n // CodebaseSearch types\n CodebaseSearchConfig,\n CodebaseSearchInput,\n CodebaseSearchResult,\n CodeSearchResult,\n SearchStats,\n} from './tools/codebase_search/types.js';\n\nexport type {\n // WarpGrep types\n WarpGrepClientConfig,\n WarpGrepInput,\n WarpGrepResult,\n WarpGrepContext,\n WarpGrepToolConfig,\n WarpGrepProvider,\n // Provider types for custom providers\n GrepResult,\n ReadResult,\n AnalyseEntry,\n} from './tools/warp_grep/types.js';\n\nexport type {\n // WarpGrep agent types (advanced usage)\n AgentRunResult,\n SessionConfig,\n ChatMessage,\n} from './tools/warp_grep/agent/types.js';\n\nexport type {\n // Browser types\n BrowserConfig,\n BrowserTaskInput,\n BrowserTaskInputWithSchema,\n BrowserTaskResult,\n BrowserTaskWithPromise,\n BrowserTaskWithPromiseAndSchema,\n RecordingStatus,\n BrowserError,\n ErrorsResponse,\n BrowserModel,\n LiveSessionOptions,\n IframeOptions,\n} from './tools/browser/types.js';\n\nexport type {\n // ModelRouter types\n RouterConfig,\n RouterInput,\n RouterResult,\n RawRouterResult,\n ComplexityLevel,\n RouterMode,\n Provider,\n} from './modelrouter/types.js';\n\nexport type {\n // Git types\n MorphGitConfig,\n} from './git/types.js';\n\nexport type {\n // Utility types\n RetryConfig,\n} from './tools/utils/resilience.js';\n\n","/**\n * Core implementation of Morph Fast Apply\n */\n\nimport { readFile, writeFile } from 'fs/promises';\nimport { join, resolve, relative } from 'path';\nimport { createTwoFilesPatch } from 'diff';\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport type {\n EditFileInput,\n EditFileResult,\n EditFileConfig,\n EditChanges,\n MorphApplyResponse,\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n} from './types.js';\n\nconst DEFAULT_CONFIG: Required<Omit<EditFileConfig, 'morphApiKey' | 'systemPrompt' | 'retryConfig' | 'description'>> = {\n morphApiUrl: 'https://api.morphllm.com',\n baseDir: process.cwd(),\n generateUdiff: true,\n autoWrite: true,\n timeout: 30000,\n debug: false,\n};\n\n/**\n * FastApply client for programmatic file editing\n */\nexport class FastApplyClient {\n private config: EditFileConfig;\n\n constructor(config: { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n this.config = {\n morphApiKey: config.apiKey,\n morphApiUrl: DEFAULT_CONFIG.morphApiUrl,\n debug: config.debug,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n retryConfig: config.retryConfig,\n generateUdiff: DEFAULT_CONFIG.generateUdiff,\n autoWrite: DEFAULT_CONFIG.autoWrite,\n };\n }\n\n /**\n * Execute a file edit operation\n * \n * @param input - Edit parameters including filepath, instructions, and code_edit\n * @param overrides - Optional config overrides for this operation\n * @returns Edit result with success status and changes\n */\n async execute(input: EditFileInput, overrides?: Partial<EditFileConfig>): Promise<EditFileResult> {\n return executeEditFile(input, { ...this.config, ...overrides });\n }\n\n /**\n * Apply an edit to code directly without file I/O\n * \n * Useful for sandbox environments or when you manage your own file system.\n * Compatible with the earlier OpenAI client API contract.\n * \n * @param input - Code and edit parameters\n * @param overrides - Optional config overrides for this operation\n * @returns Result with merged code\n * \n * @example\n * ```typescript\n * const result = await client.applyEdit({\n * originalCode: 'function hello() { return \"world\"; }',\n * codeEdit: 'function hello() { return \"universe\"; }',\n * instructions: 'Change return value'\n * });\n * console.log(result.mergedCode);\n * ```\n */\n async applyEdit(input: ApplyEditInput, overrides?: Partial<ApplyEditConfig>): Promise<ApplyEditResult> {\n return applyEdit(input, { ...this.config, ...overrides });\n }\n}\n\n/**\n * Generate a unified diff between two strings\n */\nexport function generateUdiff(\n original: string,\n modified: string,\n filepath: string\n): string {\n return createTwoFilesPatch(\n filepath,\n filepath,\n original,\n modified,\n 'Original',\n 'Modified'\n );\n}\n\n/**\n * Count changes from a unified diff\n */\nexport function countChanges(original: string, modified: string): EditChanges {\n const diff = generateUdiff(original, modified, 'file');\n const lines = diff.split('\\n');\n \n let linesAdded = 0;\n let linesRemoved = 0;\n \n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n linesAdded++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n linesRemoved++;\n }\n }\n \n const linesModified = Math.min(linesAdded, linesRemoved);\n \n return {\n linesAdded: linesAdded - linesModified,\n linesRemoved: linesRemoved - linesModified,\n linesModified,\n };\n}\n\n/**\n * Call Morph Apply API to merge code edits\n * Uses OpenAI-compatible chat completions endpoint with XML-formatted message\n */\nasync function callMorphAPI(\n originalCode: string,\n codeEdit: string,\n instructions: string,\n filepath: string,\n config: EditFileConfig\n): Promise<string> {\n const apiKey = config.morphApiKey || process.env.MORPH_API_KEY;\n const apiUrl = config.morphApiUrl || DEFAULT_CONFIG.morphApiUrl;\n const timeout = config.timeout || DEFAULT_CONFIG.timeout;\n const debug = config.debug || false;\n \n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n \n // Format message with XML tags as per Morph Fast Apply spec\n const message = `<instruction>${instructions}</instruction>\\n<code>${originalCode}</code>\\n<update>${codeEdit}</update>`;\n \n if (debug) {\n console.log(`[FastApply] Calling ${apiUrl}/v1/chat/completions`);\n console.log(`[FastApply] File: ${filepath}, Instructions: ${instructions.slice(0, 60)}...`);\n console.log(`[FastApply] Original: ${originalCode.length} chars, Edit: ${codeEdit.length} chars`);\n }\n \n const startTime = Date.now();\n \n // Fetch with retry and timeout\n const fetchPromise = fetchWithRetry(\n `${apiUrl}/v1/chat/completions`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: 'morph-v3-fast',\n messages: [{ role: 'user', content: message }],\n }),\n },\n config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n timeout,\n `Morph API request timed out after ${timeout}ms`\n );\n \n if (!response.ok) {\n const error = await response.text();\n if (debug) console.error(`[FastApply] API error: ${response.status} - ${error}`);\n throw new Error(`Morph API error (${response.status}): ${error}`);\n }\n \n const data: MorphApplyResponse = await response.json();\n const elapsed = Date.now() - startTime;\n \n if (debug) {\n console.log(`[FastApply] ✅ Success in ${elapsed}ms, merged: ${data.choices[0].message.content.length} chars`);\n }\n \n return data.choices[0].message.content;\n}\n\n/**\n * Execute a file edit using Morph Fast Apply\n */\nexport async function executeEditFile(\n input: EditFileInput,\n config: EditFileConfig = {}\n): Promise<EditFileResult> {\n const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;\n const fullPath = resolve(join(baseDir, input.target_filepath));\n const debug = config.debug || false;\n \n // Security: ensure file is within baseDir\n const relativePath = relative(baseDir, fullPath);\n if (relativePath.startsWith('..') || fullPath === baseDir) {\n return {\n success: false,\n filepath: input.target_filepath,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`,\n };\n }\n \n try {\n if (debug) console.log(`[FastApply] Reading file: ${input.target_filepath}`);\n \n // Handle both existing and non-existent files\n let originalCode = '';\n try {\n originalCode = await readFile(fullPath, 'utf-8');\n } catch (error: any) {\n if (error.code !== 'ENOENT') {\n throw error; // Re-throw if it's not a \"file not found\" error\n }\n // File doesn't exist, proceed with empty content (will create new file)\n if (debug) console.log(`[FastApply] File doesn't exist, will create new file`);\n }\n \n const mergedCode = await callMorphAPI(originalCode, input.code_edit, input.instructions, input.target_filepath, config);\n \n const udiff = config.generateUdiff !== false ? generateUdiff(originalCode, mergedCode, input.target_filepath) : undefined;\n \n if (config.autoWrite !== false) {\n await writeFile(fullPath, mergedCode, 'utf-8');\n if (debug) console.log(`[FastApply] Wrote ${mergedCode.length} chars to ${input.target_filepath}`);\n }\n \n const changes = countChanges(originalCode, mergedCode);\n \n return {\n success: true,\n filepath: input.target_filepath,\n udiff,\n changes,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n if (debug) console.error(`[FastApply] Error: ${errorMessage}`);\n \n return {\n success: false,\n filepath: input.target_filepath,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\n}\n\n/**\n * Apply an edit to code directly without file I/O\n * \n * This is the code-in/code-out API that accepts code content directly\n * and returns the merged result without reading or writing any files.\n * \n * @param input - Code and edit parameters\n * @param config - Optional configuration\n * @returns Result with merged code\n * \n * @example\n * ```typescript\n * import { applyEdit } from '@morphllm/morphsdk';\n * \n * const result = await applyEdit({\n * originalCode: fs.readFileSync('file.ts', 'utf-8'),\n * codeEdit: '// ... existing code ...\\nconst newVar = 42;\\n// ... existing code ...',\n * instructions: 'Add a new variable',\n * filepath: 'file.ts' // optional, for udiff context\n * });\n * \n * if (result.success) {\n * fs.writeFileSync('file.ts', result.mergedCode);\n * }\n * ```\n */\nexport async function applyEdit(\n input: ApplyEditInput,\n config: ApplyEditConfig = {}\n): Promise<ApplyEditResult> {\n const debug = config.debug || false;\n const filepath = input.filepath || 'file';\n\n try {\n if (debug) {\n console.log(`[FastApply] Applying edit to code (${input.originalCode.length} chars)`);\n }\n\n const mergedCode = await callMorphAPI(\n input.originalCode,\n input.codeEdit,\n input.instructions,\n filepath,\n config\n );\n\n const udiff = config.generateUdiff !== false\n ? generateUdiff(input.originalCode, mergedCode, filepath)\n : undefined;\n\n const changes = countChanges(input.originalCode, mergedCode);\n\n return {\n success: true,\n mergedCode,\n udiff,\n changes,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n if (debug) console.error(`[FastApply] Error: ${errorMessage}`);\n\n return {\n success: false,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\n}\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 codebase search\n * Calls Morph rerank service for two-stage semantic search\n */\n\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n/**\n * CodebaseSearch client for programmatic semantic search\n */\nexport class CodebaseSearchClient {\n private config: { \n apiKey?: string; \n searchUrl?: string; \n debug?: boolean; \n timeout?: number; \n retryConfig?: any;\n };\n\n constructor(config: { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n this.config = {\n apiKey: config.apiKey,\n searchUrl: process.env.MORPH_SEARCH_URL || 'https://repos.morphllm.com',\n debug: config.debug,\n timeout: config.timeout || 30000,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Execute a semantic code search\n * \n * @param input - Search parameters including query, repoId, and target directories\n * @param overrides - Optional config overrides for this operation\n * @returns Search results with ranked code matches\n */\n async search(\n input: { query: string; repoId: string; target_directories?: string[]; explanation?: string; limit?: number },\n overrides?: any\n ): Promise<CodebaseSearchResult> {\n return executeCodebaseSearch(\n {\n query: input.query,\n target_directories: input.target_directories,\n explanation: input.explanation,\n limit: input.limit,\n },\n { ...this.config, repoId: input.repoId, ...overrides }\n );\n }\n}\n\n/**\n * Execute semantic code search\n */\nexport async function executeCodebaseSearch(\n input: CodebaseSearchInput,\n config: CodebaseSearchConfig\n): Promise<CodebaseSearchResult> {\n const apiKey = config.apiKey || process.env.MORPH_API_KEY;\n if (!apiKey) {\n throw new Error('MORPH_API_KEY not found. Set environment variable or pass in config');\n }\n\n const searchUrl = config.searchUrl || process.env.MORPH_SEARCH_URL || 'https://repos.morphllm.com';\n const timeout = config.timeout || 30000;\n const debug = config.debug || false;\n\n if (debug) {\n console.log(`[CodebaseSearch] Query: \"${input.query.slice(0, 60)}...\" repo=${config.repoId}`);\n console.log(`[CodebaseSearch] URL: ${searchUrl}/v1/codebase_search`);\n }\n\n const startTime = Date.now();\n\n try {\n const fetchPromise = fetchWithRetry(\n `${searchUrl}/v1/codebase_search`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n query: input.query,\n repoId: config.repoId,\n targetDirectories: input.target_directories || [],\n limit: input.limit || 10,\n candidateLimit: 50,\n }),\n },\n config.retryConfig\n );\n\n const response = await withTimeout(fetchPromise, timeout, `Codebase search timed out after ${timeout}ms`);\n\n if (!response.ok) {\n const errorText = await response.text();\n if (debug) console.error(`[CodebaseSearch] Error: ${response.status} - ${errorText}`);\n return {\n success: false,\n results: [],\n stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },\n error: `Search failed (${response.status}): ${errorText}`,\n };\n }\n\n const data = await response.json();\n const elapsed = Date.now() - startTime;\n\n if (debug) {\n console.log(`[CodebaseSearch] ✅ ${data.results?.length || 0} results in ${elapsed}ms`);\n }\n\n return {\n success: true,\n results: data.results || [],\n stats: data.stats || { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: elapsed },\n };\n\n } catch (error) {\n if (debug) console.error(`[CodebaseSearch] Exception: ${error instanceof Error ? error.message : error}`);\n return {\n success: false,\n results: [],\n stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n}\n\n","/**\n * Live session utilities for Morph browser sessions\n * \n * Provides helpers for embedding and sharing live browser sessions with WebRTC streaming.\n */\n\nimport type { LiveSessionOptions, IframeOptions } from './types.js';\n\n/**\n * Preset configurations for common use cases\n */\nexport const LIVE_PRESETS = {\n /** Read-only monitoring (no interaction) */\n readonly: { interactive: false } as LiveSessionOptions,\n /** Interactive control (human-in-the-loop) */\n interactive: { interactive: true } as LiveSessionOptions,\n /** Watch-only without controls */\n monitoring: { interactive: false, showControls: false } as LiveSessionOptions,\n} as const;\n\n/**\n * Build a live session URL with query parameters\n * \n * @param debugUrl - Live session debug URL (e.g., from task.debugUrl)\n * @param options - Live session configuration options\n * @returns URL with query parameters for iframe embedding\n * \n * @example\n * ```typescript\n * const url = buildLiveUrl(task.debugUrl, { interactive: true });\n * // Returns: https://example.com/sessions/abc?interactive=true\n * ```\n */\nexport function buildLiveUrl(\n debugUrl: string,\n options: LiveSessionOptions = {}\n): string {\n if (!debugUrl) {\n throw new Error(\n 'debugUrl is required. Ensure your backend returns debugUrl in the task response. ' +\n 'Contact support@morphllm.com if you need help.'\n );\n } \n\n const url = new URL(debugUrl);\n \n // Add query parameters for supported options\n if (options.interactive !== undefined) {\n url.searchParams.set('interactive', String(options.interactive));\n }\n \n if (options.theme) {\n url.searchParams.set('theme', options.theme);\n }\n \n if (options.showControls !== undefined) {\n url.searchParams.set('showControls', String(options.showControls));\n }\n \n if (options.pageId) {\n url.searchParams.set('pageId', options.pageId);\n }\n \n if (options.pageIndex) {\n url.searchParams.set('pageIndex', options.pageIndex);\n }\n \n return url.toString();\n}\n\n/**\n * Build iframe HTML for embedding a live session\n * \n * @param debugUrl - Live session debug URL\n * @param options - Iframe configuration including dimensions and session options\n * @returns HTML iframe element as string\n * \n * @example\n * ```typescript\n * const iframe = buildLiveIframe(task.debugUrl, {\n * interactive: true,\n * width: '100%',\n * height: '600px'\n * });\n * ```\n */\nexport function buildLiveIframe(\n debugUrl: string,\n options: IframeOptions = {}\n): string {\n const {\n width = '100%',\n height = '600px',\n style = '',\n className = '',\n ...sessionOptions\n } = options;\n\n const src = buildLiveUrl(debugUrl, sessionOptions);\n \n // Convert numeric dimensions to pixels\n const widthStr = typeof width === 'number' ? `${width}px` : width;\n const heightStr = typeof height === 'number' ? `${height}px` : height;\n \n // Build style attribute\n const baseStyle = `width: ${widthStr}; height: ${heightStr}; border: none;`;\n const fullStyle = style ? `${baseStyle} ${style}` : baseStyle;\n \n // Build iframe attributes\n const attributes = [\n `src=\"${src}\"`,\n `style=\"${fullStyle}\"`,\n ];\n \n if (className) {\n attributes.push(`class=\"${className}\"`);\n }\n \n return `<iframe ${attributes.join(' ')}></iframe>`;\n}\n\n/**\n * Build complete embed code with HTML snippet\n * \n * @param debugUrl - Live session debug URL\n * @param options - Iframe configuration\n * @returns Multi-line HTML snippet ready to copy-paste\n * \n * @example\n * ```typescript\n * const code = buildEmbedCode(task.debugUrl, { interactive: false });\n * console.log(code);\n * // <!-- Embed Morph Live Session -->\n * // <iframe src=\"...\" style=\"...\"></iframe>\n * ```\n */\nexport function buildEmbedCode(\n debugUrl: string,\n options: IframeOptions = {}\n): string {\n const iframe = buildLiveIframe(debugUrl, options);\n return `<!-- Embed Morph Live Session -->\\n${iframe}`;\n}\n\n/**\n * Get live session options from preset name or custom config\n * \n * @internal\n */\nexport function resolvePreset(\n optionsOrPreset?: string | IframeOptions\n): IframeOptions {\n if (!optionsOrPreset) {\n return {};\n }\n \n if (typeof optionsOrPreset === 'string') {\n const preset = LIVE_PRESETS[optionsOrPreset as keyof typeof LIVE_PRESETS];\n if (!preset) {\n throw new Error(\n `Unknown preset: ${optionsOrPreset}. Available presets: ${Object.keys(LIVE_PRESETS).join(', ')}`\n );\n }\n return preset;\n }\n \n return optionsOrPreset;\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: 1000000, // 10 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 const apiUrl = this.config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = this.config.debug || false;\n \n if (debug) {\n console.log(`[Browser] createTask: \"${input.task.slice(0, 60)}...\" url=${input.url || 'none'}`);\n console.log(`[Browser] Calling async endpoint: ${apiUrl}/browser-task/async`);\n }\n \n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.config.apiKey) headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n \n // Call ASYNC endpoint for immediate return with live URL\n const response = await fetch(`${apiUrl}/browser-task/async`, {\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 allow_resizing: input.allow_resizing ?? false,\n structured_output: 'schema' in input ? stringifyStructuredOutput(input.schema) : undefined,\n }),\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 = await response.json();\n \n if (debug) {\n console.log(`[Browser] ✅ Task created: recording_id=${result.recording_id ?? 'none'} debug_url=${result.debugUrl ? 'available' : 'none'}`);\n }\n \n if ('schema' in input) {\n return wrapTaskResponseWithSchema(result, this.config, input.schema);\n } else {\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 * Returns the full task result including rich agent history data (urls, errors, \n * action_history, judgement, etc.). When using this as an agent tool, use the\n * formatResult() functions from the SDK adapters to return a concise summary.\n * \n * @param input - Task parameters\n * @param config - Optional configuration (apiKey, apiUrl to override default)\n * @returns Task result with success status, findings, and comprehensive execution history\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('URLs visited:', result.urls);\n * console.log('Actions taken:', result.action_names);\n * console.log('Has errors:', result.has_errors);\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 allow_resizing: input.allow_resizing ?? false,\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 const wrapped: BrowserTaskWithPromise = {\n ...result,\n task_id: result.task_id || '',\n liveUrl: result.task_id \n ? generateLiveUrl(result.task_id, config)\n : result.debugUrl || '',\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n // If we have a task_id, poll task status endpoint\n if (result.task_id) {\n return pollTaskUntilComplete(result.task_id!, config, pollConfig);\n }\n // If we have a recording_id, poll recording status instead\n if (result.recording_id) {\n const recording = await waitForRecording(\n result.recording_id,\n config,\n pollConfig\n );\n // Return a result-like object (recording doesn't have full task result)\n return {\n ...result,\n recording_status: recording.status,\n } as BrowserTaskResult;\n }\n // No way to poll completion\n throw new Error('Cannot poll completion: no task_id or recording_id available');\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 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: result.task_id\n ? generateLiveUrl(result.task_id, config)\n : result.debugUrl || '',\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n // If we have a task_id, poll task status endpoint\n if (result.task_id) {\n const finalResult = await pollTaskUntilComplete(result.task_id!, config, pollConfig);\n return parseStructuredTaskOutput<T>(finalResult, schema);\n }\n // If we have a recording_id, poll recording status instead\n if (result.recording_id) {\n const recording = await waitForRecording(\n result.recording_id,\n config,\n pollConfig\n );\n // Return parsed result (recording doesn't have task output)\n return {\n ...parsed,\n recording_status: recording.status,\n };\n }\n // No way to poll completion\n throw new Error('Cannot poll completion: no task_id or recording_id available');\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","// Agent configuration defaults for morph-warp-grep\n// Hard-coded: SDK does not expose control over rounds or timeout.\nexport const AGENT_CONFIG = {\n // Give the model freedom; failsafe cap to prevent infinite loops\n MAX_ROUNDS: 10,\n TIMEOUT_MS: 30000,\n};\n\n/**\n * Comprehensive exclusion list for directories and files\n * These patterns are used with ripgrep's -g flag\n */\nconst BUILTIN_EXCLUDES = [\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n \n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'packages', 'Pods', '.bundle',\n \n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs', '*.egg-info',\n \n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n \n // Cache directories\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n \n // IDE/Editor\n '.idea', '.vscode', '.vs',\n \n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n \n // Temporary\n 'tmp', 'temp', '.tmp', '.temp',\n \n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n \n // Binary/minified\n '*.min.js', '*.min.css', '*.bundle.js',\n '*.wasm', '*.so', '*.dll', '*.pyc',\n '*.map', '*.js.map',\n \n // Hidden directories catch-all\n '.*',\n];\n\nexport const DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || '')\n .split(',')\n .map(s => s.trim())\n .filter(Boolean)\n .concat(BUILTIN_EXCLUDES);\n\nexport const DEFAULT_MODEL = 'morph-warp-grep';\n\n\n","export const SYSTEM_PROMPT = `You are a code search agent. Your task is to find all relevant code for a given query.\n\n<workflow>\nYou have exactly 4 turns. The 4th turn MUST be a \\`finish\\` call. Each turn allows up to 8 parallel tool calls.\n\n- Turn 1: Map the territory OR dive deep (based on query specificity)\n- Turn 2-3: Refine based on findings\n- Turn 4: MUST call \\`finish\\` with all relevant code locations\n- You MAY call \\`finish\\` early if confident—but never before at least 1 search turn.\n\nRemember, if the task feels easy to you, it is strongly desirable to call \\`finish\\` early using fewer turns, but quality over speed.\n</workflow>\n\n<tools>\n### \\`analyse <path> [pattern]\\`\nDirectory tree or file search. Shows structure of a path, optionally filtered by regex pattern.\n- \\`path\\`: Required. Directory or file path (use \\`.\\` for repo root)\n- \\`pattern\\`: Optional regex to filter results\n\nExamples:\n\\`\\`\\`\nanalyse .\nanalyse src/api\nanalyse . \".*\\\\.ts$\"\nanalyse src \"test.*\"\n\\`\\`\\`\n\n### \\`read <path>[:start-end]\\`\nRead file contents. Line range is 1-based, inclusive.\n- Returns numbered lines for easy reference\n- Omit range to read entire file\n\nExamples:\n\\`\\`\\`\nread src/main.py\nread src/db/conn.py:10-50\nread package.json:1-20\n\\`\\`\\`\n\n### \\`grep '<pattern>' <path>\\`\nRipgrep search. Finds pattern matches across files.\n- \\`'<pattern>'\\`: Required. Regex pattern wrapped in single quotes\n- \\`<path>\\`: Required. Directory or file to search (use \\`.\\` for repo root)\n\nExamples:\n\\`\\`\\`\ngrep 'class.*Service' src/\ngrep 'def authenticate' .\ngrep 'import.*from' src/components/\ngrep 'TODO' .\n\\`\\`\\`\n\n### \\`finish <file1:ranges> [file2:ranges ...]\\`\nSubmit final answer with all relevant code locations.\n- Include generous line ranges—don't be stingy with context\n- Ranges are comma-separated: \\`file.py:10-30,50-60\\`\n- ALWAYS include import statements at the top of files (usually lines 1-20)\n- If code spans multiple files, include ALL of them\n- Small files can be returned in full\n\nExamples:\n\\`\\`\\`\nfinish src/auth.py:1-15,25-50,75-80 src/models/user.py:1-10,20-45\nfinish src/index.ts:1-100\n\\`\\`\\`\n</tools>\n\n<strategy>\n**Before your first tool call, classify the query:**\n\n| Query Type | Turn 1 Strategy | Early Finish? |\n|------------|-----------------|---------------|\n| **Specific** (function name, error string, unique identifier) | 8 parallel greps on likely paths | Often by turn 2 |\n| **Conceptual** (how does X work, where is Y handled) | analyse + 2-3 broad greps | Rarely early |\n| **Exploratory** (find all tests, list API endpoints) | analyse at multiple depths | Usually needs 3 turns |\n\n**Parallel call patterns:**\n- **Shotgun grep**: Same pattern, 8 different directories—fast coverage\n- **Variant grep**: 8 pattern variations (synonyms, naming conventions)—catches inconsistent codebases\n- **Funnel**: 1 analyse + 7 greps—orient and search simultaneously\n- **Deep read**: 8 reads on files you already identified—gather full context fast\n</strategy>\n\n<output_format>\nEVERY response MUST follow this exact format:\n\n1. First, wrap your reasoning in \\`<think>...</think>\\` tags containing:\n - Query classification (specific/conceptual/exploratory)\n - Confidence estimate (can I finish in 1-2 turns?)\n - This turn's parallel strategy\n - What signals would let me finish early?\n\n2. Then, output tool calls wrapped in \\`<tool_call>...</tool_call>\\` tags, one per line.\n\nExample:\n\\`\\`\\`\n<think>\nThis is a specific query about authentication. I'll grep for auth-related patterns.\nHigh confidence I can finish in 2 turns if I find the auth module.\nStrategy: Shotgun grep across likely directories.\n</think>\n<tool_call>grep 'authenticate' src/</tool_call>\n<tool_call>grep 'login' src/</tool_call>\n<tool_call>analyse src/auth</tool_call>\n\\`\\`\\`\n\nNo commentary outside \\`<think>\\`. No explanations after tool calls.\n</output_format>\n\n<finishing_requirements>\nWhen calling \\`finish\\`:\n- Include the import section (typically lines 1-20) of each file\n- Include all function/class definitions that are relevant\n- Include any type definitions, interfaces, or constants used\n- Better to over-include than leave the user missing context\n- If unsure about boundaries, include more rather than less\n</finishing_requirements>\n\nBegin your exploration now to find code relevant to the query.`;\n\nexport function getSystemPrompt(): string {\n\treturn SYSTEM_PROMPT;\n}\n","// Parses assistant lines into structured tool calls\nimport type { ToolCall } from './types.js';\n\n// Keep for backwards compatibility - no longer thrown, but exported for tests\nexport class LLMResponseParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'LLMResponseParseError';\n }\n}\n\n// Valid tool command names\nconst VALID_COMMANDS = ['analyse', 'grep', 'read', 'finish'];\n\n/**\n * Preprocesses text to handle XML tags:\n * 1. Removes <think>...</think> blocks entirely\n * 2. Extracts content from <tool>...</tool> or <tool_call>...</tool_call> tags\n * 3. Passes through raw tool calls (lines starting with valid commands)\n * 4. Discards unclosed <tool...> tags\n */\nfunction preprocessText(text: string): string[] {\n // Step 1: Remove <think>...</think> blocks (including multiline)\n let processed = text.replace(/<think>[\\s\\S]*?<\\/think>/gi, '');\n \n // Step 2: Check for unclosed <tool or <tool_call tags and discard them\n // Find all opening tags and their positions\n const openingTagRegex = /<tool_call>|<tool>/gi;\n const closingTagRegex = /<\\/tool_call>|<\\/tool>/gi;\n \n // Count opening and closing tags\n const openingMatches = processed.match(openingTagRegex) || [];\n const closingMatches = processed.match(closingTagRegex) || [];\n \n // If there are more opening than closing tags, we have unclosed tags\n // In that case, only process complete tag pairs\n if (openingMatches.length > closingMatches.length) {\n // Remove any content after the last complete closing tag\n const lastClosingMatch = /<\\/tool_call>|<\\/tool>/gi;\n let lastClosingIndex = -1;\n let match;\n while ((match = lastClosingMatch.exec(processed)) !== null) {\n lastClosingIndex = match.index + match[0].length;\n }\n if (lastClosingIndex > 0) {\n processed = processed.slice(0, lastClosingIndex);\n }\n }\n \n // Step 3: Extract content from <tool_call>...</tool_call> and <tool>...</tool> tags\n const toolCallLines: string[] = [];\n const toolTagRegex = /<tool_call>([\\s\\S]*?)<\\/tool_call>|<tool>([\\s\\S]*?)<\\/tool>/gi;\n let tagMatch;\n \n while ((tagMatch = toolTagRegex.exec(processed)) !== null) {\n const content = (tagMatch[1] || tagMatch[2] || '').trim();\n if (content) {\n // Split content by newlines in case there are multiple tool calls in one tag\n const lines = content.split(/\\r?\\n/).map(l => l.trim()).filter(l => l);\n toolCallLines.push(...lines);\n }\n }\n \n // Step 4: Also extract raw tool calls (lines starting with valid commands)\n // This provides backwards compatibility\n const allLines = processed.split(/\\r?\\n/).map(l => l.trim());\n for (const line of allLines) {\n if (!line) continue;\n \n // Skip lines that are inside XML tags (already processed above)\n if (line.startsWith('<')) continue;\n \n // Check if line starts with a valid command\n const firstWord = line.split(/\\s/)[0];\n if (VALID_COMMANDS.includes(firstWord)) {\n // Avoid duplicates\n if (!toolCallLines.includes(line)) {\n toolCallLines.push(line);\n }\n }\n }\n \n return toolCallLines;\n}\n\nexport class LLMResponseParser {\n private readonly finishSpecSplitRe = /,(?=[^,\\s]+:)/;\n\n parse(text: string): ToolCall[] {\n if (typeof text !== 'string') {\n // no way we hit this, but sure, we can throw here\n throw new TypeError('Command text must be a string.');\n }\n \n // Preprocess to handle XML tags\n const lines = preprocessText(text);\n \n const commands: ToolCall[] = [];\n let finishAccumulator: Map<string, number[][]> | null = null;\n\n lines.forEach((line) => {\n if (!line || line.startsWith('#')) return;\n const parts = this.splitLine(line);\n if (parts.length === 0) return;\n const cmd = parts[0];\n switch (cmd) {\n case 'analyse':\n this.handleAnalyse(parts, line, commands);\n break;\n case 'grep':\n this.handleGrep(parts, line, commands);\n break;\n case 'read':\n this.handleRead(parts, line, commands);\n break;\n case 'finish':\n finishAccumulator = this.handleFinish(parts, line, commands, finishAccumulator);\n break;\n default:\n // Silently ignore unknown commands after preprocessing\n // (they might be remnants of XML or other content)\n break;\n }\n });\n\n if (finishAccumulator) {\n const map = finishAccumulator as Map<string, number[][]>;\n const entries = [...map.entries()];\n const filesPayload = entries.map(([path, ranges]) => ({\n path,\n lines: [...ranges].sort((a, b) => a[0] - b[0]) as Array<[number, number]>,\n }));\n commands.push({ name: 'finish', arguments: { files: filesPayload } });\n }\n return commands;\n }\n\n private splitLine(line: string): string[] {\n // Split by whitespace but keep quoted blocks as one\n const parts: string[] = [];\n let current = '';\n let inSingle = false;\n for (let i = 0; i < line.length; i++) {\n const ch = line[i];\n if (ch === \"'\" && line[i - 1] !== '\\\\') {\n inSingle = !inSingle;\n current += ch;\n } else if (!inSingle && /\\s/.test(ch)) {\n if (current) {\n parts.push(current);\n current = '';\n }\n } else {\n current += ch;\n }\n }\n if (current) parts.push(current);\n return parts;\n }\n\n /** Helper to create a _skip tool call with an error message */\n private skip(message: string): ToolCall {\n return { name: '_skip', arguments: { message } };\n }\n\n private handleAnalyse(parts: string[], rawLine: string, commands: ToolCall[]) {\n // analyse <path> [pattern]\n if (parts.length < 2) {\n commands.push(this.skip(\n `[SKIPPED] Your command \"${rawLine}\" is missing a path. ` +\n `Correct format: analyse <path> [pattern]. Example: analyse src/`\n ));\n return;\n }\n const path = parts[1];\n const pattern = parts[2]?.replace(/^\"|\"$/g, '') ?? null;\n commands.push({ name: 'analyse', arguments: { path, pattern } });\n }\n\n // no glob tool in MCP\n\n private handleGrep(parts: string[], rawLine: string, commands: ToolCall[]) {\n // grep '<pattern>' <path>\n if (parts.length < 3) {\n commands.push(this.skip(\n `[SKIPPED] Your command \"${rawLine}\" is missing arguments. ` +\n `Correct format: grep '<pattern>' <path>. Example: grep 'TODO' src/`\n ));\n return;\n }\n let pat = parts[1];\n // Be lenient: accept unquoted patterns by treating the first arg as the pattern\n if (pat.startsWith(\"'\") && pat.endsWith(\"'\")) {\n pat = pat.slice(1, -1);\n }\n // If pattern is empty after processing, skip\n if (!pat) {\n commands.push(this.skip(\n `[SKIPPED] Your command \"${rawLine}\" has an empty pattern. ` +\n `Provide a non-empty search pattern. Example: grep 'function' src/`\n ));\n return;\n }\n commands.push({ name: 'grep', arguments: { pattern: pat, path: parts[2] } });\n }\n\n private handleRead(parts: string[], rawLine: string, commands: ToolCall[]) {\n // read <path>[:start-end]\n if (parts.length < 2) {\n commands.push(this.skip(\n `[SKIPPED] Your command \"${rawLine}\" is missing a path. ` +\n `Correct format: read <path> or read <path>:<start>-<end>. Example: read src/index.ts:1-50`\n ));\n return;\n }\n const spec = parts[1];\n const rangeIdx = spec.indexOf(':');\n if (rangeIdx === -1) {\n commands.push({ name: 'read', arguments: { path: spec } });\n return;\n }\n const filePath = spec.slice(0, rangeIdx);\n const range = spec.slice(rangeIdx + 1);\n const [s, e] = range.split('-').map(v => parseInt(v, 10));\n // If range is invalid, fallback to reading the whole file\n if (!Number.isFinite(s) || !Number.isFinite(e)) {\n commands.push({ name: 'read', arguments: { path: filePath } });\n return;\n }\n commands.push({ name: 'read', arguments: { path: filePath, start: s, end: e } });\n }\n\n private handleFinish(parts: string[], rawLine: string, commands: ToolCall[], acc: Map<string, number[][]> | null) {\n // finish file1:1-10,20-30 file2:5-7\n const map = acc ?? new Map<string, number[][]>();\n const args = parts.slice(1);\n for (const token of args) {\n const [filePath, rangesText] = token.split(':', 2);\n if (!filePath || !rangesText) {\n // Skip this malformed token, continue processing others\n commands.push(this.skip(\n `[SKIPPED] Invalid finish token \"${token}\". ` +\n `Correct format: finish <path>:<start>-<end>. Example: finish src/index.ts:1-50`\n ));\n continue;\n }\n const rangeSpecs = rangesText.split(',').filter(Boolean);\n for (const spec of rangeSpecs) {\n const [s, e] = spec.split('-').map(v => parseInt(v, 10));\n if (!Number.isFinite(s) || !Number.isFinite(e) || e < s) {\n // Skip this invalid range, continue with others\n commands.push(this.skip(\n `[SKIPPED] Invalid range \"${spec}\" in \"${token}\". ` +\n `Ranges must be <start>-<end> where start <= end. Example: 1-50`\n ));\n continue;\n }\n const arr = map.get(filePath) ?? [];\n arr.push([s, e]);\n map.set(filePath, arr);\n }\n }\n return map;\n }\n}\n","import type { WarpGrepProvider } from '../providers/types.js';\n\nexport async function toolRead(\n provider: WarpGrepProvider,\n args: { path: string; start?: number; end?: number }\n): Promise<string> {\n const res = await provider.read({ path: args.path, start: args.start, end: args.end });\n // Return error message if present (graceful handling)\n if (res.error) {\n return res.error;\n }\n if (!res.lines.length) return '(empty file)';\n return res.lines.join('\\n');\n}\n\n\n","import type { WarpGrepProvider } from '../providers/types.js';\n\nexport async function toolAnalyse(\n provider: WarpGrepProvider,\n args: { path: string; pattern?: string | null; maxResults?: number; maxDepth?: number }\n): Promise<string> {\n const list = await provider.analyse({\n path: args.path,\n pattern: args.pattern ?? null,\n maxResults: args.maxResults ?? 100,\n maxDepth: args.maxDepth ?? 2,\n });\n if (!list.length) return 'empty';\n return list\n .map((e) => `${' '.repeat(e.depth)}- ${e.type === 'dir' ? '[D]' : '[F]'} ${e.name}`)\n .join('\\n');\n}\n\n\n","export class ToolOutputFormatter {\n\tformat(\n\t\ttoolName: string,\n\t\targs: Record<string, unknown> | null | undefined,\n\t\toutput: string,\n\t\toptions: { isError?: boolean } = {}\n\t): string {\n\t\tconst name = (toolName ?? \"\").trim();\n\t\tif (!name) {\n\t\t\treturn \"\";\n\t\t}\n\t\tconst payload = (output as any)?.toString?.()?.trim?.() ?? \"\";\n\t\tconst isError = Boolean(options.isError);\n\t\tconst safeArgs = args ?? {};\n\n\t\tif (!payload && !isError) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\tswitch (name) {\n\t\t\tcase \"read\":\n\t\t\t\treturn this.formatRead(safeArgs, payload, isError);\n\t\t\tcase \"analyse\":\n\t\t\t\treturn this.formatAnalyse(safeArgs, payload, isError);\n\t\t\tcase \"grep\":\n\t\t\t\treturn this.formatGrep(safeArgs, payload, isError);\n\t\t\tdefault:\n\t\t\t\treturn payload ? `<tool_output>\\n${payload}\\n</tool_output>` : \"\";\n\t\t}\n\t}\n\n\tprivate formatRead(args: Record<string, unknown>, payload: string, isError: boolean): string {\n\t\tif (isError) {\n\t\t\treturn payload;\n\t\t}\n\t\tconst path = this.asString(args.path) || \"...\";\n\t\treturn `<file path=\"${path}\">\\n${payload}\\n</file>`;\n\t}\n\n\tprivate formatAnalyse(args: Record<string, unknown>, payload: string, isError: boolean): string {\n\t\tconst path = this.asString(args.path) || \".\";\n\t\tif (isError) {\n\t\t\treturn `<analyse_results path=\"${path}\" status=\"error\">\\n${payload}\\n</analyse_results>`;\n\t\t}\n\t\treturn `<analyse_results path=\"${path}\">\\n${payload}\\n</analyse_results>`;\n\t}\n\n\tprivate formatGrep(args: Record<string, unknown>, payload: string, isError: boolean): string {\n\t\tconst pattern = this.asString(args.pattern);\n\t\tconst path = this.asString(args.path);\n\t\tconst attributes: string[] = [];\n\t\tif (pattern !== undefined) {\n\t\t\tattributes.push(`pattern=\"${pattern}\"`);\n\t\t}\n\t\tif (path !== undefined) {\n\t\t\tattributes.push(`path=\"${path}\"`);\n\t\t}\n\t\tif (isError) {\n\t\t\tattributes.push('status=\"error\"');\n\t\t}\n\t\tconst attrText = attributes.length ? ` ${attributes.join(\" \")}` : \"\";\n\t\treturn `<grep_output${attrText}>\\n${payload}\\n</grep_output>`;\n\t}\n\n\tprivate asString(value: unknown): string | undefined {\n\t\tif (value === null || value === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn String(value);\n\t}\n}\n\nconst sharedFormatter = new ToolOutputFormatter();\n\nexport function formatAgentToolOutput(\n\ttoolName: string,\n\targs: Record<string, unknown> | null | undefined,\n\toutput: string,\n\toptions: { isError?: boolean } = {}\n): string {\n\treturn sharedFormatter.format(toolName, args, output, options);\n}\n\n","import type { FinishFileSpec } from '../agent/types.js';\nimport fs from 'fs/promises';\n\nexport function normalizeFinishFiles(files: FinishFileSpec[]): FinishFileSpec[] {\n return files.map((f) => {\n const merged = mergeRanges(f.lines);\n return { path: f.path, lines: merged };\n });\n}\n\nexport async function readFinishFiles(\n repoRoot: string,\n files: FinishFileSpec[],\n reader: (path: string, start: number, end: number) => Promise<string[]>\n): Promise<{ path: string; ranges: Array<[number, number]>; content: string }[]> {\n const out: { path: string; ranges: Array<[number, number]>; content: string }[] = [];\n for (const f of files) {\n const ranges = mergeRanges(f.lines);\n const chunks: string[] = [];\n for (const [s, e] of ranges) {\n const lines = await reader(f.path, s, e);\n chunks.push(lines.join('\\n'));\n }\n out.push({ path: f.path, ranges, content: chunks.join('\\n') });\n }\n return out;\n}\n\nfunction mergeRanges(ranges: Array<[number, number]>): Array<[number, number]> {\n if (!ranges.length) return [];\n const sorted = [...ranges].sort((a, b) => a[0] - b[0]);\n const merged: Array<[number, number]> = [];\n let [cs, ce] = sorted[0];\n for (let i = 1; i < sorted.length; i++) {\n const [s, e] = sorted[i];\n if (s <= ce + 1) {\n ce = Math.max(ce, e);\n } else {\n merged.push([cs, ce]);\n cs = s;\n ce = e;\n }\n }\n merged.push([cs, ce]);\n return merged;\n}\n\n\n","import { AGENT_CONFIG, DEFAULT_MODEL } from './config.js';\nimport { getSystemPrompt } from './prompt.js';\nimport type { AgentRunResult, ChatMessage, SessionConfig, ToolCall, AgentFinish } from './types.js';\nimport { LLMResponseParser } from './parser.js';\nimport type { WarpGrepProvider } from '../providers/types.js';\nimport { toolRead } from '../tools/read.js';\nimport { toolAnalyse } from '../tools/analyse.js';\nimport { fetchWithRetry, withTimeout } from '../../utils/resilience.js';\nimport { formatAgentToolOutput } from './formatter.js';\nimport { readFinishFiles } from '../tools/finish.js';\nimport path from 'path';\n\ntype EventName =\n | 'initial_state'\n | 'round_start'\n | 'round_end'\n | 'finish'\n | 'error';\n\nexport type EventCallback = (name: EventName, payload: Record<string, unknown>) => void;\n\nconst parser = new LLMResponseParser();\n\nasync function buildInitialState(repoRoot: string, query: string, provider: WarpGrepProvider): Promise<string> {\n // Summarize top-level directories and file counts using the provider\n // This works for both local and remote filesystems (Modal, E2B, etc.)\n try {\n const entries = await provider.analyse({ path: '.', maxResults: 100 });\n const dirs = entries.filter(e => e.type === 'dir').map(d => d.name).slice(0, 50);\n const files = entries.filter(e => e.type === 'file').map(f => f.name).slice(0, 50);\n const parts = [\n `<repo_root>${repoRoot}</repo_root>`,\n `<top_dirs>${dirs.join(', ')}</top_dirs>`,\n `<top_files>${files.join(', ')}</top_files>`,\n ];\n return parts.join('\\n');\n } catch {\n return `<repo_root>${repoRoot}</repo_root>`;\n }\n}\n\nfunction formatAssistantToolBlock(name: string, args: Record<string, unknown>, payload: string, isError = false): string {\n const argStr = Object.entries(args)\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(' ');\n const prefix = isError ? 'error' : 'result';\n return `<${prefix} name=\"${name}\" ${argStr}>\\n${payload}\\n</${prefix}>`;\n}\n\nasync function callModel(messages: ChatMessage[], model: string, apiKey?: string): Promise<string> {\n const api = 'https://api.morphllm.com/v1/chat/completions';\n const fetchPromise = fetchWithRetry(\n api,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey || process.env.MORPH_API_KEY || ''}`,\n },\n body: JSON.stringify({\n model,\n temperature: 0.0,\n max_tokens: 1024,\n messages,\n }),\n },\n {}\n );\n const resp = await withTimeout(fetchPromise, AGENT_CONFIG.TIMEOUT_MS, 'morph-warp-grep request timed out');\n if (!resp.ok) {\n // keeping these cases are real throws, if this happens retry will likely not help, so best we just throw here, notice the error and fix\n const t = await resp.text();\n throw new Error(`morph-warp-grep error ${resp.status}: ${t}`);\n }\n const data = await resp.json();\n const content = data?.choices?.[0]?.message?.content;\n if (!content || typeof content !== 'string') {\n throw new Error('Invalid response from model');\n }\n return content;\n}\n\nexport async function runWarpGrep(config: SessionConfig & { provider: WarpGrepProvider }): Promise<AgentRunResult> {\n const repoRoot = path.resolve(config.repoRoot || process.cwd());\n const messages: ChatMessage[] = [];\n\n // system\n const systemMessage = { role: 'system' as const, content: getSystemPrompt() };\n messages.push(systemMessage);\n // user query\n const queryContent = `<query>${config.query}</query>`;\n messages.push({ role: 'user', content: queryContent });\n // initial state\n const initialState = await buildInitialState(repoRoot, config.query, config.provider);\n messages.push({ role: 'user', content: initialState });\n\n const maxRounds = AGENT_CONFIG.MAX_ROUNDS;\n const model = config.model || DEFAULT_MODEL;\n const provider = config.provider;\n const errors: Array<{ message: string }> = [];\n\n let finishMeta: AgentFinish | undefined;\n let terminationReason: AgentRunResult['terminationReason'] = 'terminated';\n\n for (let round = 1; round <= maxRounds; round += 1) {\n // call model\n const assistantContent = await callModel(messages, model, config.apiKey).catch((e: unknown) => {\n errors.push({ message: e instanceof Error ? e.message : String(e) });\n return '';\n });\n if (!assistantContent) break;\n messages.push({ role: 'assistant', content: assistantContent });\n\n // parse tool calls (no longer throws - returns _skip calls for malformed commands)\n const toolCalls = parser.parse(assistantContent);\n if (toolCalls.length === 0) {\n errors.push({ message: 'No tool calls produced by the model.' });\n terminationReason = 'terminated';\n break;\n }\n\n const finishCalls = toolCalls.filter(c => c.name === 'finish');\n const grepCalls = toolCalls.filter(c => c.name === 'grep');\n const analyseCalls = toolCalls.filter(c => c.name === 'analyse');\n const readCalls = toolCalls.filter(c => c.name === 'read');\n const skipCalls = toolCalls.filter(c => c.name === '_skip');\n\n const formatted: string[] = [];\n\n // Surface any skipped commands as feedback to the LLM\n for (const c of skipCalls) {\n const msg = (c.arguments as { message?: string })?.message || 'Command skipped due to parsing error';\n formatted.push(msg);\n }\n\n // Execute ALL tools in parallel (grep, analyse, read)\n const allPromises: Array<Promise<string | { terminate: true; error: string }>> = [];\n \n // Grep calls\n for (const c of grepCalls) {\n const args = (c.arguments ?? {}) as { pattern: string; path: string };\n allPromises.push(\n provider.grep({ pattern: args.pattern, path: args.path }).then(\n grepRes => {\n // Check for ripgrep availability error\n if (grepRes.error) {\n return { terminate: true, error: grepRes.error };\n }\n const output = grepRes.lines.join('\\n') || 'no matches';\n return formatAgentToolOutput('grep', args, output, { isError: false });\n },\n err => formatAgentToolOutput('grep', args, String(err), { isError: true })\n )\n );\n }\n \n // Analyse calls\n for (const c of analyseCalls) {\n const args = (c.arguments ?? {}) as { path: string; pattern?: string | null };\n allPromises.push(\n toolAnalyse(provider, args).then(\n p => formatAgentToolOutput('analyse', args, p, { isError: false }),\n err => formatAgentToolOutput('analyse', args, String(err), { isError: true })\n )\n );\n }\n \n // Read calls\n for (const c of readCalls) {\n const args = (c.arguments ?? {}) as { path: string; start?: number; end?: number };\n allPromises.push(\n toolRead(provider, args).then(\n p => formatAgentToolOutput('read', args, p, { isError: false }),\n err => formatAgentToolOutput('read', args, String(err), { isError: true })\n )\n );\n }\n \n const allResults = await Promise.all(allPromises);\n \n // Check for termination signals (e.g., ripgrep not available)\n for (const result of allResults) {\n if (typeof result === 'object' && 'terminate' in result) {\n errors.push({ message: result.error });\n return {\n terminationReason: 'terminated',\n messages,\n errors,\n };\n }\n formatted.push(result as string);\n }\n\n if (formatted.length > 0) {\n // Add turn counter message\n const turnsUsed = round;\n const turnsRemaining = 4 - turnsUsed;\n let turnMessage: string;\n if (turnsRemaining === 0) {\n turnMessage = `\\n\\n[Turn ${turnsUsed}/4] This is your LAST turn. You MUST call the finish tool now.`;\n } else if (turnsRemaining === 1) {\n turnMessage = `\\n\\n[Turn ${turnsUsed}/4] You have 1 turn remaining. Next turn you MUST call the finish tool.`;\n } else {\n turnMessage = `\\n\\n[Turn ${turnsUsed}/4] You have ${turnsRemaining} turns remaining.`;\n }\n messages.push({ role: 'user', content: formatted.join('\\n') + turnMessage });\n }\n\n if (finishCalls.length) {\n const fc = finishCalls[0];\n const files = ((fc.arguments as any)?.files ?? []) as AgentFinish['files'];\n finishMeta = { files };\n terminationReason = 'completed';\n break;\n }\n }\n\n if (terminationReason !== 'completed' || !finishMeta) {\n return { terminationReason, messages, errors };\n }\n\n // Build finish payload\n const parts: string[] = ['Relevant context found:'];\n for (const f of finishMeta.files) {\n const ranges = f.lines.map(([s, e]) => `${s}-${e}`).join(', ');\n parts.push(`- ${f.path}: ${ranges}`);\n }\n const payload = parts.join('\\n');\n\n // Resolve file contents for returned ranges\n // Wrap reader in try-catch to handle non-existent or unreadable files gracefully\n // Track files that couldn't be read for error reporting\n const fileReadErrors: Array<{ path: string; error: string }> = [];\n const resolved = await readFinishFiles(\n repoRoot,\n finishMeta.files,\n async (p: string, s: number, e: number) => {\n try {\n const rr = await provider.read({ path: p, start: s, end: e });\n // rr.lines are \"line|content\" → strip the \"line|\" prefix\n return rr.lines.map(l => {\n const idx = l.indexOf('|');\n return idx >= 0 ? l.slice(idx + 1) : l;\n });\n } catch (err) {\n // File doesn't exist or can't be read - log error but don't throw\n // This handles cases where the agent hallucinated a path or the file was deleted\n const errorMsg = err instanceof Error ? err.message : String(err);\n fileReadErrors.push({ path: p, error: errorMsg });\n console.error(`[warp_grep] Failed to read file: ${p} - ${errorMsg}`);\n return [`[couldn't find: ${p}]`];\n }\n }\n );\n\n // Add file read errors to the result so MCP can report them\n if (fileReadErrors.length > 0) {\n errors.push(...fileReadErrors.map(e => ({ message: `File read error: ${e.path} - ${e.error}` })));\n }\n\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: finishMeta, resolved },\n };\n}\n\n\n","import fs from 'fs/promises';\nimport fssync from 'fs';\nimport path from 'path';\nimport { runRipgrep } from '../utils/ripgrep.js';\nimport { ensureWithinRepo, resolveUnderRepo, toRepoRelative, isSymlink, isTextualFile } from '../utils/paths.js';\nimport type { WarpGrepProvider, GrepResult, ReadResult, AnalyseEntry } from './types.js';\nimport { readAllLines } from '../utils/files.js';\nimport { DEFAULT_EXCLUDES } from '../agent/config.js';\n\nexport class LocalRipgrepProvider implements WarpGrepProvider {\n constructor(private readonly repoRoot: string, private readonly excludes: string[] = DEFAULT_EXCLUDES) {}\n\n async grep(params: { pattern: string; path: string }): Promise<GrepResult> {\n const abs = resolveUnderRepo(this.repoRoot, params.path);\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat) return { lines: [] };\n const targetArg = abs === path.resolve(this.repoRoot) ? '.' : toRepoRelative(this.repoRoot, abs);\n const args = [\n '--no-config',\n '--no-heading',\n '--with-filename',\n '--line-number',\n '--color=never',\n '--trim',\n '--max-columns=400',\n ...this.excludes.flatMap((e) => ['-g', `!${e}`]),\n params.pattern,\n targetArg || '.',\n ];\n const res = await runRipgrep(args, { cwd: this.repoRoot });\n \n // Gracefully handle ripgrep not being available\n if (res.exitCode === -1) {\n return {\n lines: [],\n error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required but failed to execute. Please install it:\\n` +\n ` • macOS: brew install ripgrep\\n` +\n ` • Ubuntu/Debian: apt install ripgrep\\n` +\n ` • Windows: choco install ripgrep\\n` +\n ` • Or visit: https://github.com/BurntSushi/ripgrep#installation\\n` +\n `Exit code: ${res.exitCode}${res.stderr ? `\\nDetails: ${res.stderr}` : ''}`,\n };\n }\n \n // Handle other ripgrep errors gracefully\n if (res.exitCode !== 0 && res.exitCode !== 1) {\n return {\n lines: [],\n error: `[RIPGREP ERROR] grep failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ''}`,\n };\n }\n \n const lines = (res.stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((l) => l.length > 0);\n return { lines };\n }\n\n async glob(params: { pattern: string; path: string }): Promise<{ files: string[] }> {\n const abs = resolveUnderRepo(this.repoRoot, params.path);\n const targetArg = abs === path.resolve(this.repoRoot) ? '.' : toRepoRelative(this.repoRoot, abs);\n const args = [\n '--no-config',\n '--files',\n '-g',\n params.pattern,\n ...this.excludes.flatMap((e) => ['-g', `!${e}`]),\n targetArg || '.',\n ];\n const res = await runRipgrep(args, { cwd: this.repoRoot });\n \n // Gracefully handle ripgrep not being available\n if (res.exitCode === -1) {\n // Return empty files with a console warning - glob is less critical than grep\n console.warn(`[warp_grep] ripgrep not available for glob: ${res.stderr || 'execution failed'}`);\n return { files: [] };\n }\n \n const files = (res.stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((l) => l.length > 0);\n return { files };\n }\n\n async read(params: { path: string; start?: number; end?: number }): Promise<ReadResult> {\n const abs = resolveUnderRepo(this.repoRoot, params.path);\n const stat = await fs.stat(abs).catch(() => null);\n \n // Gracefully handle file not found / not a file\n if (!stat || !stat.isFile()) {\n return {\n lines: [],\n error: `[FILE NOT FOUND] You tried to read \"${params.path}\" but there is no file at this path. ` +\n `Double-check the path exists and is spelled correctly.`,\n };\n }\n \n // Gracefully handle symlinks\n if (isSymlink(abs)) {\n return {\n lines: [],\n error: `[SYMLINK] You tried to read \"${params.path}\" but this is a symlink. ` +\n `Try reading the actual file it points to instead.`,\n };\n }\n \n // Gracefully handle non-text or too-large files\n if (!isTextualFile(abs)) {\n return {\n lines: [],\n error: `[UNREADABLE FILE] You tried to read \"${params.path}\" but this file is either too large ` +\n `or not a text file, so it cannot be read. Try a different file.`,\n };\n }\n \n const lines = await readAllLines(abs);\n const total = lines.length;\n let s = params.start ?? 1;\n let e = Math.min(params.end ?? total, total);\n if (s > total && total > 0) {\n // Model hallucinated range - fallback to full file\n s = 1;\n e = total;\n }\n const out: string[] = [];\n for (let i = s; i <= e; i += 1) {\n const content = lines[i - 1] ?? '';\n out.push(`${i}|${content}`);\n }\n return { lines: out };\n }\n\n async analyse(params: { path: string; pattern?: string | null; maxResults?: number; maxDepth?: number }): Promise<AnalyseEntry[]> {\n const abs = resolveUnderRepo(this.repoRoot, params.path);\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat || !stat.isDirectory()) {\n return [];\n }\n const maxResults = params.maxResults ?? 100;\n const maxDepth = params.maxDepth ?? 2;\n const regex = params.pattern ? new RegExp(params.pattern) : null;\n\n const results: AnalyseEntry[] = [];\n async function walk(dir: string, depth: number) {\n if (depth > maxDepth || results.length >= maxResults) return;\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n const rel = toRepoRelative(abs, full).replace(/^[.][/\\\\]?/, '');\n if (DEFAULT_EXCLUDES.some((ex) => rel.split(path.sep).includes(ex))) continue;\n if (regex && !regex.test(entry.name)) continue;\n if (results.length >= maxResults) break;\n results.push({\n name: entry.name,\n path: toRepoRelative(path.resolve(''), full), // relative display\n type: entry.isDirectory() ? 'dir' : 'file',\n depth,\n });\n if (entry.isDirectory()) {\n await walk(full, depth + 1);\n }\n }\n }\n await walk(abs, 0);\n return results;\n }\n}\n\n\n","import { spawn } from 'child_process';\nimport { rgPath } from '@vscode/ripgrep';\n\nexport type ExecResult = { stdout: string; stderr: string; exitCode: number };\n\n// Cache the working ripgrep path to avoid repeated fallback checks\nlet resolvedRgPath: string | null = null;\nlet rgPathChecked = false;\n\nfunction spawnRg(rgBinary: string, args: string[], opts?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult> {\n return new Promise((resolve) => {\n const child = spawn(rgBinary, args, {\n cwd: opts?.cwd,\n env: { ...process.env, ...(opts?.env || {}) },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (d) => (stdout += d.toString()));\n child.stderr.on('data', (d) => (stderr += d.toString()));\n child.on('close', (code) => {\n resolve({ stdout, stderr, exitCode: typeof code === 'number' ? code : -1 });\n });\n child.on('error', () => {\n resolve({ stdout: '', stderr: 'Failed to spawn ripgrep.', exitCode: -1 });\n });\n });\n}\n\n// Check if a result indicates a binary compatibility failure (not a normal rg error)\nfunction isBinaryFailure(result: ExecResult): boolean {\n // Spawn error\n if (result.exitCode === -1) return true;\n // jemalloc page size issue (common on ARM64 with non-standard page sizes)\n if (result.stderr.includes('jemalloc') || result.stderr.includes('Unsupported system page size')) return true;\n // SIGABRT (134 = 128 + 6)\n if (result.exitCode === 134) return true;\n return false;\n}\n\nexport async function runRipgrep(args: string[], opts?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult> {\n // If we've already determined the working path, use it\n if (rgPathChecked && resolvedRgPath) {\n return spawnRg(resolvedRgPath, args, opts);\n }\n\n // First attempt: bundled ripgrep\n if (!rgPathChecked) {\n const result = await spawnRg(rgPath, args, opts);\n \n if (!isBinaryFailure(result)) {\n // Bundled binary works, cache it\n resolvedRgPath = rgPath;\n rgPathChecked = true;\n return result;\n }\n\n // Bundled binary failed, try system rg\n const fallbackResult = await spawnRg('rg', args, opts);\n \n if (!isBinaryFailure(fallbackResult)) {\n // System rg works, cache it\n resolvedRgPath = 'rg';\n rgPathChecked = true;\n return fallbackResult;\n }\n\n // Neither works, mark as checked and return the original error\n rgPathChecked = true;\n return { \n stdout: '', \n stderr: 'Failed to spawn ripgrep. Neither bundled nor system rg is available.', \n exitCode: -1 \n };\n }\n\n // rgPathChecked is true but resolvedRgPath is null - no working rg found\n return { \n stdout: '', \n stderr: 'Failed to spawn ripgrep. Neither bundled nor system rg is available.', \n exitCode: -1 \n };\n}\n\n\n","import fs from 'fs';\nimport path from 'path';\n\nexport function resolveUnderRepo(repoRoot: string, targetPath: string): string {\n const absRoot = path.resolve(repoRoot);\n const resolved = path.resolve(absRoot, targetPath);\n ensureWithinRepo(absRoot, resolved);\n return resolved;\n}\n\nexport function ensureWithinRepo(repoRoot: string, absTarget: string): void {\n const rel = path.relative(path.resolve(repoRoot), path.resolve(absTarget));\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path outside repository root: ${absTarget}`);\n }\n}\n\nexport function toRepoRelative(repoRoot: string, absPath: string): string {\n return path.relative(path.resolve(repoRoot), path.resolve(absPath));\n}\n\nexport function isSymlink(p: string): boolean {\n try {\n const st = fs.lstatSync(p);\n return st.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport function isTextualFile(filePath: string, maxBytes = 2_000_000): boolean {\n try {\n const st = fs.statSync(filePath);\n if (!st.isFile()) return false;\n if (st.size > maxBytes) return false;\n const fd = fs.openSync(filePath, 'r');\n const buf = Buffer.alloc(512);\n const read = fs.readSync(fd, buf, 0, buf.length, 0);\n fs.closeSync(fd);\n for (let i = 0; i < read; i++) {\n const c = buf[i];\n if (c === 0) return false; // binary heuristic\n }\n return true;\n } catch {\n return false;\n }\n}\n\n\n","import fs from 'fs/promises';\n\nexport async function readAllLines(filePath: string): Promise<string[]> {\n const content = await fs.readFile(filePath, 'utf8');\n // Preserve newlines; split keeping consistency\n return content.split(/\\r?\\n/);\n}\n\n\n","/**\n * Core implementation for morph-warp-grep\n * Provides a client class for programmatic code search\n */\n\nimport { runWarpGrep } from './agent/runner.js';\nimport { LocalRipgrepProvider } from './providers/local.js';\nimport type { \n WarpGrepClientConfig, \n WarpGrepInput, \n WarpGrepResult,\n WarpGrepContext,\n} from './types.js';\n\n/**\n * WarpGrep client for programmatic code search\n * \n * @example\n * ```typescript\n * import { WarpGrepClient } from '@morphllm/morphsdk';\n * \n * const client = new WarpGrepClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * // Simple usage - defaults to LocalRipgrepProvider\n * const result = await client.execute({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * \n * // With custom excludes\n * const result = await client.execute({\n * query: 'Find database models',\n * repoRoot: '.',\n * excludes: ['node_modules', '.git', 'dist']\n * });\n * ```\n */\nexport class WarpGrepClient {\n private config: WarpGrepClientConfig;\n\n constructor(config: WarpGrepClientConfig = {}) {\n this.config = {\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Execute a code search query\n * \n * @param input - Search parameters including query, repoRoot, and optional provider\n * @returns Search results with relevant code contexts\n * \n * @example\n * ```typescript\n * const result = await client.execute({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * \n * if (result.success) {\n * for (const ctx of result.contexts) {\n * console.log(`File: ${ctx.file}`);\n * console.log(ctx.content);\n * }\n * }\n * ```\n */\n async execute(input: WarpGrepInput): Promise<WarpGrepResult> {\n // Default to LocalRipgrepProvider if no provider specified\n const provider = input.provider ?? new LocalRipgrepProvider(input.repoRoot, input.excludes);\n \n const result = await runWarpGrep({\n query: input.query,\n repoRoot: input.repoRoot,\n provider,\n excludes: input.excludes,\n includes: input.includes,\n debug: input.debug ?? this.config.debug ?? false,\n apiKey: this.config.apiKey,\n });\n\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n return { \n success: false, \n error: 'Search did not complete',\n };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n }));\n\n return { \n success: true, \n contexts, \n summary: finish.payload,\n };\n }\n}\n\n/**\n * Execute a warp grep search directly\n * \n * @param input - Search parameters\n * @param config - Optional client configuration\n * @returns Search results\n * \n * @example\n * ```typescript\n * import { executeWarpGrep } from '@morphllm/morphsdk/tools/warp-grep';\n * \n * const result = await executeWarpGrep({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * ```\n */\nexport async function executeWarpGrep(\n input: WarpGrepInput,\n config?: WarpGrepClientConfig\n): Promise<WarpGrepResult> {\n const client = new WarpGrepClient(config);\n return client.execute(input);\n}\n\n/**\n * Format warp grep results for display or tool responses\n * \n * @param result - The search result\n * @returns Formatted string representation\n */\nexport function formatResult(result: WarpGrepResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (!result.contexts || result.contexts.length === 0) {\n return 'No relevant code found. Try rephrasing your query.';\n }\n\n const lines: string[] = [];\n lines.push(`Found ${result.contexts.length} relevant code sections:\\n`);\n\n result.contexts.forEach((ctx, i) => {\n lines.push(`${i + 1}. ${ctx.file}`);\n lines.push('```');\n lines.push(ctx.content);\n lines.push('```');\n lines.push('');\n });\n\n if (result.summary) {\n lines.push(`Summary: ${result.summary}`);\n }\n\n return lines.join('\\n');\n}\n\n","/**\n * Morph Git Client - Simple, high-level Git operations\n * Built on isomorphic-git with explicit configuration\n */\n\nimport git from 'isomorphic-git';\nimport http from 'isomorphic-git/http/node';\nimport fs from 'fs';\nimport type {\n CloneOptions,\n PushOptions,\n PullOptions,\n AddOptions,\n CommitOptions,\n StatusOptions,\n LogOptions,\n CheckoutOptions,\n BranchOptions,\n DiffOptions,\n CommitObject,\n StatusResult,\n MorphGitConfig,\n MorphNotesSchema,\n WaitForEmbeddingsOptions,\n EmbeddingProgress,\n} from './types.js';\n\nconst DEFAULT_PROXY_URL = 'https://repos.morphllm.com';\n\n/**\n * MorphGit - Git operations for AI agents with Morph backend\n * \n * @example\n * ```typescript\n * import { MorphGit } from 'morphsdk/git';\n * \n * const morphGit = new MorphGit({\n * apiKey: process.env.MORPH_API_KEY!,\n * proxyUrl: 'https://repos.morphllm.com' // Optional\n * });\n * \n * await morphGit.init({ repoId: 'my-project', dir: './my-project' });\n * await morphGit.push({ dir: './my-project' });\n * ```\n */\nexport class MorphGit {\n private readonly apiKey: string;\n private readonly proxyUrl: string;\n\n constructor(config: MorphGitConfig) {\n // Validate API key\n if (!config.apiKey) {\n throw new Error('API key is required. Get one at https://morphllm.com/dashboard');\n }\n \n if (!config.apiKey.startsWith('sk-') && !config.apiKey.startsWith('morph-')) {\n throw new Error('Invalid API key format. Expected: sk-... or morph-...');\n }\n \n this.apiKey = config.apiKey;\n this.proxyUrl = config.proxyUrl || DEFAULT_PROXY_URL;\n }\n \n /**\n * Get auth callback for isomorphic-git operations\n * @private\n */\n private getAuthCallback() {\n return () => ({\n username: 'morph',\n password: this.apiKey,\n });\n }\n\n /**\n * Initialize a new repository\n * Creates the repo in the database and in the git provider\n * \n * @example\n * ```ts\n * await morphGit.init({\n * repoId: 'my-project',\n * dir: './my-project',\n * defaultBranch: 'main'\n * });\n * ```\n */\n async init(options: {\n repoId: string;\n dir: string;\n defaultBranch?: string;\n }): Promise<void> {\n const { repoId, dir, defaultBranch = 'main' } = options;\n\n // Call backend API to create repository\n const response = await fetch(`${this.proxyUrl}/v1/repos`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n repoId,\n name: repoId,\n defaultBranch,\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Failed to create repository: ${error}`);\n }\n\n // Initialize local git repository (industry standard: no clone needed)\n await git.init({\n fs,\n dir,\n defaultBranch,\n });\n\n // Add remote pointing to Morph git-proxy\n await git.addRemote({\n fs,\n dir,\n remote: 'origin',\n url: `${this.proxyUrl}/v1/repos/${repoId}`,\n });\n\n console.log(`✓ Repository '${repoId}' initialized`);\n }\n\n /**\n * Clone a repository from Morph repos\n * \n * @example\n * ```ts\n * await morphGit.clone({\n * repoId: 'my-project',\n * dir: './my-project'\n * });\n * ```\n */\n async clone(options: CloneOptions): Promise<void> {\n const { repoId, dir, branch = 'main', depth, singleBranch = true } = options;\n\n await git.clone({\n fs,\n http,\n dir,\n url: `${this.proxyUrl}/v1/repos/${repoId}`,\n ref: branch,\n singleBranch,\n depth,\n onAuth: this.getAuthCallback(),\n });\n }\n\n /**\n * Push changes to remote repository\n * \n * @example\n * ```ts\n * await morphGit.push({ \n * dir: './my-project',\n * branch: 'main', // Required: explicit branch name\n * index: true // Optional: generate embeddings (default: true)\n * });\n * ```\n */\n async push(options: PushOptions): Promise<void> {\n const { dir, remote = 'origin', branch, waitForEmbeddings, index = true } = options;\n\n if (!branch) {\n throw new Error(\n 'branch is required for push operations. ' +\n 'Specify the branch explicitly: { dir: \"./my-project\", branch: \"main\" }'\n );\n }\n\n // Get commit hash and repoId before pushing\n const commitHash = await git.resolveRef({ fs, dir, ref: 'HEAD' });\n \n // Get repoId from git remote URL\n let repoId: string | undefined;\n const remotes = await git.listRemotes({ fs, dir });\n const originRemote = remotes.find(r => r.remote === remote);\n if (originRemote) {\n // Extract repoId from URL: https://repos.morphllm.com/v1/repos/{repoId}\n const match = originRemote.url.match(/\\/repos\\/([^\\/]+)$/);\n if (match) {\n repoId = match[1];\n }\n }\n\n await git.push({\n fs,\n http,\n dir,\n remote,\n ref: branch,\n onAuth: this.getAuthCallback(),\n });\n \n // Configure commit after successful push (set index flag)\n if (repoId && commitHash) {\n await this.configureCommit({ repoId, commitHash, branch, index });\n }\n \n // Wait for embeddings if requested (and indexing is enabled)\n if (waitForEmbeddings && repoId && commitHash && index) {\n await this.waitForEmbeddings({ repoId, commitHash });\n }\n }\n\n /**\n * Configure commit settings on the backend after push.\n * Sets the index flag to control embedding generation.\n * @private\n */\n private async configureCommit(options: {\n repoId: string;\n commitHash: string;\n branch: string;\n index: boolean;\n }): Promise<void> {\n const { repoId, commitHash, branch, index } = options;\n \n const response = await fetch(\n `${this.proxyUrl}/v1/repos/${repoId}/commits/${commitHash}/config`,\n {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ index, branch }),\n }\n );\n\n if (!response.ok) {\n // Non-fatal: log warning but don't throw\n console.warn(`Failed to configure commit: ${response.status}`);\n }\n }\n\n /**\n * Pull changes from remote repository\n * \n * @example\n * ```ts\n * await morphGit.pull({ \n * dir: './my-project',\n * branch: 'main' // Required: explicit branch name\n * });\n * ```\n */\n async pull(options: PullOptions): Promise<void> {\n const { dir, remote = 'origin', branch } = options;\n\n if (!branch) {\n throw new Error(\n 'branch is required for pull operations. ' +\n 'Specify the branch explicitly: { dir: \"./my-project\", branch: \"main\" }'\n );\n }\n\n await git.pull({\n fs,\n http,\n dir,\n remote,\n ref: branch,\n onAuth: this.getAuthCallback(),\n author: {\n name: 'Morph Agent',\n email: 'agent@morph.com',\n },\n });\n }\n\n /**\n * Wait for embeddings to complete after push.\n * Polls status endpoint until embeddings are done.\n * \n * @example\n * ```ts\n * await morphGit.push({ dir: './my-project', branch: 'main' });\n * await morphGit.waitForEmbeddings({\n * repoId: 'my-project',\n * onProgress: (p) => console.log(`${p.filesProcessed}/${p.totalFiles}`)\n * });\n * ```\n */\n async waitForEmbeddings(options: WaitForEmbeddingsOptions): Promise<void> {\n const { repoId, commitHash, timeout = 120000, onProgress } = options;\n const startTime = Date.now();\n const pollInterval = 1000; // Poll every 1s\n \n while (Date.now() - startTime < timeout) {\n const statusUrl = `${this.proxyUrl}/v1/repos/${repoId}/embedding-status` +\n (commitHash ? `?commit_hash=${commitHash}` : '');\n \n const response = await fetch(statusUrl, {\n headers: { 'Authorization': `Bearer ${this.apiKey}` }\n });\n \n if (response.status === 404) {\n // No job found yet - might still be creating\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n continue;\n }\n \n if (!response.ok) {\n throw new Error(`Failed to get embedding status: ${response.status}`);\n }\n \n const status = await response.json();\n \n if (onProgress && status.progress) {\n onProgress(status.progress);\n }\n \n if (status.status === 'completed') {\n return; // Done!\n }\n \n if (status.status === 'failed') {\n throw new Error(`Embeddings failed: ${status.error || 'Unknown error'}`);\n }\n \n // Still processing (queued or processing), wait and poll again\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n \n throw new Error(`Embeddings timed out after ${timeout}ms`);\n }\n\n /**\n * Stage a file for commit\n * \n * @example\n * ```ts\n * await morphGit.add({\n * dir: './my-project',\n * filepath: 'src/app.ts'\n * });\n * ```\n */\n async add(options: AddOptions): Promise<void> {\n const { dir, filepath } = options;\n\n await git.add({\n fs,\n dir,\n filepath,\n });\n }\n\n /**\n * Remove a file from staging\n * \n * @example\n * ```ts\n * await morphGit.remove({\n * dir: './my-project',\n * filepath: 'src/old-file.ts'\n * });\n * ```\n */\n async remove(options: AddOptions): Promise<void> {\n const { dir, filepath } = options;\n\n await git.remove({\n fs,\n dir,\n filepath,\n });\n }\n\n /**\n * Commit staged changes\n * \n * @example\n * ```ts\n * await morphGit.commit({\n * dir: './my-project',\n * message: 'Add new feature',\n * author: {\n * name: 'AI Agent',\n * email: 'ai@example.com'\n * },\n * metadata: { issueId: 'PROJ-123', source: 'agent' },\n * chatHistory: [\n * { role: 'user', content: 'Please add a new feature' },\n * { role: 'assistant', content: 'I will add that feature' }\n * ],\n * recordingId: 'rec_123'\n * });\n * ```\n */\n async commit(options: CommitOptions): Promise<string> {\n const { dir, message, author, metadata, chatHistory, recordingId } = options;\n\n // Provide default author if not specified\n const commitAuthor = author || {\n name: 'Morph SDK',\n email: 'sdk@morphllm.com'\n };\n\n const sha = await git.commit({\n fs,\n dir,\n message,\n author: commitAuthor,\n });\n\n // Store notes if any note fields are provided\n if (metadata || chatHistory || recordingId) {\n const notes: MorphNotesSchema = {\n metadata,\n chatHistory,\n recordingId,\n _version: 1\n };\n \n await git.addNote({\n fs,\n dir,\n ref: 'refs/notes/morph-metadata',\n oid: sha,\n note: JSON.stringify(notes, null, 2),\n author: commitAuthor\n });\n }\n\n return sha;\n }\n\n /**\n * Get status of a file\n * \n * @example\n * ```ts\n * const status = await morphGit.status({\n * dir: './my-project',\n * filepath: 'src/app.ts'\n * });\n * console.log(status); // 'modified', '*added', etc.\n * ```\n */\n async status(options: StatusOptions): Promise<string> {\n const { dir, filepath } = options;\n\n if (!filepath) {\n throw new Error('filepath is required for status check');\n }\n\n const status = await git.status({\n fs,\n dir,\n filepath,\n });\n\n return status;\n }\n\n /**\n * Get commit history\n * \n * @example\n * ```ts\n * const commits = await morphGit.log({\n * dir: './my-project',\n * depth: 10\n * });\n * ```\n */\n async log(options: LogOptions): Promise<CommitObject[]> {\n const { dir, depth, ref } = options;\n\n const commits = await git.log({\n fs,\n dir,\n depth,\n ref,\n });\n\n return commits as CommitObject[];\n }\n\n /**\n * Checkout a branch or commit\n * \n * @example\n * ```ts\n * await morphGit.checkout({\n * dir: './my-project',\n * ref: 'feature-branch'\n * });\n * ```\n */\n async checkout(options: CheckoutOptions): Promise<void> {\n const { dir, ref } = options;\n\n await git.checkout({\n fs,\n dir,\n ref,\n });\n }\n\n /**\n * Create a new branch\n * \n * @example\n * ```ts\n * await morphGit.branch({\n * dir: './my-project',\n * name: 'feature-branch',\n * checkout: true\n * });\n * ```\n */\n async branch(options: BranchOptions): Promise<void> {\n const { dir, name, checkout = false } = options;\n\n await git.branch({\n fs,\n dir,\n ref: name,\n checkout,\n });\n }\n\n /**\n * List all branches\n * \n * @example\n * ```ts\n * const branches = await morphGit.listBranches({\n * dir: './my-project'\n * });\n * ```\n */\n async listBranches(options: { dir: string }): Promise<string[]> {\n const { dir } = options;\n\n const branches = await git.listBranches({\n fs,\n dir,\n });\n\n return branches;\n }\n\n /**\n * Get the current branch name\n * \n * @example\n * ```ts\n * const branch = await morphGit.currentBranch({\n * dir: './my-project'\n * });\n * ```\n */\n async currentBranch(options: { dir: string }): Promise<string | undefined> {\n const { dir } = options;\n\n const branch = await git.currentBranch({\n fs,\n dir,\n });\n\n return branch || undefined;\n }\n\n /**\n * Get list of changed files (similar to git diff --name-only)\n * \n * @example\n * ```ts\n * const changes = await morphGit.statusMatrix({\n * dir: './my-project'\n * });\n * ```\n */\n async statusMatrix(options: { dir: string }): Promise<StatusResult[]> {\n const { dir } = options;\n\n const matrix = await git.statusMatrix({\n fs,\n dir,\n });\n\n return matrix.map(([filepath, HEADStatus, workdirStatus, stageStatus]) => {\n let status: StatusResult['status'] = 'unmodified';\n\n // Determine status based on statusMatrix values\n if (HEADStatus === 1 && workdirStatus === 2 && stageStatus === 2) {\n status = 'modified';\n } else if (HEADStatus === 1 && workdirStatus === 2 && stageStatus === 1) {\n status = '*modified';\n } else if (HEADStatus === 0 && workdirStatus === 2 && stageStatus === 2) {\n status = 'added';\n } else if (HEADStatus === 0 && workdirStatus === 2 && stageStatus === 0) {\n status = '*added';\n } else if (HEADStatus === 1 && workdirStatus === 0 && stageStatus === 0) {\n status = 'deleted';\n } else if (HEADStatus === 1 && workdirStatus === 0 && stageStatus === 1) {\n status = '*deleted';\n } else if (HEADStatus === 1 && workdirStatus === 1 && stageStatus === 1) {\n status = 'unmodified';\n } else if (HEADStatus === 0 && workdirStatus === 0 && stageStatus === 0) {\n status = 'absent';\n }\n\n return {\n filepath,\n status,\n };\n });\n }\n\n /**\n * Get the current commit hash\n * \n * @example\n * ```ts\n * const hash = await morphGit.resolveRef({\n * dir: './my-project',\n * ref: 'HEAD'\n * });\n * ```\n */\n async resolveRef(options: { dir: string; ref: string }): Promise<string> {\n const { dir, ref } = options;\n\n const oid = await git.resolveRef({\n fs,\n dir,\n ref,\n });\n\n return oid;\n }\n\n /**\n * Get notes (metadata, chat history, recording ID) attached to a commit\n * \n * @example\n * ```ts\n * const notes = await morphGit.getCommitMetadata({\n * dir: './my-project',\n * commitSha: 'abc123...'\n * });\n * \n * if (notes) {\n * console.log('Metadata:', notes.metadata);\n * console.log('Chat history:', notes.chatHistory);\n * console.log('Recording ID:', notes.recordingId);\n * }\n * ```\n */\n async getCommitMetadata(options: {\n dir: string;\n commitSha: string;\n }): Promise<MorphNotesSchema | null> {\n try {\n const note = await git.readNote({\n fs,\n dir: options.dir,\n ref: 'refs/notes/morph-metadata',\n oid: options.commitSha\n });\n \n const notes: MorphNotesSchema = JSON.parse(new TextDecoder().decode(note));\n return notes;\n } catch (err) {\n // No notes found for this commit\n return null;\n }\n }\n}\n\n","/**\n * Morph Git SDK\n * \n * Git operations for AI agents using Morph's backend infrastructure.\n * \n * @example\n * ```typescript\n * import { MorphGit } from 'morphsdk/git';\n * \n * const morphGit = new MorphGit({\n * apiKey: process.env.MORPH_API_KEY!\n * });\n * \n * // Initialize and push\n * await morphGit.init({ repoId: 'my-project', dir: './my-project' });\n * await morphGit.add({ dir: './my-project', filepath: 'src/app.ts' });\n * await morphGit.commit({ dir: './my-project', message: 'Update' });\n * await morphGit.push({ dir: './my-project', branch: 'main' });\n * ```\n */\n\nexport { MorphGit } from './client.js';\nexport type {\n MorphGitConfig,\n CloneOptions,\n PushOptions,\n PullOptions,\n AddOptions,\n CommitOptions,\n StatusOptions,\n LogOptions,\n CheckoutOptions,\n BranchOptions,\n DiffOptions,\n CommitObject,\n StatusResult,\n ChatMessage,\n CommitMetadata,\n MorphNotesSchema,\n} from './types.js';\n\n// Re-export isomorphic-git for advanced use cases\nexport { default as git } from 'isomorphic-git';\nexport { default as http } from 'isomorphic-git/http/node';\n\n","/**\n * Core implementation for intelligent model routing\n */\n\nimport { fetchWithRetry, withTimeout } from '../tools/utils/resilience.js';\nimport type {\n RouterConfig,\n RouterInput,\n RouterResult,\n RawRouterResult,\n ComplexityLevel,\n RouterMode,\n Provider,\n} from './types.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: 'https://api.morphllm.com',\n timeout: 5000, // 5 seconds (responses typically <500ms)\n debug: false,\n};\n\nabstract class BaseRouter {\n protected config: Required<Omit<RouterConfig, 'apiKey' | 'retryConfig'>> & Pick<RouterConfig, 'apiKey' | 'retryConfig'>;\n protected provider: Provider;\n\n constructor(provider: Provider, config: RouterConfig = {}) {\n this.provider = provider;\n this.config = {\n apiKey: config.apiKey,\n apiUrl: config.apiUrl || DEFAULT_CONFIG.apiUrl,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n debug: config.debug || DEFAULT_CONFIG.debug,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Select the optimal model for a given input and mode\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || process.env.MORPH_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/${this.provider}`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Requesting ${this.provider} model selection:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model: string; confidence?: number } = await response.json();\n\n const result: RouterResult = {\n model: apiResult.model,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Selected model: ${apiResult.model}, Confidence: ${apiResult.confidence?.toFixed(3)}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[ModelRouter] Error selecting model:`, error);\n }\n throw error;\n }\n }\n}\n\n/**\n * OpenAI model router for GPT-5 series\n */\nexport class OpenAIRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('openai', config);\n }\n\n /**\n * Select optimal GPT-5 model\n * \n * @param input - User input and mode\n * @returns Selected model name (gpt-5-mini | gpt-5-low | gpt-5-medium | gpt-5-high)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Anthropic model router for Claude 4.5 series\n */\nexport class AnthropicRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('anthropic', config);\n }\n\n /**\n * Select optimal Claude model\n * \n * @param input - User input and mode\n * @returns Selected model name (claude-4.5-haiku | claude-4.5-sonnet)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Google Gemini model router\n */\nexport class GeminiRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('gemini', config);\n }\n\n /**\n * Select optimal Gemini model\n * \n * @param input - User input and mode\n * @returns Selected model name (gemini-2.5-flash | gemini-2.5-pro)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Raw difficulty classification router (no provider-specific mapping)\n */\nexport class RawRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('raw' as Provider, config);\n }\n\n /**\n * Get raw difficulty classification\n * \n * @param input - User input and mode\n * @returns Raw difficulty (easy | medium | hard | needs_info)\n */\n async classify(input: RouterInput): Promise<RawRouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || process.env.MORPH_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/raw`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Requesting raw difficulty classification:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model?: string; difficulty?: string; confidence?: number } = await response.json();\n\n // Support both 'model' and 'difficulty' fields for compatibility\n // Empty string from API means \"medium\" difficulty (API bug workaround)\n let difficulty: ComplexityLevel;\n if (apiResult.difficulty === '') {\n difficulty = 'medium';\n } else {\n difficulty = (apiResult.difficulty || apiResult.model) as ComplexityLevel;\n }\n\n const result: RawRouterResult = {\n difficulty,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Classified as: ${difficulty}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[RawRouter] Error classifying:`, error);\n }\n throw error;\n }\n }\n}\n","/**\n * Prompts and descriptions for warpgrep_codebase_search\n */\n\n/**\n * Default tool name for the warp grep tool\n */\nexport const WARP_GREP_TOOL_NAME = 'warpgrep_codebase_search';\n\n/**\n * Default tool description for the warp grep tool\n */\nexport const WARP_GREP_DESCRIPTION = \n 'IMPORTANT: If you need to explore the codebase to gather context, and the task does not involve a single file or function which is provided by name, you should ALWAYS use the warpgrep codebase search tool first instead of running search commands. ' +\n 'When the task requires exploration beyond a single known file, invoke warpgrep first with a natural-language query describing the target functionality, bug, or architectural concern. ' +\n 'Warp Grep is a fast and accurate tool that can search for all relevant context in a codebase. ' +\n 'Keep queries action-oriented (e.g., \"Find where billing invoices are generated and emailed\"), and after reviewing the summarized results, you may verify important findings with other search tools or direct file reads to ensure completeness. ' +\n 'Warp Grep can be used for query types like: find function responsible for <small feature>; find code that does <description>; find code path for <big feature>; Where does <minimal error message> come from?; or any query of that type. ' +\n 'When a task requires exploration beyond a single known file, ALWAYS default to warpgrep codebase search before other search mechanisms.'\n\n/**\n * System prompt for the warp grep agent\n * Re-exported from agent/prompt.ts for convenience\n */\nexport { SYSTEM_PROMPT as WARP_GREP_SYSTEM_PROMPT, getSystemPrompt } from './agent/prompt.js';\n","/**\n * OpenAI SDK adapter for morph-warp-grep tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { runWarpGrep } from './agent/runner.js';\nimport { LocalRipgrepProvider } from './providers/local.js';\nimport { WARP_GREP_DESCRIPTION, WARP_GREP_TOOL_NAME, getSystemPrompt } from './prompts.js';\nimport { formatResult } from './core.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, WarpGrepContext } from './types.js';\n\n/**\n * Input schema for the warp grep tool\n */\nconst TOOL_PARAMETERS = {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Free-form repository question' },\n },\n required: ['query'],\n} as const;\n\n/**\n * OpenAI-native warp grep tool definition\n * \n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { warpGrepTool, execute } from '@morphllm/morphsdk/tools/warp-grep/openai';\n * \n * const client = new OpenAI();\n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [warpGrepTool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute the tool call\n * const result = await execute({ query: '...' }, { repoRoot: '.' });\n * ```\n */\nexport const warpGrepTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: WARP_GREP_TOOL_NAME,\n description: WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n },\n};\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with query\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { query: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n const parsed = typeof input === 'string' ? JSON.parse(input) : input;\n const provider = config.provider ?? new LocalRipgrepProvider(config.repoRoot, config.excludes);\n \n const result = await runWarpGrep({\n query: parsed.query,\n repoRoot: config.repoRoot,\n provider,\n excludes: config.excludes,\n includes: config.includes,\n debug: config.debug ?? false,\n apiKey: config.apiKey,\n });\n\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n return { success: false, error: 'Search did not complete' };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n }));\n\n return { success: true, contexts, summary: finish.payload };\n}\n\n// Re-export formatResult and getSystemPrompt for convenience\nexport { formatResult, getSystemPrompt };\n\n/**\n * Create a custom warp grep tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { createMorphWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/openai';\n * \n * const tool = createMorphWarpGrepTool({\n * repoRoot: '.',\n * description: 'Custom tool description'\n * });\n * \n * const client = new OpenAI();\n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createMorphWarpGrepTool(config: WarpGrepToolConfig) {\n const tool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: config.name ?? WARP_GREP_TOOL_NAME,\n description: config.description ?? WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n },\n };\n\n return Object.assign(tool, {\n execute: async (input: unknown): Promise<WarpGrepResult> => {\n return execute(input as { query: string } | string, config);\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return getSystemPrompt();\n },\n });\n}\n\nexport default warpGrepTool;\n","/**\n * Tool descriptions and system prompts for codebase search\n */\n\nexport 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.`;\n\nexport 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.`;\n\n","/**\n * OpenAI SDK adapter for codebase_search tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION, CODEBASE_SEARCH_SYSTEM_PROMPT } from './prompts.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n/**\n * Direct codebase_search tool definition\n * Use this when you want to pass config at execute time\n */\nexport const codebaseSearchTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n },\n};\n\n/**\n * Create OpenAI-native codebase_search tool with execute and formatResult methods\n * \n * @param config - Configuration with repoId\n * @returns OpenAI ChatCompletionTool definition with methods\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/openai';\n * \n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\n * \n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * tools: [tool], // tool itself is the ChatCompletionTool\n * messages: [{ role: \"user\", content: \"Find authentication code\" }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const toolDefinition: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n },\n };\n\n return Object.assign(toolDefinition, {\n execute: async (input: CodebaseSearchInput | string): Promise<CodebaseSearchResult> => {\n const parsedInput = typeof input === 'string' ? JSON.parse(input) : input;\n return executeCodebaseSearch(parsedInput, config);\n },\n formatResult: (result: CodebaseSearchResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Execute codebase_search tool call\n * \n * @param input - Tool input from GPT (parsed from tool_calls)\n * @param config - Configuration with repoId (REQUIRED)\n * @returns Search results\n * \n * @example\n * ```ts\n * // Handle tool calls from GPT:\n * if (response.choices[0].message.tool_calls) {\n * for (const toolCall of response.choices[0].message.tool_calls) {\n * const args = JSON.parse(toolCall.function.arguments);\n * const result = await execute(args, { repoId: 'my-project' });\n * console.log(`Found ${result.results.length} matches`);\n * }\n * }\n * ```\n */\nexport async function execute(\n input: CodebaseSearchInput,\n config: CodebaseSearchConfig\n): Promise<CodebaseSearchResult> {\n return executeCodebaseSearch(input, config);\n}\n\n/**\n * Format search results for GPT\n * \n * @param result - Search result from endpoint\n * @returns Formatted string for tool message\n */\nexport function formatResult(result: CodebaseSearchResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (result.results.length === 0) {\n return 'No matching code found. Try rephrasing your query or removing directory filters.';\n }\n\n const lines: string[] = [];\n \n lines.push(`Found ${result.results.length} relevant code sections (${result.stats.searchTimeMs}ms):\\n`);\n\n result.results.forEach((r, i) => {\n const relevance = (r.rerankScore * 100).toFixed(1);\n lines.push(`${i + 1}. ${r.filepath} (${relevance}% relevant)`);\n lines.push(` Symbol: ${r.symbolPath}`);\n lines.push(` Language: ${r.language}`);\n lines.push(` Lines: ${r.startLine}-${r.endLine}`);\n lines.push(` Code:`);\n \n // Show code content\n const codeLines = r.content.split('\\n');\n codeLines.slice(0, Math.min(codeLines.length, 20)).forEach(line => {\n lines.push(` ${line}`);\n });\n \n if (codeLines.length > 20) {\n lines.push(` ... (${codeLines.length - 20} more lines)`);\n }\n \n lines.push('');\n });\n\n return lines.join('\\n');\n}\n\n/**\n * Get the system prompt for codebase_search usage\n * \n * @returns System prompt to guide GPT\n */\nexport function getSystemPrompt(): string {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n}\n\n/**\n * Default export for convenience\n */\nexport default { createCodebaseSearchTool, execute, formatResult, getSystemPrompt };\n\n","/**\n * System prompts for edit_file tool\n */\n\nexport const EDIT_FILE_TOOL_DESCRIPTION = `Use this tool to make an edit to an existing file.\n\nThis will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.\n\nWhen writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.\n\nFor example:\n\n// ... existing code ...\nFIRST_EDIT\n// ... existing code ...\nSECOND_EDIT\n// ... existing code ...\nTHIRD_EDIT\n// ... existing code ...\n\nYou should still bias towards repeating as few lines of the original file as possible to convey the change.\nBut, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.\n\nDO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.\n\nIf you plan on deleting a section, you must provide context before and after to delete it.\n\nMake sure it is clear what the edit should be, and where it should be applied.\nMake edits to a file in a single edit_file call instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.`;\n\nexport const EDIT_FILE_SYSTEM_PROMPT = `When the user is asking for edits to their code, use the edit_file tool to highlight the changes necessary and add comments to indicate where unchanged code has been skipped. For example:\n\n// ... existing code ...\n{{ edit_1 }}\n// ... existing code ...\n{{ edit_2 }}\n// ... existing code ...\n\nOften this will mean that the start/end of the file will be skipped, but that's okay! Rewrite the entire file ONLY if specifically requested. Always provide a brief explanation of the updates, unless the user specifically requests only the code.\n\nThese edit codeblocks are also read by a less intelligent language model, colloquially called the apply model, to update the file. To help specify the edit to the apply model, you will be very careful when generating the codeblock to not introduce ambiguity. You will specify all unchanged regions (code and comments) of the file with \"// ... existing code ...\" comment markers. This will ensure the apply model will not delete existing unchanged code or comments when editing the file.`;\n\n","/**\n * OpenAI SDK adapter for edit_file tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * OpenAI-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { editFileTool } from 'morphsdk/tools/openai';\n * \n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * \n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instructions: {\n type: 'string',\n description: 'A single sentence describing what you are changing (first person)',\n },\n code_edit: {\n type: 'string',\n description: 'The lazy edit with // ... existing code ... markers',\n },\n },\n required: ['target_filepath', 'instructions', 'code_edit'],\n },\n },\n};\n\n/**\n * Execute an edit_file tool call\n * \n * @param input - The tool input from GPT (parsed from tool_calls)\n * @param config - Optional configuration\n * @returns The result of the edit operation\n * \n * @example\n * ```ts\n * const args = JSON.parse(toolCall.function.arguments);\n * const result = await execute(args);\n * console.log('Changes applied:', result.udiff);\n * ```\n */\nexport async function execute(\n input: EditFileInput,\n config?: EditFileConfig\n): Promise<EditFileResult> {\n return executeEditFile(input, config);\n}\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide GPT on using edit_file properly.\n * \n * @example\n * ```ts\n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * messages: [\n * { role: \"system\", content: getSystemPrompt() },\n * { role: \"user\", content: \"Fix bugs\" }\n * ],\n * tools: [editFileTool]\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Format the result for passing back to GPT\n * \n * @param result - The edit result\n * @returns Formatted string for tool message\n */\nexport function formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n const summary = [\n changes.linesAdded && `+${changes.linesAdded} lines`,\n changes.linesRemoved && `-${changes.linesRemoved} lines`,\n changes.linesModified && `~${changes.linesModified} lines modified`,\n ]\n .filter(Boolean)\n .join(', ');\n \n if (result.udiff) {\n return `Successfully applied changes to ${result.filepath}:\\n\\n${result.udiff}\\n\\nSummary: ${summary}`;\n }\n \n return `Successfully applied changes to ${result.filepath}. ${summary}`;\n}\n\n/**\n * Create a custom edit_file tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { createEditFileTool } from 'morphsdk/tools/fastapply/openai';\n * \n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const client = new OpenAI();\n * \n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool], // tool itself is the ChatCompletionTool\n * messages: [{ role: 'user', content: 'Fix bug in app.ts' }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: ChatCompletionTool = {\n ...editFileTool,\n ...(config.description && {\n function: {\n ...editFileTool.function,\n description: config.description,\n },\n }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput | string): Promise<EditFileResult> => {\n const parsedInput = typeof input === 'string' ? JSON.parse(input) : input;\n return execute(parsedInput, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return getSystemPrompt();\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n","/**\n * OpenAI Tool Factory for MorphClient\n * \n * Creates OpenAI-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createMorphWarpGrepTool } from '../tools/warp_grep/openai.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/openai.js';\nimport { createEditFileTool } from '../tools/fastapply/openai.js';\nimport type { WarpGrepToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\n\n/**\n * Factory for creating OpenAI-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.openai.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.openai.createEditFileTool({ baseDir: './src' });\n * \n * // Use with OpenAI client\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [grepTool, searchTool, editTool],\n * messages: [{ role: 'user', content: 'Find and fix the bug' }]\n * });\n * ```\n */\nexport class OpenAIToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create an OpenAI-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (apiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'apiKey'>) {\n return createMorphWarpGrepTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Anthropic SDK adapter for morph-warp-grep tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { runWarpGrep } from './agent/runner.js';\nimport { LocalRipgrepProvider } from './providers/local.js';\nimport { WARP_GREP_DESCRIPTION, WARP_GREP_TOOL_NAME, getSystemPrompt } from './prompts.js';\nimport { formatResult } from './core.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, WarpGrepContext } from './types.js';\n\n/**\n * Input schema for the warp grep tool\n */\nconst INPUT_SCHEMA = {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Free-form repository question' },\n },\n required: ['query'],\n} as const;\n\n/**\n * Anthropic-native warp grep tool definition\n * \n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { warpGrepTool, execute } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const client = new Anthropic();\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [warpGrepTool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute the tool call\n * const result = await execute({ query: '...' }, { repoRoot: '.' });\n * ```\n */\nexport const warpGrepTool: Tool = {\n name: WARP_GREP_TOOL_NAME,\n description: WARP_GREP_DESCRIPTION,\n input_schema: INPUT_SCHEMA,\n};\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with query\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { query: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n const parsed = typeof input === 'string' ? JSON.parse(input) : input;\n const provider = config.provider ?? new LocalRipgrepProvider(config.repoRoot, config.excludes);\n \n const result = await runWarpGrep({\n query: parsed.query,\n repoRoot: config.repoRoot,\n provider,\n excludes: config.excludes,\n includes: config.includes,\n debug: config.debug ?? false,\n apiKey: config.apiKey,\n });\n\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n return { success: false, error: 'Search did not complete' };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n }));\n\n return { success: true, contexts, summary: finish.payload };\n}\n\n// Re-export formatResult and getSystemPrompt for convenience\nexport { formatResult, getSystemPrompt };\n\n/**\n * Create a custom warp grep tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createMorphWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const tool = createMorphWarpGrepTool({\n * repoRoot: '.',\n * description: 'Custom tool description'\n * });\n * \n * const client = new Anthropic();\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createMorphWarpGrepTool(config: WarpGrepToolConfig) {\n const tool: Tool = {\n name: config.name ?? WARP_GREP_TOOL_NAME,\n description: config.description ?? WARP_GREP_DESCRIPTION,\n input_schema: INPUT_SCHEMA,\n };\n\n return Object.assign(tool, {\n execute: async (input: unknown): Promise<WarpGrepResult> => {\n return execute(input as { query: string } | string, config);\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return getSystemPrompt();\n },\n });\n}\n\nexport default warpGrepTool;\n","/**\n * Anthropic SDK adapter for codebase_search tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION, CODEBASE_SEARCH_SYSTEM_PROMPT } from './prompts.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n\n/**\n * Create Anthropic-native codebase_search tool with execute and formatResult methods\n * \n * @param config - Configuration with repoId\n * @returns Anthropic Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [tool], // tool itself is the Tool definition\n * messages: [{ role: \"user\", content: \"Find authentication code\" }]\n * });\n * \n * // Execute tool and format result\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const toolDefinition: Tool = {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n input_schema: {\n type: 'object',\n properties: {\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n query: {\n type: 'string',\n description: 'A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n cache_control: { type: 'ephemeral' } as any,\n } as any;\n\n return Object.assign(toolDefinition, {\n execute: async (input: CodebaseSearchInput): Promise<CodebaseSearchResult> => {\n return executeCodebaseSearch(input, config);\n },\n formatResult: (result: CodebaseSearchResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Format search results for Claude\n * \n * @param result - Search result from endpoint\n * @returns Formatted string for tool_result\n */\nfunction formatResult(result: CodebaseSearchResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (result.results.length === 0) {\n return 'No matching code found. Try rephrasing your query or broadening the search scope.';\n }\n\n const lines: string[] = [];\n \n lines.push(`Found ${result.results.length} relevant code sections (searched ${result.stats.candidatesRetrieved} candidates in ${result.stats.searchTimeMs}ms):\\n`);\n\n result.results.forEach((r, i) => {\n const relevance = (r.rerankScore * 100).toFixed(1);\n lines.push(`${i + 1}. ${r.filepath} (${relevance}% relevant)`);\n lines.push(` Symbol: ${r.symbolPath}`);\n lines.push(` Language: ${r.language}`);\n lines.push(` Lines: ${r.startLine}-${r.endLine}`);\n lines.push(` Code:`);\n \n // Show code content with indentation\n const codeLines = r.content.split('\\n');\n codeLines.slice(0, Math.min(codeLines.length, 20)).forEach(line => {\n lines.push(` ${line}`);\n });\n \n if (codeLines.length > 20) {\n lines.push(` ... (${codeLines.length - 20} more lines)`);\n }\n \n lines.push('');\n });\n\n return lines.join('\\n');\n}\n\n","/**\n * Anthropic SDK adapter for edit_file tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * Anthropic-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { editFileTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: Tool = {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n input_schema: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instructions: {\n type: 'string',\n description: 'A single sentence describing what you are changing (first person)',\n },\n code_edit: {\n type: 'string',\n description: 'The lazy edit with // ... existing code ... markers',\n },\n },\n required: ['target_filepath', 'instructions', 'code_edit'],\n },\n};\n\n/**\n * Format the result for passing back to Claude\n * \n * @param result - The edit result\n * @returns Formatted string for tool_result\n */\nexport function formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n const summary = [\n changes.linesAdded && `+${changes.linesAdded} lines`,\n changes.linesRemoved && `-${changes.linesRemoved} lines`,\n changes.linesModified && `~${changes.linesModified} lines modified`,\n ]\n .filter(Boolean)\n .join(', ');\n \n if (result.udiff) {\n return `Successfully applied changes to ${result.filepath}:\\n\\n${result.udiff}\\n\\nSummary: ${summary}`;\n }\n \n return `Successfully applied changes to ${result.filepath}. ${summary}`;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * morphApiKey: 'sk-...',\n * description: 'Custom tool description for your use case'\n * });\n * \n * // Use as Anthropic tool\n * const response = await client.messages.create({\n * tools: [tool], // tool itself is the Tool definition\n * ...\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: Tool = {\n ...editFileTool,\n ...(config.description && { description: config.description }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput): Promise<EditFileResult> => {\n return executeEditFile(input, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return EDIT_FILE_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Execute the edit_file tool with raw input\n * \n * @param input - Tool input from Claude's tool_use\n * @param config - Configuration for Fast Apply\n * @returns Tool result to send back to Claude\n */\nexport async function execute(\n input: EditFileInput,\n config?: EditFileConfig\n): Promise<EditFileResult> {\n return executeEditFile(input, config);\n}\n\n/**\n * Get the system prompt for the edit_file tool\n * \n * @returns System prompt string\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n","/**\n * Anthropic Tool Factory for MorphClient\n * \n * Creates Anthropic-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createMorphWarpGrepTool } from '../tools/warp_grep/anthropic.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/anthropic.js';\nimport { createEditFileTool } from '../tools/fastapply/anthropic.js';\nimport type { WarpGrepToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\n\n/**\n * Factory for creating Anthropic-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.anthropic.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.anthropic.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.anthropic.createEditFileTool({ baseDir: './src' });\n * \n * // Use with Anthropic client\n * const response = await anthropic.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [grepTool, searchTool, editTool],\n * messages: [{ role: 'user', content: 'Find and fix the bug' }]\n * });\n * ```\n */\nexport class AnthropicToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create an Anthropic-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (apiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'apiKey'>) {\n return createMorphWarpGrepTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Anthropic-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Anthropic-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Vercel AI SDK adapter for morph-warp-grep tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { runWarpGrep } from './agent/runner.js';\nimport { LocalRipgrepProvider } from './providers/local.js';\nimport { WARP_GREP_DESCRIPTION, getSystemPrompt } from './prompts.js';\nimport { formatResult } from './core.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, WarpGrepContext } from './types.js';\n\n/**\n * Zod schema for warp grep input\n */\nconst warpGrepSchema = z.object({\n query: z.string().describe('Free-form repository question'),\n});\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with query\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { query: string },\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n const provider = config.provider ?? new LocalRipgrepProvider(config.repoRoot, config.excludes);\n \n const result = await runWarpGrep({\n query: input.query,\n repoRoot: config.repoRoot,\n provider,\n excludes: config.excludes,\n includes: config.includes,\n debug: config.debug ?? false,\n apiKey: config.apiKey,\n });\n\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n return { success: false, error: 'Search did not complete' };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n }));\n\n return { success: true, contexts, summary: finish.payload };\n}\n\n// Re-export formatResult and getSystemPrompt for convenience\nexport { formatResult, getSystemPrompt };\n\n/**\n * Create Vercel AI SDK warp grep tool\n * \n * @param config - Configuration options\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 { createMorphWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n * \n * const grepTool = createMorphWarpGrepTool({ repoRoot: '.' });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { grep: grepTool },\n * prompt: 'Find authentication middleware'\n * });\n * ```\n */\nexport function createMorphWarpGrepTool(config: WarpGrepToolConfig) {\n return tool({\n description: config.description ?? WARP_GREP_DESCRIPTION,\n inputSchema: warpGrepSchema,\n execute: async (params) => {\n const provider = config.provider ?? new LocalRipgrepProvider(config.repoRoot, config.excludes);\n const result = await runWarpGrep({\n query: params.query,\n repoRoot: config.repoRoot,\n provider,\n excludes: config.excludes,\n includes: config.includes,\n debug: config.debug ?? false,\n apiKey: config.apiKey,\n });\n\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n return { success: false, error: 'Search did not complete' };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n }));\n\n return { success: true, contexts, summary: finish.payload };\n },\n });\n}\n","/**\n * Vercel AI SDK adapter for codebase_search tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION } from './prompts.js';\nimport type { CodebaseSearchConfig } from './types.js';\n\n/**\n * Create Vercel AI SDK codebase_search tool\n * \n * @param config - Configuration with repoId\n * @returns Vercel AI SDK tool definition (execution built-in)\n * \n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/codebase-search/vercel';\n * \n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\n * \n * const result = await generateText({\n * model: anthropic('claude-3-5-sonnet-20241022'),\n * tools: { codebaseSearch: tool },\n * prompt: \"Find authentication code\",\n * maxSteps: 5\n * });\n * \n * // Vercel AI SDK automatically executes and handles results\n * console.log(result.text);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const schema = z.object({\n query: z.string().describe('A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"'),\n target_directories: z.array(z.string()).describe('Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.'),\n explanation: z.string().describe('One sentence explanation as to why this tool is being used, and how it contributes to the goal.'),\n limit: z.number().optional().describe('Max results to return (default: 10)'),\n });\n\n return tool({\n description: CODEBASE_SEARCH_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const { query, target_directories, explanation, limit } = params;\n const result = await executeCodebaseSearch(\n { query, target_directories, explanation, limit },\n config\n );\n\n if (!result.success) {\n return {\n error: result.error,\n results: [],\n };\n }\n\n // Format results for Vercel AI SDK\n return {\n found: result.results.length,\n searchTime: `${result.stats.searchTimeMs}ms`,\n results: result.results.map(r => ({\n file: r.filepath,\n symbol: r.symbolPath,\n lines: `${r.startLine}-${r.endLine}`,\n language: r.language,\n relevance: `${(r.rerankScore * 100).toFixed(1)}%`,\n code: r.content,\n })),\n };\n },\n });\n}\n\n/**\n * Get system prompt for Vercel AI SDK\n */\nexport function getSystemPrompt(): string {\n return CODEBASE_SEARCH_DESCRIPTION;\n}\n\n/**\n * Default export\n */\nexport default { createCodebaseSearchTool, getSystemPrompt };\n\n","/**\n * Vercel AI SDK adapter for edit_file tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileConfig } from './types.js';\n\n/**\n * Vercel AI SDK tool for edit_file\n * \n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { editFileTool } from 'morphsdk/tools/vercel';\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix the bug in app.ts\"\n * });\n * ```\n */\nconst editFileSchema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n});\n\nexport const editFileTool = tool({\n description: EDIT_FILE_TOOL_DESCRIPTION,\n inputSchema: editFileSchema,\n execute: async (params) => {\n const result = await executeEditFile({\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n });\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n});\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide the model on using edit_file properly.\n * \n * @example\n * ```ts\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * system: getSystemPrompt(),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Vercel AI SDK tool with custom config\n * \n * @example\n * ```ts\n * const customEditTool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: customEditTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const schema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n });\n\n return tool({\n description: config.description || EDIT_FILE_TOOL_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const result = await executeEditFile(\n {\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n },\n config\n );\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n","/**\n * Vercel AI SDK Tool Factory for MorphClient\n * \n * Creates Vercel AI SDK-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createMorphWarpGrepTool } from '../tools/warp_grep/vercel.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/vercel.js';\nimport { createEditFileTool } from '../tools/fastapply/vercel.js';\nimport type { WarpGrepToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\n\n/**\n * Factory for creating Vercel AI SDK-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.vercel.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.vercel.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * \n * // Use with Vercel AI SDK\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { grep: grepTool, search: searchTool, edit: editTool },\n * prompt: 'Find and fix the bug'\n * });\n * ```\n */\nexport class VercelToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create a Vercel AI SDK-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (apiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'apiKey'>) {\n return createMorphWarpGrepTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface\n * \n * @example\n * ```typescript\n * import { MorphClient } from '@morphllm/morphsdk';\n * \n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * \n * // Direct execution\n * await morph.fastApply.execute({ target_filepath: 'src/index.ts', ... });\n * await morph.warpGrep.execute({ query: 'Find auth', repoRoot: '.' });\n * await morph.codebaseSearch.search({ query: 'auth logic', repoId: 'x' });\n * \n * // Tool creation for AI agents (API key inherited)\n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.anthropic.createCodebaseSearchTool({ repoId: 'x' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * \n * // Use tools with OpenAI\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [grepTool],\n * messages: [{ role: 'user', content: 'Find the bug' }]\n * });\n * ```\n */\n\nimport type { RetryConfig } from './tools/utils/resilience.js';\nimport { FastApplyClient } from './tools/fastapply/core.js';\nimport { CodebaseSearchClient } from './tools/codebase_search/core.js';\nimport { BrowserClient } from './tools/browser/core.js';\nimport { WarpGrepClient } from './tools/warp_grep/core.js';\nimport { MorphGit } from './git/index.js';\nimport { OpenAIRouter, AnthropicRouter, GeminiRouter, RawRouter } from './modelrouter/core.js';\nimport { OpenAIToolFactory, AnthropicToolFactory, VercelToolFactory } from './factories/index.js';\n\n/**\n * Configuration for the MorphClient\n */\nexport interface MorphClientConfig {\n /** Morph API key for authentication (defaults to MORPH_API_KEY env var) */\n apiKey?: string;\n /** Enable debug logging across all tools */\n debug?: boolean;\n /** Default timeout in milliseconds for API requests */\n timeout?: number;\n /** Retry configuration for failed requests */\n retryConfig?: RetryConfig;\n}\n\n/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface:\n * - fastApply: AI-powered file editing with intelligent merging\n * - codebaseSearch: Semantic code search\n * - warpGrep: Fast code search with ripgrep\n * - browser: AI-powered browser automation\n * - git: Version control operations\n * - routers: Intelligent model selection (OpenAI, Anthropic, Gemini)\n * - openai/anthropic/vercel: Tool factories for agent frameworks\n */\nexport class MorphClient {\n /** Client configuration */\n public config: MorphClientConfig;\n\n /** FastApply tool for editing files with AI-powered merge */\n public fastApply: FastApplyClient;\n\n /** CodebaseSearch tool for semantic code search */\n public codebaseSearch: CodebaseSearchClient;\n\n /** WarpGrep tool for fast code search using ripgrep */\n public warpGrep: WarpGrepClient;\n\n /** Browser tool for AI-powered browser automation */\n public browser: BrowserClient;\n\n /** Git tool for version control operations */\n public git: MorphGit;\n\n /** Model routers for intelligent model selection */\n public routers: {\n openai: OpenAIRouter;\n anthropic: AnthropicRouter;\n gemini: GeminiRouter;\n raw: RawRouter;\n };\n\n /** OpenAI-compatible tool factories */\n public openai: OpenAIToolFactory;\n\n /** Anthropic-compatible tool factories */\n public anthropic: AnthropicToolFactory;\n\n /** Vercel AI SDK tool factories */\n public vercel: VercelToolFactory;\n\n /**\n * Create a new Morph SDK client\n * \n * @param config - Client configuration (apiKey, debug, timeout, retryConfig)\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * ```\n */\n constructor(config: MorphClientConfig = {}) {\n this.config = config;\n\n // Initialize all sub-clients with shared config\n this.fastApply = new FastApplyClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.codebaseSearch = new CodebaseSearchClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.warpGrep = new WarpGrepClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.browser = new BrowserClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.git = new MorphGit({\n apiKey: config.apiKey,\n retryConfig: config.retryConfig,\n });\n\n this.routers = {\n openai: new OpenAIRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n anthropic: new AnthropicRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n gemini: new GeminiRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n raw: new RawRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n };\n\n // Initialize tool factories\n this.openai = new OpenAIToolFactory(config);\n this.anthropic = new AnthropicToolFactory(config);\n this.vercel = new VercelToolFactory(config);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;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,OAAO;AAAA,IACtB,CAAC;AAED,SAAK,UAAU,IAAI,cAAc;AAAA,MAC/B,QAAQ,OAAO;AAAA,MACf,OAAO,OAAO;AAAA,MACd,SAAS,OAAO;AAAA,MAChB,aAAa,OAAO;AAAA,IACtB,CAAC;AAED,SAAK,MAAM,IAAI,SAAS;AAAA,MACtB,QAAQ,OAAO;AAAA,MACf,aAAa,OAAO;AAAA,IACtB,CAAC;AAED,SAAK,UAAU;AAAA,MACb,QAAQ,IAAI,aAAa;AAAA,QACvB,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,MACD,WAAW,IAAI,gBAAgB;AAAA,QAC7B,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,MACD,QAAQ,IAAI,aAAa;AAAA,QACvB,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,MACD,KAAK,IAAI,UAAU;AAAA,QACjB,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,IACH;AAGA,SAAK,SAAS,IAAI,kBAAkB,MAAM;AAC1C,SAAK,YAAY,IAAI,qBAAqB,MAAM;AAChD,SAAK,SAAS,IAAI,kBAAkB,MAAM;AAAA,EAC5C;AACF;","names":["resolve","DEFAULT_CONFIG","resolve","path","path","import_path","path","import_promises","import_path","resolve","import_path","path","fs","import_promises","fs","fs","path","import_fs","git","fs","http","resolve","import_isomorphic_git","import_node","DEFAULT_CONFIG","tool","formatResult","formatResult","execute","getSystemPrompt","formatResult","execute","createMorphWarpGrepTool","tool","execute","createCodebaseSearchTool","formatResult","editFileTool","formatResult","createEditFileTool","createMorphWarpGrepTool","createCodebaseSearchTool","createEditFileTool","createMorphWarpGrepTool","import_ai","import_zod","createCodebaseSearchTool","import_ai","import_zod","editFileTool","createEditFileTool","createMorphWarpGrepTool","createCodebaseSearchTool","createEditFileTool"]}
|
|
1
|
+
{"version":3,"sources":["../index.ts","../tools/fastapply/core.ts","../tools/utils/resilience.ts","../tools/codebase_search/core.ts","../tools/browser/live.ts","../tools/browser/core.ts","../tools/warp_grep/agent/config.ts","../tools/warp_grep/agent/prompt.ts","../tools/warp_grep/agent/parser.ts","../tools/warp_grep/agent/tools/grep.ts","../tools/warp_grep/agent/tools/read.ts","../tools/warp_grep/agent/tools/list_directory.ts","../tools/warp_grep/agent/tools/finish.ts","../tools/warp_grep/agent/formatter.ts","../tools/warp_grep/agent/helpers.ts","../tools/warp_grep/agent/runner.ts","../tools/warp_grep/providers/local.ts","../tools/warp_grep/utils/ripgrep.ts","../tools/warp_grep/utils/paths.ts","../tools/warp_grep/utils/files.ts","../tools/warp_grep/providers/remote.ts","../tools/warp_grep/client.ts","../git/client.ts","../git/index.ts","../modelrouter/core.ts","../tools/warp_grep/prompts.ts","../tools/warp_grep/openai.ts","../tools/codebase_search/prompts.ts","../tools/codebase_search/openai.ts","../tools/fastapply/prompts.ts","../tools/fastapply/openai.ts","../factories/openai.ts","../tools/warp_grep/anthropic.ts","../tools/codebase_search/anthropic.ts","../tools/fastapply/anthropic.ts","../factories/anthropic.ts","../tools/warp_grep/vercel.ts","../tools/codebase_search/vercel.ts","../tools/fastapply/vercel.ts","../factories/vercel.ts","../client.ts","../tools/warp_grep/gemini.ts"],"sourcesContent":["/**\n * Morph SDK - Main Entry Point\n * \n * Provides two ways to use the SDK:\n * 1. MorphClient - Unified client with all tools and tool factories\n * 2. Individual tool clients - FastApplyClient, CodebaseSearchClient, WarpGrepClient, BrowserClient, etc.\n * \n * @example\n * ```typescript\n * // Unified client approach (recommended)\n * import { MorphClient } from '@morphllm/morphsdk';\n * \n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY \n * });\n * \n * // Direct execution\n * await morph.fastApply.execute({ ... });\n * await morph.warpGrep.execute({ query: 'Find auth', repoRoot: '.' });\n * \n * // Tool creation for AI agents (API key inherited)\n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.anthropic.createCodebaseSearchTool({ repoId: 'x' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * ```\n */\n\n// Export unified client\nexport { MorphClient } from './client.js';\nexport type { MorphClientConfig } from './client.js';\n\n// Export individual tool clients\nexport { FastApplyClient } from './tools/fastapply/core.js';\nexport { CodebaseSearchClient } from './tools/codebase_search/core.js';\nexport { WarpGrepClient } from './tools/warp_grep/client.js';\nexport { BrowserClient } from './tools/browser/core.js';\nexport { MorphGit } from './git/index.js';\n\n// Export WarpGrep providers\nexport { LocalRipgrepProvider } from './tools/warp_grep/index.js';\n\n// Export model routers\nexport { OpenAIRouter, AnthropicRouter, GeminiRouter, RawRouter } from './modelrouter/core.js';\n\n// Export tool factories\nexport { OpenAIToolFactory, AnthropicToolFactory, VercelToolFactory } from './factories/index.js';\n\n// Export applyEdit function for code-in/code-out workflow\nexport { applyEdit } from './tools/fastapply/core.js';\n\n// Re-export core types\nexport type {\n // FastApply types\n EditFileConfig,\n EditFileInput,\n EditFileResult,\n EditChanges,\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n} from './tools/fastapply/types.js';\n\nexport type {\n // CodebaseSearch types\n CodebaseSearchConfig,\n CodebaseSearchInput,\n CodebaseSearchResult,\n CodeSearchResult,\n SearchStats,\n} from './tools/codebase_search/types.js';\n\nexport type {\n // WarpGrep types\n WarpGrepClientConfig,\n WarpGrepInput,\n WarpGrepResult,\n WarpGrepContext,\n WarpGrepToolConfig,\n WarpGrepProvider,\n // Provider types for custom providers\n GrepResult,\n ReadResult,\n ListDirectoryEntry,\n} from './tools/warp_grep/types.js';\n\nexport type {\n // WarpGrep agent types (advanced usage)\n AgentRunResult,\n SessionConfig,\n ChatMessage,\n} from './tools/warp_grep/agent/types.js';\n\nexport type {\n // Browser types\n BrowserConfig,\n BrowserTaskInput,\n BrowserTaskInputWithSchema,\n BrowserTaskResult,\n BrowserTaskWithPromise,\n BrowserTaskWithPromiseAndSchema,\n RecordingStatus,\n BrowserError,\n ErrorsResponse,\n BrowserModel,\n LiveSessionOptions,\n IframeOptions,\n} from './tools/browser/types.js';\n\nexport type {\n // ModelRouter types\n RouterConfig,\n RouterInput,\n RouterResult,\n RawRouterResult,\n ComplexityLevel,\n RouterMode,\n Provider,\n} from './modelrouter/types.js';\n\nexport type {\n // Git types\n MorphGitConfig,\n} from './git/types.js';\n\nexport type {\n // Utility types\n RetryConfig,\n} from './tools/utils/resilience.js';\n\n","/**\n * Core implementation of Morph Fast Apply\n */\n\nimport { readFile, writeFile } from 'fs/promises';\nimport { join, resolve, relative } from 'path';\nimport { createTwoFilesPatch } from 'diff';\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport type {\n EditFileInput,\n EditFileResult,\n EditFileConfig,\n EditChanges,\n MorphApplyResponse,\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n} from './types.js';\n\nconst DEFAULT_CONFIG: Required<Omit<EditFileConfig, 'morphApiKey' | 'systemPrompt' | 'retryConfig' | 'description'>> = {\n morphApiUrl: 'https://api.morphllm.com',\n baseDir: process.cwd(),\n generateUdiff: true,\n autoWrite: true,\n timeout: 30000,\n debug: false,\n};\n\n/**\n * FastApply client for programmatic file editing\n */\nexport class FastApplyClient {\n private config: EditFileConfig;\n\n constructor(config: { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n this.config = {\n morphApiKey: config.apiKey,\n morphApiUrl: DEFAULT_CONFIG.morphApiUrl,\n debug: config.debug,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n retryConfig: config.retryConfig,\n generateUdiff: DEFAULT_CONFIG.generateUdiff,\n autoWrite: DEFAULT_CONFIG.autoWrite,\n };\n }\n\n /**\n * Execute a file edit operation\n * \n * @param input - Edit parameters including filepath, instructions, and code_edit\n * @param overrides - Optional config overrides for this operation\n * @returns Edit result with success status and changes\n */\n async execute(input: EditFileInput, overrides?: Partial<EditFileConfig>): Promise<EditFileResult> {\n return executeEditFile(input, { ...this.config, ...overrides });\n }\n\n /**\n * Apply an edit to code directly without file I/O\n * \n * Useful for sandbox environments or when you manage your own file system.\n * Compatible with the earlier OpenAI client API contract.\n * \n * @param input - Code and edit parameters\n * @param overrides - Optional config overrides for this operation\n * @returns Result with merged code\n * \n * @example\n * ```typescript\n * const result = await client.applyEdit({\n * originalCode: 'function hello() { return \"world\"; }',\n * codeEdit: 'function hello() { return \"universe\"; }',\n * instructions: 'Change return value'\n * });\n * console.log(result.mergedCode);\n * ```\n */\n async applyEdit(input: ApplyEditInput, overrides?: Partial<ApplyEditConfig>): Promise<ApplyEditResult> {\n return applyEdit(input, { ...this.config, ...overrides });\n }\n}\n\n/**\n * Generate a unified diff between two strings\n */\nexport function generateUdiff(\n original: string,\n modified: string,\n filepath: string\n): string {\n return createTwoFilesPatch(\n filepath,\n filepath,\n original,\n modified,\n 'Original',\n 'Modified'\n );\n}\n\n/**\n * Count changes from a unified diff\n */\nexport function countChanges(original: string, modified: string): EditChanges {\n const diff = generateUdiff(original, modified, 'file');\n const lines = diff.split('\\n');\n \n let linesAdded = 0;\n let linesRemoved = 0;\n \n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n linesAdded++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n linesRemoved++;\n }\n }\n \n const linesModified = Math.min(linesAdded, linesRemoved);\n \n return {\n linesAdded: linesAdded - linesModified,\n linesRemoved: linesRemoved - linesModified,\n linesModified,\n };\n}\n\n/**\n * Call Morph Apply API to merge code edits\n * Uses OpenAI-compatible chat completions endpoint with XML-formatted message\n */\nasync function callMorphAPI(\n originalCode: string,\n codeEdit: string,\n instructions: string,\n filepath: string,\n config: EditFileConfig\n): Promise<string> {\n const apiKey = config.morphApiKey || process.env.MORPH_API_KEY;\n const apiUrl = config.morphApiUrl || DEFAULT_CONFIG.morphApiUrl;\n const timeout = config.timeout || DEFAULT_CONFIG.timeout;\n const debug = config.debug || false;\n \n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n \n // Format message with XML tags as per Morph Fast Apply spec\n const message = `<instruction>${instructions}</instruction>\\n<code>${originalCode}</code>\\n<update>${codeEdit}</update>`;\n \n if (debug) {\n console.log(`[FastApply] Calling ${apiUrl}/v1/chat/completions`);\n console.log(`[FastApply] File: ${filepath}, Instructions: ${instructions.slice(0, 60)}...`);\n console.log(`[FastApply] Original: ${originalCode.length} chars, Edit: ${codeEdit.length} chars`);\n }\n \n const startTime = Date.now();\n \n // Fetch with retry and timeout\n const fetchPromise = fetchWithRetry(\n `${apiUrl}/v1/chat/completions`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: 'morph-v3-fast',\n messages: [{ role: 'user', content: message }],\n }),\n },\n config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n timeout,\n `Morph API request timed out after ${timeout}ms`\n );\n \n if (!response.ok) {\n const error = await response.text();\n if (debug) console.error(`[FastApply] API error: ${response.status} - ${error}`);\n throw new Error(`Morph API error (${response.status}): ${error}`);\n }\n \n const data: MorphApplyResponse = await response.json();\n const elapsed = Date.now() - startTime;\n \n if (debug) {\n console.log(`[FastApply] ✅ Success in ${elapsed}ms, merged: ${data.choices[0].message.content.length} chars`);\n }\n \n return data.choices[0].message.content;\n}\n\n/**\n * Execute a file edit using Morph Fast Apply\n */\nexport async function executeEditFile(\n input: EditFileInput,\n config: EditFileConfig = {}\n): Promise<EditFileResult> {\n const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;\n const fullPath = resolve(join(baseDir, input.target_filepath));\n const debug = config.debug || false;\n \n // Security: ensure file is within baseDir\n const relativePath = relative(baseDir, fullPath);\n if (relativePath.startsWith('..') || fullPath === baseDir) {\n return {\n success: false,\n filepath: input.target_filepath,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`,\n };\n }\n \n try {\n if (debug) console.log(`[FastApply] Reading file: ${input.target_filepath}`);\n \n // Handle both existing and non-existent files\n let originalCode = '';\n try {\n originalCode = await readFile(fullPath, 'utf-8');\n } catch (error: any) {\n if (error.code !== 'ENOENT') {\n throw error; // Re-throw if it's not a \"file not found\" error\n }\n // File doesn't exist, proceed with empty content (will create new file)\n if (debug) console.log(`[FastApply] File doesn't exist, will create new file`);\n }\n \n const mergedCode = await callMorphAPI(originalCode, input.code_edit, input.instructions, input.target_filepath, config);\n \n const udiff = config.generateUdiff !== false ? generateUdiff(originalCode, mergedCode, input.target_filepath) : undefined;\n \n if (config.autoWrite !== false) {\n await writeFile(fullPath, mergedCode, 'utf-8');\n if (debug) console.log(`[FastApply] Wrote ${mergedCode.length} chars to ${input.target_filepath}`);\n }\n \n const changes = countChanges(originalCode, mergedCode);\n \n return {\n success: true,\n filepath: input.target_filepath,\n udiff,\n changes,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n if (debug) console.error(`[FastApply] Error: ${errorMessage}`);\n \n return {\n success: false,\n filepath: input.target_filepath,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\n}\n\n/**\n * Apply an edit to code directly without file I/O\n * \n * This is the code-in/code-out API that accepts code content directly\n * and returns the merged result without reading or writing any files.\n * \n * @param input - Code and edit parameters\n * @param config - Optional configuration\n * @returns Result with merged code\n * \n * @example\n * ```typescript\n * import { applyEdit } from '@morphllm/morphsdk';\n * \n * const result = await applyEdit({\n * originalCode: fs.readFileSync('file.ts', 'utf-8'),\n * codeEdit: '// ... existing code ...\\nconst newVar = 42;\\n// ... existing code ...',\n * instructions: 'Add a new variable',\n * filepath: 'file.ts' // optional, for udiff context\n * });\n * \n * if (result.success) {\n * fs.writeFileSync('file.ts', result.mergedCode);\n * }\n * ```\n */\nexport async function applyEdit(\n input: ApplyEditInput,\n config: ApplyEditConfig = {}\n): Promise<ApplyEditResult> {\n const debug = config.debug || false;\n const filepath = input.filepath || 'file';\n\n try {\n if (debug) {\n console.log(`[FastApply] Applying edit to code (${input.originalCode.length} chars)`);\n }\n\n const mergedCode = await callMorphAPI(\n input.originalCode,\n input.codeEdit,\n input.instructions,\n filepath,\n config\n );\n\n const udiff = config.generateUdiff !== false\n ? generateUdiff(input.originalCode, mergedCode, filepath)\n : undefined;\n\n const changes = countChanges(input.originalCode, mergedCode);\n\n return {\n success: true,\n mergedCode,\n udiff,\n changes,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n if (debug) console.error(`[FastApply] Error: ${errorMessage}`);\n\n return {\n success: false,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\n}\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 codebase search\n * Calls Morph rerank service for two-stage semantic search\n */\n\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n/**\n * CodebaseSearch client for programmatic semantic search\n */\nexport class CodebaseSearchClient {\n private config: { \n apiKey?: string; \n searchUrl?: string; \n debug?: boolean; \n timeout?: number; \n retryConfig?: any;\n };\n\n constructor(config: { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n this.config = {\n apiKey: config.apiKey,\n searchUrl: process.env.MORPH_SEARCH_URL || 'https://repos.morphllm.com',\n debug: config.debug,\n timeout: config.timeout || 30000,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Execute a semantic code search\n * \n * @param input - Search parameters including query, repoId, and target directories\n * @param overrides - Optional config overrides for this operation\n * @returns Search results with ranked code matches\n */\n async search(\n input: { query: string; repoId: string; target_directories?: string[]; explanation?: string; limit?: number },\n overrides?: any\n ): Promise<CodebaseSearchResult> {\n return executeCodebaseSearch(\n {\n query: input.query,\n target_directories: input.target_directories,\n explanation: input.explanation,\n limit: input.limit,\n },\n { ...this.config, repoId: input.repoId, ...overrides }\n );\n }\n}\n\n/**\n * Execute semantic code search\n */\nexport async function executeCodebaseSearch(\n input: CodebaseSearchInput,\n config: CodebaseSearchConfig\n): Promise<CodebaseSearchResult> {\n const apiKey = config.apiKey || process.env.MORPH_API_KEY;\n if (!apiKey) {\n throw new Error('MORPH_API_KEY not found. Set environment variable or pass in config');\n }\n\n const searchUrl = config.searchUrl || process.env.MORPH_SEARCH_URL || 'https://repos.morphllm.com';\n const timeout = config.timeout || 30000;\n const debug = config.debug || false;\n\n if (debug) {\n console.log(`[CodebaseSearch] Query: \"${input.query.slice(0, 60)}...\" repo=${config.repoId}`);\n console.log(`[CodebaseSearch] URL: ${searchUrl}/v1/codebase_search`);\n }\n\n const startTime = Date.now();\n\n try {\n const fetchPromise = fetchWithRetry(\n `${searchUrl}/v1/codebase_search`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n query: input.query,\n repoId: config.repoId,\n targetDirectories: input.target_directories || [],\n limit: input.limit || 10,\n candidateLimit: 50,\n }),\n },\n config.retryConfig\n );\n\n const response = await withTimeout(fetchPromise, timeout, `Codebase search timed out after ${timeout}ms`);\n\n if (!response.ok) {\n const errorText = await response.text();\n if (debug) console.error(`[CodebaseSearch] Error: ${response.status} - ${errorText}`);\n return {\n success: false,\n results: [],\n stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },\n error: `Search failed (${response.status}): ${errorText}`,\n };\n }\n\n const data = await response.json();\n const elapsed = Date.now() - startTime;\n\n if (debug) {\n console.log(`[CodebaseSearch] ✅ ${data.results?.length || 0} results in ${elapsed}ms`);\n }\n\n return {\n success: true,\n results: data.results || [],\n stats: data.stats || { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: elapsed },\n };\n\n } catch (error) {\n if (debug) console.error(`[CodebaseSearch] Exception: ${error instanceof Error ? error.message : error}`);\n return {\n success: false,\n results: [],\n stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n}\n\n","/**\n * Live session utilities for Morph browser sessions\n * \n * Provides helpers for embedding and sharing live browser sessions with WebRTC streaming.\n */\n\nimport type { LiveSessionOptions, IframeOptions } from './types.js';\n\n/**\n * Preset configurations for common use cases\n */\nexport const LIVE_PRESETS = {\n /** Read-only monitoring (no interaction) */\n readonly: { interactive: false } as LiveSessionOptions,\n /** Interactive control (human-in-the-loop) */\n interactive: { interactive: true } as LiveSessionOptions,\n /** Watch-only without controls */\n monitoring: { interactive: false, showControls: false } as LiveSessionOptions,\n} as const;\n\n/**\n * Build a live session URL with query parameters\n * \n * @param debugUrl - Live session debug URL (e.g., from task.debugUrl)\n * @param options - Live session configuration options\n * @returns URL with query parameters for iframe embedding\n * \n * @example\n * ```typescript\n * const url = buildLiveUrl(task.debugUrl, { interactive: true });\n * // Returns: https://example.com/sessions/abc?interactive=true\n * ```\n */\nexport function buildLiveUrl(\n debugUrl: string,\n options: LiveSessionOptions = {}\n): string {\n if (!debugUrl) {\n throw new Error(\n 'debugUrl is required. Ensure your backend returns debugUrl in the task response. ' +\n 'Contact support@morphllm.com if you need help.'\n );\n } \n\n const url = new URL(debugUrl);\n \n // Add query parameters for supported options\n if (options.interactive !== undefined) {\n url.searchParams.set('interactive', String(options.interactive));\n }\n \n if (options.theme) {\n url.searchParams.set('theme', options.theme);\n }\n \n if (options.showControls !== undefined) {\n url.searchParams.set('showControls', String(options.showControls));\n }\n \n if (options.pageId) {\n url.searchParams.set('pageId', options.pageId);\n }\n \n if (options.pageIndex) {\n url.searchParams.set('pageIndex', options.pageIndex);\n }\n \n return url.toString();\n}\n\n/**\n * Build iframe HTML for embedding a live session\n * \n * @param debugUrl - Live session debug URL\n * @param options - Iframe configuration including dimensions and session options\n * @returns HTML iframe element as string\n * \n * @example\n * ```typescript\n * const iframe = buildLiveIframe(task.debugUrl, {\n * interactive: true,\n * width: '100%',\n * height: '600px'\n * });\n * ```\n */\nexport function buildLiveIframe(\n debugUrl: string,\n options: IframeOptions = {}\n): string {\n const {\n width = '100%',\n height = '600px',\n style = '',\n className = '',\n ...sessionOptions\n } = options;\n\n const src = buildLiveUrl(debugUrl, sessionOptions);\n \n // Convert numeric dimensions to pixels\n const widthStr = typeof width === 'number' ? `${width}px` : width;\n const heightStr = typeof height === 'number' ? `${height}px` : height;\n \n // Build style attribute\n const baseStyle = `width: ${widthStr}; height: ${heightStr}; border: none;`;\n const fullStyle = style ? `${baseStyle} ${style}` : baseStyle;\n \n // Build iframe attributes\n const attributes = [\n `src=\"${src}\"`,\n `style=\"${fullStyle}\"`,\n ];\n \n if (className) {\n attributes.push(`class=\"${className}\"`);\n }\n \n return `<iframe ${attributes.join(' ')}></iframe>`;\n}\n\n/**\n * Build complete embed code with HTML snippet\n * \n * @param debugUrl - Live session debug URL\n * @param options - Iframe configuration\n * @returns Multi-line HTML snippet ready to copy-paste\n * \n * @example\n * ```typescript\n * const code = buildEmbedCode(task.debugUrl, { interactive: false });\n * console.log(code);\n * // <!-- Embed Morph Live Session -->\n * // <iframe src=\"...\" style=\"...\"></iframe>\n * ```\n */\nexport function buildEmbedCode(\n debugUrl: string,\n options: IframeOptions = {}\n): string {\n const iframe = buildLiveIframe(debugUrl, options);\n return `<!-- Embed Morph Live Session -->\\n${iframe}`;\n}\n\n/**\n * Get live session options from preset name or custom config\n * \n * @internal\n */\nexport function resolvePreset(\n optionsOrPreset?: string | IframeOptions\n): IframeOptions {\n if (!optionsOrPreset) {\n return {};\n }\n \n if (typeof optionsOrPreset === 'string') {\n const preset = LIVE_PRESETS[optionsOrPreset as keyof typeof LIVE_PRESETS];\n if (!preset) {\n throw new Error(\n `Unknown preset: ${optionsOrPreset}. Available presets: ${Object.keys(LIVE_PRESETS).join(', ')}`\n );\n }\n return preset;\n }\n \n return optionsOrPreset;\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: 1000000, // 10 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 const apiUrl = this.config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = this.config.debug || false;\n \n if (debug) {\n console.log(`[Browser] createTask: \"${input.task.slice(0, 60)}...\" url=${input.url || 'none'}`);\n console.log(`[Browser] Calling async endpoint: ${apiUrl}/browser-task/async`);\n }\n \n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.config.apiKey) headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n \n // Call ASYNC endpoint for immediate return with live URL\n const response = await fetch(`${apiUrl}/browser-task/async`, {\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 allow_resizing: input.allow_resizing ?? false,\n structured_output: 'schema' in input ? stringifyStructuredOutput(input.schema) : undefined,\n }),\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 = await response.json();\n \n if (debug) {\n console.log(`[Browser] ✅ Task created: recording_id=${result.recording_id ?? 'none'} debug_url=${result.debugUrl ? 'available' : 'none'}`);\n }\n \n if ('schema' in input) {\n return wrapTaskResponseWithSchema(result, this.config, input.schema);\n } else {\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 * Returns the full task result including rich agent history data (urls, errors, \n * action_history, judgement, etc.). When using this as an agent tool, use the\n * formatResult() functions from the SDK adapters to return a concise summary.\n * \n * @param input - Task parameters\n * @param config - Optional configuration (apiKey, apiUrl to override default)\n * @returns Task result with success status, findings, and comprehensive execution history\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('URLs visited:', result.urls);\n * console.log('Actions taken:', result.action_names);\n * console.log('Has errors:', result.has_errors);\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 allow_resizing: input.allow_resizing ?? false,\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 const wrapped: BrowserTaskWithPromise = {\n ...result,\n task_id: result.task_id || '',\n liveUrl: result.task_id \n ? generateLiveUrl(result.task_id, config)\n : result.debugUrl || '',\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n // If we have a task_id, poll task status endpoint\n if (result.task_id) {\n return pollTaskUntilComplete(result.task_id!, config, pollConfig);\n }\n // If we have a recording_id, poll recording status instead\n if (result.recording_id) {\n const recording = await waitForRecording(\n result.recording_id,\n config,\n pollConfig\n );\n // Return a result-like object (recording doesn't have full task result)\n return {\n ...result,\n recording_status: recording.status,\n } as BrowserTaskResult;\n }\n // No way to poll completion\n throw new Error('Cannot poll completion: no task_id or recording_id available');\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 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: result.task_id\n ? generateLiveUrl(result.task_id, config)\n : result.debugUrl || '',\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n // If we have a task_id, poll task status endpoint\n if (result.task_id) {\n const finalResult = await pollTaskUntilComplete(result.task_id!, config, pollConfig);\n return parseStructuredTaskOutput<T>(finalResult, schema);\n }\n // If we have a recording_id, poll recording status instead\n if (result.recording_id) {\n const recording = await waitForRecording(\n result.recording_id,\n config,\n pollConfig\n );\n // Return parsed result (recording doesn't have task output)\n return {\n ...parsed,\n recording_status: recording.status,\n };\n }\n // No way to poll completion\n throw new Error('Cannot poll completion: no task_id or recording_id available');\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","export const AGENT_CONFIG = {\n MAX_TURNS: 4,\n TIMEOUT_MS: 30_000,\n MAX_CONTEXT_CHARS: 540_000,\n MAX_OUTPUT_LINES: 200,\n MAX_READ_LINES: 800,\n MAX_LIST_DEPTH: 3,\n LIST_TIMEOUT_MS: 2_000,\n};\n\n/**\n * Comprehensive exclusion list for directories and files\n * These patterns are used with ripgrep's -g flag\n */\nconst BUILTIN_EXCLUDES = [\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n \n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'packages', 'Pods', '.bundle',\n \n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs', '*.egg-info',\n \n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n \n // Cache directories\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n \n // IDE/Editor\n '.idea', '.vscode', '.vs',\n \n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n \n // Temporary\n 'tmp', 'temp', '.tmp', '.temp',\n \n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n \n // Binary/minified\n '*.min.js', '*.min.css', '*.bundle.js',\n '*.wasm', '*.so', '*.dll', '*.pyc',\n '*.map', '*.js.map',\n \n // Hidden directories catch-all\n '.*',\n];\n\nexport const DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || '')\n .split(',')\n .map(s => s.trim())\n .filter(Boolean)\n .concat(BUILTIN_EXCLUDES);\n\nexport const DEFAULT_MODEL = 'morph-warp-grep-v1';\n\n\n","export const SYSTEM_PROMPT = `You are a code search agent. Your task is to find all relevant code for a given search_string.\n\n### workflow\nYou have exactly 4 turns. The 4th turn MUST be a \\`finish\\` call. Each turn allows up to 8 parallel tool calls.\n\n- Turn 1: Map the territory OR dive deep (based on search_string specificity)\n- Turn 2-3: Refine based on findings\n- Turn 4: MUST call \\`finish\\` with all relevant code locations\n- You MAY call \\`finish\\` early if confident—but never before at least 1 search turn.\n- The user strongly prefers if you can call the finish tool early, but you must be correct\n\nRemember, if the task feels easy to you, it is strongly desirable to call 'finish' early using fewer turns, but quality over speed\n\n### tools\nTool calls use nested XML elements:\n\\`\\`\\`xml\n<tool_name>\n <parameter>value</parameter>\n</tool_name>\n\\`\\`\\`\n\n### \\`list_directory\\`\nDirectory tree view. Shows structure of a path, optionally filtered by regex pattern.\n\nElements:\n- \\`<path>\\` (required): Directory path to list (use \\`.\\` for repo root)\n- \\`<pattern>\\` (optional): Regex to filter results\n\nExamples:\n\\`\\`\\`\n<list_directory>\n <path>src/services</path>\n</list_directory>\n\n<list_directory>\n <path>lib/utils</path>\n <pattern>.*\\\\.(ts|js)$</pattern>\n</list_directory>\n\\`\\`\\`\n\n### \\`read\\`\nRead file contents. Supports multiple line ranges.\n- Returns numbered lines for easy reference\n- ALWAYS include import statements (usually lines 1-20). Better to over-include than miss context.\n\nElements:\n- \\`<path>\\` (required): File path to read\n- \\`<lines>\\` (optional): Line ranges like \"1-50,75-80,100-120\" (omit to read entire file)\n\nExamples:\n\\`\\`\\`\n<read>\n <path>src/main.py</path>\n</read>\n\n<read>\n <path>src/auth.py</path>\n <lines>1-20,45-80,150-200</lines>\n</read>\n\\`\\`\\`\n\n### \\`grep\\`\nSearch for pattern matches across files. Returns matches with 1 line of context above and below.\n- Match lines use \\`:\\` separator → \\`filepath:linenum:content\\`\n- Context lines use \\`-\\` separator → \\`filepath-linenum-content\\`\n\nElements:\n- \\`<pattern>\\` (required): Search pattern (regex). Use \\`(a|b)\\` for OR patterns.\n- \\`<sub_dir>\\` (optional): Subdirectory to search in (defaults to \\`.\\`)\n- \\`<glob>\\` (optional): File pattern filter like \\`*.py\\` or \\`*.{ts,tsx}\\`\n\nExamples:\n\\`\\`\\`\n<grep>\n <pattern>(authenticate|authorize|login)</pattern>\n <sub_dir>src/auth/</sub_dir>\n</grep>\n\n<grep>\n <pattern>class.*(Service|Controller)</pattern>\n <glob>*.{ts,js}</glob>\n</grep>\n\n<grep>\n <pattern>(DB_HOST|DATABASE_URL|connection)</pattern>\n <glob>*.{py,yaml,env}</glob>\n <sub_dir>lib/</sub_dir>\n</grep>\n\\`\\`\\`\n\n### \\`finish\\`\nSubmit final answer with all relevant code locations. Uses nested \\`<file>\\` elements.\n\nFile elements:\n- \\`<path>\\` (required): File path\n- \\`<lines>\\` (optional): Line ranges like \"1-50,75-80\" (\\`*\\` for entire file)\n\nALWAYS include import statements (usually lines 1-20). Better to over-include than miss context.\n\nExamples:\n\\`\\`\\`\n<finish>\n <file>\n <path>src/auth.py</path>\n <lines>1-15,25-50,75-80</lines>\n </file>\n <file>\n <path>src/models/user.py</path>\n <lines>*</lines>\n </file>\n</finish>\n\\`\\`\\`\n</tools>\n\n<strategy>\n**Before your first tool call, classify the search_string:**\n\n| Search_string Type | Round 1 Strategy | Early Finish? |\n|------------|------------------|---------------|\n| **Specific** (function name, error string, unique identifier) | 8 parallel greps on likely paths | Often by round 2 |\n| **Conceptual** (how does X work, where is Y handled) | list_directory + 2-3 broad greps | Rarely early |\n| **Exploratory** (find all tests, list API endpoints) | list_directory at multiple depths | Usually needs 3 rounds |\n\n**Parallel call patterns:**\n- **Shotgun grep**: Same pattern, 8 different directories—fast coverage\n- **Variant grep**: 8 pattern variations (synonyms, naming conventions)—catches inconsistent codebases\n- **Funnel**: 1 list_directory + 7 greps—orient and search simultaneously\n- **Deep read**: 8 reads on files you already identified—gather full context fast\n\n**Tool call expectations:**\n- Low quality tool calls are ones that give back sparse information. This either means they are not well thought out and are not educated guesses OR, they are too broad and give back too many results.\n- High quality tool calls strike a balance between complexity in the tool call to exclude results we know we don't want, and how wide the search space is so that we don't miss anything. It is ok to start off with wider search spaces, but is imperative that you use your intuition from there on out and seek high quality tool calls only.\n- You are not starting blind, you have some information about root level repo structure going in, so use that to prevent making trivial repo wide queries.\n- The grep tool shows you which file path and line numbers the pattern was found in, use this information smartly when trying to read the file.\n</strategy>\n\n<output_format>\nEVERY response MUST follow this exact format:\n\n1. First, wrap your reasoning in \\`<think>...</think>\\` tags containing:\n - Search_string classification (specific/conceptual/exploratory)\n - Confidence estimate (can I finish in 1-2 rounds?)\n - This round's parallel strategy\n - What signals would let me finish early?\n\n2. Then, output up to 8 tool calls using nested XML elements.\n\nExample:\n\\`\\`\\`\n<think>\nThis is a specific search_string about authentication. I'll grep for auth-related patterns.\nHigh confidence I can finish in 2 rounds if I find the auth module. I have already been shown the repo's structure at root\nStrategy: Shotgun grep across likely directories.\n</think>\n<grep>\n <pattern>(authenticate|login|session)</pattern>\n <sub_dir>src/auth/</sub_dir>\n</grep>\n<grep>\n <pattern>(middleware|interceptor)</pattern>\n <glob>*.{ts,js}</glob>\n</grep>\n<list_directory>\n <path>src/auth</path>\n</list_directory>\n\\`\\`\\`\n\nFinishing example:\n\\`\\`\\`\n<think>\nI think I have a rough idea, but this is my last turn so I must call the finish tool regardless.\n</think>\n<finish>\n <file>\n <path>src/auth/login.py</path>\n <lines>1-50</lines>\n </file>\n <file>\n <path>src/middleware/session.py</path>\n <lines>10-80</lines>\n </file>\n</finish>\n\\`\\`\\`\n\nNo commentary outside \\`<think>\\`. No explanations after tool calls.\n</output_format>\n\n<finishing_requirements>\nWhen calling \\`finish\\`:\n- Include the import section (typically lines 1-20) of each file\n- Include all function/class definitions that are relevant\n- Include any type definitions, interfaces, or constants used\n- Better to over-include than leave the user missing context\n- If unsure about boundaries, include more rather than less\n</finishing_requirements>`;\n\nexport function getSystemPrompt(): string {\n return SYSTEM_PROMPT;\n}\n","// Parses assistant lines into structured tool calls\nimport type { ToolCall } from './types.js';\n\nconst VALID_COMMANDS = ['list_directory', 'grep', 'read', 'finish'] as const;\ntype ValidCommand = typeof VALID_COMMANDS[number];\n\nfunction isValidCommand(name: string): name is ValidCommand {\n return VALID_COMMANDS.includes(name as ValidCommand);\n}\n\nfunction getXmlElementText(xml: string, tagName: string): string | null {\n const regex = new RegExp(`<${tagName}>([\\\\s\\\\S]*?)</${tagName}>`, 'i');\n const match = xml.match(regex);\n return match ? match[1].trim() : null;\n}\n\nfunction parseNestedXmlTools(text: string): ToolCall[] {\n const tools: ToolCall[] = [];\n \n // Match any XML tool tags - this allows graceful handling of unknown tools\n // that might be added in future versions (they are simply ignored)\n const toolRegex = /<([a-z_][a-z0-9_]*)>([\\s\\S]*?)<\\/\\1>/gi;\n let match;\n \n while ((match = toolRegex.exec(text)) !== null) {\n const rawToolName = match[1].toLowerCase();\n const content = match[2];\n \n // Skip unknown tools silently - enables forward compatibility\n if (!isValidCommand(rawToolName)) continue;\n \n const toolName = rawToolName;\n \n if (toolName === 'list_directory') {\n const path = getXmlElementText(content, 'path');\n const pattern = getXmlElementText(content, 'pattern');\n if (path) {\n tools.push({ name: 'list_directory', arguments: { path, pattern } });\n }\n } else if (toolName === 'grep') {\n const pattern = getXmlElementText(content, 'pattern');\n const subDir = getXmlElementText(content, 'sub_dir');\n const glob = getXmlElementText(content, 'glob');\n if (pattern) {\n tools.push({ \n name: 'grep', \n arguments: { \n pattern, \n path: subDir || '.', \n ...(glob && { glob }) \n } \n });\n }\n } else if (toolName === 'read') {\n const path = getXmlElementText(content, 'path');\n const linesStr = getXmlElementText(content, 'lines');\n if (path) {\n const args: Record<string, unknown> = { path };\n if (linesStr) {\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of linesStr.split(',')) {\n const trimmed = rangeStr.trim();\n if (!trimmed) continue;\n const [s, e] = trimmed.split('-').map(v => parseInt(v.trim(), 10));\n if (Number.isFinite(s) && Number.isFinite(e)) {\n ranges.push([s, e]);\n } else if (Number.isFinite(s)) {\n // Single line like \"100\"\n ranges.push([s, s]);\n }\n }\n if (ranges.length === 1) {\n args.start = ranges[0][0];\n args.end = ranges[0][1];\n } else if (ranges.length > 1) {\n args.lines = ranges;\n }\n }\n tools.push({ name: 'read', arguments: args });\n }\n } else if (toolName === 'finish') {\n // Parse nested <file> elements\n const fileRegex = /<file>([\\s\\S]*?)<\\/file>/gi;\n const files: Array<{ path: string; lines: Array<[number, number]> }> = [];\n let fileMatch;\n \n while ((fileMatch = fileRegex.exec(content)) !== null) {\n const fileContent = fileMatch[1];\n const filePath = getXmlElementText(fileContent, 'path');\n const linesStr = getXmlElementText(fileContent, 'lines');\n \n if (filePath && linesStr) {\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of linesStr.split(',')) {\n if (rangeStr.trim() === '*') {\n ranges.push([1, 999999]); // Entire file\n } else {\n const [s, e] = rangeStr.split('-').map(v => parseInt(v.trim(), 10));\n if (Number.isFinite(s) && Number.isFinite(e)) {\n ranges.push([s, e]);\n }\n }\n }\n if (ranges.length > 0) {\n files.push({ path: filePath, lines: ranges });\n }\n }\n }\n \n if (files.length > 0) {\n tools.push({ name: 'finish', arguments: { files } });\n }\n }\n }\n \n return tools;\n}\n\nfunction preprocessText(text: string): { lines: string[]; nestedTools: ToolCall[] } {\n let processed = text.replace(/<think>[\\s\\S]*?<\\/think>/gi, '');\n const nestedTools = parseNestedXmlTools(processed);\n const openingTagRegex = /<tool_call>|<tool>/gi;\n const closingTagRegex = /<\\/tool_call>|<\\/tool>/gi;\n \n const openingMatches = processed.match(openingTagRegex) || [];\n const closingMatches = processed.match(closingTagRegex) || [];\n \n if (openingMatches.length > closingMatches.length) {\n const lastClosingMatch = /<\\/tool_call>|<\\/tool>/gi;\n let lastClosingIndex = -1;\n let match;\n while ((match = lastClosingMatch.exec(processed)) !== null) {\n lastClosingIndex = match.index + match[0].length;\n }\n if (lastClosingIndex > 0) {\n processed = processed.slice(0, lastClosingIndex);\n }\n }\n const toolCallLines: string[] = [];\n const toolTagRegex = /<tool_call>([\\s\\S]*?)<\\/tool_call>|<tool>([\\s\\S]*?)<\\/tool>/gi;\n let tagMatch;\n \n while ((tagMatch = toolTagRegex.exec(processed)) !== null) {\n const content = (tagMatch[1] || tagMatch[2] || '').trim();\n if (content) {\n const lines = content.split(/\\r?\\n/).map(l => l.trim()).filter(l => l);\n toolCallLines.push(...lines);\n }\n }\n \n // Also extract raw tool calls (lines starting with valid commands)\n const allLines = processed.split(/\\r?\\n/).map(l => l.trim());\n for (const line of allLines) {\n if (!line) continue;\n if (line.startsWith('<')) continue;\n \n const firstWord = line.split(/\\s/)[0];\n if (VALID_COMMANDS.includes(firstWord as ValidCommand)) {\n if (!toolCallLines.includes(line)) {\n toolCallLines.push(line);\n }\n }\n }\n \n return { lines: toolCallLines, nestedTools };\n}\n\nexport class LLMResponseParser {\n private readonly finishSpecSplitRe = /,(?=[^,\\s]+:)/;\n\n parse(text: string): ToolCall[] {\n if (typeof text !== 'string') {\n throw new TypeError('Command text must be a string.');\n }\n \n // Preprocess to handle XML tags\n const { lines, nestedTools } = preprocessText(text);\n \n // Start with nested XML tools (new format)\n const commands: ToolCall[] = [...nestedTools];\n let finishAccumulator: Map<string, number[][]> | null = null;\n\n lines.forEach((line) => {\n if (!line || line.startsWith('#')) return;\n const parts = this.splitLine(line);\n if (parts.length === 0) return;\n const cmd = parts[0];\n \n switch (cmd) {\n case 'list_directory':\n this.handleListDirectory(parts, line, commands);\n break;\n case 'grep':\n this.handleGrep(parts, line, commands);\n break;\n case 'read':\n this.handleRead(parts, line, commands);\n break;\n case 'finish':\n finishAccumulator = this.handleFinish(parts, line, commands, finishAccumulator);\n break;\n default:\n // Silently ignore unknown commands\n break;\n }\n });\n\n if (finishAccumulator) {\n const map = finishAccumulator as Map<string, number[][]>;\n const entries = [...map.entries()];\n const filesPayload = entries.map(([path, ranges]) => ({\n path,\n lines: [...ranges].sort((a, b) => a[0] - b[0]) as Array<[number, number]>,\n }));\n commands.push({ name: 'finish', arguments: { files: filesPayload } });\n }\n return commands;\n }\n\n private splitLine(line: string): string[] {\n // Split by whitespace but keep quoted blocks as one\n const parts: string[] = [];\n let current = '';\n let inSingle = false;\n for (let i = 0; i < line.length; i++) {\n const ch = line[i];\n if (ch === \"'\" && line[i - 1] !== '\\\\') {\n inSingle = !inSingle;\n current += ch;\n } else if (!inSingle && /\\s/.test(ch)) {\n if (current) {\n parts.push(current);\n current = '';\n }\n } else {\n current += ch;\n }\n }\n if (current) parts.push(current);\n return parts;\n }\n\n /** Helper to create a _skip tool call with an error message */\n private skip(message: string): ToolCall {\n return { name: '_skip', arguments: { message } };\n }\n\n private handleListDirectory(parts: string[], rawLine: string, commands: ToolCall[]) {\n // list_directory <path> [pattern]\n if (parts.length < 2) {\n commands.push(this.skip(\n `[SKIPPED] Your command \"${rawLine}\" is missing a path. ` +\n `Correct format: list_directory <path> [pattern]. Example: list_directory src/`\n ));\n return;\n }\n const path = parts[1];\n const pattern = parts[2]?.replace(/^\"|\"$/g, '') ?? null;\n commands.push({ name: 'list_directory', arguments: { path, pattern } });\n }\n\n private handleGrep(parts: string[], rawLine: string, commands: ToolCall[]) {\n // grep '<pattern>' <path>\n if (parts.length < 3) {\n commands.push(this.skip(\n `[SKIPPED] Your command \"${rawLine}\" is missing arguments. ` +\n `Correct format: grep '<pattern>' <path>. Example: grep 'TODO' src/`\n ));\n return;\n }\n let pat = parts[1];\n // Be lenient: accept unquoted patterns by treating the first arg as the pattern\n if (pat.startsWith(\"'\") && pat.endsWith(\"'\")) {\n pat = pat.slice(1, -1);\n }\n // If pattern is empty after processing, skip\n if (!pat) {\n commands.push(this.skip(\n `[SKIPPED] Your command \"${rawLine}\" has an empty pattern. ` +\n `Provide a non-empty search pattern. Example: grep 'function' src/`\n ));\n return;\n }\n commands.push({ name: 'grep', arguments: { pattern: pat, path: parts[2] } });\n }\n\n private handleRead(parts: string[], rawLine: string, commands: ToolCall[]) {\n // read <path>[:start-end]\n if (parts.length < 2) {\n commands.push(this.skip(\n `[SKIPPED] Your command \"${rawLine}\" is missing a path. ` +\n `Correct format: read <path> or read <path>:<start>-<end>. Example: read src/index.ts:1-50`\n ));\n return;\n }\n const spec = parts[1];\n const rangeIdx = spec.indexOf(':');\n if (rangeIdx === -1) {\n commands.push({ name: 'read', arguments: { path: spec } });\n return;\n }\n const filePath = spec.slice(0, rangeIdx);\n const range = spec.slice(rangeIdx + 1);\n const [s, e] = range.split('-').map(v => parseInt(v, 10));\n // If range is invalid, fallback to reading the whole file\n if (!Number.isFinite(s) || !Number.isFinite(e)) {\n commands.push({ name: 'read', arguments: { path: filePath } });\n return;\n }\n commands.push({ name: 'read', arguments: { path: filePath, start: s, end: e } });\n }\n\n private handleFinish(parts: string[], rawLine: string, commands: ToolCall[], acc: Map<string, number[][]> | null) {\n // finish file1:1-10,20-30 file2:5-7\n const map = acc ?? new Map<string, number[][]>();\n const args = parts.slice(1);\n for (const token of args) {\n const [filePath, rangesText] = token.split(':', 2);\n if (!filePath || !rangesText) {\n // Skip this malformed token, continue processing others\n commands.push(this.skip(\n `[SKIPPED] Invalid finish token \"${token}\". ` +\n `Correct format: finish <path>:<start>-<end>. Example: finish src/index.ts:1-50`\n ));\n continue;\n }\n const rangeSpecs = rangesText.split(',').filter(Boolean);\n for (const spec of rangeSpecs) {\n const [s, e] = spec.split('-').map(v => parseInt(v, 10));\n if (!Number.isFinite(s) || !Number.isFinite(e) || e < s) {\n // Skip this invalid range, continue with others\n commands.push(this.skip(\n `[SKIPPED] Invalid range \"${spec}\" in \"${token}\". ` +\n `Ranges must be <start>-<end> where start <= end. Example: 1-50`\n ));\n continue;\n }\n const arr = map.get(filePath) ?? [];\n arr.push([s, e]);\n map.set(filePath, arr);\n }\n }\n return map;\n }\n}\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nexport async function toolGrep(\n provider: WarpGrepProvider,\n args: { pattern: string; path: string; glob?: string }\n): Promise<{ output: string }> {\n const res = await provider.grep(args);\n \n // Return errors as output - let the model see and handle them\n if (res.error) {\n return { output: res.error };\n }\n \n if (!res.lines.length) {\n return { output: 'no matches' };\n }\n \n return { output: res.lines.join('\\n') };\n}\n\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nexport async function toolRead(\n provider: WarpGrepProvider,\n args: { path: string; start?: number; end?: number; lines?: Array<[number, number]> }\n): Promise<string> {\n if (args.lines && args.lines.length > 0) {\n const chunks: string[] = [];\n for (const [start, end] of args.lines) {\n const res = await provider.read({ path: args.path, start, end });\n if (res.error) return res.error;\n chunks.push(res.lines.join('\\n'));\n }\n if (chunks.every(c => c === '')) return '(empty file)';\n return chunks.join('\\n...\\n');\n }\n\n const res = await provider.read({ path: args.path, start: args.start, end: args.end });\n if (res.error) {\n return res.error;\n }\n if (!res.lines.length) return '(empty file)';\n return res.lines.join('\\n');\n}\n\n","import type { WarpGrepProvider } from '../../providers/types.js';\nimport { AGENT_CONFIG } from '../config.js';\n\nexport async function toolListDirectory(\n provider: WarpGrepProvider,\n args: { path: string; pattern?: string | null; maxResults?: number; maxDepth?: number }\n): Promise<string> {\n const list = await provider.listDirectory({\n path: args.path,\n pattern: args.pattern ?? null,\n maxResults: args.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES,\n maxDepth: args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH,\n });\n \n if (!list.length) return 'empty';\n if (list.length >= AGENT_CONFIG.MAX_OUTPUT_LINES) {\n return 'query not specific enough, tool called tried to return too much context and failed';\n }\n return list\n .map((e) => {\n const indent = ' '.repeat(e.depth);\n const name = e.type === 'dir' ? `${e.name}/` : e.name;\n return `${indent}${name}`;\n })\n .join('\\n');\n}\n\n","import type { FinishFileSpec } from '../types.js';\n\nexport function normalizeFinishFiles(files: FinishFileSpec[]): FinishFileSpec[] {\n return files.map((f) => {\n const merged = mergeRanges(f.lines);\n return { path: f.path, lines: merged };\n });\n}\n\nexport async function readFinishFiles(\n repoRoot: string,\n files: FinishFileSpec[],\n reader: (path: string, start: number, end: number) => Promise<string[]>\n): Promise<{ path: string; ranges: Array<[number, number]>; content: string }[]> {\n const out: { path: string; ranges: Array<[number, number]>; content: string }[] = [];\n for (const f of files) {\n const ranges = mergeRanges(f.lines);\n const chunks: string[] = [];\n for (const [s, e] of ranges) {\n const lines = await reader(f.path, s, e);\n chunks.push(lines.join('\\n'));\n }\n out.push({ path: f.path, ranges, content: chunks.join('\\n') });\n }\n return out;\n}\n\nfunction mergeRanges(ranges: Array<[number, number]>): Array<[number, number]> {\n if (!ranges.length) return [];\n const sorted = [...ranges].sort((a, b) => a[0] - b[0]);\n const merged: Array<[number, number]> = [];\n let [cs, ce] = sorted[0];\n for (let i = 1; i < sorted.length; i++) {\n const [s, e] = sorted[i];\n if (s <= ce + 1) {\n ce = Math.max(ce, e);\n } else {\n merged.push([cs, ce]);\n cs = s;\n ce = e;\n }\n }\n merged.push([cs, ce]);\n return merged;\n}\n\n","export class ToolOutputFormatter {\n\tformat(\n\t\ttoolName: string,\n\t\targs: Record<string, unknown> | null | undefined,\n\t\toutput: string,\n\t\toptions: { isError?: boolean } = {}\n\t): string {\n\t\tconst name = (toolName ?? \"\").trim();\n\t\tif (!name) {\n\t\t\treturn \"\";\n\t\t}\n\t\tconst payload = (output as any)?.toString?.()?.trim?.() ?? \"\";\n\t\tconst isError = Boolean(options.isError);\n\t\tconst safeArgs = args ?? {};\n\n\t\tif (!payload && !isError) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\tswitch (name) {\n\t\t\tcase \"read\":\n\t\t\t\treturn this.formatRead(safeArgs, payload, isError);\n\t\t\tcase \"list_directory\":\n\t\t\t\treturn this.formatListDirectory(safeArgs, payload, isError);\n\t\t\tcase \"grep\":\n\t\t\t\treturn this.formatGrep(safeArgs, payload, isError);\n\t\t\tdefault:\n\t\t\t\treturn payload ? `<tool_output>\\n${payload}\\n</tool_output>` : \"\";\n\t\t}\n\t}\n\n\tprivate formatRead(args: Record<string, unknown>, payload: string, isError: boolean): string {\n\t\tif (isError) {\n\t\t\treturn payload;\n\t\t}\n\t\tconst path = this.asString(args.path) || \"...\";\n\t\tconst start = args.start as number | undefined;\n\t\tconst end = args.end as number | undefined;\n\t\tconst linesArray = args.lines as Array<[number, number]> | undefined;\n\t\tconst attributes: string[] = [`path=\"${path}\"`];\n\t\tif (linesArray && linesArray.length > 0) {\n\t\t\tconst rangeStr = linesArray.map(([s, e]) => `${s}-${e}`).join(',');\n\t\t\tattributes.push(`lines=\"${rangeStr}\"`);\n\t\t} else if (start !== undefined && end !== undefined) {\n\t\t\tattributes.push(`lines=\"${start}-${end}\"`);\n\t\t}\n\t\treturn `<read ${attributes.join(\" \")}>\\n${payload}\\n</read>`;\n\t}\n\n\tprivate formatListDirectory(args: Record<string, unknown>, payload: string, isError: boolean): string {\n\t\tconst path = this.asString(args.path) || \".\";\n\t\tconst pattern = this.asString(args.pattern);\n\t\tconst attributes: string[] = [`path=\"${path}\"`];\n\t\tif (pattern) {\n\t\t\tattributes.push(`pattern=\"${pattern}\"`);\n\t\t}\n\t\tif (isError) {\n\t\t\tattributes.push('status=\"error\"');\n\t\t}\n\t\treturn `<list_directory ${attributes.join(\" \")}>\\n${payload}\\n</list_directory>`;\n\t}\n\n\tprivate formatGrep(args: Record<string, unknown>, payload: string, isError: boolean): string {\n\t\tconst pattern = this.asString(args.pattern);\n\t\tconst subDir = this.asString(args.path);\n\t\tconst glob = this.asString(args.glob);\n\t\tconst attributes: string[] = [];\n\t\tif (pattern !== undefined) {\n\t\t\tattributes.push(`pattern=\"${pattern}\"`);\n\t\t}\n\t\tif (subDir !== undefined) {\n\t\t\tattributes.push(`sub_dir=\"${subDir}\"`);\n\t\t}\n\t\tif (glob !== undefined) {\n\t\t\tattributes.push(`glob=\"${glob}\"`);\n\t\t}\n\t\tif (isError) {\n\t\t\tattributes.push('status=\"error\"');\n\t\t}\n\t\tconst attrText = attributes.length ? ` ${attributes.join(\" \")}` : \"\";\n\t\treturn `<grep${attrText}>\\n${payload}\\n</grep>`;\n\t}\n\n\tprivate asString(value: unknown): string | undefined {\n\t\tif (value === null || value === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn String(value);\n\t}\n}\n\nconst sharedFormatter = new ToolOutputFormatter();\n\nexport function formatAgentToolOutput(\n\ttoolName: string,\n\targs: Record<string, unknown> | null | undefined,\n\toutput: string,\n\toptions: { isError?: boolean } = {}\n): string {\n\treturn sharedFormatter.format(toolName, args, output, options);\n}\n\n","/**\n * Shared helper functions for warp-grep agent loop.\n * Used by both the internal runner and exported for harness users.\n */\n\nimport path from 'path';\nimport { AGENT_CONFIG } from './config.js';\nimport type { ChatMessage } from './types.js';\nimport type { WarpGrepProvider, ListDirectoryEntry } from '../providers/types.js';\n\nconst TRUNCATED_MARKER = '[truncated for context limit]';\n\n/**\n * Format the turn counter message shown to the model.\n */\nexport function formatTurnMessage(turnsUsed: number, maxTurns: number): string {\n const turnsRemaining = maxTurns - turnsUsed;\n if (turnsRemaining === 1) {\n return `\\nYou have used ${turnsUsed} turns, you only have 1 turn remaining. You have run out of turns to explore the code base and MUST call the finish tool now`;\n }\n return `\\nYou have used ${turnsUsed} turn${turnsUsed === 1 ? '' : 's'} and have ${turnsRemaining} remaining`;\n}\n\n/**\n * Calculate and format the context budget indicator.\n */\nexport function calculateContextBudget(messages: ChatMessage[]): string {\n const totalChars = messages.reduce((sum, m) => sum + m.content.length, 0);\n const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;\n const percent = Math.round((totalChars / maxChars) * 100);\n const usedK = Math.round(totalChars / 1000);\n const maxK = Math.round(maxChars / 1000);\n return `<context_budget>${percent}% (${usedK}K/${maxK}K chars)</context_budget>`;\n}\n\n/**\n * Build the initial state message containing repo structure and query.\n */\nexport async function buildInitialState(\n repoRoot: string,\n query: string,\n provider: WarpGrepProvider\n): Promise<string> {\n try {\n const entries = await provider.listDirectory({\n path: '.',\n maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,\n maxDepth: 2,\n });\n const treeLines = entries.map((e) => {\n const indent = ' '.repeat(e.depth);\n const name = e.type === 'dir' ? `${e.name}/` : e.name;\n return `${indent}${name}`;\n });\n\n const repoName = path.basename(repoRoot);\n const treeOutput =\n treeLines.length > 0 ? `${repoName}/\\n${treeLines.join('\\n')}` : `${repoName}/`;\n\n return `<repo_structure>\\n${treeOutput}\\n</repo_structure>\\n\\n<search_string>\\n${query}\\n</search_string>`;\n } catch {\n const repoName = path.basename(repoRoot);\n return `<repo_structure>\\n${repoName}/\\n</repo_structure>\\n\\n<search_string>\\n${query}\\n</search_string>`;\n }\n}\n\n/**\n * Format directory entries as an indented tree string.\n */\nexport function formatListDirectoryTree(entries: ListDirectoryEntry[]): string {\n if (!entries.length) return 'empty';\n return entries\n .map((e) => {\n const indent = ' '.repeat(e.depth);\n const name = e.type === 'dir' ? `${e.name}/` : e.name;\n return `${indent}${name}`;\n })\n .join('\\n');\n}\n\n/**\n * Enforce hard context limit by truncating user messages.\n * Preserves system prompt, first user message (initial query), and all assistant messages.\n * Removes tool result user messages from oldest to newest until under the threshold.\n * \n * @param messages - The conversation messages array (mutated in place)\n * @param maxChars - Maximum total character count (defaults to AGENT_CONFIG.MAX_CONTEXT_CHARS)\n * @returns The same messages array, truncated if necessary\n */\nexport function enforceContextLimit(\n messages: ChatMessage[],\n maxChars: number = AGENT_CONFIG.MAX_CONTEXT_CHARS\n): ChatMessage[] {\n const getTotalChars = () => messages.reduce((sum, m) => sum + m.content.length, 0);\n \n if (getTotalChars() <= maxChars) {\n return messages;\n }\n\n // Find indices of user messages, skipping the first one (initial query with repo structure)\n // We truncate tool result messages from oldest to newest\n const userIndices: number[] = [];\n let firstUserSkipped = false;\n for (let i = 0; i < messages.length; i++) {\n if (messages[i].role === 'user') {\n if (!firstUserSkipped) {\n firstUserSkipped = true;\n continue; // Skip first user message (contains the search query)\n }\n userIndices.push(i);\n }\n }\n\n // Truncate user messages from oldest to newest until under limit\n for (const idx of userIndices) {\n if (getTotalChars() <= maxChars) {\n break;\n }\n // Only truncate if not already truncated\n if (messages[idx].content !== TRUNCATED_MARKER) {\n messages[idx] = { role: 'user', content: TRUNCATED_MARKER };\n }\n }\n\n return messages;\n}\n\n","import { AGENT_CONFIG, DEFAULT_MODEL } from './config.js';\nimport { getSystemPrompt } from './prompt.js';\nimport type { AgentRunResult, ChatMessage, SessionConfig, AgentFinish } from './types.js';\nimport { LLMResponseParser } from './parser.js';\nimport type { WarpGrepProvider } from '../providers/types.js';\nimport { toolGrep } from './tools/grep.js';\nimport { toolRead } from './tools/read.js';\nimport { toolListDirectory } from './tools/list_directory.js';\nimport { readFinishFiles } from './tools/finish.js';\nimport { fetchWithRetry, withTimeout, type RetryConfig } from '../../utils/resilience.js';\nimport { formatAgentToolOutput } from './formatter.js';\nimport { formatTurnMessage, calculateContextBudget, buildInitialState, enforceContextLimit } from './helpers.js';\nimport path from 'path';\n\ntype EventName =\n | 'initial_state'\n | 'round_start'\n | 'round_end'\n | 'finish'\n | 'error';\n\nexport type EventCallback = (name: EventName, payload: Record<string, unknown>) => void;\n\nconst parser = new LLMResponseParser();\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\n\ninterface CallModelOptions {\n morphApiKey?: string;\n morphApiUrl?: string;\n retryConfig?: RetryConfig;\n}\n\nasync function callModel(\n messages: ChatMessage[],\n model: string,\n options: CallModelOptions = {}\n): Promise<string> {\n const baseUrl = DEFAULT_API_URL;\n const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || '';\n \n const fetchPromise = fetchWithRetry(\n `${baseUrl}/v1/chat/completions`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model,\n temperature: 0.0,\n max_tokens: 1024,\n messages,\n }),\n },\n options.retryConfig\n );\n const resp = await withTimeout(fetchPromise, AGENT_CONFIG.TIMEOUT_MS, 'morph-warp-grep request timed out');\n if (!resp.ok) {\n if (resp.status === 404) {\n throw new Error(\n 'The endpoint you are trying to call is likely deprecated. Please update with: npm cache clean --force && npx -y @morphllm/morphmcp@latest or visit: https://morphllm.com/mcp'\n );\n }\n // keeping these cases are real throws, if this happens retry will likely not help, so best we just throw here, notice the error and fix\n const t = await resp.text();\n throw new Error(`morph-warp-grep error ${resp.status}: ${t}`);\n }\n const data = await resp.json();\n const content = data?.choices?.[0]?.message?.content;\n if (!content || typeof content !== 'string') {\n throw new Error('Invalid response from model');\n }\n return content;\n}\n\nexport async function runWarpGrep(config: SessionConfig & { provider: WarpGrepProvider }): Promise<AgentRunResult> {\n const repoRoot = path.resolve(config.repoRoot || process.cwd());\n const messages: ChatMessage[] = [];\n\n messages.push({ role: 'system' as const, content: getSystemPrompt() });\n const initialState = await buildInitialState(repoRoot, config.query, config.provider);\n messages.push({ role: 'user', content: initialState });\n\n const maxTurns = AGENT_CONFIG.MAX_TURNS;\n const model = config.model || DEFAULT_MODEL;\n const provider = config.provider;\n const errors: Array<{ message: string }> = [];\n\n let finishMeta: AgentFinish | undefined;\n let terminationReason: AgentRunResult['terminationReason'] = 'terminated';\n\n for (let turn = 1; turn <= maxTurns; turn += 1) {\n // Enforce hard context limit before calling model\n enforceContextLimit(messages);\n \n // call model\n const assistantContent = await callModel(messages, model, {\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n }).catch((e: unknown) => {\n errors.push({ message: e instanceof Error ? e.message : String(e) });\n return '';\n });\n if (!assistantContent) break;\n messages.push({ role: 'assistant', content: assistantContent });\n\n // parse tool calls (no longer throws - returns _skip calls for malformed commands)\n const toolCalls = parser.parse(assistantContent);\n if (toolCalls.length === 0) {\n errors.push({ message: 'No tool calls produced by the model. Your MCP is likely out of date! Update it by running: npm cache clean --force && npx -y @morphllm/morphmcp@latest' });\n terminationReason = 'terminated';\n break;\n }\n\n const finishCalls = toolCalls.filter(c => c.name === 'finish');\n const grepCalls = toolCalls.filter(c => c.name === 'grep');\n const listDirCalls = toolCalls.filter(c => c.name === 'list_directory');\n const readCalls = toolCalls.filter(c => c.name === 'read');\n const skipCalls = toolCalls.filter(c => c.name === '_skip');\n\n const formatted: string[] = [];\n\n // Surface any skipped commands as feedback to the LLM\n for (const c of skipCalls) {\n const msg = (c.arguments as { message?: string })?.message || 'Command skipped due to parsing error';\n formatted.push(msg);\n }\n\n const allPromises: Array<Promise<string>> = [];\n \n for (const c of grepCalls) {\n const args = (c.arguments ?? {}) as { pattern: string; path: string; glob?: string };\n allPromises.push(\n toolGrep(provider, args).then(\n ({ output }) => formatAgentToolOutput('grep', args, output, { isError: false }),\n err => formatAgentToolOutput('grep', args, String(err), { isError: true })\n )\n );\n }\n \n for (const c of listDirCalls) {\n const args = (c.arguments ?? {}) as { path: string; pattern?: string | null };\n allPromises.push(\n toolListDirectory(provider, args).then(\n p => formatAgentToolOutput('list_directory', args, p, { isError: false }),\n err => formatAgentToolOutput('list_directory', args, String(err), { isError: true })\n )\n );\n }\n \n for (const c of readCalls) {\n const args = (c.arguments ?? {}) as { path: string; start?: number; end?: number; lines?: Array<[number, number]> };\n allPromises.push(\n toolRead(provider, args).then(\n p => formatAgentToolOutput('read', args, p, { isError: false }),\n err => formatAgentToolOutput('read', args, String(err), { isError: true })\n )\n );\n }\n \n const allResults = await Promise.all(allPromises);\n for (const result of allResults) {\n formatted.push(result);\n }\n\n if (formatted.length > 0) {\n const turnMessage = formatTurnMessage(turn, maxTurns);\n const contextBudget = calculateContextBudget(messages);\n messages.push({ role: 'user', content: formatted.join('\\n') + turnMessage + '\\n' + contextBudget });\n }\n\n if (finishCalls.length) {\n const fc = finishCalls[0];\n const files = ((fc.arguments as any)?.files ?? []) as AgentFinish['files'];\n finishMeta = { files };\n terminationReason = 'completed';\n break;\n }\n }\n\n if (terminationReason !== 'completed' || !finishMeta) {\n return { terminationReason, messages, errors };\n }\n\n // Build finish payload\n const parts: string[] = ['Relevant context found:'];\n for (const f of finishMeta.files) {\n const ranges = f.lines.map(([s, e]) => `${s}-${e}`).join(', ');\n parts.push(`- ${f.path}: ${ranges}`);\n }\n const payload = parts.join('\\n');\n\n // Resolve file contents for returned ranges\n // Wrap reader in try-catch to handle non-existent or unreadable files gracefully\n // Track files that couldn't be read for error reporting\n const fileReadErrors: Array<{ path: string; error: string }> = [];\n const resolved = await readFinishFiles(\n repoRoot,\n finishMeta.files,\n async (p: string, s: number, e: number) => {\n try {\n const rr = await provider.read({ path: p, start: s, end: e });\n // rr.lines are \"line|content\" → strip the \"line|\" prefix\n return rr.lines.map(l => {\n const idx = l.indexOf('|');\n return idx >= 0 ? l.slice(idx + 1) : l;\n });\n } catch (err) {\n // File doesn't exist or can't be read - log error but don't throw\n // This handles cases where the agent hallucinated a path or the file was deleted\n const errorMsg = err instanceof Error ? err.message : String(err);\n fileReadErrors.push({ path: p, error: errorMsg });\n console.error(`[warp_grep] Failed to read file: ${p} - ${errorMsg}`);\n return [`[couldn't find: ${p}]`];\n }\n }\n );\n\n // Add file read errors to the result so MCP can report them\n if (fileReadErrors.length > 0) {\n errors.push(...fileReadErrors.map(e => ({ message: `File read error: ${e.path} - ${e.error}` })));\n }\n\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: finishMeta, resolved },\n };\n}\n","import fs from 'fs/promises';\nimport fssync from 'fs';\nimport path from 'path';\nimport { runRipgrep } from '../utils/ripgrep.js';\nimport { ensureWithinRepo, resolveUnderRepo, toRepoRelative, isSymlink, isTextualFile } from '../utils/paths.js';\nimport type { WarpGrepProvider, GrepResult, ReadResult, ListDirectoryEntry } from './types.js';\nimport { readAllLines } from '../utils/files.js';\nimport { DEFAULT_EXCLUDES, AGENT_CONFIG } from '../agent/config.js';\n\nexport class LocalRipgrepProvider implements WarpGrepProvider {\n constructor(private readonly repoRoot: string, private readonly excludes: string[] = DEFAULT_EXCLUDES) {}\n\n async grep(params: { pattern: string; path: string; glob?: string }): Promise<GrepResult> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch (err) {\n return {\n lines: [],\n error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat) return { lines: [] };\n const targetArg = abs === path.resolve(this.repoRoot) ? '.' : toRepoRelative(this.repoRoot, abs);\n const args = [\n '--no-config',\n '--no-heading',\n '--with-filename',\n '--line-number',\n '--color=never',\n '--trim',\n '--max-columns=400',\n '-C', '1',\n ...(params.glob ? ['--glob', params.glob] : []),\n ...this.excludes.flatMap((e) => ['-g', `!${e}`]),\n params.pattern,\n targetArg || '.',\n ];\n const res = await runRipgrep(args, { cwd: this.repoRoot });\n \n // Gracefully handle ripgrep not being available\n if (res.exitCode === -1) {\n return {\n lines: [],\n error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required but failed to execute. Please install it:\\n` +\n ` • macOS: brew install ripgrep\\n` +\n ` • Ubuntu/Debian: apt install ripgrep\\n` +\n ` • Windows: choco install ripgrep\\n` +\n ` • Or visit: https://github.com/BurntSushi/ripgrep#installation\\n` +\n `Exit code: ${res.exitCode}${res.stderr ? `\\nDetails: ${res.stderr}` : ''}`,\n };\n }\n \n // Handle other ripgrep errors gracefully\n if (res.exitCode !== 0 && res.exitCode !== 1) {\n return {\n lines: [],\n error: `[RIPGREP ERROR] grep failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ''}`,\n };\n }\n \n const lines = (res.stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((l) => l.length > 0);\n if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {\n return {\n lines: [],\n error: 'query not specific enough, tool tried to return too much context and failed',\n };\n }\n \n return { lines };\n }\n\n async read(params: { path: string; start?: number; end?: number }): Promise<ReadResult> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch (err) {\n return {\n lines: [],\n error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n const stat = await fs.stat(abs).catch(() => null);\n \n // Gracefully handle file not found / not a file\n if (!stat || !stat.isFile()) {\n return {\n lines: [],\n error: `[FILE NOT FOUND] You tried to read \"${params.path}\" but there is no file at this path. ` +\n `Double-check the path exists and is spelled correctly.`,\n };\n }\n \n // Gracefully handle symlinks\n if (isSymlink(abs)) {\n return {\n lines: [],\n error: `[SYMLINK] You tried to read \"${params.path}\" but this is a symlink. ` +\n `Try reading the actual file it points to instead.`,\n };\n }\n \n // Gracefully handle non-text or too-large files\n if (!isTextualFile(abs)) {\n return {\n lines: [],\n error: `[UNREADABLE FILE] You tried to read \"${params.path}\" but this file is either too large ` +\n `or not a text file, so it cannot be read. Try a different file.`,\n };\n }\n \n let lines: string[];\n try {\n lines = await readAllLines(abs);\n } catch (err) {\n return {\n lines: [],\n error: `[READ ERROR] Failed to read \"${params.path}\": ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n const total = lines.length;\n let s = params.start ?? 1;\n let e = Math.min(params.end ?? total, total);\n if (s > total && total > 0) {\n // Model hallucinated range - fallback to full file\n s = 1;\n e = total;\n }\n const out: string[] = [];\n for (let i = s; i <= e; i += 1) {\n const content = lines[i - 1] ?? '';\n out.push(`${i}|${content}`);\n }\n if (out.length > AGENT_CONFIG.MAX_READ_LINES) {\n const truncated = out.slice(0, AGENT_CONFIG.MAX_READ_LINES);\n truncated.push(`... [truncated: showing ${AGENT_CONFIG.MAX_READ_LINES} of ${out.length} lines]`);\n return { lines: truncated };\n }\n \n return { lines: out };\n }\n\n async listDirectory(params: { path: string; pattern?: string | null; maxResults?: number; maxDepth?: number }): Promise<ListDirectoryEntry[]> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch {\n // Path outside repo - return empty (graceful failure)\n return [];\n }\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat || !stat.isDirectory()) {\n return [];\n }\n const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;\n const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n const regex = params.pattern ? new RegExp(params.pattern) : null;\n\n const results: ListDirectoryEntry[] = [];\n let timedOut = false;\n const startTime = Date.now();\n \n async function walk(dir: string, depth: number) {\n if (Date.now() - startTime > AGENT_CONFIG.LIST_TIMEOUT_MS) {\n timedOut = true;\n return;\n }\n if (depth > maxDepth || results.length >= maxResults) return;\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (timedOut || results.length >= maxResults) break;\n const full = path.join(dir, entry.name);\n const rel = toRepoRelative(abs, full).replace(/^[.][/\\\\]?/, '');\n if (DEFAULT_EXCLUDES.some((ex) => rel.split(path.sep).includes(ex))) continue;\n if (regex && !regex.test(entry.name)) continue;\n results.push({\n name: entry.name,\n path: toRepoRelative(path.resolve(''), full), // relative display\n type: entry.isDirectory() ? 'dir' : 'file',\n depth,\n });\n if (entry.isDirectory()) {\n await walk(full, depth + 1);\n }\n }\n }\n await walk(abs, 0);\n return results;\n }\n}\n\n\n","import { spawn } from 'child_process';\nimport { rgPath } from '@vscode/ripgrep';\n\nexport type ExecResult = { stdout: string; stderr: string; exitCode: number };\n\n// Cache the working ripgrep path to avoid repeated fallback checks\nlet resolvedRgPath: string | null = null;\nlet rgPathChecked = false;\n\nfunction spawnRg(rgBinary: string, args: string[], opts?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult> {\n return new Promise((resolve) => {\n const child = spawn(rgBinary, args, {\n cwd: opts?.cwd,\n env: { ...process.env, ...(opts?.env || {}) },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (d) => (stdout += d.toString()));\n child.stderr.on('data', (d) => (stderr += d.toString()));\n child.on('close', (code) => {\n resolve({ stdout, stderr, exitCode: typeof code === 'number' ? code : -1 });\n });\n child.on('error', () => {\n resolve({ stdout: '', stderr: 'Failed to spawn ripgrep.', exitCode: -1 });\n });\n });\n}\n\n// Check if a result indicates a binary compatibility failure (not a normal rg error)\nfunction isBinaryFailure(result: ExecResult): boolean {\n // Spawn error\n if (result.exitCode === -1) return true;\n // jemalloc page size issue (common on ARM64 with non-standard page sizes)\n if (result.stderr.includes('jemalloc') || result.stderr.includes('Unsupported system page size')) return true;\n // SIGABRT (134 = 128 + 6)\n if (result.exitCode === 134) return true;\n return false;\n}\n\nexport async function runRipgrep(args: string[], opts?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult> {\n // If we've already determined the working path, use it\n if (rgPathChecked && resolvedRgPath) {\n return spawnRg(resolvedRgPath, args, opts);\n }\n\n // First attempt: bundled ripgrep\n if (!rgPathChecked) {\n const result = await spawnRg(rgPath, args, opts);\n \n if (!isBinaryFailure(result)) {\n // Bundled binary works, cache it\n resolvedRgPath = rgPath;\n rgPathChecked = true;\n return result;\n }\n\n // Bundled binary failed, try system rg\n const fallbackResult = await spawnRg('rg', args, opts);\n \n if (!isBinaryFailure(fallbackResult)) {\n // System rg works, cache it\n resolvedRgPath = 'rg';\n rgPathChecked = true;\n return fallbackResult;\n }\n\n // Neither works, mark as checked and return the original error\n rgPathChecked = true;\n return { \n stdout: '', \n stderr: 'Failed to spawn ripgrep. Neither bundled nor system rg is available.', \n exitCode: -1 \n };\n }\n\n // rgPathChecked is true but resolvedRgPath is null - no working rg found\n return { \n stdout: '', \n stderr: 'Failed to spawn ripgrep. Neither bundled nor system rg is available.', \n exitCode: -1 \n };\n}\n\n\n","import fs from 'fs';\nimport path from 'path';\n\nexport function resolveUnderRepo(repoRoot: string, targetPath: string): string {\n const absRoot = path.resolve(repoRoot);\n const resolved = path.resolve(absRoot, targetPath);\n ensureWithinRepo(absRoot, resolved);\n return resolved;\n}\n\nexport function ensureWithinRepo(repoRoot: string, absTarget: string): void {\n const rel = path.relative(path.resolve(repoRoot), path.resolve(absTarget));\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path outside repository root: ${absTarget}`);\n }\n}\n\nexport function toRepoRelative(repoRoot: string, absPath: string): string {\n return path.relative(path.resolve(repoRoot), path.resolve(absPath));\n}\n\nexport function isSymlink(p: string): boolean {\n try {\n const st = fs.lstatSync(p);\n return st.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport function isTextualFile(filePath: string, maxBytes = 2_000_000): boolean {\n try {\n const st = fs.statSync(filePath);\n if (!st.isFile()) return false;\n if (st.size > maxBytes) return false;\n const fd = fs.openSync(filePath, 'r');\n const buf = Buffer.alloc(512);\n const read = fs.readSync(fd, buf, 0, buf.length, 0);\n fs.closeSync(fd);\n for (let i = 0; i < read; i++) {\n const c = buf[i];\n if (c === 0) return false; // binary heuristic\n }\n return true;\n } catch {\n return false;\n }\n}\n\n\n","import fs from 'fs/promises';\n\nexport async function readAllLines(filePath: string): Promise<string[]> {\n const content = await fs.readFile(filePath, 'utf8');\n // Preserve newlines; split keeping consistency\n return content.split(/\\r?\\n/);\n}\n\n\n","/**\n * RemoteCommandsProvider - wraps simple RemoteCommands into WarpGrepProvider\n * \n * Handles parsing of raw stdout from grep/read/listDir commands.\n * Users just return stdout, SDK handles all format conversion.\n */\n\nimport type { WarpGrepProvider, GrepResult, ReadResult, ListDirectoryEntry } from './types.js';\nimport type { RemoteCommands } from '../types.js';\nimport { AGENT_CONFIG } from '../agent/config.js';\n\n/**\n * Wraps simple RemoteCommands functions into a full WarpGrepProvider.\n * \n * This allows users to provide three simple functions that return raw stdout,\n * and the SDK handles all parsing internally.\n * \n * @example\n * ```typescript\n * const provider = new RemoteCommandsProvider('/home/repo', {\n * grep: async (pattern, path) => {\n * const r = await sandbox.run(`rg '${pattern}' '${path}'`);\n * return r.stdout;\n * },\n * read: async (path, start, end) => {\n * const r = await sandbox.run(`sed -n '${start},${end}p' '${path}'`);\n * return r.stdout;\n * },\n * listDir: async (path, maxDepth) => {\n * const r = await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`);\n * return r.stdout;\n * },\n * });\n * ```\n */\nexport class RemoteCommandsProvider implements WarpGrepProvider {\n constructor(\n private readonly repoRoot: string,\n private readonly commands: RemoteCommands\n ) {}\n\n /**\n * Run grep command and parse ripgrep output\n */\n async grep(params: { pattern: string; path: string; glob?: string }): Promise<GrepResult> {\n try {\n const stdout = await this.commands.grep(params.pattern, params.path, params.glob);\n \n // Parse ripgrep output: each line is \"path:line:content\" or \"path-line-content\" for context\n const lines = (stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((l) => l.length > 0);\n \n // Check if output is too large\n if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {\n return {\n lines: [],\n error: 'Query not specific enough - too many results returned. Try a more specific pattern.',\n };\n }\n \n return { lines };\n } catch (error) {\n return {\n lines: [],\n error: `[GREP ERROR] ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Read file and add line numbers\n */\n async read(params: { path: string; start?: number; end?: number }): Promise<ReadResult> {\n const start = params.start ?? 1;\n const end = params.end ?? 1_000_000;\n \n try {\n const stdout = await this.commands.read(params.path, start, end);\n \n // Split content into lines and add line numbers\n const contentLines = (stdout || '').split('\\n');\n \n // Remove trailing empty line if present (common with sed output)\n if (contentLines.length > 0 && contentLines[contentLines.length - 1] === '') {\n contentLines.pop();\n }\n \n // Format as \"lineNumber|content\"\n const lines = contentLines.map((content, idx) => `${start + idx}|${content}`);\n \n // Check if output is too large\n if (lines.length > AGENT_CONFIG.MAX_READ_LINES) {\n const truncated = lines.slice(0, AGENT_CONFIG.MAX_READ_LINES);\n truncated.push(`... [truncated: showing ${AGENT_CONFIG.MAX_READ_LINES} of ${lines.length} lines]`);\n return { lines: truncated };\n }\n \n return { lines };\n } catch (error) {\n return {\n lines: [],\n error: `[READ ERROR] ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * List directory and parse find output\n */\n async listDirectory(params: { \n path: string; \n pattern?: string | null; \n maxResults?: number; \n maxDepth?: number;\n }): Promise<ListDirectoryEntry[]> {\n const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;\n \n try {\n const stdout = await this.commands.listDir(params.path, maxDepth);\n \n // Parse find output: one path per line\n const paths = (stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((p) => p.length > 0);\n \n const regex = params.pattern ? new RegExp(params.pattern) : null;\n const entries: ListDirectoryEntry[] = [];\n \n for (const fullPath of paths) {\n // Skip the root path itself\n if (fullPath === params.path || fullPath === this.repoRoot) continue;\n \n const name = fullPath.split('/').pop() || '';\n \n // Apply pattern filter if provided\n if (regex && !regex.test(name)) continue;\n \n // Determine relative path\n let relativePath = fullPath;\n if (fullPath.startsWith(this.repoRoot)) {\n relativePath = fullPath.slice(this.repoRoot.length).replace(/^\\//, '');\n }\n \n // Calculate depth based on path separators\n const depth = relativePath.split('/').filter(Boolean).length - 1;\n \n // Determine if it's a directory (ends with / or infer from path structure)\n // Note: Most sandbox find commands don't indicate type, so we guess based on extension\n const hasExtension = name.includes('.') && !name.startsWith('.');\n const type: 'file' | 'dir' = hasExtension ? 'file' : 'dir';\n \n entries.push({\n name,\n path: relativePath,\n type,\n depth: Math.max(0, depth),\n });\n \n if (entries.length >= maxResults) break;\n }\n \n return entries;\n } catch (error) {\n // Return empty array on error (consistent with LocalRipgrepProvider)\n return [];\n }\n }\n}\n\n","/**\n * WarpGrep client for programmatic code search\n */\n\nimport { runWarpGrep } from './agent/runner.js';\nimport { LocalRipgrepProvider } from './providers/local.js';\nimport { RemoteCommandsProvider } from './providers/remote.js';\nimport type { \n WarpGrepClientConfig, \n WarpGrepInput, \n WarpGrepResult,\n WarpGrepContext,\n WarpGrepToolConfig,\n} from './types.js';\n\n/**\n * WarpGrep client for programmatic code search\n * \n * @example\n * ```typescript\n * import { WarpGrepClient } from '@morphllm/morphsdk';\n * \n * const client = new WarpGrepClient({ morphApiKey: process.env.MORPH_API_KEY });\n * \n * // Simple usage - defaults to LocalRipgrepProvider\n * const result = await client.execute({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * \n * // With custom excludes\n * const result = await client.execute({\n * query: 'Find database models',\n * repoRoot: '.',\n * excludes: ['node_modules', '.git', 'dist']\n * });\n * ```\n */\nexport class WarpGrepClient {\n private config: WarpGrepClientConfig;\n\n constructor(config: WarpGrepClientConfig = {}) {\n this.config = {\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Execute a code search query\n * \n * @param input - Search parameters including query, repoRoot, and optional provider\n * @returns Search results with relevant code contexts\n * \n * @example\n * ```typescript\n * const result = await client.execute({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * \n * if (result.success) {\n * for (const ctx of result.contexts) {\n * console.log(`File: ${ctx.file}`);\n * console.log(ctx.content);\n * }\n * }\n * ```\n */\n async execute(input: WarpGrepInput): Promise<WarpGrepResult> {\n return executeToolCall(\n { query: input.query },\n {\n repoRoot: input.repoRoot,\n remoteCommands: input.remoteCommands,\n provider: input.provider,\n excludes: input.excludes,\n includes: input.includes,\n debug: input.debug ?? this.config.debug,\n morphApiKey: this.config.morphApiKey,\n morphApiUrl: this.config.morphApiUrl,\n retryConfig: this.config.retryConfig,\n }\n );\n }\n}\n\n/**\n * Execute a warp grep search directly\n * \n * @param input - Search parameters\n * @param config - Optional client configuration\n * @returns Search results\n * \n * @example\n * ```typescript\n * import { executeWarpGrep } from '@morphllm/morphsdk/tools/warp-grep';\n * \n * const result = await executeWarpGrep({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * ```\n */\nexport async function executeWarpGrep(\n input: WarpGrepInput,\n config?: WarpGrepClientConfig\n): Promise<WarpGrepResult> {\n const client = new WarpGrepClient(config);\n return client.execute(input);\n}\n\nexport async function executeToolCall(\n input: { query: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n const parsed = typeof input === 'string' ? JSON.parse(input) : input;\n \n // Priority: remoteCommands > provider > LocalRipgrepProvider\n const provider = config.remoteCommands\n ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands)\n : config.provider ?? new LocalRipgrepProvider(config.repoRoot, config.excludes);\n \n const result = await runWarpGrep({\n query: parsed.query,\n repoRoot: config.repoRoot,\n provider,\n excludes: config.excludes,\n includes: config.includes,\n debug: config.debug ?? false,\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n });\n\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n return { success: false, error: 'Search did not complete' };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n }));\n\n return { success: true, contexts, summary: finish.payload };\n}\n\n/**\n * Format warp grep results for display or tool responses\n * \n * @param result - The search result\n * @returns Formatted string representation\n */\nexport function formatResult(result: WarpGrepResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (!result.contexts || result.contexts.length === 0) {\n return 'No relevant code found. Try rephrasing your query.';\n }\n\n const lines: string[] = [];\n lines.push(`Found ${result.contexts.length} relevant code sections:\\n`);\n\n result.contexts.forEach((ctx, i) => {\n lines.push(`${i + 1}. ${ctx.file}`);\n lines.push('```');\n lines.push(ctx.content);\n lines.push('```');\n lines.push('');\n });\n\n if (result.summary) {\n lines.push(`Summary: ${result.summary}`);\n }\n\n return lines.join('\\n');\n}\n\n","/**\n * Morph Git Client - Simple, high-level Git operations\n * Built on isomorphic-git with explicit configuration\n */\n\nimport git from 'isomorphic-git';\nimport http from 'isomorphic-git/http/node';\nimport fs from 'fs';\nimport type {\n CloneOptions,\n PushOptions,\n PullOptions,\n AddOptions,\n CommitOptions,\n StatusOptions,\n LogOptions,\n CheckoutOptions,\n BranchOptions,\n DiffOptions,\n CommitObject,\n StatusResult,\n MorphGitConfig,\n MorphNotesSchema,\n WaitForEmbeddingsOptions,\n EmbeddingProgress,\n} from './types.js';\n\nconst DEFAULT_PROXY_URL = 'https://repos.morphllm.com';\n\n/**\n * MorphGit - Git operations for AI agents with Morph backend\n * \n * @example\n * ```typescript\n * import { MorphGit } from 'morphsdk/git';\n * \n * const morphGit = new MorphGit({\n * apiKey: process.env.MORPH_API_KEY!,\n * proxyUrl: 'https://repos.morphllm.com' // Optional\n * });\n * \n * await morphGit.init({ repoId: 'my-project', dir: './my-project' });\n * await morphGit.push({ dir: './my-project' });\n * ```\n */\nexport class MorphGit {\n private readonly apiKey: string;\n private readonly proxyUrl: string;\n\n constructor(config: MorphGitConfig) {\n // Validate API key\n if (!config.apiKey) {\n throw new Error('API key is required. Get one at https://morphllm.com/dashboard');\n }\n \n if (!config.apiKey.startsWith('sk-') && !config.apiKey.startsWith('morph-')) {\n throw new Error('Invalid API key format. Expected: sk-... or morph-...');\n }\n \n this.apiKey = config.apiKey;\n this.proxyUrl = config.proxyUrl || DEFAULT_PROXY_URL;\n }\n \n /**\n * Get auth callback for isomorphic-git operations\n * @private\n */\n private getAuthCallback() {\n return () => ({\n username: 'morph',\n password: this.apiKey,\n });\n }\n\n /**\n * Initialize a new repository\n * Creates the repo in the database and in the git provider\n * \n * @example\n * ```ts\n * await morphGit.init({\n * repoId: 'my-project',\n * dir: './my-project',\n * defaultBranch: 'main'\n * });\n * ```\n */\n async init(options: {\n repoId: string;\n dir: string;\n defaultBranch?: string;\n }): Promise<void> {\n const { repoId, dir, defaultBranch = 'main' } = options;\n\n // Call backend API to create repository\n const response = await fetch(`${this.proxyUrl}/v1/repos`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n repoId,\n name: repoId,\n defaultBranch,\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Failed to create repository: ${error}`);\n }\n\n // Initialize local git repository (industry standard: no clone needed)\n await git.init({\n fs,\n dir,\n defaultBranch,\n });\n\n // Add remote pointing to Morph git-proxy\n await git.addRemote({\n fs,\n dir,\n remote: 'origin',\n url: `${this.proxyUrl}/v1/repos/${repoId}`,\n });\n\n console.log(`✓ Repository '${repoId}' initialized`);\n }\n\n /**\n * Clone a repository from Morph repos\n * \n * @example\n * ```ts\n * await morphGit.clone({\n * repoId: 'my-project',\n * dir: './my-project'\n * });\n * ```\n */\n async clone(options: CloneOptions): Promise<void> {\n const { repoId, dir, branch = 'main', depth, singleBranch = true } = options;\n\n await git.clone({\n fs,\n http,\n dir,\n url: `${this.proxyUrl}/v1/repos/${repoId}`,\n ref: branch,\n singleBranch,\n depth,\n onAuth: this.getAuthCallback(),\n });\n }\n\n /**\n * Push changes to remote repository\n * \n * @example\n * ```ts\n * await morphGit.push({ \n * dir: './my-project',\n * branch: 'main', // Required: explicit branch name\n * index: true // Optional: generate embeddings for semantic search\n * });\n * ```\n */\n async push(options: PushOptions): Promise<void> {\n const { dir, remote = 'origin', branch, waitForEmbeddings, index = false } = options;\n\n if (!branch) {\n throw new Error(\n 'branch is required for push operations. ' +\n 'Specify the branch explicitly: { dir: \"./my-project\", branch: \"main\" }'\n );\n }\n\n // Get commit hash and repoId before pushing\n const commitHash = await git.resolveRef({ fs, dir, ref: 'HEAD' });\n \n // Get repoId from git remote URL\n let repoId: string | undefined;\n const remotes = await git.listRemotes({ fs, dir });\n const originRemote = remotes.find(r => r.remote === remote);\n if (originRemote) {\n // Extract repoId from URL: https://repos.morphllm.com/v1/repos/{repoId}\n const match = originRemote.url.match(/\\/repos\\/([^\\/]+)$/);\n if (match) {\n repoId = match[1];\n }\n }\n\n await git.push({\n fs,\n http,\n dir,\n remote,\n ref: branch,\n onAuth: this.getAuthCallback(),\n });\n \n // Configure commit after successful push (set index flag)\n if (repoId && commitHash) {\n await this.configureCommit({ repoId, commitHash, branch, index });\n }\n \n // Wait for embeddings if requested (and indexing is enabled)\n if (waitForEmbeddings && repoId && commitHash && index) {\n await this.waitForEmbeddings({ repoId, commitHash });\n }\n }\n\n /**\n * Configure commit settings on the backend after push.\n * Sets the index flag to control embedding generation.\n * @private\n */\n private async configureCommit(options: {\n repoId: string;\n commitHash: string;\n branch: string;\n index: boolean;\n }): Promise<void> {\n const { repoId, commitHash, branch, index } = options;\n \n const response = await fetch(\n `${this.proxyUrl}/v1/repos/${repoId}/commits/${commitHash}/config`,\n {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ index, branch }),\n }\n );\n\n if (!response.ok) {\n // Non-fatal: log warning but don't throw\n console.warn(`Failed to configure commit: ${response.status}`);\n }\n }\n\n /**\n * Pull changes from remote repository\n * \n * @example\n * ```ts\n * await morphGit.pull({ \n * dir: './my-project',\n * branch: 'main' // Required: explicit branch name\n * });\n * ```\n */\n async pull(options: PullOptions): Promise<void> {\n const { dir, remote = 'origin', branch } = options;\n\n if (!branch) {\n throw new Error(\n 'branch is required for pull operations. ' +\n 'Specify the branch explicitly: { dir: \"./my-project\", branch: \"main\" }'\n );\n }\n\n await git.pull({\n fs,\n http,\n dir,\n remote,\n ref: branch,\n onAuth: this.getAuthCallback(),\n author: {\n name: 'Morph Agent',\n email: 'agent@morph.com',\n },\n });\n }\n\n /**\n * Wait for embeddings to complete after push.\n * Polls status endpoint until embeddings are done.\n * \n * @example\n * ```ts\n * await morphGit.push({ dir: './my-project', branch: 'main' });\n * await morphGit.waitForEmbeddings({\n * repoId: 'my-project',\n * onProgress: (p) => console.log(`${p.filesProcessed}/${p.totalFiles}`)\n * });\n * ```\n */\n async waitForEmbeddings(options: WaitForEmbeddingsOptions): Promise<void> {\n const { repoId, commitHash, timeout = 120000, onProgress } = options;\n const startTime = Date.now();\n const pollInterval = 1000; // Poll every 1s\n \n while (Date.now() - startTime < timeout) {\n const statusUrl = `${this.proxyUrl}/v1/repos/${repoId}/embedding-status` +\n (commitHash ? `?commit_hash=${commitHash}` : '');\n \n const response = await fetch(statusUrl, {\n headers: { 'Authorization': `Bearer ${this.apiKey}` }\n });\n \n if (response.status === 404) {\n // No job found yet - might still be creating\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n continue;\n }\n \n if (!response.ok) {\n throw new Error(`Failed to get embedding status: ${response.status}`);\n }\n \n const status = await response.json();\n \n if (onProgress && status.progress) {\n onProgress(status.progress);\n }\n \n if (status.status === 'completed') {\n return; // Done!\n }\n \n if (status.status === 'failed') {\n throw new Error(`Embeddings failed: ${status.error || 'Unknown error'}`);\n }\n \n // Still processing (queued or processing), wait and poll again\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n \n throw new Error(`Embeddings timed out after ${timeout}ms`);\n }\n\n /**\n * Stage a file for commit\n * \n * @example\n * ```ts\n * await morphGit.add({\n * dir: './my-project',\n * filepath: 'src/app.ts'\n * });\n * ```\n */\n async add(options: AddOptions): Promise<void> {\n const { dir, filepath } = options;\n\n await git.add({\n fs,\n dir,\n filepath,\n });\n }\n\n /**\n * Remove a file from staging\n * \n * @example\n * ```ts\n * await morphGit.remove({\n * dir: './my-project',\n * filepath: 'src/old-file.ts'\n * });\n * ```\n */\n async remove(options: AddOptions): Promise<void> {\n const { dir, filepath } = options;\n\n await git.remove({\n fs,\n dir,\n filepath,\n });\n }\n\n /**\n * Commit staged changes\n * \n * @example\n * ```ts\n * await morphGit.commit({\n * dir: './my-project',\n * message: 'Add new feature',\n * author: {\n * name: 'AI Agent',\n * email: 'ai@example.com'\n * },\n * metadata: { issueId: 'PROJ-123', source: 'agent' },\n * chatHistory: [\n * { role: 'user', content: 'Please add a new feature' },\n * { role: 'assistant', content: 'I will add that feature' }\n * ],\n * recordingId: 'rec_123'\n * });\n * ```\n */\n async commit(options: CommitOptions): Promise<string> {\n const { dir, message, author, metadata, chatHistory, recordingId } = options;\n\n // Provide default author if not specified\n const commitAuthor = author || {\n name: 'Morph SDK',\n email: 'sdk@morphllm.com'\n };\n\n const sha = await git.commit({\n fs,\n dir,\n message,\n author: commitAuthor,\n });\n\n // Store notes if any note fields are provided\n if (metadata || chatHistory || recordingId) {\n const notes: MorphNotesSchema = {\n metadata,\n chatHistory,\n recordingId,\n _version: 1\n };\n \n await git.addNote({\n fs,\n dir,\n ref: 'refs/notes/morph-metadata',\n oid: sha,\n note: JSON.stringify(notes, null, 2),\n author: commitAuthor\n });\n }\n\n return sha;\n }\n\n /**\n * Get status of a file\n * \n * @example\n * ```ts\n * const status = await morphGit.status({\n * dir: './my-project',\n * filepath: 'src/app.ts'\n * });\n * console.log(status); // 'modified', '*added', etc.\n * ```\n */\n async status(options: StatusOptions): Promise<string> {\n const { dir, filepath } = options;\n\n if (!filepath) {\n throw new Error('filepath is required for status check');\n }\n\n const status = await git.status({\n fs,\n dir,\n filepath,\n });\n\n return status;\n }\n\n /**\n * Get commit history\n * \n * @example\n * ```ts\n * const commits = await morphGit.log({\n * dir: './my-project',\n * depth: 10\n * });\n * ```\n */\n async log(options: LogOptions): Promise<CommitObject[]> {\n const { dir, depth, ref } = options;\n\n const commits = await git.log({\n fs,\n dir,\n depth,\n ref,\n });\n\n return commits as CommitObject[];\n }\n\n /**\n * Checkout a branch or commit\n * \n * @example\n * ```ts\n * await morphGit.checkout({\n * dir: './my-project',\n * ref: 'feature-branch'\n * });\n * ```\n */\n async checkout(options: CheckoutOptions): Promise<void> {\n const { dir, ref } = options;\n\n await git.checkout({\n fs,\n dir,\n ref,\n });\n }\n\n /**\n * Create a new branch\n * \n * @example\n * ```ts\n * await morphGit.branch({\n * dir: './my-project',\n * name: 'feature-branch',\n * checkout: true\n * });\n * ```\n */\n async branch(options: BranchOptions): Promise<void> {\n const { dir, name, checkout = false } = options;\n\n await git.branch({\n fs,\n dir,\n ref: name,\n checkout,\n });\n }\n\n /**\n * List all branches\n * \n * @example\n * ```ts\n * const branches = await morphGit.listBranches({\n * dir: './my-project'\n * });\n * ```\n */\n async listBranches(options: { dir: string }): Promise<string[]> {\n const { dir } = options;\n\n const branches = await git.listBranches({\n fs,\n dir,\n });\n\n return branches;\n }\n\n /**\n * Get the current branch name\n * \n * @example\n * ```ts\n * const branch = await morphGit.currentBranch({\n * dir: './my-project'\n * });\n * ```\n */\n async currentBranch(options: { dir: string }): Promise<string | undefined> {\n const { dir } = options;\n\n const branch = await git.currentBranch({\n fs,\n dir,\n });\n\n return branch || undefined;\n }\n\n /**\n * Get list of changed files (similar to git diff --name-only)\n * \n * @example\n * ```ts\n * const changes = await morphGit.statusMatrix({\n * dir: './my-project'\n * });\n * ```\n */\n async statusMatrix(options: { dir: string }): Promise<StatusResult[]> {\n const { dir } = options;\n\n const matrix = await git.statusMatrix({\n fs,\n dir,\n });\n\n return matrix.map(([filepath, HEADStatus, workdirStatus, stageStatus]) => {\n let status: StatusResult['status'] = 'unmodified';\n\n // Determine status based on statusMatrix values\n if (HEADStatus === 1 && workdirStatus === 2 && stageStatus === 2) {\n status = 'modified';\n } else if (HEADStatus === 1 && workdirStatus === 2 && stageStatus === 1) {\n status = '*modified';\n } else if (HEADStatus === 0 && workdirStatus === 2 && stageStatus === 2) {\n status = 'added';\n } else if (HEADStatus === 0 && workdirStatus === 2 && stageStatus === 0) {\n status = '*added';\n } else if (HEADStatus === 1 && workdirStatus === 0 && stageStatus === 0) {\n status = 'deleted';\n } else if (HEADStatus === 1 && workdirStatus === 0 && stageStatus === 1) {\n status = '*deleted';\n } else if (HEADStatus === 1 && workdirStatus === 1 && stageStatus === 1) {\n status = 'unmodified';\n } else if (HEADStatus === 0 && workdirStatus === 0 && stageStatus === 0) {\n status = 'absent';\n }\n\n return {\n filepath,\n status,\n };\n });\n }\n\n /**\n * Get the current commit hash\n * \n * @example\n * ```ts\n * const hash = await morphGit.resolveRef({\n * dir: './my-project',\n * ref: 'HEAD'\n * });\n * ```\n */\n async resolveRef(options: { dir: string; ref: string }): Promise<string> {\n const { dir, ref } = options;\n\n const oid = await git.resolveRef({\n fs,\n dir,\n ref,\n });\n\n return oid;\n }\n\n /**\n * Get notes (metadata, chat history, recording ID) attached to a commit\n * \n * @example\n * ```ts\n * const notes = await morphGit.getCommitMetadata({\n * dir: './my-project',\n * commitSha: 'abc123...'\n * });\n * \n * if (notes) {\n * console.log('Metadata:', notes.metadata);\n * console.log('Chat history:', notes.chatHistory);\n * console.log('Recording ID:', notes.recordingId);\n * }\n * ```\n */\n async getCommitMetadata(options: {\n dir: string;\n commitSha: string;\n }): Promise<MorphNotesSchema | null> {\n try {\n const note = await git.readNote({\n fs,\n dir: options.dir,\n ref: 'refs/notes/morph-metadata',\n oid: options.commitSha\n });\n \n const notes: MorphNotesSchema = JSON.parse(new TextDecoder().decode(note));\n return notes;\n } catch (err) {\n // No notes found for this commit\n return null;\n }\n }\n}\n\n","/**\n * Morph Git SDK\n * \n * Git operations for AI agents using Morph's backend infrastructure.\n * \n * @example\n * ```typescript\n * import { MorphGit } from 'morphsdk/git';\n * \n * const morphGit = new MorphGit({\n * apiKey: process.env.MORPH_API_KEY!\n * });\n * \n * // Initialize and push\n * await morphGit.init({ repoId: 'my-project', dir: './my-project' });\n * await morphGit.add({ dir: './my-project', filepath: 'src/app.ts' });\n * await morphGit.commit({ dir: './my-project', message: 'Update' });\n * await morphGit.push({ dir: './my-project', branch: 'main' });\n * ```\n */\n\nexport { MorphGit } from './client.js';\nexport type {\n MorphGitConfig,\n CloneOptions,\n PushOptions,\n PullOptions,\n AddOptions,\n CommitOptions,\n StatusOptions,\n LogOptions,\n CheckoutOptions,\n BranchOptions,\n DiffOptions,\n CommitObject,\n StatusResult,\n ChatMessage,\n CommitMetadata,\n MorphNotesSchema,\n} from './types.js';\n\n// Re-export isomorphic-git for advanced use cases\nexport { default as git } from 'isomorphic-git';\nexport { default as http } from 'isomorphic-git/http/node';\n\n","/**\n * Core implementation for intelligent model routing\n */\n\nimport { fetchWithRetry, withTimeout } from '../tools/utils/resilience.js';\nimport type {\n RouterConfig,\n RouterInput,\n RouterResult,\n RawRouterResult,\n ComplexityLevel,\n RouterMode,\n Provider,\n} from './types.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: 'https://api.morphllm.com',\n timeout: 5000, // 5 seconds (responses typically <500ms)\n debug: false,\n};\n\nabstract class BaseRouter {\n protected config: Required<Omit<RouterConfig, 'apiKey' | 'retryConfig'>> & Pick<RouterConfig, 'apiKey' | 'retryConfig'>;\n protected provider: Provider;\n\n constructor(provider: Provider, config: RouterConfig = {}) {\n this.provider = provider;\n this.config = {\n apiKey: config.apiKey,\n apiUrl: config.apiUrl || DEFAULT_CONFIG.apiUrl,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n debug: config.debug || DEFAULT_CONFIG.debug,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Select the optimal model for a given input and mode\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || process.env.MORPH_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/${this.provider}`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Requesting ${this.provider} model selection:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model: string; confidence?: number } = await response.json();\n\n const result: RouterResult = {\n model: apiResult.model,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Selected model: ${apiResult.model}, Confidence: ${apiResult.confidence?.toFixed(3)}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[ModelRouter] Error selecting model:`, error);\n }\n throw error;\n }\n }\n}\n\n/**\n * OpenAI model router for GPT-5 series\n */\nexport class OpenAIRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('openai', config);\n }\n\n /**\n * Select optimal GPT-5 model\n * \n * @param input - User input and mode\n * @returns Selected model name (gpt-5-mini | gpt-5-low | gpt-5-medium | gpt-5-high)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Anthropic model router for Claude 4.5 series\n */\nexport class AnthropicRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('anthropic', config);\n }\n\n /**\n * Select optimal Claude model\n * \n * @param input - User input and mode\n * @returns Selected model name (claude-4.5-haiku | claude-4.5-sonnet)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Google Gemini model router\n */\nexport class GeminiRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('gemini', config);\n }\n\n /**\n * Select optimal Gemini model\n * \n * @param input - User input and mode\n * @returns Selected model name (gemini-2.5-flash | gemini-2.5-pro)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Raw difficulty classification router (no provider-specific mapping)\n */\nexport class RawRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('raw' as Provider, config);\n }\n\n /**\n * Get raw difficulty classification\n * \n * @param input - User input and mode\n * @returns Raw difficulty (easy | medium | hard | needs_info)\n */\n async classify(input: RouterInput): Promise<RawRouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || process.env.MORPH_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/raw`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Requesting raw difficulty classification:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model?: string; difficulty?: string; confidence?: number } = await response.json();\n\n // Support both 'model' and 'difficulty' fields for compatibility\n // Empty string from API means \"medium\" difficulty (API bug workaround)\n let difficulty: ComplexityLevel;\n if (apiResult.difficulty === '') {\n difficulty = 'medium';\n } else {\n difficulty = (apiResult.difficulty || apiResult.model) as ComplexityLevel;\n }\n\n const result: RawRouterResult = {\n difficulty,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Classified as: ${difficulty}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[RawRouter] Error classifying:`, error);\n }\n throw error;\n }\n }\n}\n","/**\n * Prompts and descriptions for warpgrep_codebase_search\n */\n\n/**\n * Default tool name for the warp grep tool\n */\nexport const WARP_GREP_TOOL_NAME = 'warpgrep_codebase_search';\n\n/**\n * Default tool description for the warp grep tool\n */\nexport const WARP_GREP_DESCRIPTION = \n 'IMPORTANT: If you need to explore the codebase to gather context, and the task does not involve a single file or function which is provided by name, you should ALWAYS use the warpgrep codebase search tool first instead of running search commands. ' +\n 'When the task requires exploration beyond a single known file, invoke warpgrep first with a natural-language query describing the target functionality, bug, or architectural concern. ' +\n 'Warp Grep is a fast and accurate tool that can search for all relevant context in a codebase. ' +\n 'Keep queries action-oriented (e.g., \"Find where billing invoices are generated and emailed\"), and after reviewing the summarized results, you may verify important findings with other search tools or direct file reads to ensure completeness. ' +\n 'Warp Grep can be used for query types like: find function responsible for <small feature>; find code that does <description>; find code path for <big feature>; Where does <minimal error message> come from?; or any query of that type. ' +\n 'When a task requires exploration beyond a single known file, ALWAYS default to warpgrep codebase search before other search mechanisms.'\n\n/**\n * System prompt for the warp grep agent\n * Re-exported from agent/prompt.ts for convenience\n */\nexport { SYSTEM_PROMPT as WARP_GREP_SYSTEM_PROMPT, getSystemPrompt } from './agent/prompt.js';\n","/**\n * OpenAI SDK adapter for morph-warp-grep tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeToolCall, formatResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, WARP_GREP_TOOL_NAME, getSystemPrompt } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult } from './types.js';\n\n/**\n * Input schema for the warp grep tool\n */\nconst TOOL_PARAMETERS = {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Free-form repository question' },\n },\n required: ['query'],\n} as const;\n\n/**\n * OpenAI-native warp grep tool definition\n * \n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { warpGrepTool, execute } from '@morphllm/morphsdk/tools/warp-grep/openai';\n * \n * const client = new OpenAI();\n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [warpGrepTool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute the tool call\n * const result = await execute({ query: '...' }, { repoRoot: '.' });\n * ```\n */\nexport const warpGrepTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: WARP_GREP_TOOL_NAME,\n description: WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n },\n};\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with query\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { query: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult and getSystemPrompt for convenience\nexport { formatResult, getSystemPrompt };\n\n/**\n * Create a custom warp grep tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example Local usage\n * ```typescript\n * import OpenAI from 'openai';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/openai';\n * \n * const tool = createWarpGrepTool({ repoRoot: '.' });\n * \n * const client = new OpenAI();\n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * ```\n * \n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const tool = createMorphWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepToolConfig) {\n const tool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: config.name ?? WARP_GREP_TOOL_NAME,\n description: config.description ?? WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n },\n };\n\n return Object.assign(tool, {\n execute: async (input: unknown): Promise<WarpGrepResult> => {\n return executeToolCall(input as { query: string } | string, config);\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return getSystemPrompt();\n },\n });\n}\n\nexport default warpGrepTool;\n","/**\n * Tool descriptions and system prompts for codebase search\n */\n\nexport 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.`;\n\nexport 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.`;\n\n","/**\n * OpenAI SDK adapter for codebase_search tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION, CODEBASE_SEARCH_SYSTEM_PROMPT } from './prompts.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n/**\n * Direct codebase_search tool definition\n * Use this when you want to pass config at execute time\n */\nexport const codebaseSearchTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n },\n};\n\n/**\n * Create OpenAI-native codebase_search tool with execute and formatResult methods\n * \n * @param config - Configuration with repoId\n * @returns OpenAI ChatCompletionTool definition with methods\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/openai';\n * \n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\n * \n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * tools: [tool], // tool itself is the ChatCompletionTool\n * messages: [{ role: \"user\", content: \"Find authentication code\" }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const toolDefinition: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n },\n };\n\n return Object.assign(toolDefinition, {\n execute: async (input: CodebaseSearchInput | string): Promise<CodebaseSearchResult> => {\n const parsedInput = typeof input === 'string' ? JSON.parse(input) : input;\n return executeCodebaseSearch(parsedInput, config);\n },\n formatResult: (result: CodebaseSearchResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Execute codebase_search tool call\n * \n * @param input - Tool input from GPT (parsed from tool_calls)\n * @param config - Configuration with repoId (REQUIRED)\n * @returns Search results\n * \n * @example\n * ```ts\n * // Handle tool calls from GPT:\n * if (response.choices[0].message.tool_calls) {\n * for (const toolCall of response.choices[0].message.tool_calls) {\n * const args = JSON.parse(toolCall.function.arguments);\n * const result = await execute(args, { repoId: 'my-project' });\n * console.log(`Found ${result.results.length} matches`);\n * }\n * }\n * ```\n */\nexport async function execute(\n input: CodebaseSearchInput,\n config: CodebaseSearchConfig\n): Promise<CodebaseSearchResult> {\n return executeCodebaseSearch(input, config);\n}\n\n/**\n * Format search results for GPT\n * \n * @param result - Search result from endpoint\n * @returns Formatted string for tool message\n */\nexport function formatResult(result: CodebaseSearchResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (result.results.length === 0) {\n return 'No matching code found. Try rephrasing your query or removing directory filters.';\n }\n\n const lines: string[] = [];\n \n lines.push(`Found ${result.results.length} relevant code sections (${result.stats.searchTimeMs}ms):\\n`);\n\n result.results.forEach((r, i) => {\n const relevance = (r.rerankScore * 100).toFixed(1);\n lines.push(`${i + 1}. ${r.filepath} (${relevance}% relevant)`);\n lines.push(` Symbol: ${r.symbolPath}`);\n lines.push(` Language: ${r.language}`);\n lines.push(` Lines: ${r.startLine}-${r.endLine}`);\n lines.push(` Code:`);\n \n // Show code content\n const codeLines = r.content.split('\\n');\n codeLines.slice(0, Math.min(codeLines.length, 20)).forEach(line => {\n lines.push(` ${line}`);\n });\n \n if (codeLines.length > 20) {\n lines.push(` ... (${codeLines.length - 20} more lines)`);\n }\n \n lines.push('');\n });\n\n return lines.join('\\n');\n}\n\n/**\n * Get the system prompt for codebase_search usage\n * \n * @returns System prompt to guide GPT\n */\nexport function getSystemPrompt(): string {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n}\n\n/**\n * Default export for convenience\n */\nexport default { createCodebaseSearchTool, execute, formatResult, getSystemPrompt };\n\n","/**\n * System prompts for edit_file tool\n */\n\nexport const EDIT_FILE_TOOL_DESCRIPTION = `Use this tool to make an edit to an existing file.\n\nThis will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.\n\nWhen writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.\n\nFor example:\n\n// ... existing code ...\nFIRST_EDIT\n// ... existing code ...\nSECOND_EDIT\n// ... existing code ...\nTHIRD_EDIT\n// ... existing code ...\n\nYou should still bias towards repeating as few lines of the original file as possible to convey the change.\nBut, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.\n\nDO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.\n\nIf you plan on deleting a section, you must provide context before and after to delete it.\n\nMake sure it is clear what the edit should be, and where it should be applied.\nMake edits to a file in a single edit_file call instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.`;\n\nexport const EDIT_FILE_SYSTEM_PROMPT = `When the user is asking for edits to their code, use the edit_file tool to highlight the changes necessary and add comments to indicate where unchanged code has been skipped. For example:\n\n// ... existing code ...\n{{ edit_1 }}\n// ... existing code ...\n{{ edit_2 }}\n// ... existing code ...\n\nOften this will mean that the start/end of the file will be skipped, but that's okay! Rewrite the entire file ONLY if specifically requested. Always provide a brief explanation of the updates, unless the user specifically requests only the code.\n\nThese edit codeblocks are also read by a less intelligent language model, colloquially called the apply model, to update the file. To help specify the edit to the apply model, you will be very careful when generating the codeblock to not introduce ambiguity. You will specify all unchanged regions (code and comments) of the file with \"// ... existing code ...\" comment markers. This will ensure the apply model will not delete existing unchanged code or comments when editing the file.`;\n\n","/**\n * OpenAI SDK adapter for edit_file tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * OpenAI-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { editFileTool } from 'morphsdk/tools/openai';\n * \n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * \n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instructions: {\n type: 'string',\n description: 'A single sentence describing what you are changing (first person)',\n },\n code_edit: {\n type: 'string',\n description: 'The lazy edit with // ... existing code ... markers',\n },\n },\n required: ['target_filepath', 'instructions', 'code_edit'],\n },\n },\n};\n\n/**\n * Execute an edit_file tool call\n * \n * @param input - The tool input from GPT (parsed from tool_calls)\n * @param config - Optional configuration\n * @returns The result of the edit operation\n * \n * @example\n * ```ts\n * const args = JSON.parse(toolCall.function.arguments);\n * const result = await execute(args);\n * console.log('Changes applied:', result.udiff);\n * ```\n */\nexport async function execute(\n input: EditFileInput,\n config?: EditFileConfig\n): Promise<EditFileResult> {\n return executeEditFile(input, config);\n}\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide GPT on using edit_file properly.\n * \n * @example\n * ```ts\n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * messages: [\n * { role: \"system\", content: getSystemPrompt() },\n * { role: \"user\", content: \"Fix bugs\" }\n * ],\n * tools: [editFileTool]\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Format the result for passing back to GPT\n * \n * @param result - The edit result\n * @returns Formatted string for tool message\n */\nexport function formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n const summary = [\n changes.linesAdded && `+${changes.linesAdded} lines`,\n changes.linesRemoved && `-${changes.linesRemoved} lines`,\n changes.linesModified && `~${changes.linesModified} lines modified`,\n ]\n .filter(Boolean)\n .join(', ');\n \n if (result.udiff) {\n return `Successfully applied changes to ${result.filepath}:\\n\\n${result.udiff}\\n\\nSummary: ${summary}`;\n }\n \n return `Successfully applied changes to ${result.filepath}. ${summary}`;\n}\n\n/**\n * Create a custom edit_file tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { createEditFileTool } from 'morphsdk/tools/fastapply/openai';\n * \n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const client = new OpenAI();\n * \n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool], // tool itself is the ChatCompletionTool\n * messages: [{ role: 'user', content: 'Fix bug in app.ts' }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: ChatCompletionTool = {\n ...editFileTool,\n ...(config.description && {\n function: {\n ...editFileTool.function,\n description: config.description,\n },\n }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput | string): Promise<EditFileResult> => {\n const parsedInput = typeof input === 'string' ? JSON.parse(input) : input;\n return execute(parsedInput, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return getSystemPrompt();\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n","/**\n * OpenAI Tool Factory for MorphClient\n * \n * Creates OpenAI-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool } from '../tools/warp_grep/openai.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/openai.js';\nimport { createEditFileTool } from '../tools/fastapply/openai.js';\nimport type { WarpGrepToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\n\n/**\n * Factory for creating OpenAI-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.openai.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.openai.createEditFileTool({ baseDir: './src' });\n * \n * // Use with OpenAI client\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [grepTool, searchTool, editTool],\n * messages: [{ role: 'user', content: 'Find and fix the bug' }]\n * });\n * ```\n */\nexport class OpenAIToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create an OpenAI-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Anthropic SDK adapter for morph-warp-grep tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeToolCall, formatResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, WARP_GREP_TOOL_NAME, getSystemPrompt } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult } from './types.js';\n\n/**\n * Input schema for the warp grep tool\n */\nconst INPUT_SCHEMA = {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Free-form repository question' },\n },\n required: ['query'],\n} as const;\n\n/**\n * Anthropic-native warp grep tool definition\n * \n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { warpGrepTool, execute } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const client = new Anthropic();\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [warpGrepTool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute the tool call\n * const result = await execute({ query: '...' }, { repoRoot: '.' });\n * ```\n */\nexport const warpGrepTool: Tool = {\n name: WARP_GREP_TOOL_NAME,\n description: WARP_GREP_DESCRIPTION,\n input_schema: INPUT_SCHEMA,\n};\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with query\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { query: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult and getSystemPrompt for convenience\nexport { formatResult, getSystemPrompt };\n\n/**\n * Create a custom warp grep tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example Local usage\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const tool = createWarpGrepTool({ repoRoot: '.' });\n * \n * const client = new Anthropic();\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * ```\n * \n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const tool = createMorphWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepToolConfig) {\n const tool: Tool = {\n name: config.name ?? WARP_GREP_TOOL_NAME,\n description: config.description ?? WARP_GREP_DESCRIPTION,\n input_schema: INPUT_SCHEMA,\n };\n\n return Object.assign(tool, {\n execute: async (input: unknown): Promise<WarpGrepResult> => {\n return executeToolCall(input as { query: string } | string, config);\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return getSystemPrompt();\n },\n });\n}\n","/**\n * Anthropic SDK adapter for codebase_search tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION, CODEBASE_SEARCH_SYSTEM_PROMPT } from './prompts.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n\n/**\n * Create Anthropic-native codebase_search tool with execute and formatResult methods\n * \n * @param config - Configuration with repoId\n * @returns Anthropic Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [tool], // tool itself is the Tool definition\n * messages: [{ role: \"user\", content: \"Find authentication code\" }]\n * });\n * \n * // Execute tool and format result\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const toolDefinition: Tool = {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n input_schema: {\n type: 'object',\n properties: {\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n query: {\n type: 'string',\n description: 'A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n cache_control: { type: 'ephemeral' } as any,\n } as any;\n\n return Object.assign(toolDefinition, {\n execute: async (input: CodebaseSearchInput): Promise<CodebaseSearchResult> => {\n return executeCodebaseSearch(input, config);\n },\n formatResult: (result: CodebaseSearchResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Format search results for Claude\n * \n * @param result - Search result from endpoint\n * @returns Formatted string for tool_result\n */\nfunction formatResult(result: CodebaseSearchResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (result.results.length === 0) {\n return 'No matching code found. Try rephrasing your query or broadening the search scope.';\n }\n\n const lines: string[] = [];\n \n lines.push(`Found ${result.results.length} relevant code sections (searched ${result.stats.candidatesRetrieved} candidates in ${result.stats.searchTimeMs}ms):\\n`);\n\n result.results.forEach((r, i) => {\n const relevance = (r.rerankScore * 100).toFixed(1);\n lines.push(`${i + 1}. ${r.filepath} (${relevance}% relevant)`);\n lines.push(` Symbol: ${r.symbolPath}`);\n lines.push(` Language: ${r.language}`);\n lines.push(` Lines: ${r.startLine}-${r.endLine}`);\n lines.push(` Code:`);\n \n // Show code content with indentation\n const codeLines = r.content.split('\\n');\n codeLines.slice(0, Math.min(codeLines.length, 20)).forEach(line => {\n lines.push(` ${line}`);\n });\n \n if (codeLines.length > 20) {\n lines.push(` ... (${codeLines.length - 20} more lines)`);\n }\n \n lines.push('');\n });\n\n return lines.join('\\n');\n}\n\n","/**\n * Anthropic SDK adapter for edit_file tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * Anthropic-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { editFileTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: Tool = {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n input_schema: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instructions: {\n type: 'string',\n description: 'A single sentence describing what you are changing (first person)',\n },\n code_edit: {\n type: 'string',\n description: 'The lazy edit with // ... existing code ... markers',\n },\n },\n required: ['target_filepath', 'instructions', 'code_edit'],\n },\n};\n\n/**\n * Format the result for passing back to Claude\n * \n * @param result - The edit result\n * @returns Formatted string for tool_result\n */\nexport function formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n const summary = [\n changes.linesAdded && `+${changes.linesAdded} lines`,\n changes.linesRemoved && `-${changes.linesRemoved} lines`,\n changes.linesModified && `~${changes.linesModified} lines modified`,\n ]\n .filter(Boolean)\n .join(', ');\n \n if (result.udiff) {\n return `Successfully applied changes to ${result.filepath}:\\n\\n${result.udiff}\\n\\nSummary: ${summary}`;\n }\n \n return `Successfully applied changes to ${result.filepath}. ${summary}`;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * morphApiKey: 'sk-...',\n * description: 'Custom tool description for your use case'\n * });\n * \n * // Use as Anthropic tool\n * const response = await client.messages.create({\n * tools: [tool], // tool itself is the Tool definition\n * ...\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: Tool = {\n ...editFileTool,\n ...(config.description && { description: config.description }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput): Promise<EditFileResult> => {\n return executeEditFile(input, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return EDIT_FILE_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Execute the edit_file tool with raw input\n * \n * @param input - Tool input from Claude's tool_use\n * @param config - Configuration for Fast Apply\n * @returns Tool result to send back to Claude\n */\nexport async function execute(\n input: EditFileInput,\n config?: EditFileConfig\n): Promise<EditFileResult> {\n return executeEditFile(input, config);\n}\n\n/**\n * Get the system prompt for the edit_file tool\n * \n * @returns System prompt string\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n","/**\n * Anthropic Tool Factory for MorphClient\n * \n * Creates Anthropic-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool } from '../tools/warp_grep/anthropic.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/anthropic.js';\nimport { createEditFileTool } from '../tools/fastapply/anthropic.js';\nimport type { WarpGrepToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\n\n/**\n * Factory for creating Anthropic-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.anthropic.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.anthropic.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.anthropic.createEditFileTool({ baseDir: './src' });\n * \n * // Use with Anthropic client\n * const response = await anthropic.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [grepTool, searchTool, editTool],\n * messages: [{ role: 'user', content: 'Find and fix the bug' }]\n * });\n * ```\n */\nexport class AnthropicToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create an Anthropic-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Anthropic-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Anthropic-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Vercel AI SDK adapter for morph-warp-grep tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeToolCall, formatResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, getSystemPrompt } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult } from './types.js';\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with query\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { query: string },\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult and getSystemPrompt for convenience\nexport { formatResult, getSystemPrompt };\n\n/**\n * Create Vercel AI SDK warp grep tool\n * \n * @param config - Configuration options\n * @returns Vercel AI SDK tool\n * \n * @example Local usage\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n * \n * const grepTool = createWarpGrepTool({ repoRoot: '.' });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { grep: grepTool },\n * prompt: 'Find authentication middleware'\n * });\n * ```\n * \n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const grepTool = createMorphWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepToolConfig) {\n const schema = z.object({\n query: z.string().describe('Free-form repository question'),\n });\n\n return tool({\n description: config.description ?? WARP_GREP_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const result = await executeToolCall(params, config);\n \n if (!result.success) {\n throw new Error(`Failed to search codebase: ${result.error}`);\n }\n \n return {\n success: true,\n contexts: result.contexts,\n summary: result.summary,\n };\n },\n });\n}\n\n// Default export for convenience\nexport default createWarpGrepTool;\n","/**\n * Vercel AI SDK adapter for codebase_search tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION } from './prompts.js';\nimport type { CodebaseSearchConfig } from './types.js';\n\n/**\n * Create Vercel AI SDK codebase_search tool\n * \n * @param config - Configuration with repoId\n * @returns Vercel AI SDK tool definition (execution built-in)\n * \n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/codebase-search/vercel';\n * \n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\n * \n * const result = await generateText({\n * model: anthropic('claude-3-5-sonnet-20241022'),\n * tools: { codebaseSearch: tool },\n * prompt: \"Find authentication code\",\n * maxSteps: 5\n * });\n * \n * // Vercel AI SDK automatically executes and handles results\n * console.log(result.text);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const schema = z.object({\n query: z.string().describe('A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"'),\n target_directories: z.array(z.string()).describe('Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.'),\n explanation: z.string().describe('One sentence explanation as to why this tool is being used, and how it contributes to the goal.'),\n limit: z.number().optional().describe('Max results to return (default: 10)'),\n });\n\n return tool({\n description: CODEBASE_SEARCH_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const { query, target_directories, explanation, limit } = params;\n const result = await executeCodebaseSearch(\n { query, target_directories, explanation, limit },\n config\n );\n\n if (!result.success) {\n return {\n error: result.error,\n results: [],\n };\n }\n\n // Format results for Vercel AI SDK\n return {\n found: result.results.length,\n searchTime: `${result.stats.searchTimeMs}ms`,\n results: result.results.map(r => ({\n file: r.filepath,\n symbol: r.symbolPath,\n lines: `${r.startLine}-${r.endLine}`,\n language: r.language,\n relevance: `${(r.rerankScore * 100).toFixed(1)}%`,\n code: r.content,\n })),\n };\n },\n });\n}\n\n/**\n * Get system prompt for Vercel AI SDK\n */\nexport function getSystemPrompt(): string {\n return CODEBASE_SEARCH_DESCRIPTION;\n}\n\n/**\n * Default export\n */\nexport default { createCodebaseSearchTool, getSystemPrompt };\n\n","/**\n * Vercel AI SDK adapter for edit_file tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileConfig } from './types.js';\n\n/**\n * Vercel AI SDK tool for edit_file\n * \n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { editFileTool } from 'morphsdk/tools/vercel';\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix the bug in app.ts\"\n * });\n * ```\n */\nconst editFileSchema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n});\n\nexport const editFileTool = tool({\n description: EDIT_FILE_TOOL_DESCRIPTION,\n inputSchema: editFileSchema,\n execute: async (params) => {\n const result = await executeEditFile({\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n });\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n});\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide the model on using edit_file properly.\n * \n * @example\n * ```ts\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * system: getSystemPrompt(),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Vercel AI SDK tool with custom config\n * \n * @example\n * ```ts\n * const customEditTool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: customEditTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const schema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n });\n\n return tool({\n description: config.description || EDIT_FILE_TOOL_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const result = await executeEditFile(\n {\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n },\n config\n );\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n","/**\n * Vercel AI SDK Tool Factory for MorphClient\n * \n * Creates Vercel AI SDK-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool } from '../tools/warp_grep/vercel.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/vercel.js';\nimport { createEditFileTool } from '../tools/fastapply/vercel.js';\nimport type { WarpGrepToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\n\n/**\n * Factory for creating Vercel AI SDK-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.vercel.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.vercel.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * \n * // Use with Vercel AI SDK\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { grep: grepTool, search: searchTool, edit: editTool },\n * prompt: 'Find and fix the bug'\n * });\n * ```\n */\nexport class VercelToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create a Vercel AI SDK-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface\n * \n * @example\n * ```typescript\n * import { MorphClient } from '@morphllm/morphsdk';\n * \n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * \n * // Direct execution\n * await morph.fastApply.execute({ target_filepath: 'src/index.ts', ... });\n * await morph.warpGrep.execute({ query: 'Find auth', repoRoot: '.' });\n * await morph.codebaseSearch.search({ query: 'auth logic', repoId: 'x' });\n * \n * // Tool creation for AI agents (API key inherited)\n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.anthropic.createCodebaseSearchTool({ repoId: 'x' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * \n * // Use tools with OpenAI\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [grepTool],\n * messages: [{ role: 'user', content: 'Find the bug' }]\n * });\n * ```\n */\n\nimport type { RetryConfig } from './tools/utils/resilience.js';\nimport { FastApplyClient } from './tools/fastapply/core.js';\nimport { CodebaseSearchClient } from './tools/codebase_search/core.js';\nimport { BrowserClient } from './tools/browser/core.js';\nimport { WarpGrepClient } from './tools/warp_grep/client.js';\nimport { MorphGit } from './git/index.js';\nimport { OpenAIRouter, AnthropicRouter, GeminiRouter, RawRouter } from './modelrouter/core.js';\nimport { OpenAIToolFactory, AnthropicToolFactory, VercelToolFactory } from './factories/index.js';\n\n/**\n * Configuration for the MorphClient\n */\nexport interface MorphClientConfig {\n /** Morph API key for authentication (defaults to MORPH_API_KEY env var) */\n apiKey?: string;\n /** Enable debug logging across all tools */\n debug?: boolean;\n /** Default timeout in milliseconds for API requests */\n timeout?: number;\n /** Retry configuration for failed requests */\n retryConfig?: RetryConfig;\n}\n\n/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface:\n * - fastApply: AI-powered file editing with intelligent merging\n * - codebaseSearch: Semantic code search\n * - warpGrep: Fast code search with ripgrep\n * - browser: AI-powered browser automation\n * - git: Version control operations\n * - routers: Intelligent model selection (OpenAI, Anthropic, Gemini)\n * - openai/anthropic/vercel: Tool factories for agent frameworks\n */\nexport class MorphClient {\n /** Client configuration */\n public config: MorphClientConfig;\n\n /** FastApply tool for editing files with AI-powered merge */\n public fastApply: FastApplyClient;\n\n /** CodebaseSearch tool for semantic code search */\n public codebaseSearch: CodebaseSearchClient;\n\n /** WarpGrep tool for fast code search using ripgrep */\n public warpGrep: WarpGrepClient;\n\n /** Browser tool for AI-powered browser automation */\n public browser: BrowserClient;\n\n /** Git tool for version control operations */\n public git: MorphGit;\n\n /** Model routers for intelligent model selection */\n public routers: {\n openai: OpenAIRouter;\n anthropic: AnthropicRouter;\n gemini: GeminiRouter;\n raw: RawRouter;\n };\n\n /** OpenAI-compatible tool factories */\n public openai: OpenAIToolFactory;\n\n /** Anthropic-compatible tool factories */\n public anthropic: AnthropicToolFactory;\n\n /** Vercel AI SDK tool factories */\n public vercel: VercelToolFactory;\n\n /**\n * Create a new Morph SDK client\n * \n * @param config - Client configuration (apiKey, debug, timeout, retryConfig)\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * ```\n */\n constructor(config: MorphClientConfig = {}) {\n this.config = config;\n\n // Initialize all sub-clients with shared config\n this.fastApply = new FastApplyClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.codebaseSearch = new CodebaseSearchClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.warpGrep = new WarpGrepClient({\n morphApiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.browser = new BrowserClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.git = new MorphGit({\n apiKey: config.apiKey,\n retryConfig: config.retryConfig,\n });\n\n this.routers = {\n openai: new OpenAIRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n anthropic: new AnthropicRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n gemini: new GeminiRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n raw: new RawRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n };\n\n // Initialize tool factories\n this.openai = new OpenAIToolFactory(config);\n this.anthropic = new AnthropicToolFactory(config);\n this.vercel = new VercelToolFactory(config);\n }\n}\n","/**\n * Google Gemini SDK adapter for morph-warp-grep tool\n */\n\nimport type { FunctionDeclaration, FunctionDeclarationSchema } from '@google/generative-ai';\nimport { SchemaType } from '@google/generative-ai';\nimport { executeToolCall, formatResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, WARP_GREP_TOOL_NAME, getSystemPrompt } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult } from './types.js';\n\n/**\n * Parameter schema for the warp grep tool (Gemini format)\n */\nconst TOOL_PARAMETERS: FunctionDeclarationSchema = {\n type: SchemaType.OBJECT,\n properties: {\n query: { \n type: SchemaType.STRING, \n description: 'Free-form repository question' \n },\n },\n required: ['query'],\n};\n\n/**\n * Gemini-native warp grep function declaration\n * \n * @example\n * ```typescript\n * import { GoogleGenerativeAI } from '@google/generative-ai';\n * import { warpGrepFunctionDeclaration, execute } from '@morphllm/morphsdk/tools/warp-grep/gemini';\n * \n * const genAI = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY);\n * const model = genAI.getGenerativeModel({\n * model: 'gemini-2.0-flash',\n * tools: [{ functionDeclarations: [warpGrepFunctionDeclaration] }]\n * });\n * \n * const chat = model.startChat();\n * const result = await chat.sendMessage('Find authentication middleware');\n * \n * // Handle function call\n * const call = result.response.functionCalls()?.[0];\n * if (call) {\n * const searchResult = await execute(call.args, { repoRoot: '.' });\n * console.log(searchResult);\n * }\n * ```\n */\nexport const warpGrepFunctionDeclaration: FunctionDeclaration = {\n name: WARP_GREP_TOOL_NAME,\n description: WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n};\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with query\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { query: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult and getSystemPrompt for convenience\nexport { formatResult, getSystemPrompt };\n\n/**\n * Gemini tool with execute method attached\n */\nexport interface GeminiWarpGrepTool extends FunctionDeclaration {\n execute: (input: unknown) => Promise<WarpGrepResult>;\n formatResult: (result: WarpGrepResult) => string;\n getSystemPrompt: () => string;\n}\n\n/**\n * Create a custom warp grep tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Function declaration with execute and formatResult methods\n * \n * @example Local usage\n * ```typescript\n * import { GoogleGenerativeAI } from '@google/generative-ai';\n * import { createMorphWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/gemini';\n * \n * const tool = createMorphWarpGrepTool({ repoRoot: '.' });\n * \n * const genAI = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY);\n * const model = genAI.getGenerativeModel({\n * model: 'gemini-2.0-flash',\n * tools: [{ functionDeclarations: [tool] }]\n * });\n * \n * const chat = model.startChat();\n * const result = await chat.sendMessage('Find authentication middleware');\n * \n * // Handle function call\n * const call = result.response.functionCalls()?.[0];\n * if (call && call.name === tool.name) {\n * const searchResult = await tool.execute(call.args);\n * console.log(tool.formatResult(searchResult));\n * \n * // Send result back to model\n * await chat.sendMessage([{\n * functionResponse: {\n * name: call.name,\n * response: { result: tool.formatResult(searchResult) }\n * }\n * }]);\n * }\n * ```\n * \n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const tool = createMorphWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createMorphWarpGrepTool(config: WarpGrepToolConfig): GeminiWarpGrepTool {\n const declaration: FunctionDeclaration = {\n name: config.name ?? WARP_GREP_TOOL_NAME,\n description: config.description ?? WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n };\n\n return Object.assign(declaration, {\n execute: async (input: unknown): Promise<WarpGrepResult> => {\n return executeToolCall(input as { query: string } | string, config);\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return getSystemPrompt();\n },\n });\n}\n\nexport default warpGrepFunctionDeclaration;\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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,KAAK,IAAI,UAAU;AAAA,QACjB,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,IACH;AAGA,SAAK,SAAS,IAAI,kBAAkB,MAAM;AAC1C,SAAK,YAAY,IAAI,qBAAqB,MAAM;AAChD,SAAK,SAAS,IAAI,kBAAkB,MAAM;AAAA,EAC5C;AACF;;;ACvLA,2BAA2B;AAQ3B,IAAMC,mBAA6C;AAAA,EACjD,MAAM,gCAAW;AAAA,EACjB,YAAY;AAAA,IACV,OAAO;AAAA,MACL,MAAM,gCAAW;AAAA,MACjB,aAAa;AAAA,IACf;AAAA,EACF;AAAA,EACA,UAAU,CAAC,OAAO;AACpB;","names":["resolve","DEFAULT_CONFIG","resolve","path","res","path","import_path","path","import_path","path","import_promises","import_path","resolve","import_path","path","fs","import_promises","fs","fs","path","import_fs","git","fs","http","resolve","import_isomorphic_git","import_node","DEFAULT_CONFIG","tool","formatResult","formatResult","getSystemPrompt","formatResult","createWarpGrepTool","tool","createCodebaseSearchTool","formatResult","editFileTool","formatResult","createEditFileTool","createWarpGrepTool","createCodebaseSearchTool","createEditFileTool","createWarpGrepTool","import_ai","import_zod","createCodebaseSearchTool","import_ai","import_zod","editFileTool","createEditFileTool","createWarpGrepTool","createCodebaseSearchTool","createEditFileTool","TOOL_PARAMETERS"]}
|