@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
  });
@@ -636,58 +595,131 @@ var import_zod = require("zod");
636
595
  init_config();
637
596
 
638
597
  // tools/warp_grep/agent/parser.ts
639
- function parseReadLines(linesStr) {
640
- const ranges = [];
641
- for (const rangeStr of linesStr.split(",")) {
642
- const trimmed = rangeStr.trim();
643
- if (!trimmed) continue;
644
- const parts = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
645
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
646
- ranges.push([parts[0], parts[1]]);
647
- } else if (Number.isFinite(parts[0])) {
648
- ranges.push([parts[0], parts[0]]);
649
- }
650
- }
651
- if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };
652
- if (ranges.length > 1) return { lines: ranges };
653
- return {};
598
+ var VALID_COMMANDS = ["list_directory", "ripgrep", "read", "finish"];
599
+ function isValidCommand(name) {
600
+ return VALID_COMMANDS.includes(name);
654
601
  }
655
- function parseFinishFiles(filesStr) {
656
- const files = [];
657
- for (const line of filesStr.trim().split(/\s+/)) {
658
- const trimmed = line.trim();
659
- if (!trimmed) continue;
660
- const colonIdx = trimmed.indexOf(":");
661
- if (colonIdx === -1) {
662
- files.push({ path: trimmed, lines: "*" });
663
- continue;
602
+ function parseQwen3ToolCalls(text) {
603
+ const tools = [];
604
+ const toolCallRegex = /<tool_call>\s*<function=([a-z_][a-z0-9_]*)>([\s\S]*?)<\/function>\s*<\/tool_call>/gi;
605
+ let match;
606
+ while ((match = toolCallRegex.exec(text)) !== null) {
607
+ const funcName = match[1].toLowerCase();
608
+ const body = match[2];
609
+ if (!isValidCommand(funcName)) continue;
610
+ const params = {};
611
+ const paramRegex = /<parameter=([a-z_][a-z0-9_]*)>([\s\S]*?)<\/parameter>/gi;
612
+ let paramMatch;
613
+ while ((paramMatch = paramRegex.exec(body)) !== null) {
614
+ params[paramMatch[1].toLowerCase()] = paramMatch[2].trim();
664
615
  }
665
- const filePath = trimmed.slice(0, colonIdx);
666
- const rangesPart = trimmed.slice(colonIdx + 1);
667
- if (!rangesPart.trim() || rangesPart.trim() === "*") {
668
- files.push({ path: filePath, lines: "*" });
669
- continue;
670
- }
671
- const ranges = [];
672
- for (const rangeStr of rangesPart.split(",")) {
673
- const rt = rangeStr.trim();
674
- if (!rt) continue;
675
- const parts = rt.split("-").map((v) => parseInt(v.trim(), 10));
676
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
677
- ranges.push([parts[0], parts[1]]);
678
- } else if (Number.isFinite(parts[0])) {
679
- ranges.push([parts[0], parts[0]]);
616
+ if (funcName === "ripgrep") {
617
+ const pattern = params.pattern;
618
+ if (!pattern) continue;
619
+ const args = {
620
+ pattern,
621
+ path: params.path || ".",
622
+ ...params.glob && { glob: params.glob },
623
+ ...params.context_lines && { context_lines: parseInt(params.context_lines, 10) },
624
+ ...params.case_sensitive && { case_sensitive: params.case_sensitive === "true" }
625
+ };
626
+ tools.push({ name: "grep", arguments: args });
627
+ } else if (funcName === "list_directory") {
628
+ const command = params.command;
629
+ const directPath = params.path;
630
+ let dirPath = directPath || ".";
631
+ if (!directPath && command) {
632
+ const tokens = command.trim().split(/\s+/);
633
+ const pathTokens = tokens.slice(1).filter((t) => !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("\\("));
634
+ if (pathTokens.length > 0) {
635
+ dirPath = pathTokens[0];
636
+ }
637
+ }
638
+ tools.push({ name: "list_directory", arguments: { path: dirPath, pattern: params.pattern || null } });
639
+ } else if (funcName === "read") {
640
+ const filePath = params.path;
641
+ if (!filePath) continue;
642
+ const args = { path: filePath };
643
+ const linesStr = params.lines;
644
+ if (linesStr) {
645
+ const ranges = [];
646
+ for (const rangeStr of linesStr.split(",")) {
647
+ const trimmed = rangeStr.trim();
648
+ if (!trimmed) continue;
649
+ const [s, e] = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
650
+ if (Number.isFinite(s) && Number.isFinite(e)) {
651
+ ranges.push([s, e]);
652
+ } else if (Number.isFinite(s)) {
653
+ ranges.push([s, s]);
654
+ }
655
+ }
656
+ if (ranges.length === 1) {
657
+ args.start = ranges[0][0];
658
+ args.end = ranges[0][1];
659
+ } else if (ranges.length > 1) {
660
+ args.lines = ranges;
661
+ }
662
+ }
663
+ tools.push({ name: "read", arguments: args });
664
+ } else if (funcName === "finish") {
665
+ if (params.result && !params.files) {
666
+ tools.push({ name: "finish", arguments: { files: [], textResult: params.result } });
667
+ continue;
668
+ }
669
+ const filesStr = params.files;
670
+ if (!filesStr) {
671
+ tools.push({ name: "finish", arguments: { files: [], textResult: "No relevant code found." } });
672
+ continue;
673
+ }
674
+ const files = [];
675
+ for (const line of filesStr.split("\n")) {
676
+ const trimmed = line.trim();
677
+ if (!trimmed) continue;
678
+ const colonIdx = trimmed.indexOf(":");
679
+ if (colonIdx === -1) {
680
+ files.push({ path: trimmed, lines: "*" });
681
+ } else {
682
+ const filePath = trimmed.slice(0, colonIdx);
683
+ const rangesPart = trimmed.slice(colonIdx + 1);
684
+ const ranges = [];
685
+ for (const rangeStr of rangesPart.split(",")) {
686
+ const rt = rangeStr.trim();
687
+ if (!rt || rt === "*") {
688
+ files.push({ path: filePath, lines: "*" });
689
+ break;
690
+ }
691
+ const [s, e] = rt.split("-").map((v) => parseInt(v.trim(), 10));
692
+ if (Number.isFinite(s) && Number.isFinite(e)) {
693
+ ranges.push([s, e]);
694
+ } else if (Number.isFinite(s)) {
695
+ ranges.push([s, s]);
696
+ }
697
+ }
698
+ if (ranges.length > 0) {
699
+ files.push({ path: filePath, lines: ranges });
700
+ } else if (!files.some((f) => f.path === filePath)) {
701
+ files.push({ path: filePath, lines: "*" });
702
+ }
703
+ }
704
+ }
705
+ if (files.length > 0) {
706
+ tools.push({ name: "finish", arguments: { files } });
707
+ } else {
708
+ tools.push({ name: "finish", arguments: { files: [], textResult: filesStr } });
680
709
  }
681
710
  }
682
- files.push({ path: filePath, lines: ranges.length > 0 ? ranges : "*" });
683
711
  }
684
- return files;
685
- }
686
- function extractPathFromCommand(command) {
687
- const tokens = command.trim().split(/\s+/);
688
- const pathTokens = tokens.slice(1).filter((t) => !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("\\("));
689
- return pathTokens[0] || ".";
712
+ return tools;
690
713
  }
714
+ var LLMResponseParser = class {
715
+ parse(text) {
716
+ if (typeof text !== "string") {
717
+ throw new TypeError("Command text must be a string.");
718
+ }
719
+ const withoutThink = text.replace(/<think>[\s\S]*?<\/think>/gi, "");
720
+ return parseQwen3ToolCalls(withoutThink);
721
+ }
722
+ };
691
723
 
692
724
  // tools/warp_grep/agent/tools/grep.ts
693
725
  async function toolGrep(provider, args) {
@@ -738,42 +770,29 @@ async function toolRead(provider, args) {
738
770
 
739
771
  // tools/warp_grep/agent/tools/list_directory.ts
740
772
  init_config();
741
- var import_path = __toESM(require("path"), 1);
742
- async function toolListDirectory(provider, args, repoRoot) {
743
- const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;
744
- const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
745
- const entries = await provider.listDirectory({
746
- path: args.path,
747
- pattern: args.pattern ?? null,
748
- maxResults,
749
- maxDepth
750
- });
751
- if (!entries.length) return "empty";
752
- if (repoRoot) {
753
- const absRoot = import_path.default.resolve(repoRoot);
754
- const lines = entries.map((e) => import_path.default.join(absRoot, e.path));
755
- return lines.join("\n");
756
- }
757
- return entries.map((e) => e.path).join("\n");
758
- }
759
-
760
- // tools/warp_grep/agent/tools/glob.ts
761
- async function toolGlob(provider, args) {
762
- const res = await provider.glob(args);
763
- if (res.error) {
764
- return res.error;
765
- }
766
- if (!res.files.length) {
767
- return "no matches";
768
- }
769
- const header = `Found ${res.totalFound} file(s) matching "${args.pattern}" within ${res.searchDir}, sorted by modification time (newest first):`;
770
- const body = res.files.join("\n");
771
- const truncated = res.totalFound > res.files.length ? `
772
- [${res.totalFound - res.files.length} files truncated]` : "";
773
- return `${header}
774
- ---
775
- ${body}
776
- ---${truncated}`;
773
+ async function toolListDirectory(provider, args) {
774
+ const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
775
+ const initialDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
776
+ async function getListRecursive(currentDepth) {
777
+ const entries = await provider.listDirectory({
778
+ path: args.path,
779
+ pattern: args.pattern ?? null,
780
+ maxResults,
781
+ maxDepth: currentDepth
782
+ });
783
+ if (entries.length >= maxResults && currentDepth > 0) {
784
+ return getListRecursive(currentDepth - 1);
785
+ }
786
+ return { entries };
787
+ }
788
+ const { entries: list } = await getListRecursive(initialDepth);
789
+ if (!list.length) return "empty";
790
+ const tree = list.map((e) => {
791
+ const indent = " ".repeat(e.depth);
792
+ const name = e.type === "dir" ? `${e.name}/` : e.name;
793
+ return `${indent}${name}`;
794
+ }).join("\n");
795
+ return tree;
777
796
  }
778
797
 
779
798
  // tools/warp_grep/agent/tools/finish.ts
@@ -834,21 +853,32 @@ function mergeRanges(ranges) {
834
853
  return merged;
835
854
  }
836
855
 
837
- // tools/warp_grep/agent/helpers.ts
838
- var import_path2 = __toESM(require("path"), 1);
839
- init_config();
840
- var TRUNCATED_MARKER = "[truncated for context limit]";
841
- function getMessageSize(m) {
842
- if (m.role === "tool") return m.content.length;
843
- if (m.role === "assistant") {
844
- let size = typeof m.content === "string" ? m.content.length : 0;
845
- if (m.tool_calls) {
846
- size += m.tool_calls.reduce((s, tc) => s + tc.function.name.length + tc.function.arguments.length, 0);
856
+ // tools/warp_grep/agent/formatter.ts
857
+ var ToolOutputFormatter = class {
858
+ format(toolName, _args, output, options = {}) {
859
+ const name = (toolName ?? "").trim();
860
+ if (!name) {
861
+ return "";
847
862
  }
848
- return size;
863
+ const payload = output?.toString?.()?.trim?.() ?? "";
864
+ const isError = Boolean(options.isError);
865
+ if (!payload && !isError) {
866
+ return "";
867
+ }
868
+ return `<tool_response>
869
+ ${payload}
870
+ </tool_response>`;
849
871
  }
850
- return m.content.length;
872
+ };
873
+ var sharedFormatter = new ToolOutputFormatter();
874
+ function formatAgentToolOutput(toolName, args, output, options = {}) {
875
+ return sharedFormatter.format(toolName, args, output, options);
851
876
  }
877
+
878
+ // tools/warp_grep/agent/helpers.ts
879
+ var import_path = __toESM(require("path"), 1);
880
+ init_config();
881
+ var TRUNCATED_MARKER = "[truncated for context limit]";
852
882
  function formatTurnMessage(turnsUsed, maxTurns) {
853
883
  const turnsRemaining = maxTurns - turnsUsed;
854
884
  if (turnsRemaining === 1) {
@@ -859,7 +889,7 @@ You have used ${turnsUsed} turns, you only have 1 turn remaining. You have run o
859
889
  You have used ${turnsUsed} turn${turnsUsed === 1 ? "" : "s"} and have ${turnsRemaining} remaining`;
860
890
  }
861
891
  function calculateContextBudget(messages) {
862
- const totalChars = messages.reduce((sum, m) => sum + getMessageSize(m), 0);
892
+ const totalChars = messages.reduce((sum, m) => sum + m.content.length, 0);
863
893
  const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;
864
894
  const percent = Math.round(totalChars / maxChars * 100);
865
895
  const usedK = Math.round(totalChars / 1e3);
@@ -868,21 +898,24 @@ function calculateContextBudget(messages) {
868
898
  }
869
899
  async function buildInitialState(repoRoot, searchTerm, provider, options) {
870
900
  const budget = calculateContextBudget([]);
871
- const turnTag = `You have used 0 turns and have ${AGENT_CONFIG.MAX_TURNS} remaining`;
901
+ const turnTag = `Turn 0/${AGENT_CONFIG.MAX_TURNS}`;
872
902
  const treeDepth = options?.search_type === "node_modules" ? 1 : 2;
873
- const absRoot = import_path2.default.resolve(repoRoot);
874
903
  try {
875
904
  const entries = await provider.listDirectory({
876
905
  path: ".",
877
906
  maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,
878
907
  maxDepth: treeDepth
879
908
  });
880
- const lines = [absRoot];
881
- for (const e of entries) {
882
- lines.push(import_path2.default.join(absRoot, e.path));
883
- }
909
+ const treeLines = entries.map((e) => {
910
+ const indent = " ".repeat(e.depth);
911
+ const name = e.type === "dir" ? `${e.name}/` : e.name;
912
+ return `${indent}${name}`;
913
+ });
914
+ const repoName = import_path.default.basename(repoRoot);
915
+ const treeOutput = treeLines.length > 0 ? `${repoName}/
916
+ ${treeLines.join("\n")}` : `${repoName}/`;
884
917
  return `<repo_structure>
885
- ${lines.join("\n")}
918
+ ${treeOutput}
886
919
  </repo_structure>
887
920
 
888
921
  <search_string>
@@ -891,8 +924,9 @@ ${searchTerm}
891
924
  ${budget}
892
925
  ${turnTag}`;
893
926
  } catch {
927
+ const repoName = import_path.default.basename(repoRoot);
894
928
  return `<repo_structure>
895
- ${absRoot}
929
+ ${repoName}/
896
930
  </repo_structure>
897
931
 
898
932
  <search_string>
@@ -903,32 +937,26 @@ ${turnTag}`;
903
937
  }
904
938
  }
905
939
  function enforceContextLimit(messages, maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS) {
906
- const getTotalChars = () => messages.reduce((sum, m) => sum + getMessageSize(m), 0);
940
+ const getTotalChars = () => messages.reduce((sum, m) => sum + m.content.length, 0);
907
941
  if (getTotalChars() <= maxChars) {
908
942
  return messages;
909
943
  }
910
- const truncatableIndices = [];
944
+ const userIndices = [];
911
945
  let firstUserSkipped = false;
912
946
  for (let i = 0; i < messages.length; i++) {
913
- const m = messages[i];
914
- if (m.role === "tool") {
915
- truncatableIndices.push(i);
916
- } else if (m.role === "user") {
947
+ if (messages[i].role === "user") {
917
948
  if (!firstUserSkipped) {
918
949
  firstUserSkipped = true;
919
950
  continue;
920
951
  }
921
- truncatableIndices.push(i);
952
+ userIndices.push(i);
922
953
  }
923
954
  }
924
- for (const idx of truncatableIndices) {
955
+ for (const idx of userIndices) {
925
956
  if (getTotalChars() <= maxChars) {
926
957
  break;
927
958
  }
928
- const m = messages[idx];
929
- if (m.role === "tool" && m.content !== TRUNCATED_MARKER) {
930
- messages[idx] = { role: "tool", tool_call_id: m.tool_call_id, content: TRUNCATED_MARKER };
931
- } else if (m.role === "user" && m.content !== TRUNCATED_MARKER) {
959
+ if (messages[idx].content !== TRUNCATED_MARKER) {
932
960
  messages[idx] = { role: "user", content: TRUNCATED_MARKER };
933
961
  }
934
962
  }
@@ -941,7 +969,7 @@ var import_openai = __toESM(require("openai"), 1);
941
969
  // package.json
942
970
  var package_default = {
943
971
  name: "@morphllm/morphsdk",
944
- version: "0.2.145",
972
+ version: "0.2.146",
945
973
  description: "TypeScript SDK and CLI for Morph Fast Apply integration",
946
974
  type: "module",
947
975
  main: "./dist/index.cjs",
@@ -1180,115 +1208,9 @@ var package_default = {
1180
1208
  var SDK_VERSION = package_default.version;
1181
1209
 
1182
1210
  // tools/warp_grep/agent/runner.ts
1183
- var import_path3 = __toESM(require("path"), 1);
1211
+ var import_path2 = __toESM(require("path"), 1);
1212
+ var parser = new LLMResponseParser();
1184
1213
  var DEFAULT_API_URL = "https://api.morphllm.com";
1185
- var TOOL_SPECS = [
1186
- {
1187
- type: "function",
1188
- function: {
1189
- name: "list_directory",
1190
- description: "Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.",
1191
- parameters: {
1192
- type: "object",
1193
- properties: {
1194
- command: {
1195
- type: "string",
1196
- description: "Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */)."
1197
- }
1198
- },
1199
- required: ["command"]
1200
- }
1201
- }
1202
- },
1203
- {
1204
- type: "function",
1205
- function: {
1206
- name: "grep_search",
1207
- description: "Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.",
1208
- parameters: {
1209
- type: "object",
1210
- properties: {
1211
- pattern: {
1212
- type: "string",
1213
- description: "Regex pattern to search for in file contents (e.g. 'class\\s+\\w+Error', 'import|require|from', 'def (get|set|update)_user')."
1214
- },
1215
- path: {
1216
- type: "string",
1217
- description: "File or directory to search in. Defaults to current working directory."
1218
- },
1219
- glob: {
1220
- type: "string",
1221
- description: "Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*')."
1222
- },
1223
- limit: {
1224
- type: "integer",
1225
- description: "Limit output to first N matching lines. Shows all matches if not specified."
1226
- }
1227
- },
1228
- required: ["pattern"]
1229
- }
1230
- }
1231
- },
1232
- {
1233
- type: "function",
1234
- function: {
1235
- name: "glob",
1236
- description: "Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.",
1237
- parameters: {
1238
- type: "object",
1239
- properties: {
1240
- pattern: {
1241
- type: "string",
1242
- description: "Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py')."
1243
- },
1244
- path: {
1245
- type: "string",
1246
- description: "Directory to search in. Defaults to repository root."
1247
- }
1248
- },
1249
- required: ["pattern"]
1250
- }
1251
- }
1252
- },
1253
- {
1254
- type: "function",
1255
- function: {
1256
- name: "read",
1257
- description: "Read entire files or specific line ranges using absolute paths.",
1258
- parameters: {
1259
- type: "object",
1260
- properties: {
1261
- path: {
1262
- type: "string",
1263
- description: "File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path)."
1264
- },
1265
- lines: {
1266
- type: "string",
1267
- description: "Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file."
1268
- }
1269
- },
1270
- required: ["path"]
1271
- }
1272
- }
1273
- },
1274
- {
1275
- type: "function",
1276
- function: {
1277
- name: "finish",
1278
- description: "Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.",
1279
- parameters: {
1280
- type: "object",
1281
- properties: {
1282
- files: {
1283
- type: "string",
1284
- 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."
1285
- }
1286
- },
1287
- required: ["files"]
1288
- }
1289
- }
1290
- }
1291
- ];
1292
1214
  async function callModel(messages, model, options = {}) {
1293
1215
  const baseUrl = options.morphApiUrl || DEFAULT_API_URL;
1294
1216
  const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
@@ -1309,9 +1231,8 @@ async function callModel(messages, model, options = {}) {
1309
1231
  data = await client.chat.completions.create({
1310
1232
  model,
1311
1233
  temperature: 0,
1312
- max_tokens: 2048,
1234
+ max_tokens: 1024,
1313
1235
  messages,
1314
- tools: TOOL_SPECS,
1315
1236
  ...options.search_type ? { search_type: options.search_type } : {}
1316
1237
  });
1317
1238
  } catch (error) {
@@ -1323,87 +1244,187 @@ async function callModel(messages, model, options = {}) {
1323
1244
  throw error;
1324
1245
  }
1325
1246
  const choice = data?.choices?.[0];
1326
- const message = choice?.message;
1327
- if (!message) {
1328
- if (attempt === MAX_EMPTY_RETRIES) {
1329
- throw new Error("Invalid response from model: no message in response");
1330
- }
1331
- await new Promise((resolve) => setTimeout(resolve, 200));
1332
- continue;
1333
- }
1334
- const toolCalls = (message.tool_calls || []).map((tc) => ({
1335
- id: tc.id,
1336
- type: "function",
1337
- function: { name: tc.function.name, arguments: tc.function.arguments }
1338
- }));
1339
- if (message.content || toolCalls.length > 0) {
1340
- return { content: message.content ?? null, tool_calls: toolCalls };
1247
+ const content = choice?.message?.content;
1248
+ if (content && typeof content === "string") {
1249
+ return content;
1341
1250
  }
1342
1251
  if (attempt === MAX_EMPTY_RETRIES) {
1343
1252
  const finishReason = choice?.finish_reason ?? "unknown";
1253
+ const hasToolCalls = Array.isArray(choice?.message?.tool_calls) && choice.message.tool_calls.length > 0;
1254
+ const choicesLen = data?.choices?.length ?? 0;
1255
+ const contentType = content === null ? "null" : content === void 0 ? "undefined" : typeof content;
1344
1256
  throw new Error(
1345
- `Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`
1257
+ `Invalid response from model: content=${contentType}, finish_reason=${finishReason}, has_tool_calls=${hasToolCalls}, choices_length=${choicesLen}`
1346
1258
  );
1347
1259
  }
1348
1260
  await new Promise((resolve) => setTimeout(resolve, 200));
1349
1261
  }
1350
1262
  throw new Error("Invalid response from model");
1351
1263
  }
1352
- function safeParseJSON(s) {
1353
- try {
1354
- return JSON.parse(s);
1355
- } catch {
1356
- return {};
1357
- }
1358
- }
1359
- async function executeTool(provider, name, args, repoRoot) {
1360
- switch (name) {
1361
- case "grep_search": {
1362
- const grepArgs = {
1363
- pattern: args.pattern,
1364
- path: args.path || "."
1365
- };
1366
- if (args.glob) grepArgs.glob = args.glob;
1367
- if (args.case_sensitive !== void 0) grepArgs.case_sensitive = args.case_sensitive;
1368
- const result = await toolGrep(provider, grepArgs);
1369
- let output = result.output;
1370
- if (args.limit && typeof args.limit === "number") {
1371
- const lines = output.split("\n");
1372
- if (lines.length > args.limit) {
1373
- output = lines.slice(0, args.limit).join("\n") + `
1374
- ... (truncated at ${args.limit} lines)`;
1375
- }
1376
- }
1377
- return output;
1264
+ async function runWarpGrep(config) {
1265
+ const totalStart = Date.now();
1266
+ const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
1267
+ const timings = { turns: [], timeout_ms: timeoutMs };
1268
+ const repoRoot = import_path2.default.resolve(config.repoRoot || process.cwd());
1269
+ const model = config.model || DEFAULT_MODEL;
1270
+ const messages = [];
1271
+ const maxTurns = AGENT_CONFIG.MAX_TURNS;
1272
+ const initialStateStart = Date.now();
1273
+ const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });
1274
+ timings.initial_state_ms = Date.now() - initialStateStart;
1275
+ messages.push({ role: "user", content: initialState });
1276
+ const provider = config.provider;
1277
+ const errors = [];
1278
+ let finishMeta;
1279
+ let terminationReason = "terminated";
1280
+ for (let turn = 1; turn <= maxTurns; turn += 1) {
1281
+ const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
1282
+ enforceContextLimit(messages);
1283
+ const modelCallStart = Date.now();
1284
+ const assistantContent = await callModel(messages, model, {
1285
+ morphApiKey: config.morphApiKey,
1286
+ morphApiUrl: config.morphApiUrl,
1287
+ retryConfig: config.retryConfig,
1288
+ timeout: timeoutMs,
1289
+ search_type: config.search_type
1290
+ }).catch((e) => {
1291
+ const errMsg = e instanceof Error ? e.message : String(e);
1292
+ console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
1293
+ errors.push({ message: errMsg });
1294
+ return "";
1295
+ });
1296
+ turnMetrics.morph_api_ms = Date.now() - modelCallStart;
1297
+ if (!assistantContent) {
1298
+ console.error(`[warp_grep] Empty response from Morph API on turn ${turn}. Errors so far:`, errors);
1299
+ timings.turns.push(turnMetrics);
1300
+ break;
1378
1301
  }
1379
- case "glob": {
1380
- return toolGlob(provider, {
1381
- pattern: args.pattern,
1382
- path: args.path
1383
- });
1302
+ messages.push({ role: "assistant", content: assistantContent });
1303
+ const toolCalls = parser.parse(assistantContent);
1304
+ if (toolCalls.length === 0) {
1305
+ console.error(`[warp_grep] No tool calls parsed on turn ${turn}. Assistant content (first 500 chars):`, assistantContent.slice(0, 500));
1306
+ 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" });
1307
+ terminationReason = "terminated";
1308
+ timings.turns.push(turnMetrics);
1309
+ break;
1384
1310
  }
1385
- case "list_directory": {
1386
- const dirPath = extractPathFromCommand(args.command || ".");
1387
- return toolListDirectory(provider, { path: dirPath }, repoRoot);
1311
+ const finishCalls = toolCalls.filter((c) => c.name === "finish");
1312
+ const grepCalls = toolCalls.filter((c) => c.name === "grep");
1313
+ const listDirCalls = toolCalls.filter((c) => c.name === "list_directory");
1314
+ const readCalls = toolCalls.filter((c) => c.name === "read");
1315
+ const skipCalls = toolCalls.filter((c) => c.name === "_skip");
1316
+ const formatted = [];
1317
+ for (const c of skipCalls) {
1318
+ const msg = c.arguments?.message || "Command skipped due to parsing error";
1319
+ formatted.push(msg);
1388
1320
  }
1389
- case "read": {
1390
- const readArgs = {
1391
- path: args.path
1392
- };
1393
- if (args.lines && typeof args.lines === "string") {
1394
- Object.assign(readArgs, parseReadLines(args.lines));
1321
+ const allPromises = [];
1322
+ for (const c of grepCalls) {
1323
+ const args = c.arguments ?? {};
1324
+ allPromises.push(
1325
+ toolGrep(provider, args).then(
1326
+ ({ output }) => formatAgentToolOutput("grep", args, output),
1327
+ (err) => formatAgentToolOutput("grep", args, String(err), { isError: true })
1328
+ )
1329
+ );
1330
+ }
1331
+ for (const c of listDirCalls) {
1332
+ const args = c.arguments ?? {};
1333
+ allPromises.push(
1334
+ toolListDirectory(provider, args).then(
1335
+ (p) => formatAgentToolOutput("list_directory", args, p),
1336
+ (err) => formatAgentToolOutput("list_directory", args, String(err), { isError: true })
1337
+ )
1338
+ );
1339
+ }
1340
+ for (const c of readCalls) {
1341
+ const args = c.arguments ?? {};
1342
+ allPromises.push(
1343
+ toolRead(provider, args).then(
1344
+ (p) => formatAgentToolOutput("read", args, p),
1345
+ (err) => formatAgentToolOutput("read", args, String(err), { isError: true })
1346
+ )
1347
+ );
1348
+ }
1349
+ const toolExecStart = Date.now();
1350
+ const allResults = await Promise.all(allPromises);
1351
+ turnMetrics.local_tools_ms = Date.now() - toolExecStart;
1352
+ for (const result of allResults) {
1353
+ formatted.push(result);
1354
+ }
1355
+ if (formatted.length > 0) {
1356
+ const turnMessage = formatTurnMessage(turn, maxTurns);
1357
+ const contextBudget = calculateContextBudget(messages);
1358
+ messages.push({ role: "user", content: formatted.join("\n") + turnMessage + "\n" + contextBudget });
1359
+ }
1360
+ timings.turns.push(turnMetrics);
1361
+ if (finishCalls.length) {
1362
+ const fc = finishCalls[0];
1363
+ const files = fc.arguments?.files ?? [];
1364
+ const textResult = fc.arguments?.textResult;
1365
+ finishMeta = { files };
1366
+ terminationReason = "completed";
1367
+ if (files.length === 0) {
1368
+ const payload2 = textResult || "No relevant code found.";
1369
+ timings.turns.push(turnMetrics);
1370
+ timings.total_ms = Date.now() - totalStart;
1371
+ return {
1372
+ terminationReason: "completed",
1373
+ messages,
1374
+ finish: { payload: payload2, metadata: finishMeta },
1375
+ timings
1376
+ };
1377
+ }
1378
+ break;
1379
+ }
1380
+ }
1381
+ if (terminationReason !== "completed" || !finishMeta) {
1382
+ timings.total_ms = Date.now() - totalStart;
1383
+ return { terminationReason, messages, errors, timings };
1384
+ }
1385
+ const parts = ["Relevant context found:"];
1386
+ for (const f of finishMeta.files) {
1387
+ const ranges = f.lines === "*" ? "*" : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(", ") : "*";
1388
+ parts.push(`- ${f.path}: ${ranges}`);
1389
+ }
1390
+ const payload = parts.join("\n");
1391
+ const finishResolutionStart = Date.now();
1392
+ const fileReadErrors = [];
1393
+ const resolved = await readFinishFiles(
1394
+ repoRoot,
1395
+ finishMeta.files,
1396
+ async (p, s, e) => {
1397
+ try {
1398
+ const rr = await provider.read({ path: p, start: s, end: e });
1399
+ return rr.lines.map((l) => {
1400
+ const idx = l.indexOf("|");
1401
+ return idx >= 0 ? l.slice(idx + 1) : l;
1402
+ });
1403
+ } catch (err) {
1404
+ const errorMsg = err instanceof Error ? err.message : String(err);
1405
+ fileReadErrors.push({ path: p, error: errorMsg });
1406
+ console.error(`[warp_grep] Failed to read file: ${p} - ${errorMsg}`);
1407
+ return [`[couldn't find: ${p}]`];
1395
1408
  }
1396
- return toolRead(provider, readArgs);
1397
1409
  }
1398
- default:
1399
- return `Unknown tool: ${name}`;
1410
+ );
1411
+ timings.finish_resolution_ms = Date.now() - finishResolutionStart;
1412
+ if (fileReadErrors.length > 0) {
1413
+ errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
1400
1414
  }
1415
+ timings.total_ms = Date.now() - totalStart;
1416
+ return {
1417
+ terminationReason: "completed",
1418
+ messages,
1419
+ finish: { payload, metadata: finishMeta, resolved },
1420
+ timings
1421
+ };
1401
1422
  }
1402
1423
  async function* runWarpGrepStreaming(config) {
1403
1424
  const totalStart = Date.now();
1404
1425
  const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
1405
1426
  const timings = { turns: [], timeout_ms: timeoutMs };
1406
- const repoRoot = import_path3.default.resolve(config.repoRoot || process.cwd());
1427
+ const repoRoot = import_path2.default.resolve(config.repoRoot || process.cwd());
1407
1428
  const model = config.model || DEFAULT_MODEL;
1408
1429
  const messages = [];
1409
1430
  const maxTurns = AGENT_CONFIG.MAX_TURNS;
@@ -1419,7 +1440,7 @@ async function* runWarpGrepStreaming(config) {
1419
1440
  const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
1420
1441
  enforceContextLimit(messages);
1421
1442
  const modelCallStart = Date.now();
1422
- const response = await callModel(messages, model, {
1443
+ const assistantContent = await callModel(messages, model, {
1423
1444
  morphApiKey: config.morphApiKey,
1424
1445
  morphApiUrl: config.morphApiUrl,
1425
1446
  retryConfig: config.retryConfig,
@@ -1427,45 +1448,90 @@ async function* runWarpGrepStreaming(config) {
1427
1448
  search_type: config.search_type
1428
1449
  }).catch((e) => {
1429
1450
  const errMsg = e instanceof Error ? e.message : String(e);
1430
- console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
1451
+ console.error(`[warp_grep:stream] Morph API call failed on turn ${turn}:`, errMsg);
1431
1452
  errors.push({ message: errMsg });
1432
- return null;
1453
+ return "";
1433
1454
  });
1434
1455
  turnMetrics.morph_api_ms = Date.now() - modelCallStart;
1435
- if (!response) {
1456
+ if (!assistantContent) {
1457
+ console.error(`[warp_grep:stream] Empty response from Morph API on turn ${turn}. Errors so far:`, errors);
1436
1458
  timings.turns.push(turnMetrics);
1437
1459
  break;
1438
1460
  }
1439
- const toolCalls = response.tool_calls;
1440
- messages.push({
1441
- role: "assistant",
1442
- content: response.content,
1443
- ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
1444
- });
1461
+ messages.push({ role: "assistant", content: assistantContent });
1462
+ const toolCalls = parser.parse(assistantContent);
1445
1463
  if (toolCalls.length === 0) {
1446
- console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || "").slice(0, 500)}`);
1447
- errors.push({ message: "No tool calls produced by the model." });
1464
+ console.error(`[warp_grep:stream] No tool calls parsed on turn ${turn}. Assistant content (first 500 chars):`, assistantContent.slice(0, 500));
1465
+ 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" });
1448
1466
  terminationReason = "terminated";
1449
1467
  timings.turns.push(turnMetrics);
1450
1468
  break;
1451
1469
  }
1452
1470
  yield {
1453
1471
  turn,
1454
- toolCalls: toolCalls.map((tc) => ({
1455
- name: tc.function.name,
1456
- arguments: safeParseJSON(tc.function.arguments)
1472
+ toolCalls: toolCalls.map((c) => ({
1473
+ name: c.name,
1474
+ arguments: c.arguments ?? {}
1457
1475
  }))
1458
1476
  };
1459
- const finishCall = toolCalls.find((tc) => tc.function.name === "finish");
1460
- if (finishCall) {
1461
- const args = safeParseJSON(finishCall.function.arguments);
1462
- const filesStr = args.files || "";
1463
- const files = parseFinishFiles(filesStr);
1477
+ const finishCalls = toolCalls.filter((c) => c.name === "finish");
1478
+ const grepCalls = toolCalls.filter((c) => c.name === "grep");
1479
+ const listDirCalls = toolCalls.filter((c) => c.name === "list_directory");
1480
+ const readCalls = toolCalls.filter((c) => c.name === "read");
1481
+ const skipCalls = toolCalls.filter((c) => c.name === "_skip");
1482
+ const formatted = [];
1483
+ for (const c of skipCalls) {
1484
+ const msg = c.arguments?.message || "Command skipped due to parsing error";
1485
+ formatted.push(msg);
1486
+ }
1487
+ const allPromises = [];
1488
+ for (const c of grepCalls) {
1489
+ const args = c.arguments ?? {};
1490
+ allPromises.push(
1491
+ toolGrep(provider, args).then(
1492
+ ({ output }) => formatAgentToolOutput("grep", args, output),
1493
+ (err) => formatAgentToolOutput("grep", args, String(err), { isError: true })
1494
+ )
1495
+ );
1496
+ }
1497
+ for (const c of listDirCalls) {
1498
+ const args = c.arguments ?? {};
1499
+ allPromises.push(
1500
+ toolListDirectory(provider, args).then(
1501
+ (p) => formatAgentToolOutput("list_directory", args, p),
1502
+ (err) => formatAgentToolOutput("list_directory", args, String(err), { isError: true })
1503
+ )
1504
+ );
1505
+ }
1506
+ for (const c of readCalls) {
1507
+ const args = c.arguments ?? {};
1508
+ allPromises.push(
1509
+ toolRead(provider, args).then(
1510
+ (p) => formatAgentToolOutput("read", args, p),
1511
+ (err) => formatAgentToolOutput("read", args, String(err), { isError: true })
1512
+ )
1513
+ );
1514
+ }
1515
+ const toolExecStart = Date.now();
1516
+ const allResults = await Promise.all(allPromises);
1517
+ turnMetrics.local_tools_ms = Date.now() - toolExecStart;
1518
+ for (const result of allResults) {
1519
+ formatted.push(result);
1520
+ }
1521
+ if (formatted.length > 0) {
1522
+ const turnMessage = formatTurnMessage(turn, maxTurns);
1523
+ const contextBudget = calculateContextBudget(messages);
1524
+ messages.push({ role: "user", content: formatted.join("\n") + turnMessage + "\n" + contextBudget });
1525
+ }
1526
+ timings.turns.push(turnMetrics);
1527
+ if (finishCalls.length) {
1528
+ const fc = finishCalls[0];
1529
+ const files = fc.arguments?.files ?? [];
1530
+ const textResult = fc.arguments?.textResult;
1464
1531
  finishMeta = { files };
1465
1532
  terminationReason = "completed";
1466
1533
  if (files.length === 0) {
1467
- const payload2 = filesStr || "No relevant code found.";
1468
- timings.turns.push(turnMetrics);
1534
+ const payload2 = textResult || "No relevant code found.";
1469
1535
  timings.total_ms = Date.now() - totalStart;
1470
1536
  return {
1471
1537
  terminationReason: "completed",
@@ -1474,25 +1540,8 @@ async function* runWarpGrepStreaming(config) {
1474
1540
  timings
1475
1541
  };
1476
1542
  }
1477
- timings.turns.push(turnMetrics);
1478
1543
  break;
1479
1544
  }
1480
- const toolExecStart = Date.now();
1481
- const results = await Promise.all(
1482
- toolCalls.map(async (tc) => {
1483
- const args = safeParseJSON(tc.function.arguments);
1484
- const output = await executeTool(provider, tc.function.name, args, repoRoot).catch((err) => String(err));
1485
- return { tool_call_id: tc.id, content: output };
1486
- })
1487
- );
1488
- turnMetrics.local_tools_ms = Date.now() - toolExecStart;
1489
- for (const result of results) {
1490
- messages.push({ role: "tool", tool_call_id: result.tool_call_id, content: result.content });
1491
- }
1492
- const turnMsg = formatTurnMessage(turn, maxTurns);
1493
- const budget = calculateContextBudget(messages);
1494
- messages.push({ role: "user", content: turnMsg + "\n" + budget });
1495
- timings.turns.push(turnMetrics);
1496
1545
  }
1497
1546
  if (terminationReason !== "completed" || !finishMeta) {
1498
1547
  timings.total_ms = Date.now() - totalStart;
@@ -1536,14 +1585,6 @@ async function* runWarpGrepStreaming(config) {
1536
1585
  timings
1537
1586
  };
1538
1587
  }
1539
- async function runWarpGrep(config) {
1540
- const gen = runWarpGrepStreaming(config);
1541
- let result = await gen.next();
1542
- while (!result.done) {
1543
- result = await gen.next();
1544
- }
1545
- return result.value;
1546
- }
1547
1588
 
1548
1589
  // tools/warp_grep/providers/remote.ts
1549
1590
  init_config();
@@ -1723,35 +1764,6 @@ var RemoteCommandsProvider = class {
1723
1764
  return [];
1724
1765
  }
1725
1766
  }
1726
- /**
1727
- * Glob search - finds files matching a pattern.
1728
- * Falls back to a grep --files approach via the listDir command.
1729
- */
1730
- async glob(params) {
1731
- const searchPath = params.path || this.repoRoot;
1732
- try {
1733
- const stdout = await this.commands.listDir(searchPath, 10);
1734
- const allPaths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
1735
- const globToRegex = (glob) => {
1736
- const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
1737
- return new RegExp(escaped);
1738
- };
1739
- const regex = globToRegex(params.pattern);
1740
- const matched = allPaths.filter((p) => {
1741
- const name = p.split("/").pop() || "";
1742
- return regex.test(name) && !shouldSkip(name);
1743
- });
1744
- const totalFound = matched.length;
1745
- return { files: matched.slice(0, 100), searchDir: searchPath, totalFound };
1746
- } catch (error) {
1747
- return {
1748
- files: [],
1749
- searchDir: searchPath,
1750
- totalFound: 0,
1751
- error: `[GLOB ERROR] ${error instanceof Error ? error.message : String(error)}`
1752
- };
1753
- }
1754
- }
1755
1767
  };
1756
1768
 
1757
1769
  // tools/warp_grep/providers/code_storage_http.ts
@@ -1778,9 +1790,9 @@ function createCodeStorageHttpCommands(config) {
1778
1790
  const { baseUrl, repoId, branch } = config;
1779
1791
  const encodedRepoId = encodeURIComponent(repoId);
1780
1792
  return {
1781
- grep: (pattern, path6, glob) => post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path: path6, glob, branch }, "grep"),
1782
- read: (path6, start, end) => post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path: path6, start, end, branch }, "read"),
1783
- listDir: (path6, maxDepth) => post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path: path6, maxDepth, branch }, "list")
1793
+ grep: (pattern, path5, glob) => post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path: path5, glob, branch }, "grep"),
1794
+ read: (path5, start, end) => post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path: path5, start, end, branch }, "read"),
1795
+ listDir: (path5, maxDepth) => post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path: path5, maxDepth, branch }, "list")
1784
1796
  };
1785
1797
  }
1786
1798