@morphllm/morphsdk 0.2.28 → 0.2.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/anthropic-DpEAqqZF.d.ts +88 -0
- package/dist/{chunk-LN4CTQZG.js → chunk-4OBDFXR4.js} +4 -4
- package/dist/{chunk-S3HTYGYF.js → chunk-B4H7N4GZ.js} +14 -2
- package/dist/chunk-B4H7N4GZ.js.map +1 -0
- package/dist/{chunk-YSBSDU75.js → chunk-BGDEQTRF.js} +4 -4
- package/dist/{chunk-EAA7D24N.js → chunk-JJ5ONKDN.js} +7 -7
- package/dist/{chunk-CMKITT6X.js → chunk-U6ZHZ5LY.js} +10 -10
- package/dist/{chunk-W5CHJ6OX.js → chunk-VD7US3AJ.js} +4 -4
- package/dist/client.d.ts +114 -0
- package/dist/client.js +4 -4
- package/dist/git/client.d.ts +261 -0
- package/dist/git/config.d.ts +11 -0
- package/dist/git/index.d.ts +5 -0
- package/dist/git/types.d.ts +102 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +10 -10
- package/dist/modelrouter/core.d.ts +56 -0
- package/dist/modelrouter/index.d.ts +2 -0
- package/dist/modelrouter/types.d.ts +35 -0
- package/dist/openai-BkKsS30n.d.ts +111 -0
- package/dist/tools/browser/anthropic.d.ts +51 -0
- package/dist/tools/browser/core.d.ts +203 -0
- package/dist/tools/browser/index.d.ts +72 -0
- package/dist/tools/browser/openai.d.ts +73 -0
- package/dist/tools/browser/prompts.d.ts +7 -0
- package/dist/tools/browser/types.d.ts +255 -0
- package/dist/tools/browser/vercel.d.ts +69 -0
- package/dist/tools/codebase_search/anthropic.d.ts +40 -0
- package/dist/tools/codebase_search/core.d.ts +40 -0
- package/dist/tools/codebase_search/index.d.ts +10 -0
- package/dist/tools/codebase_search/index.js +3 -3
- package/dist/tools/codebase_search/openai.d.ts +87 -0
- package/dist/tools/codebase_search/prompts.d.ts +7 -0
- package/dist/tools/codebase_search/types.d.ts +50 -0
- package/dist/tools/codebase_search/vercel.d.ts +65 -0
- package/dist/tools/fastapply/anthropic.cjs +14 -2
- package/dist/tools/fastapply/anthropic.cjs.map +1 -1
- package/dist/tools/fastapply/anthropic.d.ts +4 -0
- package/dist/tools/fastapply/anthropic.js +9 -3
- package/dist/tools/fastapply/core.d.ts +41 -0
- package/dist/tools/fastapply/index.cjs +18 -9
- package/dist/tools/fastapply/index.cjs.map +1 -1
- package/dist/tools/fastapply/index.d.ts +10 -0
- package/dist/tools/fastapply/index.js +4 -4
- package/dist/tools/fastapply/openai.d.ts +4 -0
- package/dist/tools/fastapply/prompts.d.ts +7 -0
- package/dist/tools/fastapply/types.d.ts +77 -0
- package/dist/tools/fastapply/vercel.d.ts +4 -0
- package/dist/tools/index.cjs +18 -9
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.ts +10 -0
- package/dist/tools/index.js +4 -4
- package/dist/tools/utils/resilience.d.ts +58 -0
- package/dist/tools/warp_grep/agent/config.d.ts +8 -0
- package/dist/tools/warp_grep/agent/formatter.d.ts +14 -0
- package/dist/tools/warp_grep/agent/grep_helpers.d.ts +16 -0
- package/dist/tools/warp_grep/agent/parser.d.ts +16 -0
- package/dist/tools/warp_grep/agent/prompt.d.ts +4 -0
- package/dist/tools/warp_grep/agent/runner.d.ts +10 -0
- package/dist/tools/warp_grep/agent/runner.js +3 -3
- package/dist/tools/warp_grep/agent/types.cjs.map +1 -1
- package/dist/tools/warp_grep/agent/types.d.ts +44 -0
- package/dist/tools/warp_grep/anthropic.d.ts +14 -0
- package/dist/tools/warp_grep/anthropic.js +5 -5
- package/dist/tools/warp_grep/index.d.ts +11 -0
- package/dist/tools/warp_grep/index.js +9 -9
- package/dist/tools/warp_grep/openai.d.ts +33 -0
- package/dist/tools/warp_grep/openai.js +5 -5
- package/dist/tools/warp_grep/providers/command.d.ts +48 -0
- package/dist/tools/warp_grep/providers/local.d.ts +30 -0
- package/dist/tools/warp_grep/providers/types.d.ts +49 -0
- package/dist/tools/warp_grep/tools/analyse.d.ts +10 -0
- package/dist/tools/warp_grep/tools/finish.d.ts +10 -0
- package/dist/tools/warp_grep/tools/grep.d.ts +8 -0
- package/dist/tools/warp_grep/tools/read.d.ts +9 -0
- package/dist/tools/warp_grep/utils/files.d.ts +3 -0
- package/dist/tools/warp_grep/utils/format.d.ts +4 -0
- package/dist/tools/warp_grep/utils/paths.d.ts +7 -0
- package/dist/tools/warp_grep/utils/ripgrep.d.ts +11 -0
- package/dist/tools/warp_grep/vercel.d.ts +33 -0
- package/dist/tools/warp_grep/vercel.js +5 -5
- package/dist/vercel-B1GZ_g9N.d.ts +69 -0
- package/package.json +1 -1
- package/dist/chunk-S3HTYGYF.js.map +0 -1
- /package/dist/{chunk-LN4CTQZG.js.map → chunk-4OBDFXR4.js.map} +0 -0
- /package/dist/{chunk-YSBSDU75.js.map → chunk-BGDEQTRF.js.map} +0 -0
- /package/dist/{chunk-EAA7D24N.js.map → chunk-JJ5ONKDN.js.map} +0 -0
- /package/dist/{chunk-CMKITT6X.js.map → chunk-U6ZHZ5LY.js.map} +0 -0
- /package/dist/{chunk-W5CHJ6OX.js.map → chunk-VD7US3AJ.js.map} +0 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { RetryConfig } from '../utils/resilience.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Core types for Morph Fast Apply SDK
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Input parameters for the edit_file tool
|
|
9
|
+
*/
|
|
10
|
+
interface EditFileInput {
|
|
11
|
+
/** Path to the file to edit (relative to baseDir) */
|
|
12
|
+
target_filepath: string;
|
|
13
|
+
/** First-person description of what you're changing */
|
|
14
|
+
instructions: string;
|
|
15
|
+
/** Lazy edit with // ... existing code ... markers */
|
|
16
|
+
code_edit: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Statistics about the changes made
|
|
20
|
+
*/
|
|
21
|
+
interface EditChanges {
|
|
22
|
+
linesAdded: number;
|
|
23
|
+
linesRemoved: number;
|
|
24
|
+
linesModified: number;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Result returned after executing an edit
|
|
28
|
+
*/
|
|
29
|
+
interface EditFileResult {
|
|
30
|
+
/** Whether the edit was successful */
|
|
31
|
+
success: boolean;
|
|
32
|
+
/** Path to the edited file */
|
|
33
|
+
filepath: string;
|
|
34
|
+
/** Universal diff format showing changes */
|
|
35
|
+
udiff?: string;
|
|
36
|
+
/** Statistics about the changes */
|
|
37
|
+
changes: EditChanges;
|
|
38
|
+
/** Error message if unsuccessful */
|
|
39
|
+
error?: string;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Configuration options for the edit_file tool
|
|
43
|
+
*/
|
|
44
|
+
interface EditFileConfig {
|
|
45
|
+
/** Morph API key (defaults to MORPH_API_KEY env var) */
|
|
46
|
+
morphApiKey?: string;
|
|
47
|
+
/** Morph API base URL */
|
|
48
|
+
morphApiUrl?: string;
|
|
49
|
+
/** Base directory for file operations (defaults to cwd) */
|
|
50
|
+
baseDir?: string;
|
|
51
|
+
/** Whether to generate udiff (default: true) */
|
|
52
|
+
generateUdiff?: boolean;
|
|
53
|
+
/** Whether to automatically write to file (default: true) */
|
|
54
|
+
autoWrite?: boolean;
|
|
55
|
+
/** Custom system prompt (null to disable) */
|
|
56
|
+
systemPrompt?: string | null;
|
|
57
|
+
/** Custom tool description (defaults to EDIT_FILE_TOOL_DESCRIPTION) */
|
|
58
|
+
description?: string;
|
|
59
|
+
/** Timeout for API calls in ms (default: 30000) */
|
|
60
|
+
timeout?: number;
|
|
61
|
+
/** Retry configuration for API calls */
|
|
62
|
+
retryConfig?: RetryConfig;
|
|
63
|
+
/** Enable debug logging (default: false) */
|
|
64
|
+
debug?: boolean;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Response from Morph Apply API
|
|
68
|
+
*/
|
|
69
|
+
interface MorphApplyResponse {
|
|
70
|
+
choices: Array<{
|
|
71
|
+
message: {
|
|
72
|
+
content: string;
|
|
73
|
+
};
|
|
74
|
+
}>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export type { EditChanges, EditFileConfig, EditFileInput, EditFileResult, MorphApplyResponse };
|
package/dist/tools/index.cjs
CHANGED
|
@@ -282,7 +282,10 @@ These edit codeblocks are also read by a less intelligent language model, colloq
|
|
|
282
282
|
var anthropic_exports = {};
|
|
283
283
|
__export(anthropic_exports, {
|
|
284
284
|
createEditFileTool: () => createEditFileTool,
|
|
285
|
-
editFileTool: () => editFileTool
|
|
285
|
+
editFileTool: () => editFileTool,
|
|
286
|
+
execute: () => execute,
|
|
287
|
+
formatResult: () => formatResult,
|
|
288
|
+
getSystemPrompt: () => getSystemPrompt
|
|
286
289
|
});
|
|
287
290
|
var editFileTool = {
|
|
288
291
|
name: "edit_file",
|
|
@@ -342,6 +345,12 @@ function createEditFileTool(config = {}) {
|
|
|
342
345
|
}
|
|
343
346
|
});
|
|
344
347
|
}
|
|
348
|
+
async function execute(input, config) {
|
|
349
|
+
return executeEditFile(input, config);
|
|
350
|
+
}
|
|
351
|
+
function getSystemPrompt() {
|
|
352
|
+
return EDIT_FILE_SYSTEM_PROMPT;
|
|
353
|
+
}
|
|
345
354
|
|
|
346
355
|
// tools/fastapply/openai.ts
|
|
347
356
|
var openai_exports = {};
|
|
@@ -349,9 +358,9 @@ __export(openai_exports, {
|
|
|
349
358
|
createEditFileTool: () => createEditFileTool2,
|
|
350
359
|
default: () => openai_default,
|
|
351
360
|
editFileTool: () => editFileTool2,
|
|
352
|
-
execute: () =>
|
|
361
|
+
execute: () => execute2,
|
|
353
362
|
formatResult: () => formatResult2,
|
|
354
|
-
getSystemPrompt: () =>
|
|
363
|
+
getSystemPrompt: () => getSystemPrompt2
|
|
355
364
|
});
|
|
356
365
|
var editFileTool2 = {
|
|
357
366
|
type: "function",
|
|
@@ -378,10 +387,10 @@ var editFileTool2 = {
|
|
|
378
387
|
}
|
|
379
388
|
}
|
|
380
389
|
};
|
|
381
|
-
async function
|
|
390
|
+
async function execute2(input, config) {
|
|
382
391
|
return executeEditFile(input, config);
|
|
383
392
|
}
|
|
384
|
-
function
|
|
393
|
+
function getSystemPrompt2() {
|
|
385
394
|
return EDIT_FILE_SYSTEM_PROMPT;
|
|
386
395
|
}
|
|
387
396
|
function formatResult2(result) {
|
|
@@ -416,13 +425,13 @@ function createEditFileTool2(config = {}) {
|
|
|
416
425
|
return Object.assign({}, toolDef, {
|
|
417
426
|
execute: async (input) => {
|
|
418
427
|
const parsedInput = typeof input === "string" ? JSON.parse(input) : input;
|
|
419
|
-
return
|
|
428
|
+
return execute2(parsedInput, config);
|
|
420
429
|
},
|
|
421
430
|
formatResult: (result) => {
|
|
422
431
|
return formatResult2(result);
|
|
423
432
|
},
|
|
424
433
|
getSystemPrompt: () => {
|
|
425
|
-
return
|
|
434
|
+
return getSystemPrompt2();
|
|
426
435
|
}
|
|
427
436
|
});
|
|
428
437
|
}
|
|
@@ -434,7 +443,7 @@ __export(vercel_exports, {
|
|
|
434
443
|
createEditFileTool: () => createEditFileTool3,
|
|
435
444
|
default: () => vercel_default,
|
|
436
445
|
editFileTool: () => editFileTool3,
|
|
437
|
-
getSystemPrompt: () =>
|
|
446
|
+
getSystemPrompt: () => getSystemPrompt3
|
|
438
447
|
});
|
|
439
448
|
var import_ai = require("ai");
|
|
440
449
|
var import_zod = require("zod");
|
|
@@ -463,7 +472,7 @@ var editFileTool3 = (0, import_ai.tool)({
|
|
|
463
472
|
};
|
|
464
473
|
}
|
|
465
474
|
});
|
|
466
|
-
function
|
|
475
|
+
function getSystemPrompt3() {
|
|
467
476
|
return EDIT_FILE_SYSTEM_PROMPT;
|
|
468
477
|
}
|
|
469
478
|
function createEditFileTool3(config = {}) {
|
package/dist/tools/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../tools/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 SDK Tools\n * \n * @example\n * ```ts\n * // Import framework-specific tools\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// Re-export fastapply tools\nexport * from './fastapply/index.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 const originalCode = await readFile(fullPath, 'utf-8');\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 */\nfunction 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 * 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,I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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","formatResult","editFileTool","formatResult","createEditFileTool","createEditFileTool","editFileTool","getSystemPrompt","editFileTool","getSystemPrompt","createEditFileTool"]}
|
|
1
|
+
{"version":3,"sources":["../../tools/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 SDK Tools\n * \n * @example\n * ```ts\n * // Import framework-specific tools\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// Re-export fastapply tools\nexport * from './fastapply/index.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 const originalCode = await readFile(fullPath, 'utf-8');\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,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;A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B,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,SAASC,mBAA0B;AACxC,SAAO;AACT;AAuBO,SAASC,oBAAmB,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,iBAAQF;","names":["resolve","createEditFileTool","editFileTool","execute","formatResult","getSystemPrompt","editFileTool","execute","getSystemPrompt","formatResult","createEditFileTool","createEditFileTool","editFileTool","getSystemPrompt","editFileTool","getSystemPrompt","createEditFileTool"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { countChanges, executeEditFile, generateUdiff } from './fastapply/core.js';
|
|
2
|
+
export { EditChanges, EditFileConfig, EditFileInput, EditFileResult } from './fastapply/types.js';
|
|
3
|
+
export { EDIT_FILE_SYSTEM_PROMPT, EDIT_FILE_TOOL_DESCRIPTION } from './fastapply/prompts.js';
|
|
4
|
+
export { a as anthropic } from '../anthropic-DpEAqqZF.js';
|
|
5
|
+
export { o as openai } from '../openai-BkKsS30n.js';
|
|
6
|
+
export { v as vercel } from '../vercel-B1GZ_g9N.js';
|
|
7
|
+
import './utils/resilience.js';
|
|
8
|
+
import '@anthropic-ai/sdk/resources/messages';
|
|
9
|
+
import 'openai/resources/chat/completions';
|
|
10
|
+
import 'ai';
|
package/dist/tools/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import "../chunk-X2K57BH6.js";
|
|
2
|
+
import {
|
|
3
|
+
openai_exports
|
|
4
|
+
} from "../chunk-OZMHDB6O.js";
|
|
2
5
|
import {
|
|
3
6
|
vercel_exports
|
|
4
7
|
} from "../chunk-Y5RCNDLV.js";
|
|
5
8
|
import {
|
|
6
9
|
anthropic_exports
|
|
7
|
-
} from "../chunk-
|
|
8
|
-
import {
|
|
9
|
-
openai_exports
|
|
10
|
-
} from "../chunk-OZMHDB6O.js";
|
|
10
|
+
} from "../chunk-B4H7N4GZ.js";
|
|
11
11
|
import {
|
|
12
12
|
EDIT_FILE_SYSTEM_PROMPT,
|
|
13
13
|
EDIT_FILE_TOOL_DESCRIPTION
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resilience utilities for retry logic and timeout handling
|
|
3
|
+
*/
|
|
4
|
+
interface RetryConfig {
|
|
5
|
+
maxRetries?: number;
|
|
6
|
+
initialDelay?: number;
|
|
7
|
+
maxDelay?: number;
|
|
8
|
+
backoffMultiplier?: number;
|
|
9
|
+
retryableErrors?: string[];
|
|
10
|
+
onRetry?: (attempt: number, error: Error) => void;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Retry a fetch request with exponential backoff
|
|
14
|
+
*
|
|
15
|
+
* @param url - Request URL
|
|
16
|
+
* @param options - Fetch options
|
|
17
|
+
* @param retryConfig - Retry configuration
|
|
18
|
+
* @returns Response from fetch
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```typescript
|
|
22
|
+
* const response = await fetchWithRetry(
|
|
23
|
+
* 'https://api.example.com/data',
|
|
24
|
+
* { method: 'POST', body: JSON.stringify(data) },
|
|
25
|
+
* { maxRetries: 5, initialDelay: 500 }
|
|
26
|
+
* );
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
declare function fetchWithRetry(url: string, options: RequestInit, retryConfig?: RetryConfig): Promise<Response>;
|
|
30
|
+
/**
|
|
31
|
+
* Add timeout to any promise
|
|
32
|
+
*
|
|
33
|
+
* @param promise - Promise to wrap with timeout
|
|
34
|
+
* @param timeoutMs - Timeout in milliseconds
|
|
35
|
+
* @param errorMessage - Optional custom error message
|
|
36
|
+
* @returns Promise that rejects if timeout is reached
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```typescript
|
|
40
|
+
* const result = await withTimeout(
|
|
41
|
+
* fetchData(),
|
|
42
|
+
* 5000,
|
|
43
|
+
* 'Data fetch timed out'
|
|
44
|
+
* );
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
declare function withTimeout<T>(promise: Promise<T>, timeoutMs: number, errorMessage?: string): Promise<T>;
|
|
48
|
+
/**
|
|
49
|
+
* Unified error type for all tools
|
|
50
|
+
*/
|
|
51
|
+
declare class MorphError extends Error {
|
|
52
|
+
code: string;
|
|
53
|
+
statusCode?: number | undefined;
|
|
54
|
+
retryable: boolean;
|
|
55
|
+
constructor(message: string, code: string, statusCode?: number | undefined, retryable?: boolean);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export { MorphError, type RetryConfig, fetchWithRetry, withTimeout };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
declare class ToolOutputFormatter {
|
|
2
|
+
format(toolName: string, args: Record<string, unknown> | null | undefined, output: string, options?: {
|
|
3
|
+
isError?: boolean;
|
|
4
|
+
}): string;
|
|
5
|
+
private formatRead;
|
|
6
|
+
private formatAnalyse;
|
|
7
|
+
private formatGrep;
|
|
8
|
+
private asString;
|
|
9
|
+
}
|
|
10
|
+
declare function formatAgentToolOutput(toolName: string, args: Record<string, unknown> | null | undefined, output: string, options?: {
|
|
11
|
+
isError?: boolean;
|
|
12
|
+
}): string;
|
|
13
|
+
|
|
14
|
+
export { ToolOutputFormatter, formatAgentToolOutput };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
interface GrepMatch {
|
|
2
|
+
path: string;
|
|
3
|
+
lineNumber: number;
|
|
4
|
+
content: string;
|
|
5
|
+
}
|
|
6
|
+
declare class GrepState {
|
|
7
|
+
private readonly seenLines;
|
|
8
|
+
isNew(path: string, lineNumber: number): boolean;
|
|
9
|
+
add(path: string, lineNumber: number): void;
|
|
10
|
+
private makeKey;
|
|
11
|
+
}
|
|
12
|
+
declare const MAX_GREP_OUTPUT_CHARS_PER_TURN = 60000;
|
|
13
|
+
declare function parseAndFilterGrepOutput(rawOutput: string, state: GrepState): GrepMatch[];
|
|
14
|
+
declare function formatTurnGrepOutput(matches: GrepMatch[], maxChars?: number): string;
|
|
15
|
+
|
|
16
|
+
export { type GrepMatch, GrepState, MAX_GREP_OUTPUT_CHARS_PER_TURN, formatTurnGrepOutput, parseAndFilterGrepOutput };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ToolCall } from './types.js';
|
|
2
|
+
|
|
3
|
+
declare class LLMResponseParseError extends Error {
|
|
4
|
+
constructor(message: string);
|
|
5
|
+
}
|
|
6
|
+
declare class LLMResponseParser {
|
|
7
|
+
private readonly finishSpecSplitRe;
|
|
8
|
+
parse(text: string): ToolCall[];
|
|
9
|
+
private splitLine;
|
|
10
|
+
private handleAnalyse;
|
|
11
|
+
private handleGrep;
|
|
12
|
+
private handleRead;
|
|
13
|
+
private handleFinish;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export { LLMResponseParseError, LLMResponseParser };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
declare const SYSTEM_PROMPT = "You are a code search agent. Your task is to find relevant code snippets based on a search query.\n\n<workflow>\nYou operate in exactly 3 rounds of tool exploration, followed by a final answer:\n\n1. In each round, you can make MULTIPLE tool calls (up to 8) to search in parallel. All tool results will be returned together after each round.\n2. After your third round of tool calls, your next turn MUST be a single call to the `finish` tool with all the context you have found.\n</workflow>\n\n<tool_calling>\nYou have tools at your disposal to solve the coding task. Follow these rules regarding tool calls:\n\n### 1. `analyse` - Explore Directories\nExplore directory structure in a tree-like format.\n**Syntax:** `analyse <path> [pattern]`\n- `<path>`: Directory path to analyze (defaults to `.`)\n- `[pattern]`: Optional regex pattern to filter names\n\nFor example:\n```\nanalyse src/api\nanalyse . \"test\"\n```\n\n### 2. `read` - Read File Contents\nRead entire files or specific line ranges.\n**Syntax:** `read <path>[:start-end]`\n- `<path>`: File path to read\n- `[:start-end]`: Optional 1-based, inclusive line range\n\nFor example:\n```\nread src/main.py\nread src/database/connection.py:10-50\n```\n\n### 3. `grep` - Search with Regex\nSearch for regex patterns across files using ripgrep.\n**Syntax:** `grep '<pattern>' <path>`\n- `'<pattern>'`: Regex pattern (always wrap in single quotes)\n- `<path>`: Directory or file to search (use `.` for the repo root)\n\nFor example:\n```\ngrep 'create_user' .\ngrep 'import.*requests' src/api\ngrep 'class\\\\s+AuthService' controllers/auth.py\n```\n\n### 4. `finish` - Submit Final Answer\nSubmit your findings when complete.\n**Syntax:** `finish <file1:range1,range2...> [file2:range3...]`\n- Provide file paths with colon-separated, comma-separated line ranges\n\nFor example:\n```\nfinish src/api/auth.py:25-50,75-80 src/models/user.py:10-15\n```\n</tool_calling>\n\n<strategy>\n- Use the `analyse`, `grep`, and `read` tools to gather information about the codebase.\n- Leverage the tools smartly to make full use of their potential\n- Make parallel tool calls within each round to investigate multiple paths or files efficiently\n- Be systematic and thorough within your 3-round limit\n</strategy>\n\n<output_format>\n- Only output tool calls themselves\n- Do not include explanatory text, reasoning, or commentary\n- Each tool call should be on its own line\n- After 3 rounds of exploration, call `finish` with all relevant code snippets you found\n</output_format>\n\nBegin your exploration now to find code relevant to the query.";
|
|
2
|
+
declare function getSystemPrompt(): string;
|
|
3
|
+
|
|
4
|
+
export { SYSTEM_PROMPT, getSystemPrompt };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { SessionConfig, AgentRunResult } from './types.js';
|
|
2
|
+
import { WarpGrepProvider } from '../providers/types.js';
|
|
3
|
+
|
|
4
|
+
type EventName = 'initial_state' | 'round_start' | 'round_end' | 'finish' | 'error';
|
|
5
|
+
type EventCallback = (name: EventName, payload: Record<string, unknown>) => void;
|
|
6
|
+
declare function runWarpGrep(config: SessionConfig & {
|
|
7
|
+
provider: WarpGrepProvider;
|
|
8
|
+
}): Promise<AgentRunResult>;
|
|
9
|
+
|
|
10
|
+
export { type EventCallback, runWarpGrep };
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
runWarpGrep
|
|
3
|
-
} from "../../../chunk-
|
|
4
|
-
import "../../../chunk-Z2FBMSNE.js";
|
|
5
|
-
import "../../../chunk-HKZB23U7.js";
|
|
3
|
+
} from "../../../chunk-JJ5ONKDN.js";
|
|
6
4
|
import "../../../chunk-73RQWOQC.js";
|
|
7
5
|
import "../../../chunk-EK7OQPWD.js";
|
|
6
|
+
import "../../../chunk-Z2FBMSNE.js";
|
|
7
|
+
import "../../../chunk-HKZB23U7.js";
|
|
8
8
|
import "../../../chunk-AFEPUNAO.js";
|
|
9
9
|
import "../../../chunk-TICMYDII.js";
|
|
10
10
|
import "../../../chunk-NDZO5IPV.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../tools/warp_grep/agent/types.ts"],"sourcesContent":["// Core types for morph-warp-grep agent\n\nexport type ChatMessage = {\n role: 'system' | 'user' | 'assistant';\n content: string;\n};\n\nexport type ToolName = 'analyse' | 'grep' | 'glob' | 'read' | 'finish';\n\nexport type ToolCall = {\n name: ToolName;\n arguments?: Record<string, unknown>;\n};\n\nexport type FinishFileSpec = {\n path: string;\n lines: Array<[number, number]>;\n};\n\nexport type AgentFinish = {\n files: FinishFileSpec[];\n};\n\nexport type AgentRunResult = {\n terminationReason: 'completed' | 'terminated' | 'error';\n messages: ChatMessage[];\n finish?: { payload: string; metadata?: AgentFinish };\n errors?: Array<{ message: string }>;\n};\n\nexport type SessionConfig = {\n query: string;\n model?: string;\n repoRoot: string;\n excludes?: string[];\n includes?: string[];\n debug?: boolean;\n provider?: unknown; // late-bound to provider interface to avoid cycles\n apiKey?: string;\n};\n\n\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../tools/warp_grep/agent/types.ts"],"sourcesContent":["// Core types for morph-warp-grep agent\n\nexport type ChatMessage = {\n role: 'system' | 'user' | 'assistant';\n content: string;\n};\n\nexport type ToolName = 'analyse' | 'grep' | 'glob' | 'read' | 'finish';\n\nexport type ToolCall = {\n name: ToolName;\n arguments?: Record<string, unknown>;\n};\n\nexport type FinishFileSpec = {\n path: string;\n lines: Array<[number, number]>;\n};\n\nexport type AgentFinish = {\n files: FinishFileSpec[];\n};\n\nexport type ResolvedFile = {\n path: string;\n content: string;\n};\n\nexport type AgentRunResult = {\n terminationReason: 'completed' | 'terminated' | 'error';\n messages: ChatMessage[];\n finish?: { \n payload: string; \n metadata?: AgentFinish;\n resolved?: ResolvedFile[];\n };\n errors?: Array<{ message: string }>;\n};\n\nexport type SessionConfig = {\n query: string;\n model?: string;\n repoRoot: string;\n excludes?: string[];\n includes?: string[];\n debug?: boolean;\n provider?: unknown; // late-bound to provider interface to avoid cycles\n apiKey?: string;\n};\n\n\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
type ChatMessage = {
|
|
2
|
+
role: 'system' | 'user' | 'assistant';
|
|
3
|
+
content: string;
|
|
4
|
+
};
|
|
5
|
+
type ToolName = 'analyse' | 'grep' | 'glob' | 'read' | 'finish';
|
|
6
|
+
type ToolCall = {
|
|
7
|
+
name: ToolName;
|
|
8
|
+
arguments?: Record<string, unknown>;
|
|
9
|
+
};
|
|
10
|
+
type FinishFileSpec = {
|
|
11
|
+
path: string;
|
|
12
|
+
lines: Array<[number, number]>;
|
|
13
|
+
};
|
|
14
|
+
type AgentFinish = {
|
|
15
|
+
files: FinishFileSpec[];
|
|
16
|
+
};
|
|
17
|
+
type ResolvedFile = {
|
|
18
|
+
path: string;
|
|
19
|
+
content: string;
|
|
20
|
+
};
|
|
21
|
+
type AgentRunResult = {
|
|
22
|
+
terminationReason: 'completed' | 'terminated' | 'error';
|
|
23
|
+
messages: ChatMessage[];
|
|
24
|
+
finish?: {
|
|
25
|
+
payload: string;
|
|
26
|
+
metadata?: AgentFinish;
|
|
27
|
+
resolved?: ResolvedFile[];
|
|
28
|
+
};
|
|
29
|
+
errors?: Array<{
|
|
30
|
+
message: string;
|
|
31
|
+
}>;
|
|
32
|
+
};
|
|
33
|
+
type SessionConfig = {
|
|
34
|
+
query: string;
|
|
35
|
+
model?: string;
|
|
36
|
+
repoRoot: string;
|
|
37
|
+
excludes?: string[];
|
|
38
|
+
includes?: string[];
|
|
39
|
+
debug?: boolean;
|
|
40
|
+
provider?: unknown;
|
|
41
|
+
apiKey?: string;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export type { AgentFinish, AgentRunResult, ChatMessage, FinishFileSpec, ResolvedFile, SessionConfig, ToolCall, ToolName };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { WarpGrepProvider } from './providers/types.js';
|
|
2
|
+
|
|
3
|
+
type WarpGrepConfig = {
|
|
4
|
+
repoRoot: string;
|
|
5
|
+
provider?: WarpGrepProvider;
|
|
6
|
+
excludes?: string[];
|
|
7
|
+
includes?: string[];
|
|
8
|
+
debug?: boolean;
|
|
9
|
+
apiKey?: string;
|
|
10
|
+
description?: string;
|
|
11
|
+
};
|
|
12
|
+
declare function createMorphWarpGrepTool(config: WarpGrepConfig): any;
|
|
13
|
+
|
|
14
|
+
export { type WarpGrepConfig, createMorphWarpGrepTool };
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createMorphWarpGrepTool
|
|
3
|
-
} from "../../chunk-
|
|
4
|
-
import "../../chunk-
|
|
3
|
+
} from "../../chunk-VD7US3AJ.js";
|
|
4
|
+
import "../../chunk-UYBIKZPM.js";
|
|
5
|
+
import "../../chunk-JJ5ONKDN.js";
|
|
6
|
+
import "../../chunk-73RQWOQC.js";
|
|
7
|
+
import "../../chunk-EK7OQPWD.js";
|
|
5
8
|
import "../../chunk-Z2FBMSNE.js";
|
|
6
9
|
import "../../chunk-HKZB23U7.js";
|
|
7
|
-
import "../../chunk-UYBIKZPM.js";
|
|
8
10
|
import "../../chunk-G2RSY56Q.js";
|
|
9
11
|
import "../../chunk-SMGZ6A64.js";
|
|
10
12
|
import "../../chunk-RSLIOCOE.js";
|
|
11
|
-
import "../../chunk-73RQWOQC.js";
|
|
12
|
-
import "../../chunk-EK7OQPWD.js";
|
|
13
13
|
import "../../chunk-AFEPUNAO.js";
|
|
14
14
|
import "../../chunk-TICMYDII.js";
|
|
15
15
|
import "../../chunk-NDZO5IPV.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { AgentFinish, AgentRunResult, ChatMessage, FinishFileSpec, ResolvedFile, SessionConfig, ToolCall, ToolName } from './agent/types.js';
|
|
2
|
+
export { AGENT_CONFIG, DEFAULT_EXCLUDES, DEFAULT_MODEL } from './agent/config.js';
|
|
3
|
+
export { runWarpGrep } from './agent/runner.js';
|
|
4
|
+
export { AnalyseEntry, GrepResult, ReadResult, WarpGrepProvider } from './providers/types.js';
|
|
5
|
+
export { LocalRipgrepProvider } from './providers/local.js';
|
|
6
|
+
export { CommandExecProvider } from './providers/command.js';
|
|
7
|
+
export { createMorphWarpGrepTool as createOpenAIWarpGrepTool } from './openai.js';
|
|
8
|
+
export { createMorphWarpGrepTool as createAnthropicWarpGrepTool } from './anthropic.js';
|
|
9
|
+
export { createMorphWarpGrepTool as createVercelWarpGrepTool } from './vercel.js';
|
|
10
|
+
import 'openai/resources/chat/completions';
|
|
11
|
+
import 'ai';
|