@morphllm/morphsdk 0.2.145 → 0.2.146

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 (205) hide show
  1. package/dist/{chunk-HBIW2XV2.js → chunk-4PBUB77N.js} +2 -2
  2. package/dist/{chunk-SUE4GYA2.js → chunk-BDHKL3MT.js} +2 -2
  3. package/dist/{chunk-S54SPKX3.js → chunk-BIQ7234U.js} +2 -2
  4. package/dist/{chunk-I3J46TSB.js → chunk-DKODF3YG.js} +4 -5
  5. package/dist/chunk-DKODF3YG.js.map +1 -0
  6. package/dist/{chunk-MRPASJBX.js → chunk-E45FW5EK.js} +2 -2
  7. package/dist/{chunk-BXRJYLRS.js → chunk-E4YKEKGW.js} +2 -2
  8. package/dist/{chunk-G23BI5CQ.js → chunk-EU7OLX4Z.js} +2 -2
  9. package/dist/chunk-EUHNJMWL.js +409 -0
  10. package/dist/chunk-EUHNJMWL.js.map +1 -0
  11. package/dist/{chunk-HE7K2QNQ.js → chunk-FBOJJ3UY.js} +17 -17
  12. package/dist/{chunk-HYRHI2UL.js → chunk-FIVYDIHX.js} +1 -1
  13. package/dist/{chunk-GXM3G7Z4.js → chunk-FYO46OT6.js} +2 -2
  14. package/dist/{chunk-GHPQYSSF.js → chunk-GJUB3ECP.js} +2 -2
  15. package/dist/{chunk-4Y2NM6JD.js → chunk-HZOTLGJH.js} +2 -42
  16. package/dist/chunk-HZOTLGJH.js.map +1 -0
  17. package/dist/{chunk-MTJ3PR4M.js → chunk-I7SFRYTX.js} +2 -2
  18. package/dist/{chunk-PX7ODEML.js → chunk-J2HIK4GB.js} +2 -2
  19. package/dist/{chunk-RZXS4ADX.js → chunk-JSWNBCGS.js} +2 -2
  20. package/dist/{chunk-GXCWKYGU.js → chunk-KYKRRF7E.js} +2 -2
  21. package/dist/{chunk-N7TTZIBK.js → chunk-MMBQKN4G.js} +2 -2
  22. package/dist/{chunk-B3AKP3RA.js → chunk-NF2QWJDY.js} +2 -31
  23. package/dist/chunk-NF2QWJDY.js.map +1 -0
  24. package/dist/{chunk-JMUAQQJU.js → chunk-NKUSUSVI.js} +3 -3
  25. package/dist/{chunk-VRV5UYTN.js → chunk-OV57JBMB.js} +2 -2
  26. package/dist/{chunk-EPIOAODF.js → chunk-Q36MNOFA.js} +2 -2
  27. package/dist/{chunk-JRBU4UNP.js → chunk-QRSWXP4K.js} +2 -2
  28. package/dist/{chunk-KELRCMA6.js → chunk-SJYAKVSS.js} +2 -2
  29. package/dist/{chunk-KELRCMA6.js.map → chunk-SJYAKVSS.js.map} +1 -1
  30. package/dist/{chunk-IRWHN55G.js → chunk-T564HFSH.js} +1 -1
  31. package/dist/{chunk-6CFKWZK3.js → chunk-UVNENJ6H.js} +3 -3
  32. package/dist/{chunk-5FCXLQJU.js → chunk-UYPWKQKV.js} +2 -2
  33. package/dist/{chunk-BAF33L6C.js → chunk-V73GO5AJ.js} +2 -2
  34. package/dist/chunk-VCKJ22DX.js +131 -0
  35. package/dist/chunk-VCKJ22DX.js.map +1 -0
  36. package/dist/{chunk-XL7R3XN5.js → chunk-VZ6VYRQB.js} +2 -2
  37. package/dist/{chunk-4LWMPKSB.js → chunk-YIETFYCL.js} +44 -71
  38. package/dist/chunk-YIETFYCL.js.map +1 -0
  39. package/dist/client.cjs +438 -426
  40. package/dist/client.cjs.map +1 -1
  41. package/dist/client.js +27 -26
  42. package/dist/edge.cjs +1 -1
  43. package/dist/edge.cjs.map +1 -1
  44. package/dist/edge.js +4 -4
  45. package/dist/{finish-Ddj1MPGt.d.ts → finish-DBKuo8yj.d.ts} +1 -1
  46. package/dist/index.cjs +438 -445
  47. package/dist/index.cjs.map +1 -1
  48. package/dist/index.js +29 -29
  49. package/dist/modelrouter/core.cjs +1 -1
  50. package/dist/modelrouter/core.cjs.map +1 -1
  51. package/dist/modelrouter/core.js +3 -3
  52. package/dist/modelrouter/index.cjs +1 -1
  53. package/dist/modelrouter/index.cjs.map +1 -1
  54. package/dist/modelrouter/index.js +3 -3
  55. package/dist/subagents/anthropic.cjs +434 -422
  56. package/dist/subagents/anthropic.cjs.map +1 -1
  57. package/dist/subagents/anthropic.js +9 -8
  58. package/dist/subagents/vercel.cjs +434 -422
  59. package/dist/subagents/vercel.cjs.map +1 -1
  60. package/dist/subagents/vercel.js +9 -8
  61. package/dist/tools/browser/anthropic.cjs +1 -1
  62. package/dist/tools/browser/anthropic.cjs.map +1 -1
  63. package/dist/tools/browser/anthropic.js +5 -5
  64. package/dist/tools/browser/core.cjs +1 -1
  65. package/dist/tools/browser/core.cjs.map +1 -1
  66. package/dist/tools/browser/core.js +4 -4
  67. package/dist/tools/browser/index.cjs +1 -1
  68. package/dist/tools/browser/index.cjs.map +1 -1
  69. package/dist/tools/browser/index.js +7 -7
  70. package/dist/tools/browser/openai.cjs +1 -1
  71. package/dist/tools/browser/openai.cjs.map +1 -1
  72. package/dist/tools/browser/openai.js +5 -5
  73. package/dist/tools/browser/profiles/core.cjs +1 -1
  74. package/dist/tools/browser/profiles/core.cjs.map +1 -1
  75. package/dist/tools/browser/profiles/core.js +3 -3
  76. package/dist/tools/browser/profiles/index.cjs +1 -1
  77. package/dist/tools/browser/profiles/index.cjs.map +1 -1
  78. package/dist/tools/browser/profiles/index.js +3 -3
  79. package/dist/tools/browser/vercel.cjs +1 -1
  80. package/dist/tools/browser/vercel.cjs.map +1 -1
  81. package/dist/tools/browser/vercel.js +5 -5
  82. package/dist/tools/codebase_search/anthropic.cjs +1 -1
  83. package/dist/tools/codebase_search/anthropic.cjs.map +1 -1
  84. package/dist/tools/codebase_search/anthropic.js +4 -4
  85. package/dist/tools/codebase_search/core.cjs +1 -1
  86. package/dist/tools/codebase_search/core.cjs.map +1 -1
  87. package/dist/tools/codebase_search/core.js +3 -3
  88. package/dist/tools/codebase_search/index.cjs +1 -1
  89. package/dist/tools/codebase_search/index.cjs.map +1 -1
  90. package/dist/tools/codebase_search/index.js +6 -6
  91. package/dist/tools/codebase_search/openai.cjs +1 -1
  92. package/dist/tools/codebase_search/openai.cjs.map +1 -1
  93. package/dist/tools/codebase_search/openai.js +4 -4
  94. package/dist/tools/codebase_search/vercel.cjs +1 -1
  95. package/dist/tools/codebase_search/vercel.cjs.map +1 -1
  96. package/dist/tools/codebase_search/vercel.js +4 -4
  97. package/dist/tools/fastapply/anthropic.cjs +1 -1
  98. package/dist/tools/fastapply/anthropic.cjs.map +1 -1
  99. package/dist/tools/fastapply/anthropic.js +4 -4
  100. package/dist/tools/fastapply/apply.cjs +1 -1
  101. package/dist/tools/fastapply/apply.cjs.map +1 -1
  102. package/dist/tools/fastapply/apply.js +2 -2
  103. package/dist/tools/fastapply/core.cjs +1 -1
  104. package/dist/tools/fastapply/core.cjs.map +1 -1
  105. package/dist/tools/fastapply/core.js +3 -3
  106. package/dist/tools/fastapply/index.cjs +1 -1
  107. package/dist/tools/fastapply/index.cjs.map +1 -1
  108. package/dist/tools/fastapply/index.js +6 -6
  109. package/dist/tools/fastapply/openai.cjs +1 -1
  110. package/dist/tools/fastapply/openai.cjs.map +1 -1
  111. package/dist/tools/fastapply/openai.js +4 -4
  112. package/dist/tools/fastapply/vercel.cjs +1 -1
  113. package/dist/tools/fastapply/vercel.cjs.map +1 -1
  114. package/dist/tools/fastapply/vercel.js +4 -4
  115. package/dist/tools/index.cjs +1 -1
  116. package/dist/tools/index.cjs.map +1 -1
  117. package/dist/tools/index.js +6 -6
  118. package/dist/tools/utils/resilience.cjs +1 -1
  119. package/dist/tools/utils/resilience.cjs.map +1 -1
  120. package/dist/tools/utils/resilience.js +2 -2
  121. package/dist/tools/warp_grep/agent/config.cjs +3 -4
  122. package/dist/tools/warp_grep/agent/config.cjs.map +1 -1
  123. package/dist/tools/warp_grep/agent/config.d.ts +1 -2
  124. package/dist/tools/warp_grep/agent/config.js +1 -1
  125. package/dist/tools/warp_grep/agent/parser.cjs +121 -52
  126. package/dist/tools/warp_grep/agent/parser.cjs.map +1 -1
  127. package/dist/tools/warp_grep/agent/parser.d.ts +5 -12
  128. package/dist/tools/warp_grep/agent/parser.js +3 -7
  129. package/dist/tools/warp_grep/agent/runner.cjs +416 -335
  130. package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
  131. package/dist/tools/warp_grep/agent/runner.d.ts +3 -6
  132. package/dist/tools/warp_grep/agent/runner.js +6 -5
  133. package/dist/tools/warp_grep/agent/types.cjs.map +1 -1
  134. package/dist/tools/warp_grep/agent/types.d.ts +3 -22
  135. package/dist/tools/warp_grep/anthropic.cjs +434 -422
  136. package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
  137. package/dist/tools/warp_grep/anthropic.js +9 -8
  138. package/dist/tools/warp_grep/client.cjs +434 -422
  139. package/dist/tools/warp_grep/client.cjs.map +1 -1
  140. package/dist/tools/warp_grep/client.js +8 -7
  141. package/dist/tools/warp_grep/gemini.cjs +434 -422
  142. package/dist/tools/warp_grep/gemini.cjs.map +1 -1
  143. package/dist/tools/warp_grep/gemini.js +8 -7
  144. package/dist/tools/warp_grep/gemini.js.map +1 -1
  145. package/dist/tools/warp_grep/harness.cjs +176 -164
  146. package/dist/tools/warp_grep/harness.cjs.map +1 -1
  147. package/dist/tools/warp_grep/harness.d.ts +38 -17
  148. package/dist/tools/warp_grep/harness.js +14 -15
  149. package/dist/tools/warp_grep/harness.js.map +1 -1
  150. package/dist/tools/warp_grep/index.cjs +434 -441
  151. package/dist/tools/warp_grep/index.cjs.map +1 -1
  152. package/dist/tools/warp_grep/index.d.ts +1 -1
  153. package/dist/tools/warp_grep/index.js +10 -10
  154. package/dist/tools/warp_grep/openai.cjs +434 -422
  155. package/dist/tools/warp_grep/openai.cjs.map +1 -1
  156. package/dist/tools/warp_grep/openai.js +9 -8
  157. package/dist/tools/warp_grep/providers/local.cjs +2 -43
  158. package/dist/tools/warp_grep/providers/local.cjs.map +1 -1
  159. package/dist/tools/warp_grep/providers/local.d.ts +1 -5
  160. package/dist/tools/warp_grep/providers/local.js +2 -2
  161. package/dist/tools/warp_grep/providers/remote.cjs +2 -32
  162. package/dist/tools/warp_grep/providers/remote.cjs.map +1 -1
  163. package/dist/tools/warp_grep/providers/remote.d.ts +1 -9
  164. package/dist/tools/warp_grep/providers/remote.js +2 -2
  165. package/dist/tools/warp_grep/providers/types.cjs.map +1 -1
  166. package/dist/tools/warp_grep/providers/types.d.ts +1 -14
  167. package/dist/tools/warp_grep/vercel.cjs +434 -422
  168. package/dist/tools/warp_grep/vercel.cjs.map +1 -1
  169. package/dist/tools/warp_grep/vercel.js +9 -8
  170. package/dist/version.cjs +1 -1
  171. package/dist/version.cjs.map +1 -1
  172. package/dist/version.js +1 -1
  173. package/package.json +1 -1
  174. package/dist/chunk-4LWMPKSB.js.map +0 -1
  175. package/dist/chunk-4Y2NM6JD.js.map +0 -1
  176. package/dist/chunk-B3AKP3RA.js.map +0 -1
  177. package/dist/chunk-CMSHXALI.js +0 -60
  178. package/dist/chunk-CMSHXALI.js.map +0 -1
  179. package/dist/chunk-I3J46TSB.js.map +0 -1
  180. package/dist/chunk-OPEQQGST.js +0 -396
  181. package/dist/chunk-OPEQQGST.js.map +0 -1
  182. /package/dist/{chunk-HBIW2XV2.js.map → chunk-4PBUB77N.js.map} +0 -0
  183. /package/dist/{chunk-SUE4GYA2.js.map → chunk-BDHKL3MT.js.map} +0 -0
  184. /package/dist/{chunk-S54SPKX3.js.map → chunk-BIQ7234U.js.map} +0 -0
  185. /package/dist/{chunk-MRPASJBX.js.map → chunk-E45FW5EK.js.map} +0 -0
  186. /package/dist/{chunk-BXRJYLRS.js.map → chunk-E4YKEKGW.js.map} +0 -0
  187. /package/dist/{chunk-G23BI5CQ.js.map → chunk-EU7OLX4Z.js.map} +0 -0
  188. /package/dist/{chunk-HE7K2QNQ.js.map → chunk-FBOJJ3UY.js.map} +0 -0
  189. /package/dist/{chunk-HYRHI2UL.js.map → chunk-FIVYDIHX.js.map} +0 -0
  190. /package/dist/{chunk-GXM3G7Z4.js.map → chunk-FYO46OT6.js.map} +0 -0
  191. /package/dist/{chunk-GHPQYSSF.js.map → chunk-GJUB3ECP.js.map} +0 -0
  192. /package/dist/{chunk-MTJ3PR4M.js.map → chunk-I7SFRYTX.js.map} +0 -0
  193. /package/dist/{chunk-PX7ODEML.js.map → chunk-J2HIK4GB.js.map} +0 -0
  194. /package/dist/{chunk-RZXS4ADX.js.map → chunk-JSWNBCGS.js.map} +0 -0
  195. /package/dist/{chunk-GXCWKYGU.js.map → chunk-KYKRRF7E.js.map} +0 -0
  196. /package/dist/{chunk-N7TTZIBK.js.map → chunk-MMBQKN4G.js.map} +0 -0
  197. /package/dist/{chunk-JMUAQQJU.js.map → chunk-NKUSUSVI.js.map} +0 -0
  198. /package/dist/{chunk-VRV5UYTN.js.map → chunk-OV57JBMB.js.map} +0 -0
  199. /package/dist/{chunk-EPIOAODF.js.map → chunk-Q36MNOFA.js.map} +0 -0
  200. /package/dist/{chunk-JRBU4UNP.js.map → chunk-QRSWXP4K.js.map} +0 -0
  201. /package/dist/{chunk-IRWHN55G.js.map → chunk-T564HFSH.js.map} +0 -0
  202. /package/dist/{chunk-6CFKWZK3.js.map → chunk-UVNENJ6H.js.map} +0 -0
  203. /package/dist/{chunk-5FCXLQJU.js.map → chunk-UYPWKQKV.js.map} +0 -0
  204. /package/dist/{chunk-BAF33L6C.js.map → chunk-V73GO5AJ.js.map} +0 -0
  205. /package/dist/{chunk-XL7R3XN5.js.map → chunk-VZ6VYRQB.js.map} +0 -0
@@ -41,12 +41,11 @@ var init_config = __esm({
41
41
  return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;
42
42
  };
43
43
  AGENT_CONFIG = {
44
- MAX_TURNS: 6,
44
+ MAX_TURNS: 4,
45
45
  /** Default timeout for model calls. Can be overridden via MORPH_WARP_GREP_TIMEOUT env var (in ms) */
46
46
  TIMEOUT_MS: parseEnvTimeout(process.env.MORPH_WARP_GREP_TIMEOUT, 3e4),
47
- MAX_CONTEXT_CHARS: 321600,
47
+ MAX_CONTEXT_CHARS: 54e4,
48
48
  MAX_OUTPUT_LINES: 200,
49
- MAX_LIST_RESULTS: 500,
50
49
  MAX_READ_LINES: 800,
51
50
  MAX_LIST_DEPTH: 3,
52
51
  LIST_TIMEOUT_MS: 2e3
@@ -131,7 +130,7 @@ var init_config = __esm({
131
130
  ".*"
132
131
  ];
133
132
  DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || "").split(",").map((s) => s.trim()).filter(Boolean).concat(BUILTIN_EXCLUDES);
134
- DEFAULT_MODEL = "morph-warp-grep-v2.1";
133
+ DEFAULT_MODEL = "morph-warp-grep-v2";
135
134
  }
136
135
  });
137
136
 
@@ -204,19 +203,19 @@ var init_ripgrep = __esm({
204
203
 
205
204
  // tools/warp_grep/utils/paths.ts
206
205
  function resolveUnderRepo(repoRoot, targetPath) {
207
- const absRoot = import_path4.default.resolve(repoRoot);
208
- const resolved = import_path4.default.resolve(absRoot, targetPath);
206
+ const absRoot = import_path3.default.resolve(repoRoot);
207
+ const resolved = import_path3.default.resolve(absRoot, targetPath);
209
208
  ensureWithinRepo(absRoot, resolved);
210
209
  return resolved;
211
210
  }
212
211
  function ensureWithinRepo(repoRoot, absTarget) {
213
- const rel = import_path4.default.relative(import_path4.default.resolve(repoRoot), import_path4.default.resolve(absTarget));
214
- if (rel.startsWith("..") || import_path4.default.isAbsolute(rel)) {
212
+ const rel = import_path3.default.relative(import_path3.default.resolve(repoRoot), import_path3.default.resolve(absTarget));
213
+ if (rel.startsWith("..") || import_path3.default.isAbsolute(rel)) {
215
214
  throw new Error(`Path outside repository root: ${absTarget}`);
216
215
  }
217
216
  }
218
217
  function toRepoRelative(repoRoot, absPath) {
219
- return import_path4.default.relative(import_path4.default.resolve(repoRoot), import_path4.default.resolve(absPath));
218
+ return import_path3.default.relative(import_path3.default.resolve(repoRoot), import_path3.default.resolve(absPath));
220
219
  }
221
220
  function isSymlink(p) {
222
221
  try {
@@ -227,7 +226,7 @@ function isSymlink(p) {
227
226
  }
228
227
  }
229
228
  function fixPathRepetition(fullPath) {
230
- const segments = fullPath.split(import_path4.default.sep).filter(Boolean);
229
+ const segments = fullPath.split(import_path3.default.sep).filter(Boolean);
231
230
  if (segments.length < 2) return null;
232
231
  for (let len = Math.floor(segments.length / 2); len >= 1; len--) {
233
232
  for (let i = 0; i <= segments.length - 2 * len; i++) {
@@ -235,7 +234,7 @@ function fixPathRepetition(fullPath) {
235
234
  const second = segments.slice(i + len, i + 2 * len);
236
235
  if (first.every((seg, idx) => seg === second[idx])) {
237
236
  const fixed = [...segments.slice(0, i), ...segments.slice(i + len)];
238
- return import_path4.default.sep + fixed.join(import_path4.default.sep);
237
+ return import_path3.default.sep + fixed.join(import_path3.default.sep);
239
238
  }
240
239
  }
241
240
  }
@@ -259,12 +258,12 @@ function isTextualFile(filePath, maxBytes = 2e6) {
259
258
  return false;
260
259
  }
261
260
  }
262
- var import_fs, import_path4;
261
+ var import_fs, import_path3;
263
262
  var init_paths = __esm({
264
263
  "tools/warp_grep/utils/paths.ts"() {
265
264
  "use strict";
266
265
  import_fs = __toESM(require("fs"), 1);
267
- import_path4 = __toESM(require("path"), 1);
266
+ import_path3 = __toESM(require("path"), 1);
268
267
  }
269
268
  });
270
269
 
@@ -295,12 +294,12 @@ function shouldSkip2(name, allowNames) {
295
294
  }
296
295
  return false;
297
296
  }
298
- var import_promises2, import_path5, SKIP_NAMES2, SKIP_EXTENSIONS2, LocalRipgrepProvider;
297
+ var import_promises2, import_path4, SKIP_NAMES2, SKIP_EXTENSIONS2, LocalRipgrepProvider;
299
298
  var init_local = __esm({
300
299
  "tools/warp_grep/providers/local.ts"() {
301
300
  "use strict";
302
301
  import_promises2 = __toESM(require("fs/promises"), 1);
303
- import_path5 = __toESM(require("path"), 1);
302
+ import_path4 = __toESM(require("path"), 1);
304
303
  init_ripgrep();
305
304
  init_paths();
306
305
  init_files();
@@ -402,7 +401,7 @@ var init_local = __esm({
402
401
  }
403
402
  const stat = await import_promises2.default.stat(abs).catch(() => null);
404
403
  if (!stat) return { lines: [] };
405
- const targetArg = abs === import_path5.default.resolve(this.repoRoot) ? "." : toRepoRelative(this.repoRoot, abs);
404
+ const targetArg = abs === import_path4.default.resolve(this.repoRoot) ? "." : toRepoRelative(this.repoRoot, abs);
406
405
  const contextLines = params.context_lines !== void 0 ? String(params.context_lines) : "1";
407
406
  const args = [
408
407
  "--no-config",
@@ -557,7 +556,7 @@ Details: ${res.stderr}` : ""}`
557
556
  if (timedOut || results.length >= maxResults) break;
558
557
  if (shouldSkip2(entry.name, allowNames)) continue;
559
558
  if (regex && !regex.test(entry.name)) continue;
560
- const full = import_path5.default.join(dir, entry.name);
559
+ const full = import_path4.default.join(dir, entry.name);
561
560
  const isDir = entry.isDirectory();
562
561
  results.push({
563
562
  name: entry.name,
@@ -573,46 +572,6 @@ Details: ${res.stderr}` : ""}`
573
572
  await walk(abs, 0);
574
573
  return results;
575
574
  }
576
- async glob(params) {
577
- let abs;
578
- try {
579
- abs = params.path ? resolveUnderRepo(this.repoRoot, params.path) : this.repoRoot;
580
- } catch (err) {
581
- return { files: [], searchDir: this.repoRoot, totalFound: 0, error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}` };
582
- }
583
- const stat = await import_promises2.default.stat(abs).catch(() => null);
584
- if (!stat || !stat.isDirectory()) {
585
- return { files: [], searchDir: abs, totalFound: 0, error: `[PATH ERROR] Directory not found: ${params.path || "."}` };
586
- }
587
- const targetArg = abs === import_path5.default.resolve(this.repoRoot) ? "." : toRepoRelative(this.repoRoot, abs);
588
- const args = [
589
- "--no-config",
590
- "--files",
591
- "--color=never",
592
- "-g",
593
- params.pattern,
594
- ...this.excludes.filter((e) => !this.allowNames?.has(e)).flatMap((e) => ["-g", `!${e}`]),
595
- targetArg || "."
596
- ];
597
- const res = await runRipgrep(args, { cwd: this.repoRoot });
598
- if (res.exitCode === -1) {
599
- return { files: [], searchDir: abs, totalFound: 0, error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required for glob search.` };
600
- }
601
- if (res.exitCode !== 0 && res.exitCode !== 1) {
602
- return { files: [], searchDir: abs, totalFound: 0, error: `[GLOB ERROR] glob failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ""}` };
603
- }
604
- const absRoot = import_path5.default.resolve(this.repoRoot);
605
- const relFiles = (res.stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
606
- const absFiles = relFiles.map((f) => import_path5.default.resolve(absRoot, f));
607
- const withMtime = [];
608
- for (const f of absFiles) {
609
- const s = await import_promises2.default.stat(f).catch(() => null);
610
- withMtime.push({ file: f, mtime: s?.mtimeMs ?? 0 });
611
- }
612
- withMtime.sort((a, b) => b.mtime - a.mtime);
613
- const totalFound = withMtime.length;
614
- return { files: withMtime.slice(0, 100).map((f) => f.file), searchDir: abs, totalFound };
615
- }
616
575
  };
617
576
  }
618
577
  });
@@ -630,58 +589,131 @@ var import_zod = require("zod");
630
589
  init_config();
631
590
 
632
591
  // tools/warp_grep/agent/parser.ts
633
- function parseReadLines(linesStr) {
634
- const ranges = [];
635
- for (const rangeStr of linesStr.split(",")) {
636
- const trimmed = rangeStr.trim();
637
- if (!trimmed) continue;
638
- const parts = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
639
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
640
- ranges.push([parts[0], parts[1]]);
641
- } else if (Number.isFinite(parts[0])) {
642
- ranges.push([parts[0], parts[0]]);
643
- }
644
- }
645
- if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };
646
- if (ranges.length > 1) return { lines: ranges };
647
- return {};
592
+ var VALID_COMMANDS = ["list_directory", "ripgrep", "read", "finish"];
593
+ function isValidCommand(name) {
594
+ return VALID_COMMANDS.includes(name);
648
595
  }
649
- function parseFinishFiles(filesStr) {
650
- const files = [];
651
- for (const line of filesStr.trim().split(/\s+/)) {
652
- const trimmed = line.trim();
653
- if (!trimmed) continue;
654
- const colonIdx = trimmed.indexOf(":");
655
- if (colonIdx === -1) {
656
- files.push({ path: trimmed, lines: "*" });
657
- continue;
658
- }
659
- const filePath = trimmed.slice(0, colonIdx);
660
- const rangesPart = trimmed.slice(colonIdx + 1);
661
- if (!rangesPart.trim() || rangesPart.trim() === "*") {
662
- files.push({ path: filePath, lines: "*" });
663
- continue;
596
+ function parseQwen3ToolCalls(text) {
597
+ const tools = [];
598
+ const toolCallRegex = /<tool_call>\s*<function=([a-z_][a-z0-9_]*)>([\s\S]*?)<\/function>\s*<\/tool_call>/gi;
599
+ let match;
600
+ while ((match = toolCallRegex.exec(text)) !== null) {
601
+ const funcName = match[1].toLowerCase();
602
+ const body = match[2];
603
+ if (!isValidCommand(funcName)) continue;
604
+ const params = {};
605
+ const paramRegex = /<parameter=([a-z_][a-z0-9_]*)>([\s\S]*?)<\/parameter>/gi;
606
+ let paramMatch;
607
+ while ((paramMatch = paramRegex.exec(body)) !== null) {
608
+ params[paramMatch[1].toLowerCase()] = paramMatch[2].trim();
664
609
  }
665
- const ranges = [];
666
- for (const rangeStr of rangesPart.split(",")) {
667
- const rt = rangeStr.trim();
668
- if (!rt) continue;
669
- const parts = rt.split("-").map((v) => parseInt(v.trim(), 10));
670
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
671
- ranges.push([parts[0], parts[1]]);
672
- } else if (Number.isFinite(parts[0])) {
673
- ranges.push([parts[0], parts[0]]);
610
+ if (funcName === "ripgrep") {
611
+ const pattern = params.pattern;
612
+ if (!pattern) continue;
613
+ const args = {
614
+ pattern,
615
+ path: params.path || ".",
616
+ ...params.glob && { glob: params.glob },
617
+ ...params.context_lines && { context_lines: parseInt(params.context_lines, 10) },
618
+ ...params.case_sensitive && { case_sensitive: params.case_sensitive === "true" }
619
+ };
620
+ tools.push({ name: "grep", arguments: args });
621
+ } else if (funcName === "list_directory") {
622
+ const command = params.command;
623
+ const directPath = params.path;
624
+ let dirPath = directPath || ".";
625
+ if (!directPath && command) {
626
+ const tokens = command.trim().split(/\s+/);
627
+ const pathTokens = tokens.slice(1).filter((t) => !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("\\("));
628
+ if (pathTokens.length > 0) {
629
+ dirPath = pathTokens[0];
630
+ }
631
+ }
632
+ tools.push({ name: "list_directory", arguments: { path: dirPath, pattern: params.pattern || null } });
633
+ } else if (funcName === "read") {
634
+ const filePath = params.path;
635
+ if (!filePath) continue;
636
+ const args = { path: filePath };
637
+ const linesStr = params.lines;
638
+ if (linesStr) {
639
+ const ranges = [];
640
+ for (const rangeStr of linesStr.split(",")) {
641
+ const trimmed = rangeStr.trim();
642
+ if (!trimmed) continue;
643
+ const [s, e] = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
644
+ if (Number.isFinite(s) && Number.isFinite(e)) {
645
+ ranges.push([s, e]);
646
+ } else if (Number.isFinite(s)) {
647
+ ranges.push([s, s]);
648
+ }
649
+ }
650
+ if (ranges.length === 1) {
651
+ args.start = ranges[0][0];
652
+ args.end = ranges[0][1];
653
+ } else if (ranges.length > 1) {
654
+ args.lines = ranges;
655
+ }
656
+ }
657
+ tools.push({ name: "read", arguments: args });
658
+ } else if (funcName === "finish") {
659
+ if (params.result && !params.files) {
660
+ tools.push({ name: "finish", arguments: { files: [], textResult: params.result } });
661
+ continue;
662
+ }
663
+ const filesStr = params.files;
664
+ if (!filesStr) {
665
+ tools.push({ name: "finish", arguments: { files: [], textResult: "No relevant code found." } });
666
+ continue;
667
+ }
668
+ const files = [];
669
+ for (const line of filesStr.split("\n")) {
670
+ const trimmed = line.trim();
671
+ if (!trimmed) continue;
672
+ const colonIdx = trimmed.indexOf(":");
673
+ if (colonIdx === -1) {
674
+ files.push({ path: trimmed, lines: "*" });
675
+ } else {
676
+ const filePath = trimmed.slice(0, colonIdx);
677
+ const rangesPart = trimmed.slice(colonIdx + 1);
678
+ const ranges = [];
679
+ for (const rangeStr of rangesPart.split(",")) {
680
+ const rt = rangeStr.trim();
681
+ if (!rt || rt === "*") {
682
+ files.push({ path: filePath, lines: "*" });
683
+ break;
684
+ }
685
+ const [s, e] = rt.split("-").map((v) => parseInt(v.trim(), 10));
686
+ if (Number.isFinite(s) && Number.isFinite(e)) {
687
+ ranges.push([s, e]);
688
+ } else if (Number.isFinite(s)) {
689
+ ranges.push([s, s]);
690
+ }
691
+ }
692
+ if (ranges.length > 0) {
693
+ files.push({ path: filePath, lines: ranges });
694
+ } else if (!files.some((f) => f.path === filePath)) {
695
+ files.push({ path: filePath, lines: "*" });
696
+ }
697
+ }
698
+ }
699
+ if (files.length > 0) {
700
+ tools.push({ name: "finish", arguments: { files } });
701
+ } else {
702
+ tools.push({ name: "finish", arguments: { files: [], textResult: filesStr } });
674
703
  }
675
704
  }
676
- files.push({ path: filePath, lines: ranges.length > 0 ? ranges : "*" });
677
705
  }
678
- return files;
679
- }
680
- function extractPathFromCommand(command) {
681
- const tokens = command.trim().split(/\s+/);
682
- const pathTokens = tokens.slice(1).filter((t) => !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("\\("));
683
- return pathTokens[0] || ".";
706
+ return tools;
684
707
  }
708
+ var LLMResponseParser = class {
709
+ parse(text) {
710
+ if (typeof text !== "string") {
711
+ throw new TypeError("Command text must be a string.");
712
+ }
713
+ const withoutThink = text.replace(/<think>[\s\S]*?<\/think>/gi, "");
714
+ return parseQwen3ToolCalls(withoutThink);
715
+ }
716
+ };
685
717
 
686
718
  // tools/warp_grep/agent/tools/grep.ts
687
719
  async function toolGrep(provider, args) {
@@ -732,42 +764,29 @@ async function toolRead(provider, args) {
732
764
 
733
765
  // tools/warp_grep/agent/tools/list_directory.ts
734
766
  init_config();
735
- var import_path = __toESM(require("path"), 1);
736
- async function toolListDirectory(provider, args, repoRoot) {
737
- const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;
738
- const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
739
- const entries = await provider.listDirectory({
740
- path: args.path,
741
- pattern: args.pattern ?? null,
742
- maxResults,
743
- maxDepth
744
- });
745
- if (!entries.length) return "empty";
746
- if (repoRoot) {
747
- const absRoot = import_path.default.resolve(repoRoot);
748
- const lines = entries.map((e) => import_path.default.join(absRoot, e.path));
749
- return lines.join("\n");
750
- }
751
- return entries.map((e) => e.path).join("\n");
752
- }
753
-
754
- // tools/warp_grep/agent/tools/glob.ts
755
- async function toolGlob(provider, args) {
756
- const res = await provider.glob(args);
757
- if (res.error) {
758
- return res.error;
759
- }
760
- if (!res.files.length) {
761
- return "no matches";
762
- }
763
- const header = `Found ${res.totalFound} file(s) matching "${args.pattern}" within ${res.searchDir}, sorted by modification time (newest first):`;
764
- const body = res.files.join("\n");
765
- const truncated = res.totalFound > res.files.length ? `
766
- [${res.totalFound - res.files.length} files truncated]` : "";
767
- return `${header}
768
- ---
769
- ${body}
770
- ---${truncated}`;
767
+ async function toolListDirectory(provider, args) {
768
+ const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
769
+ const initialDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
770
+ async function getListRecursive(currentDepth) {
771
+ const entries = await provider.listDirectory({
772
+ path: args.path,
773
+ pattern: args.pattern ?? null,
774
+ maxResults,
775
+ maxDepth: currentDepth
776
+ });
777
+ if (entries.length >= maxResults && currentDepth > 0) {
778
+ return getListRecursive(currentDepth - 1);
779
+ }
780
+ return { entries };
781
+ }
782
+ const { entries: list } = await getListRecursive(initialDepth);
783
+ if (!list.length) return "empty";
784
+ const tree = list.map((e) => {
785
+ const indent = " ".repeat(e.depth);
786
+ const name = e.type === "dir" ? `${e.name}/` : e.name;
787
+ return `${indent}${name}`;
788
+ }).join("\n");
789
+ return tree;
771
790
  }
772
791
 
773
792
  // tools/warp_grep/agent/tools/finish.ts
@@ -828,21 +847,32 @@ function mergeRanges(ranges) {
828
847
  return merged;
829
848
  }
830
849
 
831
- // tools/warp_grep/agent/helpers.ts
832
- var import_path2 = __toESM(require("path"), 1);
833
- init_config();
834
- var TRUNCATED_MARKER = "[truncated for context limit]";
835
- function getMessageSize(m) {
836
- if (m.role === "tool") return m.content.length;
837
- if (m.role === "assistant") {
838
- let size = typeof m.content === "string" ? m.content.length : 0;
839
- if (m.tool_calls) {
840
- size += m.tool_calls.reduce((s, tc) => s + tc.function.name.length + tc.function.arguments.length, 0);
850
+ // tools/warp_grep/agent/formatter.ts
851
+ var ToolOutputFormatter = class {
852
+ format(toolName, _args, output, options = {}) {
853
+ const name = (toolName ?? "").trim();
854
+ if (!name) {
855
+ return "";
856
+ }
857
+ const payload = output?.toString?.()?.trim?.() ?? "";
858
+ const isError = Boolean(options.isError);
859
+ if (!payload && !isError) {
860
+ return "";
841
861
  }
842
- return size;
862
+ return `<tool_response>
863
+ ${payload}
864
+ </tool_response>`;
843
865
  }
844
- return m.content.length;
866
+ };
867
+ var sharedFormatter = new ToolOutputFormatter();
868
+ function formatAgentToolOutput(toolName, args, output, options = {}) {
869
+ return sharedFormatter.format(toolName, args, output, options);
845
870
  }
871
+
872
+ // tools/warp_grep/agent/helpers.ts
873
+ var import_path = __toESM(require("path"), 1);
874
+ init_config();
875
+ var TRUNCATED_MARKER = "[truncated for context limit]";
846
876
  function formatTurnMessage(turnsUsed, maxTurns) {
847
877
  const turnsRemaining = maxTurns - turnsUsed;
848
878
  if (turnsRemaining === 1) {
@@ -853,7 +883,7 @@ You have used ${turnsUsed} turns, you only have 1 turn remaining. You have run o
853
883
  You have used ${turnsUsed} turn${turnsUsed === 1 ? "" : "s"} and have ${turnsRemaining} remaining`;
854
884
  }
855
885
  function calculateContextBudget(messages) {
856
- const totalChars = messages.reduce((sum, m) => sum + getMessageSize(m), 0);
886
+ const totalChars = messages.reduce((sum, m) => sum + m.content.length, 0);
857
887
  const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;
858
888
  const percent = Math.round(totalChars / maxChars * 100);
859
889
  const usedK = Math.round(totalChars / 1e3);
@@ -862,21 +892,24 @@ function calculateContextBudget(messages) {
862
892
  }
863
893
  async function buildInitialState(repoRoot, searchTerm, provider, options) {
864
894
  const budget = calculateContextBudget([]);
865
- const turnTag = `You have used 0 turns and have ${AGENT_CONFIG.MAX_TURNS} remaining`;
895
+ const turnTag = `Turn 0/${AGENT_CONFIG.MAX_TURNS}`;
866
896
  const treeDepth = options?.search_type === "node_modules" ? 1 : 2;
867
- const absRoot = import_path2.default.resolve(repoRoot);
868
897
  try {
869
898
  const entries = await provider.listDirectory({
870
899
  path: ".",
871
900
  maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,
872
901
  maxDepth: treeDepth
873
902
  });
874
- const lines = [absRoot];
875
- for (const e of entries) {
876
- lines.push(import_path2.default.join(absRoot, e.path));
877
- }
903
+ const treeLines = entries.map((e) => {
904
+ const indent = " ".repeat(e.depth);
905
+ const name = e.type === "dir" ? `${e.name}/` : e.name;
906
+ return `${indent}${name}`;
907
+ });
908
+ const repoName = import_path.default.basename(repoRoot);
909
+ const treeOutput = treeLines.length > 0 ? `${repoName}/
910
+ ${treeLines.join("\n")}` : `${repoName}/`;
878
911
  return `<repo_structure>
879
- ${lines.join("\n")}
912
+ ${treeOutput}
880
913
  </repo_structure>
881
914
 
882
915
  <search_string>
@@ -885,8 +918,9 @@ ${searchTerm}
885
918
  ${budget}
886
919
  ${turnTag}`;
887
920
  } catch {
921
+ const repoName = import_path.default.basename(repoRoot);
888
922
  return `<repo_structure>
889
- ${absRoot}
923
+ ${repoName}/
890
924
  </repo_structure>
891
925
 
892
926
  <search_string>
@@ -897,32 +931,26 @@ ${turnTag}`;
897
931
  }
898
932
  }
899
933
  function enforceContextLimit(messages, maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS) {
900
- const getTotalChars = () => messages.reduce((sum, m) => sum + getMessageSize(m), 0);
934
+ const getTotalChars = () => messages.reduce((sum, m) => sum + m.content.length, 0);
901
935
  if (getTotalChars() <= maxChars) {
902
936
  return messages;
903
937
  }
904
- const truncatableIndices = [];
938
+ const userIndices = [];
905
939
  let firstUserSkipped = false;
906
940
  for (let i = 0; i < messages.length; i++) {
907
- const m = messages[i];
908
- if (m.role === "tool") {
909
- truncatableIndices.push(i);
910
- } else if (m.role === "user") {
941
+ if (messages[i].role === "user") {
911
942
  if (!firstUserSkipped) {
912
943
  firstUserSkipped = true;
913
944
  continue;
914
945
  }
915
- truncatableIndices.push(i);
946
+ userIndices.push(i);
916
947
  }
917
948
  }
918
- for (const idx of truncatableIndices) {
949
+ for (const idx of userIndices) {
919
950
  if (getTotalChars() <= maxChars) {
920
951
  break;
921
952
  }
922
- const m = messages[idx];
923
- if (m.role === "tool" && m.content !== TRUNCATED_MARKER) {
924
- messages[idx] = { role: "tool", tool_call_id: m.tool_call_id, content: TRUNCATED_MARKER };
925
- } else if (m.role === "user" && m.content !== TRUNCATED_MARKER) {
953
+ if (messages[idx].content !== TRUNCATED_MARKER) {
926
954
  messages[idx] = { role: "user", content: TRUNCATED_MARKER };
927
955
  }
928
956
  }
@@ -935,7 +963,7 @@ var import_openai = __toESM(require("openai"), 1);
935
963
  // package.json
936
964
  var package_default = {
937
965
  name: "@morphllm/morphsdk",
938
- version: "0.2.145",
966
+ version: "0.2.146",
939
967
  description: "TypeScript SDK and CLI for Morph Fast Apply integration",
940
968
  type: "module",
941
969
  main: "./dist/index.cjs",
@@ -1174,115 +1202,9 @@ var package_default = {
1174
1202
  var SDK_VERSION = package_default.version;
1175
1203
 
1176
1204
  // tools/warp_grep/agent/runner.ts
1177
- var import_path3 = __toESM(require("path"), 1);
1205
+ var import_path2 = __toESM(require("path"), 1);
1206
+ var parser = new LLMResponseParser();
1178
1207
  var DEFAULT_API_URL = "https://api.morphllm.com";
1179
- var TOOL_SPECS = [
1180
- {
1181
- type: "function",
1182
- function: {
1183
- name: "list_directory",
1184
- description: "Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.",
1185
- parameters: {
1186
- type: "object",
1187
- properties: {
1188
- command: {
1189
- type: "string",
1190
- description: "Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */)."
1191
- }
1192
- },
1193
- required: ["command"]
1194
- }
1195
- }
1196
- },
1197
- {
1198
- type: "function",
1199
- function: {
1200
- name: "grep_search",
1201
- description: "Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.",
1202
- parameters: {
1203
- type: "object",
1204
- properties: {
1205
- pattern: {
1206
- type: "string",
1207
- description: "Regex pattern to search for in file contents (e.g. 'class\\s+\\w+Error', 'import|require|from', 'def (get|set|update)_user')."
1208
- },
1209
- path: {
1210
- type: "string",
1211
- description: "File or directory to search in. Defaults to current working directory."
1212
- },
1213
- glob: {
1214
- type: "string",
1215
- description: "Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*')."
1216
- },
1217
- limit: {
1218
- type: "integer",
1219
- description: "Limit output to first N matching lines. Shows all matches if not specified."
1220
- }
1221
- },
1222
- required: ["pattern"]
1223
- }
1224
- }
1225
- },
1226
- {
1227
- type: "function",
1228
- function: {
1229
- name: "glob",
1230
- description: "Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.",
1231
- parameters: {
1232
- type: "object",
1233
- properties: {
1234
- pattern: {
1235
- type: "string",
1236
- description: "Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py')."
1237
- },
1238
- path: {
1239
- type: "string",
1240
- description: "Directory to search in. Defaults to repository root."
1241
- }
1242
- },
1243
- required: ["pattern"]
1244
- }
1245
- }
1246
- },
1247
- {
1248
- type: "function",
1249
- function: {
1250
- name: "read",
1251
- description: "Read entire files or specific line ranges using absolute paths.",
1252
- parameters: {
1253
- type: "object",
1254
- properties: {
1255
- path: {
1256
- type: "string",
1257
- description: "File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path)."
1258
- },
1259
- lines: {
1260
- type: "string",
1261
- description: "Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file."
1262
- }
1263
- },
1264
- required: ["path"]
1265
- }
1266
- }
1267
- },
1268
- {
1269
- type: "function",
1270
- function: {
1271
- name: "finish",
1272
- description: "Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.",
1273
- parameters: {
1274
- type: "object",
1275
- properties: {
1276
- files: {
1277
- type: "string",
1278
- 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."
1279
- }
1280
- },
1281
- required: ["files"]
1282
- }
1283
- }
1284
- }
1285
- ];
1286
1208
  async function callModel(messages, model, options = {}) {
1287
1209
  const baseUrl = options.morphApiUrl || DEFAULT_API_URL;
1288
1210
  const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
@@ -1303,9 +1225,8 @@ async function callModel(messages, model, options = {}) {
1303
1225
  data = await client.chat.completions.create({
1304
1226
  model,
1305
1227
  temperature: 0,
1306
- max_tokens: 2048,
1228
+ max_tokens: 1024,
1307
1229
  messages,
1308
- tools: TOOL_SPECS,
1309
1230
  ...options.search_type ? { search_type: options.search_type } : {}
1310
1231
  });
1311
1232
  } catch (error) {
@@ -1317,87 +1238,187 @@ async function callModel(messages, model, options = {}) {
1317
1238
  throw error;
1318
1239
  }
1319
1240
  const choice = data?.choices?.[0];
1320
- const message = choice?.message;
1321
- if (!message) {
1322
- if (attempt === MAX_EMPTY_RETRIES) {
1323
- throw new Error("Invalid response from model: no message in response");
1324
- }
1325
- await new Promise((resolve) => setTimeout(resolve, 200));
1326
- continue;
1327
- }
1328
- const toolCalls = (message.tool_calls || []).map((tc) => ({
1329
- id: tc.id,
1330
- type: "function",
1331
- function: { name: tc.function.name, arguments: tc.function.arguments }
1332
- }));
1333
- if (message.content || toolCalls.length > 0) {
1334
- return { content: message.content ?? null, tool_calls: toolCalls };
1241
+ const content = choice?.message?.content;
1242
+ if (content && typeof content === "string") {
1243
+ return content;
1335
1244
  }
1336
1245
  if (attempt === MAX_EMPTY_RETRIES) {
1337
1246
  const finishReason = choice?.finish_reason ?? "unknown";
1247
+ const hasToolCalls = Array.isArray(choice?.message?.tool_calls) && choice.message.tool_calls.length > 0;
1248
+ const choicesLen = data?.choices?.length ?? 0;
1249
+ const contentType = content === null ? "null" : content === void 0 ? "undefined" : typeof content;
1338
1250
  throw new Error(
1339
- `Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`
1251
+ `Invalid response from model: content=${contentType}, finish_reason=${finishReason}, has_tool_calls=${hasToolCalls}, choices_length=${choicesLen}`
1340
1252
  );
1341
1253
  }
1342
1254
  await new Promise((resolve) => setTimeout(resolve, 200));
1343
1255
  }
1344
1256
  throw new Error("Invalid response from model");
1345
1257
  }
1346
- function safeParseJSON(s) {
1347
- try {
1348
- return JSON.parse(s);
1349
- } catch {
1350
- return {};
1351
- }
1352
- }
1353
- async function executeTool(provider, name, args, repoRoot) {
1354
- switch (name) {
1355
- case "grep_search": {
1356
- const grepArgs = {
1357
- pattern: args.pattern,
1358
- path: args.path || "."
1359
- };
1360
- if (args.glob) grepArgs.glob = args.glob;
1361
- if (args.case_sensitive !== void 0) grepArgs.case_sensitive = args.case_sensitive;
1362
- const result = await toolGrep(provider, grepArgs);
1363
- let output = result.output;
1364
- if (args.limit && typeof args.limit === "number") {
1365
- const lines = output.split("\n");
1366
- if (lines.length > args.limit) {
1367
- output = lines.slice(0, args.limit).join("\n") + `
1368
- ... (truncated at ${args.limit} lines)`;
1369
- }
1370
- }
1371
- return output;
1258
+ async function runWarpGrep(config) {
1259
+ const totalStart = Date.now();
1260
+ const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
1261
+ const timings = { turns: [], timeout_ms: timeoutMs };
1262
+ const repoRoot = import_path2.default.resolve(config.repoRoot || process.cwd());
1263
+ const model = config.model || DEFAULT_MODEL;
1264
+ const messages = [];
1265
+ const maxTurns = AGENT_CONFIG.MAX_TURNS;
1266
+ const initialStateStart = Date.now();
1267
+ const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });
1268
+ timings.initial_state_ms = Date.now() - initialStateStart;
1269
+ messages.push({ role: "user", content: initialState });
1270
+ const provider = config.provider;
1271
+ const errors = [];
1272
+ let finishMeta;
1273
+ let terminationReason = "terminated";
1274
+ for (let turn = 1; turn <= maxTurns; turn += 1) {
1275
+ const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
1276
+ enforceContextLimit(messages);
1277
+ const modelCallStart = Date.now();
1278
+ const assistantContent = await callModel(messages, model, {
1279
+ morphApiKey: config.morphApiKey,
1280
+ morphApiUrl: config.morphApiUrl,
1281
+ retryConfig: config.retryConfig,
1282
+ timeout: timeoutMs,
1283
+ search_type: config.search_type
1284
+ }).catch((e) => {
1285
+ const errMsg = e instanceof Error ? e.message : String(e);
1286
+ console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
1287
+ errors.push({ message: errMsg });
1288
+ return "";
1289
+ });
1290
+ turnMetrics.morph_api_ms = Date.now() - modelCallStart;
1291
+ if (!assistantContent) {
1292
+ console.error(`[warp_grep] Empty response from Morph API on turn ${turn}. Errors so far:`, errors);
1293
+ timings.turns.push(turnMetrics);
1294
+ break;
1372
1295
  }
1373
- case "glob": {
1374
- return toolGlob(provider, {
1375
- pattern: args.pattern,
1376
- path: args.path
1377
- });
1296
+ messages.push({ role: "assistant", content: assistantContent });
1297
+ const toolCalls = parser.parse(assistantContent);
1298
+ if (toolCalls.length === 0) {
1299
+ console.error(`[warp_grep] No tool calls parsed on turn ${turn}. Assistant content (first 500 chars):`, assistantContent.slice(0, 500));
1300
+ errors.push({ message: "No tool calls produced by the model. Your MCP is likely out of date! Update it by running: rm -rf ~/.npm/_npx && npm cache clean --force && npx -y @morphllm/morphmcp@latest" });
1301
+ terminationReason = "terminated";
1302
+ timings.turns.push(turnMetrics);
1303
+ break;
1378
1304
  }
1379
- case "list_directory": {
1380
- const dirPath = extractPathFromCommand(args.command || ".");
1381
- return toolListDirectory(provider, { path: dirPath }, repoRoot);
1305
+ const finishCalls = toolCalls.filter((c) => c.name === "finish");
1306
+ const grepCalls = toolCalls.filter((c) => c.name === "grep");
1307
+ const listDirCalls = toolCalls.filter((c) => c.name === "list_directory");
1308
+ const readCalls = toolCalls.filter((c) => c.name === "read");
1309
+ const skipCalls = toolCalls.filter((c) => c.name === "_skip");
1310
+ const formatted = [];
1311
+ for (const c of skipCalls) {
1312
+ const msg = c.arguments?.message || "Command skipped due to parsing error";
1313
+ formatted.push(msg);
1382
1314
  }
1383
- case "read": {
1384
- const readArgs = {
1385
- path: args.path
1386
- };
1387
- if (args.lines && typeof args.lines === "string") {
1388
- Object.assign(readArgs, parseReadLines(args.lines));
1315
+ const allPromises = [];
1316
+ for (const c of grepCalls) {
1317
+ const args = c.arguments ?? {};
1318
+ allPromises.push(
1319
+ toolGrep(provider, args).then(
1320
+ ({ output }) => formatAgentToolOutput("grep", args, output),
1321
+ (err) => formatAgentToolOutput("grep", args, String(err), { isError: true })
1322
+ )
1323
+ );
1324
+ }
1325
+ for (const c of listDirCalls) {
1326
+ const args = c.arguments ?? {};
1327
+ allPromises.push(
1328
+ toolListDirectory(provider, args).then(
1329
+ (p) => formatAgentToolOutput("list_directory", args, p),
1330
+ (err) => formatAgentToolOutput("list_directory", args, String(err), { isError: true })
1331
+ )
1332
+ );
1333
+ }
1334
+ for (const c of readCalls) {
1335
+ const args = c.arguments ?? {};
1336
+ allPromises.push(
1337
+ toolRead(provider, args).then(
1338
+ (p) => formatAgentToolOutput("read", args, p),
1339
+ (err) => formatAgentToolOutput("read", args, String(err), { isError: true })
1340
+ )
1341
+ );
1342
+ }
1343
+ const toolExecStart = Date.now();
1344
+ const allResults = await Promise.all(allPromises);
1345
+ turnMetrics.local_tools_ms = Date.now() - toolExecStart;
1346
+ for (const result of allResults) {
1347
+ formatted.push(result);
1348
+ }
1349
+ if (formatted.length > 0) {
1350
+ const turnMessage = formatTurnMessage(turn, maxTurns);
1351
+ const contextBudget = calculateContextBudget(messages);
1352
+ messages.push({ role: "user", content: formatted.join("\n") + turnMessage + "\n" + contextBudget });
1353
+ }
1354
+ timings.turns.push(turnMetrics);
1355
+ if (finishCalls.length) {
1356
+ const fc = finishCalls[0];
1357
+ const files = fc.arguments?.files ?? [];
1358
+ const textResult = fc.arguments?.textResult;
1359
+ finishMeta = { files };
1360
+ terminationReason = "completed";
1361
+ if (files.length === 0) {
1362
+ const payload2 = textResult || "No relevant code found.";
1363
+ timings.turns.push(turnMetrics);
1364
+ timings.total_ms = Date.now() - totalStart;
1365
+ return {
1366
+ terminationReason: "completed",
1367
+ messages,
1368
+ finish: { payload: payload2, metadata: finishMeta },
1369
+ timings
1370
+ };
1371
+ }
1372
+ break;
1373
+ }
1374
+ }
1375
+ if (terminationReason !== "completed" || !finishMeta) {
1376
+ timings.total_ms = Date.now() - totalStart;
1377
+ return { terminationReason, messages, errors, timings };
1378
+ }
1379
+ const parts = ["Relevant context found:"];
1380
+ for (const f of finishMeta.files) {
1381
+ const ranges = f.lines === "*" ? "*" : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(", ") : "*";
1382
+ parts.push(`- ${f.path}: ${ranges}`);
1383
+ }
1384
+ const payload = parts.join("\n");
1385
+ const finishResolutionStart = Date.now();
1386
+ const fileReadErrors = [];
1387
+ const resolved = await readFinishFiles(
1388
+ repoRoot,
1389
+ finishMeta.files,
1390
+ async (p, s, e) => {
1391
+ try {
1392
+ const rr = await provider.read({ path: p, start: s, end: e });
1393
+ return rr.lines.map((l) => {
1394
+ const idx = l.indexOf("|");
1395
+ return idx >= 0 ? l.slice(idx + 1) : l;
1396
+ });
1397
+ } catch (err) {
1398
+ const errorMsg = err instanceof Error ? err.message : String(err);
1399
+ fileReadErrors.push({ path: p, error: errorMsg });
1400
+ console.error(`[warp_grep] Failed to read file: ${p} - ${errorMsg}`);
1401
+ return [`[couldn't find: ${p}]`];
1389
1402
  }
1390
- return toolRead(provider, readArgs);
1391
1403
  }
1392
- default:
1393
- return `Unknown tool: ${name}`;
1404
+ );
1405
+ timings.finish_resolution_ms = Date.now() - finishResolutionStart;
1406
+ if (fileReadErrors.length > 0) {
1407
+ errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
1394
1408
  }
1409
+ timings.total_ms = Date.now() - totalStart;
1410
+ return {
1411
+ terminationReason: "completed",
1412
+ messages,
1413
+ finish: { payload, metadata: finishMeta, resolved },
1414
+ timings
1415
+ };
1395
1416
  }
1396
1417
  async function* runWarpGrepStreaming(config) {
1397
1418
  const totalStart = Date.now();
1398
1419
  const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
1399
1420
  const timings = { turns: [], timeout_ms: timeoutMs };
1400
- const repoRoot = import_path3.default.resolve(config.repoRoot || process.cwd());
1421
+ const repoRoot = import_path2.default.resolve(config.repoRoot || process.cwd());
1401
1422
  const model = config.model || DEFAULT_MODEL;
1402
1423
  const messages = [];
1403
1424
  const maxTurns = AGENT_CONFIG.MAX_TURNS;
@@ -1413,7 +1434,7 @@ async function* runWarpGrepStreaming(config) {
1413
1434
  const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
1414
1435
  enforceContextLimit(messages);
1415
1436
  const modelCallStart = Date.now();
1416
- const response = await callModel(messages, model, {
1437
+ const assistantContent = await callModel(messages, model, {
1417
1438
  morphApiKey: config.morphApiKey,
1418
1439
  morphApiUrl: config.morphApiUrl,
1419
1440
  retryConfig: config.retryConfig,
@@ -1421,45 +1442,90 @@ async function* runWarpGrepStreaming(config) {
1421
1442
  search_type: config.search_type
1422
1443
  }).catch((e) => {
1423
1444
  const errMsg = e instanceof Error ? e.message : String(e);
1424
- console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
1445
+ console.error(`[warp_grep:stream] Morph API call failed on turn ${turn}:`, errMsg);
1425
1446
  errors.push({ message: errMsg });
1426
- return null;
1447
+ return "";
1427
1448
  });
1428
1449
  turnMetrics.morph_api_ms = Date.now() - modelCallStart;
1429
- if (!response) {
1450
+ if (!assistantContent) {
1451
+ console.error(`[warp_grep:stream] Empty response from Morph API on turn ${turn}. Errors so far:`, errors);
1430
1452
  timings.turns.push(turnMetrics);
1431
1453
  break;
1432
1454
  }
1433
- const toolCalls = response.tool_calls;
1434
- messages.push({
1435
- role: "assistant",
1436
- content: response.content,
1437
- ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
1438
- });
1455
+ messages.push({ role: "assistant", content: assistantContent });
1456
+ const toolCalls = parser.parse(assistantContent);
1439
1457
  if (toolCalls.length === 0) {
1440
- console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || "").slice(0, 500)}`);
1441
- errors.push({ message: "No tool calls produced by the model." });
1458
+ console.error(`[warp_grep:stream] No tool calls parsed on turn ${turn}. Assistant content (first 500 chars):`, assistantContent.slice(0, 500));
1459
+ errors.push({ message: "No tool calls produced by the model. Your MCP is likely out of date! Update it by running: rm -rf ~/.npm/_npx && npm cache clean --force && npx -y @morphllm/morphmcp@latest" });
1442
1460
  terminationReason = "terminated";
1443
1461
  timings.turns.push(turnMetrics);
1444
1462
  break;
1445
1463
  }
1446
1464
  yield {
1447
1465
  turn,
1448
- toolCalls: toolCalls.map((tc) => ({
1449
- name: tc.function.name,
1450
- arguments: safeParseJSON(tc.function.arguments)
1466
+ toolCalls: toolCalls.map((c) => ({
1467
+ name: c.name,
1468
+ arguments: c.arguments ?? {}
1451
1469
  }))
1452
1470
  };
1453
- const finishCall = toolCalls.find((tc) => tc.function.name === "finish");
1454
- if (finishCall) {
1455
- const args = safeParseJSON(finishCall.function.arguments);
1456
- const filesStr = args.files || "";
1457
- const files = parseFinishFiles(filesStr);
1471
+ const finishCalls = toolCalls.filter((c) => c.name === "finish");
1472
+ const grepCalls = toolCalls.filter((c) => c.name === "grep");
1473
+ const listDirCalls = toolCalls.filter((c) => c.name === "list_directory");
1474
+ const readCalls = toolCalls.filter((c) => c.name === "read");
1475
+ const skipCalls = toolCalls.filter((c) => c.name === "_skip");
1476
+ const formatted = [];
1477
+ for (const c of skipCalls) {
1478
+ const msg = c.arguments?.message || "Command skipped due to parsing error";
1479
+ formatted.push(msg);
1480
+ }
1481
+ const allPromises = [];
1482
+ for (const c of grepCalls) {
1483
+ const args = c.arguments ?? {};
1484
+ allPromises.push(
1485
+ toolGrep(provider, args).then(
1486
+ ({ output }) => formatAgentToolOutput("grep", args, output),
1487
+ (err) => formatAgentToolOutput("grep", args, String(err), { isError: true })
1488
+ )
1489
+ );
1490
+ }
1491
+ for (const c of listDirCalls) {
1492
+ const args = c.arguments ?? {};
1493
+ allPromises.push(
1494
+ toolListDirectory(provider, args).then(
1495
+ (p) => formatAgentToolOutput("list_directory", args, p),
1496
+ (err) => formatAgentToolOutput("list_directory", args, String(err), { isError: true })
1497
+ )
1498
+ );
1499
+ }
1500
+ for (const c of readCalls) {
1501
+ const args = c.arguments ?? {};
1502
+ allPromises.push(
1503
+ toolRead(provider, args).then(
1504
+ (p) => formatAgentToolOutput("read", args, p),
1505
+ (err) => formatAgentToolOutput("read", args, String(err), { isError: true })
1506
+ )
1507
+ );
1508
+ }
1509
+ const toolExecStart = Date.now();
1510
+ const allResults = await Promise.all(allPromises);
1511
+ turnMetrics.local_tools_ms = Date.now() - toolExecStart;
1512
+ for (const result of allResults) {
1513
+ formatted.push(result);
1514
+ }
1515
+ if (formatted.length > 0) {
1516
+ const turnMessage = formatTurnMessage(turn, maxTurns);
1517
+ const contextBudget = calculateContextBudget(messages);
1518
+ messages.push({ role: "user", content: formatted.join("\n") + turnMessage + "\n" + contextBudget });
1519
+ }
1520
+ timings.turns.push(turnMetrics);
1521
+ if (finishCalls.length) {
1522
+ const fc = finishCalls[0];
1523
+ const files = fc.arguments?.files ?? [];
1524
+ const textResult = fc.arguments?.textResult;
1458
1525
  finishMeta = { files };
1459
1526
  terminationReason = "completed";
1460
1527
  if (files.length === 0) {
1461
- const payload2 = filesStr || "No relevant code found.";
1462
- timings.turns.push(turnMetrics);
1528
+ const payload2 = textResult || "No relevant code found.";
1463
1529
  timings.total_ms = Date.now() - totalStart;
1464
1530
  return {
1465
1531
  terminationReason: "completed",
@@ -1468,25 +1534,8 @@ async function* runWarpGrepStreaming(config) {
1468
1534
  timings
1469
1535
  };
1470
1536
  }
1471
- timings.turns.push(turnMetrics);
1472
1537
  break;
1473
1538
  }
1474
- const toolExecStart = Date.now();
1475
- const results = await Promise.all(
1476
- toolCalls.map(async (tc) => {
1477
- const args = safeParseJSON(tc.function.arguments);
1478
- const output = await executeTool(provider, tc.function.name, args, repoRoot).catch((err) => String(err));
1479
- return { tool_call_id: tc.id, content: output };
1480
- })
1481
- );
1482
- turnMetrics.local_tools_ms = Date.now() - toolExecStart;
1483
- for (const result of results) {
1484
- messages.push({ role: "tool", tool_call_id: result.tool_call_id, content: result.content });
1485
- }
1486
- const turnMsg = formatTurnMessage(turn, maxTurns);
1487
- const budget = calculateContextBudget(messages);
1488
- messages.push({ role: "user", content: turnMsg + "\n" + budget });
1489
- timings.turns.push(turnMetrics);
1490
1539
  }
1491
1540
  if (terminationReason !== "completed" || !finishMeta) {
1492
1541
  timings.total_ms = Date.now() - totalStart;
@@ -1530,14 +1579,6 @@ async function* runWarpGrepStreaming(config) {
1530
1579
  timings
1531
1580
  };
1532
1581
  }
1533
- async function runWarpGrep(config) {
1534
- const gen = runWarpGrepStreaming(config);
1535
- let result = await gen.next();
1536
- while (!result.done) {
1537
- result = await gen.next();
1538
- }
1539
- return result.value;
1540
- }
1541
1582
 
1542
1583
  // tools/warp_grep/providers/remote.ts
1543
1584
  init_config();
@@ -1717,35 +1758,6 @@ var RemoteCommandsProvider = class {
1717
1758
  return [];
1718
1759
  }
1719
1760
  }
1720
- /**
1721
- * Glob search - finds files matching a pattern.
1722
- * Falls back to a grep --files approach via the listDir command.
1723
- */
1724
- async glob(params) {
1725
- const searchPath = params.path || this.repoRoot;
1726
- try {
1727
- const stdout = await this.commands.listDir(searchPath, 10);
1728
- const allPaths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
1729
- const globToRegex = (glob) => {
1730
- const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
1731
- return new RegExp(escaped);
1732
- };
1733
- const regex = globToRegex(params.pattern);
1734
- const matched = allPaths.filter((p) => {
1735
- const name = p.split("/").pop() || "";
1736
- return regex.test(name) && !shouldSkip(name);
1737
- });
1738
- const totalFound = matched.length;
1739
- return { files: matched.slice(0, 100), searchDir: searchPath, totalFound };
1740
- } catch (error) {
1741
- return {
1742
- files: [],
1743
- searchDir: searchPath,
1744
- totalFound: 0,
1745
- error: `[GLOB ERROR] ${error instanceof Error ? error.message : String(error)}`
1746
- };
1747
- }
1748
- }
1749
1761
  };
1750
1762
 
1751
1763
  // tools/warp_grep/providers/code_storage_http.ts
@@ -1772,9 +1784,9 @@ function createCodeStorageHttpCommands(config) {
1772
1784
  const { baseUrl, repoId, branch } = config;
1773
1785
  const encodedRepoId = encodeURIComponent(repoId);
1774
1786
  return {
1775
- grep: (pattern, path6, glob) => post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path: path6, glob, branch }, "grep"),
1776
- read: (path6, start, end) => post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path: path6, start, end, branch }, "read"),
1777
- listDir: (path6, maxDepth) => post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path: path6, maxDepth, branch }, "list")
1787
+ grep: (pattern, path5, glob) => post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path: path5, glob, branch }, "grep"),
1788
+ read: (path5, start, end) => post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path: path5, start, end, branch }, "read"),
1789
+ listDir: (path5, maxDepth) => post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path: path5, maxDepth, branch }, "list")
1778
1790
  };
1779
1791
  }
1780
1792