@morphllm/morphsdk 0.2.52 → 0.2.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/{chunk-UU6XCZG3.js → chunk-2XNF3W7C.js} +3 -3
  2. package/dist/{chunk-FYQUSDOE.js → chunk-563REN2T.js} +3 -3
  3. package/dist/{chunk-G4AWE5A2.js → chunk-5QIWYEHJ.js} +2 -2
  4. package/dist/{chunk-YR53PPVM.js → chunk-C4IXE2RM.js} +3 -3
  5. package/dist/{chunk-64PMM72R.js → chunk-CKTA4AXM.js} +58 -2
  6. package/dist/chunk-CKTA4AXM.js.map +1 -0
  7. package/dist/{chunk-L5BMGLLQ.js → chunk-IFVROB4L.js} +21 -14
  8. package/dist/{chunk-L5BMGLLQ.js.map → chunk-IFVROB4L.js.map} +1 -1
  9. package/dist/{chunk-3FTAIJBH.js → chunk-IUG2FHNN.js} +2 -2
  10. package/dist/{chunk-MZT6HVGD.js → chunk-KYVR4QCG.js} +3 -3
  11. package/dist/{chunk-MZT6HVGD.js.map → chunk-KYVR4QCG.js.map} +1 -1
  12. package/dist/{chunk-PZDR5ZZ2.js → chunk-NOQCKVY3.js} +9 -9
  13. package/dist/{chunk-UIZT3KVJ.js → chunk-QZNGKOCZ.js} +2 -2
  14. package/dist/client.cjs +64 -2
  15. package/dist/client.cjs.map +1 -1
  16. package/dist/client.js +15 -15
  17. package/dist/index.cjs +68 -4
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.ts +6 -5
  20. package/dist/index.js +19 -17
  21. package/dist/tools/fastapply/anthropic.cjs.map +1 -1
  22. package/dist/tools/fastapply/anthropic.js +2 -2
  23. package/dist/tools/fastapply/core.cjs +57 -0
  24. package/dist/tools/fastapply/core.cjs.map +1 -1
  25. package/dist/tools/fastapply/core.d.ts +50 -2
  26. package/dist/tools/fastapply/core.js +3 -1
  27. package/dist/tools/fastapply/index.cjs +34 -0
  28. package/dist/tools/fastapply/index.cjs.map +1 -1
  29. package/dist/tools/fastapply/index.d.ts +2 -2
  30. package/dist/tools/fastapply/index.js +6 -4
  31. package/dist/tools/fastapply/openai.cjs.map +1 -1
  32. package/dist/tools/fastapply/openai.js +2 -2
  33. package/dist/tools/fastapply/types.cjs.map +1 -1
  34. package/dist/tools/fastapply/types.d.ts +47 -1
  35. package/dist/tools/fastapply/vercel.cjs.map +1 -1
  36. package/dist/tools/fastapply/vercel.js +2 -2
  37. package/dist/tools/index.cjs +34 -0
  38. package/dist/tools/index.cjs.map +1 -1
  39. package/dist/tools/index.d.ts +2 -2
  40. package/dist/tools/index.js +6 -4
  41. package/dist/tools/warp_grep/agent/runner.cjs +8 -1
  42. package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
  43. package/dist/tools/warp_grep/agent/runner.js +6 -6
  44. package/dist/tools/warp_grep/anthropic.cjs +9 -2
  45. package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
  46. package/dist/tools/warp_grep/anthropic.js +8 -8
  47. package/dist/tools/warp_grep/index.cjs +9 -2
  48. package/dist/tools/warp_grep/index.cjs.map +1 -1
  49. package/dist/tools/warp_grep/index.js +10 -10
  50. package/dist/tools/warp_grep/openai.cjs +9 -2
  51. package/dist/tools/warp_grep/openai.cjs.map +1 -1
  52. package/dist/tools/warp_grep/openai.js +8 -8
  53. package/dist/tools/warp_grep/vercel.cjs +9 -2
  54. package/dist/tools/warp_grep/vercel.cjs.map +1 -1
  55. package/dist/tools/warp_grep/vercel.js +8 -8
  56. package/package.json +1 -1
  57. package/dist/chunk-64PMM72R.js.map +0 -1
  58. /package/dist/{chunk-UU6XCZG3.js.map → chunk-2XNF3W7C.js.map} +0 -0
  59. /package/dist/{chunk-FYQUSDOE.js.map → chunk-563REN2T.js.map} +0 -0
  60. /package/dist/{chunk-G4AWE5A2.js.map → chunk-5QIWYEHJ.js.map} +0 -0
  61. /package/dist/{chunk-YR53PPVM.js.map → chunk-C4IXE2RM.js.map} +0 -0
  62. /package/dist/{chunk-3FTAIJBH.js.map → chunk-IUG2FHNN.js.map} +0 -0
  63. /package/dist/{chunk-PZDR5ZZ2.js.map → chunk-NOQCKVY3.js.map} +0 -0
  64. /package/dist/{chunk-UIZT3KVJ.js.map → chunk-QZNGKOCZ.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../tools/fastapply/index.ts","../../../tools/fastapply/core.ts","../../../tools/utils/resilience.ts","../../../tools/fastapply/prompts.ts","../../../tools/fastapply/anthropic.ts","../../../tools/fastapply/openai.ts","../../../tools/fastapply/vercel.ts"],"sourcesContent":["/**\n * Morph Fast Apply SDK - Main exports\n * \n * @example\n * ```ts\n * // Framework-specific imports (recommended)\n * import { editFileTool } from 'morphsdk/tools/anthropic';\n * import { editFileTool } from 'morphsdk/tools/openai';\n * import { editFileTool } from 'morphsdk/tools/vercel';\n * ```\n */\n\n// Core exports\nexport { executeEditFile, generateUdiff, countChanges } from './core.js';\nexport type {\n EditFileInput,\n EditFileResult,\n EditFileConfig,\n EditChanges,\n} from './types.js';\n\n// Prompt exports\nexport {\n EDIT_FILE_TOOL_DESCRIPTION,\n EDIT_FILE_SYSTEM_PROMPT,\n} from './prompts.js';\n\n// Re-export all adapters for convenience\nexport * as anthropic from './anthropic.js';\nexport * as openai from './openai.js';\nexport * as vercel from './vercel.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} 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/**\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 * 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 * 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 * 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 * 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 * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIA,sBAAoC;AACpC,kBAAwC;AACxC,kBAAoC;;;ACOpC,IAAM,uBAA+D;AAAA,EACnE,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,iBAAiB,CAAC,gBAAgB,aAAa,WAAW;AAC5D;AAmBA,eAAsB,eACpB,KACA,SACA,cAA2B,CAAC,GACT;AACnB,QAAM;AAAA,IACJ,aAAa,qBAAqB;AAAA,IAClC,eAAe,qBAAqB;AAAA,I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AI,CAAC,OAAO,SAAS;AACnB,cAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,MACxD;AAEA,aAAO;AAAA,QACL,SAAS;AAAA,QACT,UAAU,OAAO;AAAA,QACjB,SAAS,OAAO;AAAA,QAChB,OAAO,OAAO;AAAA,MAChB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAGA,IAAO,iBAAQF;","names":["resolve","createEditFileTool","editFileTool","execute","formatResult","getSystemPrompt","editFileTool","execute","getSystemPrompt","formatResult","createEditFileTool","createEditFileTool","editFileTool","getSystemPrompt","editFileTool","getSystemPrompt","createEditFileTool"]}
1
+ {"version":3,"sources":["../../../tools/fastapply/index.ts","../../../tools/fastapply/core.ts","../../../tools/utils/resilience.ts","../../../tools/fastapply/prompts.ts","../../../tools/fastapply/anthropic.ts","../../../tools/fastapply/openai.ts","../../../tools/fastapply/vercel.ts"],"sourcesContent":["/**\n * Morph Fast Apply SDK - Main exports\n * \n * @example\n * ```ts\n * // Framework-specific imports (recommended)\n * import { editFileTool } from 'morphsdk/tools/anthropic';\n * import { editFileTool } from 'morphsdk/tools/openai';\n * import { editFileTool } from 'morphsdk/tools/vercel';\n * ```\n */\n\n// Core exports\nexport { executeEditFile, generateUdiff, countChanges, applyEdit } from './core.js';\nexport type {\n EditFileInput,\n EditFileResult,\n EditFileConfig,\n EditChanges,\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n} from './types.js';\n\n// Prompt exports\nexport {\n EDIT_FILE_TOOL_DESCRIPTION,\n EDIT_FILE_SYSTEM_PROMPT,\n} from './prompts.js';\n\n// Re-export all adapters for convenience\nexport * as anthropic from './anthropic.js';\nexport * as openai from './openai.js';\nexport * as vercel from './vercel.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 * 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 * 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 * 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 * 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"],"mappings":";;;;;;;;;;;;;;;;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A,MACxD;AAEA,aAAO;AAAA,QACL,SAAS;AAAA,QACT,UAAU,OAAO;AAAA,QACjB,SAAS,OAAO;AAAA,QAChB,OAAO,OAAO;AAAA,MAChB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAGA,IAAO,iBAAQF;","names":["resolve","createEditFileTool","editFileTool","execute","formatResult","getSystemPrompt","editFileTool","execute","getSystemPrompt","formatResult","createEditFileTool","createEditFileTool","editFileTool","getSystemPrompt","editFileTool","getSystemPrompt","createEditFileTool"]}
@@ -1,5 +1,5 @@
1
- export { countChanges, executeEditFile, generateUdiff } from './core.js';
2
- export { EditChanges, EditFileConfig, EditFileInput, EditFileResult } from './types.js';
1
+ export { applyEdit, countChanges, executeEditFile, generateUdiff } from './core.js';
2
+ export { ApplyEditConfig, ApplyEditInput, ApplyEditResult, EditChanges, EditFileConfig, EditFileInput, EditFileResult } from './types.js';
3
3
  export { EDIT_FILE_SYSTEM_PROMPT, EDIT_FILE_TOOL_DESCRIPTION } from './prompts.js';
4
4
  export { a as anthropic } from '../../anthropic-DpEAqqZF.js';
5
5
  export { o as openai } from '../../openai-BkKsS30n.js';
@@ -1,18 +1,19 @@
1
1
  import "../../chunk-X2K57BH6.js";
2
2
  import {
3
3
  anthropic_exports
4
- } from "../../chunk-3FTAIJBH.js";
4
+ } from "../../chunk-IUG2FHNN.js";
5
5
  import {
6
6
  openai_exports
7
- } from "../../chunk-G4AWE5A2.js";
7
+ } from "../../chunk-5QIWYEHJ.js";
8
8
  import {
9
9
  vercel_exports
10
- } from "../../chunk-UIZT3KVJ.js";
10
+ } from "../../chunk-QZNGKOCZ.js";
11
11
  import {
12
+ applyEdit,
12
13
  countChanges,
13
14
  executeEditFile,
14
15
  generateUdiff
15
- } from "../../chunk-64PMM72R.js";
16
+ } from "../../chunk-CKTA4AXM.js";
16
17
  import {
17
18
  EDIT_FILE_SYSTEM_PROMPT,
18
19
  EDIT_FILE_TOOL_DESCRIPTION
@@ -23,6 +24,7 @@ export {
23
24
  EDIT_FILE_SYSTEM_PROMPT,
24
25
  EDIT_FILE_TOOL_DESCRIPTION,
25
26
  anthropic_exports as anthropic,
27
+ applyEdit,
26
28
  countChanges,
27
29
  executeEditFile,
28
30
  generateUdiff,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../tools/fastapply/openai.ts","../../../tools/fastapply/core.ts","../../../tools/utils/resilience.ts","../../../tools/fastapply/prompts.ts"],"sourcesContent":["/**\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 * 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} 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/**\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 * 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 * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIA,sBAAoC;AACpC,kBAAwC;AACxC,kBAAoC;;;ACOpC,IAAM,uBAA+D;AAAA,EACnE,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,iBAAiB,CAAC,gBAAgB,aAAa,WAAW;AAC5D;AAmBA,eAAsB,eACpB,KACA,SACA,cAA2B,CAAC,GACT;AACnB,QAAM;AAAA,IACJ,aAAa,qBAAqB;AAAA,IAClC,eAAe,qBAAqB;AAAA,IACpC,WAAW,qBAAqB;AAAA,IAChC,oBAAoB,qBAAqB;AAAA,IACzC,kBAAkB,qBAAqB;AAAA,IACvC;AAAA,EACF,IAAI;AAEJ,MAAI,YAA0B;AAC9B,MAAI,QAAQ;AAEZ,WAAS,UAAU,GAAG,WAAW,YAAY,WAAW;AACtD,QAAI;AACF,YAAM,WAAW,MAAM,MAAM,KAAK,OAAO;AAGzC,UAAI,SAAS,WAAW,OAAO,SAAS,WAAW,KAAK;AACtD,YAAI,UAAU,YAAY;AAExB,gBAAM,aAAa,SAAS,QAAQ,IAAI,aAAa;AACrD,gBAAM,WAAW,aACb,SAAS,UAAU,IAAI,MACvB,KAAK,IAAI,OAAO,QAAQ;AAE5B,gBAAM,QAAQ,IAAI,MAAM,QAAQ,SAAS,MAAM,oBAAoB,QAAQ,IAAI;AAC/E,cAAI,SAAS;AACX,oBAAQ,UAAU,GAAG,KAAK;AAAA,UAC5B;AAEA,gBAAM,MAAM,QAAQ;AACpB,mBAAS;AACT;AAAA,QACF;AAAA,MACF;AAEA,aAAO;AAAA,IACT,SAAS,OAAO;AACd,kBAAY;AAGZ,YAAM,cAAc,gBAAgB;AAAA,QAAK,aACvC,WAAW,SAAS,SAA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ACA,iBAAiB,MAAc;AAC7B,aAAO,gBAAgB;AAAA,IACzB;AAAA,EACF,CAAC;AACH;AAGA,IAAO,iBAAQ;","names":["resolve"]}
1
+ {"version":3,"sources":["../../../tools/fastapply/openai.ts","../../../tools/fastapply/core.ts","../../../tools/utils/resilience.ts","../../../tools/fastapply/prompts.ts"],"sourcesContent":["/**\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 * 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 * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIA,sBAAoC;AACpC,kBAAwC;AACxC,kBAAoC;;;ACOpC,IAAM,uBAA+D;AAAA,EACnE,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,iBAAiB,CAAC,gBAAgB,aAAa,WAAW;AAC5D;AAmBA,eAAsB,eACpB,KACA,SACA,cAA2B,CAAC,GACT;AACnB,QAAM;AAAA,IACJ,aAAa,qBAAqB;AAAA,IAClC,eAAe,qBAAqB;AAAA,IACpC,WAAW,qBAAqB;AAAA,IAChC,oBAAoB,qBAAqB;AAAA,IACzC,kBAAkB,qBAAqB;AAAA,IACvC;AAAA,EACF,IAAI;AAEJ,MAAI,YAA0B;AAC9B,MAAI,QAAQ;AAEZ,WAAS,UAAU,GAAG,WAAW,YAAY,WAAW;AACtD,QAAI;AACF,YAAM,WAAW,MAAM,MAAM,KAAK,OAAO;AAGzC,UAAI,SAAS,WAAW,OAAO,SAAS,WAAW,KAAK;AACtD,YAAI,UAAU,YAAY;AAExB,gBAAM,aAAa,SAAS,QAAQ,IAAI,aAAa;AACrD,gBAAM,WAAW,aACb,SAAS,UAAU,IAAI,MACvB,KAAK,IAAI,OAAO,QAAQ;AAE5B,gBAAM,QAAQ,IAAI,MAAM,QAAQ,SAAS,MAAM,oBAAoB,QAAQ,IAAI;AAC/E,cAAI,SAAS;AACX,oBAAQ,UAAU,GAAG,KAAK;AAAA,UAC5B;AAEA,gBAAM,MAAM,QAAQ;AACpB,mBAAS;AACT;AAAA,QACF;AAAA,MACF;AAEA,aAA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aAAa,MAAM;AAAA,IACpC;AAAA,IACA,cAAc,CAAC,WAAmC;AAChD,aAAO,aAAa,MAAM;AAAA,IAC5B;AAAA,IACA,iBAAiB,MAAc;AAC7B,aAAO,gBAAgB;AAAA,IACzB;AAAA,EACF,CAAC;AACH;AAGA,IAAO,iBAAQ;","names":["resolve"]}
@@ -5,8 +5,8 @@ import {
5
5
  formatResult,
6
6
  getSystemPrompt,
7
7
  openai_default
8
- } from "../../chunk-G4AWE5A2.js";
9
- import "../../chunk-64PMM72R.js";
8
+ } from "../../chunk-5QIWYEHJ.js";
9
+ import "../../chunk-CKTA4AXM.js";
10
10
  import "../../chunk-63WE2C5R.js";
11
11
  import "../../chunk-4VWJFZVS.js";
12
12
  import "../../chunk-PZ5AY32C.js";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../tools/fastapply/types.ts"],"sourcesContent":["/**\n * Core types for Morph Fast Apply SDK\n */\n\nimport type { RetryConfig } from '../utils/resilience.js';\n\n/**\n * Input parameters for the edit_file tool\n */\nexport interface EditFileInput {\n /** Path to the file to edit (relative to baseDir) */\n target_filepath: string;\n /** First-person description of what you're changing */\n instructions: string;\n /** Lazy edit with // ... existing code ... markers */\n code_edit: string;\n}\n\n/**\n * Statistics about the changes made\n */\nexport interface EditChanges {\n linesAdded: number;\n linesRemoved: number;\n linesModified: number;\n}\n\n/**\n * Result returned after executing an edit\n */\nexport interface EditFileResult {\n /** Whether the edit was successful */\n success: boolean;\n /** Path to the edited file */\n filepath: string;\n /** Universal diff format showing changes */\n udiff?: string;\n /** Statistics about the changes */\n changes: EditChanges;\n /** Error message if unsuccessful */\n error?: string;\n}\n\n/**\n * Configuration options for the edit_file tool\n */\nexport interface EditFileConfig {\n /** Morph API key (defaults to MORPH_API_KEY env var) */\n morphApiKey?: string;\n /** Morph API base URL */\n morphApiUrl?: string;\n /** Base directory for file operations (defaults to cwd) */\n baseDir?: string;\n /** Whether to generate udiff (default: true) */\n generateUdiff?: boolean;\n /** Whether to automatically write to file (default: true) */\n autoWrite?: boolean;\n /** Custom system prompt (null to disable) */\n systemPrompt?: string | null;\n /** Custom tool description (defaults to EDIT_FILE_TOOL_DESCRIPTION) */\n description?: string;\n /** Timeout for API calls in ms (default: 30000) */\n timeout?: number;\n /** Retry configuration for API calls */\n retryConfig?: RetryConfig;\n /** Enable debug logging (default: false) */\n debug?: boolean;\n}\n\n/**\n * Response from Morph Apply API\n */\nexport interface MorphApplyResponse {\n choices: Array<{\n message: {\n content: string;\n };\n }>;\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
1
+ {"version":3,"sources":["../../../tools/fastapply/types.ts"],"sourcesContent":["/**\n * Core types for Morph Fast Apply SDK\n */\n\nimport type { RetryConfig } from '../utils/resilience.js';\n\n/**\n * Input parameters for the edit_file tool\n */\nexport interface EditFileInput {\n /** Path to the file to edit (relative to baseDir) */\n target_filepath: string;\n /** First-person description of what you're changing */\n instructions: string;\n /** Lazy edit with // ... existing code ... markers */\n code_edit: string;\n}\n\n/**\n * Statistics about the changes made\n */\nexport interface EditChanges {\n linesAdded: number;\n linesRemoved: number;\n linesModified: number;\n}\n\n/**\n * Result returned after executing an edit\n */\nexport interface EditFileResult {\n /** Whether the edit was successful */\n success: boolean;\n /** Path to the edited file */\n filepath: string;\n /** Universal diff format showing changes */\n udiff?: string;\n /** Statistics about the changes */\n changes: EditChanges;\n /** Error message if unsuccessful */\n error?: string;\n}\n\n/**\n * Configuration options for the edit_file tool\n */\nexport interface EditFileConfig {\n /** Morph API key (defaults to MORPH_API_KEY env var) */\n morphApiKey?: string;\n /** Morph API base URL */\n morphApiUrl?: string;\n /** Base directory for file operations (defaults to cwd) */\n baseDir?: string;\n /** Whether to generate udiff (default: true) */\n generateUdiff?: boolean;\n /** Whether to automatically write to file (default: true) */\n autoWrite?: boolean;\n /** Custom system prompt (null to disable) */\n systemPrompt?: string | null;\n /** Custom tool description (defaults to EDIT_FILE_TOOL_DESCRIPTION) */\n description?: string;\n /** Timeout for API calls in ms (default: 30000) */\n timeout?: number;\n /** Retry configuration for API calls */\n retryConfig?: RetryConfig;\n /** Enable debug logging (default: false) */\n debug?: boolean;\n}\n\n/**\n * Response from Morph Apply API\n */\nexport interface MorphApplyResponse {\n choices: Array<{\n message: {\n content: string;\n };\n }>;\n}\n\n/**\n * Input for code-to-code edit (no file I/O)\n * Use this when you manage your own file system or work in a sandbox\n */\nexport interface ApplyEditInput {\n /** The current file contents */\n originalCode: string;\n /** Lazy edit with // ... existing code ... markers */\n codeEdit: string;\n /** First-person description of what you're changing */\n instructions: string;\n /** Optional filepath for context in udiff generation */\n filepath?: string;\n}\n\n/**\n * Configuration for applyEdit (code-to-code, no file I/O)\n */\nexport interface ApplyEditConfig {\n /** Morph API key (defaults to MORPH_API_KEY env var) */\n morphApiKey?: string;\n /** Morph API base URL */\n morphApiUrl?: string;\n /** Whether to generate udiff (default: true) */\n generateUdiff?: boolean;\n /** Timeout for API calls in ms (default: 30000) */\n timeout?: number;\n /** Retry configuration for API calls */\n retryConfig?: RetryConfig;\n /** Enable debug logging (default: false) */\n debug?: boolean;\n}\n\n/**\n * Result from code-to-code edit\n */\nexport interface ApplyEditResult {\n /** Whether the edit was successful */\n success: boolean;\n /** The merged code result */\n mergedCode?: string;\n /** Universal diff format showing changes */\n udiff?: string;\n /** Statistics about the changes */\n changes: EditChanges;\n /** Error message if unsuccessful */\n error?: string;\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -73,5 +73,51 @@ interface MorphApplyResponse {
73
73
  };
74
74
  }>;
75
75
  }
76
+ /**
77
+ * Input for code-to-code edit (no file I/O)
78
+ * Use this when you manage your own file system or work in a sandbox
79
+ */
80
+ interface ApplyEditInput {
81
+ /** The current file contents */
82
+ originalCode: string;
83
+ /** Lazy edit with // ... existing code ... markers */
84
+ codeEdit: string;
85
+ /** First-person description of what you're changing */
86
+ instructions: string;
87
+ /** Optional filepath for context in udiff generation */
88
+ filepath?: string;
89
+ }
90
+ /**
91
+ * Configuration for applyEdit (code-to-code, no file I/O)
92
+ */
93
+ interface ApplyEditConfig {
94
+ /** Morph API key (defaults to MORPH_API_KEY env var) */
95
+ morphApiKey?: string;
96
+ /** Morph API base URL */
97
+ morphApiUrl?: string;
98
+ /** Whether to generate udiff (default: true) */
99
+ generateUdiff?: boolean;
100
+ /** Timeout for API calls in ms (default: 30000) */
101
+ timeout?: number;
102
+ /** Retry configuration for API calls */
103
+ retryConfig?: RetryConfig;
104
+ /** Enable debug logging (default: false) */
105
+ debug?: boolean;
106
+ }
107
+ /**
108
+ * Result from code-to-code edit
109
+ */
110
+ interface ApplyEditResult {
111
+ /** Whether the edit was successful */
112
+ success: boolean;
113
+ /** The merged code result */
114
+ mergedCode?: string;
115
+ /** Universal diff format showing changes */
116
+ udiff?: string;
117
+ /** Statistics about the changes */
118
+ changes: EditChanges;
119
+ /** Error message if unsuccessful */
120
+ error?: string;
121
+ }
76
122
 
77
- export type { EditChanges, EditFileConfig, EditFileInput, EditFileResult, MorphApplyResponse };
123
+ export type { ApplyEditConfig, ApplyEditInput, ApplyEditResult, EditChanges, EditFileConfig, EditFileInput, EditFileResult, MorphApplyResponse };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../tools/fastapply/vercel.ts","../../../tools/fastapply/core.ts","../../../tools/utils/resilience.ts","../../../tools/fastapply/prompts.ts"],"sourcesContent":["/**\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 * 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} 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/**\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 * 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 * 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.`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BAAgB;AAAA,MACnC,iBAAiB,OAAO;AAAA,MACxB,cAAc,OAAO;AAAA,MACrB,WAAW,OAAO;AAAA,IACpB,CAAC;AAED,QAAI,CAAC,OAAO,SAAS;AACnB,YAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,IACxD;AAEA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,UAAU,OAAO;AAAA,MACjB,SAAS,OAAO;AAAA,MAChB,OAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF,CAAC;AAiBM,SAAS,kBAA0B;AACxC,SAAO;AACT;AAuBO,SAAS,mBAAmB,SAAyB,CAAC,GAAG;AAC9D,QAAM,SAAS,aAAE,OAAO;AAAA,IACtB,iBAAiB,aAAE,OAAO,EAAE,SAAS,uCAAuC;AAAA,IAC5E,cAAc,aACX,OAAO,EACP,SAAS,mEAAmE;AAAA,IAC/E,WAAW,aACR,OAAO,EACP,SAAS,qDAAqD;AAAA,EACnE,CAAC;AAED,aAAO,gBAAK;AAAA,IACV,aAAa,OAAO,eAAe;AAAA,IACnC,aAAa;AAAA,IACb,SAAS,OAAO,WAAW;AACzB,YAAM,SAAS,MAAM;AAAA,QACnB;AAAA,UACE,iBAAiB,OAAO;AAAA,UACxB,cAAc,OAAO;AAAA,UACrB,WAAW,OAAO;AAAA,QACpB;AAAA,QACA;AAAA,MACF;AAEA,UAAI,CAAC,OAAO,SAAS;AACnB,cAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,MACxD;AAEA,aAAO;AAAA,QACL,SAAS;AAAA,QACT,UAAU,OAAO;AAAA,QACjB,SAAS,OAAO;AAAA,QAChB,OAAO,OAAO;AAAA,MAChB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAGA,IAAO,iBAAQ;","names":["resolve"]}
1
+ {"version":3,"sources":["../../../tools/fastapply/vercel.ts","../../../tools/fastapply/core.ts","../../../tools/utils/resilience.ts","../../../tools/fastapply/prompts.ts"],"sourcesContent":["/**\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 * 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 * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,gBAAqB;AACrB,iBAAkB;;;ACDlB,sBAAoC;AACpC,kBAAwC;AACxC,kBAAoC;;;ACOpC,IAAM,uBAA+D;AAAA,EACnE,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,iBAAiB,CAAC,gBAAgB,aAAa,WAAW;AAC5D;AAmBA,eAAsB,eACpB,KACA,SACA,cAA2B,CAAC,GACT;AACnB,QAAM;AAAA,IACJ,aAAa,qBAAqB;AAAA,IAClC,eAAe,qBAAqB;AAAA,IACpC,WAAW,qBAAqB;AAAA,IAChC,oBAAoB,qBAAqB;AAAA,IACzC,kBAAkB,qBAAqB;AAAA,IACvC;AAAA,EACF,IAAI;AAEJ,MAAI,YAA0B;AAC9B,MAAI,QAAQ;AAEZ,WAAS,UAAU,GAAG,WAAW,YAAY,WAAW;AACtD,QAAI;AACF,YAAM,WAAW,MAAM,MAAM,KAAK,OAAO;AAGzC,UAAI,SAAS,WAAW,OAAO,SAAS,WAAW,K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