@morphllm/morphsdk 0.2.201 → 0.2.203

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/dist/chunk-2PPYWRMZ.js +3 -4
  2. package/dist/{chunk-DBNSOYQ3.js → chunk-2UIOCSVJ.js} +3 -24
  3. package/dist/chunk-44OIEPIO.js +4 -23
  4. package/dist/chunk-4EQQGUZ7.cjs +104 -0
  5. package/dist/chunk-4OUGA3KS.js +1 -5
  6. package/dist/chunk-4R5MDGL6.cjs +280 -0
  7. package/dist/chunk-65W4I66Q.cjs +103 -0
  8. package/dist/{chunk-WBTXEJOC.js → chunk-66THRMD7.js} +10 -35
  9. package/dist/chunk-6TZCVTW5.js +3 -4
  10. package/dist/chunk-6WP7EA4F.js +2 -4
  11. package/dist/chunk-74A4HLIO.cjs +42 -0
  12. package/dist/chunk-75ZPJI57.cjs +9 -0
  13. package/dist/chunk-7NA7X7W2.cjs +77 -0
  14. package/dist/chunk-7PJYY46L.cjs +2 -0
  15. package/dist/chunk-AFF6XYKL.cjs +71 -0
  16. package/dist/{chunk-P2KW2O5R.js → chunk-AJBZA23L.js} +3 -25
  17. package/dist/chunk-AWFZKS27.cjs +11 -0
  18. package/dist/{chunk-FVT4PU4I.js → chunk-AXEKIRRY.js} +22 -62
  19. package/dist/chunk-B3FD67F2.cjs +256 -0
  20. package/dist/chunk-BJBWWIZV.cjs +2 -0
  21. package/dist/{chunk-M6AVXUM4.js → chunk-E3XNKAMI.js} +5 -15
  22. package/dist/{chunk-TS3OJ4LA.js → chunk-E7FLETFO.js} +2 -8
  23. package/dist/{chunk-EQAWWVKV.js → chunk-EI2M567U.js} +2 -6
  24. package/dist/chunk-EJTL2BOZ.cjs +42 -0
  25. package/dist/chunk-ETBRAKVV.js +1 -5
  26. package/dist/{chunk-VOXUA5ZH.js → chunk-EZ2OFDBJ.js} +5 -19
  27. package/dist/chunk-FBOZIVVQ.js +1 -0
  28. package/dist/{chunk-TZC3EOZS.js → chunk-GDFPZ3NJ.js} +4 -19
  29. package/dist/{chunk-LISSWRUD.js → chunk-GIQAIHUI.js} +8 -33
  30. package/dist/chunk-GSUQGDCL.cjs +235 -0
  31. package/dist/{chunk-5NSYDT36.js → chunk-H3HRSRR5.js} +4 -12
  32. package/dist/chunk-HDP4QAZL.js +1 -4
  33. package/dist/chunk-HMLYJVZM.cjs +410 -0
  34. package/dist/chunk-IPJA3ZS6.cjs +10 -0
  35. package/dist/{chunk-B376VMIH.js → chunk-IUM6CQYX.js} +3 -12
  36. package/dist/{chunk-OVLUL5AC.js → chunk-J56Q6C4Y.js} +4 -18
  37. package/dist/chunk-JBTR3FQD.cjs +135 -0
  38. package/dist/chunk-JNQKQKHS.cjs +81 -0
  39. package/dist/chunk-JOZC4T6C.cjs +168 -0
  40. package/dist/{chunk-ILY5N5NJ.js → chunk-JUGNTIVU.js} +6 -19
  41. package/dist/{chunk-SU7AAS3O.js → chunk-JY6COF3X.js} +5 -22
  42. package/dist/{chunk-JBAY3PRV.js → chunk-KLVJIC2O.js} +5 -17
  43. package/dist/chunk-KSZYOX6S.cjs +91 -0
  44. package/dist/chunk-KVGZ2TSG.cjs +274 -0
  45. package/dist/chunk-LDM7RNNN.js +1 -0
  46. package/dist/{chunk-RZOJ4GSY.js → chunk-LLQH6CCB.js} +10 -28
  47. package/dist/chunk-M34E2AMK.js +1 -5
  48. package/dist/chunk-MF56KEI4.js +1 -4
  49. package/dist/chunk-MLKGABMK.js +1 -3
  50. package/dist/{chunk-I26FQELI.js → chunk-MLPZKUCO.js} +11 -5
  51. package/dist/chunk-MWXJ6DZ2.cjs +21 -0
  52. package/dist/{chunk-NWGRW4V7.js → chunk-N7UKZ5X7.js} +2 -6
  53. package/dist/chunk-NDUC7OV6.cjs +74 -0
  54. package/dist/{chunk-RJXAXR7Q.js → chunk-NLACTMZT.js} +6 -19
  55. package/dist/chunk-NNKBKENK.cjs +15 -0
  56. package/dist/chunk-NRG6QX3L.js +1 -3
  57. package/dist/chunk-OCCGJ4S6.js +8 -0
  58. package/dist/chunk-ODY2NKQU.cjs +50 -0
  59. package/dist/chunk-OM5ZSXQW.cjs +91 -0
  60. package/dist/chunk-OOEORM7H.cjs +334 -0
  61. package/dist/chunk-OPDWMD4Q.js +1 -3
  62. package/dist/{chunk-BZXOAC2R.js → chunk-OSL4CNSO.js} +7 -23
  63. package/dist/chunk-OXXMTDOY.cjs +86 -0
  64. package/dist/chunk-PA3UTI4A.js +1 -4
  65. package/dist/chunk-QEEAIXL5.cjs +74 -0
  66. package/dist/chunk-RYVW7RUM.js +2 -6
  67. package/dist/chunk-S6QBPXBI.cjs +107 -0
  68. package/dist/chunk-TL34BLQD.cjs +10 -0
  69. package/dist/chunk-TPZHMD7J.cjs +72 -0
  70. package/dist/chunk-UAPK3AIJ.js +1 -10
  71. package/dist/chunk-UF5IKELS.cjs +26 -0
  72. package/dist/chunk-UNX7V6P6.cjs +60 -0
  73. package/dist/chunk-UUCRWJJR.cjs +313 -0
  74. package/dist/chunk-VDFLPO7B.cjs +396 -0
  75. package/dist/chunk-VHD7CW5O.cjs +43 -0
  76. package/dist/chunk-VL4QNALG.cjs +50 -0
  77. package/dist/chunk-WR7LSUIR.cjs +213 -0
  78. package/dist/chunk-XE6D4J63.cjs +72 -0
  79. package/dist/chunk-ZLG2M2I4.cjs +21 -0
  80. package/dist/chunk-ZSHVXDA2.js +4 -10
  81. package/dist/client.cjs +40 -4353
  82. package/dist/client.js +32 -37
  83. package/dist/core/client.cjs +10 -476
  84. package/dist/core/client.js +6 -11
  85. package/dist/core/error.cjs +8 -251
  86. package/dist/core/error.js +4 -9
  87. package/dist/core/index.cjs +20 -488
  88. package/dist/core/index.js +8 -19
  89. package/dist/core/resource.cjs +9 -33
  90. package/dist/core/resource.js +2 -7
  91. package/dist/edge.cjs +62 -1111
  92. package/dist/edge.js +10 -42
  93. package/dist/index.cjs +115 -4424
  94. package/dist/index.js +39 -87
  95. package/dist/modelrouter/core.cjs +28 -648
  96. package/dist/modelrouter/core.js +8 -21
  97. package/dist/modelrouter/index.cjs +28 -648
  98. package/dist/modelrouter/index.js +8 -21
  99. package/dist/modelrouter/types.cjs +1 -17
  100. package/dist/modelrouter/types.js +1 -0
  101. package/dist/subagents/anthropic.cjs +27 -2777
  102. package/dist/subagents/anthropic.js +19 -24
  103. package/dist/subagents/index.cjs +14 -95
  104. package/dist/subagents/index.js +2 -11
  105. package/dist/subagents/prompts.cjs +14 -93
  106. package/dist/subagents/prompts.js +2 -11
  107. package/dist/subagents/types.cjs +1 -17
  108. package/dist/subagents/types.js +1 -0
  109. package/dist/subagents/vercel.cjs +27 -2754
  110. package/dist/subagents/vercel.js +19 -24
  111. package/dist/tools/compact/core.cjs +12 -548
  112. package/dist/tools/compact/core.js +8 -13
  113. package/dist/tools/compact/index.cjs +17 -595
  114. package/dist/tools/compact/index.js +9 -17
  115. package/dist/tools/compact/types.cjs +1 -17
  116. package/dist/tools/compact/types.js +1 -0
  117. package/dist/tools/fastapply/anthropic.cjs +27 -891
  118. package/dist/tools/fastapply/anthropic.js +11 -24
  119. package/dist/tools/fastapply/apply.cjs +28 -672
  120. package/dist/tools/fastapply/apply.js +4 -19
  121. package/dist/tools/fastapply/core.cjs +37 -1061
  122. package/dist/tools/fastapply/core.js +9 -29
  123. package/dist/tools/fastapply/index.cjs +62 -1062
  124. package/dist/tools/fastapply/index.js +14 -44
  125. package/dist/tools/fastapply/openai.cjs +32 -901
  126. package/dist/tools/fastapply/openai.js +11 -26
  127. package/dist/tools/fastapply/prompts.cjs +10 -62
  128. package/dist/tools/fastapply/prompts.js +2 -9
  129. package/dist/tools/fastapply/types.cjs +1 -17
  130. package/dist/tools/fastapply/types.js +1 -0
  131. package/dist/tools/fastapply/vercel.cjs +25 -897
  132. package/dist/tools/fastapply/vercel.js +11 -22
  133. package/dist/tools/index.cjs +62 -1062
  134. package/dist/tools/index.js +14 -44
  135. package/dist/tools/utils/resilience.cjs +15 -312
  136. package/dist/tools/utils/resilience.js +3 -12
  137. package/dist/tools/warp_grep/agent/config.cjs +16 -127
  138. package/dist/tools/warp_grep/agent/config.js +2 -11
  139. package/dist/tools/warp_grep/agent/formatter.cjs +12 -48
  140. package/dist/tools/warp_grep/agent/formatter.js +2 -9
  141. package/dist/tools/warp_grep/agent/parser.cjs +16 -83
  142. package/dist/tools/warp_grep/agent/parser.js +2 -11
  143. package/dist/tools/warp_grep/agent/runner.cjs +15 -1081
  144. package/dist/tools/warp_grep/agent/runner.js +7 -14
  145. package/dist/tools/warp_grep/agent/types.cjs +1 -17
  146. package/dist/tools/warp_grep/agent/types.js +1 -0
  147. package/dist/tools/warp_grep/anthropic.cjs +47 -2554
  148. package/dist/tools/warp_grep/anthropic.js +19 -35
  149. package/dist/tools/warp_grep/client.cjs +49 -2464
  150. package/dist/tools/warp_grep/client.js +17 -34
  151. package/dist/tools/warp_grep/gemini.cjs +48 -2483
  152. package/dist/tools/warp_grep/gemini.js +21 -41
  153. package/dist/tools/warp_grep/harness.cjs +81 -929
  154. package/dist/tools/warp_grep/harness.js +12 -51
  155. package/dist/tools/warp_grep/index.cjs +124 -2568
  156. package/dist/tools/warp_grep/index.js +24 -87
  157. package/dist/tools/warp_grep/openai.cjs +53 -2568
  158. package/dist/tools/warp_grep/openai.js +19 -37
  159. package/dist/tools/warp_grep/providers/code_storage_http.cjs +12 -65
  160. package/dist/tools/warp_grep/providers/code_storage_http.js +2 -9
  161. package/dist/tools/warp_grep/providers/local.cjs +10 -582
  162. package/dist/tools/warp_grep/providers/local.js +6 -11
  163. package/dist/tools/warp_grep/providers/remote.cjs +8 -331
  164. package/dist/tools/warp_grep/providers/remote.js +3 -8
  165. package/dist/tools/warp_grep/providers/types.cjs +1 -17
  166. package/dist/tools/warp_grep/providers/types.js +1 -0
  167. package/dist/tools/warp_grep/utils/files.cjs +9 -42
  168. package/dist/tools/warp_grep/utils/files.js +2 -7
  169. package/dist/tools/warp_grep/utils/github.cjs +9 -43
  170. package/dist/tools/warp_grep/utils/github.js +2 -7
  171. package/dist/tools/warp_grep/utils/paths.cjs +28 -104
  172. package/dist/tools/warp_grep/utils/paths.js +2 -17
  173. package/dist/tools/warp_grep/utils/ripgrep.cjs +9 -86
  174. package/dist/tools/warp_grep/utils/ripgrep.js +2 -7
  175. package/dist/tools/warp_grep/vercel.cjs +53 -2550
  176. package/dist/tools/warp_grep/vercel.js +19 -37
  177. package/dist/version.cjs +7 -225
  178. package/dist/version.js +2 -7
  179. package/package.json +2 -2
  180. package/dist/chunk-UZCXOOZO.js +0 -203
@@ -0,0 +1,410 @@
1
+ 'use strict';
2
+
3
+ var chunkKVGZ2TSG_cjs = require('./chunk-KVGZ2TSG.cjs');
4
+ var chunk4EQQGUZ7_cjs = require('./chunk-4EQQGUZ7.cjs');
5
+ var chunkUNX7V6P6_cjs = require('./chunk-UNX7V6P6.cjs');
6
+ var chunkVL4QNALG_cjs = require('./chunk-VL4QNALG.cjs');
7
+ var chunkTL34BLQD_cjs = require('./chunk-TL34BLQD.cjs');
8
+ var OpenAI = require('openai');
9
+ var path = require('path');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
+
13
+ var OpenAI__default = /*#__PURE__*/_interopDefault(OpenAI);
14
+ var path__default = /*#__PURE__*/_interopDefault(path);
15
+
16
+ var DEFAULT_API_URL = "https://api.morphllm.com";
17
+ var TOOL_SPECS = [
18
+ {
19
+ type: "function",
20
+ function: {
21
+ name: "list_directory",
22
+ description: "Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.",
23
+ parameters: {
24
+ type: "object",
25
+ properties: {
26
+ command: {
27
+ type: "string",
28
+ description: "Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */)."
29
+ }
30
+ },
31
+ required: ["command"]
32
+ }
33
+ }
34
+ },
35
+ {
36
+ type: "function",
37
+ function: {
38
+ name: "grep_search",
39
+ description: "Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.",
40
+ parameters: {
41
+ type: "object",
42
+ properties: {
43
+ pattern: {
44
+ type: "string",
45
+ description: "Regex pattern to search for in file contents (e.g. 'class\\s+\\w+Error', 'import|require|from', 'def (get|set|update)_user')."
46
+ },
47
+ path: {
48
+ type: "string",
49
+ description: "File or directory to search in. Defaults to current working directory."
50
+ },
51
+ glob: {
52
+ type: "string",
53
+ description: "Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*')."
54
+ },
55
+ limit: {
56
+ type: "integer",
57
+ description: "Limit output to first N matching lines. Shows all matches if not specified."
58
+ }
59
+ },
60
+ required: ["pattern"]
61
+ }
62
+ }
63
+ },
64
+ {
65
+ type: "function",
66
+ function: {
67
+ name: "glob",
68
+ description: "Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.",
69
+ parameters: {
70
+ type: "object",
71
+ properties: {
72
+ pattern: {
73
+ type: "string",
74
+ description: "Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py')."
75
+ },
76
+ path: {
77
+ type: "string",
78
+ description: "Directory to search in. Defaults to repository root."
79
+ }
80
+ },
81
+ required: ["pattern"]
82
+ }
83
+ }
84
+ },
85
+ {
86
+ type: "function",
87
+ function: {
88
+ name: "read",
89
+ description: "Read entire files or specific line ranges using absolute paths.",
90
+ parameters: {
91
+ type: "object",
92
+ properties: {
93
+ path: {
94
+ type: "string",
95
+ description: "File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path)."
96
+ },
97
+ lines: {
98
+ type: "string",
99
+ description: "Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file."
100
+ }
101
+ },
102
+ required: ["path"]
103
+ }
104
+ }
105
+ },
106
+ {
107
+ type: "function",
108
+ function: {
109
+ name: "finish",
110
+ description: "Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.",
111
+ parameters: {
112
+ type: "object",
113
+ properties: {
114
+ files: {
115
+ type: "string",
116
+ description: "One file per line as path:lines (e.g. 'src/auth.py:1-15,25-50\\nsrc/user.py'). Omit line range to include entire file."
117
+ }
118
+ },
119
+ required: ["files"]
120
+ }
121
+ }
122
+ }
123
+ ];
124
+ async function callModel(messages, model, options = {}) {
125
+ const baseUrl = options.morphApiUrl || DEFAULT_API_URL;
126
+ const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
127
+ const timeoutMs = options.timeout ?? chunk4EQQGUZ7_cjs.AGENT_CONFIG.TIMEOUT_MS;
128
+ const parsedUrl = new URL(baseUrl);
129
+ const baseURL = parsedUrl.pathname === "/" ? `${baseUrl}/v1` : baseUrl;
130
+ const client = new OpenAI__default.default({
131
+ apiKey,
132
+ baseURL,
133
+ maxRetries: 0,
134
+ timeout: timeoutMs,
135
+ defaultHeaders: { "X-Morph-SDK-Version": chunkTL34BLQD_cjs.SDK_VERSION }
136
+ });
137
+ const MAX_EMPTY_RETRIES = 1;
138
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "model_call", { url: baseURL, model, message_count: messages.length });
139
+ const callStartTime = Date.now();
140
+ for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {
141
+ let data;
142
+ try {
143
+ data = await client.chat.completions.create({
144
+ model,
145
+ temperature: 0,
146
+ max_tokens: 2048,
147
+ messages,
148
+ tools: TOOL_SPECS,
149
+ ...options.search_type ? { search_type: options.search_type } : {}
150
+ });
151
+ } catch (error) {
152
+ const callLatencyMs = Date.now() - callStartTime;
153
+ if (error instanceof OpenAI__default.default.APIError) {
154
+ chunkVL4QNALG_cjs.logger.error("WarpGrep", "model_call_error", { status: error.status, error: error.message, latency_ms: callLatencyMs });
155
+ if (error.status === 404) {
156
+ const defaultMsg = "The endpoint you are trying to call is likely deprecated. Please update with: npm cache clean --force && npx -y @morphllm/morphmcp@latest or visit: https://morphllm.com/mcp";
157
+ const errorText = error.message?.trim();
158
+ throw new Error(errorText || defaultMsg);
159
+ }
160
+ } else {
161
+ chunkVL4QNALG_cjs.logger.error("WarpGrep", "model_call_error", { status: void 0, error: error instanceof Error ? error.message : String(error), latency_ms: callLatencyMs });
162
+ }
163
+ throw error;
164
+ }
165
+ const choice = data?.choices?.[0];
166
+ const message = choice?.message;
167
+ if (!message) {
168
+ if (attempt === MAX_EMPTY_RETRIES) {
169
+ throw new Error("Invalid response from model: no message in response");
170
+ }
171
+ await new Promise((resolve) => setTimeout(resolve, 200));
172
+ continue;
173
+ }
174
+ const toolCalls = (message.tool_calls || []).map((tc) => ({
175
+ id: tc.id,
176
+ type: "function",
177
+ function: { name: tc.function.name, arguments: tc.function.arguments }
178
+ }));
179
+ if (message.content || toolCalls.length > 0) {
180
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "model_call_complete", { latency_ms: Date.now() - callStartTime, tool_calls_count: toolCalls.length, finish_reason: choice?.finish_reason ?? "unknown" });
181
+ return { content: message.content ?? null, tool_calls: toolCalls };
182
+ }
183
+ if (attempt === MAX_EMPTY_RETRIES) {
184
+ const finishReason = choice?.finish_reason ?? "unknown";
185
+ throw new Error(
186
+ `Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`
187
+ );
188
+ }
189
+ await new Promise((resolve) => setTimeout(resolve, 200));
190
+ }
191
+ throw new Error("Invalid response from model");
192
+ }
193
+ function safeParseJSON(s) {
194
+ try {
195
+ return JSON.parse(s);
196
+ } catch {
197
+ return {};
198
+ }
199
+ }
200
+ async function executeTool(provider, name, args, repoRoot) {
201
+ switch (name) {
202
+ case "grep_search": {
203
+ const grepArgs = {
204
+ pattern: args.pattern,
205
+ path: args.path || "."
206
+ };
207
+ if (args.glob) grepArgs.glob = args.glob;
208
+ if (args.case_sensitive !== void 0) grepArgs.case_sensitive = args.case_sensitive;
209
+ const result = await chunkKVGZ2TSG_cjs.toolGrep(provider, grepArgs);
210
+ let output = result.output;
211
+ if (args.limit && typeof args.limit === "number") {
212
+ const lines = output.split("\n");
213
+ if (lines.length > args.limit) {
214
+ output = lines.slice(0, args.limit).join("\n") + `
215
+ ... (truncated at ${args.limit} lines)`;
216
+ }
217
+ }
218
+ return output;
219
+ }
220
+ case "glob": {
221
+ return chunkKVGZ2TSG_cjs.toolGlob(provider, {
222
+ pattern: args.pattern,
223
+ path: args.path
224
+ });
225
+ }
226
+ case "list_directory": {
227
+ const dirPath = chunkUNX7V6P6_cjs.extractPathFromCommand(args.command || ".");
228
+ return chunkKVGZ2TSG_cjs.toolListDirectory(provider, { path: dirPath }, repoRoot);
229
+ }
230
+ case "read": {
231
+ const readArgs = {
232
+ path: args.path
233
+ };
234
+ if (args.lines && typeof args.lines === "string") {
235
+ Object.assign(readArgs, chunkUNX7V6P6_cjs.parseReadLines(args.lines));
236
+ }
237
+ return chunkKVGZ2TSG_cjs.toolRead(provider, readArgs);
238
+ }
239
+ default:
240
+ return `Unknown tool: ${name}`;
241
+ }
242
+ }
243
+ async function* runWarpGrepStreaming(config) {
244
+ const totalStart = Date.now();
245
+ const timeoutMs = config.timeout ?? chunk4EQQGUZ7_cjs.AGENT_CONFIG.TIMEOUT_MS;
246
+ const timings = { turns: [], timeout_ms: timeoutMs };
247
+ const repoRoot = config.repoRoot || process.cwd();
248
+ const model = config.model || chunk4EQQGUZ7_cjs.DEFAULT_MODEL;
249
+ const messages = [];
250
+ const maxTurns = chunk4EQQGUZ7_cjs.AGENT_CONFIG.MAX_TURNS;
251
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "session_start", { search_term: config.searchTerm, model, max_turns: maxTurns });
252
+ const initialStateStart = Date.now();
253
+ const initialState = await chunkKVGZ2TSG_cjs.buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });
254
+ timings.initial_state_ms = Date.now() - initialStateStart;
255
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "initial_state", { system_prompt_len: initialState.length, user_message_len: initialState.length });
256
+ messages.push({ role: "user", content: initialState });
257
+ const provider = config.provider;
258
+ const errors = [];
259
+ let finishMeta;
260
+ let terminationReason = "terminated";
261
+ for (let turn = 1; turn <= maxTurns; turn += 1) {
262
+ const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
263
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "turn_start", { turn, message_count: messages.length });
264
+ const beforeChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
265
+ chunkKVGZ2TSG_cjs.enforceContextLimit(messages);
266
+ const afterChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
267
+ if (afterChars < beforeChars) {
268
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "context_truncated", { before_chars: beforeChars, after_chars: afterChars });
269
+ }
270
+ const modelCallStart = Date.now();
271
+ const response = await callModel(messages, model, {
272
+ morphApiKey: config.morphApiKey,
273
+ morphApiUrl: config.morphApiUrl,
274
+ retryConfig: config.retryConfig,
275
+ timeout: timeoutMs,
276
+ search_type: config.search_type
277
+ }).catch((e) => {
278
+ const errMsg = e instanceof Error ? e.message : String(e);
279
+ console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
280
+ chunkVL4QNALG_cjs.logger.error("WarpGrep", "error", { turn, error: errMsg, phase: "model_call" });
281
+ errors.push({ message: errMsg });
282
+ return null;
283
+ });
284
+ turnMetrics.morph_api_ms = Date.now() - modelCallStart;
285
+ if (!response) {
286
+ timings.turns.push(turnMetrics);
287
+ break;
288
+ }
289
+ const toolCalls = response.tool_calls;
290
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "model_response", { turn, tool_calls: toolCalls.map((tc) => tc.function.name), latency_ms: turnMetrics.morph_api_ms });
291
+ messages.push({
292
+ role: "assistant",
293
+ content: response.content,
294
+ ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
295
+ });
296
+ if (toolCalls.length === 0) {
297
+ console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || "").slice(0, 500)}`);
298
+ errors.push({ message: "No tool calls produced by the model." });
299
+ terminationReason = "terminated";
300
+ timings.turns.push(turnMetrics);
301
+ break;
302
+ }
303
+ yield {
304
+ turn,
305
+ toolCalls: toolCalls.map((tc) => ({
306
+ name: tc.function.name,
307
+ arguments: safeParseJSON(tc.function.arguments)
308
+ }))
309
+ };
310
+ const finishCall = toolCalls.find((tc) => tc.function.name === "finish");
311
+ if (finishCall) {
312
+ const args = safeParseJSON(finishCall.function.arguments);
313
+ const filesStr = args.files || "";
314
+ const files = chunkUNX7V6P6_cjs.parseFinishFiles(filesStr);
315
+ finishMeta = { files };
316
+ terminationReason = "completed";
317
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "finish", { turns: turn, files: files.map((f) => f.path) });
318
+ if (files.length === 0) {
319
+ const payload2 = filesStr || "No relevant code found.";
320
+ timings.turns.push(turnMetrics);
321
+ timings.total_ms = Date.now() - totalStart;
322
+ return {
323
+ terminationReason: "completed",
324
+ messages,
325
+ finish: { payload: payload2, metadata: finishMeta },
326
+ timings
327
+ };
328
+ }
329
+ timings.turns.push(turnMetrics);
330
+ break;
331
+ }
332
+ const toolExecStart = Date.now();
333
+ const results = await Promise.all(
334
+ toolCalls.map(async (tc) => {
335
+ const args = safeParseJSON(tc.function.arguments);
336
+ const argsSummary = Object.fromEntries(Object.entries(args).map(([k, v]) => [k, typeof v === "string" && v.length > 100 ? v.slice(0, 100) + "..." : v]));
337
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "tool_exec", { turn, tool: tc.function.name, args_summary: argsSummary });
338
+ const toolStart = Date.now();
339
+ const output = await executeTool(provider, tc.function.name, args, repoRoot).catch((err) => String(err));
340
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "tool_result", { turn, tool: tc.function.name, result_len: output.length, latency_ms: Date.now() - toolStart });
341
+ return { tool_call_id: tc.id, content: output };
342
+ })
343
+ );
344
+ turnMetrics.local_tools_ms = Date.now() - toolExecStart;
345
+ for (const result of results) {
346
+ messages.push({ role: "tool", tool_call_id: result.tool_call_id, content: result.content });
347
+ }
348
+ const turnMsg = chunkKVGZ2TSG_cjs.formatTurnMessage(turn, maxTurns);
349
+ const budget = chunkKVGZ2TSG_cjs.calculateContextBudget(messages);
350
+ messages.push({ role: "user", content: turnMsg + "\n" + budget });
351
+ timings.turns.push(turnMetrics);
352
+ }
353
+ if (terminationReason !== "completed" || !finishMeta) {
354
+ timings.total_ms = Date.now() - totalStart;
355
+ return { terminationReason, messages, errors, timings };
356
+ }
357
+ const parts = ["Relevant context found:"];
358
+ for (const f of finishMeta.files) {
359
+ const ranges = f.lines === "*" ? "*" : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(", ") : "*";
360
+ parts.push(`- ${f.path}: ${ranges}`);
361
+ }
362
+ const payload = parts.join("\n");
363
+ const finishResolutionStart = Date.now();
364
+ const fileReadErrors = [];
365
+ const resolved = await chunkKVGZ2TSG_cjs.readFinishFiles(
366
+ repoRoot,
367
+ finishMeta.files,
368
+ async (p, s, e) => {
369
+ let resolvedPath = p;
370
+ if (!p.startsWith(repoRoot)) {
371
+ const relative = p.startsWith("/") ? p.slice(1) : p;
372
+ resolvedPath = path__default.default.join(repoRoot, relative);
373
+ }
374
+ try {
375
+ const rr = await provider.read({ path: resolvedPath, start: s, end: e });
376
+ return rr.lines.map((l) => {
377
+ const idx = l.indexOf("|");
378
+ return idx >= 0 ? l.slice(idx + 1) : l;
379
+ });
380
+ } catch (err) {
381
+ const errorMsg = err instanceof Error ? err.message : String(err);
382
+ fileReadErrors.push({ path: resolvedPath, error: errorMsg });
383
+ console.error(`[warp_grep] Failed to read file: ${resolvedPath} - ${errorMsg}`);
384
+ return [`[couldn't find: ${resolvedPath}]`];
385
+ }
386
+ }
387
+ );
388
+ timings.finish_resolution_ms = Date.now() - finishResolutionStart;
389
+ if (fileReadErrors.length > 0) {
390
+ errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
391
+ }
392
+ timings.total_ms = Date.now() - totalStart;
393
+ return {
394
+ terminationReason: "completed",
395
+ messages,
396
+ finish: { payload, metadata: finishMeta, resolved },
397
+ timings
398
+ };
399
+ }
400
+ async function runWarpGrep(config) {
401
+ const gen = runWarpGrepStreaming(config);
402
+ let result = await gen.next();
403
+ while (!result.done) {
404
+ result = await gen.next();
405
+ }
406
+ return result.value;
407
+ }
408
+
409
+ exports.runWarpGrep = runWarpGrep;
410
+ exports.runWarpGrepStreaming = runWarpGrepStreaming;
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+
5
+ // tools/warp_grep/index.ts
6
+ var warpGrepInputSchema = zod.z.object({
7
+ search_term: zod.z.string().describe("Search problem statement that this subagent is supposed to research for")
8
+ });
9
+
10
+ exports.warpGrepInputSchema = warpGrepInputSchema;
@@ -1,12 +1,5 @@
1
- import {
2
- WarpGrepClient,
3
- formatResult
4
- } from "./chunk-WBTXEJOC.js";
5
- import {
6
- CODEBASE_SEARCH_TOOL,
7
- SEND_MESSAGE_TOOL,
8
- getSystemPrompt
9
- } from "./chunk-ETBRAKVV.js";
1
+ import { WarpGrepClient, formatResult } from './chunk-66THRMD7.js';
2
+ import { CODEBASE_SEARCH_TOOL, SEND_MESSAGE_TOOL, getSystemPrompt } from './chunk-ETBRAKVV.js';
10
3
 
11
4
  // subagents/anthropic.ts
12
5
  var DEFAULT_MAX_TURNS = {
@@ -282,6 +275,4 @@ function deduplicateContexts(contexts) {
282
275
  return Array.from(map.values());
283
276
  }
284
277
 
285
- export {
286
- createExploreSubagent
287
- };
278
+ export { createExploreSubagent };
@@ -1,13 +1,6 @@
1
- import {
2
- EDIT_FILE_SYSTEM_PROMPT,
3
- EDIT_FILE_TOOL_DESCRIPTION
4
- } from "./chunk-PA3UTI4A.js";
5
- import {
6
- executeEditFile
7
- } from "./chunk-RZOJ4GSY.js";
8
- import {
9
- __export
10
- } from "./chunk-MLKGABMK.js";
1
+ import { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './chunk-PA3UTI4A.js';
2
+ import { executeEditFile } from './chunk-LLQH6CCB.js';
3
+ import { __export } from './chunk-MLKGABMK.js';
11
4
 
12
5
  // tools/fastapply/anthropic.ts
13
6
  var anthropic_exports = {};
@@ -71,11 +64,4 @@ function getSystemPrompt() {
71
64
  return EDIT_FILE_SYSTEM_PROMPT;
72
65
  }
73
66
 
74
- export {
75
- editFileTool,
76
- formatResult,
77
- createEditFileTool,
78
- execute,
79
- getSystemPrompt,
80
- anthropic_exports
81
- };
67
+ export { anthropic_exports, createEditFileTool, editFileTool, execute, formatResult, getSystemPrompt };
@@ -0,0 +1,135 @@
1
+ 'use strict';
2
+
3
+ var chunkVDFLPO7B_cjs = require('./chunk-VDFLPO7B.cjs');
4
+ var chunk65W4I66Q_cjs = require('./chunk-65W4I66Q.cjs');
5
+ var chunkVL4QNALG_cjs = require('./chunk-VL4QNALG.cjs');
6
+ var chunkAWFZKS27_cjs = require('./chunk-AWFZKS27.cjs');
7
+ var path = require('path');
8
+
9
+ var DEFAULT_CONFIG = {
10
+ baseDir: process.cwd(),
11
+ generateUdiff: true,
12
+ autoWrite: true,
13
+ timeout: 6e5};
14
+ var FastApplyClient = class extends chunkAWFZKS27_cjs.APIResource {
15
+ config;
16
+ constructor(clientOrConfig = {}) {
17
+ const isClient = clientOrConfig instanceof chunk65W4I66Q_cjs.MorphAPIClient;
18
+ super(
19
+ isClient ? clientOrConfig : new chunk65W4I66Q_cjs.MorphAPIClient({
20
+ apiKey: clientOrConfig.apiKey,
21
+ timeout: clientOrConfig.timeout ?? DEFAULT_CONFIG.timeout,
22
+ retryConfig: clientOrConfig.retryConfig,
23
+ debug: clientOrConfig.debug
24
+ })
25
+ );
26
+ this.config = {
27
+ morphApiKey: this._client.resolveApiKey(),
28
+ morphApiUrl: this._client.baseURL,
29
+ debug: this._client.debug,
30
+ timeout: (isClient ? void 0 : clientOrConfig.timeout) ?? DEFAULT_CONFIG.timeout,
31
+ retryConfig: this._client.retryConfig,
32
+ generateUdiff: DEFAULT_CONFIG.generateUdiff,
33
+ autoWrite: DEFAULT_CONFIG.autoWrite
34
+ };
35
+ }
36
+ /**
37
+ * Execute a file edit operation
38
+ *
39
+ * @param input - Edit parameters including filepath, instructions, and code_edit
40
+ * @param overrides - Optional config overrides for this operation
41
+ * @returns Edit result with success status and changes
42
+ */
43
+ async execute(input, overrides) {
44
+ return executeEditFile(input, { ...this.config, ...overrides });
45
+ }
46
+ /**
47
+ * Apply an edit to code directly without file I/O
48
+ *
49
+ * Useful for sandbox environments or when you manage your own file system.
50
+ * Compatible with the earlier OpenAI client API contract.
51
+ *
52
+ * @param input - Code and edit parameters
53
+ * @param overrides - Optional config overrides for this operation
54
+ * @returns Result with merged code
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * const result = await client.applyEdit({
59
+ * originalCode: 'function hello() { return "world"; }',
60
+ * codeEdit: 'function hello() { return "universe"; }',
61
+ * instructions: 'Change return value'
62
+ * });
63
+ * console.log(result.mergedCode);
64
+ * ```
65
+ */
66
+ async applyEdit(input, overrides) {
67
+ const { applyEdit: applyEdit2 } = await import('./tools/fastapply/apply.cjs');
68
+ return applyEdit2(input, { ...this.config, ...overrides });
69
+ }
70
+ };
71
+ async function executeEditFile(input, config = {}) {
72
+ const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;
73
+ const fullPath = path.resolve(path.join(baseDir, input.target_filepath));
74
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "execute_start", { target_filepath: input.target_filepath, baseDir, autoWrite: config.autoWrite !== false });
75
+ const relativePath = path.relative(baseDir, fullPath);
76
+ if (relativePath.startsWith("..") || fullPath === baseDir) {
77
+ chunkVL4QNALG_cjs.logger.warn("FastApply", "security_check_failed", { target_filepath: input.target_filepath, relative: relativePath });
78
+ return {
79
+ success: false,
80
+ filepath: input.target_filepath,
81
+ changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
82
+ error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`
83
+ };
84
+ }
85
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "security_check", { resolved: fullPath, relative: relativePath });
86
+ try {
87
+ const { readFile, writeFile } = await import('fs/promises');
88
+ const { callMorphAPI: callMorphAPI2, generateUdiff: generateUdiff2, countChanges: countChanges2 } = await import('./tools/fastapply/apply.cjs');
89
+ let originalCode = "";
90
+ let fileExists = true;
91
+ try {
92
+ originalCode = await readFile(fullPath, "utf-8");
93
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "file_read", { path: fullPath, exists: true, size_bytes: originalCode.length });
94
+ } catch (error) {
95
+ if (error.code !== "ENOENT") {
96
+ throw error;
97
+ }
98
+ fileExists = false;
99
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "file_read", { path: fullPath, exists: false });
100
+ }
101
+ const instruction = input.instruction ?? input.instructions ?? "";
102
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "api_call", { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });
103
+ const { content: mergedCode, completionId } = await callMorphAPI2(originalCode, input.code_edit, instruction, input.target_filepath, config);
104
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "api_response", { completion_id: completionId, merged_len: mergedCode.length });
105
+ const udiff = config.generateUdiff !== false ? generateUdiff2(originalCode, mergedCode, input.target_filepath) : void 0;
106
+ if (config.autoWrite !== false) {
107
+ await writeFile(fullPath, mergedCode, "utf-8");
108
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "file_write", { path: fullPath, size_bytes: mergedCode.length });
109
+ }
110
+ const changes = countChanges2(originalCode, mergedCode);
111
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "changes", { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });
112
+ return {
113
+ success: true,
114
+ filepath: input.target_filepath,
115
+ udiff,
116
+ changes,
117
+ completionId
118
+ };
119
+ } catch (error) {
120
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
121
+ const structuredError = error instanceof chunkVDFLPO7B_cjs.FastApplyContextLengthError || error instanceof chunkVDFLPO7B_cjs.FastApplyAnchorIntegrityError ? error : void 0;
122
+ chunkVL4QNALG_cjs.logger.error("FastApply", "execute_error", { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : void 0 });
123
+ return {
124
+ success: false,
125
+ filepath: input.target_filepath,
126
+ changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
127
+ error: errorMessage,
128
+ errorCode: structuredError?.code,
129
+ completionId: structuredError?.completionId
130
+ };
131
+ }
132
+ }
133
+
134
+ exports.FastApplyClient = FastApplyClient;
135
+ exports.executeEditFile = executeEditFile;
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+
3
+ var chunk74A4HLIO_cjs = require('./chunk-74A4HLIO.cjs');
4
+ var chunkJBTR3FQD_cjs = require('./chunk-JBTR3FQD.cjs');
5
+ var chunk75ZPJI57_cjs = require('./chunk-75ZPJI57.cjs');
6
+ var ai = require('ai');
7
+ var zod = require('zod');
8
+
9
+ // tools/fastapply/vercel.ts
10
+ var vercel_exports = {};
11
+ chunk75ZPJI57_cjs.__export(vercel_exports, {
12
+ createEditFileTool: () => createEditFileTool,
13
+ default: () => vercel_default,
14
+ editFileTool: () => editFileTool,
15
+ getSystemPrompt: () => getSystemPrompt
16
+ });
17
+ var editFileSchema = zod.z.object({
18
+ target_filepath: zod.z.string().describe("The path of the target file to modify"),
19
+ instruction: zod.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
20
+ code_edit: zod.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
21
+ });
22
+ var editFileTool = ai.tool({
23
+ description: chunk74A4HLIO_cjs.EDIT_FILE_TOOL_DESCRIPTION,
24
+ inputSchema: editFileSchema,
25
+ execute: async (params) => {
26
+ const result = await chunkJBTR3FQD_cjs.executeEditFile({
27
+ target_filepath: params.target_filepath,
28
+ instruction: params.instruction,
29
+ code_edit: params.code_edit
30
+ });
31
+ if (!result.success) {
32
+ throw new Error(`Failed to edit file: ${result.error}`);
33
+ }
34
+ return {
35
+ success: true,
36
+ filepath: result.filepath,
37
+ changes: result.changes,
38
+ udiff: result.udiff
39
+ };
40
+ }
41
+ });
42
+ function getSystemPrompt() {
43
+ return chunk74A4HLIO_cjs.EDIT_FILE_SYSTEM_PROMPT;
44
+ }
45
+ function createEditFileTool(config = {}) {
46
+ const schema = zod.z.object({
47
+ target_filepath: zod.z.string().describe("The path of the target file to modify"),
48
+ instruction: zod.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
49
+ code_edit: zod.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
50
+ });
51
+ return ai.tool({
52
+ description: config.description || chunk74A4HLIO_cjs.EDIT_FILE_TOOL_DESCRIPTION,
53
+ inputSchema: schema,
54
+ execute: async (params) => {
55
+ const result = await chunkJBTR3FQD_cjs.executeEditFile(
56
+ {
57
+ target_filepath: params.target_filepath,
58
+ instruction: params.instruction,
59
+ code_edit: params.code_edit
60
+ },
61
+ config
62
+ );
63
+ if (!result.success) {
64
+ throw new Error(`Failed to edit file: ${result.error}`);
65
+ }
66
+ return {
67
+ success: true,
68
+ filepath: result.filepath,
69
+ changes: result.changes,
70
+ udiff: result.udiff
71
+ };
72
+ }
73
+ });
74
+ }
75
+ var vercel_default = editFileTool;
76
+
77
+ exports.createEditFileTool = createEditFileTool;
78
+ exports.editFileTool = editFileTool;
79
+ exports.getSystemPrompt = getSystemPrompt;
80
+ exports.vercel_default = vercel_default;
81
+ exports.vercel_exports = vercel_exports;