@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.
- package/dist/{chunk-UU6XCZG3.js → chunk-2XNF3W7C.js} +3 -3
- package/dist/{chunk-FYQUSDOE.js → chunk-563REN2T.js} +3 -3
- package/dist/{chunk-G4AWE5A2.js → chunk-5QIWYEHJ.js} +2 -2
- package/dist/{chunk-YR53PPVM.js → chunk-C4IXE2RM.js} +3 -3
- package/dist/{chunk-64PMM72R.js → chunk-CKTA4AXM.js} +58 -2
- package/dist/chunk-CKTA4AXM.js.map +1 -0
- package/dist/{chunk-L5BMGLLQ.js → chunk-IFVROB4L.js} +21 -14
- package/dist/{chunk-L5BMGLLQ.js.map → chunk-IFVROB4L.js.map} +1 -1
- package/dist/{chunk-3FTAIJBH.js → chunk-IUG2FHNN.js} +2 -2
- package/dist/{chunk-MZT6HVGD.js → chunk-KYVR4QCG.js} +3 -3
- package/dist/{chunk-MZT6HVGD.js.map → chunk-KYVR4QCG.js.map} +1 -1
- package/dist/{chunk-PZDR5ZZ2.js → chunk-NOQCKVY3.js} +9 -9
- package/dist/{chunk-UIZT3KVJ.js → chunk-QZNGKOCZ.js} +2 -2
- package/dist/client.cjs +64 -2
- package/dist/client.cjs.map +1 -1
- package/dist/client.js +15 -15
- package/dist/index.cjs +68 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.js +19 -17
- package/dist/tools/fastapply/anthropic.cjs.map +1 -1
- package/dist/tools/fastapply/anthropic.js +2 -2
- package/dist/tools/fastapply/core.cjs +57 -0
- package/dist/tools/fastapply/core.cjs.map +1 -1
- package/dist/tools/fastapply/core.d.ts +50 -2
- package/dist/tools/fastapply/core.js +3 -1
- package/dist/tools/fastapply/index.cjs +34 -0
- package/dist/tools/fastapply/index.cjs.map +1 -1
- package/dist/tools/fastapply/index.d.ts +2 -2
- package/dist/tools/fastapply/index.js +6 -4
- package/dist/tools/fastapply/openai.cjs.map +1 -1
- package/dist/tools/fastapply/openai.js +2 -2
- package/dist/tools/fastapply/types.cjs.map +1 -1
- package/dist/tools/fastapply/types.d.ts +47 -1
- package/dist/tools/fastapply/vercel.cjs.map +1 -1
- package/dist/tools/fastapply/vercel.js +2 -2
- package/dist/tools/index.cjs +34 -0
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.ts +2 -2
- package/dist/tools/index.js +6 -4
- package/dist/tools/warp_grep/agent/runner.cjs +8 -1
- package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
- package/dist/tools/warp_grep/agent/runner.js +6 -6
- package/dist/tools/warp_grep/anthropic.cjs +9 -2
- package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
- package/dist/tools/warp_grep/anthropic.js +8 -8
- package/dist/tools/warp_grep/index.cjs +9 -2
- package/dist/tools/warp_grep/index.cjs.map +1 -1
- package/dist/tools/warp_grep/index.js +10 -10
- package/dist/tools/warp_grep/openai.cjs +9 -2
- package/dist/tools/warp_grep/openai.cjs.map +1 -1
- package/dist/tools/warp_grep/openai.js +8 -8
- package/dist/tools/warp_grep/vercel.cjs +9 -2
- package/dist/tools/warp_grep/vercel.cjs.map +1 -1
- package/dist/tools/warp_grep/vercel.js +8 -8
- package/package.json +1 -1
- package/dist/chunk-64PMM72R.js.map +0 -1
- /package/dist/{chunk-UU6XCZG3.js.map → chunk-2XNF3W7C.js.map} +0 -0
- /package/dist/{chunk-FYQUSDOE.js.map → chunk-563REN2T.js.map} +0 -0
- /package/dist/{chunk-G4AWE5A2.js.map → chunk-5QIWYEHJ.js.map} +0 -0
- /package/dist/{chunk-YR53PPVM.js.map → chunk-C4IXE2RM.js.map} +0 -0
- /package/dist/{chunk-3FTAIJBH.js.map → chunk-IUG2FHNN.js.map} +0 -0
- /package/dist/{chunk-PZDR5ZZ2.js.map → chunk-NOQCKVY3.js.map} +0 -0
- /package/dist/{chunk-UIZT3KVJ.js.map → chunk-QZNGKOCZ.js.map} +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
WARP_GREP_DESCRIPTION,
|
|
3
3
|
formatResult
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-KYVR4QCG.js";
|
|
5
5
|
import {
|
|
6
6
|
runWarpGrep
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-IFVROB4L.js";
|
|
8
8
|
import {
|
|
9
9
|
getSystemPrompt
|
|
10
10
|
} from "./chunk-WETRQJGU.js";
|
|
@@ -79,4 +79,4 @@ export {
|
|
|
79
79
|
createMorphWarpGrepTool,
|
|
80
80
|
openai_default
|
|
81
81
|
};
|
|
82
|
-
//# sourceMappingURL=chunk-
|
|
82
|
+
//# sourceMappingURL=chunk-2XNF3W7C.js.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
WARP_GREP_DESCRIPTION
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-KYVR4QCG.js";
|
|
4
4
|
import {
|
|
5
5
|
runWarpGrep
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-IFVROB4L.js";
|
|
7
7
|
import {
|
|
8
8
|
LocalRipgrepProvider
|
|
9
9
|
} from "./chunk-ZJIIICRA.js";
|
|
@@ -67,4 +67,4 @@ export {
|
|
|
67
67
|
execute,
|
|
68
68
|
createMorphWarpGrepTool
|
|
69
69
|
};
|
|
70
|
-
//# sourceMappingURL=chunk-
|
|
70
|
+
//# sourceMappingURL=chunk-563REN2T.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
executeEditFile
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-CKTA4AXM.js";
|
|
4
4
|
import {
|
|
5
5
|
EDIT_FILE_SYSTEM_PROMPT,
|
|
6
6
|
EDIT_FILE_TOOL_DESCRIPTION
|
|
@@ -103,4 +103,4 @@ export {
|
|
|
103
103
|
openai_default,
|
|
104
104
|
openai_exports
|
|
105
105
|
};
|
|
106
|
-
//# sourceMappingURL=chunk-
|
|
106
|
+
//# sourceMappingURL=chunk-5QIWYEHJ.js.map
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
WARP_GREP_DESCRIPTION,
|
|
3
3
|
formatResult
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-KYVR4QCG.js";
|
|
5
5
|
import {
|
|
6
6
|
runWarpGrep
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-IFVROB4L.js";
|
|
8
8
|
import {
|
|
9
9
|
getSystemPrompt
|
|
10
10
|
} from "./chunk-WETRQJGU.js";
|
|
@@ -73,4 +73,4 @@ export {
|
|
|
73
73
|
createMorphWarpGrepTool,
|
|
74
74
|
anthropic_default
|
|
75
75
|
};
|
|
76
|
-
//# sourceMappingURL=chunk-
|
|
76
|
+
//# sourceMappingURL=chunk-C4IXE2RM.js.map
|
|
@@ -38,6 +38,29 @@ var FastApplyClient = class {
|
|
|
38
38
|
async execute(input, overrides) {
|
|
39
39
|
return executeEditFile(input, { ...this.config, ...overrides });
|
|
40
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* Apply an edit to code directly without file I/O
|
|
43
|
+
*
|
|
44
|
+
* Useful for sandbox environments or when you manage your own file system.
|
|
45
|
+
* Compatible with the earlier OpenAI client API contract.
|
|
46
|
+
*
|
|
47
|
+
* @param input - Code and edit parameters
|
|
48
|
+
* @param overrides - Optional config overrides for this operation
|
|
49
|
+
* @returns Result with merged code
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```typescript
|
|
53
|
+
* const result = await client.applyEdit({
|
|
54
|
+
* originalCode: 'function hello() { return "world"; }',
|
|
55
|
+
* codeEdit: 'function hello() { return "universe"; }',
|
|
56
|
+
* instructions: 'Change return value'
|
|
57
|
+
* });
|
|
58
|
+
* console.log(result.mergedCode);
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
async applyEdit(input, overrides) {
|
|
62
|
+
return applyEdit(input, { ...this.config, ...overrides });
|
|
63
|
+
}
|
|
41
64
|
};
|
|
42
65
|
function generateUdiff(original, modified, filepath) {
|
|
43
66
|
return createTwoFilesPatch(
|
|
@@ -167,11 +190,44 @@ async function executeEditFile(input, config = {}) {
|
|
|
167
190
|
};
|
|
168
191
|
}
|
|
169
192
|
}
|
|
193
|
+
async function applyEdit(input, config = {}) {
|
|
194
|
+
const debug = config.debug || false;
|
|
195
|
+
const filepath = input.filepath || "file";
|
|
196
|
+
try {
|
|
197
|
+
if (debug) {
|
|
198
|
+
console.log(`[FastApply] Applying edit to code (${input.originalCode.length} chars)`);
|
|
199
|
+
}
|
|
200
|
+
const mergedCode = await callMorphAPI(
|
|
201
|
+
input.originalCode,
|
|
202
|
+
input.codeEdit,
|
|
203
|
+
input.instructions,
|
|
204
|
+
filepath,
|
|
205
|
+
config
|
|
206
|
+
);
|
|
207
|
+
const udiff = config.generateUdiff !== false ? generateUdiff(input.originalCode, mergedCode, filepath) : void 0;
|
|
208
|
+
const changes = countChanges(input.originalCode, mergedCode);
|
|
209
|
+
return {
|
|
210
|
+
success: true,
|
|
211
|
+
mergedCode,
|
|
212
|
+
udiff,
|
|
213
|
+
changes
|
|
214
|
+
};
|
|
215
|
+
} catch (error) {
|
|
216
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
|
217
|
+
if (debug) console.error(`[FastApply] Error: ${errorMessage}`);
|
|
218
|
+
return {
|
|
219
|
+
success: false,
|
|
220
|
+
changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
|
|
221
|
+
error: errorMessage
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
}
|
|
170
225
|
|
|
171
226
|
export {
|
|
172
227
|
FastApplyClient,
|
|
173
228
|
generateUdiff,
|
|
174
229
|
countChanges,
|
|
175
|
-
executeEditFile
|
|
230
|
+
executeEditFile,
|
|
231
|
+
applyEdit
|
|
176
232
|
};
|
|
177
|
-
//# sourceMappingURL=chunk-
|
|
233
|
+
//# sourceMappingURL=chunk-CKTA4AXM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../tools/fastapply/core.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;AAIA,SAAS,UAAU,iBAAiB;AACpC,SAAS,MAAM,SAAS,gBAAgB;AACxC,SAAS,2BAA2B;AAapC,IAAM,iBAAiH;AAAA,EACrH,aAAa;AAAA,EACb,SAAS,QAAQ,IAAI;AAAA,EACrB,eAAe;AAAA,EACf,WAAW;AAAA,EACX,SAAS;AAAA,EACT,OAAO;AACT;AAKO,IAAM,kBAAN,MAAsB;AAAA,EACnB;AAAA,EAER,YAAY,SAAoF,CAAC,GAAG;AAClG,SAAK,SAAS;AAAA,MACZ,aAAa,OAAO;AAAA,MACpB,aAAa,eAAe;AAAA,MAC5B,OAAO,OAAO;AAAA,MACd,SAAS,OAAO,WAAW,eAAe;AAAA,MAC1C,aAAa,OAAO;AAAA,MACpB,eAAe,eAAe;AAAA,MAC9B,WAAW,eAAe;AAAA,IAC5B;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,QAAQ,OAAsB,WAA8D;AAChG,WAAO,gBAAgB,OAAO,EAAE,GAAG,KAAK,QAAQ,GAAG,UAAU,CAAC;AAAA,EAChE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAsBA,MAAM,UAAU,OAAuB,WAAgE;AACrG,WAAO,UAAU,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sCAAsC,MAAM,aAAa,MAAM,SAAS;AAAA,IACtF;AAEA,UAAM,aAAa,MAAM;AAAA,MACvB,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,MACN;AAAA,MACA;AAAA,IACF;AAEA,UAAM,QAAQ,OAAO,kBAAkB,QACnC,cAAc,MAAM,cAAc,YAAY,QAAQ,IACtD;AAEJ,UAAM,UAAU,aAAa,MAAM,cAAc,UAAU;AAE3D,WAAO;AAAA,MACL,SAAS;AAAA,MACT;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd,UAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU;AAC9D,QAAI,MAAO,SAAQ,MAAM,sBAAsB,YAAY,EAAE;AAE7D,WAAO;AAAA,MACL,SAAS;AAAA,MACT,SAAS,EAAE,YAAY,GAAG,cAAc,GAAG,eAAe,EAAE;AAAA,MAC5D,OAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
} from "./chunk-
|
|
2
|
+
readFinishFiles
|
|
3
|
+
} from "./chunk-EK7OQPWD.js";
|
|
4
4
|
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
parseAndFilterGrepOutput
|
|
8
|
-
} from "./chunk-NDZO5IPV.js";
|
|
5
|
+
toolRead
|
|
6
|
+
} from "./chunk-HQO45BAJ.js";
|
|
9
7
|
import {
|
|
10
8
|
LLMResponseParser
|
|
11
9
|
} from "./chunk-LVPVVLTI.js";
|
|
@@ -13,18 +11,20 @@ import {
|
|
|
13
11
|
getSystemPrompt
|
|
14
12
|
} from "./chunk-WETRQJGU.js";
|
|
15
13
|
import {
|
|
16
|
-
|
|
17
|
-
} from "./chunk-
|
|
14
|
+
toolAnalyse
|
|
15
|
+
} from "./chunk-73RQWOQC.js";
|
|
18
16
|
import {
|
|
19
17
|
AGENT_CONFIG,
|
|
20
18
|
DEFAULT_MODEL
|
|
21
19
|
} from "./chunk-TJIUA27P.js";
|
|
22
20
|
import {
|
|
23
|
-
|
|
24
|
-
} from "./chunk-
|
|
21
|
+
formatAgentToolOutput
|
|
22
|
+
} from "./chunk-TICMYDII.js";
|
|
25
23
|
import {
|
|
26
|
-
|
|
27
|
-
|
|
24
|
+
GrepState,
|
|
25
|
+
formatTurnGrepOutput,
|
|
26
|
+
parseAndFilterGrepOutput
|
|
27
|
+
} from "./chunk-NDZO5IPV.js";
|
|
28
28
|
import {
|
|
29
29
|
fetchWithRetry,
|
|
30
30
|
withTimeout
|
|
@@ -200,6 +200,7 @@ async function runWarpGrep(config) {
|
|
|
200
200
|
parts.push(`- ${f.path}: ${ranges}`);
|
|
201
201
|
}
|
|
202
202
|
const payload = parts.join("\n");
|
|
203
|
+
const fileReadErrors = [];
|
|
203
204
|
const resolved = await readFinishFiles(
|
|
204
205
|
repoRoot,
|
|
205
206
|
finishMeta.files,
|
|
@@ -210,11 +211,17 @@ async function runWarpGrep(config) {
|
|
|
210
211
|
const idx = l.indexOf("|");
|
|
211
212
|
return idx >= 0 ? l.slice(idx + 1) : l;
|
|
212
213
|
});
|
|
213
|
-
} catch {
|
|
214
|
+
} catch (err) {
|
|
215
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
216
|
+
fileReadErrors.push({ path: p, error: errorMsg });
|
|
217
|
+
console.error(`[warp_grep] Failed to read file: ${p} - ${errorMsg}`);
|
|
214
218
|
return [`[couldn't find: ${p}]`];
|
|
215
219
|
}
|
|
216
220
|
}
|
|
217
221
|
);
|
|
222
|
+
if (fileReadErrors.length > 0) {
|
|
223
|
+
errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
|
|
224
|
+
}
|
|
218
225
|
return {
|
|
219
226
|
terminationReason: "completed",
|
|
220
227
|
messages,
|
|
@@ -225,4 +232,4 @@ async function runWarpGrep(config) {
|
|
|
225
232
|
export {
|
|
226
233
|
runWarpGrep
|
|
227
234
|
};
|
|
228
|
-
//# sourceMappingURL=chunk-
|
|
235
|
+
//# sourceMappingURL=chunk-IFVROB4L.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/agent/runner.ts"],"sourcesContent":["import { AGENT_CONFIG, DEFAULT_MODEL } from './config.js';\nimport { getSystemPrompt } from './prompt.js';\nimport type { AgentRunResult, ChatMessage, SessionConfig, ToolCall, AgentFinish } from './types.js';\nimport { LLMResponseParser } from './parser.js';\nimport type { WarpGrepProvider } from '../providers/types.js';\nimport { toolRead } from '../tools/read.js';\nimport { toolAnalyse } from '../tools/analyse.js';\nimport { fetchWithRetry, withTimeout } from '../../utils/resilience.js';\nimport { formatAgentToolOutput } from './formatter.js';\nimport { GrepState, parseAndFilterGrepOutput, formatTurnGrepOutput } from './grep_helpers.js';\nimport { readFinishFiles } from '../tools/finish.js';\nimport path from 'path';\nimport fs from 'fs/promises';\n\ntype EventName =\n | 'initial_state'\n | 'round_start'\n | 'round_end'\n | 'finish'\n | 'error';\n\nexport type EventCallback = (name: EventName, payload: Record<string, unknown>) => void;\n\nconst parser = new LLMResponseParser();\n\nasync function buildInitialState(repoRoot: string, query: string): Promise<string> {\n // Summarize top-level directories and file counts\n try {\n const entries = await fs.readdir(repoRoot, { withFileTypes: true });\n const dirs = entries.filter(e => e.isDirectory()).map(d => d.name).slice(0, 50);\n const files = entries.filter(e => e.isFile()).map(f => f.name).slice(0, 50);\n const parts = [\n `<repo_root>${repoRoot}</repo_root>`,\n `<top_dirs>${dirs.join(', ')}</top_dirs>`,\n `<top_files>${files.join(', ')}</top_files>`,\n ];\n return parts.join('\\n');\n } catch {\n return `<repo_root>${repoRoot}</repo_root>`;\n }\n}\n\nfunction formatAssistantToolBlock(name: string, args: Record<string, unknown>, payload: string, isError = false): string {\n const argStr = Object.entries(args)\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(' ');\n const prefix = isError ? 'error' : 'result';\n return `<${prefix} name=\"${name}\" ${argStr}>\\n${payload}\\n</${prefix}>`;\n}\n\nasync function callModel(messages: ChatMessage[], model: string, apiKey?: string): Promise<string> {\n const api = 'https://api.morphllm.com/v1/chat/completions';\n const fetchPromise = fetchWithRetry(\n api,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey || process.env.MORPH_API_KEY || ''}`,\n },\n body: JSON.stringify({\n model,\n temperature: 0.0,\n max_tokens: 1024,\n messages,\n }),\n },\n {}\n );\n const resp = await withTimeout(fetchPromise, AGENT_CONFIG.TIMEOUT_MS, 'morph-warp-grep request timed out');\n if (!resp.ok) {\n // keeping these cases are real throws, if this happens retry will likely not help, so best we just throw here, notice the error and fix\n const t = await resp.text();\n throw new Error(`morph-warp-grep error ${resp.status}: ${t}`);\n }\n const data = await resp.json();\n const content = data?.choices?.[0]?.message?.content;\n if (!content || typeof content !== 'string') {\n throw new Error('Invalid response from model');\n }\n return content;\n}\n\nexport async function runWarpGrep(config: SessionConfig & { provider: WarpGrepProvider }): Promise<AgentRunResult> {\n const repoRoot = path.resolve(config.repoRoot || process.cwd());\n const messages: ChatMessage[] = [];\n\n // system\n const systemMessage = { role: 'system' as const, content: getSystemPrompt() };\n messages.push(systemMessage);\n // user query\n const queryContent = `<query>${config.query}</query>`;\n messages.push({ role: 'user', content: queryContent });\n // initial state\n const initialState = await buildInitialState(repoRoot, config.query);\n messages.push({ role: 'user', content: initialState });\n\n const maxRounds = AGENT_CONFIG.MAX_ROUNDS;\n const model = config.model || DEFAULT_MODEL;\n const provider = config.provider;\n const errors: Array<{ message: string }> = [];\n const grepState = new GrepState();\n\n let finishMeta: AgentFinish | undefined;\n let terminationReason: AgentRunResult['terminationReason'] = 'terminated';\n\n for (let round = 1; round <= maxRounds; round += 1) {\n // call model\n const assistantContent = await callModel(messages, model, config.apiKey).catch((e: unknown) => {\n errors.push({ message: e instanceof Error ? e.message : String(e) });\n return '';\n });\n if (!assistantContent) break;\n messages.push({ role: 'assistant', content: assistantContent });\n\n // parse tool calls (no longer throws - returns _skip calls for malformed commands)\n const toolCalls = parser.parse(assistantContent);\n if (toolCalls.length === 0) {\n errors.push({ message: 'No tool calls produced by the model.' });\n terminationReason = 'terminated';\n break;\n }\n\n const finishCalls = toolCalls.filter(c => c.name === 'finish');\n const grepCalls = toolCalls.filter(c => c.name === 'grep');\n const analyseCalls = toolCalls.filter(c => c.name === 'analyse');\n const readCalls = toolCalls.filter(c => c.name === 'read');\n const skipCalls = toolCalls.filter(c => c.name === '_skip');\n\n const formatted: string[] = [];\n\n // Surface any skipped commands as feedback to the LLM\n for (const c of skipCalls) {\n const msg = (c.arguments as { message?: string })?.message || 'Command skipped due to parsing error';\n formatted.push(msg);\n }\n\n // Execute non-grep tools in parallel\n const otherPromises: Array<Promise<string>> = [];\n for (const c of analyseCalls) {\n const args = (c.arguments ?? {}) as { path: string; pattern?: string | null };\n otherPromises.push(\n toolAnalyse(provider, args).then(\n p => formatAgentToolOutput('analyse', args, p, { isError: false }),\n err => formatAgentToolOutput('analyse', args, String(err), { isError: true })\n )\n );\n }\n for (const c of readCalls) {\n const args = (c.arguments ?? {}) as { path: string; start?: number; end?: number };\n otherPromises.push(\n toolRead(provider, args).then(\n p => formatAgentToolOutput('read', args, p, { isError: false }),\n err => formatAgentToolOutput('read', args, String(err), { isError: true })\n )\n );\n }\n const otherResults = await Promise.all(otherPromises);\n formatted.push(...otherResults);\n\n // Execute grep calls sequentially like MCP runner to keep outputs compact\n for (const c of grepCalls) {\n const args = (c.arguments ?? {}) as { pattern: string; path: string };\n try {\n const grepRes = await provider.grep({ pattern: args.pattern, path: args.path });\n \n // Check for ripgrep availability error - terminate early with clear message\n if (grepRes.error) {\n errors.push({ message: grepRes.error });\n terminationReason = 'terminated';\n // Return immediately with the error so user knows to install ripgrep\n return {\n terminationReason: 'terminated',\n messages,\n errors,\n };\n }\n \n const rawOutput = Array.isArray(grepRes.lines) ? grepRes.lines.join('\\n') : '';\n const newMatches = parseAndFilterGrepOutput(rawOutput, grepState);\n let formattedPayload = formatTurnGrepOutput(newMatches);\n if (formattedPayload === \"No new matches found.\") {\n formattedPayload = \"no new matches\";\n }\n formatted.push(formatAgentToolOutput('grep', args, formattedPayload, { isError: false }));\n } catch (err) {\n formatted.push(formatAgentToolOutput('grep', args, String(err), { isError: true }));\n }\n }\n\n if (formatted.length > 0) {\n // Add turn counter message\n const turnsUsed = round;\n const turnsRemaining = 4 - turnsUsed;\n let turnMessage: string;\n if (turnsRemaining === 0) {\n turnMessage = `\\n\\n[Turn ${turnsUsed}/4] This is your LAST turn. You MUST call the finish tool now.`;\n } else if (turnsRemaining === 1) {\n turnMessage = `\\n\\n[Turn ${turnsUsed}/4] You have 1 turn remaining. Next turn you MUST call the finish tool.`;\n } else {\n turnMessage = `\\n\\n[Turn ${turnsUsed}/4] You have ${turnsRemaining} turns remaining.`;\n }\n messages.push({ role: 'user', content: formatted.join('\\n') + turnMessage });\n }\n\n if (finishCalls.length) {\n const fc = finishCalls[0];\n const files = ((fc.arguments as any)?.files ?? []) as AgentFinish['files'];\n finishMeta = { files };\n terminationReason = 'completed';\n break;\n }\n }\n\n if (terminationReason !== 'completed' || !finishMeta) {\n return { terminationReason, messages, errors };\n }\n\n // Build finish payload\n const parts: string[] = ['Relevant context found:'];\n for (const f of finishMeta.files) {\n const ranges = f.lines.map(([s, e]) => `${s}-${e}`).join(', ');\n parts.push(`- ${f.path}: ${ranges}`);\n }\n const payload = parts.join('\\n');\n\n // Resolve file contents for returned ranges\n // Wrap reader in try-catch to handle non-existent or unreadable files gracefully\n const resolved = await readFinishFiles(\n repoRoot,\n finishMeta.files,\n async (p: string, s: number, e: number) => {\n try {\n const rr = await provider.read({ path: p, start: s, end: e });\n // rr.lines are \"line|content\" → strip the \"line|\" prefix\n return rr.lines.map(l => {\n const idx = l.indexOf('|');\n return idx >= 0 ? l.slice(idx + 1) : l;\n });\n } catch {\n // File doesn't exist or can't be read - return placeholder\n // This handles cases where the agent hallucinated a path or the file was deleted\n return [`[couldn't find: ${p}]`];\n }\n }\n );\n\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: finishMeta, resolved },\n };\n}\n\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,OAAO,UAAU;AACjB,OAAO,QAAQ;AAWf,IAAM,SAAS,IAAI,kBAAkB;AAErC,eAAe,kBAAkB,UAAkB,OAAgC;AAEjF,MAAI;AACF,UAAM,UAAU,MAAM,GAAG,QAAQ,UAAU,EAAE,eAAe,KAAK,CAAC;AAClE,UAAM,OAAO,QAAQ,OAAO,OAAK,EAAE,YAAY,CAAC,EAAE,IAAI,OAAK,EAAE,IAAI,EAAE,MAAM,GAAG,EAAE;AAC9E,UAAM,QAAQ,QAAQ,OAAO,OAAK,EAAE,OAAO,CAAC,EAAE,IAAI,OAAK,EAAE,IAAI,EAAE,MAAM,GAAG,EAAE;AAC1E,UAAM,QAAQ;AAAA,MACZ,cAAc,QAAQ;AAAA,MACtB,aAAa,KAAK,KAAK,IAAI,CAAC;AAAA,MAC5B,cAAc,MAAM,KAAK,IAAI,CAAC;AAAA,IAChC;AACA,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB,QAAQ;AACN,WAAO,cAAc,QAAQ;AAAA,EAC/B;AACF;AAUA,eAAe,UAAU,UAAyB,OAAe,QAAkC;AACjG,QAAM,MAAM;AACZ,QAAM,eAAe;AAAA,IACnB;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,eAAe,UAAU,UAAU,QAAQ,IAAI,iBAAiB,EAAE;AAAA,MACpE;AAAA,MACA,MAAM,KAAK,UAAU;AAAA,QACnB;AAAA,QACA,aAAa;AAAA,QACb,YAAY;AAAA,QACZ;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IACA,CAAC;AAAA,EACH;AACA,QAAM,OAAO,MAAM,YAAY,cAAc,aAAa,YAAY,mCAAmC;AACzG,MAAI,CAAC,KAAK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S,CAAC;AAChD,mBAAa,EAAE,MAAM;AACrB,0BAAoB;AACpB;AAAA,IACF;AAAA,EACF;AAEA,MAAI,sBAAsB,eAAe,CAAC,YAAY;AACpD,WAAO,EAAE,mBAAmB,UAAU,OAAO;AAAA,EAC/C;AAGA,QAAM,QAAkB,CAAC,yBAAyB;AAClD,aAAW,KAAK,WAAW,OAAO;AAChC,UAAM,SAAS,EAAE,MAAM,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,IAAI;AAC7D,UAAM,KAAK,KAAK,EAAE,IAAI,KAAK,MAAM,EAAE;AAAA,EACrC;AACA,QAAM,UAAU,MAAM,KAAK,IAAI;AAI/B,QAAM,WAAW,MAAM;AAAA,IACrB;AAAA,IACA,WAAW;AAAA,IACX,OAAO,GAAW,GAAW,MAAc;AACzC,UAAI;AACF,cAAM,KAAK,MAAM,SAAS,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,KAAK,EAAE,CAAC;AAE5D,eAAO,GAAG,MAAM,IAAI,OAAK;AACvB,gBAAM,MAAM,EAAE,QAAQ,GAAG;AACzB,iBAAO,OAAO,IAAI,EAAE,MAAM,MAAM,CAAC,IAAI;AAAA,QACvC,CAAC;AAAA,MACH,QAAQ;AAGN,eAAO,CAAC,mBAAmB,CAAC,GAAG;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB;AAAA,IACA,QAAQ,EAAE,SAAS,UAAU,YAAY,SAAS;AAAA,EACpD;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../tools/warp_grep/agent/runner.ts"],"sourcesContent":["import { AGENT_CONFIG, DEFAULT_MODEL } from './config.js';\nimport { getSystemPrompt } from './prompt.js';\nimport type { AgentRunResult, ChatMessage, SessionConfig, ToolCall, AgentFinish } from './types.js';\nimport { LLMResponseParser } from './parser.js';\nimport type { WarpGrepProvider } from '../providers/types.js';\nimport { toolRead } from '../tools/read.js';\nimport { toolAnalyse } from '../tools/analyse.js';\nimport { fetchWithRetry, withTimeout } from '../../utils/resilience.js';\nimport { formatAgentToolOutput } from './formatter.js';\nimport { GrepState, parseAndFilterGrepOutput, formatTurnGrepOutput } from './grep_helpers.js';\nimport { readFinishFiles } from '../tools/finish.js';\nimport path from 'path';\nimport fs from 'fs/promises';\n\ntype EventName =\n | 'initial_state'\n | 'round_start'\n | 'round_end'\n | 'finish'\n | 'error';\n\nexport type EventCallback = (name: EventName, payload: Record<string, unknown>) => void;\n\nconst parser = new LLMResponseParser();\n\nasync function buildInitialState(repoRoot: string, query: string): Promise<string> {\n // Summarize top-level directories and file counts\n try {\n const entries = await fs.readdir(repoRoot, { withFileTypes: true });\n const dirs = entries.filter(e => e.isDirectory()).map(d => d.name).slice(0, 50);\n const files = entries.filter(e => e.isFile()).map(f => f.name).slice(0, 50);\n const parts = [\n `<repo_root>${repoRoot}</repo_root>`,\n `<top_dirs>${dirs.join(', ')}</top_dirs>`,\n `<top_files>${files.join(', ')}</top_files>`,\n ];\n return parts.join('\\n');\n } catch {\n return `<repo_root>${repoRoot}</repo_root>`;\n }\n}\n\nfunction formatAssistantToolBlock(name: string, args: Record<string, unknown>, payload: string, isError = false): string {\n const argStr = Object.entries(args)\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(' ');\n const prefix = isError ? 'error' : 'result';\n return `<${prefix} name=\"${name}\" ${argStr}>\\n${payload}\\n</${prefix}>`;\n}\n\nasync function callModel(messages: ChatMessage[], model: string, apiKey?: string): Promise<string> {\n const api = 'https://api.morphllm.com/v1/chat/completions';\n const fetchPromise = fetchWithRetry(\n api,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey || process.env.MORPH_API_KEY || ''}`,\n },\n body: JSON.stringify({\n model,\n temperature: 0.0,\n max_tokens: 1024,\n messages,\n }),\n },\n {}\n );\n const resp = await withTimeout(fetchPromise, AGENT_CONFIG.TIMEOUT_MS, 'morph-warp-grep request timed out');\n if (!resp.ok) {\n // keeping these cases are real throws, if this happens retry will likely not help, so best we just throw here, notice the error and fix\n const t = await resp.text();\n throw new Error(`morph-warp-grep error ${resp.status}: ${t}`);\n }\n const data = await resp.json();\n const content = data?.choices?.[0]?.message?.content;\n if (!content || typeof content !== 'string') {\n throw new Error('Invalid response from model');\n }\n return content;\n}\n\nexport async function runWarpGrep(config: SessionConfig & { provider: WarpGrepProvider }): Promise<AgentRunResult> {\n const repoRoot = path.resolve(config.repoRoot || process.cwd());\n const messages: ChatMessage[] = [];\n\n // system\n const systemMessage = { role: 'system' as const, content: getSystemPrompt() };\n messages.push(systemMessage);\n // user query\n const queryContent = `<query>${config.query}</query>`;\n messages.push({ role: 'user', content: queryContent });\n // initial state\n const initialState = await buildInitialState(repoRoot, config.query);\n messages.push({ role: 'user', content: initialState });\n\n const maxRounds = AGENT_CONFIG.MAX_ROUNDS;\n const model = config.model || DEFAULT_MODEL;\n const provider = config.provider;\n const errors: Array<{ message: string }> = [];\n const grepState = new GrepState();\n\n let finishMeta: AgentFinish | undefined;\n let terminationReason: AgentRunResult['terminationReason'] = 'terminated';\n\n for (let round = 1; round <= maxRounds; round += 1) {\n // call model\n const assistantContent = await callModel(messages, model, config.apiKey).catch((e: unknown) => {\n errors.push({ message: e instanceof Error ? e.message : String(e) });\n return '';\n });\n if (!assistantContent) break;\n messages.push({ role: 'assistant', content: assistantContent });\n\n // parse tool calls (no longer throws - returns _skip calls for malformed commands)\n const toolCalls = parser.parse(assistantContent);\n if (toolCalls.length === 0) {\n errors.push({ message: 'No tool calls produced by the model.' });\n terminationReason = 'terminated';\n break;\n }\n\n const finishCalls = toolCalls.filter(c => c.name === 'finish');\n const grepCalls = toolCalls.filter(c => c.name === 'grep');\n const analyseCalls = toolCalls.filter(c => c.name === 'analyse');\n const readCalls = toolCalls.filter(c => c.name === 'read');\n const skipCalls = toolCalls.filter(c => c.name === '_skip');\n\n const formatted: string[] = [];\n\n // Surface any skipped commands as feedback to the LLM\n for (const c of skipCalls) {\n const msg = (c.arguments as { message?: string })?.message || 'Command skipped due to parsing error';\n formatted.push(msg);\n }\n\n // Execute non-grep tools in parallel\n const otherPromises: Array<Promise<string>> = [];\n for (const c of analyseCalls) {\n const args = (c.arguments ?? {}) as { path: string; pattern?: string | null };\n otherPromises.push(\n toolAnalyse(provider, args).then(\n p => formatAgentToolOutput('analyse', args, p, { isError: false }),\n err => formatAgentToolOutput('analyse', args, String(err), { isError: true })\n )\n );\n }\n for (const c of readCalls) {\n const args = (c.arguments ?? {}) as { path: string; start?: number; end?: number };\n otherPromises.push(\n toolRead(provider, args).then(\n p => formatAgentToolOutput('read', args, p, { isError: false }),\n err => formatAgentToolOutput('read', args, String(err), { isError: true })\n )\n );\n }\n const otherResults = await Promise.all(otherPromises);\n formatted.push(...otherResults);\n\n // Execute grep calls sequentially like MCP runner to keep outputs compact\n for (const c of grepCalls) {\n const args = (c.arguments ?? {}) as { pattern: string; path: string };\n try {\n const grepRes = await provider.grep({ pattern: args.pattern, path: args.path });\n \n // Check for ripgrep availability error - terminate early with clear message\n if (grepRes.error) {\n errors.push({ message: grepRes.error });\n terminationReason = 'terminated';\n // Return immediately with the error so user knows to install ripgrep\n return {\n terminationReason: 'terminated',\n messages,\n errors,\n };\n }\n \n const rawOutput = Array.isArray(grepRes.lines) ? grepRes.lines.join('\\n') : '';\n const newMatches = parseAndFilterGrepOutput(rawOutput, grepState);\n let formattedPayload = formatTurnGrepOutput(newMatches);\n if (formattedPayload === \"No new matches found.\") {\n formattedPayload = \"no new matches\";\n }\n formatted.push(formatAgentToolOutput('grep', args, formattedPayload, { isError: false }));\n } catch (err) {\n formatted.push(formatAgentToolOutput('grep', args, String(err), { isError: true }));\n }\n }\n\n if (formatted.length > 0) {\n // Add turn counter message\n const turnsUsed = round;\n const turnsRemaining = 4 - turnsUsed;\n let turnMessage: string;\n if (turnsRemaining === 0) {\n turnMessage = `\\n\\n[Turn ${turnsUsed}/4] This is your LAST turn. You MUST call the finish tool now.`;\n } else if (turnsRemaining === 1) {\n turnMessage = `\\n\\n[Turn ${turnsUsed}/4] You have 1 turn remaining. Next turn you MUST call the finish tool.`;\n } else {\n turnMessage = `\\n\\n[Turn ${turnsUsed}/4] You have ${turnsRemaining} turns remaining.`;\n }\n messages.push({ role: 'user', content: formatted.join('\\n') + turnMessage });\n }\n\n if (finishCalls.length) {\n const fc = finishCalls[0];\n const files = ((fc.arguments as any)?.files ?? []) as AgentFinish['files'];\n finishMeta = { files };\n terminationReason = 'completed';\n break;\n }\n }\n\n if (terminationReason !== 'completed' || !finishMeta) {\n return { terminationReason, messages, errors };\n }\n\n // Build finish payload\n const parts: string[] = ['Relevant context found:'];\n for (const f of finishMeta.files) {\n const ranges = f.lines.map(([s, e]) => `${s}-${e}`).join(', ');\n parts.push(`- ${f.path}: ${ranges}`);\n }\n const payload = parts.join('\\n');\n\n // Resolve file contents for returned ranges\n // Wrap reader in try-catch to handle non-existent or unreadable files gracefully\n // Track files that couldn't be read for error reporting\n const fileReadErrors: Array<{ path: string; error: string }> = [];\n const resolved = await readFinishFiles(\n repoRoot,\n finishMeta.files,\n async (p: string, s: number, e: number) => {\n try {\n const rr = await provider.read({ path: p, start: s, end: e });\n // rr.lines are \"line|content\" → strip the \"line|\" prefix\n return rr.lines.map(l => {\n const idx = l.indexOf('|');\n return idx >= 0 ? l.slice(idx + 1) : l;\n });\n } catch (err) {\n // File doesn't exist or can't be read - log error but don't throw\n // This handles cases where the agent hallucinated a path or the file was deleted\n const errorMsg = err instanceof Error ? err.message : String(err);\n fileReadErrors.push({ path: p, error: errorMsg });\n console.error(`[warp_grep] Failed to read file: ${p} - ${errorMsg}`);\n return [`[couldn't find: ${p}]`];\n }\n }\n );\n\n // Add file read errors to the result so MCP can report them\n if (fileReadErrors.length > 0) {\n errors.push(...fileReadErrors.map(e => ({ message: `File read error: ${e.path} - ${e.error}` })));\n }\n\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: fin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S;AAAA,EACpD;AACF;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
executeEditFile
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-CKTA4AXM.js";
|
|
4
4
|
import {
|
|
5
5
|
EDIT_FILE_SYSTEM_PROMPT,
|
|
6
6
|
EDIT_FILE_TOOL_DESCRIPTION
|
|
@@ -91,4 +91,4 @@ export {
|
|
|
91
91
|
getSystemPrompt,
|
|
92
92
|
anthropic_exports
|
|
93
93
|
};
|
|
94
|
-
//# sourceMappingURL=chunk-
|
|
94
|
+
//# sourceMappingURL=chunk-IUG2FHNN.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
runWarpGrep
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-IFVROB4L.js";
|
|
4
4
|
import {
|
|
5
5
|
LocalRipgrepProvider
|
|
6
6
|
} from "./chunk-ZJIIICRA.js";
|
|
@@ -94,7 +94,7 @@ function formatResult(result) {
|
|
|
94
94
|
}
|
|
95
95
|
|
|
96
96
|
// tools/warp_grep/prompts.ts
|
|
97
|
-
var WARP_GREP_DESCRIPTION = "
|
|
97
|
+
var WARP_GREP_DESCRIPTION = "ALWAYS use Warp Grep when you need to search a large chunk of code. Warp Grep is a fast and accurate tool that can search for all relevant context in a codebase. Warp Grep can be used for query types like: find function responsible for <small feature>; find code that does <description>; find code path for <big feature>; Where does <minimal error message> come from?; or any query of that type ";
|
|
98
98
|
|
|
99
99
|
export {
|
|
100
100
|
WarpGrepClient,
|
|
@@ -102,4 +102,4 @@ export {
|
|
|
102
102
|
formatResult,
|
|
103
103
|
WARP_GREP_DESCRIPTION
|
|
104
104
|
};
|
|
105
|
-
//# sourceMappingURL=chunk-
|
|
105
|
+
//# sourceMappingURL=chunk-KYVR4QCG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/core.ts","../tools/warp_grep/prompts.ts"],"sourcesContent":["/**\n * Core implementation for morph-warp-grep\n * Provides a client class for programmatic code search\n */\n\nimport { runWarpGrep } from './agent/runner.js';\nimport { LocalRipgrepProvider } from './providers/local.js';\nimport type { \n WarpGrepClientConfig, \n WarpGrepInput, \n WarpGrepResult,\n WarpGrepContext,\n} from './types.js';\n\n/**\n * WarpGrep client for programmatic code search\n * \n * @example\n * ```typescript\n * import { WarpGrepClient } from '@morphllm/morphsdk';\n * \n * const client = new WarpGrepClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * // Simple usage - defaults to LocalRipgrepProvider\n * const result = await client.execute({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * \n * // With custom excludes\n * const result = await client.execute({\n * query: 'Find database models',\n * repoRoot: '.',\n * excludes: ['node_modules', '.git', 'dist']\n * });\n * ```\n */\nexport class WarpGrepClient {\n private config: WarpGrepClientConfig;\n\n constructor(config: WarpGrepClientConfig = {}) {\n this.config = {\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Execute a code search query\n * \n * @param input - Search parameters including query, repoRoot, and optional provider\n * @returns Search results with relevant code contexts\n * \n * @example\n * ```typescript\n * const result = await client.execute({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * \n * if (result.success) {\n * for (const ctx of result.contexts) {\n * console.log(`File: ${ctx.file}`);\n * console.log(ctx.content);\n * }\n * }\n * ```\n */\n async execute(input: WarpGrepInput): Promise<WarpGrepResult> {\n // Default to LocalRipgrepProvider if no provider specified\n const provider = input.provider ?? new LocalRipgrepProvider(input.repoRoot, input.excludes);\n \n const result = await runWarpGrep({\n query: input.query,\n repoRoot: input.repoRoot,\n provider,\n excludes: input.excludes,\n includes: input.includes,\n debug: input.debug ?? this.config.debug ?? false,\n apiKey: this.config.apiKey,\n });\n\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n return { \n success: false, \n error: 'Search did not complete',\n };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n }));\n\n return { \n success: true, \n contexts, \n summary: finish.payload,\n };\n }\n}\n\n/**\n * Execute a warp grep search directly\n * \n * @param input - Search parameters\n * @param config - Optional client configuration\n * @returns Search results\n * \n * @example\n * ```typescript\n * import { executeWarpGrep } from '@morphllm/morphsdk/tools/warp-grep';\n * \n * const result = await executeWarpGrep({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * ```\n */\nexport async function executeWarpGrep(\n input: WarpGrepInput,\n config?: WarpGrepClientConfig\n): Promise<WarpGrepResult> {\n const client = new WarpGrepClient(config);\n return client.execute(input);\n}\n\n/**\n * Format warp grep results for display or tool responses\n * \n * @param result - The search result\n * @returns Formatted string representation\n */\nexport function formatResult(result: WarpGrepResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (!result.contexts || result.contexts.length === 0) {\n return 'No relevant code found. Try rephrasing your query.';\n }\n\n const lines: string[] = [];\n lines.push(`Found ${result.contexts.length} relevant code sections:\\n`);\n\n result.contexts.forEach((ctx, i) => {\n lines.push(`${i + 1}. ${ctx.file}`);\n lines.push('```');\n lines.push(ctx.content);\n lines.push('```');\n lines.push('');\n });\n\n if (result.summary) {\n lines.push(`Summary: ${result.summary}`);\n }\n\n return lines.join('\\n');\n}\n\n","/**\n * Prompts and descriptions for morph-warp-grep\n */\n\n/**\n * Default tool description for the warp grep tool\n */\nexport const WARP_GREP_DESCRIPTION = \n '
|
|
1
|
+
{"version":3,"sources":["../tools/warp_grep/core.ts","../tools/warp_grep/prompts.ts"],"sourcesContent":["/**\n * Core implementation for morph-warp-grep\n * Provides a client class for programmatic code search\n */\n\nimport { runWarpGrep } from './agent/runner.js';\nimport { LocalRipgrepProvider } from './providers/local.js';\nimport type { \n WarpGrepClientConfig, \n WarpGrepInput, \n WarpGrepResult,\n WarpGrepContext,\n} from './types.js';\n\n/**\n * WarpGrep client for programmatic code search\n * \n * @example\n * ```typescript\n * import { WarpGrepClient } from '@morphllm/morphsdk';\n * \n * const client = new WarpGrepClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * // Simple usage - defaults to LocalRipgrepProvider\n * const result = await client.execute({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * \n * // With custom excludes\n * const result = await client.execute({\n * query: 'Find database models',\n * repoRoot: '.',\n * excludes: ['node_modules', '.git', 'dist']\n * });\n * ```\n */\nexport class WarpGrepClient {\n private config: WarpGrepClientConfig;\n\n constructor(config: WarpGrepClientConfig = {}) {\n this.config = {\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Execute a code search query\n * \n * @param input - Search parameters including query, repoRoot, and optional provider\n * @returns Search results with relevant code contexts\n * \n * @example\n * ```typescript\n * const result = await client.execute({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * \n * if (result.success) {\n * for (const ctx of result.contexts) {\n * console.log(`File: ${ctx.file}`);\n * console.log(ctx.content);\n * }\n * }\n * ```\n */\n async execute(input: WarpGrepInput): Promise<WarpGrepResult> {\n // Default to LocalRipgrepProvider if no provider specified\n const provider = input.provider ?? new LocalRipgrepProvider(input.repoRoot, input.excludes);\n \n const result = await runWarpGrep({\n query: input.query,\n repoRoot: input.repoRoot,\n provider,\n excludes: input.excludes,\n includes: input.includes,\n debug: input.debug ?? this.config.debug ?? false,\n apiKey: this.config.apiKey,\n });\n\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n return { \n success: false, \n error: 'Search did not complete',\n };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n }));\n\n return { \n success: true, \n contexts, \n summary: finish.payload,\n };\n }\n}\n\n/**\n * Execute a warp grep search directly\n * \n * @param input - Search parameters\n * @param config - Optional client configuration\n * @returns Search results\n * \n * @example\n * ```typescript\n * import { executeWarpGrep } from '@morphllm/morphsdk/tools/warp-grep';\n * \n * const result = await executeWarpGrep({\n * query: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * ```\n */\nexport async function executeWarpGrep(\n input: WarpGrepInput,\n config?: WarpGrepClientConfig\n): Promise<WarpGrepResult> {\n const client = new WarpGrepClient(config);\n return client.execute(input);\n}\n\n/**\n * Format warp grep results for display or tool responses\n * \n * @param result - The search result\n * @returns Formatted string representation\n */\nexport function formatResult(result: WarpGrepResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (!result.contexts || result.contexts.length === 0) {\n return 'No relevant code found. Try rephrasing your query.';\n }\n\n const lines: string[] = [];\n lines.push(`Found ${result.contexts.length} relevant code sections:\\n`);\n\n result.contexts.forEach((ctx, i) => {\n lines.push(`${i + 1}. ${ctx.file}`);\n lines.push('```');\n lines.push(ctx.content);\n lines.push('```');\n lines.push('');\n });\n\n if (result.summary) {\n lines.push(`Summary: ${result.summary}`);\n }\n\n return lines.join('\\n');\n}\n\n","/**\n * Prompts and descriptions for morph-warp-grep\n */\n\n/**\n * Default tool description for the warp grep tool\n */\nexport const WARP_GREP_DESCRIPTION = \n 'ALWAYS use Warp Grep when you need to search a large chunk of code. ' +\n 'Warp Grep is a fast and accurate tool that can search for all relevant context in a codebase. ' +\n 'Warp Grep can be used for query types like: find function responsible for <small feature>; find code that does <description>; find code path for <big feature>; Where does <minimal error message> come from?; or any query of that type '\n\n/**\n * System prompt for the warp grep agent\n * Re-exported from agent/prompt.ts for convenience\n */\nexport { SYSTEM_PROMPT as WARP_GREP_SYSTEM_PROMPT, getSystemPrompt } from './agent/prompt.js';\n\n"],"mappings":";;;;;;;;AAqCO,IAAM,iBAAN,MAAqB;AAAA,EAClB;AAAA,EAER,YAAY,SAA+B,CAAC,GAAG;AAC7C,SAAK,SAAS;AAAA,MACZ,QAAQ,OAAO;AAAA,MACf,OAAO,OAAO;AAAA,MACd,SAAS,OAAO;AAAA,MAChB,aAAa,OAAO;AAAA,IACtB;A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,MAAM;AAClC,UAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,EAAE;AAClC,UAAM,KAAK,KAAK;AAChB,UAAM,KAAK,IAAI,OAAO;AACtB,UAAM,KAAK,KAAK;AAChB,UAAM,KAAK,EAAE;AAAA,EACf,CAAC;AAED,MAAI,OAAO,SAAS;AAClB,UAAM,KAAK,YAAY,OAAO,OAAO,EAAE;AAAA,EACzC;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;;;AC1JO,IAAM,wBACX;","names":[]}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createMorphWarpGrepTool as createMorphWarpGrepTool2
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-C4IXE2RM.js";
|
|
4
4
|
import {
|
|
5
5
|
createMorphWarpGrepTool
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-2XNF3W7C.js";
|
|
7
7
|
import {
|
|
8
8
|
createMorphWarpGrepTool as createMorphWarpGrepTool3
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-563REN2T.js";
|
|
10
10
|
import {
|
|
11
11
|
WarpGrepClient
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-KYVR4QCG.js";
|
|
13
13
|
import {
|
|
14
14
|
createCodebaseSearchTool as createCodebaseSearchTool3
|
|
15
15
|
} from "./chunk-UBX7QYBD.js";
|
|
@@ -24,16 +24,16 @@ import {
|
|
|
24
24
|
} from "./chunk-WM77HRKO.js";
|
|
25
25
|
import {
|
|
26
26
|
createEditFileTool as createEditFileTool2
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-IUG2FHNN.js";
|
|
28
28
|
import {
|
|
29
29
|
createEditFileTool
|
|
30
|
-
} from "./chunk-
|
|
30
|
+
} from "./chunk-5QIWYEHJ.js";
|
|
31
31
|
import {
|
|
32
32
|
createEditFileTool as createEditFileTool3
|
|
33
|
-
} from "./chunk-
|
|
33
|
+
} from "./chunk-QZNGKOCZ.js";
|
|
34
34
|
import {
|
|
35
35
|
FastApplyClient
|
|
36
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-CKTA4AXM.js";
|
|
37
37
|
import {
|
|
38
38
|
BrowserClient
|
|
39
39
|
} from "./chunk-LVY5LPEX.js";
|
|
@@ -280,4 +280,4 @@ export {
|
|
|
280
280
|
VercelToolFactory,
|
|
281
281
|
MorphClient
|
|
282
282
|
};
|
|
283
|
-
//# sourceMappingURL=chunk-
|
|
283
|
+
//# sourceMappingURL=chunk-NOQCKVY3.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
executeEditFile
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-CKTA4AXM.js";
|
|
4
4
|
import {
|
|
5
5
|
EDIT_FILE_SYSTEM_PROMPT,
|
|
6
6
|
EDIT_FILE_TOOL_DESCRIPTION
|
|
@@ -86,4 +86,4 @@ export {
|
|
|
86
86
|
vercel_default,
|
|
87
87
|
vercel_exports
|
|
88
88
|
};
|
|
89
|
-
//# sourceMappingURL=chunk-
|
|
89
|
+
//# sourceMappingURL=chunk-QZNGKOCZ.js.map
|
package/dist/client.cjs
CHANGED
|
@@ -145,6 +145,29 @@ var FastApplyClient = class {
|
|
|
145
145
|
async execute(input, overrides) {
|
|
146
146
|
return executeEditFile(input, { ...this.config, ...overrides });
|
|
147
147
|
}
|
|
148
|
+
/**
|
|
149
|
+
* Apply an edit to code directly without file I/O
|
|
150
|
+
*
|
|
151
|
+
* Useful for sandbox environments or when you manage your own file system.
|
|
152
|
+
* Compatible with the earlier OpenAI client API contract.
|
|
153
|
+
*
|
|
154
|
+
* @param input - Code and edit parameters
|
|
155
|
+
* @param overrides - Optional config overrides for this operation
|
|
156
|
+
* @returns Result with merged code
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* ```typescript
|
|
160
|
+
* const result = await client.applyEdit({
|
|
161
|
+
* originalCode: 'function hello() { return "world"; }',
|
|
162
|
+
* codeEdit: 'function hello() { return "universe"; }',
|
|
163
|
+
* instructions: 'Change return value'
|
|
164
|
+
* });
|
|
165
|
+
* console.log(result.mergedCode);
|
|
166
|
+
* ```
|
|
167
|
+
*/
|
|
168
|
+
async applyEdit(input, overrides) {
|
|
169
|
+
return applyEdit(input, { ...this.config, ...overrides });
|
|
170
|
+
}
|
|
148
171
|
};
|
|
149
172
|
function generateUdiff(original, modified, filepath) {
|
|
150
173
|
return (0, import_diff.createTwoFilesPatch)(
|
|
@@ -274,6 +297,38 @@ async function executeEditFile(input, config = {}) {
|
|
|
274
297
|
};
|
|
275
298
|
}
|
|
276
299
|
}
|
|
300
|
+
async function applyEdit(input, config = {}) {
|
|
301
|
+
const debug = config.debug || false;
|
|
302
|
+
const filepath = input.filepath || "file";
|
|
303
|
+
try {
|
|
304
|
+
if (debug) {
|
|
305
|
+
console.log(`[FastApply] Applying edit to code (${input.originalCode.length} chars)`);
|
|
306
|
+
}
|
|
307
|
+
const mergedCode = await callMorphAPI(
|
|
308
|
+
input.originalCode,
|
|
309
|
+
input.codeEdit,
|
|
310
|
+
input.instructions,
|
|
311
|
+
filepath,
|
|
312
|
+
config
|
|
313
|
+
);
|
|
314
|
+
const udiff = config.generateUdiff !== false ? generateUdiff(input.originalCode, mergedCode, filepath) : void 0;
|
|
315
|
+
const changes = countChanges(input.originalCode, mergedCode);
|
|
316
|
+
return {
|
|
317
|
+
success: true,
|
|
318
|
+
mergedCode,
|
|
319
|
+
udiff,
|
|
320
|
+
changes
|
|
321
|
+
};
|
|
322
|
+
} catch (error) {
|
|
323
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
|
324
|
+
if (debug) console.error(`[FastApply] Error: ${errorMessage}`);
|
|
325
|
+
return {
|
|
326
|
+
success: false,
|
|
327
|
+
changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
|
|
328
|
+
error: errorMessage
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
}
|
|
277
332
|
|
|
278
333
|
// tools/codebase_search/core.ts
|
|
279
334
|
var CodebaseSearchClient = class {
|
|
@@ -1708,6 +1763,7 @@ async function runWarpGrep(config) {
|
|
|
1708
1763
|
parts.push(`- ${f.path}: ${ranges}`);
|
|
1709
1764
|
}
|
|
1710
1765
|
const payload = parts.join("\n");
|
|
1766
|
+
const fileReadErrors = [];
|
|
1711
1767
|
const resolved = await readFinishFiles(
|
|
1712
1768
|
repoRoot,
|
|
1713
1769
|
finishMeta.files,
|
|
@@ -1718,11 +1774,17 @@ async function runWarpGrep(config) {
|
|
|
1718
1774
|
const idx = l.indexOf("|");
|
|
1719
1775
|
return idx >= 0 ? l.slice(idx + 1) : l;
|
|
1720
1776
|
});
|
|
1721
|
-
} catch {
|
|
1777
|
+
} catch (err) {
|
|
1778
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
1779
|
+
fileReadErrors.push({ path: p, error: errorMsg });
|
|
1780
|
+
console.error(`[warp_grep] Failed to read file: ${p} - ${errorMsg}`);
|
|
1722
1781
|
return [`[couldn't find: ${p}]`];
|
|
1723
1782
|
}
|
|
1724
1783
|
}
|
|
1725
1784
|
);
|
|
1785
|
+
if (fileReadErrors.length > 0) {
|
|
1786
|
+
errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
|
|
1787
|
+
}
|
|
1726
1788
|
return {
|
|
1727
1789
|
terminationReason: "completed",
|
|
1728
1790
|
messages,
|
|
@@ -2812,7 +2874,7 @@ var RawRouter = class extends BaseRouter {
|
|
|
2812
2874
|
};
|
|
2813
2875
|
|
|
2814
2876
|
// tools/warp_grep/prompts.ts
|
|
2815
|
-
var WARP_GREP_DESCRIPTION = "
|
|
2877
|
+
var WARP_GREP_DESCRIPTION = "ALWAYS use Warp Grep when you need to search a large chunk of code. Warp Grep is a fast and accurate tool that can search for all relevant context in a codebase. Warp Grep can be used for query types like: find function responsible for <small feature>; find code that does <description>; find code path for <big feature>; Where does <minimal error message> come from?; or any query of that type ";
|
|
2816
2878
|
|
|
2817
2879
|
// tools/warp_grep/openai.ts
|
|
2818
2880
|
var TOOL_PARAMETERS = {
|