@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,2785 +1,28 @@
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
- // subagents/anthropic.ts
628
- var anthropic_exports = {};
629
- __export(anthropic_exports, {
630
- createExploreSubagent: () => createExploreSubagent
631
- });
632
- module.exports = __toCommonJS(anthropic_exports);
633
-
634
- // tools/warp_grep/agent/runner.ts
635
- init_config();
636
-
637
- // tools/warp_grep/agent/parser.ts
638
- function parseReadLines(linesStr) {
639
- const ranges = [];
640
- for (const rangeStr of linesStr.split(",")) {
641
- const trimmed = rangeStr.trim();
642
- if (!trimmed) continue;
643
- const parts = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
644
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
645
- ranges.push([parts[0], parts[1]]);
646
- } else if (Number.isFinite(parts[0])) {
647
- ranges.push([parts[0], parts[0]]);
648
- }
649
- }
650
- if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };
651
- if (ranges.length > 1) return { lines: ranges };
652
- return {};
653
- }
654
- function parseFinishFiles(filesStr) {
655
- const files = [];
656
- for (const line of filesStr.trim().split(/\s+/)) {
657
- const trimmed = line.trim();
658
- if (!trimmed) continue;
659
- const searchFrom = /^[A-Za-z]:/.test(trimmed) ? 2 : 0;
660
- const colonIdx = trimmed.indexOf(":", searchFrom);
661
- if (colonIdx === -1) {
662
- files.push({ path: trimmed, lines: "*" });
663
- continue;
664
- }
665
- const filePath = trimmed.slice(0, colonIdx);
666
- const rangesPart = trimmed.slice(colonIdx + 1);
667
- if (!rangesPart.trim() || rangesPart.trim() === "*") {
668
- files.push({ path: filePath, lines: "*" });
669
- continue;
670
- }
671
- const ranges = [];
672
- for (const rangeStr of rangesPart.split(",")) {
673
- const rt = rangeStr.trim();
674
- if (!rt) continue;
675
- const parts = rt.split("-").map((v) => parseInt(v.trim(), 10));
676
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
677
- ranges.push([parts[0], parts[1]]);
678
- } else if (Number.isFinite(parts[0])) {
679
- ranges.push([parts[0], parts[0]]);
680
- }
681
- }
682
- files.push({ path: filePath, lines: ranges.length > 0 ? ranges : "*" });
683
- }
684
- return files;
685
- }
686
- function extractPathFromCommand(command) {
687
- const tokens = command.trim().split(/\s+/);
688
- const pathTokens = tokens.slice(1).filter((t) => !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("\\("));
689
- return pathTokens[0] || ".";
690
- }
691
-
692
- // tools/warp_grep/agent/tools/grep.ts
693
- async function toolGrep(provider, args) {
694
- const res = await provider.grep(args);
695
- if (res.error) {
696
- return { output: res.error };
697
- }
698
- if (!res.lines.length) {
699
- return { output: "no matches" };
700
- }
701
- return { output: res.lines.join("\n") };
702
- }
703
-
704
- // tools/warp_grep/agent/tools/read.ts
705
- function isValidRange(start, end) {
706
- return typeof start === "number" && typeof end === "number" && Number.isFinite(start) && Number.isFinite(end) && start > 0 && end >= start;
707
- }
708
- async function toolRead(provider, args) {
709
- if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {
710
- const validRanges = [];
711
- for (const range of args.lines) {
712
- if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {
713
- validRanges.push([range[0], range[1]]);
714
- }
715
- }
716
- if (validRanges.length === 0) {
717
- const res2 = await provider.read({ path: args.path });
718
- if (res2.error) return res2.error;
719
- if (!res2.lines.length) return "(empty file)";
720
- return res2.lines.join("\n");
721
- }
722
- const chunks = [];
723
- for (const [start, end] of validRanges) {
724
- const res2 = await provider.read({ path: args.path, start, end });
725
- if (res2.error) return res2.error;
726
- chunks.push(res2.lines.join("\n"));
727
- }
728
- if (chunks.every((c) => c === "")) return "(empty file)";
729
- return chunks.join("\n...\n");
730
- }
731
- const res = await provider.read({ path: args.path, start: args.start, end: args.end });
732
- if (res.error) {
733
- return res.error;
734
- }
735
- if (!res.lines.length) return "(empty file)";
736
- return res.lines.join("\n");
737
- }
738
-
739
- // tools/warp_grep/agent/tools/list_directory.ts
740
- init_config();
741
- var import_path = __toESM(require("path"), 1);
742
- async function toolListDirectory(provider, args, repoRoot) {
743
- const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;
744
- const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
745
- const entries = await provider.listDirectory({
746
- path: args.path,
747
- pattern: args.pattern ?? null,
748
- maxResults,
749
- maxDepth
750
- });
751
- if (!entries.length) return "empty";
752
- if (repoRoot) {
753
- const absRoot = repoRoot;
754
- const lines = entries.map((e) => import_path.default.join(absRoot, e.path));
755
- return lines.join("\n");
756
- }
757
- return entries.map((e) => e.path).join("\n");
758
- }
759
-
760
- // tools/warp_grep/agent/tools/glob.ts
761
- async function toolGlob(provider, args) {
762
- const res = await provider.glob(args);
763
- if (res.error) {
764
- return res.error;
765
- }
766
- if (!res.files.length) {
767
- return "no matches";
768
- }
769
- const header = `Found ${res.totalFound} file(s) matching "${args.pattern}" within ${res.searchDir}, sorted by modification time (newest first):`;
770
- const body = res.files.join("\n");
771
- const truncated = res.totalFound > res.files.length ? `
772
- [${res.totalFound - res.files.length} files truncated]` : "";
773
- return `${header}
774
- ---
775
- ${body}
776
- ---${truncated}`;
777
- }
778
-
779
- // tools/warp_grep/agent/tools/finish.ts
780
- function isValidRange2(range) {
781
- 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];
782
- }
783
- function extractValidRanges(lines) {
784
- if (!Array.isArray(lines)) return null;
785
- const valid = [];
786
- for (const range of lines) {
787
- if (isValidRange2(range)) {
788
- valid.push([range[0], range[1]]);
789
- }
790
- }
791
- return valid.length > 0 ? valid : null;
792
- }
793
- async function readFinishFiles(repoRoot, files, reader) {
794
- const out = [];
795
- for (const f of files) {
796
- const validRanges = f.lines === "*" ? null : extractValidRanges(f.lines);
797
- if (f.lines === "*" || !validRanges) {
798
- const lines = await reader(f.path);
799
- out.push({ path: f.path, ranges: "*", content: lines.join("\n") });
800
- } else {
801
- const ranges = mergeRanges(validRanges);
802
- const chunks = [];
803
- for (let i = 0; i < ranges.length; i++) {
804
- const [s, e] = ranges[i];
805
- if (i === 0 && s > 1) {
806
- chunks.push(`// ... existing code, block starting at line ${s} ...`);
807
- } else if (i > 0) {
808
- chunks.push(`// ... existing code, block starting at line ${s} ...`);
809
- }
810
- const lines = await reader(f.path, s, e);
811
- chunks.push(lines.join("\n"));
812
- }
813
- out.push({ path: f.path, ranges, content: chunks.join("\n") });
814
- }
815
- }
816
- return out;
817
- }
818
- function mergeRanges(ranges) {
819
- if (!ranges.length) return [];
820
- const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
821
- const merged = [];
822
- let [cs, ce] = sorted[0];
823
- for (let i = 1; i < sorted.length; i++) {
824
- const [s, e] = sorted[i];
825
- if (s <= ce + 1) {
826
- ce = Math.max(ce, e);
827
- } else {
828
- merged.push([cs, ce]);
829
- cs = s;
830
- ce = e;
831
- }
832
- }
833
- merged.push([cs, ce]);
834
- return merged;
835
- }
836
-
837
- // tools/warp_grep/agent/helpers.ts
838
- var import_path2 = __toESM(require("path"), 1);
839
- init_config();
840
- var TRUNCATED_MARKER = "[truncated for context limit]";
841
- function getMessageSize(m) {
842
- if (m.role === "tool") return m.content.length;
843
- if (m.role === "assistant") {
844
- let size = typeof m.content === "string" ? m.content.length : 0;
845
- if (m.tool_calls) {
846
- size += m.tool_calls.reduce((s, tc) => s + tc.function.name.length + tc.function.arguments.length, 0);
847
- }
848
- return size;
849
- }
850
- return m.content.length;
851
- }
852
- function formatTurnMessage(turnsUsed, maxTurns) {
853
- const turnsRemaining = maxTurns - turnsUsed;
854
- if (turnsRemaining === 1) {
855
- return `
856
- 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`;
857
- }
858
- return `
859
- You have used ${turnsUsed} turn${turnsUsed === 1 ? "" : "s"} and have ${turnsRemaining} remaining`;
860
- }
861
- function calculateContextBudget(messages) {
862
- const totalChars = messages.reduce((sum, m) => sum + getMessageSize(m), 0);
863
- const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;
864
- const percent = Math.floor(totalChars / maxChars * 100);
865
- const usedK = Math.floor(totalChars / 1e3);
866
- const maxK = Math.floor(maxChars / 1e3);
867
- return `<context_budget>${percent}% (${usedK}K/${maxK}K chars)</context_budget>`;
868
- }
869
- async function buildInitialState(repoRoot, searchTerm, provider, options) {
870
- const budget = calculateContextBudget([]);
871
- const turnTag = `You have used 0 turns and have ${AGENT_CONFIG.MAX_TURNS} remaining`;
872
- const treeDepth = options?.search_type === "node_modules" ? 1 : 2;
873
- const absRoot = repoRoot;
874
- try {
875
- const entries = await provider.listDirectory({
876
- path: ".",
877
- maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,
878
- maxDepth: treeDepth
879
- });
880
- const lines = [absRoot];
881
- for (const e of entries) {
882
- lines.push(import_path2.default.join(absRoot, e.path));
883
- }
884
- return `<repo_structure>
885
- ${lines.join("\n")}
886
- </repo_structure>
887
-
888
- <search_string>
889
- ${searchTerm}
890
- </search_string>
891
- ${budget}
892
- ${turnTag}`;
893
- } catch {
894
- return `<repo_structure>
895
- ${absRoot}
896
- </repo_structure>
897
-
898
- <search_string>
899
- ${searchTerm}
900
- </search_string>
901
- ${budget}
902
- ${turnTag}`;
903
- }
904
- }
905
- function enforceContextLimit(messages, maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS) {
906
- const getTotalChars = () => messages.reduce((sum, m) => sum + getMessageSize(m), 0);
907
- if (getTotalChars() <= maxChars) {
908
- return messages;
909
- }
910
- const truncatableIndices = [];
911
- let firstUserSkipped = false;
912
- for (let i = 0; i < messages.length; i++) {
913
- const m = messages[i];
914
- if (m.role === "tool") {
915
- truncatableIndices.push(i);
916
- } else if (m.role === "user") {
917
- if (!firstUserSkipped) {
918
- firstUserSkipped = true;
919
- continue;
920
- }
921
- truncatableIndices.push(i);
922
- }
923
- }
924
- for (const idx of truncatableIndices) {
925
- if (getTotalChars() <= maxChars) {
926
- break;
927
- }
928
- const m = messages[idx];
929
- if (m.role === "tool" && m.content !== TRUNCATED_MARKER) {
930
- messages[idx] = { role: "tool", tool_call_id: m.tool_call_id, content: TRUNCATED_MARKER };
931
- } else if (m.role === "user" && m.content !== TRUNCATED_MARKER) {
932
- messages[idx] = { role: "user", content: TRUNCATED_MARKER };
933
- }
934
- }
935
- return messages;
936
- }
937
-
938
- // tools/warp_grep/agent/runner.ts
939
- var import_openai = __toESM(require("openai"), 1);
940
-
941
- // package.json
942
- var package_default = {
943
- name: "@morphllm/morphsdk",
944
- version: "0.2.202",
945
- description: "TypeScript SDK and CLI for Morph Fast Apply integration",
946
- type: "module",
947
- main: "./dist/index.cjs",
948
- module: "./dist/index.js",
949
- types: "./dist/index.d.ts",
950
- exports: {
951
- ".": {
952
- types: "./dist/index.d.ts",
953
- import: "./dist/index.js",
954
- require: "./dist/index.cjs"
955
- },
956
- "./logger": {
957
- types: "./dist/logger.d.ts",
958
- import: "./dist/logger.js",
959
- require: "./dist/logger.cjs"
960
- },
961
- "./edge": {
962
- types: "./dist/edge.d.ts",
963
- import: "./dist/edge.js",
964
- require: "./dist/edge.cjs"
965
- },
966
- "./tools/warp-grep": {
967
- types: "./dist/tools/warp_grep/index.d.ts",
968
- import: "./dist/tools/warp_grep/index.js",
969
- require: "./dist/tools/warp_grep/index.cjs"
970
- },
971
- "./tools/warp-grep/openai": {
972
- types: "./dist/tools/warp_grep/openai.d.ts",
973
- import: "./dist/tools/warp_grep/openai.js",
974
- require: "./dist/tools/warp_grep/openai.cjs"
975
- },
976
- "./tools/warp-grep/anthropic": {
977
- types: "./dist/tools/warp_grep/anthropic.d.ts",
978
- import: "./dist/tools/warp_grep/anthropic.js",
979
- require: "./dist/tools/warp_grep/anthropic.cjs"
980
- },
981
- "./tools/warp-grep/vercel": {
982
- types: "./dist/tools/warp_grep/vercel.d.ts",
983
- import: "./dist/tools/warp_grep/vercel.js",
984
- require: "./dist/tools/warp_grep/vercel.cjs"
985
- },
986
- "./tools/warp-grep/client": {
987
- types: "./dist/tools/warp_grep/client.d.ts",
988
- import: "./dist/tools/warp_grep/client.js",
989
- require: "./dist/tools/warp_grep/client.cjs"
990
- },
991
- "./tools/warp-grep/gemini": {
992
- types: "./dist/tools/warp_grep/gemini.d.ts",
993
- import: "./dist/tools/warp_grep/gemini.js",
994
- require: "./dist/tools/warp_grep/gemini.cjs"
995
- },
996
- "./tools/warp-grep/harness": {
997
- types: "./dist/tools/warp_grep/harness.d.ts",
998
- import: "./dist/tools/warp_grep/harness.js",
999
- require: "./dist/tools/warp_grep/harness.cjs"
1000
- },
1001
- "./tools/fastapply": {
1002
- types: "./dist/tools/fastapply/index.d.ts",
1003
- import: "./dist/tools/fastapply/index.js",
1004
- require: "./dist/tools/fastapply/index.cjs"
1005
- },
1006
- "./tools/fastapply/anthropic": {
1007
- types: "./dist/tools/fastapply/anthropic.d.ts",
1008
- import: "./dist/tools/fastapply/anthropic.js",
1009
- require: "./dist/tools/fastapply/anthropic.cjs"
1010
- },
1011
- "./tools/fastapply/openai": {
1012
- types: "./dist/tools/fastapply/openai.d.ts",
1013
- import: "./dist/tools/fastapply/openai.js",
1014
- require: "./dist/tools/fastapply/openai.cjs"
1015
- },
1016
- "./tools/fastapply/vercel": {
1017
- types: "./dist/tools/fastapply/vercel.d.ts",
1018
- import: "./dist/tools/fastapply/vercel.js",
1019
- require: "./dist/tools/fastapply/vercel.cjs"
1020
- },
1021
- "./modelrouter": {
1022
- types: "./dist/modelrouter/index.d.ts",
1023
- import: "./dist/modelrouter/index.js",
1024
- require: "./dist/modelrouter/index.cjs"
1025
- },
1026
- "./tools/compact": {
1027
- types: "./dist/tools/compact/index.d.ts",
1028
- import: "./dist/tools/compact/index.js",
1029
- require: "./dist/tools/compact/index.cjs"
1030
- },
1031
- "./subagents": {
1032
- types: "./dist/subagents/index.d.ts",
1033
- import: "./dist/subagents/index.js",
1034
- require: "./dist/subagents/index.cjs"
1035
- },
1036
- "./subagents/vercel": {
1037
- types: "./dist/subagents/vercel.d.ts",
1038
- import: "./dist/subagents/vercel.js",
1039
- require: "./dist/subagents/vercel.cjs"
1040
- },
1041
- "./subagents/anthropic": {
1042
- types: "./dist/subagents/anthropic.d.ts",
1043
- import: "./dist/subagents/anthropic.js",
1044
- require: "./dist/subagents/anthropic.cjs"
1045
- },
1046
- "./ai-sdk": {
1047
- types: "./dist/ai-sdk/index.d.ts",
1048
- import: "./dist/ai-sdk/index.js",
1049
- require: "./dist/ai-sdk/index.cjs"
1050
- }
1051
- },
1052
- files: [
1053
- "dist/**/*.js",
1054
- "dist/**/*.cjs",
1055
- "dist/**/*.d.ts",
1056
- "!dist/**/__tests__/**",
1057
- "!dist/**/*.test.*"
1058
- ],
1059
- scripts: {
1060
- 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",
1061
- prepare: "npm run build",
1062
- typecheck: "tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json",
1063
- lint: "eslint .",
1064
- test: "vitest run",
1065
- "test:watch": "vitest watch",
1066
- "test:anthropic": "vitest run anthropic",
1067
- "test:openai": "vitest run openai",
1068
- "test:vercel": "vitest run vercel",
1069
- "test:git": "vitest run git",
1070
- "test:agent": "npx tsx tests/fullAgentTest.ts",
1071
- "test:integration": "npx tsx tests/fullIntegrationTest.ts",
1072
- "test:e2e": "vitest run --config vitest.e2e.config.ts",
1073
- "release:patch": "npm version patch && npm publish",
1074
- "release:minor": "npm version minor && npm publish",
1075
- "release:major": "npm version major && npm publish"
1076
- },
1077
- keywords: [
1078
- "morph",
1079
- "fast-apply",
1080
- "cli",
1081
- "sdk",
1082
- "edit-file"
1083
- ],
1084
- engines: {
1085
- node: ">=18"
1086
- },
1087
- license: "MIT",
1088
- dependencies: {
1089
- "@vscode/ripgrep": "^1.17.0",
1090
- ai: ">=5.0.0",
1091
- diff: "^7.0.0",
1092
- openai: "^4.52.7",
1093
- zod: ">=3.23.0"
1094
- },
1095
- devDependencies: {
1096
- "@ai-sdk/anthropic": "^2.0.70",
1097
- "@ai-sdk/openai": "^2.0.35",
1098
- "@anthropic-ai/sdk": "^0.30.1",
1099
- "@google/generative-ai": "^0.24.1",
1100
- "@types/diff": "^7.0.2",
1101
- "@types/node": "^20.14.10",
1102
- "@typescript-eslint/eslint-plugin": "^7.18.0",
1103
- "@typescript-eslint/parser": "^7.18.0",
1104
- dotenv: "^16.4.5",
1105
- eslint: "^8.57.0",
1106
- shx: "^0.3.4",
1107
- tsup: "^8.5.0",
1108
- tsx: "^4.16.2",
1109
- typescript: "^5.5.4",
1110
- vitest: "^2.1.6"
1111
- },
1112
- peerDependencies: {
1113
- "@ai-sdk/openai-compatible": ">=2.0.74 <4",
1114
- "@anthropic-ai/sdk": ">=0.25.0",
1115
- "@google/generative-ai": ">=0.21.0",
1116
- ai: ">=5.0.0",
1117
- zod: ">=3.23.0"
1118
- },
1119
- peerDependenciesMeta: {
1120
- "@anthropic-ai/sdk": {
1121
- optional: true
1122
- },
1123
- "@google/generative-ai": {
1124
- optional: true
1125
- },
1126
- ai: {
1127
- optional: true
1128
- },
1129
- zod: {
1130
- optional: true
1131
- }
1132
- },
1133
- publishConfig: {
1134
- access: "public"
1135
- }
1136
- };
1137
-
1138
- // version.ts
1139
- var SDK_VERSION = package_default.version;
1140
-
1141
- // tools/warp_grep/agent/runner.ts
1142
- var import_path3 = __toESM(require("path"), 1);
1143
-
1144
- // logger.ts
1145
- var MorphLogger = class {
1146
- enabled;
1147
- fileStream;
1148
- /** Resolves once the file stream is initialized (or immediately if no file logging). */
1149
- ready;
1150
- constructor() {
1151
- this.enabled = typeof process !== "undefined" && (process.env.MORPH_DEBUG === "1" || !!process.env.MORPH_LOG_FILE);
1152
- this.fileStream = null;
1153
- const f = typeof process !== "undefined" ? process.env.MORPH_LOG_FILE : void 0;
1154
- if (f) {
1155
- this.ready = import("fs").then((fs4) => {
1156
- this.fileStream = fs4.createWriteStream(f, { flags: "a" });
1157
- }).catch(() => {
1158
- });
1159
- } else {
1160
- this.ready = Promise.resolve();
1161
- }
1162
- }
1163
- debug(component, msg, data) {
1164
- this._log("debug", component, msg, data);
1165
- }
1166
- info(component, msg, data) {
1167
- this._log("info", component, msg, data);
1168
- }
1169
- warn(component, msg, data) {
1170
- this._log("warn", component, msg, data);
1171
- }
1172
- error(component, msg, data) {
1173
- this._log("error", component, msg, data);
1174
- }
1175
- enable() {
1176
- this.enabled = true;
1177
- }
1178
- get isEnabled() {
1179
- return this.enabled;
1180
- }
1181
- _log(level, component, msg, data) {
1182
- if (level !== "error" && !this.enabled) return;
1183
- const ts = (/* @__PURE__ */ new Date()).toISOString();
1184
- const prefix = `[${ts}] [${level.toUpperCase()}] [${component}]`;
1185
- console.error(data ? `${prefix} ${msg} ${JSON.stringify(data)}` : `${prefix} ${msg}`);
1186
- this.fileStream?.write(JSON.stringify({ ts, level, component, msg, ...data && { data } }) + "\n");
1187
- }
1188
- };
1189
- var logger = new MorphLogger();
1190
-
1191
- // tools/warp_grep/agent/runner.ts
1192
- var DEFAULT_API_URL = "https://api.morphllm.com";
1193
- var TOOL_SPECS = [
1194
- {
1195
- type: "function",
1196
- function: {
1197
- name: "list_directory",
1198
- description: "Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.",
1199
- parameters: {
1200
- type: "object",
1201
- properties: {
1202
- command: {
1203
- type: "string",
1204
- description: "Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */)."
1205
- }
1206
- },
1207
- required: ["command"]
1208
- }
1209
- }
1210
- },
1211
- {
1212
- type: "function",
1213
- function: {
1214
- name: "grep_search",
1215
- description: "Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.",
1216
- parameters: {
1217
- type: "object",
1218
- properties: {
1219
- pattern: {
1220
- type: "string",
1221
- description: "Regex pattern to search for in file contents (e.g. 'class\\s+\\w+Error', 'import|require|from', 'def (get|set|update)_user')."
1222
- },
1223
- path: {
1224
- type: "string",
1225
- description: "File or directory to search in. Defaults to current working directory."
1226
- },
1227
- glob: {
1228
- type: "string",
1229
- description: "Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*')."
1230
- },
1231
- limit: {
1232
- type: "integer",
1233
- description: "Limit output to first N matching lines. Shows all matches if not specified."
1234
- }
1235
- },
1236
- required: ["pattern"]
1237
- }
1238
- }
1239
- },
1240
- {
1241
- type: "function",
1242
- function: {
1243
- name: "glob",
1244
- description: "Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.",
1245
- parameters: {
1246
- type: "object",
1247
- properties: {
1248
- pattern: {
1249
- type: "string",
1250
- description: "Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py')."
1251
- },
1252
- path: {
1253
- type: "string",
1254
- description: "Directory to search in. Defaults to repository root."
1255
- }
1256
- },
1257
- required: ["pattern"]
1258
- }
1259
- }
1260
- },
1261
- {
1262
- type: "function",
1263
- function: {
1264
- name: "read",
1265
- description: "Read entire files or specific line ranges using absolute paths.",
1266
- parameters: {
1267
- type: "object",
1268
- properties: {
1269
- path: {
1270
- type: "string",
1271
- description: "File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path)."
1272
- },
1273
- lines: {
1274
- type: "string",
1275
- description: "Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file."
1276
- }
1277
- },
1278
- required: ["path"]
1279
- }
1280
- }
1281
- },
1282
- {
1283
- type: "function",
1284
- function: {
1285
- name: "finish",
1286
- description: "Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.",
1287
- parameters: {
1288
- type: "object",
1289
- properties: {
1290
- files: {
1291
- type: "string",
1292
- 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."
1293
- }
1294
- },
1295
- required: ["files"]
1296
- }
1297
- }
1298
- }
1299
- ];
1300
- async function callModel(messages, model, options = {}) {
1301
- const baseUrl = options.morphApiUrl || DEFAULT_API_URL;
1302
- const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
1303
- const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
1304
- const parsedUrl = new URL(baseUrl);
1305
- const baseURL = parsedUrl.pathname === "/" ? `${baseUrl}/v1` : baseUrl;
1306
- const client = new import_openai.default({
1307
- apiKey,
1308
- baseURL,
1309
- maxRetries: 0,
1310
- timeout: timeoutMs,
1311
- defaultHeaders: { "X-Morph-SDK-Version": SDK_VERSION }
1312
- });
1313
- const MAX_EMPTY_RETRIES = 1;
1314
- logger.debug("WarpGrep", "model_call", { url: baseURL, model, message_count: messages.length });
1315
- const callStartTime = Date.now();
1316
- for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {
1317
- let data;
1318
- try {
1319
- data = await client.chat.completions.create({
1320
- model,
1321
- temperature: 0,
1322
- max_tokens: 2048,
1323
- messages,
1324
- tools: TOOL_SPECS,
1325
- ...options.search_type ? { search_type: options.search_type } : {}
1326
- });
1327
- } catch (error) {
1328
- const callLatencyMs = Date.now() - callStartTime;
1329
- if (error instanceof import_openai.default.APIError) {
1330
- logger.error("WarpGrep", "model_call_error", { status: error.status, error: error.message, latency_ms: callLatencyMs });
1331
- if (error.status === 404) {
1332
- 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";
1333
- const errorText = error.message?.trim();
1334
- throw new Error(errorText || defaultMsg);
1335
- }
1336
- } else {
1337
- logger.error("WarpGrep", "model_call_error", { status: void 0, error: error instanceof Error ? error.message : String(error), latency_ms: callLatencyMs });
1338
- }
1339
- throw error;
1340
- }
1341
- const choice = data?.choices?.[0];
1342
- const message = choice?.message;
1343
- if (!message) {
1344
- if (attempt === MAX_EMPTY_RETRIES) {
1345
- throw new Error("Invalid response from model: no message in response");
1346
- }
1347
- await new Promise((resolve) => setTimeout(resolve, 200));
1348
- continue;
1349
- }
1350
- const toolCalls = (message.tool_calls || []).map((tc) => ({
1351
- id: tc.id,
1352
- type: "function",
1353
- function: { name: tc.function.name, arguments: tc.function.arguments }
1354
- }));
1355
- if (message.content || toolCalls.length > 0) {
1356
- logger.debug("WarpGrep", "model_call_complete", { latency_ms: Date.now() - callStartTime, tool_calls_count: toolCalls.length, finish_reason: choice?.finish_reason ?? "unknown" });
1357
- return { content: message.content ?? null, tool_calls: toolCalls };
1358
- }
1359
- if (attempt === MAX_EMPTY_RETRIES) {
1360
- const finishReason = choice?.finish_reason ?? "unknown";
1361
- throw new Error(
1362
- `Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`
1363
- );
1364
- }
1365
- await new Promise((resolve) => setTimeout(resolve, 200));
1366
- }
1367
- throw new Error("Invalid response from model");
1368
- }
1369
- function safeParseJSON(s) {
1370
- try {
1371
- return JSON.parse(s);
1372
- } catch {
1373
- return {};
1374
- }
1375
- }
1376
- async function executeTool(provider, name, args, repoRoot) {
1377
- switch (name) {
1378
- case "grep_search": {
1379
- const grepArgs = {
1380
- pattern: args.pattern,
1381
- path: args.path || "."
1382
- };
1383
- if (args.glob) grepArgs.glob = args.glob;
1384
- if (args.case_sensitive !== void 0) grepArgs.case_sensitive = args.case_sensitive;
1385
- const result = await toolGrep(provider, grepArgs);
1386
- let output = result.output;
1387
- if (args.limit && typeof args.limit === "number") {
1388
- const lines = output.split("\n");
1389
- if (lines.length > args.limit) {
1390
- output = lines.slice(0, args.limit).join("\n") + `
1391
- ... (truncated at ${args.limit} lines)`;
1392
- }
1393
- }
1394
- return output;
1395
- }
1396
- case "glob": {
1397
- return toolGlob(provider, {
1398
- pattern: args.pattern,
1399
- path: args.path
1400
- });
1401
- }
1402
- case "list_directory": {
1403
- const dirPath = extractPathFromCommand(args.command || ".");
1404
- return toolListDirectory(provider, { path: dirPath }, repoRoot);
1405
- }
1406
- case "read": {
1407
- const readArgs = {
1408
- path: args.path
1409
- };
1410
- if (args.lines && typeof args.lines === "string") {
1411
- Object.assign(readArgs, parseReadLines(args.lines));
1412
- }
1413
- return toolRead(provider, readArgs);
1414
- }
1415
- default:
1416
- return `Unknown tool: ${name}`;
1417
- }
1418
- }
1419
- async function* runWarpGrepStreaming(config) {
1420
- const totalStart = Date.now();
1421
- const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
1422
- const timings = { turns: [], timeout_ms: timeoutMs };
1423
- const repoRoot = config.repoRoot || process.cwd();
1424
- const model = config.model || DEFAULT_MODEL;
1425
- const messages = [];
1426
- const maxTurns = AGENT_CONFIG.MAX_TURNS;
1427
- logger.debug("WarpGrep", "session_start", { search_term: config.searchTerm, model, max_turns: maxTurns });
1428
- const initialStateStart = Date.now();
1429
- const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });
1430
- timings.initial_state_ms = Date.now() - initialStateStart;
1431
- logger.debug("WarpGrep", "initial_state", { system_prompt_len: initialState.length, user_message_len: initialState.length });
1432
- messages.push({ role: "user", content: initialState });
1433
- const provider = config.provider;
1434
- const errors = [];
1435
- let finishMeta;
1436
- let terminationReason = "terminated";
1437
- for (let turn = 1; turn <= maxTurns; turn += 1) {
1438
- const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
1439
- logger.debug("WarpGrep", "turn_start", { turn, message_count: messages.length });
1440
- const beforeChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
1441
- enforceContextLimit(messages);
1442
- const afterChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
1443
- if (afterChars < beforeChars) {
1444
- logger.debug("WarpGrep", "context_truncated", { before_chars: beforeChars, after_chars: afterChars });
1445
- }
1446
- const modelCallStart = Date.now();
1447
- const response = await callModel(messages, model, {
1448
- morphApiKey: config.morphApiKey,
1449
- morphApiUrl: config.morphApiUrl,
1450
- retryConfig: config.retryConfig,
1451
- timeout: timeoutMs,
1452
- search_type: config.search_type
1453
- }).catch((e) => {
1454
- const errMsg = e instanceof Error ? e.message : String(e);
1455
- console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
1456
- logger.error("WarpGrep", "error", { turn, error: errMsg, phase: "model_call" });
1457
- errors.push({ message: errMsg });
1458
- return null;
1459
- });
1460
- turnMetrics.morph_api_ms = Date.now() - modelCallStart;
1461
- if (!response) {
1462
- timings.turns.push(turnMetrics);
1463
- break;
1464
- }
1465
- const toolCalls = response.tool_calls;
1466
- logger.debug("WarpGrep", "model_response", { turn, tool_calls: toolCalls.map((tc) => tc.function.name), latency_ms: turnMetrics.morph_api_ms });
1467
- messages.push({
1468
- role: "assistant",
1469
- content: response.content,
1470
- ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
1471
- });
1472
- if (toolCalls.length === 0) {
1473
- console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || "").slice(0, 500)}`);
1474
- errors.push({ message: "No tool calls produced by the model." });
1475
- terminationReason = "terminated";
1476
- timings.turns.push(turnMetrics);
1477
- break;
1478
- }
1479
- yield {
1480
- turn,
1481
- toolCalls: toolCalls.map((tc) => ({
1482
- name: tc.function.name,
1483
- arguments: safeParseJSON(tc.function.arguments)
1484
- }))
1485
- };
1486
- const finishCall = toolCalls.find((tc) => tc.function.name === "finish");
1487
- if (finishCall) {
1488
- const args = safeParseJSON(finishCall.function.arguments);
1489
- const filesStr = args.files || "";
1490
- const files = parseFinishFiles(filesStr);
1491
- finishMeta = { files };
1492
- terminationReason = "completed";
1493
- logger.debug("WarpGrep", "finish", { turns: turn, files: files.map((f) => f.path) });
1494
- if (files.length === 0) {
1495
- const payload2 = filesStr || "No relevant code found.";
1496
- timings.turns.push(turnMetrics);
1497
- timings.total_ms = Date.now() - totalStart;
1498
- return {
1499
- terminationReason: "completed",
1500
- messages,
1501
- finish: { payload: payload2, metadata: finishMeta },
1502
- timings
1503
- };
1504
- }
1505
- timings.turns.push(turnMetrics);
1506
- break;
1507
- }
1508
- const toolExecStart = Date.now();
1509
- const results = await Promise.all(
1510
- toolCalls.map(async (tc) => {
1511
- const args = safeParseJSON(tc.function.arguments);
1512
- const argsSummary = Object.fromEntries(Object.entries(args).map(([k, v]) => [k, typeof v === "string" && v.length > 100 ? v.slice(0, 100) + "..." : v]));
1513
- logger.debug("WarpGrep", "tool_exec", { turn, tool: tc.function.name, args_summary: argsSummary });
1514
- const toolStart = Date.now();
1515
- const output = await executeTool(provider, tc.function.name, args, repoRoot).catch((err) => String(err));
1516
- logger.debug("WarpGrep", "tool_result", { turn, tool: tc.function.name, result_len: output.length, latency_ms: Date.now() - toolStart });
1517
- return { tool_call_id: tc.id, content: output };
1518
- })
1519
- );
1520
- turnMetrics.local_tools_ms = Date.now() - toolExecStart;
1521
- for (const result of results) {
1522
- messages.push({ role: "tool", tool_call_id: result.tool_call_id, content: result.content });
1523
- }
1524
- const turnMsg = formatTurnMessage(turn, maxTurns);
1525
- const budget = calculateContextBudget(messages);
1526
- messages.push({ role: "user", content: turnMsg + "\n" + budget });
1527
- timings.turns.push(turnMetrics);
1528
- }
1529
- if (terminationReason !== "completed" || !finishMeta) {
1530
- timings.total_ms = Date.now() - totalStart;
1531
- return { terminationReason, messages, errors, timings };
1532
- }
1533
- const parts = ["Relevant context found:"];
1534
- for (const f of finishMeta.files) {
1535
- const ranges = f.lines === "*" ? "*" : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(", ") : "*";
1536
- parts.push(`- ${f.path}: ${ranges}`);
1537
- }
1538
- const payload = parts.join("\n");
1539
- const finishResolutionStart = Date.now();
1540
- const fileReadErrors = [];
1541
- const resolved = await readFinishFiles(
1542
- repoRoot,
1543
- finishMeta.files,
1544
- async (p, s, e) => {
1545
- let resolvedPath = p;
1546
- if (!p.startsWith(repoRoot)) {
1547
- const relative = p.startsWith("/") ? p.slice(1) : p;
1548
- resolvedPath = import_path3.default.join(repoRoot, relative);
1549
- }
1550
- try {
1551
- const rr = await provider.read({ path: resolvedPath, start: s, end: e });
1552
- return rr.lines.map((l) => {
1553
- const idx = l.indexOf("|");
1554
- return idx >= 0 ? l.slice(idx + 1) : l;
1555
- });
1556
- } catch (err) {
1557
- const errorMsg = err instanceof Error ? err.message : String(err);
1558
- fileReadErrors.push({ path: resolvedPath, error: errorMsg });
1559
- console.error(`[warp_grep] Failed to read file: ${resolvedPath} - ${errorMsg}`);
1560
- return [`[couldn't find: ${resolvedPath}]`];
1561
- }
1562
- }
1563
- );
1564
- timings.finish_resolution_ms = Date.now() - finishResolutionStart;
1565
- if (fileReadErrors.length > 0) {
1566
- errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
1567
- }
1568
- timings.total_ms = Date.now() - totalStart;
1569
- return {
1570
- terminationReason: "completed",
1571
- messages,
1572
- finish: { payload, metadata: finishMeta, resolved },
1573
- timings
1574
- };
1575
- }
1576
- async function runWarpGrep(config) {
1577
- const gen = runWarpGrepStreaming(config);
1578
- let result = await gen.next();
1579
- while (!result.done) {
1580
- result = await gen.next();
1581
- }
1582
- return result.value;
1583
- }
1584
-
1585
- // tools/warp_grep/providers/remote.ts
1586
- init_config();
1587
- var SKIP_NAMES = /* @__PURE__ */ new Set([
1588
- // Version control
1589
- ".git",
1590
- ".svn",
1591
- ".hg",
1592
- ".bzr",
1593
- // Dependencies
1594
- "node_modules",
1595
- "bower_components",
1596
- ".pnpm",
1597
- ".yarn",
1598
- "vendor",
1599
- "Pods",
1600
- ".bundle",
1601
- // Python
1602
- "__pycache__",
1603
- ".pytest_cache",
1604
- ".mypy_cache",
1605
- ".ruff_cache",
1606
- ".venv",
1607
- "venv",
1608
- ".tox",
1609
- ".nox",
1610
- ".eggs",
1611
- // Build outputs
1612
- "dist",
1613
- "build",
1614
- "out",
1615
- "output",
1616
- "target",
1617
- "_build",
1618
- ".next",
1619
- ".nuxt",
1620
- ".output",
1621
- ".vercel",
1622
- ".netlify",
1623
- // Cache
1624
- ".cache",
1625
- ".parcel-cache",
1626
- ".turbo",
1627
- ".nx",
1628
- ".gradle",
1629
- // IDE
1630
- ".idea",
1631
- ".vscode",
1632
- ".vs",
1633
- // Coverage
1634
- "coverage",
1635
- ".coverage",
1636
- "htmlcov",
1637
- ".nyc_output",
1638
- // Temp
1639
- "tmp",
1640
- "temp",
1641
- ".tmp",
1642
- ".temp",
1643
- // Lock files
1644
- "package-lock.json",
1645
- "yarn.lock",
1646
- "pnpm-lock.yaml",
1647
- "bun.lockb",
1648
- "Cargo.lock",
1649
- "Gemfile.lock",
1650
- "poetry.lock"
1651
- ]);
1652
- var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
1653
- ".min.js",
1654
- ".min.css",
1655
- ".bundle.js",
1656
- ".wasm",
1657
- ".so",
1658
- ".dll",
1659
- ".pyc",
1660
- ".map",
1661
- ".js.map"
1662
- ]);
1663
- function shouldSkip(name) {
1664
- if (SKIP_NAMES.has(name)) return true;
1665
- if (name.startsWith(".")) return true;
1666
- for (const ext of SKIP_EXTENSIONS) {
1667
- if (name.endsWith(ext)) return true;
1668
- }
1669
- return false;
1670
- }
1671
- var RemoteCommandsProvider = class {
1672
- constructor(repoRoot, commands) {
1673
- this.repoRoot = repoRoot;
1674
- this.commands = commands;
1675
- }
1676
- /**
1677
- * Run grep command and parse ripgrep output
1678
- */
1679
- async grep(params) {
1680
- try {
1681
- const stdout = await this.commands.grep(params.pattern, params.path, params.glob);
1682
- const lines = (stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
1683
- if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {
1684
- const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);
1685
- truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);
1686
- return { lines: truncated };
1687
- }
1688
- return { lines };
1689
- } catch (error) {
1690
- return {
1691
- lines: [],
1692
- error: `[GREP ERROR] ${error instanceof Error ? error.message : String(error)}`
1693
- };
1694
- }
1695
- }
1696
- /**
1697
- * Read file and add line numbers
1698
- */
1699
- async read(params) {
1700
- const rawStart = params.start;
1701
- const rawEnd = params.end;
1702
- const startValid = rawStart === void 0 || Number.isFinite(rawStart) && rawStart > 0;
1703
- const endValid = rawEnd === void 0 || Number.isFinite(rawEnd) && rawEnd > 0;
1704
- const rangeValid = startValid && endValid && (rawStart === void 0 || rawEnd === void 0 || rawStart <= rawEnd);
1705
- const start = rangeValid && rawStart !== void 0 ? rawStart : 1;
1706
- const end = rangeValid && rawEnd !== void 0 ? rawEnd : 1e6;
1707
- try {
1708
- const stdout = await this.commands.read(params.path, start, end);
1709
- const contentLines = (stdout || "").split("\n");
1710
- if (contentLines.length > 0 && contentLines[contentLines.length - 1] === "") {
1711
- contentLines.pop();
1712
- }
1713
- const lines = contentLines.map((content, idx) => `${start + idx}|${content}`);
1714
- if (lines.length > AGENT_CONFIG.MAX_READ_LINES) {
1715
- const truncated = lines.slice(0, AGENT_CONFIG.MAX_READ_LINES);
1716
- truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${lines.length} lines)`);
1717
- return { lines: truncated };
1718
- }
1719
- return { lines };
1720
- } catch (error) {
1721
- return {
1722
- lines: [],
1723
- error: `[READ ERROR] ${error instanceof Error ? error.message : String(error)}`
1724
- };
1725
- }
1726
- }
1727
- /**
1728
- * List directory and parse find output
1729
- */
1730
- async listDirectory(params) {
1731
- const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
1732
- const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
1733
- try {
1734
- const stdout = await this.commands.listDir(params.path, maxDepth);
1735
- const paths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
1736
- const regex = params.pattern ? new RegExp(params.pattern) : null;
1737
- const entries = [];
1738
- for (const fullPath of paths) {
1739
- if (fullPath === params.path || fullPath === this.repoRoot) continue;
1740
- const name = fullPath.split("/").pop() || "";
1741
- if (shouldSkip(name)) continue;
1742
- if (regex && !regex.test(name)) continue;
1743
- let relativePath = fullPath;
1744
- if (fullPath.startsWith(this.repoRoot)) {
1745
- relativePath = fullPath.slice(this.repoRoot.length).replace(/^\//, "");
1746
- }
1747
- const depth = relativePath.split("/").filter(Boolean).length - 1;
1748
- const hasExtension = name.includes(".") && !name.startsWith(".");
1749
- const type = hasExtension ? "file" : "dir";
1750
- entries.push({
1751
- name,
1752
- path: relativePath,
1753
- type,
1754
- depth: Math.max(0, depth)
1755
- });
1756
- if (entries.length >= maxResults) break;
1757
- }
1758
- return entries;
1759
- } catch (error) {
1760
- return [];
1761
- }
1762
- }
1763
- /**
1764
- * Glob search - finds files matching a pattern.
1765
- * Falls back to a grep --files approach via the listDir command.
1766
- */
1767
- async glob(params) {
1768
- const searchPath = params.path || this.repoRoot;
1769
- try {
1770
- const stdout = await this.commands.listDir(searchPath, 10);
1771
- const allPaths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
1772
- const globToRegex = (glob) => {
1773
- const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
1774
- return new RegExp(escaped);
1775
- };
1776
- const regex = globToRegex(params.pattern);
1777
- const matched = allPaths.filter((p) => {
1778
- const name = p.split("/").pop() || "";
1779
- return regex.test(name) && !shouldSkip(name);
1780
- });
1781
- const totalFound = matched.length;
1782
- return { files: matched.slice(0, 100), searchDir: searchPath, totalFound };
1783
- } catch (error) {
1784
- return {
1785
- files: [],
1786
- searchDir: searchPath,
1787
- totalFound: 0,
1788
- error: `[GLOB ERROR] ${error instanceof Error ? error.message : String(error)}`
1789
- };
1790
- }
1791
- }
1792
- };
1793
-
1794
- // tools/warp_grep/providers/code_storage_http.ts
1795
- var MODEL_REPO_ROOT = /^\/?home\/ubuntu\/repo(?:\/|$)/;
1796
- function toRepoRelative(path6) {
1797
- if (!path6) return path6;
1798
- const stripped = path6.replace(MODEL_REPO_ROOT, "").replace(/^\.?\/+/, "");
1799
- return stripped || ".";
1800
- }
1801
- async function post(url, body, op, apiKey) {
1802
- const res = await fetch(url, {
1803
- method: "POST",
1804
- headers: {
1805
- "Content-Type": "application/json",
1806
- ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {}
1807
- },
1808
- body: JSON.stringify(body)
1809
- });
1810
- if (!res.ok) {
1811
- const text = await res.text().catch(() => res.statusText);
1812
- try {
1813
- const parsed = JSON.parse(text);
1814
- if (parsed.error) return `Error: ${parsed.error}`;
1815
- } catch {
1816
- }
1817
- return `Error: ${op} failed (${res.status}): ${text}`;
1818
- }
1819
- const data = await res.json();
1820
- if (data.error) throw new Error(data.error);
1821
- return data.stdout;
1822
- }
1823
- function createCodeStorageHttpCommands(config) {
1824
- const { baseUrl, repoId, branch, apiKey } = config;
1825
- const encodedRepoId = encodeURIComponent(repoId);
1826
- return {
1827
- grep: (pattern, path6, glob) => post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path: toRepoRelative(path6), glob, branch }, "grep", apiKey),
1828
- read: (path6, start, end) => post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path: toRepoRelative(path6), start, end, branch }, "read", apiKey),
1829
- listDir: (path6, maxDepth) => post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path: toRepoRelative(path6), maxDepth, branch }, "list", apiKey)
1830
- };
1831
- }
1832
-
1833
- // tools/warp_grep/utils/github.ts
1834
- function parseGitHubUrl(input) {
1835
- input = input.trim();
1836
- const urlPattern = /^(?:https?:\/\/)?github\.com\/([^\/]+)\/([^\/\?\#]+)/;
1837
- const match = input.match(urlPattern);
1838
- if (match) {
1839
- return { owner: match[1], repo: match[2].replace(/\.git$/, "") };
1840
- }
1841
- const shortPattern = /^([^\/]+)\/([^\/]+)$/;
1842
- const shortMatch = input.match(shortPattern);
1843
- if (shortMatch && !shortMatch[1].includes(".")) {
1844
- return { owner: shortMatch[1], repo: shortMatch[2].replace(/\.git$/, "") };
1845
- }
1846
- throw new Error(
1847
- `Invalid GitHub URL or shorthand: "${input}". Expected "owner/repo" or "https://github.com/owner/repo"`
1848
- );
1849
- }
1850
-
1851
- // tools/utils/resilience.ts
1852
- var DEFAULT_RETRY_CONFIG = {
1853
- maxRetries: 3,
1854
- initialDelay: 1e3,
1855
- maxDelay: 3e4,
1856
- backoffMultiplier: 2,
1857
- retryableErrors: ["ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND"]
1858
- };
1859
- async function fetchWithRetry(url, options, retryConfig = {}) {
1860
- const {
1861
- maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,
1862
- initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,
1863
- maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,
1864
- backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,
1865
- retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,
1866
- onRetry
1867
- } = retryConfig;
1868
- let lastError = null;
1869
- let delay = initialDelay;
1870
- options = { ...options, headers: { "X-Morph-SDK-Version": SDK_VERSION, ...options.headers } };
1871
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
1872
- try {
1873
- const response = await fetch(url, options);
1874
- if (response.status === 429 || response.status === 503) {
1875
- if (attempt < maxRetries) {
1876
- const retryAfter = response.headers.get("Retry-After");
1877
- const waitTime = retryAfter ? parseInt(retryAfter) * 1e3 : Math.min(delay, maxDelay);
1878
- const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);
1879
- if (onRetry) {
1880
- onRetry(attempt + 1, error);
1881
- }
1882
- await sleep(waitTime);
1883
- delay *= backoffMultiplier;
1884
- continue;
1885
- }
1886
- }
1887
- return response;
1888
- } catch (error) {
1889
- lastError = error;
1890
- const isRetryable = retryableErrors.some(
1891
- (errType) => lastError?.message?.includes(errType)
1892
- );
1893
- if (!isRetryable || attempt === maxRetries) {
1894
- throw lastError;
1895
- }
1896
- const waitTime = Math.min(delay, maxDelay);
1897
- if (onRetry) {
1898
- onRetry(attempt + 1, lastError);
1899
- }
1900
- await sleep(waitTime);
1901
- delay *= backoffMultiplier;
1902
- }
1903
- }
1904
- throw lastError || new Error("Max retries exceeded");
1905
- }
1906
- async function withTimeout(promise, timeoutMs, errorMessage) {
1907
- let timeoutId;
1908
- const timeoutPromise = new Promise((_, reject) => {
1909
- timeoutId = setTimeout(() => {
1910
- reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));
1911
- }, timeoutMs);
1912
- });
1913
- try {
1914
- const result = await Promise.race([promise, timeoutPromise]);
1915
- clearTimeout(timeoutId);
1916
- return result;
1917
- } catch (error) {
1918
- clearTimeout(timeoutId);
1919
- throw error;
1920
- }
1921
- }
1922
- function sleep(ms) {
1923
- return new Promise((resolve) => setTimeout(resolve, ms));
1924
- }
1925
- var MorphError = class extends Error {
1926
- constructor(message, code, statusCode, retryable = false) {
1927
- super(message);
1928
- this.code = code;
1929
- this.statusCode = statusCode;
1930
- this.retryable = retryable;
1931
- this.name = "MorphError";
1932
- }
1933
- };
1934
-
1935
- // core/error.ts
1936
- async function toMorphError(response) {
1937
- let message = `Morph API request failed (${response.status})`;
1938
- let code = "api_error";
1939
- try {
1940
- const body = await response.json();
1941
- message = body.error?.message ?? body.message ?? message;
1942
- code = body.error?.code ?? body.error?.type ?? code;
1943
- } catch {
1944
- }
1945
- if (response.status === 401) code = "authentication_error";
1946
- if (response.status === 429) code = "rate_limit_exceeded";
1947
- const retryable = response.status === 429 || response.status === 503;
1948
- return new MorphError(message, code, response.status, retryable);
1949
- }
1950
-
1951
- // core/client.ts
1952
- var DEFAULT_BASE_URL = "https://api.morphllm.com";
1953
- var DEFAULT_REPOS_URL = "https://repos.morphllm.com";
1954
- var DEFAULT_TIMEOUT = 6e4;
1955
- var env = (name) => typeof process !== "undefined" ? process.env?.[name] : void 0;
1956
- var stripTrailingSlash = (url) => url.replace(/\/+$/, "");
1957
- var MorphAPIClient = class {
1958
- /** Explicit key as provided; resolved against env at request time. */
1959
- apiKey;
1960
- baseURL;
1961
- reposURL;
1962
- /** Explicit default timeout (ms), if set. The request default is applied lazily so
1963
- * resources can read an undefined value and supply their own fallback. */
1964
- timeout;
1965
- retryConfig;
1966
- debug;
1967
- constructor(options = {}) {
1968
- this.apiKey = options.apiKey;
1969
- this.baseURL = stripTrailingSlash(options.baseURL ?? DEFAULT_BASE_URL);
1970
- this.reposURL = stripTrailingSlash(options.reposURL ?? env("MORPH_SEARCH_URL") ?? DEFAULT_REPOS_URL);
1971
- this.timeout = options.timeout;
1972
- this.retryConfig = options.retryConfig;
1973
- this.debug = options.debug ?? false;
1974
- if (this.debug) logger.enable();
1975
- }
1976
- /** The key actually used for requests: explicit, else `MORPH_API_KEY`. */
1977
- resolveApiKey() {
1978
- return this.apiKey ?? env("MORPH_API_KEY");
1979
- }
1980
- /** Headers shared with tools that bring their own HTTP client (FastApply/WarpGrep via the `openai` package). */
1981
- defaultHeaders() {
1982
- return { "X-Morph-SDK-Version": SDK_VERSION };
1983
- }
1984
- buildURL(path6, baseURL) {
1985
- if (/^https?:\/\//i.test(path6)) return path6;
1986
- const base = stripTrailingSlash(baseURL ?? this.baseURL);
1987
- return `${base}${path6.startsWith("/") ? "" : "/"}${path6}`;
1988
- }
1989
- buildHeaders(apiKey, extra) {
1990
- return {
1991
- "Content-Type": "application/json",
1992
- "X-Morph-SDK-Version": SDK_VERSION,
1993
- Authorization: `Bearer ${apiKey}`,
1994
- ...extra
1995
- };
1996
- }
1997
- applyQuery(url, query) {
1998
- if (!query) return url;
1999
- const params = new URLSearchParams();
2000
- for (const [key, value] of Object.entries(query)) {
2001
- if (value !== void 0 && value !== null) params.set(key, String(value));
2002
- }
2003
- const qs = params.toString();
2004
- return qs ? `${url}${url.includes("?") ? "&" : "?"}${qs}` : url;
2005
- }
2006
- async request(method, path6, opts = {}) {
2007
- const apiKey = this.resolveApiKey();
2008
- if (!apiKey) {
2009
- throw new MorphError(
2010
- "Morph API key not found. Set the MORPH_API_KEY environment variable or pass apiKey in config.",
2011
- "missing_api_key",
2012
- 401
2013
- );
2014
- }
2015
- const url = this.applyQuery(this.buildURL(path6, opts.baseURL), opts.query);
2016
- const timeout = opts.timeout ?? this.timeout ?? DEFAULT_TIMEOUT;
2017
- const init = {
2018
- method,
2019
- headers: this.buildHeaders(apiKey, opts.headers),
2020
- ...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
2021
- ...opts.signal ? { signal: opts.signal } : {}
2022
- };
2023
- logger.debug("MorphAPIClient", "request", { method, url });
2024
- const response = await withTimeout(
2025
- fetchWithRetry(url, init, this.retryConfig ?? {}),
2026
- timeout,
2027
- `Morph request to ${url} timed out after ${timeout}ms`
2028
- );
2029
- if (!response.ok) throw await toMorphError(response);
2030
- if (opts.stream) return response;
2031
- if (response.status === 204) return void 0;
2032
- const text = await response.text();
2033
- return text ? JSON.parse(text) : void 0;
2034
- }
2035
- get(path6, opts) {
2036
- return this.request("GET", path6, opts);
2037
- }
2038
- post(path6, opts) {
2039
- return this.request("POST", path6, opts);
2040
- }
2041
- delete(path6, opts) {
2042
- return this.request("DELETE", path6, opts);
2043
- }
2044
- };
2045
-
2046
- // core/resource.ts
2047
- var APIResource = class {
2048
- _client;
2049
- constructor(client) {
2050
- this._client = client;
2051
- }
2052
- };
2053
-
2054
- // tools/compact/core.ts
2055
- var DEFAULT_API_URL2 = "https://api.morphllm.com";
2056
- var DEFAULT_TIMEOUT2 = 12e4;
2057
- function resolveClient(clientOrConfig) {
2058
- if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
2059
- return new MorphAPIClient({
2060
- apiKey: clientOrConfig.morphApiKey,
2061
- baseURL: clientOrConfig.morphApiUrl ?? DEFAULT_API_URL2,
2062
- timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT2,
2063
- retryConfig: clientOrConfig.retryConfig,
2064
- debug: clientOrConfig.debug
2065
- });
2066
- }
2067
- var CompactClient = class extends APIResource {
2068
- /** Resolved URL/timeout, exposed for backwards-compatible introspection. */
2069
- config;
2070
- constructor(clientOrConfig = {}) {
2071
- super(resolveClient(clientOrConfig));
2072
- const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
2073
- this.config = {
2074
- morphApiUrl: this._client.baseURL,
2075
- timeout: cfg.timeout ?? DEFAULT_TIMEOUT2,
2076
- debug: cfg.debug ?? false
2077
- };
2078
- }
2079
- /**
2080
- * Compact messages or text via /v1/compact.
2081
- * Returns per-message `compacted_line_ranges` showing which lines were removed.
2082
- *
2083
- * @example
2084
- * ```typescript
2085
- * const client = new CompactClient({ morphApiKey: 'sk-...' });
2086
- * const result = await client.compact({
2087
- * input: codeFile,
2088
- * query: "authentication",
2089
- * compressionRatio: 0.5,
2090
- * });
2091
- * console.log(result.output);
2092
- * ```
2093
- */
2094
- async compact(input) {
2095
- const body = {
2096
- compression_ratio: input.compressionRatio ?? 0.5,
2097
- preserve_recent: input.preserveRecent ?? 2,
2098
- model: input.model ?? "morph-compactor",
2099
- include_line_ranges: input.includeLineRanges ?? true,
2100
- include_markers: input.includeMarkers ?? true
2101
- };
2102
- if (input.query !== void 0) body.query = input.query;
2103
- if (input.messages) body.messages = input.messages;
2104
- else if (typeof input.input === "string") body.input = input.input;
2105
- else if (Array.isArray(input.input)) body.messages = input.input;
2106
- else throw new Error("Either 'input' or 'messages' must be provided");
2107
- try {
2108
- return await this._client.post("/v1/compact", { body, timeout: this.config.timeout });
2109
- } catch (err) {
2110
- if (err instanceof MorphError) {
2111
- throw new Error(`Compact API error ${err.statusCode}: ${err.message}`);
2112
- }
2113
- throw err;
2114
- }
2115
- }
2116
- };
2117
-
2118
- // tools/compact/utils.ts
2119
- async function compactFileContexts(files, query, apiKey, apiUrl, maxTokens = 1e4, maxConcurrency = 3) {
2120
- const totalLength = files.reduce((sum, file) => sum + file.content.length, 0);
2121
- const estimatedTokens = totalLength / 3;
2122
- if (estimatedTokens <= maxTokens) {
2123
- return files;
2124
- }
2125
- let compressionRatio = maxTokens / estimatedTokens;
2126
- compressionRatio = Math.max(0.3, Math.min(0.99, compressionRatio));
2127
- const client = new CompactClient({
2128
- morphApiKey: apiKey,
2129
- morphApiUrl: apiUrl
2130
- });
2131
- const results = [];
2132
- const inProgress = /* @__PURE__ */ new Set();
2133
- for (const file of files) {
2134
- if (file.content.length < 500) {
2135
- results.push({ path: file.path, content: file.content });
2136
- continue;
2137
- }
2138
- const task = async () => {
2139
- try {
2140
- const result = await client.compact({
2141
- input: file.content,
2142
- query,
2143
- compressionRatio,
2144
- preserveRecent: 0
2145
- });
2146
- results.push({ path: file.path, content: result.output });
2147
- } catch (error) {
2148
- console.error(`[compactFileContexts] Failed to compact file ${file.path}:`, error);
2149
- results.push({ path: file.path, content: file.content });
2150
- }
2151
- };
2152
- const promise = task().finally(() => inProgress.delete(promise));
2153
- inProgress.add(promise);
2154
- if (inProgress.size >= maxConcurrency) {
2155
- await Promise.race(inProgress);
2156
- }
2157
- }
2158
- await Promise.all(inProgress);
2159
- const orderMap = new Map(files.map((f, i) => [f.path, i]));
2160
- return results.sort((a, b) => (orderMap.get(a.path) ?? 0) - (orderMap.get(b.path) ?? 0));
2161
- }
2162
-
2163
- // tools/warp_grep/client.ts
2164
- var DEFAULT_CODE_SEARCH_URL = "https://api.morphllm.com";
2165
- async function getLocalProvider(repoRoot, excludes, allowNames) {
2166
- const { LocalRipgrepProvider: LocalRipgrepProvider2 } = await Promise.resolve().then(() => (init_local(), local_exports));
2167
- const opts = allowNames?.length ? { allowNames } : void 0;
2168
- return new LocalRipgrepProvider2(repoRoot, excludes, opts);
2169
- }
2170
- var WarpGrepClient = class extends APIResource {
2171
- config;
2172
- constructor(clientOrConfig = {}) {
2173
- const isClient = clientOrConfig instanceof MorphAPIClient;
2174
- super(
2175
- isClient ? clientOrConfig : new MorphAPIClient({
2176
- apiKey: clientOrConfig.morphApiKey,
2177
- baseURL: clientOrConfig.morphApiUrl,
2178
- timeout: clientOrConfig.timeout,
2179
- retryConfig: clientOrConfig.retryConfig,
2180
- debug: clientOrConfig.debug
2181
- })
2182
- );
2183
- const cfg = isClient ? {} : clientOrConfig;
2184
- this.config = {
2185
- ...cfg,
2186
- morphApiKey: this._client.resolveApiKey(),
2187
- morphApiUrl: this._client.baseURL,
2188
- timeout: this._client.timeout,
2189
- retryConfig: this._client.retryConfig,
2190
- debug: this._client.debug
2191
- };
2192
- }
2193
- execute(input) {
2194
- const toolConfig = {
2195
- repoRoot: input.repoRoot,
2196
- remoteCommands: input.remoteCommands,
2197
- provider: input.provider,
2198
- excludes: input.excludes,
2199
- includes: input.includes,
2200
- debug: input.debug ?? this.config.debug,
2201
- morphApiKey: this.config.morphApiKey,
2202
- morphApiUrl: this.config.morphApiUrl,
2203
- retryConfig: this.config.retryConfig,
2204
- timeout: this.config.timeout,
2205
- search_type: input.search_type
2206
- };
2207
- if (input.streamSteps) {
2208
- return executeToolCallStreaming({ search_term: input.searchTerm }, toolConfig);
2209
- }
2210
- return executeToolCall({ search_term: input.searchTerm }, toolConfig);
2211
- }
2212
- searchGitHub(input) {
2213
- if (input.streamSteps) {
2214
- return this._searchGitHubStreaming(input);
2215
- }
2216
- return this._searchGitHubAsync(input);
2217
- }
2218
- /**
2219
- * Read a single file from a public GitHub repository
2220
- *
2221
- * @example
2222
- * ```typescript
2223
- * const result = await client.readGitHubFile({
2224
- * github: 'vercel/next.js',
2225
- * path: 'src/server/app-render/index.tsx',
2226
- * startLine: 1,
2227
- * endLine: 50,
2228
- * });
2229
- * if (result.success) console.log(result.content);
2230
- * ```
2231
- */
2232
- async readGitHubFile(input) {
2233
- return executeGitHubReadFile(input, { timeout: this.config.timeout });
2234
- }
2235
- async _resolveGitHubRepo(input) {
2236
- const { owner, repo } = parseGitHubUrl(input.github);
2237
- const baseUrl = this.config.codeSearchUrl || DEFAULT_CODE_SEARCH_URL;
2238
- logger.debug("WarpGrep", "github_resolve", { owner_repo: `${owner}/${repo}`, branch: input.branch });
2239
- const resolveStart = Date.now();
2240
- const importRes = await fetch(`${baseUrl}/api/code-search/get-or-create?url=${encodeURIComponent(`${owner}/${repo}`)}`, {
2241
- headers: this.config.morphApiKey ? { Authorization: `Bearer ${this.config.morphApiKey}` } : void 0
2242
- });
2243
- if (!importRes.ok) {
2244
- const text = await importRes.text().catch(() => importRes.statusText);
2245
- logger.error("WarpGrep", "github_resolve_failed", { owner_repo: `${owner}/${repo}`, status: importRes.status, error: text });
2246
- throw new Error(`Failed to import repo ${owner}/${repo}: ${text}`);
2247
- }
2248
- const { repoId, defaultBranch } = await importRes.json();
2249
- logger.debug("WarpGrep", "github_repo_fetched", { repo_id: repoId, default_branch: defaultBranch, latency_ms: Date.now() - resolveStart });
2250
- return {
2251
- repo,
2252
- remoteCommands: createCodeStorageHttpCommands({
2253
- baseUrl,
2254
- repoId,
2255
- branch: input.branch || defaultBranch,
2256
- apiKey: this.config.morphApiKey
2257
- })
2258
- };
2259
- }
2260
- async _searchGitHubAsync(input) {
2261
- try {
2262
- const { remoteCommands } = await this._resolveGitHubRepo(input);
2263
- return this.execute({
2264
- searchTerm: input.searchTerm,
2265
- repoRoot: ".",
2266
- remoteCommands
2267
- });
2268
- } catch (error) {
2269
- return { success: false, error: error instanceof Error ? error.message : String(error) };
2270
- }
2271
- }
2272
- async *_searchGitHubStreaming(input) {
2273
- let remoteCommands;
2274
- try {
2275
- ({ remoteCommands } = await this._resolveGitHubRepo(input));
2276
- } catch (error) {
2277
- return { success: false, error: error instanceof Error ? error.message : String(error) };
2278
- }
2279
- const generator = this.execute({
2280
- searchTerm: input.searchTerm,
2281
- repoRoot: ".",
2282
- remoteCommands,
2283
- streamSteps: true
2284
- });
2285
- let result;
2286
- for (; ; ) {
2287
- const { value, done } = await generator.next();
2288
- if (done) {
2289
- result = value;
2290
- break;
2291
- }
2292
- yield value;
2293
- }
2294
- return result;
2295
- }
2296
- };
2297
- async function executeToolCall(input, config) {
2298
- const parsed = typeof input === "string" ? JSON.parse(input) : input;
2299
- const allowNames = config.search_type === "node_modules" ? ["node_modules"] : void 0;
2300
- const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);
2301
- const result = await runWarpGrep({
2302
- searchTerm: parsed.search_term,
2303
- repoRoot: config.repoRoot,
2304
- provider,
2305
- excludes: config.excludes,
2306
- includes: config.includes,
2307
- debug: config.debug ?? false,
2308
- morphApiKey: config.morphApiKey,
2309
- morphApiUrl: config.morphApiUrl,
2310
- retryConfig: config.retryConfig,
2311
- timeout: config.timeout,
2312
- search_type: config.search_type
2313
- });
2314
- return processAgentResult(result, parsed.search_term, config.morphApiKey, config.morphApiUrl);
2315
- }
2316
- async function processAgentResult(result, searchTerm, apiKey, apiUrl) {
2317
- const finish = result.finish;
2318
- if (result.terminationReason !== "completed" || !finish?.metadata) {
2319
- const errorDetails = result.errors?.map((e) => e.message).join("; ") || "unknown reason";
2320
- console.error(`[warp_grep] processAgentResult failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);
2321
- return { success: false, error: `Search did not complete: ${errorDetails}` };
2322
- }
2323
- const contexts = (finish.resolved ?? []).map((r) => ({
2324
- file: r.path,
2325
- content: r.content,
2326
- lines: r.ranges
2327
- }));
2328
- try {
2329
- const compactable = contexts.map((c) => ({ path: c.file, content: c.content }));
2330
- const compacted = await compactFileContexts(compactable, searchTerm, apiKey, apiUrl);
2331
- for (let i = 0; i < contexts.length; i++) {
2332
- contexts[i].content = compacted[i].content;
2333
- }
2334
- } catch (error) {
2335
- console.error(`[warp_grep] Failed to compact result contexts:`, error);
2336
- }
2337
- return { success: true, contexts, summary: finish.payload };
2338
- }
2339
- async function* executeToolCallStreaming(input, config) {
2340
- const parsed = typeof input === "string" ? JSON.parse(input) : input;
2341
- const allowNames = config.search_type === "node_modules" ? ["node_modules"] : void 0;
2342
- const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);
2343
- const generator = runWarpGrepStreaming({
2344
- searchTerm: parsed.search_term,
2345
- repoRoot: config.repoRoot,
2346
- provider,
2347
- excludes: config.excludes,
2348
- includes: config.includes,
2349
- debug: config.debug ?? false,
2350
- morphApiKey: config.morphApiKey,
2351
- morphApiUrl: config.morphApiUrl,
2352
- retryConfig: config.retryConfig,
2353
- timeout: config.timeout,
2354
- search_type: config.search_type
2355
- });
2356
- let agentResult;
2357
- for (; ; ) {
2358
- const { value, done } = await generator.next();
2359
- if (done) {
2360
- agentResult = value;
2361
- break;
2362
- }
2363
- yield value;
2364
- }
2365
- return await processAgentResult(agentResult, parsed.search_term, config.morphApiKey, config.morphApiUrl);
2366
- }
2367
- async function fetchRawGitHubFile(owner, repo, filePath, branch, timeout) {
2368
- const branches = branch ? [branch] : ["HEAD"];
2369
- const fallbacks = ["main", "master", "develop"];
2370
- const fetchWithTimeout = (url) => timeout ? fetch(url, { signal: AbortSignal.timeout(timeout) }) : fetch(url);
2371
- for (const b of branches) {
2372
- const url = `https://raw.githubusercontent.com/${owner}/${repo}/${b}/${filePath}`;
2373
- const res = await fetchWithTimeout(url);
2374
- if (res.ok) return { content: await res.text(), branch: b };
2375
- }
2376
- for (const fb of fallbacks) {
2377
- if (branch && fb === branch) continue;
2378
- const url = `https://raw.githubusercontent.com/${owner}/${repo}/${fb}/${filePath}`;
2379
- const res = await fetchWithTimeout(url);
2380
- if (res.ok) return { content: await res.text(), branch: fb };
2381
- }
2382
- throw new Error(`File not found: ${owner}/${repo}/${filePath}`);
2383
- }
2384
- async function executeGitHubReadFile(input, config) {
2385
- try {
2386
- const { owner, repo } = parseGitHubUrl(input.github);
2387
- const { content: raw, branch } = await fetchRawGitHubFile(
2388
- owner,
2389
- repo,
2390
- input.path,
2391
- input.branch,
2392
- config?.timeout
2393
- );
2394
- const allLines = raw.split("\n");
2395
- const totalLines = allLines.length;
2396
- const start = Math.max(1, input.startLine ?? 1);
2397
- const end = Math.min(totalLines, input.endLine ?? totalLines);
2398
- const selected = allLines.slice(start - 1, end);
2399
- const padWidth = String(end).length;
2400
- const numbered = selected.map((line, i) => `${String(start + i).padStart(padWidth)}|${line}`).join("\n");
2401
- return {
2402
- success: true,
2403
- content: numbered,
2404
- path: input.path,
2405
- github: `${owner}/${repo}`,
2406
- branch,
2407
- lineRange: [start, end],
2408
- totalLines
2409
- };
2410
- } catch (error) {
2411
- return {
2412
- success: false,
2413
- error: error instanceof Error ? error.message : String(error)
2414
- };
2415
- }
2416
- }
2417
- function formatResult(result) {
2418
- if (!result.success) {
2419
- return `Search failed: ${result.error}`;
2420
- }
2421
- if (!result.contexts || result.contexts.length === 0) {
2422
- return "No relevant code found. Try rephrasing your search term.";
2423
- }
2424
- const parts = [];
2425
- parts.push(`Morph Fast Context subagent performed search on repository:
2426
- `);
2427
- parts.push("Relevant context found:");
2428
- for (const ctx of result.contexts) {
2429
- const rangeStr = !ctx.lines || ctx.lines === "*" ? "*" : ctx.lines.map(([s, e]) => `${s}-${e}`).join(",");
2430
- parts.push(`- ${ctx.file}:${rangeStr}`);
2431
- }
2432
- parts.push("\nHere is the content of files:\n");
2433
- for (const ctx of result.contexts) {
2434
- const rangeStr = !ctx.lines || ctx.lines === "*" ? "" : ` lines="${ctx.lines.map(([s, e]) => `${s}-${e}`).join(",")}"`;
2435
- parts.push(`<file path="${ctx.file}"${rangeStr}>`);
2436
- parts.push(ctx.content);
2437
- parts.push("</file>\n");
2438
- }
2439
- return parts.join("\n");
2440
- }
2441
-
2442
- // subagents/prompts.ts
2443
- var THOROUGHNESS_INSTRUCTIONS = {
2444
- quick: `Do 1-2 targeted searches. Find the most relevant file/function quickly and summarize. Don't go deep.`,
2445
- medium: `Do 2-4 searches. Start broad, then follow up on the most promising leads. Cover the main aspects.`,
2446
- thorough: `Do 4-8 searches. Explore systematically: start broad, then drill into each relevant area. Cover edge cases, related files, and the full call chain. Leave no stone unturned.`
2447
- };
2448
- function getSystemPrompt(thoroughness = "medium") {
2449
- return `You are a codebase exploration specialist. Your job is to search a codebase and return a concise, accurate summary of what you find.
2450
-
2451
- ## Mode
2452
- READ-ONLY. You cannot modify files. You can only search and read code.
2453
-
2454
- ## Strategy
2455
- ${THOROUGHNESS_INSTRUCTIONS[thoroughness]}
2456
-
2457
- - Use multiple focused searches rather than one vague search
2458
- - Follow imports, function calls, and type references to build complete understanding
2459
- - If a search returns no results, try alternative terms (e.g., "auth" vs "authentication" vs "login")
2460
- - Look at both implementation and tests when relevant
2461
-
2462
- ## Communication
2463
- You have a \`send_message\` tool. Use it when:
2464
- - You hit a fork in the road and need guidance ("Found auth in both src/middleware/ and legacy/auth/. Which should I focus on?")
2465
- - You need clarification on ambiguous requests ("There are 3 auth strategies: JWT, session, OAuth. Which one?")
2466
- - You want to share a key finding before continuing ("The main auth handler is in src/auth/index.ts. It delegates to strategy-specific modules. Continuing to trace JWT flow.")
2467
-
2468
- Do NOT use send_message for routine status updates. Only use it when you genuinely need input or have a significant finding worth sharing before you're done.
2469
-
2470
- ## Output
2471
- When you have enough information, output your final summary. Structure it as:
2472
- 1. Direct answer to the question
2473
- 2. Key files and their roles
2474
- 3. How the pieces connect
2475
-
2476
- Be concise. The summary should be useful to another AI model that will use your findings to complete a task.`;
2477
- }
2478
- var CODEBASE_SEARCH_TOOL = {
2479
- name: "codebase_search",
2480
- description: "Search the codebase for relevant code. Takes a natural language search request describing what you want to find. Returns matching file contents with line numbers.",
2481
- input_schema: {
2482
- type: "object",
2483
- properties: {
2484
- searchRequest: {
2485
- type: "string",
2486
- description: "Natural language description of what to search for in the codebase"
2487
- }
2488
- },
2489
- required: ["searchRequest"],
2490
- additionalProperties: false
2491
- }
2492
- };
2493
- var SEND_MESSAGE_TOOL = {
2494
- name: "send_message",
2495
- description: "Send a message to the orchestrating agent. Use this to ask questions, request clarification, or share important findings. The orchestrator may reply with additional context. Use sparingly \u2014 only when you genuinely need input or have a significant finding.",
2496
- input_schema: {
2497
- type: "object",
2498
- properties: {
2499
- message: {
2500
- type: "string",
2501
- description: "The message to send to the orchestrator"
2502
- }
2503
- },
2504
- required: ["message"],
2505
- additionalProperties: false
2506
- }
2507
- };
2508
-
2509
- // subagents/anthropic.ts
2510
- var DEFAULT_MAX_TURNS = {
2511
- quick: 3,
2512
- medium: 6,
2513
- thorough: 12
2514
- };
2515
- function getMaxTurns(config) {
2516
- return config.maxTurns ?? DEFAULT_MAX_TURNS[config.thoroughness ?? "medium"] ?? 6;
2517
- }
2518
- var TOOLS = [
2519
- {
2520
- name: CODEBASE_SEARCH_TOOL.name,
2521
- description: CODEBASE_SEARCH_TOOL.description,
2522
- input_schema: CODEBASE_SEARCH_TOOL.input_schema
2523
- },
2524
- {
2525
- name: SEND_MESSAGE_TOOL.name,
2526
- description: SEND_MESSAGE_TOOL.description,
2527
- input_schema: SEND_MESSAGE_TOOL.input_schema
2528
- }
2529
- ];
2530
- function createExploreSubagent(config) {
2531
- if (!config.repoRoot) {
2532
- throw new Error("repoRoot is required for Explore subagent");
2533
- }
2534
- const warpGrep = new WarpGrepClient({
2535
- morphApiKey: config.morphApiKey
2536
- });
2537
- const thoroughness = config.thoroughness ?? "medium";
2538
- const maxTurns = getMaxTurns(config);
2539
- const replyTimeout = config.replyTimeout ?? 3e4;
2540
- async function runExplore(prompt, callbacks = {}) {
2541
- const startTime = Date.now();
2542
- const allContexts = [];
2543
- let searchCount = 0;
2544
- const timeoutMs = config.timeout;
2545
- try {
2546
- const messages = [{ role: "user", content: prompt }];
2547
- let turns = 0;
2548
- while (turns < maxTurns) {
2549
- if (timeoutMs && Date.now() - startTime > timeoutMs) {
2550
- return {
2551
- success: false,
2552
- summary: "",
2553
- contexts: deduplicateContexts(allContexts),
2554
- searchCount,
2555
- durationMs: Date.now() - startTime,
2556
- error: `Exploration timed out after ${timeoutMs}ms`
2557
- };
2558
- }
2559
- const response = await config.client.messages.create({
2560
- model: config.model,
2561
- max_tokens: 4096,
2562
- system: getSystemPrompt(thoroughness),
2563
- tools: TOOLS,
2564
- messages
2565
- });
2566
- turns++;
2567
- if (response.stop_reason === "end_turn" || !response.content.some((b) => b.type === "tool_use")) {
2568
- const textBlock = response.content.find((b) => b.type === "text");
2569
- const summary = textBlock?.text || "Exploration completed but no summary was generated.";
2570
- callbacks.onStep?.({
2571
- step: searchCount,
2572
- searchRequest: "",
2573
- contextsFound: allContexts.length,
2574
- isFinal: true
2575
- });
2576
- return {
2577
- success: true,
2578
- summary,
2579
- contexts: deduplicateContexts(allContexts),
2580
- searchCount,
2581
- durationMs: Date.now() - startTime
2582
- };
2583
- }
2584
- messages.push({ role: "assistant", content: response.content });
2585
- const toolResults = [];
2586
- for (const block of response.content) {
2587
- if (block.type !== "tool_use") continue;
2588
- if (block.name === "codebase_search") {
2589
- searchCount++;
2590
- const input = block.input;
2591
- const warpResult = await warpGrep.execute({
2592
- searchTerm: input.searchRequest,
2593
- repoRoot: config.repoRoot,
2594
- excludes: config.excludes,
2595
- includes: config.includes
2596
- });
2597
- if (warpResult.contexts) {
2598
- allContexts.push(...warpResult.contexts);
2599
- }
2600
- callbacks.onStep?.({
2601
- step: searchCount,
2602
- searchRequest: input.searchRequest,
2603
- contextsFound: warpResult.contexts?.length ?? 0,
2604
- isFinal: false
2605
- });
2606
- toolResults.push({
2607
- type: "tool_result",
2608
- tool_use_id: block.id,
2609
- content: formatResult(warpResult)
2610
- });
2611
- } else if (block.name === "send_message") {
2612
- const input = block.input;
2613
- const subagentMsg = {
2614
- from: "explore",
2615
- content: input.message,
2616
- timestamp: Date.now()
2617
- };
2618
- let replyText = "";
2619
- if (callbacks.onMessage) {
2620
- replyText = await Promise.race([
2621
- new Promise((resolve) => {
2622
- callbacks.onMessage(subagentMsg, (text) => {
2623
- resolve(text);
2624
- });
2625
- }),
2626
- new Promise(
2627
- (resolve) => setTimeout(() => resolve(""), replyTimeout)
2628
- )
2629
- ]);
2630
- }
2631
- const toolResponse = replyText ? `Response from orchestrator: ${replyText}` : "No response. Continue with your best judgment.";
2632
- toolResults.push({
2633
- type: "tool_result",
2634
- tool_use_id: block.id,
2635
- content: toolResponse
2636
- });
2637
- }
2638
- }
2639
- messages.push({ role: "user", content: toolResults });
2640
- }
2641
- return {
2642
- success: true,
2643
- summary: "Exploration completed (max turns reached).",
2644
- contexts: deduplicateContexts(allContexts),
2645
- searchCount,
2646
- durationMs: Date.now() - startTime
2647
- };
2648
- } catch (error) {
2649
- return {
2650
- success: false,
2651
- summary: "",
2652
- contexts: deduplicateContexts(allContexts),
2653
- searchCount,
2654
- durationMs: Date.now() - startTime,
2655
- error: error instanceof Error ? error.message : String(error)
2656
- };
2657
- }
2658
- }
2659
- const exploreTool = Object.assign(
2660
- {
2661
- name: "explore",
2662
- description: "Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings.",
2663
- input_schema: {
2664
- type: "object",
2665
- properties: {
2666
- searchRequest: {
2667
- type: "string",
2668
- description: "What to explore in the codebase. Be specific about what you want to understand."
2669
- }
2670
- },
2671
- required: ["searchRequest"]
2672
- }
2673
- },
2674
- {
2675
- execute: async (input) => {
2676
- return runExplore(input.searchRequest);
2677
- },
2678
- formatResult: (result) => {
2679
- if (!result.success) {
2680
- return `Exploration failed: ${result.error}`;
2681
- }
2682
- return result.summary;
2683
- }
2684
- }
2685
- );
2686
- return {
2687
- /** Anthropic Tool definition for use in parent agents */
2688
- tool: exploreTool,
2689
- /** Run exploration with messaging support */
2690
- run(prompt) {
2691
- const messageHandlers = [];
2692
- const stepHandlers = [];
2693
- let resultPromise = null;
2694
- const session = {
2695
- on(event, handler) {
2696
- if (event === "message") messageHandlers.push(handler);
2697
- if (event === "step") stepHandlers.push(handler);
2698
- return session;
2699
- },
2700
- send(_text) {
2701
- },
2702
- get result() {
2703
- if (!resultPromise) {
2704
- resultPromise = runExplore(prompt, {
2705
- onStep: (step) => {
2706
- for (const handler of stepHandlers) handler(step);
2707
- },
2708
- onMessage: (msg, reply) => {
2709
- if (messageHandlers.length > 0) {
2710
- for (const handler of messageHandlers) handler(msg, reply);
2711
- } else {
2712
- reply("");
2713
- }
2714
- }
2715
- });
2716
- }
2717
- return resultPromise;
2718
- }
2719
- };
2720
- return session;
2721
- },
2722
- /** Stream exploration events as an async generator */
2723
- async *stream(prompt) {
2724
- const events = [];
2725
- let resolveNext = null;
2726
- let done = false;
2727
- const resultPromise = runExplore(prompt, {
2728
- onStep: (step) => {
2729
- events.push({
2730
- type: "step",
2731
- step: step.step,
2732
- searchRequest: step.searchRequest,
2733
- contextsFound: step.contextsFound,
2734
- isFinal: step.isFinal
2735
- });
2736
- resolveNext?.();
2737
- },
2738
- onMessage: (msg, reply) => {
2739
- events.push({
2740
- type: "message",
2741
- from: msg.from,
2742
- content: msg.content,
2743
- timestamp: msg.timestamp
2744
- });
2745
- resolveNext?.();
2746
- reply("Continue with your best judgment.");
2747
- }
2748
- });
2749
- while (!done) {
2750
- if (events.length > 0) {
2751
- yield events.shift();
2752
- } else {
2753
- const raceResult = await Promise.race([
2754
- resultPromise.then((r) => ({ type: "done", result: r })),
2755
- new Promise((resolve) => {
2756
- resolveNext = () => resolve({ type: "event" });
2757
- })
2758
- ]);
2759
- if (raceResult.type === "done") {
2760
- while (events.length > 0) {
2761
- yield events.shift();
2762
- }
2763
- done = true;
2764
- return raceResult.result;
2765
- }
2766
- }
2767
- }
2768
- return await resultPromise;
2769
- }
2770
- };
2771
- }
2772
- function deduplicateContexts(contexts) {
2773
- const map = /* @__PURE__ */ new Map();
2774
- for (const ctx of contexts) {
2775
- const existing = map.get(ctx.file);
2776
- if (!existing || ctx.content.length > existing.content.length) {
2777
- map.set(ctx.file, ctx);
2778
- }
2779
- }
2780
- return Array.from(map.values());
2781
- }
2782
- // Annotate the CommonJS export names for ESM import in node:
2783
- 0 && (module.exports = {
2784
- createExploreSubagent
1
+ 'use strict';
2
+
3
+ var chunk4R5MDGL6_cjs = require('../chunk-4R5MDGL6.cjs');
4
+ require('../chunk-UUCRWJJR.cjs');
5
+ require('../chunk-VHD7CW5O.cjs');
6
+ require('../chunk-WR7LSUIR.cjs');
7
+ require('../chunk-MWXJ6DZ2.cjs');
8
+ require('../chunk-HMLYJVZM.cjs');
9
+ require('../chunk-KVGZ2TSG.cjs');
10
+ require('../chunk-4EQQGUZ7.cjs');
11
+ require('../chunk-UNX7V6P6.cjs');
12
+ require('../chunk-ODY2NKQU.cjs');
13
+ require('../chunk-TPZHMD7J.cjs');
14
+ require('../chunk-AFF6XYKL.cjs');
15
+ require('../chunk-65W4I66Q.cjs');
16
+ require('../chunk-VL4QNALG.cjs');
17
+ require('../chunk-ZLG2M2I4.cjs');
18
+ require('../chunk-OM5ZSXQW.cjs');
19
+ require('../chunk-TL34BLQD.cjs');
20
+ require('../chunk-AWFZKS27.cjs');
21
+ require('../chunk-75ZPJI57.cjs');
22
+
23
+
24
+
25
+ Object.defineProperty(exports, "createExploreSubagent", {
26
+ enumerable: true,
27
+ get: function () { return chunk4R5MDGL6_cjs.createExploreSubagent; }
2785
28
  });