@morphllm/morphsdk 0.2.202 → 0.2.203

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/dist/chunk-2PPYWRMZ.js +3 -4
  2. package/dist/{chunk-SIFDK4AA.js → chunk-2UIOCSVJ.js} +3 -24
  3. package/dist/chunk-44OIEPIO.js +4 -23
  4. package/dist/chunk-4EQQGUZ7.cjs +104 -0
  5. package/dist/chunk-4OUGA3KS.js +1 -5
  6. package/dist/chunk-4R5MDGL6.cjs +280 -0
  7. package/dist/chunk-65W4I66Q.cjs +103 -0
  8. package/dist/{chunk-3CPI6ZIC.js → chunk-66THRMD7.js} +10 -35
  9. package/dist/chunk-6TZCVTW5.js +3 -4
  10. package/dist/chunk-6WP7EA4F.js +2 -4
  11. package/dist/chunk-74A4HLIO.cjs +42 -0
  12. package/dist/chunk-75ZPJI57.cjs +9 -0
  13. package/dist/chunk-7NA7X7W2.cjs +77 -0
  14. package/dist/chunk-7PJYY46L.cjs +2 -0
  15. package/dist/chunk-AFF6XYKL.cjs +71 -0
  16. package/dist/{chunk-2XU3XXUE.js → chunk-AJBZA23L.js} +3 -25
  17. package/dist/chunk-AWFZKS27.cjs +11 -0
  18. package/dist/{chunk-LVKKICOB.js → chunk-AXEKIRRY.js} +22 -62
  19. package/dist/chunk-B3FD67F2.cjs +256 -0
  20. package/dist/chunk-BJBWWIZV.cjs +2 -0
  21. package/dist/{chunk-UAZKHSEU.js → chunk-E3XNKAMI.js} +5 -15
  22. package/dist/{chunk-VQDDL3UH.js → chunk-E7FLETFO.js} +2 -8
  23. package/dist/{chunk-YAM6P5OQ.js → chunk-EI2M567U.js} +2 -6
  24. package/dist/chunk-EJTL2BOZ.cjs +42 -0
  25. package/dist/chunk-ETBRAKVV.js +1 -5
  26. package/dist/{chunk-6OYJC4TZ.js → chunk-EZ2OFDBJ.js} +5 -19
  27. package/dist/chunk-FBOZIVVQ.js +1 -0
  28. package/dist/{chunk-CAWQEHKP.js → chunk-GDFPZ3NJ.js} +4 -19
  29. package/dist/{chunk-UKXCGQPS.js → chunk-GIQAIHUI.js} +8 -33
  30. package/dist/chunk-GSUQGDCL.cjs +235 -0
  31. package/dist/{chunk-D6YJ5X3C.js → chunk-H3HRSRR5.js} +4 -12
  32. package/dist/chunk-HDP4QAZL.js +1 -4
  33. package/dist/chunk-HMLYJVZM.cjs +410 -0
  34. package/dist/chunk-IPJA3ZS6.cjs +10 -0
  35. package/dist/{chunk-XPHNS7NW.js → chunk-IUM6CQYX.js} +3 -12
  36. package/dist/{chunk-26K5EJD3.js → chunk-J56Q6C4Y.js} +4 -18
  37. package/dist/chunk-JBTR3FQD.cjs +135 -0
  38. package/dist/chunk-JNQKQKHS.cjs +81 -0
  39. package/dist/chunk-JOZC4T6C.cjs +168 -0
  40. package/dist/{chunk-JEVLCA5C.js → chunk-JUGNTIVU.js} +6 -19
  41. package/dist/{chunk-NFPRKZQ5.js → chunk-JY6COF3X.js} +5 -22
  42. package/dist/{chunk-ICCGLO6V.js → chunk-KLVJIC2O.js} +5 -17
  43. package/dist/chunk-KSZYOX6S.cjs +91 -0
  44. package/dist/chunk-KVGZ2TSG.cjs +274 -0
  45. package/dist/chunk-LDM7RNNN.js +1 -0
  46. package/dist/{chunk-65TUD7JV.js → chunk-LLQH6CCB.js} +10 -28
  47. package/dist/chunk-M34E2AMK.js +1 -5
  48. package/dist/chunk-MF56KEI4.js +1 -4
  49. package/dist/chunk-MLKGABMK.js +1 -3
  50. package/dist/chunk-MLPZKUCO.js +4 -5
  51. package/dist/chunk-MWXJ6DZ2.cjs +21 -0
  52. package/dist/{chunk-IBRBSDLT.js → chunk-N7UKZ5X7.js} +2 -6
  53. package/dist/chunk-NDUC7OV6.cjs +74 -0
  54. package/dist/{chunk-PDSIWL7I.js → chunk-NLACTMZT.js} +6 -19
  55. package/dist/chunk-NNKBKENK.cjs +15 -0
  56. package/dist/chunk-NRG6QX3L.js +1 -3
  57. package/dist/chunk-OCCGJ4S6.js +8 -0
  58. package/dist/chunk-ODY2NKQU.cjs +50 -0
  59. package/dist/chunk-OM5ZSXQW.cjs +91 -0
  60. package/dist/chunk-OOEORM7H.cjs +334 -0
  61. package/dist/chunk-OPDWMD4Q.js +1 -3
  62. package/dist/chunk-OSL4CNSO.js +7 -23
  63. package/dist/chunk-OXXMTDOY.cjs +86 -0
  64. package/dist/chunk-PA3UTI4A.js +1 -4
  65. package/dist/chunk-QEEAIXL5.cjs +74 -0
  66. package/dist/chunk-RYVW7RUM.js +2 -6
  67. package/dist/chunk-S6QBPXBI.cjs +107 -0
  68. package/dist/chunk-TL34BLQD.cjs +10 -0
  69. package/dist/chunk-TPZHMD7J.cjs +72 -0
  70. package/dist/chunk-UAPK3AIJ.js +1 -10
  71. package/dist/chunk-UF5IKELS.cjs +26 -0
  72. package/dist/chunk-UNX7V6P6.cjs +60 -0
  73. package/dist/chunk-UUCRWJJR.cjs +313 -0
  74. package/dist/chunk-VDFLPO7B.cjs +396 -0
  75. package/dist/chunk-VHD7CW5O.cjs +43 -0
  76. package/dist/chunk-VL4QNALG.cjs +50 -0
  77. package/dist/chunk-WR7LSUIR.cjs +213 -0
  78. package/dist/chunk-XE6D4J63.cjs +72 -0
  79. package/dist/chunk-ZLG2M2I4.cjs +21 -0
  80. package/dist/chunk-ZSHVXDA2.js +4 -10
  81. package/dist/client.cjs +40 -4360
  82. package/dist/client.js +32 -37
  83. package/dist/core/client.cjs +10 -476
  84. package/dist/core/client.js +6 -11
  85. package/dist/core/error.cjs +8 -251
  86. package/dist/core/error.js +4 -9
  87. package/dist/core/index.cjs +20 -488
  88. package/dist/core/index.js +8 -19
  89. package/dist/core/resource.cjs +9 -33
  90. package/dist/core/resource.js +2 -7
  91. package/dist/edge.cjs +62 -1111
  92. package/dist/edge.js +10 -42
  93. package/dist/index.cjs +115 -4431
  94. package/dist/index.js +39 -87
  95. package/dist/modelrouter/core.cjs +28 -648
  96. package/dist/modelrouter/core.js +8 -21
  97. package/dist/modelrouter/index.cjs +28 -648
  98. package/dist/modelrouter/index.js +8 -21
  99. package/dist/modelrouter/types.cjs +1 -17
  100. package/dist/modelrouter/types.js +1 -0
  101. package/dist/subagents/anthropic.cjs +27 -2784
  102. package/dist/subagents/anthropic.js +19 -24
  103. package/dist/subagents/index.cjs +14 -95
  104. package/dist/subagents/index.js +2 -11
  105. package/dist/subagents/prompts.cjs +14 -93
  106. package/dist/subagents/prompts.js +2 -11
  107. package/dist/subagents/types.cjs +1 -17
  108. package/dist/subagents/types.js +1 -0
  109. package/dist/subagents/vercel.cjs +27 -2761
  110. package/dist/subagents/vercel.js +19 -24
  111. package/dist/tools/compact/core.cjs +12 -548
  112. package/dist/tools/compact/core.js +8 -13
  113. package/dist/tools/compact/index.cjs +17 -595
  114. package/dist/tools/compact/index.js +9 -17
  115. package/dist/tools/compact/types.cjs +1 -17
  116. package/dist/tools/compact/types.js +1 -0
  117. package/dist/tools/fastapply/anthropic.cjs +27 -891
  118. package/dist/tools/fastapply/anthropic.js +11 -24
  119. package/dist/tools/fastapply/apply.cjs +28 -672
  120. package/dist/tools/fastapply/apply.js +4 -19
  121. package/dist/tools/fastapply/core.cjs +37 -1061
  122. package/dist/tools/fastapply/core.js +9 -29
  123. package/dist/tools/fastapply/index.cjs +62 -1062
  124. package/dist/tools/fastapply/index.js +14 -44
  125. package/dist/tools/fastapply/openai.cjs +32 -901
  126. package/dist/tools/fastapply/openai.js +11 -26
  127. package/dist/tools/fastapply/prompts.cjs +10 -62
  128. package/dist/tools/fastapply/prompts.js +2 -9
  129. package/dist/tools/fastapply/types.cjs +1 -17
  130. package/dist/tools/fastapply/types.js +1 -0
  131. package/dist/tools/fastapply/vercel.cjs +25 -897
  132. package/dist/tools/fastapply/vercel.js +11 -22
  133. package/dist/tools/index.cjs +62 -1062
  134. package/dist/tools/index.js +14 -44
  135. package/dist/tools/utils/resilience.cjs +15 -312
  136. package/dist/tools/utils/resilience.js +3 -12
  137. package/dist/tools/warp_grep/agent/config.cjs +16 -127
  138. package/dist/tools/warp_grep/agent/config.js +2 -11
  139. package/dist/tools/warp_grep/agent/formatter.cjs +12 -48
  140. package/dist/tools/warp_grep/agent/formatter.js +2 -9
  141. package/dist/tools/warp_grep/agent/parser.cjs +16 -83
  142. package/dist/tools/warp_grep/agent/parser.js +2 -11
  143. package/dist/tools/warp_grep/agent/runner.cjs +15 -1081
  144. package/dist/tools/warp_grep/agent/runner.js +7 -14
  145. package/dist/tools/warp_grep/agent/types.cjs +1 -17
  146. package/dist/tools/warp_grep/agent/types.js +1 -0
  147. package/dist/tools/warp_grep/anthropic.cjs +47 -2561
  148. package/dist/tools/warp_grep/anthropic.js +19 -35
  149. package/dist/tools/warp_grep/client.cjs +49 -2471
  150. package/dist/tools/warp_grep/client.js +17 -34
  151. package/dist/tools/warp_grep/gemini.cjs +48 -2490
  152. package/dist/tools/warp_grep/gemini.js +21 -41
  153. package/dist/tools/warp_grep/harness.cjs +81 -936
  154. package/dist/tools/warp_grep/harness.js +12 -51
  155. package/dist/tools/warp_grep/index.cjs +124 -2575
  156. package/dist/tools/warp_grep/index.js +24 -87
  157. package/dist/tools/warp_grep/openai.cjs +53 -2575
  158. package/dist/tools/warp_grep/openai.js +19 -37
  159. package/dist/tools/warp_grep/providers/code_storage_http.cjs +12 -65
  160. package/dist/tools/warp_grep/providers/code_storage_http.js +2 -9
  161. package/dist/tools/warp_grep/providers/local.cjs +10 -589
  162. package/dist/tools/warp_grep/providers/local.js +6 -11
  163. package/dist/tools/warp_grep/providers/remote.cjs +8 -331
  164. package/dist/tools/warp_grep/providers/remote.js +3 -8
  165. package/dist/tools/warp_grep/providers/types.cjs +1 -17
  166. package/dist/tools/warp_grep/providers/types.js +1 -0
  167. package/dist/tools/warp_grep/utils/files.cjs +9 -42
  168. package/dist/tools/warp_grep/utils/files.js +2 -7
  169. package/dist/tools/warp_grep/utils/github.cjs +9 -43
  170. package/dist/tools/warp_grep/utils/github.js +2 -7
  171. package/dist/tools/warp_grep/utils/paths.cjs +28 -104
  172. package/dist/tools/warp_grep/utils/paths.js +2 -17
  173. package/dist/tools/warp_grep/utils/ripgrep.cjs +9 -103
  174. package/dist/tools/warp_grep/utils/ripgrep.js +2 -7
  175. package/dist/tools/warp_grep/vercel.cjs +53 -2557
  176. package/dist/tools/warp_grep/vercel.js +19 -37
  177. package/dist/version.cjs +7 -225
  178. package/dist/version.js +2 -7
  179. package/package.json +2 -2
  180. package/dist/chunk-E6TL6MIH.js +0 -203
@@ -1,2472 +1,50 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
-
33
- // tools/warp_grep/agent/config.ts
34
- var parseEnvTimeout, AGENT_CONFIG, BUILTIN_EXCLUDES, DEFAULT_EXCLUDES, DEFAULT_MODEL;
35
- var init_config = __esm({
36
- "tools/warp_grep/agent/config.ts"() {
37
- "use strict";
38
- parseEnvTimeout = (envValue, defaultMs) => {
39
- if (!envValue) return defaultMs;
40
- const parsed = parseInt(envValue, 10);
41
- return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;
42
- };
43
- AGENT_CONFIG = {
44
- MAX_TURNS: 6,
45
- /** Default timeout for model calls. Can be overridden via MORPH_WARP_GREP_TIMEOUT env var (in ms) */
46
- TIMEOUT_MS: parseEnvTimeout(process.env.MORPH_WARP_GREP_TIMEOUT, 6e4),
47
- MAX_CONTEXT_CHARS: 321600,
48
- MAX_OUTPUT_LINES: 200,
49
- MAX_LIST_RESULTS: 500,
50
- MAX_READ_LINES: 800,
51
- MAX_LIST_DEPTH: 3,
52
- LIST_TIMEOUT_MS: 2e3
53
- };
54
- BUILTIN_EXCLUDES = [
55
- // Version control
56
- ".git",
57
- ".svn",
58
- ".hg",
59
- ".bzr",
60
- // Dependencies
61
- "node_modules",
62
- "bower_components",
63
- ".pnpm",
64
- ".yarn",
65
- "vendor",
66
- "packages",
67
- "Pods",
68
- ".bundle",
69
- // Python
70
- "__pycache__",
71
- ".pytest_cache",
72
- ".mypy_cache",
73
- ".ruff_cache",
74
- ".venv",
75
- "venv",
76
- ".tox",
77
- ".nox",
78
- ".eggs",
79
- "*.egg-info",
80
- // Build outputs
81
- "dist",
82
- "build",
83
- "out",
84
- "output",
85
- "target",
86
- "_build",
87
- ".next",
88
- ".nuxt",
89
- ".output",
90
- ".vercel",
91
- ".netlify",
92
- // Cache directories
93
- ".cache",
94
- ".parcel-cache",
95
- ".turbo",
96
- ".nx",
97
- ".gradle",
98
- // IDE/Editor
99
- ".idea",
100
- ".vscode",
101
- ".vs",
102
- // Coverage
103
- "coverage",
104
- ".coverage",
105
- "htmlcov",
106
- ".nyc_output",
107
- // Temporary
108
- "tmp",
109
- "temp",
110
- ".tmp",
111
- ".temp",
112
- // Lock files
113
- "package-lock.json",
114
- "yarn.lock",
115
- "pnpm-lock.yaml",
116
- "bun.lockb",
117
- "Cargo.lock",
118
- "Gemfile.lock",
119
- "poetry.lock",
120
- // Binary/minified
121
- "*.min.js",
122
- "*.min.css",
123
- "*.bundle.js",
124
- "*.wasm",
125
- "*.so",
126
- "*.dll",
127
- "*.pyc",
128
- "*.map",
129
- "*.js.map",
130
- // Hidden directories catch-all
131
- ".*"
132
- ];
133
- 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";
135
- }
136
- });
137
-
138
- // tools/warp_grep/utils/ripgrep.ts
139
- function spawnRg(rgBinary, args, opts) {
140
- return new Promise((resolve) => {
141
- const child = (0, import_child_process.spawn)(rgBinary, args, {
142
- cwd: opts?.cwd,
143
- env: { ...process.env, ...opts?.env || {} },
144
- stdio: ["ignore", "pipe", "pipe"]
145
- });
146
- let stdout = "";
147
- let stderr = "";
148
- child.stdout.on("data", (d) => stdout += d.toString());
149
- child.stderr.on("data", (d) => stderr += d.toString());
150
- child.on("close", (code) => {
151
- resolve({ stdout, stderr, exitCode: typeof code === "number" ? code : -1 });
152
- });
153
- child.on("error", () => {
154
- resolve({ stdout: "", stderr: "Failed to spawn ripgrep.", exitCode: -1 });
155
- });
156
- });
157
- }
158
- async function preferredRgPath() {
159
- try {
160
- return (await import("@vscode/ripgrep")).rgPath ?? "rg";
161
- } catch {
162
- return "rg";
163
- }
164
- }
165
- function isBinaryFailure(result) {
166
- if (result.exitCode === -1) return true;
167
- if (result.stderr.includes("jemalloc") || result.stderr.includes("Unsupported system page size")) return true;
168
- if (result.exitCode === 134) return true;
169
- return false;
170
- }
171
- async function runRipgrep(args, opts) {
172
- if (rgPathChecked && resolvedRgPath) {
173
- return spawnRg(resolvedRgPath, args, opts);
174
- }
175
- if (!rgPathChecked) {
176
- const rgPath = await preferredRgPath();
177
- const result = await spawnRg(rgPath, args, opts);
178
- if (!isBinaryFailure(result)) {
179
- resolvedRgPath = rgPath;
180
- rgPathChecked = true;
181
- return result;
182
- }
183
- const fallbackResult = await spawnRg("rg", args, opts);
184
- if (!isBinaryFailure(fallbackResult)) {
185
- resolvedRgPath = "rg";
186
- rgPathChecked = true;
187
- return fallbackResult;
188
- }
189
- rgPathChecked = true;
190
- return {
191
- stdout: "",
192
- stderr: "Failed to spawn ripgrep. Neither bundled nor system rg is available.",
193
- exitCode: -1
194
- };
195
- }
196
- return {
197
- stdout: "",
198
- stderr: "Failed to spawn ripgrep. Neither bundled nor system rg is available.",
199
- exitCode: -1
200
- };
201
- }
202
- var import_child_process, resolvedRgPath, rgPathChecked;
203
- var init_ripgrep = __esm({
204
- "tools/warp_grep/utils/ripgrep.ts"() {
205
- "use strict";
206
- import_child_process = require("child_process");
207
- resolvedRgPath = null;
208
- rgPathChecked = false;
209
- }
210
- });
211
-
212
- // tools/warp_grep/utils/paths.ts
213
- function resolveUnderRepo(repoRoot, targetPath) {
214
- const absRoot = import_path4.default.resolve(repoRoot);
215
- const resolved = import_path4.default.resolve(absRoot, targetPath);
216
- ensureWithinRepo(absRoot, resolved);
217
- return resolved;
218
- }
219
- function ensureWithinRepo(repoRoot, absTarget) {
220
- const rel = import_path4.default.relative(import_path4.default.resolve(repoRoot), import_path4.default.resolve(absTarget));
221
- if (rel.startsWith("..") || import_path4.default.isAbsolute(rel)) {
222
- throw new Error(`Path outside repository root: ${absTarget}`);
223
- }
224
- }
225
- function toRepoRelative2(repoRoot, absPath) {
226
- return import_path4.default.relative(import_path4.default.resolve(repoRoot), import_path4.default.resolve(absPath));
227
- }
228
- function isSymlink(p) {
229
- try {
230
- const st = import_fs.default.lstatSync(p);
231
- return st.isSymbolicLink();
232
- } catch {
233
- return false;
234
- }
235
- }
236
- function fixPathRepetition(fullPath) {
237
- const segments = fullPath.split(import_path4.default.sep).filter(Boolean);
238
- if (segments.length < 2) return null;
239
- for (let len = Math.floor(segments.length / 2); len >= 1; len--) {
240
- for (let i = 0; i <= segments.length - 2 * len; i++) {
241
- const first = segments.slice(i, i + len);
242
- const second = segments.slice(i + len, i + 2 * len);
243
- if (first.every((seg, idx) => seg === second[idx])) {
244
- const fixed = [...segments.slice(0, i), ...segments.slice(i + len)];
245
- return import_path4.default.sep + fixed.join(import_path4.default.sep);
246
- }
247
- }
248
- }
249
- return null;
250
- }
251
- function isTextualFile(filePath, maxBytes = 2e6) {
252
- try {
253
- const st = import_fs.default.statSync(filePath);
254
- if (!st.isFile()) return false;
255
- if (st.size > maxBytes) return false;
256
- const fd = import_fs.default.openSync(filePath, "r");
257
- const buf = Buffer.alloc(512);
258
- const read = import_fs.default.readSync(fd, buf, 0, buf.length, 0);
259
- import_fs.default.closeSync(fd);
260
- for (let i = 0; i < read; i++) {
261
- const c = buf[i];
262
- if (c === 0) return false;
263
- }
264
- return true;
265
- } catch {
266
- return false;
267
- }
268
- }
269
- var import_fs, import_path4;
270
- var init_paths = __esm({
271
- "tools/warp_grep/utils/paths.ts"() {
272
- "use strict";
273
- import_fs = __toESM(require("fs"), 1);
274
- import_path4 = __toESM(require("path"), 1);
275
- }
276
- });
277
-
278
- // tools/warp_grep/utils/files.ts
279
- async function readAllLines(filePath) {
280
- const content = await import_promises.default.readFile(filePath, "utf8");
281
- return content.split(/\r?\n/);
282
- }
283
- var import_promises;
284
- var init_files = __esm({
285
- "tools/warp_grep/utils/files.ts"() {
286
- "use strict";
287
- import_promises = __toESM(require("fs/promises"), 1);
288
- }
289
- });
290
-
291
- // tools/warp_grep/providers/local.ts
292
- var local_exports = {};
293
- __export(local_exports, {
294
- LocalRipgrepProvider: () => LocalRipgrepProvider
295
- });
296
- function shouldSkip2(name, allowNames) {
297
- if (allowNames?.has(name)) return false;
298
- if (SKIP_NAMES2.has(name)) return true;
299
- if (name.startsWith(".")) return true;
300
- for (const ext of SKIP_EXTENSIONS2) {
301
- if (name.endsWith(ext)) return true;
302
- }
303
- return false;
304
- }
305
- var import_promises2, import_path5, SKIP_NAMES2, SKIP_EXTENSIONS2, LocalRipgrepProvider;
306
- var init_local = __esm({
307
- "tools/warp_grep/providers/local.ts"() {
308
- "use strict";
309
- import_promises2 = __toESM(require("fs/promises"), 1);
310
- import_path5 = __toESM(require("path"), 1);
311
- init_ripgrep();
312
- init_paths();
313
- init_files();
314
- init_config();
315
- SKIP_NAMES2 = /* @__PURE__ */ new Set([
316
- // Version control
317
- ".git",
318
- ".svn",
319
- ".hg",
320
- ".bzr",
321
- // Dependencies
322
- "node_modules",
323
- "bower_components",
324
- ".pnpm",
325
- ".yarn",
326
- "vendor",
327
- "Pods",
328
- ".bundle",
329
- // Python
330
- "__pycache__",
331
- ".pytest_cache",
332
- ".mypy_cache",
333
- ".ruff_cache",
334
- ".venv",
335
- "venv",
336
- ".tox",
337
- ".nox",
338
- ".eggs",
339
- // Build outputs
340
- "dist",
341
- "build",
342
- "out",
343
- "output",
344
- "target",
345
- "_build",
346
- ".next",
347
- ".nuxt",
348
- ".output",
349
- ".vercel",
350
- ".netlify",
351
- // Cache
352
- ".cache",
353
- ".parcel-cache",
354
- ".turbo",
355
- ".nx",
356
- ".gradle",
357
- // IDE
358
- ".idea",
359
- ".vscode",
360
- ".vs",
361
- // Coverage
362
- "coverage",
363
- ".coverage",
364
- "htmlcov",
365
- ".nyc_output",
366
- // Temp
367
- "tmp",
368
- "temp",
369
- ".tmp",
370
- ".temp",
371
- // Lock files
372
- "package-lock.json",
373
- "yarn.lock",
374
- "pnpm-lock.yaml",
375
- "bun.lockb",
376
- "Cargo.lock",
377
- "Gemfile.lock",
378
- "poetry.lock"
379
- ]);
380
- SKIP_EXTENSIONS2 = /* @__PURE__ */ new Set([
381
- ".min.js",
382
- ".min.css",
383
- ".bundle.js",
384
- ".wasm",
385
- ".so",
386
- ".dll",
387
- ".pyc",
388
- ".map",
389
- ".js.map"
390
- ]);
391
- LocalRipgrepProvider = class {
392
- constructor(repoRoot, excludes = DEFAULT_EXCLUDES, options) {
393
- this.repoRoot = repoRoot;
394
- this.excludes = excludes;
395
- if (options?.allowNames?.length) {
396
- this.allowNames = new Set(options.allowNames);
397
- }
398
- }
399
- allowNames;
400
- async grep(params) {
401
- let abs;
402
- try {
403
- abs = resolveUnderRepo(this.repoRoot, params.path);
404
- } catch (err) {
405
- return {
406
- lines: [],
407
- error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`
408
- };
409
- }
410
- const stat = await import_promises2.default.stat(abs).catch(() => null);
411
- if (!stat) return { lines: [] };
412
- const targetArg = abs === import_path5.default.resolve(this.repoRoot) ? "." : toRepoRelative2(this.repoRoot, abs);
413
- const contextLines = params.context_lines !== void 0 ? String(params.context_lines) : "1";
414
- const args = [
415
- "--no-config",
416
- "--no-heading",
417
- "--with-filename",
418
- "--line-number",
419
- "--color=never",
420
- "--trim",
421
- "--max-columns=400",
422
- "-C",
423
- contextLines,
424
- ...params.case_sensitive === false ? ["--ignore-case"] : [],
425
- ...params.glob ? ["--glob", params.glob] : [],
426
- ...this.excludes.filter((e) => !this.allowNames?.has(e)).flatMap((e) => ["-g", `!${e}`]),
427
- params.pattern,
428
- targetArg || "."
429
- ];
430
- const res = await runRipgrep(args, { cwd: this.repoRoot });
431
- if (res.exitCode === -1) {
432
- return {
433
- lines: [],
434
- error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required but failed to execute. Please install it:
435
- \u2022 macOS: brew install ripgrep
436
- \u2022 Ubuntu/Debian: apt install ripgrep
437
- \u2022 Windows: choco install ripgrep
438
- \u2022 Or visit: https://github.com/BurntSushi/ripgrep#installation
439
- Exit code: ${res.exitCode}${res.stderr ? `
440
- Details: ${res.stderr}` : ""}`
441
- };
442
- }
443
- if (res.exitCode !== 0 && res.exitCode !== 1) {
444
- return {
445
- lines: [],
446
- error: `[RIPGREP ERROR] grep failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ""}`
447
- };
448
- }
449
- const lines = (res.stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
450
- if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {
451
- const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);
452
- truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);
453
- return { lines: truncated };
454
- }
455
- return { lines };
456
- }
457
- async read(params) {
458
- let abs;
459
- try {
460
- abs = resolveUnderRepo(this.repoRoot, params.path);
461
- } catch (err) {
462
- return {
463
- lines: [],
464
- error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`
465
- };
466
- }
467
- let stat = await import_promises2.default.stat(abs).catch(() => null);
468
- if (!stat || !stat.isFile()) {
469
- const fixedPath = fixPathRepetition(abs);
470
- if (fixedPath) {
471
- const fixedStat = await import_promises2.default.stat(fixedPath).catch(() => null);
472
- if (fixedStat?.isFile()) {
473
- abs = fixedPath;
474
- stat = fixedStat;
475
- }
476
- }
477
- }
478
- if (!stat || !stat.isFile()) {
479
- return {
480
- lines: [],
481
- error: `[FILE NOT FOUND] You tried to read "${params.path}" but there is no file at this path. Double-check the path exists and is spelled correctly.`
482
- };
483
- }
484
- if (isSymlink(abs)) {
485
- return {
486
- lines: [],
487
- error: `[SYMLINK] You tried to read "${params.path}" but this is a symlink. Try reading the actual file it points to instead.`
488
- };
489
- }
490
- if (!isTextualFile(abs)) {
491
- return {
492
- lines: [],
493
- error: `[UNREADABLE FILE] You tried to read "${params.path}" but this file is either too large or not a text file, so it cannot be read. Try a different file.`
494
- };
495
- }
496
- let lines;
497
- try {
498
- lines = await readAllLines(abs);
499
- } catch (err) {
500
- return {
501
- lines: [],
502
- error: `[READ ERROR] Failed to read "${params.path}": ${err instanceof Error ? err.message : String(err)}`
503
- };
504
- }
505
- const total = lines.length;
506
- const rawStart = params.start;
507
- const rawEnd = params.end;
508
- let s = 1;
509
- let e = total;
510
- const startValid = rawStart === void 0 || Number.isFinite(rawStart) && rawStart > 0;
511
- const endValid = rawEnd === void 0 || Number.isFinite(rawEnd) && rawEnd > 0;
512
- if (startValid && endValid) {
513
- s = rawStart ?? 1;
514
- e = Math.min(rawEnd ?? total, total);
515
- if (s > total && total > 0 || s > e) {
516
- s = 1;
517
- e = total;
518
- }
519
- }
520
- const out = [];
521
- for (let i = s; i <= e; i += 1) {
522
- const content = lines[i - 1] ?? "";
523
- out.push(`${i}|${content}`);
524
- }
525
- if (out.length > AGENT_CONFIG.MAX_READ_LINES) {
526
- const truncated = out.slice(0, AGENT_CONFIG.MAX_READ_LINES);
527
- truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${out.length} lines)`);
528
- return { lines: truncated };
529
- }
530
- return { lines: out };
531
- }
532
- async listDirectory(params) {
533
- let abs;
534
- try {
535
- abs = resolveUnderRepo(this.repoRoot, params.path);
536
- } catch {
537
- return [];
538
- }
539
- const stat = await import_promises2.default.stat(abs).catch(() => null);
540
- if (!stat || !stat.isDirectory()) {
541
- return [];
542
- }
543
- const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
544
- const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
545
- const regex = params.pattern ? new RegExp(params.pattern) : null;
546
- const repoRoot = this.repoRoot;
547
- const allowNames = this.allowNames;
548
- const results = [];
549
- let timedOut = false;
550
- const startTime = Date.now();
551
- async function walk(dir, depth) {
552
- if (Date.now() - startTime > AGENT_CONFIG.LIST_TIMEOUT_MS) {
553
- timedOut = true;
554
- return;
555
- }
556
- if (depth > maxDepth || results.length >= maxResults) return;
557
- let entries;
558
- try {
559
- entries = await import_promises2.default.readdir(dir, { withFileTypes: true });
560
- } catch {
561
- return;
562
- }
563
- for (const entry of entries) {
564
- if (timedOut || results.length >= maxResults) break;
565
- if (shouldSkip2(entry.name, allowNames)) continue;
566
- if (regex && !regex.test(entry.name)) continue;
567
- const full = import_path5.default.join(dir, entry.name);
568
- const isDir = entry.isDirectory();
569
- results.push({
570
- name: entry.name,
571
- path: toRepoRelative2(repoRoot, full),
572
- type: isDir ? "dir" : "file",
573
- depth
574
- });
575
- if (isDir) {
576
- await walk(full, depth + 1);
577
- }
578
- }
579
- }
580
- await walk(abs, 0);
581
- return results;
582
- }
583
- async glob(params) {
584
- let abs;
585
- try {
586
- abs = params.path ? resolveUnderRepo(this.repoRoot, params.path) : this.repoRoot;
587
- } catch (err) {
588
- return { files: [], searchDir: this.repoRoot, totalFound: 0, error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}` };
589
- }
590
- const stat = await import_promises2.default.stat(abs).catch(() => null);
591
- if (!stat || !stat.isDirectory()) {
592
- return { files: [], searchDir: abs, totalFound: 0, error: `[PATH ERROR] Directory not found: ${params.path || "."}` };
593
- }
594
- const targetArg = abs === import_path5.default.resolve(this.repoRoot) ? "." : toRepoRelative2(this.repoRoot, abs);
595
- const args = [
596
- "--no-config",
597
- "--files",
598
- "--color=never",
599
- "-g",
600
- params.pattern,
601
- ...this.excludes.filter((e) => !this.allowNames?.has(e)).flatMap((e) => ["-g", `!${e}`]),
602
- targetArg || "."
603
- ];
604
- const res = await runRipgrep(args, { cwd: this.repoRoot });
605
- if (res.exitCode === -1) {
606
- return { files: [], searchDir: abs, totalFound: 0, error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required for glob search.` };
607
- }
608
- if (res.exitCode !== 0 && res.exitCode !== 1) {
609
- return { files: [], searchDir: abs, totalFound: 0, error: `[GLOB ERROR] glob failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ""}` };
610
- }
611
- const absRoot = import_path5.default.resolve(this.repoRoot);
612
- const relFiles = (res.stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
613
- const absFiles = relFiles.map((f) => import_path5.default.resolve(absRoot, f));
614
- const withMtime = [];
615
- for (const f of absFiles) {
616
- const s = await import_promises2.default.stat(f).catch(() => null);
617
- withMtime.push({ file: f, mtime: s?.mtimeMs ?? 0 });
618
- }
619
- withMtime.sort((a, b) => b.mtime - a.mtime);
620
- const totalFound = withMtime.length;
621
- return { files: withMtime.slice(0, 100).map((f) => f.file), searchDir: abs, totalFound };
622
- }
623
- };
624
- }
625
- });
626
-
627
- // tools/warp_grep/client.ts
628
- var client_exports = {};
629
- __export(client_exports, {
630
- WarpGrepClient: () => WarpGrepClient,
631
- executeGitHubReadFile: () => executeGitHubReadFile,
632
- executeToolCall: () => executeToolCall,
633
- executeToolCallStreaming: () => executeToolCallStreaming,
634
- executeWarpGrep: () => executeWarpGrep,
635
- formatGitHubReadFileResult: () => formatGitHubReadFileResult,
636
- formatResult: () => formatResult
637
- });
638
- module.exports = __toCommonJS(client_exports);
639
-
640
- // tools/warp_grep/agent/runner.ts
641
- init_config();
642
-
643
- // tools/warp_grep/agent/parser.ts
644
- function parseReadLines(linesStr) {
645
- const ranges = [];
646
- for (const rangeStr of linesStr.split(",")) {
647
- const trimmed = rangeStr.trim();
648
- if (!trimmed) continue;
649
- const parts = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
650
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
651
- ranges.push([parts[0], parts[1]]);
652
- } else if (Number.isFinite(parts[0])) {
653
- ranges.push([parts[0], parts[0]]);
654
- }
655
- }
656
- if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };
657
- if (ranges.length > 1) return { lines: ranges };
658
- return {};
659
- }
660
- function parseFinishFiles(filesStr) {
661
- const files = [];
662
- for (const line of filesStr.trim().split(/\s+/)) {
663
- const trimmed = line.trim();
664
- if (!trimmed) continue;
665
- const searchFrom = /^[A-Za-z]:/.test(trimmed) ? 2 : 0;
666
- const colonIdx = trimmed.indexOf(":", searchFrom);
667
- if (colonIdx === -1) {
668
- files.push({ path: trimmed, lines: "*" });
669
- continue;
670
- }
671
- const filePath = trimmed.slice(0, colonIdx);
672
- const rangesPart = trimmed.slice(colonIdx + 1);
673
- if (!rangesPart.trim() || rangesPart.trim() === "*") {
674
- files.push({ path: filePath, lines: "*" });
675
- continue;
676
- }
677
- const ranges = [];
678
- for (const rangeStr of rangesPart.split(",")) {
679
- const rt = rangeStr.trim();
680
- if (!rt) continue;
681
- const parts = rt.split("-").map((v) => parseInt(v.trim(), 10));
682
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
683
- ranges.push([parts[0], parts[1]]);
684
- } else if (Number.isFinite(parts[0])) {
685
- ranges.push([parts[0], parts[0]]);
686
- }
687
- }
688
- files.push({ path: filePath, lines: ranges.length > 0 ? ranges : "*" });
689
- }
690
- return files;
691
- }
692
- function extractPathFromCommand(command) {
693
- const tokens = command.trim().split(/\s+/);
694
- const pathTokens = tokens.slice(1).filter((t) => !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("\\("));
695
- return pathTokens[0] || ".";
696
- }
697
-
698
- // tools/warp_grep/agent/tools/grep.ts
699
- async function toolGrep(provider, args) {
700
- const res = await provider.grep(args);
701
- if (res.error) {
702
- return { output: res.error };
703
- }
704
- if (!res.lines.length) {
705
- return { output: "no matches" };
706
- }
707
- return { output: res.lines.join("\n") };
708
- }
709
-
710
- // tools/warp_grep/agent/tools/read.ts
711
- function isValidRange(start, end) {
712
- return typeof start === "number" && typeof end === "number" && Number.isFinite(start) && Number.isFinite(end) && start > 0 && end >= start;
713
- }
714
- async function toolRead(provider, args) {
715
- if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {
716
- const validRanges = [];
717
- for (const range of args.lines) {
718
- if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {
719
- validRanges.push([range[0], range[1]]);
720
- }
721
- }
722
- if (validRanges.length === 0) {
723
- const res2 = await provider.read({ path: args.path });
724
- if (res2.error) return res2.error;
725
- if (!res2.lines.length) return "(empty file)";
726
- return res2.lines.join("\n");
727
- }
728
- const chunks = [];
729
- for (const [start, end] of validRanges) {
730
- const res2 = await provider.read({ path: args.path, start, end });
731
- if (res2.error) return res2.error;
732
- chunks.push(res2.lines.join("\n"));
733
- }
734
- if (chunks.every((c) => c === "")) return "(empty file)";
735
- return chunks.join("\n...\n");
736
- }
737
- const res = await provider.read({ path: args.path, start: args.start, end: args.end });
738
- if (res.error) {
739
- return res.error;
740
- }
741
- if (!res.lines.length) return "(empty file)";
742
- return res.lines.join("\n");
743
- }
744
-
745
- // tools/warp_grep/agent/tools/list_directory.ts
746
- init_config();
747
- var import_path = __toESM(require("path"), 1);
748
- async function toolListDirectory(provider, args, repoRoot) {
749
- const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;
750
- const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
751
- const entries = await provider.listDirectory({
752
- path: args.path,
753
- pattern: args.pattern ?? null,
754
- maxResults,
755
- maxDepth
756
- });
757
- if (!entries.length) return "empty";
758
- if (repoRoot) {
759
- const absRoot = repoRoot;
760
- const lines = entries.map((e) => import_path.default.join(absRoot, e.path));
761
- return lines.join("\n");
762
- }
763
- return entries.map((e) => e.path).join("\n");
764
- }
765
-
766
- // tools/warp_grep/agent/tools/glob.ts
767
- async function toolGlob(provider, args) {
768
- const res = await provider.glob(args);
769
- if (res.error) {
770
- return res.error;
771
- }
772
- if (!res.files.length) {
773
- return "no matches";
774
- }
775
- const header = `Found ${res.totalFound} file(s) matching "${args.pattern}" within ${res.searchDir}, sorted by modification time (newest first):`;
776
- const body = res.files.join("\n");
777
- const truncated = res.totalFound > res.files.length ? `
778
- [${res.totalFound - res.files.length} files truncated]` : "";
779
- return `${header}
780
- ---
781
- ${body}
782
- ---${truncated}`;
783
- }
784
-
785
- // tools/warp_grep/agent/tools/finish.ts
786
- function isValidRange2(range) {
787
- return Array.isArray(range) && range.length >= 2 && typeof range[0] === "number" && typeof range[1] === "number" && Number.isFinite(range[0]) && Number.isFinite(range[1]) && range[0] > 0 && range[1] >= range[0];
788
- }
789
- function extractValidRanges(lines) {
790
- if (!Array.isArray(lines)) return null;
791
- const valid = [];
792
- for (const range of lines) {
793
- if (isValidRange2(range)) {
794
- valid.push([range[0], range[1]]);
795
- }
796
- }
797
- return valid.length > 0 ? valid : null;
798
- }
799
- async function readFinishFiles(repoRoot, files, reader) {
800
- const out = [];
801
- for (const f of files) {
802
- const validRanges = f.lines === "*" ? null : extractValidRanges(f.lines);
803
- if (f.lines === "*" || !validRanges) {
804
- const lines = await reader(f.path);
805
- out.push({ path: f.path, ranges: "*", content: lines.join("\n") });
806
- } else {
807
- const ranges = mergeRanges(validRanges);
808
- const chunks = [];
809
- for (let i = 0; i < ranges.length; i++) {
810
- const [s, e] = ranges[i];
811
- if (i === 0 && s > 1) {
812
- chunks.push(`// ... existing code, block starting at line ${s} ...`);
813
- } else if (i > 0) {
814
- chunks.push(`// ... existing code, block starting at line ${s} ...`);
815
- }
816
- const lines = await reader(f.path, s, e);
817
- chunks.push(lines.join("\n"));
818
- }
819
- out.push({ path: f.path, ranges, content: chunks.join("\n") });
820
- }
821
- }
822
- return out;
823
- }
824
- function mergeRanges(ranges) {
825
- if (!ranges.length) return [];
826
- const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
827
- const merged = [];
828
- let [cs, ce] = sorted[0];
829
- for (let i = 1; i < sorted.length; i++) {
830
- const [s, e] = sorted[i];
831
- if (s <= ce + 1) {
832
- ce = Math.max(ce, e);
833
- } else {
834
- merged.push([cs, ce]);
835
- cs = s;
836
- ce = e;
837
- }
838
- }
839
- merged.push([cs, ce]);
840
- return merged;
841
- }
842
-
843
- // tools/warp_grep/agent/helpers.ts
844
- var import_path2 = __toESM(require("path"), 1);
845
- init_config();
846
- var TRUNCATED_MARKER = "[truncated for context limit]";
847
- function getMessageSize(m) {
848
- if (m.role === "tool") return m.content.length;
849
- if (m.role === "assistant") {
850
- let size = typeof m.content === "string" ? m.content.length : 0;
851
- if (m.tool_calls) {
852
- size += m.tool_calls.reduce((s, tc) => s + tc.function.name.length + tc.function.arguments.length, 0);
853
- }
854
- return size;
855
- }
856
- return m.content.length;
857
- }
858
- function formatTurnMessage(turnsUsed, maxTurns) {
859
- const turnsRemaining = maxTurns - turnsUsed;
860
- if (turnsRemaining === 1) {
861
- return `
862
- You have used ${turnsUsed} turns, you only have 1 turn remaining. You have run out of turns to explore the code base and MUST call the finish tool now`;
863
- }
864
- return `
865
- You have used ${turnsUsed} turn${turnsUsed === 1 ? "" : "s"} and have ${turnsRemaining} remaining`;
866
- }
867
- function calculateContextBudget(messages) {
868
- const totalChars = messages.reduce((sum, m) => sum + getMessageSize(m), 0);
869
- const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;
870
- const percent = Math.floor(totalChars / maxChars * 100);
871
- const usedK = Math.floor(totalChars / 1e3);
872
- const maxK = Math.floor(maxChars / 1e3);
873
- return `<context_budget>${percent}% (${usedK}K/${maxK}K chars)</context_budget>`;
874
- }
875
- async function buildInitialState(repoRoot, searchTerm, provider, options) {
876
- const budget = calculateContextBudget([]);
877
- const turnTag = `You have used 0 turns and have ${AGENT_CONFIG.MAX_TURNS} remaining`;
878
- const treeDepth = options?.search_type === "node_modules" ? 1 : 2;
879
- const absRoot = repoRoot;
880
- try {
881
- const entries = await provider.listDirectory({
882
- path: ".",
883
- maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,
884
- maxDepth: treeDepth
885
- });
886
- const lines = [absRoot];
887
- for (const e of entries) {
888
- lines.push(import_path2.default.join(absRoot, e.path));
889
- }
890
- return `<repo_structure>
891
- ${lines.join("\n")}
892
- </repo_structure>
893
-
894
- <search_string>
895
- ${searchTerm}
896
- </search_string>
897
- ${budget}
898
- ${turnTag}`;
899
- } catch {
900
- return `<repo_structure>
901
- ${absRoot}
902
- </repo_structure>
903
-
904
- <search_string>
905
- ${searchTerm}
906
- </search_string>
907
- ${budget}
908
- ${turnTag}`;
909
- }
910
- }
911
- function enforceContextLimit(messages, maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS) {
912
- const getTotalChars = () => messages.reduce((sum, m) => sum + getMessageSize(m), 0);
913
- if (getTotalChars() <= maxChars) {
914
- return messages;
915
- }
916
- const truncatableIndices = [];
917
- let firstUserSkipped = false;
918
- for (let i = 0; i < messages.length; i++) {
919
- const m = messages[i];
920
- if (m.role === "tool") {
921
- truncatableIndices.push(i);
922
- } else if (m.role === "user") {
923
- if (!firstUserSkipped) {
924
- firstUserSkipped = true;
925
- continue;
926
- }
927
- truncatableIndices.push(i);
928
- }
929
- }
930
- for (const idx of truncatableIndices) {
931
- if (getTotalChars() <= maxChars) {
932
- break;
933
- }
934
- const m = messages[idx];
935
- if (m.role === "tool" && m.content !== TRUNCATED_MARKER) {
936
- messages[idx] = { role: "tool", tool_call_id: m.tool_call_id, content: TRUNCATED_MARKER };
937
- } else if (m.role === "user" && m.content !== TRUNCATED_MARKER) {
938
- messages[idx] = { role: "user", content: TRUNCATED_MARKER };
939
- }
940
- }
941
- return messages;
942
- }
943
-
944
- // tools/warp_grep/agent/runner.ts
945
- var import_openai = __toESM(require("openai"), 1);
946
-
947
- // package.json
948
- var package_default = {
949
- name: "@morphllm/morphsdk",
950
- version: "0.2.202",
951
- description: "TypeScript SDK and CLI for Morph Fast Apply integration",
952
- type: "module",
953
- main: "./dist/index.cjs",
954
- module: "./dist/index.js",
955
- types: "./dist/index.d.ts",
956
- exports: {
957
- ".": {
958
- types: "./dist/index.d.ts",
959
- import: "./dist/index.js",
960
- require: "./dist/index.cjs"
961
- },
962
- "./logger": {
963
- types: "./dist/logger.d.ts",
964
- import: "./dist/logger.js",
965
- require: "./dist/logger.cjs"
966
- },
967
- "./edge": {
968
- types: "./dist/edge.d.ts",
969
- import: "./dist/edge.js",
970
- require: "./dist/edge.cjs"
971
- },
972
- "./tools/warp-grep": {
973
- types: "./dist/tools/warp_grep/index.d.ts",
974
- import: "./dist/tools/warp_grep/index.js",
975
- require: "./dist/tools/warp_grep/index.cjs"
976
- },
977
- "./tools/warp-grep/openai": {
978
- types: "./dist/tools/warp_grep/openai.d.ts",
979
- import: "./dist/tools/warp_grep/openai.js",
980
- require: "./dist/tools/warp_grep/openai.cjs"
981
- },
982
- "./tools/warp-grep/anthropic": {
983
- types: "./dist/tools/warp_grep/anthropic.d.ts",
984
- import: "./dist/tools/warp_grep/anthropic.js",
985
- require: "./dist/tools/warp_grep/anthropic.cjs"
986
- },
987
- "./tools/warp-grep/vercel": {
988
- types: "./dist/tools/warp_grep/vercel.d.ts",
989
- import: "./dist/tools/warp_grep/vercel.js",
990
- require: "./dist/tools/warp_grep/vercel.cjs"
991
- },
992
- "./tools/warp-grep/client": {
993
- types: "./dist/tools/warp_grep/client.d.ts",
994
- import: "./dist/tools/warp_grep/client.js",
995
- require: "./dist/tools/warp_grep/client.cjs"
996
- },
997
- "./tools/warp-grep/gemini": {
998
- types: "./dist/tools/warp_grep/gemini.d.ts",
999
- import: "./dist/tools/warp_grep/gemini.js",
1000
- require: "./dist/tools/warp_grep/gemini.cjs"
1001
- },
1002
- "./tools/warp-grep/harness": {
1003
- types: "./dist/tools/warp_grep/harness.d.ts",
1004
- import: "./dist/tools/warp_grep/harness.js",
1005
- require: "./dist/tools/warp_grep/harness.cjs"
1006
- },
1007
- "./tools/fastapply": {
1008
- types: "./dist/tools/fastapply/index.d.ts",
1009
- import: "./dist/tools/fastapply/index.js",
1010
- require: "./dist/tools/fastapply/index.cjs"
1011
- },
1012
- "./tools/fastapply/anthropic": {
1013
- types: "./dist/tools/fastapply/anthropic.d.ts",
1014
- import: "./dist/tools/fastapply/anthropic.js",
1015
- require: "./dist/tools/fastapply/anthropic.cjs"
1016
- },
1017
- "./tools/fastapply/openai": {
1018
- types: "./dist/tools/fastapply/openai.d.ts",
1019
- import: "./dist/tools/fastapply/openai.js",
1020
- require: "./dist/tools/fastapply/openai.cjs"
1021
- },
1022
- "./tools/fastapply/vercel": {
1023
- types: "./dist/tools/fastapply/vercel.d.ts",
1024
- import: "./dist/tools/fastapply/vercel.js",
1025
- require: "./dist/tools/fastapply/vercel.cjs"
1026
- },
1027
- "./modelrouter": {
1028
- types: "./dist/modelrouter/index.d.ts",
1029
- import: "./dist/modelrouter/index.js",
1030
- require: "./dist/modelrouter/index.cjs"
1031
- },
1032
- "./tools/compact": {
1033
- types: "./dist/tools/compact/index.d.ts",
1034
- import: "./dist/tools/compact/index.js",
1035
- require: "./dist/tools/compact/index.cjs"
1036
- },
1037
- "./subagents": {
1038
- types: "./dist/subagents/index.d.ts",
1039
- import: "./dist/subagents/index.js",
1040
- require: "./dist/subagents/index.cjs"
1041
- },
1042
- "./subagents/vercel": {
1043
- types: "./dist/subagents/vercel.d.ts",
1044
- import: "./dist/subagents/vercel.js",
1045
- require: "./dist/subagents/vercel.cjs"
1046
- },
1047
- "./subagents/anthropic": {
1048
- types: "./dist/subagents/anthropic.d.ts",
1049
- import: "./dist/subagents/anthropic.js",
1050
- require: "./dist/subagents/anthropic.cjs"
1051
- },
1052
- "./ai-sdk": {
1053
- types: "./dist/ai-sdk/index.d.ts",
1054
- import: "./dist/ai-sdk/index.js",
1055
- require: "./dist/ai-sdk/index.cjs"
1056
- }
1057
- },
1058
- files: [
1059
- "dist/**/*.js",
1060
- "dist/**/*.cjs",
1061
- "dist/**/*.d.ts",
1062
- "!dist/**/__tests__/**",
1063
- "!dist/**/*.test.*"
1064
- ],
1065
- scripts: {
1066
- build: "tsup version.ts index.ts edge.ts client.ts core/index.ts core/client.ts core/resource.ts core/error.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts --format esm,cjs --clean --dts --dts-resolve && tsup ai-sdk/index.ts --format esm,cjs --dts --no-clean --out-dir dist/ai-sdk",
1067
- prepare: "npm run build",
1068
- typecheck: "tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json",
1069
- lint: "eslint .",
1070
- test: "vitest run",
1071
- "test:watch": "vitest watch",
1072
- "test:anthropic": "vitest run anthropic",
1073
- "test:openai": "vitest run openai",
1074
- "test:vercel": "vitest run vercel",
1075
- "test:git": "vitest run git",
1076
- "test:agent": "npx tsx tests/fullAgentTest.ts",
1077
- "test:integration": "npx tsx tests/fullIntegrationTest.ts",
1078
- "test:e2e": "vitest run --config vitest.e2e.config.ts",
1079
- "release:patch": "npm version patch && npm publish",
1080
- "release:minor": "npm version minor && npm publish",
1081
- "release:major": "npm version major && npm publish"
1082
- },
1083
- keywords: [
1084
- "morph",
1085
- "fast-apply",
1086
- "cli",
1087
- "sdk",
1088
- "edit-file"
1089
- ],
1090
- engines: {
1091
- node: ">=18"
1092
- },
1093
- license: "MIT",
1094
- dependencies: {
1095
- "@vscode/ripgrep": "^1.17.0",
1096
- ai: ">=5.0.0",
1097
- diff: "^7.0.0",
1098
- openai: "^4.52.7",
1099
- zod: ">=3.23.0"
1100
- },
1101
- devDependencies: {
1102
- "@ai-sdk/anthropic": "^2.0.70",
1103
- "@ai-sdk/openai": "^2.0.35",
1104
- "@anthropic-ai/sdk": "^0.30.1",
1105
- "@google/generative-ai": "^0.24.1",
1106
- "@types/diff": "^7.0.2",
1107
- "@types/node": "^20.14.10",
1108
- "@typescript-eslint/eslint-plugin": "^7.18.0",
1109
- "@typescript-eslint/parser": "^7.18.0",
1110
- dotenv: "^16.4.5",
1111
- eslint: "^8.57.0",
1112
- shx: "^0.3.4",
1113
- tsup: "^8.5.0",
1114
- tsx: "^4.16.2",
1115
- typescript: "^5.5.4",
1116
- vitest: "^2.1.6"
1117
- },
1118
- peerDependencies: {
1119
- "@ai-sdk/openai-compatible": ">=2.0.74 <4",
1120
- "@anthropic-ai/sdk": ">=0.25.0",
1121
- "@google/generative-ai": ">=0.21.0",
1122
- ai: ">=5.0.0",
1123
- zod: ">=3.23.0"
1124
- },
1125
- peerDependenciesMeta: {
1126
- "@anthropic-ai/sdk": {
1127
- optional: true
1128
- },
1129
- "@google/generative-ai": {
1130
- optional: true
1131
- },
1132
- ai: {
1133
- optional: true
1134
- },
1135
- zod: {
1136
- optional: true
1137
- }
1138
- },
1139
- publishConfig: {
1140
- access: "public"
1141
- }
1142
- };
1143
-
1144
- // version.ts
1145
- var SDK_VERSION = package_default.version;
1146
-
1147
- // tools/warp_grep/agent/runner.ts
1148
- var import_path3 = __toESM(require("path"), 1);
1149
-
1150
- // logger.ts
1151
- var MorphLogger = class {
1152
- enabled;
1153
- fileStream;
1154
- /** Resolves once the file stream is initialized (or immediately if no file logging). */
1155
- ready;
1156
- constructor() {
1157
- this.enabled = typeof process !== "undefined" && (process.env.MORPH_DEBUG === "1" || !!process.env.MORPH_LOG_FILE);
1158
- this.fileStream = null;
1159
- const f = typeof process !== "undefined" ? process.env.MORPH_LOG_FILE : void 0;
1160
- if (f) {
1161
- this.ready = import("fs").then((fs4) => {
1162
- this.fileStream = fs4.createWriteStream(f, { flags: "a" });
1163
- }).catch(() => {
1164
- });
1165
- } else {
1166
- this.ready = Promise.resolve();
1167
- }
1168
- }
1169
- debug(component, msg, data) {
1170
- this._log("debug", component, msg, data);
1171
- }
1172
- info(component, msg, data) {
1173
- this._log("info", component, msg, data);
1174
- }
1175
- warn(component, msg, data) {
1176
- this._log("warn", component, msg, data);
1177
- }
1178
- error(component, msg, data) {
1179
- this._log("error", component, msg, data);
1180
- }
1181
- enable() {
1182
- this.enabled = true;
1183
- }
1184
- get isEnabled() {
1185
- return this.enabled;
1186
- }
1187
- _log(level, component, msg, data) {
1188
- if (level !== "error" && !this.enabled) return;
1189
- const ts = (/* @__PURE__ */ new Date()).toISOString();
1190
- const prefix = `[${ts}] [${level.toUpperCase()}] [${component}]`;
1191
- console.error(data ? `${prefix} ${msg} ${JSON.stringify(data)}` : `${prefix} ${msg}`);
1192
- this.fileStream?.write(JSON.stringify({ ts, level, component, msg, ...data && { data } }) + "\n");
1193
- }
1194
- };
1195
- var logger = new MorphLogger();
1196
-
1197
- // tools/warp_grep/agent/runner.ts
1198
- var DEFAULT_API_URL = "https://api.morphllm.com";
1199
- var TOOL_SPECS = [
1200
- {
1201
- type: "function",
1202
- function: {
1203
- name: "list_directory",
1204
- description: "Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.",
1205
- parameters: {
1206
- type: "object",
1207
- properties: {
1208
- command: {
1209
- type: "string",
1210
- description: "Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */)."
1211
- }
1212
- },
1213
- required: ["command"]
1214
- }
1215
- }
1216
- },
1217
- {
1218
- type: "function",
1219
- function: {
1220
- name: "grep_search",
1221
- description: "Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.",
1222
- parameters: {
1223
- type: "object",
1224
- properties: {
1225
- pattern: {
1226
- type: "string",
1227
- description: "Regex pattern to search for in file contents (e.g. 'class\\s+\\w+Error', 'import|require|from', 'def (get|set|update)_user')."
1228
- },
1229
- path: {
1230
- type: "string",
1231
- description: "File or directory to search in. Defaults to current working directory."
1232
- },
1233
- glob: {
1234
- type: "string",
1235
- description: "Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*')."
1236
- },
1237
- limit: {
1238
- type: "integer",
1239
- description: "Limit output to first N matching lines. Shows all matches if not specified."
1240
- }
1241
- },
1242
- required: ["pattern"]
1243
- }
1244
- }
1245
- },
1246
- {
1247
- type: "function",
1248
- function: {
1249
- name: "glob",
1250
- description: "Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.",
1251
- parameters: {
1252
- type: "object",
1253
- properties: {
1254
- pattern: {
1255
- type: "string",
1256
- description: "Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py')."
1257
- },
1258
- path: {
1259
- type: "string",
1260
- description: "Directory to search in. Defaults to repository root."
1261
- }
1262
- },
1263
- required: ["pattern"]
1264
- }
1265
- }
1266
- },
1267
- {
1268
- type: "function",
1269
- function: {
1270
- name: "read",
1271
- description: "Read entire files or specific line ranges using absolute paths.",
1272
- parameters: {
1273
- type: "object",
1274
- properties: {
1275
- path: {
1276
- type: "string",
1277
- description: "File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path)."
1278
- },
1279
- lines: {
1280
- type: "string",
1281
- description: "Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file."
1282
- }
1283
- },
1284
- required: ["path"]
1285
- }
1286
- }
1287
- },
1288
- {
1289
- type: "function",
1290
- function: {
1291
- name: "finish",
1292
- description: "Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.",
1293
- parameters: {
1294
- type: "object",
1295
- properties: {
1296
- files: {
1297
- type: "string",
1298
- 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."
1299
- }
1300
- },
1301
- required: ["files"]
1302
- }
1303
- }
1304
- }
1305
- ];
1306
- async function callModel(messages, model, options = {}) {
1307
- const baseUrl = options.morphApiUrl || DEFAULT_API_URL;
1308
- const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
1309
- const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
1310
- const parsedUrl = new URL(baseUrl);
1311
- const baseURL = parsedUrl.pathname === "/" ? `${baseUrl}/v1` : baseUrl;
1312
- const client = new import_openai.default({
1313
- apiKey,
1314
- baseURL,
1315
- maxRetries: 0,
1316
- timeout: timeoutMs,
1317
- defaultHeaders: { "X-Morph-SDK-Version": SDK_VERSION }
1318
- });
1319
- const MAX_EMPTY_RETRIES = 1;
1320
- logger.debug("WarpGrep", "model_call", { url: baseURL, model, message_count: messages.length });
1321
- const callStartTime = Date.now();
1322
- for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {
1323
- let data;
1324
- try {
1325
- data = await client.chat.completions.create({
1326
- model,
1327
- temperature: 0,
1328
- max_tokens: 2048,
1329
- messages,
1330
- tools: TOOL_SPECS,
1331
- ...options.search_type ? { search_type: options.search_type } : {}
1332
- });
1333
- } catch (error) {
1334
- const callLatencyMs = Date.now() - callStartTime;
1335
- if (error instanceof import_openai.default.APIError) {
1336
- logger.error("WarpGrep", "model_call_error", { status: error.status, error: error.message, latency_ms: callLatencyMs });
1337
- if (error.status === 404) {
1338
- const defaultMsg = "The endpoint you are trying to call is likely deprecated. Please update with: npm cache clean --force && npx -y @morphllm/morphmcp@latest or visit: https://morphllm.com/mcp";
1339
- const errorText = error.message?.trim();
1340
- throw new Error(errorText || defaultMsg);
1341
- }
1342
- } else {
1343
- logger.error("WarpGrep", "model_call_error", { status: void 0, error: error instanceof Error ? error.message : String(error), latency_ms: callLatencyMs });
1344
- }
1345
- throw error;
1346
- }
1347
- const choice = data?.choices?.[0];
1348
- const message = choice?.message;
1349
- if (!message) {
1350
- if (attempt === MAX_EMPTY_RETRIES) {
1351
- throw new Error("Invalid response from model: no message in response");
1352
- }
1353
- await new Promise((resolve) => setTimeout(resolve, 200));
1354
- continue;
1355
- }
1356
- const toolCalls = (message.tool_calls || []).map((tc) => ({
1357
- id: tc.id,
1358
- type: "function",
1359
- function: { name: tc.function.name, arguments: tc.function.arguments }
1360
- }));
1361
- if (message.content || toolCalls.length > 0) {
1362
- logger.debug("WarpGrep", "model_call_complete", { latency_ms: Date.now() - callStartTime, tool_calls_count: toolCalls.length, finish_reason: choice?.finish_reason ?? "unknown" });
1363
- return { content: message.content ?? null, tool_calls: toolCalls };
1364
- }
1365
- if (attempt === MAX_EMPTY_RETRIES) {
1366
- const finishReason = choice?.finish_reason ?? "unknown";
1367
- throw new Error(
1368
- `Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`
1369
- );
1370
- }
1371
- await new Promise((resolve) => setTimeout(resolve, 200));
1372
- }
1373
- throw new Error("Invalid response from model");
1374
- }
1375
- function safeParseJSON(s) {
1376
- try {
1377
- return JSON.parse(s);
1378
- } catch {
1379
- return {};
1380
- }
1381
- }
1382
- async function executeTool(provider, name, args, repoRoot) {
1383
- switch (name) {
1384
- case "grep_search": {
1385
- const grepArgs = {
1386
- pattern: args.pattern,
1387
- path: args.path || "."
1388
- };
1389
- if (args.glob) grepArgs.glob = args.glob;
1390
- if (args.case_sensitive !== void 0) grepArgs.case_sensitive = args.case_sensitive;
1391
- const result = await toolGrep(provider, grepArgs);
1392
- let output = result.output;
1393
- if (args.limit && typeof args.limit === "number") {
1394
- const lines = output.split("\n");
1395
- if (lines.length > args.limit) {
1396
- output = lines.slice(0, args.limit).join("\n") + `
1397
- ... (truncated at ${args.limit} lines)`;
1398
- }
1399
- }
1400
- return output;
1401
- }
1402
- case "glob": {
1403
- return toolGlob(provider, {
1404
- pattern: args.pattern,
1405
- path: args.path
1406
- });
1407
- }
1408
- case "list_directory": {
1409
- const dirPath = extractPathFromCommand(args.command || ".");
1410
- return toolListDirectory(provider, { path: dirPath }, repoRoot);
1411
- }
1412
- case "read": {
1413
- const readArgs = {
1414
- path: args.path
1415
- };
1416
- if (args.lines && typeof args.lines === "string") {
1417
- Object.assign(readArgs, parseReadLines(args.lines));
1418
- }
1419
- return toolRead(provider, readArgs);
1420
- }
1421
- default:
1422
- return `Unknown tool: ${name}`;
1423
- }
1424
- }
1425
- async function* runWarpGrepStreaming(config) {
1426
- const totalStart = Date.now();
1427
- const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
1428
- const timings = { turns: [], timeout_ms: timeoutMs };
1429
- const repoRoot = config.repoRoot || process.cwd();
1430
- const model = config.model || DEFAULT_MODEL;
1431
- const messages = [];
1432
- const maxTurns = AGENT_CONFIG.MAX_TURNS;
1433
- logger.debug("WarpGrep", "session_start", { search_term: config.searchTerm, model, max_turns: maxTurns });
1434
- const initialStateStart = Date.now();
1435
- const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });
1436
- timings.initial_state_ms = Date.now() - initialStateStart;
1437
- logger.debug("WarpGrep", "initial_state", { system_prompt_len: initialState.length, user_message_len: initialState.length });
1438
- messages.push({ role: "user", content: initialState });
1439
- const provider = config.provider;
1440
- const errors = [];
1441
- let finishMeta;
1442
- let terminationReason = "terminated";
1443
- for (let turn = 1; turn <= maxTurns; turn += 1) {
1444
- const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
1445
- logger.debug("WarpGrep", "turn_start", { turn, message_count: messages.length });
1446
- const beforeChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
1447
- enforceContextLimit(messages);
1448
- const afterChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
1449
- if (afterChars < beforeChars) {
1450
- logger.debug("WarpGrep", "context_truncated", { before_chars: beforeChars, after_chars: afterChars });
1451
- }
1452
- const modelCallStart = Date.now();
1453
- const response = await callModel(messages, model, {
1454
- morphApiKey: config.morphApiKey,
1455
- morphApiUrl: config.morphApiUrl,
1456
- retryConfig: config.retryConfig,
1457
- timeout: timeoutMs,
1458
- search_type: config.search_type
1459
- }).catch((e) => {
1460
- const errMsg = e instanceof Error ? e.message : String(e);
1461
- console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
1462
- logger.error("WarpGrep", "error", { turn, error: errMsg, phase: "model_call" });
1463
- errors.push({ message: errMsg });
1464
- return null;
1465
- });
1466
- turnMetrics.morph_api_ms = Date.now() - modelCallStart;
1467
- if (!response) {
1468
- timings.turns.push(turnMetrics);
1469
- break;
1470
- }
1471
- const toolCalls = response.tool_calls;
1472
- logger.debug("WarpGrep", "model_response", { turn, tool_calls: toolCalls.map((tc) => tc.function.name), latency_ms: turnMetrics.morph_api_ms });
1473
- messages.push({
1474
- role: "assistant",
1475
- content: response.content,
1476
- ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
1477
- });
1478
- if (toolCalls.length === 0) {
1479
- console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || "").slice(0, 500)}`);
1480
- errors.push({ message: "No tool calls produced by the model." });
1481
- terminationReason = "terminated";
1482
- timings.turns.push(turnMetrics);
1483
- break;
1484
- }
1485
- yield {
1486
- turn,
1487
- toolCalls: toolCalls.map((tc) => ({
1488
- name: tc.function.name,
1489
- arguments: safeParseJSON(tc.function.arguments)
1490
- }))
1491
- };
1492
- const finishCall = toolCalls.find((tc) => tc.function.name === "finish");
1493
- if (finishCall) {
1494
- const args = safeParseJSON(finishCall.function.arguments);
1495
- const filesStr = args.files || "";
1496
- const files = parseFinishFiles(filesStr);
1497
- finishMeta = { files };
1498
- terminationReason = "completed";
1499
- logger.debug("WarpGrep", "finish", { turns: turn, files: files.map((f) => f.path) });
1500
- if (files.length === 0) {
1501
- const payload2 = filesStr || "No relevant code found.";
1502
- timings.turns.push(turnMetrics);
1503
- timings.total_ms = Date.now() - totalStart;
1504
- return {
1505
- terminationReason: "completed",
1506
- messages,
1507
- finish: { payload: payload2, metadata: finishMeta },
1508
- timings
1509
- };
1510
- }
1511
- timings.turns.push(turnMetrics);
1512
- break;
1513
- }
1514
- const toolExecStart = Date.now();
1515
- const results = await Promise.all(
1516
- toolCalls.map(async (tc) => {
1517
- const args = safeParseJSON(tc.function.arguments);
1518
- const argsSummary = Object.fromEntries(Object.entries(args).map(([k, v]) => [k, typeof v === "string" && v.length > 100 ? v.slice(0, 100) + "..." : v]));
1519
- logger.debug("WarpGrep", "tool_exec", { turn, tool: tc.function.name, args_summary: argsSummary });
1520
- const toolStart = Date.now();
1521
- const output = await executeTool(provider, tc.function.name, args, repoRoot).catch((err) => String(err));
1522
- logger.debug("WarpGrep", "tool_result", { turn, tool: tc.function.name, result_len: output.length, latency_ms: Date.now() - toolStart });
1523
- return { tool_call_id: tc.id, content: output };
1524
- })
1525
- );
1526
- turnMetrics.local_tools_ms = Date.now() - toolExecStart;
1527
- for (const result of results) {
1528
- messages.push({ role: "tool", tool_call_id: result.tool_call_id, content: result.content });
1529
- }
1530
- const turnMsg = formatTurnMessage(turn, maxTurns);
1531
- const budget = calculateContextBudget(messages);
1532
- messages.push({ role: "user", content: turnMsg + "\n" + budget });
1533
- timings.turns.push(turnMetrics);
1534
- }
1535
- if (terminationReason !== "completed" || !finishMeta) {
1536
- timings.total_ms = Date.now() - totalStart;
1537
- return { terminationReason, messages, errors, timings };
1538
- }
1539
- const parts = ["Relevant context found:"];
1540
- for (const f of finishMeta.files) {
1541
- const ranges = f.lines === "*" ? "*" : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(", ") : "*";
1542
- parts.push(`- ${f.path}: ${ranges}`);
1543
- }
1544
- const payload = parts.join("\n");
1545
- const finishResolutionStart = Date.now();
1546
- const fileReadErrors = [];
1547
- const resolved = await readFinishFiles(
1548
- repoRoot,
1549
- finishMeta.files,
1550
- async (p, s, e) => {
1551
- let resolvedPath = p;
1552
- if (!p.startsWith(repoRoot)) {
1553
- const relative = p.startsWith("/") ? p.slice(1) : p;
1554
- resolvedPath = import_path3.default.join(repoRoot, relative);
1555
- }
1556
- try {
1557
- const rr = await provider.read({ path: resolvedPath, start: s, end: e });
1558
- return rr.lines.map((l) => {
1559
- const idx = l.indexOf("|");
1560
- return idx >= 0 ? l.slice(idx + 1) : l;
1561
- });
1562
- } catch (err) {
1563
- const errorMsg = err instanceof Error ? err.message : String(err);
1564
- fileReadErrors.push({ path: resolvedPath, error: errorMsg });
1565
- console.error(`[warp_grep] Failed to read file: ${resolvedPath} - ${errorMsg}`);
1566
- return [`[couldn't find: ${resolvedPath}]`];
1567
- }
1568
- }
1569
- );
1570
- timings.finish_resolution_ms = Date.now() - finishResolutionStart;
1571
- if (fileReadErrors.length > 0) {
1572
- errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
1573
- }
1574
- timings.total_ms = Date.now() - totalStart;
1575
- return {
1576
- terminationReason: "completed",
1577
- messages,
1578
- finish: { payload, metadata: finishMeta, resolved },
1579
- timings
1580
- };
1581
- }
1582
- async function runWarpGrep(config) {
1583
- const gen = runWarpGrepStreaming(config);
1584
- let result = await gen.next();
1585
- while (!result.done) {
1586
- result = await gen.next();
1587
- }
1588
- return result.value;
1589
- }
1590
-
1591
- // tools/warp_grep/providers/remote.ts
1592
- init_config();
1593
- var SKIP_NAMES = /* @__PURE__ */ new Set([
1594
- // Version control
1595
- ".git",
1596
- ".svn",
1597
- ".hg",
1598
- ".bzr",
1599
- // Dependencies
1600
- "node_modules",
1601
- "bower_components",
1602
- ".pnpm",
1603
- ".yarn",
1604
- "vendor",
1605
- "Pods",
1606
- ".bundle",
1607
- // Python
1608
- "__pycache__",
1609
- ".pytest_cache",
1610
- ".mypy_cache",
1611
- ".ruff_cache",
1612
- ".venv",
1613
- "venv",
1614
- ".tox",
1615
- ".nox",
1616
- ".eggs",
1617
- // Build outputs
1618
- "dist",
1619
- "build",
1620
- "out",
1621
- "output",
1622
- "target",
1623
- "_build",
1624
- ".next",
1625
- ".nuxt",
1626
- ".output",
1627
- ".vercel",
1628
- ".netlify",
1629
- // Cache
1630
- ".cache",
1631
- ".parcel-cache",
1632
- ".turbo",
1633
- ".nx",
1634
- ".gradle",
1635
- // IDE
1636
- ".idea",
1637
- ".vscode",
1638
- ".vs",
1639
- // Coverage
1640
- "coverage",
1641
- ".coverage",
1642
- "htmlcov",
1643
- ".nyc_output",
1644
- // Temp
1645
- "tmp",
1646
- "temp",
1647
- ".tmp",
1648
- ".temp",
1649
- // Lock files
1650
- "package-lock.json",
1651
- "yarn.lock",
1652
- "pnpm-lock.yaml",
1653
- "bun.lockb",
1654
- "Cargo.lock",
1655
- "Gemfile.lock",
1656
- "poetry.lock"
1657
- ]);
1658
- var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
1659
- ".min.js",
1660
- ".min.css",
1661
- ".bundle.js",
1662
- ".wasm",
1663
- ".so",
1664
- ".dll",
1665
- ".pyc",
1666
- ".map",
1667
- ".js.map"
1668
- ]);
1669
- function shouldSkip(name) {
1670
- if (SKIP_NAMES.has(name)) return true;
1671
- if (name.startsWith(".")) return true;
1672
- for (const ext of SKIP_EXTENSIONS) {
1673
- if (name.endsWith(ext)) return true;
1674
- }
1675
- return false;
1676
- }
1677
- var RemoteCommandsProvider = class {
1678
- constructor(repoRoot, commands) {
1679
- this.repoRoot = repoRoot;
1680
- this.commands = commands;
1681
- }
1682
- /**
1683
- * Run grep command and parse ripgrep output
1684
- */
1685
- async grep(params) {
1686
- try {
1687
- const stdout = await this.commands.grep(params.pattern, params.path, params.glob);
1688
- const lines = (stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
1689
- if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {
1690
- const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);
1691
- truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);
1692
- return { lines: truncated };
1693
- }
1694
- return { lines };
1695
- } catch (error) {
1696
- return {
1697
- lines: [],
1698
- error: `[GREP ERROR] ${error instanceof Error ? error.message : String(error)}`
1699
- };
1700
- }
1701
- }
1702
- /**
1703
- * Read file and add line numbers
1704
- */
1705
- async read(params) {
1706
- const rawStart = params.start;
1707
- const rawEnd = params.end;
1708
- const startValid = rawStart === void 0 || Number.isFinite(rawStart) && rawStart > 0;
1709
- const endValid = rawEnd === void 0 || Number.isFinite(rawEnd) && rawEnd > 0;
1710
- const rangeValid = startValid && endValid && (rawStart === void 0 || rawEnd === void 0 || rawStart <= rawEnd);
1711
- const start = rangeValid && rawStart !== void 0 ? rawStart : 1;
1712
- const end = rangeValid && rawEnd !== void 0 ? rawEnd : 1e6;
1713
- try {
1714
- const stdout = await this.commands.read(params.path, start, end);
1715
- const contentLines = (stdout || "").split("\n");
1716
- if (contentLines.length > 0 && contentLines[contentLines.length - 1] === "") {
1717
- contentLines.pop();
1718
- }
1719
- const lines = contentLines.map((content, idx) => `${start + idx}|${content}`);
1720
- if (lines.length > AGENT_CONFIG.MAX_READ_LINES) {
1721
- const truncated = lines.slice(0, AGENT_CONFIG.MAX_READ_LINES);
1722
- truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${lines.length} lines)`);
1723
- return { lines: truncated };
1724
- }
1725
- return { lines };
1726
- } catch (error) {
1727
- return {
1728
- lines: [],
1729
- error: `[READ ERROR] ${error instanceof Error ? error.message : String(error)}`
1730
- };
1731
- }
1732
- }
1733
- /**
1734
- * List directory and parse find output
1735
- */
1736
- async listDirectory(params) {
1737
- const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
1738
- const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
1739
- try {
1740
- const stdout = await this.commands.listDir(params.path, maxDepth);
1741
- const paths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
1742
- const regex = params.pattern ? new RegExp(params.pattern) : null;
1743
- const entries = [];
1744
- for (const fullPath of paths) {
1745
- if (fullPath === params.path || fullPath === this.repoRoot) continue;
1746
- const name = fullPath.split("/").pop() || "";
1747
- if (shouldSkip(name)) continue;
1748
- if (regex && !regex.test(name)) continue;
1749
- let relativePath = fullPath;
1750
- if (fullPath.startsWith(this.repoRoot)) {
1751
- relativePath = fullPath.slice(this.repoRoot.length).replace(/^\//, "");
1752
- }
1753
- const depth = relativePath.split("/").filter(Boolean).length - 1;
1754
- const hasExtension = name.includes(".") && !name.startsWith(".");
1755
- const type = hasExtension ? "file" : "dir";
1756
- entries.push({
1757
- name,
1758
- path: relativePath,
1759
- type,
1760
- depth: Math.max(0, depth)
1761
- });
1762
- if (entries.length >= maxResults) break;
1763
- }
1764
- return entries;
1765
- } catch (error) {
1766
- return [];
1767
- }
1768
- }
1769
- /**
1770
- * Glob search - finds files matching a pattern.
1771
- * Falls back to a grep --files approach via the listDir command.
1772
- */
1773
- async glob(params) {
1774
- const searchPath = params.path || this.repoRoot;
1775
- try {
1776
- const stdout = await this.commands.listDir(searchPath, 10);
1777
- const allPaths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
1778
- const globToRegex = (glob) => {
1779
- const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
1780
- return new RegExp(escaped);
1781
- };
1782
- const regex = globToRegex(params.pattern);
1783
- const matched = allPaths.filter((p) => {
1784
- const name = p.split("/").pop() || "";
1785
- return regex.test(name) && !shouldSkip(name);
1786
- });
1787
- const totalFound = matched.length;
1788
- return { files: matched.slice(0, 100), searchDir: searchPath, totalFound };
1789
- } catch (error) {
1790
- return {
1791
- files: [],
1792
- searchDir: searchPath,
1793
- totalFound: 0,
1794
- error: `[GLOB ERROR] ${error instanceof Error ? error.message : String(error)}`
1795
- };
1796
- }
1797
- }
1798
- };
1799
-
1800
- // tools/warp_grep/providers/code_storage_http.ts
1801
- var MODEL_REPO_ROOT = /^\/?home\/ubuntu\/repo(?:\/|$)/;
1802
- function toRepoRelative(path6) {
1803
- if (!path6) return path6;
1804
- const stripped = path6.replace(MODEL_REPO_ROOT, "").replace(/^\.?\/+/, "");
1805
- return stripped || ".";
1806
- }
1807
- async function post(url, body, op, apiKey) {
1808
- const res = await fetch(url, {
1809
- method: "POST",
1810
- headers: {
1811
- "Content-Type": "application/json",
1812
- ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {}
1813
- },
1814
- body: JSON.stringify(body)
1815
- });
1816
- if (!res.ok) {
1817
- const text = await res.text().catch(() => res.statusText);
1818
- try {
1819
- const parsed = JSON.parse(text);
1820
- if (parsed.error) return `Error: ${parsed.error}`;
1821
- } catch {
1822
- }
1823
- return `Error: ${op} failed (${res.status}): ${text}`;
1824
- }
1825
- const data = await res.json();
1826
- if (data.error) throw new Error(data.error);
1827
- return data.stdout;
1828
- }
1829
- function createCodeStorageHttpCommands(config) {
1830
- const { baseUrl, repoId, branch, apiKey } = config;
1831
- const encodedRepoId = encodeURIComponent(repoId);
1832
- return {
1833
- grep: (pattern, path6, glob) => post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path: toRepoRelative(path6), glob, branch }, "grep", apiKey),
1834
- read: (path6, start, end) => post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path: toRepoRelative(path6), start, end, branch }, "read", apiKey),
1835
- listDir: (path6, maxDepth) => post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path: toRepoRelative(path6), maxDepth, branch }, "list", apiKey)
1836
- };
1837
- }
1838
-
1839
- // tools/warp_grep/utils/github.ts
1840
- function parseGitHubUrl(input) {
1841
- input = input.trim();
1842
- const urlPattern = /^(?:https?:\/\/)?github\.com\/([^\/]+)\/([^\/\?\#]+)/;
1843
- const match = input.match(urlPattern);
1844
- if (match) {
1845
- return { owner: match[1], repo: match[2].replace(/\.git$/, "") };
1846
- }
1847
- const shortPattern = /^([^\/]+)\/([^\/]+)$/;
1848
- const shortMatch = input.match(shortPattern);
1849
- if (shortMatch && !shortMatch[1].includes(".")) {
1850
- return { owner: shortMatch[1], repo: shortMatch[2].replace(/\.git$/, "") };
1851
- }
1852
- throw new Error(
1853
- `Invalid GitHub URL or shorthand: "${input}". Expected "owner/repo" or "https://github.com/owner/repo"`
1854
- );
1855
- }
1856
-
1857
- // tools/utils/resilience.ts
1858
- var DEFAULT_RETRY_CONFIG = {
1859
- maxRetries: 3,
1860
- initialDelay: 1e3,
1861
- maxDelay: 3e4,
1862
- backoffMultiplier: 2,
1863
- retryableErrors: ["ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND"]
1864
- };
1865
- async function fetchWithRetry(url, options, retryConfig = {}) {
1866
- const {
1867
- maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,
1868
- initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,
1869
- maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,
1870
- backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,
1871
- retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,
1872
- onRetry
1873
- } = retryConfig;
1874
- let lastError = null;
1875
- let delay = initialDelay;
1876
- options = { ...options, headers: { "X-Morph-SDK-Version": SDK_VERSION, ...options.headers } };
1877
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
1878
- try {
1879
- const response = await fetch(url, options);
1880
- if (response.status === 429 || response.status === 503) {
1881
- if (attempt < maxRetries) {
1882
- const retryAfter = response.headers.get("Retry-After");
1883
- const waitTime = retryAfter ? parseInt(retryAfter) * 1e3 : Math.min(delay, maxDelay);
1884
- const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);
1885
- if (onRetry) {
1886
- onRetry(attempt + 1, error);
1887
- }
1888
- await sleep(waitTime);
1889
- delay *= backoffMultiplier;
1890
- continue;
1891
- }
1892
- }
1893
- return response;
1894
- } catch (error) {
1895
- lastError = error;
1896
- const isRetryable = retryableErrors.some(
1897
- (errType) => lastError?.message?.includes(errType)
1898
- );
1899
- if (!isRetryable || attempt === maxRetries) {
1900
- throw lastError;
1901
- }
1902
- const waitTime = Math.min(delay, maxDelay);
1903
- if (onRetry) {
1904
- onRetry(attempt + 1, lastError);
1905
- }
1906
- await sleep(waitTime);
1907
- delay *= backoffMultiplier;
1908
- }
1909
- }
1910
- throw lastError || new Error("Max retries exceeded");
1911
- }
1912
- async function withTimeout(promise, timeoutMs, errorMessage) {
1913
- let timeoutId;
1914
- const timeoutPromise = new Promise((_, reject) => {
1915
- timeoutId = setTimeout(() => {
1916
- reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));
1917
- }, timeoutMs);
1918
- });
1919
- try {
1920
- const result = await Promise.race([promise, timeoutPromise]);
1921
- clearTimeout(timeoutId);
1922
- return result;
1923
- } catch (error) {
1924
- clearTimeout(timeoutId);
1925
- throw error;
1926
- }
1927
- }
1928
- function sleep(ms) {
1929
- return new Promise((resolve) => setTimeout(resolve, ms));
1930
- }
1931
- var MorphError = class extends Error {
1932
- constructor(message, code, statusCode, retryable = false) {
1933
- super(message);
1934
- this.code = code;
1935
- this.statusCode = statusCode;
1936
- this.retryable = retryable;
1937
- this.name = "MorphError";
1938
- }
1939
- };
1940
-
1941
- // core/error.ts
1942
- async function toMorphError(response) {
1943
- let message = `Morph API request failed (${response.status})`;
1944
- let code = "api_error";
1945
- try {
1946
- const body = await response.json();
1947
- message = body.error?.message ?? body.message ?? message;
1948
- code = body.error?.code ?? body.error?.type ?? code;
1949
- } catch {
1950
- }
1951
- if (response.status === 401) code = "authentication_error";
1952
- if (response.status === 429) code = "rate_limit_exceeded";
1953
- const retryable = response.status === 429 || response.status === 503;
1954
- return new MorphError(message, code, response.status, retryable);
1955
- }
1956
-
1957
- // core/client.ts
1958
- var DEFAULT_BASE_URL = "https://api.morphllm.com";
1959
- var DEFAULT_REPOS_URL = "https://repos.morphllm.com";
1960
- var DEFAULT_TIMEOUT = 6e4;
1961
- var env = (name) => typeof process !== "undefined" ? process.env?.[name] : void 0;
1962
- var stripTrailingSlash = (url) => url.replace(/\/+$/, "");
1963
- var MorphAPIClient = class {
1964
- /** Explicit key as provided; resolved against env at request time. */
1965
- apiKey;
1966
- baseURL;
1967
- reposURL;
1968
- /** Explicit default timeout (ms), if set. The request default is applied lazily so
1969
- * resources can read an undefined value and supply their own fallback. */
1970
- timeout;
1971
- retryConfig;
1972
- debug;
1973
- constructor(options = {}) {
1974
- this.apiKey = options.apiKey;
1975
- this.baseURL = stripTrailingSlash(options.baseURL ?? DEFAULT_BASE_URL);
1976
- this.reposURL = stripTrailingSlash(options.reposURL ?? env("MORPH_SEARCH_URL") ?? DEFAULT_REPOS_URL);
1977
- this.timeout = options.timeout;
1978
- this.retryConfig = options.retryConfig;
1979
- this.debug = options.debug ?? false;
1980
- if (this.debug) logger.enable();
1981
- }
1982
- /** The key actually used for requests: explicit, else `MORPH_API_KEY`. */
1983
- resolveApiKey() {
1984
- return this.apiKey ?? env("MORPH_API_KEY");
1985
- }
1986
- /** Headers shared with tools that bring their own HTTP client (FastApply/WarpGrep via the `openai` package). */
1987
- defaultHeaders() {
1988
- return { "X-Morph-SDK-Version": SDK_VERSION };
1989
- }
1990
- buildURL(path6, baseURL) {
1991
- if (/^https?:\/\//i.test(path6)) return path6;
1992
- const base = stripTrailingSlash(baseURL ?? this.baseURL);
1993
- return `${base}${path6.startsWith("/") ? "" : "/"}${path6}`;
1994
- }
1995
- buildHeaders(apiKey, extra) {
1996
- return {
1997
- "Content-Type": "application/json",
1998
- "X-Morph-SDK-Version": SDK_VERSION,
1999
- Authorization: `Bearer ${apiKey}`,
2000
- ...extra
2001
- };
2002
- }
2003
- applyQuery(url, query) {
2004
- if (!query) return url;
2005
- const params = new URLSearchParams();
2006
- for (const [key, value] of Object.entries(query)) {
2007
- if (value !== void 0 && value !== null) params.set(key, String(value));
2008
- }
2009
- const qs = params.toString();
2010
- return qs ? `${url}${url.includes("?") ? "&" : "?"}${qs}` : url;
2011
- }
2012
- async request(method, path6, opts = {}) {
2013
- const apiKey = this.resolveApiKey();
2014
- if (!apiKey) {
2015
- throw new MorphError(
2016
- "Morph API key not found. Set the MORPH_API_KEY environment variable or pass apiKey in config.",
2017
- "missing_api_key",
2018
- 401
2019
- );
2020
- }
2021
- const url = this.applyQuery(this.buildURL(path6, opts.baseURL), opts.query);
2022
- const timeout = opts.timeout ?? this.timeout ?? DEFAULT_TIMEOUT;
2023
- const init = {
2024
- method,
2025
- headers: this.buildHeaders(apiKey, opts.headers),
2026
- ...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
2027
- ...opts.signal ? { signal: opts.signal } : {}
2028
- };
2029
- logger.debug("MorphAPIClient", "request", { method, url });
2030
- const response = await withTimeout(
2031
- fetchWithRetry(url, init, this.retryConfig ?? {}),
2032
- timeout,
2033
- `Morph request to ${url} timed out after ${timeout}ms`
2034
- );
2035
- if (!response.ok) throw await toMorphError(response);
2036
- if (opts.stream) return response;
2037
- if (response.status === 204) return void 0;
2038
- const text = await response.text();
2039
- return text ? JSON.parse(text) : void 0;
2040
- }
2041
- get(path6, opts) {
2042
- return this.request("GET", path6, opts);
2043
- }
2044
- post(path6, opts) {
2045
- return this.request("POST", path6, opts);
2046
- }
2047
- delete(path6, opts) {
2048
- return this.request("DELETE", path6, opts);
2049
- }
2050
- };
2051
-
2052
- // core/resource.ts
2053
- var APIResource = class {
2054
- _client;
2055
- constructor(client) {
2056
- this._client = client;
2057
- }
2058
- };
2059
-
2060
- // tools/compact/core.ts
2061
- var DEFAULT_API_URL2 = "https://api.morphllm.com";
2062
- var DEFAULT_TIMEOUT2 = 12e4;
2063
- function resolveClient(clientOrConfig) {
2064
- if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
2065
- return new MorphAPIClient({
2066
- apiKey: clientOrConfig.morphApiKey,
2067
- baseURL: clientOrConfig.morphApiUrl ?? DEFAULT_API_URL2,
2068
- timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT2,
2069
- retryConfig: clientOrConfig.retryConfig,
2070
- debug: clientOrConfig.debug
2071
- });
2072
- }
2073
- var CompactClient = class extends APIResource {
2074
- /** Resolved URL/timeout, exposed for backwards-compatible introspection. */
2075
- config;
2076
- constructor(clientOrConfig = {}) {
2077
- super(resolveClient(clientOrConfig));
2078
- const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
2079
- this.config = {
2080
- morphApiUrl: this._client.baseURL,
2081
- timeout: cfg.timeout ?? DEFAULT_TIMEOUT2,
2082
- debug: cfg.debug ?? false
2083
- };
2084
- }
2085
- /**
2086
- * Compact messages or text via /v1/compact.
2087
- * Returns per-message `compacted_line_ranges` showing which lines were removed.
2088
- *
2089
- * @example
2090
- * ```typescript
2091
- * const client = new CompactClient({ morphApiKey: 'sk-...' });
2092
- * const result = await client.compact({
2093
- * input: codeFile,
2094
- * query: "authentication",
2095
- * compressionRatio: 0.5,
2096
- * });
2097
- * console.log(result.output);
2098
- * ```
2099
- */
2100
- async compact(input) {
2101
- const body = {
2102
- compression_ratio: input.compressionRatio ?? 0.5,
2103
- preserve_recent: input.preserveRecent ?? 2,
2104
- model: input.model ?? "morph-compactor",
2105
- include_line_ranges: input.includeLineRanges ?? true,
2106
- include_markers: input.includeMarkers ?? true
2107
- };
2108
- if (input.query !== void 0) body.query = input.query;
2109
- if (input.messages) body.messages = input.messages;
2110
- else if (typeof input.input === "string") body.input = input.input;
2111
- else if (Array.isArray(input.input)) body.messages = input.input;
2112
- else throw new Error("Either 'input' or 'messages' must be provided");
2113
- try {
2114
- return await this._client.post("/v1/compact", { body, timeout: this.config.timeout });
2115
- } catch (err) {
2116
- if (err instanceof MorphError) {
2117
- throw new Error(`Compact API error ${err.statusCode}: ${err.message}`);
2118
- }
2119
- throw err;
2120
- }
2121
- }
2122
- };
2123
-
2124
- // tools/compact/utils.ts
2125
- async function compactFileContexts(files, query, apiKey, apiUrl, maxTokens = 1e4, maxConcurrency = 3) {
2126
- const totalLength = files.reduce((sum, file) => sum + file.content.length, 0);
2127
- const estimatedTokens = totalLength / 3;
2128
- if (estimatedTokens <= maxTokens) {
2129
- return files;
2130
- }
2131
- let compressionRatio = maxTokens / estimatedTokens;
2132
- compressionRatio = Math.max(0.3, Math.min(0.99, compressionRatio));
2133
- const client = new CompactClient({
2134
- morphApiKey: apiKey,
2135
- morphApiUrl: apiUrl
2136
- });
2137
- const results = [];
2138
- const inProgress = /* @__PURE__ */ new Set();
2139
- for (const file of files) {
2140
- if (file.content.length < 500) {
2141
- results.push({ path: file.path, content: file.content });
2142
- continue;
2143
- }
2144
- const task = async () => {
2145
- try {
2146
- const result = await client.compact({
2147
- input: file.content,
2148
- query,
2149
- compressionRatio,
2150
- preserveRecent: 0
2151
- });
2152
- results.push({ path: file.path, content: result.output });
2153
- } catch (error) {
2154
- console.error(`[compactFileContexts] Failed to compact file ${file.path}:`, error);
2155
- results.push({ path: file.path, content: file.content });
2156
- }
2157
- };
2158
- const promise = task().finally(() => inProgress.delete(promise));
2159
- inProgress.add(promise);
2160
- if (inProgress.size >= maxConcurrency) {
2161
- await Promise.race(inProgress);
2162
- }
2163
- }
2164
- await Promise.all(inProgress);
2165
- const orderMap = new Map(files.map((f, i) => [f.path, i]));
2166
- return results.sort((a, b) => (orderMap.get(a.path) ?? 0) - (orderMap.get(b.path) ?? 0));
2167
- }
2168
-
2169
- // tools/warp_grep/client.ts
2170
- var DEFAULT_CODE_SEARCH_URL = "https://api.morphllm.com";
2171
- async function getLocalProvider(repoRoot, excludes, allowNames) {
2172
- const { LocalRipgrepProvider: LocalRipgrepProvider2 } = await Promise.resolve().then(() => (init_local(), local_exports));
2173
- const opts = allowNames?.length ? { allowNames } : void 0;
2174
- return new LocalRipgrepProvider2(repoRoot, excludes, opts);
2175
- }
2176
- var WarpGrepClient = class extends APIResource {
2177
- config;
2178
- constructor(clientOrConfig = {}) {
2179
- const isClient = clientOrConfig instanceof MorphAPIClient;
2180
- super(
2181
- isClient ? clientOrConfig : new MorphAPIClient({
2182
- apiKey: clientOrConfig.morphApiKey,
2183
- baseURL: clientOrConfig.morphApiUrl,
2184
- timeout: clientOrConfig.timeout,
2185
- retryConfig: clientOrConfig.retryConfig,
2186
- debug: clientOrConfig.debug
2187
- })
2188
- );
2189
- const cfg = isClient ? {} : clientOrConfig;
2190
- this.config = {
2191
- ...cfg,
2192
- morphApiKey: this._client.resolveApiKey(),
2193
- morphApiUrl: this._client.baseURL,
2194
- timeout: this._client.timeout,
2195
- retryConfig: this._client.retryConfig,
2196
- debug: this._client.debug
2197
- };
2198
- }
2199
- execute(input) {
2200
- const toolConfig = {
2201
- repoRoot: input.repoRoot,
2202
- remoteCommands: input.remoteCommands,
2203
- provider: input.provider,
2204
- excludes: input.excludes,
2205
- includes: input.includes,
2206
- debug: input.debug ?? this.config.debug,
2207
- morphApiKey: this.config.morphApiKey,
2208
- morphApiUrl: this.config.morphApiUrl,
2209
- retryConfig: this.config.retryConfig,
2210
- timeout: this.config.timeout,
2211
- search_type: input.search_type
2212
- };
2213
- if (input.streamSteps) {
2214
- return executeToolCallStreaming({ search_term: input.searchTerm }, toolConfig);
2215
- }
2216
- return executeToolCall({ search_term: input.searchTerm }, toolConfig);
2217
- }
2218
- searchGitHub(input) {
2219
- if (input.streamSteps) {
2220
- return this._searchGitHubStreaming(input);
2221
- }
2222
- return this._searchGitHubAsync(input);
2223
- }
2224
- /**
2225
- * Read a single file from a public GitHub repository
2226
- *
2227
- * @example
2228
- * ```typescript
2229
- * const result = await client.readGitHubFile({
2230
- * github: 'vercel/next.js',
2231
- * path: 'src/server/app-render/index.tsx',
2232
- * startLine: 1,
2233
- * endLine: 50,
2234
- * });
2235
- * if (result.success) console.log(result.content);
2236
- * ```
2237
- */
2238
- async readGitHubFile(input) {
2239
- return executeGitHubReadFile(input, { timeout: this.config.timeout });
2240
- }
2241
- async _resolveGitHubRepo(input) {
2242
- const { owner, repo } = parseGitHubUrl(input.github);
2243
- const baseUrl = this.config.codeSearchUrl || DEFAULT_CODE_SEARCH_URL;
2244
- logger.debug("WarpGrep", "github_resolve", { owner_repo: `${owner}/${repo}`, branch: input.branch });
2245
- const resolveStart = Date.now();
2246
- const importRes = await fetch(`${baseUrl}/api/code-search/get-or-create?url=${encodeURIComponent(`${owner}/${repo}`)}`, {
2247
- headers: this.config.morphApiKey ? { Authorization: `Bearer ${this.config.morphApiKey}` } : void 0
2248
- });
2249
- if (!importRes.ok) {
2250
- const text = await importRes.text().catch(() => importRes.statusText);
2251
- logger.error("WarpGrep", "github_resolve_failed", { owner_repo: `${owner}/${repo}`, status: importRes.status, error: text });
2252
- throw new Error(`Failed to import repo ${owner}/${repo}: ${text}`);
2253
- }
2254
- const { repoId, defaultBranch } = await importRes.json();
2255
- logger.debug("WarpGrep", "github_repo_fetched", { repo_id: repoId, default_branch: defaultBranch, latency_ms: Date.now() - resolveStart });
2256
- return {
2257
- repo,
2258
- remoteCommands: createCodeStorageHttpCommands({
2259
- baseUrl,
2260
- repoId,
2261
- branch: input.branch || defaultBranch,
2262
- apiKey: this.config.morphApiKey
2263
- })
2264
- };
2265
- }
2266
- async _searchGitHubAsync(input) {
2267
- try {
2268
- const { remoteCommands } = await this._resolveGitHubRepo(input);
2269
- return this.execute({
2270
- searchTerm: input.searchTerm,
2271
- repoRoot: ".",
2272
- remoteCommands
2273
- });
2274
- } catch (error) {
2275
- return { success: false, error: error instanceof Error ? error.message : String(error) };
2276
- }
2277
- }
2278
- async *_searchGitHubStreaming(input) {
2279
- let remoteCommands;
2280
- try {
2281
- ({ remoteCommands } = await this._resolveGitHubRepo(input));
2282
- } catch (error) {
2283
- return { success: false, error: error instanceof Error ? error.message : String(error) };
2284
- }
2285
- const generator = this.execute({
2286
- searchTerm: input.searchTerm,
2287
- repoRoot: ".",
2288
- remoteCommands,
2289
- streamSteps: true
2290
- });
2291
- let result;
2292
- for (; ; ) {
2293
- const { value, done } = await generator.next();
2294
- if (done) {
2295
- result = value;
2296
- break;
2297
- }
2298
- yield value;
2299
- }
2300
- return result;
2301
- }
2302
- };
2303
- function executeWarpGrep(input, config) {
2304
- const client = new WarpGrepClient(config);
2305
- if (input.streamSteps) {
2306
- return client.execute({ ...input, streamSteps: true });
2307
- }
2308
- return client.execute({ ...input, streamSteps: false });
2309
- }
2310
- async function executeToolCall(input, config) {
2311
- const parsed = typeof input === "string" ? JSON.parse(input) : input;
2312
- const allowNames = config.search_type === "node_modules" ? ["node_modules"] : void 0;
2313
- const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);
2314
- const result = await runWarpGrep({
2315
- searchTerm: parsed.search_term,
2316
- repoRoot: config.repoRoot,
2317
- provider,
2318
- excludes: config.excludes,
2319
- includes: config.includes,
2320
- debug: config.debug ?? false,
2321
- morphApiKey: config.morphApiKey,
2322
- morphApiUrl: config.morphApiUrl,
2323
- retryConfig: config.retryConfig,
2324
- timeout: config.timeout,
2325
- search_type: config.search_type
2326
- });
2327
- return processAgentResult(result, parsed.search_term, config.morphApiKey, config.morphApiUrl);
2328
- }
2329
- async function processAgentResult(result, searchTerm, apiKey, apiUrl) {
2330
- const finish = result.finish;
2331
- if (result.terminationReason !== "completed" || !finish?.metadata) {
2332
- const errorDetails = result.errors?.map((e) => e.message).join("; ") || "unknown reason";
2333
- console.error(`[warp_grep] processAgentResult failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);
2334
- return { success: false, error: `Search did not complete: ${errorDetails}` };
2335
- }
2336
- const contexts = (finish.resolved ?? []).map((r) => ({
2337
- file: r.path,
2338
- content: r.content,
2339
- lines: r.ranges
2340
- }));
2341
- try {
2342
- const compactable = contexts.map((c) => ({ path: c.file, content: c.content }));
2343
- const compacted = await compactFileContexts(compactable, searchTerm, apiKey, apiUrl);
2344
- for (let i = 0; i < contexts.length; i++) {
2345
- contexts[i].content = compacted[i].content;
2346
- }
2347
- } catch (error) {
2348
- console.error(`[warp_grep] Failed to compact result contexts:`, error);
2349
- }
2350
- return { success: true, contexts, summary: finish.payload };
2351
- }
2352
- async function* executeToolCallStreaming(input, config) {
2353
- const parsed = typeof input === "string" ? JSON.parse(input) : input;
2354
- const allowNames = config.search_type === "node_modules" ? ["node_modules"] : void 0;
2355
- const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);
2356
- const generator = runWarpGrepStreaming({
2357
- searchTerm: parsed.search_term,
2358
- repoRoot: config.repoRoot,
2359
- provider,
2360
- excludes: config.excludes,
2361
- includes: config.includes,
2362
- debug: config.debug ?? false,
2363
- morphApiKey: config.morphApiKey,
2364
- morphApiUrl: config.morphApiUrl,
2365
- retryConfig: config.retryConfig,
2366
- timeout: config.timeout,
2367
- search_type: config.search_type
2368
- });
2369
- let agentResult;
2370
- for (; ; ) {
2371
- const { value, done } = await generator.next();
2372
- if (done) {
2373
- agentResult = value;
2374
- break;
2375
- }
2376
- yield value;
2377
- }
2378
- return await processAgentResult(agentResult, parsed.search_term, config.morphApiKey, config.morphApiUrl);
2379
- }
2380
- async function fetchRawGitHubFile(owner, repo, filePath, branch, timeout) {
2381
- const branches = branch ? [branch] : ["HEAD"];
2382
- const fallbacks = ["main", "master", "develop"];
2383
- const fetchWithTimeout = (url) => timeout ? fetch(url, { signal: AbortSignal.timeout(timeout) }) : fetch(url);
2384
- for (const b of branches) {
2385
- const url = `https://raw.githubusercontent.com/${owner}/${repo}/${b}/${filePath}`;
2386
- const res = await fetchWithTimeout(url);
2387
- if (res.ok) return { content: await res.text(), branch: b };
2388
- }
2389
- for (const fb of fallbacks) {
2390
- if (branch && fb === branch) continue;
2391
- const url = `https://raw.githubusercontent.com/${owner}/${repo}/${fb}/${filePath}`;
2392
- const res = await fetchWithTimeout(url);
2393
- if (res.ok) return { content: await res.text(), branch: fb };
2394
- }
2395
- throw new Error(`File not found: ${owner}/${repo}/${filePath}`);
2396
- }
2397
- async function executeGitHubReadFile(input, config) {
2398
- try {
2399
- const { owner, repo } = parseGitHubUrl(input.github);
2400
- const { content: raw, branch } = await fetchRawGitHubFile(
2401
- owner,
2402
- repo,
2403
- input.path,
2404
- input.branch,
2405
- config?.timeout
2406
- );
2407
- const allLines = raw.split("\n");
2408
- const totalLines = allLines.length;
2409
- const start = Math.max(1, input.startLine ?? 1);
2410
- const end = Math.min(totalLines, input.endLine ?? totalLines);
2411
- const selected = allLines.slice(start - 1, end);
2412
- const padWidth = String(end).length;
2413
- const numbered = selected.map((line, i) => `${String(start + i).padStart(padWidth)}|${line}`).join("\n");
2414
- return {
2415
- success: true,
2416
- content: numbered,
2417
- path: input.path,
2418
- github: `${owner}/${repo}`,
2419
- branch,
2420
- lineRange: [start, end],
2421
- totalLines
2422
- };
2423
- } catch (error) {
2424
- return {
2425
- success: false,
2426
- error: error instanceof Error ? error.message : String(error)
2427
- };
2428
- }
2429
- }
2430
- function formatGitHubReadFileResult(result) {
2431
- if (!result.success) {
2432
- return `Failed to read file: ${result.error}`;
2433
- }
2434
- const rangeStr = result.lineRange ? ` (lines ${result.lineRange[0]}-${result.lineRange[1]} of ${result.totalLines})` : "";
2435
- return `File: ${result.github}/${result.path}${rangeStr}
2436
-
2437
- ${result.content}`;
2438
- }
2439
- function formatResult(result) {
2440
- if (!result.success) {
2441
- return `Search failed: ${result.error}`;
2442
- }
2443
- if (!result.contexts || result.contexts.length === 0) {
2444
- return "No relevant code found. Try rephrasing your search term.";
2445
- }
2446
- const parts = [];
2447
- parts.push(`Morph Fast Context subagent performed search on repository:
2448
- `);
2449
- parts.push("Relevant context found:");
2450
- for (const ctx of result.contexts) {
2451
- const rangeStr = !ctx.lines || ctx.lines === "*" ? "*" : ctx.lines.map(([s, e]) => `${s}-${e}`).join(",");
2452
- parts.push(`- ${ctx.file}:${rangeStr}`);
2453
- }
2454
- parts.push("\nHere is the content of files:\n");
2455
- for (const ctx of result.contexts) {
2456
- const rangeStr = !ctx.lines || ctx.lines === "*" ? "" : ` lines="${ctx.lines.map(([s, e]) => `${s}-${e}`).join(",")}"`;
2457
- parts.push(`<file path="${ctx.file}"${rangeStr}>`);
2458
- parts.push(ctx.content);
2459
- parts.push("</file>\n");
2460
- }
2461
- return parts.join("\n");
2462
- }
2463
- // Annotate the CommonJS export names for ESM import in node:
2464
- 0 && (module.exports = {
2465
- WarpGrepClient,
2466
- executeGitHubReadFile,
2467
- executeToolCall,
2468
- executeToolCallStreaming,
2469
- executeWarpGrep,
2470
- formatGitHubReadFileResult,
2471
- formatResult
1
+ 'use strict';
2
+
3
+ var chunkUUCRWJJR_cjs = require('../../chunk-UUCRWJJR.cjs');
4
+ require('../../chunk-VHD7CW5O.cjs');
5
+ require('../../chunk-WR7LSUIR.cjs');
6
+ require('../../chunk-MWXJ6DZ2.cjs');
7
+ require('../../chunk-HMLYJVZM.cjs');
8
+ require('../../chunk-KVGZ2TSG.cjs');
9
+ require('../../chunk-4EQQGUZ7.cjs');
10
+ require('../../chunk-UNX7V6P6.cjs');
11
+ require('../../chunk-ODY2NKQU.cjs');
12
+ require('../../chunk-AFF6XYKL.cjs');
13
+ require('../../chunk-65W4I66Q.cjs');
14
+ require('../../chunk-VL4QNALG.cjs');
15
+ require('../../chunk-ZLG2M2I4.cjs');
16
+ require('../../chunk-OM5ZSXQW.cjs');
17
+ require('../../chunk-TL34BLQD.cjs');
18
+ require('../../chunk-AWFZKS27.cjs');
19
+ require('../../chunk-75ZPJI57.cjs');
20
+
21
+
22
+
23
+ Object.defineProperty(exports, "WarpGrepClient", {
24
+ enumerable: true,
25
+ get: function () { return chunkUUCRWJJR_cjs.WarpGrepClient; }
26
+ });
27
+ Object.defineProperty(exports, "executeGitHubReadFile", {
28
+ enumerable: true,
29
+ get: function () { return chunkUUCRWJJR_cjs.executeGitHubReadFile; }
30
+ });
31
+ Object.defineProperty(exports, "executeToolCall", {
32
+ enumerable: true,
33
+ get: function () { return chunkUUCRWJJR_cjs.executeToolCall; }
34
+ });
35
+ Object.defineProperty(exports, "executeToolCallStreaming", {
36
+ enumerable: true,
37
+ get: function () { return chunkUUCRWJJR_cjs.executeToolCallStreaming; }
38
+ });
39
+ Object.defineProperty(exports, "executeWarpGrep", {
40
+ enumerable: true,
41
+ get: function () { return chunkUUCRWJJR_cjs.executeWarpGrep; }
42
+ });
43
+ Object.defineProperty(exports, "formatGitHubReadFileResult", {
44
+ enumerable: true,
45
+ get: function () { return chunkUUCRWJJR_cjs.formatGitHubReadFileResult; }
46
+ });
47
+ Object.defineProperty(exports, "formatResult", {
48
+ enumerable: true,
49
+ get: function () { return chunkUUCRWJJR_cjs.formatResult; }
2472
50
  });