@morphllm/morphsdk 0.2.143 → 0.2.145

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