@morphllm/morphsdk 0.2.202 → 0.2.204

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 (246) hide show
  1. package/README.md +101 -0
  2. package/dist/chunk-2GMG5XKU.js +100 -0
  3. package/dist/chunk-2PPYWRMZ.js +3 -4
  4. package/dist/chunk-3HAHJYZQ.cjs +74 -0
  5. package/dist/{chunk-2XU3XXUE.js → chunk-3JROKKS4.js} +3 -25
  6. package/dist/{chunk-26K5EJD3.js → chunk-43JBUEIX.js} +4 -18
  7. package/dist/chunk-44OIEPIO.js +4 -23
  8. package/dist/chunk-4EQQGUZ7.cjs +104 -0
  9. package/dist/chunk-4OUGA3KS.js +1 -5
  10. package/dist/{chunk-VQDDL3UH.js → chunk-4TZBUFVP.js} +2 -8
  11. package/dist/{chunk-YAM6P5OQ.js → chunk-564XJOQP.js} +2 -6
  12. package/dist/chunk-5H3FKFOI.cjs +77 -0
  13. package/dist/chunk-5TTZQF4X.cjs +110 -0
  14. package/dist/chunk-6HAYJA6M.cjs +317 -0
  15. package/dist/chunk-6TZCVTW5.js +3 -4
  16. package/dist/chunk-6WP7EA4F.js +2 -4
  17. package/dist/chunk-74A4HLIO.cjs +42 -0
  18. package/dist/chunk-75ZPJI57.cjs +9 -0
  19. package/dist/chunk-7PJYY46L.cjs +2 -0
  20. package/dist/chunk-AWFZKS27.cjs +11 -0
  21. package/dist/chunk-BJBWWIZV.cjs +2 -0
  22. package/dist/chunk-DLYDIYDK.cjs +305 -0
  23. package/dist/{chunk-65TUD7JV.js → chunk-DYCMPDPV.js} +13 -29
  24. package/dist/{chunk-3CPI6ZIC.js → chunk-DZP7BR66.js} +22 -43
  25. package/dist/chunk-E63OPKP7.js +96 -0
  26. package/dist/chunk-E6V75LI6.cjs +334 -0
  27. package/dist/{chunk-XPHNS7NW.js → chunk-EJ6ID24K.js} +3 -12
  28. package/dist/chunk-EJTL2BOZ.cjs +42 -0
  29. package/dist/chunk-ETBRAKVV.js +1 -5
  30. package/dist/chunk-F633IVQA.cjs +91 -0
  31. package/dist/chunk-FBOZIVVQ.js +1 -0
  32. package/dist/{chunk-UKXCGQPS.js → chunk-FGA6EYC2.js} +35 -37
  33. package/dist/{chunk-CAWQEHKP.js → chunk-G4RODMXA.js} +4 -19
  34. package/dist/chunk-GUNGJC6X.cjs +256 -0
  35. package/dist/chunk-GYE3FY6Z.js +8 -0
  36. package/dist/chunk-HDP4QAZL.js +1 -4
  37. package/dist/chunk-HNMEBYIS.cjs +86 -0
  38. package/dist/chunk-HP3PCOTW.cjs +81 -0
  39. package/dist/{chunk-ICCGLO6V.js → chunk-IGXNLXPN.js} +12 -17
  40. package/dist/chunk-IPJA3ZS6.cjs +10 -0
  41. package/dist/chunk-JHC2R3HU.cjs +317 -0
  42. package/dist/{chunk-IBRBSDLT.js → chunk-JVMIFGZY.js} +5 -8
  43. package/dist/chunk-KF6S3EPJ.cjs +100 -0
  44. package/dist/chunk-KVGZ2TSG.cjs +274 -0
  45. package/dist/{chunk-6OYJC4TZ.js → chunk-L5SCKZVK.js} +13 -22
  46. package/dist/chunk-LDM7RNNN.js +1 -0
  47. package/dist/{chunk-UAZKHSEU.js → chunk-LQST3NW2.js} +5 -15
  48. package/dist/chunk-M34E2AMK.js +1 -5
  49. package/dist/chunk-MF56KEI4.js +1 -4
  50. package/dist/chunk-MLKGABMK.js +1 -3
  51. package/dist/chunk-MLPZKUCO.js +4 -5
  52. package/dist/chunk-MMX5PUGC.cjs +242 -0
  53. package/dist/chunk-MWXJ6DZ2.cjs +21 -0
  54. package/dist/chunk-NJWOWXUR.cjs +137 -0
  55. package/dist/chunk-NNKBKENK.cjs +15 -0
  56. package/dist/chunk-NRG6QX3L.js +1 -3
  57. package/dist/chunk-OCKEEEYE.cjs +433 -0
  58. package/dist/chunk-OENJO7YW.js +306 -0
  59. package/dist/chunk-OKLAYEBC.cjs +2 -0
  60. package/dist/chunk-OPDWMD4Q.js +1 -3
  61. package/dist/{chunk-D6YJ5X3C.js → chunk-OX5GN2KB.js} +26 -14
  62. package/dist/{chunk-JEVLCA5C.js → chunk-OYBOP47A.js} +18 -19
  63. package/dist/chunk-OZHCHPIE.js +1 -0
  64. package/dist/chunk-PA3UTI4A.js +1 -4
  65. package/dist/chunk-QEEAIXL5.cjs +74 -0
  66. package/dist/chunk-QT5LGZG3.cjs +10 -0
  67. package/dist/chunk-R3TUE7O2.cjs +107 -0
  68. package/dist/chunk-RYVW7RUM.js +2 -6
  69. package/dist/{chunk-LVKKICOB.js → chunk-SOQYE5A4.js} +36 -69
  70. package/dist/chunk-ST2OXLT5.cjs +91 -0
  71. package/dist/{chunk-SIFDK4AA.js → chunk-TH4MG73B.js} +3 -24
  72. package/dist/{chunk-OSL4CNSO.js → chunk-TLMAMVAW.js} +7 -23
  73. package/dist/chunk-TPZHMD7J.cjs +72 -0
  74. package/dist/{chunk-PDSIWL7I.js → chunk-U4PYAGNR.js} +6 -19
  75. package/dist/chunk-UAPK3AIJ.js +1 -10
  76. package/dist/chunk-UF5IKELS.cjs +26 -0
  77. package/dist/chunk-UHFVWYSP.cjs +408 -0
  78. package/dist/chunk-UKBSXYKE.cjs +280 -0
  79. package/dist/chunk-UNX7V6P6.cjs +60 -0
  80. package/dist/chunk-UZMMJ47A.cjs +107 -0
  81. package/dist/chunk-VHD7CW5O.cjs +43 -0
  82. package/dist/chunk-VL4QNALG.cjs +50 -0
  83. package/dist/chunk-VYE7O4FM.cjs +51 -0
  84. package/dist/chunk-WIYVT4UO.cjs +173 -0
  85. package/dist/chunk-WJHHO24M.cjs +91 -0
  86. package/dist/chunk-WR7LSUIR.cjs +213 -0
  87. package/dist/chunk-XE6D4J63.cjs +72 -0
  88. package/dist/chunk-YAUXTFIN.cjs +21 -0
  89. package/dist/{chunk-NFPRKZQ5.js → chunk-YJUCGZNN.js} +5 -22
  90. package/dist/chunk-ZSHVXDA2.js +4 -10
  91. package/dist/chunk-ZX6T3LNG.js +302 -0
  92. package/dist/{client-BWhi-vSj.d.ts → client-DSXbcxII.d.ts} +10 -1
  93. package/dist/client.cjs +44 -4360
  94. package/dist/client.d.ts +4 -2
  95. package/dist/client.js +36 -37
  96. package/dist/core/client.cjs +14 -476
  97. package/dist/core/client.d.ts +8 -0
  98. package/dist/core/client.js +10 -11
  99. package/dist/core/error.cjs +8 -251
  100. package/dist/core/error.js +4 -9
  101. package/dist/core/index.cjs +27 -491
  102. package/dist/core/index.d.ts +2 -0
  103. package/dist/core/index.js +12 -19
  104. package/dist/core/resource.cjs +9 -33
  105. package/dist/core/resource.d.ts +2 -0
  106. package/dist/core/resource.js +2 -7
  107. package/dist/edge.cjs +74 -1111
  108. package/dist/edge.d.ts +3 -0
  109. package/dist/edge.js +14 -42
  110. package/dist/guard-CvW03v4u.d.ts +59 -0
  111. package/dist/index.cjs +140 -4431
  112. package/dist/index.d.ts +6 -2
  113. package/dist/index.js +44 -87
  114. package/dist/modelrouter/core.cjs +35 -651
  115. package/dist/modelrouter/core.d.ts +2 -0
  116. package/dist/modelrouter/core.js +12 -21
  117. package/dist/modelrouter/index.cjs +35 -651
  118. package/dist/modelrouter/index.d.ts +2 -0
  119. package/dist/modelrouter/index.js +12 -21
  120. package/dist/modelrouter/types.cjs +1 -17
  121. package/dist/modelrouter/types.d.ts +5 -0
  122. package/dist/modelrouter/types.js +1 -0
  123. package/dist/subagents/anthropic.cjs +31 -2784
  124. package/dist/subagents/anthropic.d.ts +3 -1
  125. package/dist/subagents/anthropic.js +23 -24
  126. package/dist/subagents/index.cjs +14 -95
  127. package/dist/subagents/index.d.ts +3 -1
  128. package/dist/subagents/index.js +2 -11
  129. package/dist/subagents/prompts.cjs +14 -93
  130. package/dist/subagents/prompts.d.ts +3 -1
  131. package/dist/subagents/prompts.js +2 -11
  132. package/dist/subagents/types.cjs +1 -17
  133. package/dist/subagents/types.d.ts +3 -1
  134. package/dist/subagents/types.js +1 -0
  135. package/dist/subagents/vercel.cjs +31 -2761
  136. package/dist/subagents/vercel.d.ts +3 -1
  137. package/dist/subagents/vercel.js +23 -24
  138. package/dist/tools/compact/core.cjs +20 -552
  139. package/dist/tools/compact/core.d.ts +2 -0
  140. package/dist/tools/compact/core.js +12 -13
  141. package/dist/tools/compact/index.cjs +24 -598
  142. package/dist/tools/compact/index.d.ts +3 -1
  143. package/dist/tools/compact/index.js +13 -17
  144. package/dist/tools/compact/types.cjs +1 -17
  145. package/dist/tools/compact/types.d.ts +4 -4
  146. package/dist/tools/compact/types.js +1 -0
  147. package/dist/tools/fastapply/anthropic.cjs +39 -899
  148. package/dist/tools/fastapply/anthropic.d.ts +2 -0
  149. package/dist/tools/fastapply/anthropic.js +15 -24
  150. package/dist/tools/fastapply/apply.cjs +32 -672
  151. package/dist/tools/fastapply/apply.d.ts +2 -0
  152. package/dist/tools/fastapply/apply.js +8 -19
  153. package/dist/tools/fastapply/core.cjs +49 -1069
  154. package/dist/tools/fastapply/core.d.ts +3 -0
  155. package/dist/tools/fastapply/core.js +13 -29
  156. package/dist/tools/fastapply/index.cjs +56 -1052
  157. package/dist/tools/fastapply/index.d.ts +2 -0
  158. package/dist/tools/fastapply/index.js +18 -44
  159. package/dist/tools/fastapply/openai.cjs +45 -910
  160. package/dist/tools/fastapply/openai.d.ts +2 -0
  161. package/dist/tools/fastapply/openai.js +15 -26
  162. package/dist/tools/fastapply/prompts.cjs +10 -62
  163. package/dist/tools/fastapply/prompts.js +2 -9
  164. package/dist/tools/fastapply/types.cjs +1 -17
  165. package/dist/tools/fastapply/types.d.ts +9 -4
  166. package/dist/tools/fastapply/types.js +1 -0
  167. package/dist/tools/fastapply/vercel.cjs +37 -905
  168. package/dist/tools/fastapply/vercel.d.ts +2 -0
  169. package/dist/tools/fastapply/vercel.js +15 -22
  170. package/dist/tools/index.cjs +56 -1052
  171. package/dist/tools/index.d.ts +2 -0
  172. package/dist/tools/index.js +18 -44
  173. package/dist/tools/pii/index.cjs +47 -0
  174. package/dist/tools/pii/index.d.ts +4 -0
  175. package/dist/tools/pii/index.js +6 -0
  176. package/dist/tools/pii/model.cjs +45 -0
  177. package/dist/tools/pii/model.d.ts +83 -0
  178. package/dist/tools/pii/model.js +4 -0
  179. package/dist/tools/pii/patterns.cjs +15 -0
  180. package/dist/tools/pii/patterns.d.ts +31 -0
  181. package/dist/tools/pii/patterns.js +2 -0
  182. package/dist/tools/pii/regex.cjs +32 -0
  183. package/dist/tools/pii/regex.d.ts +48 -0
  184. package/dist/tools/pii/regex.js +3 -0
  185. package/dist/tools/pii/types.cjs +2 -0
  186. package/dist/tools/pii/types.d.ts +108 -0
  187. package/dist/tools/pii/types.js +1 -0
  188. package/dist/tools/utils/resilience.cjs +15 -312
  189. package/dist/tools/utils/resilience.js +3 -12
  190. package/dist/tools/warp_grep/agent/config.cjs +16 -127
  191. package/dist/tools/warp_grep/agent/config.js +2 -11
  192. package/dist/tools/warp_grep/agent/formatter.cjs +12 -48
  193. package/dist/tools/warp_grep/agent/formatter.js +2 -9
  194. package/dist/tools/warp_grep/agent/parser.cjs +16 -83
  195. package/dist/tools/warp_grep/agent/parser.d.ts +2 -0
  196. package/dist/tools/warp_grep/agent/parser.js +2 -11
  197. package/dist/tools/warp_grep/agent/runner.cjs +19 -1081
  198. package/dist/tools/warp_grep/agent/runner.d.ts +2 -0
  199. package/dist/tools/warp_grep/agent/runner.js +11 -14
  200. package/dist/tools/warp_grep/agent/types.cjs +1 -17
  201. package/dist/tools/warp_grep/agent/types.d.ts +4 -0
  202. package/dist/tools/warp_grep/agent/types.js +1 -0
  203. package/dist/tools/warp_grep/anthropic.cjs +51 -2561
  204. package/dist/tools/warp_grep/anthropic.d.ts +3 -1
  205. package/dist/tools/warp_grep/anthropic.js +23 -35
  206. package/dist/tools/warp_grep/client.cjs +53 -2471
  207. package/dist/tools/warp_grep/client.d.ts +3 -1
  208. package/dist/tools/warp_grep/client.js +21 -34
  209. package/dist/tools/warp_grep/gemini.cjs +52 -2490
  210. package/dist/tools/warp_grep/gemini.d.ts +3 -1
  211. package/dist/tools/warp_grep/gemini.js +25 -41
  212. package/dist/tools/warp_grep/harness.cjs +81 -936
  213. package/dist/tools/warp_grep/harness.d.ts +2 -0
  214. package/dist/tools/warp_grep/harness.js +12 -51
  215. package/dist/tools/warp_grep/index.cjs +128 -2575
  216. package/dist/tools/warp_grep/index.d.ts +3 -1
  217. package/dist/tools/warp_grep/index.js +28 -87
  218. package/dist/tools/warp_grep/openai.cjs +57 -2575
  219. package/dist/tools/warp_grep/openai.d.ts +3 -1
  220. package/dist/tools/warp_grep/openai.js +23 -37
  221. package/dist/tools/warp_grep/providers/code_storage_http.cjs +12 -65
  222. package/dist/tools/warp_grep/providers/code_storage_http.d.ts +3 -1
  223. package/dist/tools/warp_grep/providers/code_storage_http.js +2 -9
  224. package/dist/tools/warp_grep/providers/local.cjs +10 -589
  225. package/dist/tools/warp_grep/providers/local.js +6 -11
  226. package/dist/tools/warp_grep/providers/remote.cjs +8 -331
  227. package/dist/tools/warp_grep/providers/remote.d.ts +3 -1
  228. package/dist/tools/warp_grep/providers/remote.js +3 -8
  229. package/dist/tools/warp_grep/providers/types.cjs +1 -17
  230. package/dist/tools/warp_grep/providers/types.js +1 -0
  231. package/dist/tools/warp_grep/utils/files.cjs +9 -42
  232. package/dist/tools/warp_grep/utils/files.js +2 -7
  233. package/dist/tools/warp_grep/utils/github.cjs +9 -43
  234. package/dist/tools/warp_grep/utils/github.js +2 -7
  235. package/dist/tools/warp_grep/utils/paths.cjs +28 -104
  236. package/dist/tools/warp_grep/utils/paths.js +2 -17
  237. package/dist/tools/warp_grep/utils/ripgrep.cjs +9 -103
  238. package/dist/tools/warp_grep/utils/ripgrep.js +2 -7
  239. package/dist/tools/warp_grep/vercel.cjs +57 -2557
  240. package/dist/tools/warp_grep/vercel.d.ts +3 -1
  241. package/dist/tools/warp_grep/vercel.js +23 -37
  242. package/dist/{types-DxZLPogx.d.ts → types-BKhXjDCB.d.ts} +6 -1
  243. package/dist/version.cjs +7 -225
  244. package/dist/version.js +2 -7
  245. package/package.json +11 -2
  246. package/dist/chunk-E6TL6MIH.js +0 -203
package/dist/index.cjs CHANGED
@@ -1,4432 +1,141 @@
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
- // package.json
34
- var package_default;
35
- var init_package = __esm({
36
- "package.json"() {
37
- package_default = {
38
- name: "@morphllm/morphsdk",
39
- version: "0.2.202",
40
- description: "TypeScript SDK and CLI for Morph Fast Apply integration",
41
- type: "module",
42
- main: "./dist/index.cjs",
43
- module: "./dist/index.js",
44
- types: "./dist/index.d.ts",
45
- exports: {
46
- ".": {
47
- types: "./dist/index.d.ts",
48
- import: "./dist/index.js",
49
- require: "./dist/index.cjs"
50
- },
51
- "./logger": {
52
- types: "./dist/logger.d.ts",
53
- import: "./dist/logger.js",
54
- require: "./dist/logger.cjs"
55
- },
56
- "./edge": {
57
- types: "./dist/edge.d.ts",
58
- import: "./dist/edge.js",
59
- require: "./dist/edge.cjs"
60
- },
61
- "./tools/warp-grep": {
62
- types: "./dist/tools/warp_grep/index.d.ts",
63
- import: "./dist/tools/warp_grep/index.js",
64
- require: "./dist/tools/warp_grep/index.cjs"
65
- },
66
- "./tools/warp-grep/openai": {
67
- types: "./dist/tools/warp_grep/openai.d.ts",
68
- import: "./dist/tools/warp_grep/openai.js",
69
- require: "./dist/tools/warp_grep/openai.cjs"
70
- },
71
- "./tools/warp-grep/anthropic": {
72
- types: "./dist/tools/warp_grep/anthropic.d.ts",
73
- import: "./dist/tools/warp_grep/anthropic.js",
74
- require: "./dist/tools/warp_grep/anthropic.cjs"
75
- },
76
- "./tools/warp-grep/vercel": {
77
- types: "./dist/tools/warp_grep/vercel.d.ts",
78
- import: "./dist/tools/warp_grep/vercel.js",
79
- require: "./dist/tools/warp_grep/vercel.cjs"
80
- },
81
- "./tools/warp-grep/client": {
82
- types: "./dist/tools/warp_grep/client.d.ts",
83
- import: "./dist/tools/warp_grep/client.js",
84
- require: "./dist/tools/warp_grep/client.cjs"
85
- },
86
- "./tools/warp-grep/gemini": {
87
- types: "./dist/tools/warp_grep/gemini.d.ts",
88
- import: "./dist/tools/warp_grep/gemini.js",
89
- require: "./dist/tools/warp_grep/gemini.cjs"
90
- },
91
- "./tools/warp-grep/harness": {
92
- types: "./dist/tools/warp_grep/harness.d.ts",
93
- import: "./dist/tools/warp_grep/harness.js",
94
- require: "./dist/tools/warp_grep/harness.cjs"
95
- },
96
- "./tools/fastapply": {
97
- types: "./dist/tools/fastapply/index.d.ts",
98
- import: "./dist/tools/fastapply/index.js",
99
- require: "./dist/tools/fastapply/index.cjs"
100
- },
101
- "./tools/fastapply/anthropic": {
102
- types: "./dist/tools/fastapply/anthropic.d.ts",
103
- import: "./dist/tools/fastapply/anthropic.js",
104
- require: "./dist/tools/fastapply/anthropic.cjs"
105
- },
106
- "./tools/fastapply/openai": {
107
- types: "./dist/tools/fastapply/openai.d.ts",
108
- import: "./dist/tools/fastapply/openai.js",
109
- require: "./dist/tools/fastapply/openai.cjs"
110
- },
111
- "./tools/fastapply/vercel": {
112
- types: "./dist/tools/fastapply/vercel.d.ts",
113
- import: "./dist/tools/fastapply/vercel.js",
114
- require: "./dist/tools/fastapply/vercel.cjs"
115
- },
116
- "./modelrouter": {
117
- types: "./dist/modelrouter/index.d.ts",
118
- import: "./dist/modelrouter/index.js",
119
- require: "./dist/modelrouter/index.cjs"
120
- },
121
- "./tools/compact": {
122
- types: "./dist/tools/compact/index.d.ts",
123
- import: "./dist/tools/compact/index.js",
124
- require: "./dist/tools/compact/index.cjs"
125
- },
126
- "./subagents": {
127
- types: "./dist/subagents/index.d.ts",
128
- import: "./dist/subagents/index.js",
129
- require: "./dist/subagents/index.cjs"
130
- },
131
- "./subagents/vercel": {
132
- types: "./dist/subagents/vercel.d.ts",
133
- import: "./dist/subagents/vercel.js",
134
- require: "./dist/subagents/vercel.cjs"
135
- },
136
- "./subagents/anthropic": {
137
- types: "./dist/subagents/anthropic.d.ts",
138
- import: "./dist/subagents/anthropic.js",
139
- require: "./dist/subagents/anthropic.cjs"
140
- },
141
- "./ai-sdk": {
142
- types: "./dist/ai-sdk/index.d.ts",
143
- import: "./dist/ai-sdk/index.js",
144
- require: "./dist/ai-sdk/index.cjs"
145
- }
146
- },
147
- files: [
148
- "dist/**/*.js",
149
- "dist/**/*.cjs",
150
- "dist/**/*.d.ts",
151
- "!dist/**/__tests__/**",
152
- "!dist/**/*.test.*"
153
- ],
154
- scripts: {
155
- 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",
156
- prepare: "npm run build",
157
- typecheck: "tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json",
158
- lint: "eslint .",
159
- test: "vitest run",
160
- "test:watch": "vitest watch",
161
- "test:anthropic": "vitest run anthropic",
162
- "test:openai": "vitest run openai",
163
- "test:vercel": "vitest run vercel",
164
- "test:git": "vitest run git",
165
- "test:agent": "npx tsx tests/fullAgentTest.ts",
166
- "test:integration": "npx tsx tests/fullIntegrationTest.ts",
167
- "test:e2e": "vitest run --config vitest.e2e.config.ts",
168
- "release:patch": "npm version patch && npm publish",
169
- "release:minor": "npm version minor && npm publish",
170
- "release:major": "npm version major && npm publish"
171
- },
172
- keywords: [
173
- "morph",
174
- "fast-apply",
175
- "cli",
176
- "sdk",
177
- "edit-file"
178
- ],
179
- engines: {
180
- node: ">=18"
181
- },
182
- license: "MIT",
183
- dependencies: {
184
- "@vscode/ripgrep": "^1.17.0",
185
- ai: ">=5.0.0",
186
- diff: "^7.0.0",
187
- openai: "^4.52.7",
188
- zod: ">=3.23.0"
189
- },
190
- devDependencies: {
191
- "@ai-sdk/anthropic": "^2.0.70",
192
- "@ai-sdk/openai": "^2.0.35",
193
- "@anthropic-ai/sdk": "^0.30.1",
194
- "@google/generative-ai": "^0.24.1",
195
- "@types/diff": "^7.0.2",
196
- "@types/node": "^20.14.10",
197
- "@typescript-eslint/eslint-plugin": "^7.18.0",
198
- "@typescript-eslint/parser": "^7.18.0",
199
- dotenv: "^16.4.5",
200
- eslint: "^8.57.0",
201
- shx: "^0.3.4",
202
- tsup: "^8.5.0",
203
- tsx: "^4.16.2",
204
- typescript: "^5.5.4",
205
- vitest: "^2.1.6"
206
- },
207
- peerDependencies: {
208
- "@ai-sdk/openai-compatible": ">=2.0.74 <4",
209
- "@anthropic-ai/sdk": ">=0.25.0",
210
- "@google/generative-ai": ">=0.21.0",
211
- ai: ">=5.0.0",
212
- zod: ">=3.23.0"
213
- },
214
- peerDependenciesMeta: {
215
- "@anthropic-ai/sdk": {
216
- optional: true
217
- },
218
- "@google/generative-ai": {
219
- optional: true
220
- },
221
- ai: {
222
- optional: true
223
- },
224
- zod: {
225
- optional: true
226
- }
227
- },
228
- publishConfig: {
229
- access: "public"
230
- }
231
- };
232
- }
233
- });
234
-
235
- // version.ts
236
- var SDK_VERSION;
237
- var init_version = __esm({
238
- "version.ts"() {
239
- "use strict";
240
- init_package();
241
- SDK_VERSION = package_default.version;
242
- }
243
- });
244
-
245
- // logger.ts
246
- var MorphLogger, logger;
247
- var init_logger = __esm({
248
- "logger.ts"() {
249
- "use strict";
250
- MorphLogger = class {
251
- enabled;
252
- fileStream;
253
- /** Resolves once the file stream is initialized (or immediately if no file logging). */
254
- ready;
255
- constructor() {
256
- this.enabled = typeof process !== "undefined" && (process.env.MORPH_DEBUG === "1" || !!process.env.MORPH_LOG_FILE);
257
- this.fileStream = null;
258
- const f = typeof process !== "undefined" ? process.env.MORPH_LOG_FILE : void 0;
259
- if (f) {
260
- this.ready = import("fs").then((fs4) => {
261
- this.fileStream = fs4.createWriteStream(f, { flags: "a" });
262
- }).catch(() => {
263
- });
264
- } else {
265
- this.ready = Promise.resolve();
266
- }
267
- }
268
- debug(component, msg, data) {
269
- this._log("debug", component, msg, data);
270
- }
271
- info(component, msg, data) {
272
- this._log("info", component, msg, data);
273
- }
274
- warn(component, msg, data) {
275
- this._log("warn", component, msg, data);
276
- }
277
- error(component, msg, data) {
278
- this._log("error", component, msg, data);
279
- }
280
- enable() {
281
- this.enabled = true;
282
- }
283
- get isEnabled() {
284
- return this.enabled;
285
- }
286
- _log(level, component, msg, data) {
287
- if (level !== "error" && !this.enabled) return;
288
- const ts = (/* @__PURE__ */ new Date()).toISOString();
289
- const prefix = `[${ts}] [${level.toUpperCase()}] [${component}]`;
290
- console.error(data ? `${prefix} ${msg} ${JSON.stringify(data)}` : `${prefix} ${msg}`);
291
- this.fileStream?.write(JSON.stringify({ ts, level, component, msg, ...data && { data } }) + "\n");
292
- }
293
- };
294
- logger = new MorphLogger();
295
- }
296
- });
297
-
298
- // tools/fastapply/anchors.ts
299
- function escapeRegExp(value) {
300
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
301
- }
302
- function findNamespace(values) {
303
- for (let namespace = 0; namespace < Number.MAX_SAFE_INTEGER; namespace++) {
304
- const prefix = `\u27EAM${namespace}:`;
305
- if (values.every((value) => !value.includes(prefix))) {
306
- return namespace;
307
- }
308
- }
309
- throw new Error("Unable to allocate a Fast Apply anchor namespace");
310
- }
311
- function htmlLabel(token) {
312
- if (!token.startsWith("<")) return "text";
313
- const match = token.match(/^<\s*(!doctype|\/?[a-zA-Z][\w:-]*)/);
314
- return (match?.[1] ?? "tag").toLowerCase();
315
- }
316
- function htmlTokenUnits(value, visibleTags = /* @__PURE__ */ new Set()) {
317
- return (value.match(/<[^>]*>|[^<]+/g) ?? [value]).map((token) => ({
318
- value: token,
319
- label: htmlLabel(token),
320
- anchorable: token.length >= DEFAULT_MIN_ANCHOR_LINE_LENGTH && !visibleTags.has(htmlLabel(token).replace(/^\//, ""))
321
- }));
322
- }
323
- function sourceUnits(originalCode, editContext) {
324
- const trimmed = originalCode.trimStart().toLowerCase();
325
- const looksLikeHtml = (trimmed.startsWith("<!doctype") || trimmed.startsWith("<html")) && /<\/html\s*>/i.test(originalCode);
326
- if (looksLikeHtml) {
327
- const contextWords = new Set(
328
- editContext.join(" ").toLowerCase().match(/[a-z][\w:-]*/g) ?? []
329
- );
330
- return htmlTokenUnits(originalCode, contextWords);
331
- }
332
- const parts = originalCode.split(/(\r\n|\n|\r)/);
333
- const units = [];
334
- for (let index = 0; index < parts.length; index += 2) {
335
- const line = parts[index] ?? "";
336
- const lineEnding = parts[index + 1] ?? "";
337
- units.push({
338
- value: line,
339
- label: "line",
340
- anchorable: line.length >= DEFAULT_MIN_ANCHOR_LINE_LENGTH
341
- });
342
- if (lineEnding) {
343
- units.push({ value: lineEnding, anchorable: false });
344
- }
345
- }
346
- return units;
347
- }
348
- function copyCount(value) {
349
- const words = {
350
- one: 1,
351
- two: 2,
352
- three: 3,
353
- four: 4,
354
- five: 5,
355
- six: 6,
356
- seven: 7,
357
- eight: 8,
358
- nine: 9,
359
- ten: 10
360
- };
361
- return /^\d+$/.test(value) ? Number(value) : words[value.toLowerCase()];
362
- }
363
- function structuralExpectation(originalCode, editContext) {
364
- const context = editContext.join(" ");
365
- const match = context.match(
366
- /(?:for every|for each|each)\s+([a-z][\w:-]*)[\s\S]{0,120}?add\s+(one|two|three|four|five|six|seven|eight|nine|ten|\d+)\s+identical cop(?:y|ies)/i
367
- );
368
- if (!match) return void 0;
369
- const tag = match[1].toLowerCase();
370
- const addedCopies = copyCount(match[2]);
371
- if (addedCopies === void 0) return void 0;
372
- const tagPattern = new RegExp(`<${escapeRegExp(tag)}(?:\\s|>)`, "gi");
373
- const originalCount = originalCode.match(tagPattern)?.length ?? 0;
374
- if (originalCount === 0) return void 0;
375
- return { tag, expectedCount: originalCount * (addedCopies + 1) };
376
- }
377
- function createAnchorCompactionPlan(originalCode, collisionValues = []) {
378
- const namespace = findNamespace([originalCode, ...collisionValues]);
379
- const expectation = structuralExpectation(originalCode, collisionValues);
380
- const markerPrefix = `\u27EAM${namespace}:`;
381
- const definitions = /* @__PURE__ */ new Map();
382
- const values = [];
383
- const markers = [];
384
- let anchorCount = 0;
385
- let skeleton = "";
386
- for (const unit of sourceUnits(originalCode, collisionValues)) {
387
- if (!unit.anchorable) {
388
- skeleton += unit.value;
389
- continue;
390
- }
391
- let id = definitions.get(unit.value);
392
- if (id === void 0) {
393
- id = values.length;
394
- definitions.set(unit.value, id);
395
- values.push(unit.value);
396
- markers.push(`${markerPrefix}${id}:${unit.label ?? "unit"}\u27EB`);
397
- }
398
- skeleton += markers[id];
399
- anchorCount++;
400
- }
401
- if (anchorCount === 0 || skeleton.length >= originalCode.length) {
402
- return void 0;
403
- }
404
- const definitionsBegin = `\u27EAMORPH_DEFINITIONS_BEGIN_${namespace}\u27EB`;
405
- const definitionsEnd = `\u27EAMORPH_DEFINITIONS_END_${namespace}\u27EB`;
406
- const codeBegin = `\u27EAMORPH_CODE_BEGIN_${namespace}\u27EB`;
407
- const serializedDefinitions = values.map((value, id) => `${markers[id]}=${JSON.stringify(value)}`).join("\n");
408
- const code = [
409
- definitionsBegin,
410
- serializedDefinitions,
411
- definitionsEnd,
412
- codeBegin,
413
- skeleton
414
- ].join("\n");
415
- const instructionSuffix = `
416
-
417
- LARGE-FILE ANCHOR PROTOCOL:
418
- The <code> block starts with an exact anchor definition table, then ${codeBegin}, then the source skeleton.
419
- Each ${markerPrefix}N:kind\u27EB placeholder represents the exact source fragment in its matching JSON-string definition. The kind suffix describes its HTML tag, text, or source line.
420
- Return only the updated source skeleton after ${codeBegin}; never return the definition table or protocol delimiters.
421
- Copy a placeholder exactly when its source fragment is unchanged. You may repeat, reorder, or remove placeholders when the requested edit requires it.
422
- To modify an anchored fragment, output the modified source instead of its placeholder.
423
- Do not invent or alter placeholder IDs.`;
424
- const markerPattern = new RegExp(`${escapeRegExp(markerPrefix)}(\\d+):[^\u27EB]+\u27EB`, "g");
425
- return {
426
- code,
427
- instructionSuffix,
428
- anchorCount,
429
- uniqueAnchorCount: values.length,
430
- hasStructuralValidation: expectation !== void 0,
431
- expand(content) {
432
- const codeBeginIndex = content.lastIndexOf(codeBegin);
433
- const skeletonContent = codeBeginIndex >= 0 ? content.slice(codeBeginIndex + codeBegin.length).replace(/^\r?\n/, "") : content;
434
- const expanded = skeletonContent.replace(markerPattern, (marker, idText) => {
435
- const id = Number(idText);
436
- const value = values[id];
437
- return value === void 0 || markers[id] !== marker ? marker : value;
438
- });
439
- if (expanded.includes(markerPrefix)) {
440
- throw new FastApplyAnchorIntegrityError();
441
- }
442
- if (expectation) {
443
- const tagPattern = new RegExp(`<${escapeRegExp(expectation.tag)}(?:\\s|>)`, "gi");
444
- const actualCount = expanded.match(tagPattern)?.length ?? 0;
445
- if (actualCount !== expectation.expectedCount) {
446
- throw new FastApplyAnchorIntegrityError();
447
- }
448
- }
449
- return expanded;
450
- }
451
- };
452
- }
453
- var DEFAULT_MIN_ANCHOR_LINE_LENGTH, DEFAULT_ANCHOR_COMPACTION_THRESHOLD, FastApplyAnchorIntegrityError;
454
- var init_anchors = __esm({
455
- "tools/fastapply/anchors.ts"() {
456
- "use strict";
457
- DEFAULT_MIN_ANCHOR_LINE_LENGTH = 24;
458
- DEFAULT_ANCHOR_COMPACTION_THRESHOLD = 128 * 1024;
459
- FastApplyAnchorIntegrityError = class extends Error {
460
- code = "anchor_integrity_failed";
461
- completionId;
462
- constructor(completionId) {
463
- super(
464
- "Fast Apply failed large-file anchor integrity checks. The partial result was discarded safely."
465
- );
466
- this.name = "FastApplyAnchorIntegrityError";
467
- this.completionId = completionId;
468
- }
469
- };
470
- }
471
- });
472
-
473
- // tools/fastapply/apply.ts
474
- var apply_exports = {};
475
- __export(apply_exports, {
476
- FastApplyAnchorIntegrityError: () => FastApplyAnchorIntegrityError,
477
- FastApplyContextLengthError: () => FastApplyContextLengthError,
478
- applyEdit: () => applyEdit,
479
- callMorphAPI: () => callMorphAPI,
480
- countChanges: () => countChanges,
481
- generateUdiff: () => generateUdiff
482
- });
483
- function isAsyncIterable(value) {
484
- return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
485
- }
486
- async function collectCompletion(response) {
487
- if (!isAsyncIterable(response)) {
488
- const completion = response;
489
- return {
490
- content: completion.choices?.[0]?.message?.content ?? "",
491
- completionId: completion.id,
492
- finishReason: completion.choices?.[0]?.finish_reason
493
- };
494
- }
495
- const content = [];
496
- let completionId;
497
- let finishReason;
498
- for await (const chunk of response) {
499
- completionId = chunk.id ?? completionId;
500
- for (const choice of chunk.choices ?? []) {
501
- if (choice.delta?.content) {
502
- content.push(choice.delta.content);
503
- }
504
- if (choice.finish_reason !== void 0 && choice.finish_reason !== null) {
505
- finishReason = choice.finish_reason;
506
- }
507
- }
508
- }
509
- return { content: content.join(""), completionId, finishReason };
510
- }
511
- function generateUdiff(original, modified, filepath) {
512
- return (0, import_diff.createTwoFilesPatch)(
513
- filepath,
514
- filepath,
515
- original,
516
- modified,
517
- "Original",
518
- "Modified"
519
- );
520
- }
521
- function countChanges(original, modified) {
522
- const diff = generateUdiff(original, modified, "file");
523
- const lines = diff.split("\n");
524
- let linesAdded = 0;
525
- let linesRemoved = 0;
526
- for (const line of lines) {
527
- if (line.startsWith("+") && !line.startsWith("+++")) {
528
- linesAdded++;
529
- } else if (line.startsWith("-") && !line.startsWith("---")) {
530
- linesRemoved++;
531
- }
532
- }
533
- const linesModified = Math.min(linesAdded, linesRemoved);
534
- return {
535
- linesAdded: linesAdded - linesModified,
536
- linesRemoved: linesRemoved - linesModified,
537
- linesModified
538
- };
539
- }
540
- async function callMorphAPI(originalCode, codeEdit, instructions, filepath, config) {
541
- const apiKey = config.morphApiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
542
- const apiUrl = config.morphApiUrl || DEFAULT_API_URL;
543
- const useLarge = config.large ?? (typeof process !== "undefined" ? process.env?.MORPH_LARGE_APPLY !== "false" : true);
544
- const model = useLarge ? "morph-v3-large" : "morph-v3-fast";
545
- const timeout = config.timeout ?? DEFAULT_TIMEOUT2;
546
- const debug = config.debug || false;
547
- if (!apiKey) {
548
- throw new Error(
549
- "Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config."
550
- );
551
- }
552
- const anchorThreshold = config.anchorCompactionThreshold ?? DEFAULT_ANCHOR_COMPACTION_THRESHOLD;
553
- const anchorPlan = config.anchorCompaction !== false && originalCode.length >= anchorThreshold ? createAnchorCompactionPlan(originalCode, [codeEdit, instructions]) : void 0;
554
- const requestCode = anchorPlan?.code ?? originalCode;
555
- const requestInstructions = anchorPlan ? instructions + anchorPlan.instructionSuffix : instructions;
556
- const message = `<instruction>${requestInstructions}</instruction>
557
- <code>${requestCode}</code>
558
- <update>${codeEdit}</update>`;
559
- logger.debug("FastApply", "http_request", {
560
- url: `${apiUrl}/v1/chat/completions`,
561
- model,
562
- filepath,
563
- instruction_len: instructions.length,
564
- original_len: originalCode.length,
565
- request_code_len: requestCode.length,
566
- code_edit_len: codeEdit.length,
567
- anchor_count: anchorPlan?.anchorCount ?? 0,
568
- unique_anchor_count: anchorPlan?.uniqueAnchorCount ?? 0
569
- });
570
- const startTime = Date.now();
571
- const client = new import_openai.default({
572
- apiKey,
573
- baseURL: `${apiUrl}/v1`,
574
- timeout,
575
- maxRetries: config.retryConfig?.maxRetries ?? 3,
576
- defaultHeaders: {
577
- "X-Morph-SDK-Version": SDK_VERSION,
578
- ...anchorPlan ? { "X-Morph-Apply-Context": "extralong" } : {}
579
- }
580
- });
581
- try {
582
- const maxAttempts = anchorPlan?.hasStructuralValidation ? 2 : 1;
583
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
584
- const response = await client.chat.completions.create({
585
- model,
586
- messages: [{ role: "user", content: message }],
587
- stream: true
588
- });
589
- const completion = await collectCompletion(response);
590
- if (completion.finishReason === "length") {
591
- throw new FastApplyContextLengthError(completion.completionId);
592
- }
593
- let content = completion.content;
594
- if (!content) {
595
- throw new Error("Morph API returned empty response");
596
- }
597
- if (anchorPlan) {
598
- try {
599
- content = anchorPlan.expand(content);
600
- } catch (error) {
601
- if (error instanceof FastApplyAnchorIntegrityError) {
602
- if (attempt < maxAttempts) {
603
- logger.warn("FastApply", "anchor_validation_retry", {
604
- attempt,
605
- completion_id: completion.completionId
606
- });
607
- continue;
608
- }
609
- throw new FastApplyAnchorIntegrityError(completion.completionId);
610
- }
611
- throw error;
612
- }
613
- }
614
- const elapsed = Date.now() - startTime;
615
- logger.debug("FastApply", "http_response", { status: 200, completion_id: completion.completionId, content_len: content.length, latency_ms: elapsed });
616
- return { content, completionId: completion.completionId };
617
- }
618
- throw new FastApplyAnchorIntegrityError();
619
- } catch (error) {
620
- const elapsed = Date.now() - startTime;
621
- const status = error?.status || error?.response?.status;
622
- logger.error("FastApply", "http_error", {
623
- status,
624
- error: error?.message,
625
- latency_ms: elapsed
626
- });
627
- if (status === 401) {
628
- const err = new Error(
629
- "Authentication failed: Your Morph API key is invalid or has been revoked. Please visit https://morphllm.com to get a valid API key, then update your MCP configuration."
630
- );
631
- err.status = 401;
632
- throw err;
633
- }
634
- if (status === 429) {
635
- const err = new Error(
636
- "Rate limited: You've exceeded your Morph API usage limits. Please visit https://morphllm.com to check your plan and purchase additional credits."
637
- );
638
- err.status = 429;
639
- throw err;
640
- }
641
- throw error;
642
- }
643
- }
644
- async function applyEdit(input, config = {}) {
645
- const filepath = input.filepath || "file";
646
- try {
647
- logger.debug("FastApply", "apply_edit_start", { original_len: input.originalCode.length, code_edit_len: input.codeEdit.length });
648
- const instruction = input.instruction ?? input.instructions ?? "";
649
- const { content: mergedCode, completionId } = await callMorphAPI(
650
- input.originalCode,
651
- input.codeEdit,
652
- instruction,
653
- filepath,
654
- config
655
- );
656
- const udiff = config.generateUdiff !== false ? generateUdiff(input.originalCode, mergedCode, filepath) : void 0;
657
- const changes = countChanges(input.originalCode, mergedCode);
658
- return {
659
- success: true,
660
- mergedCode,
661
- udiff,
662
- changes,
663
- completionId
664
- };
665
- } catch (error) {
666
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
667
- logger.error("FastApply", "apply_edit_error", { error: errorMessage });
668
- const structuredError = error instanceof FastApplyContextLengthError || error instanceof FastApplyAnchorIntegrityError ? error : void 0;
669
- return {
670
- success: false,
671
- changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
672
- error: errorMessage,
673
- errorCode: structuredError?.code,
674
- completionId: structuredError?.completionId
675
- };
676
- }
677
- }
678
- var import_diff, import_openai, DEFAULT_API_URL, DEFAULT_TIMEOUT2, FastApplyContextLengthError;
679
- var init_apply = __esm({
680
- "tools/fastapply/apply.ts"() {
681
- "use strict";
682
- import_diff = require("diff");
683
- import_openai = __toESM(require("openai"), 1);
684
- init_version();
685
- init_logger();
686
- init_anchors();
687
- init_anchors();
688
- DEFAULT_API_URL = "https://api.morphllm.com";
689
- DEFAULT_TIMEOUT2 = 6e5;
690
- FastApplyContextLengthError = class extends Error {
691
- code = "context_length_exceeded";
692
- completionId;
693
- constructor(completionId) {
694
- super(
695
- "Fast Apply exhausted its context window before producing the complete file. Retry with a smaller input/update or use sparse anchors for unchanged code."
696
- );
697
- this.name = "FastApplyContextLengthError";
698
- this.completionId = completionId;
699
- }
700
- };
701
- }
702
- });
703
-
704
- // tools/warp_grep/agent/config.ts
705
- var parseEnvTimeout, AGENT_CONFIG, BUILTIN_EXCLUDES, DEFAULT_EXCLUDES, DEFAULT_MODEL;
706
- var init_config = __esm({
707
- "tools/warp_grep/agent/config.ts"() {
708
- "use strict";
709
- parseEnvTimeout = (envValue, defaultMs) => {
710
- if (!envValue) return defaultMs;
711
- const parsed = parseInt(envValue, 10);
712
- return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;
713
- };
714
- AGENT_CONFIG = {
715
- MAX_TURNS: 6,
716
- /** Default timeout for model calls. Can be overridden via MORPH_WARP_GREP_TIMEOUT env var (in ms) */
717
- TIMEOUT_MS: parseEnvTimeout(process.env.MORPH_WARP_GREP_TIMEOUT, 6e4),
718
- MAX_CONTEXT_CHARS: 321600,
719
- MAX_OUTPUT_LINES: 200,
720
- MAX_LIST_RESULTS: 500,
721
- MAX_READ_LINES: 800,
722
- MAX_LIST_DEPTH: 3,
723
- LIST_TIMEOUT_MS: 2e3
724
- };
725
- BUILTIN_EXCLUDES = [
726
- // Version control
727
- ".git",
728
- ".svn",
729
- ".hg",
730
- ".bzr",
731
- // Dependencies
732
- "node_modules",
733
- "bower_components",
734
- ".pnpm",
735
- ".yarn",
736
- "vendor",
737
- "packages",
738
- "Pods",
739
- ".bundle",
740
- // Python
741
- "__pycache__",
742
- ".pytest_cache",
743
- ".mypy_cache",
744
- ".ruff_cache",
745
- ".venv",
746
- "venv",
747
- ".tox",
748
- ".nox",
749
- ".eggs",
750
- "*.egg-info",
751
- // Build outputs
752
- "dist",
753
- "build",
754
- "out",
755
- "output",
756
- "target",
757
- "_build",
758
- ".next",
759
- ".nuxt",
760
- ".output",
761
- ".vercel",
762
- ".netlify",
763
- // Cache directories
764
- ".cache",
765
- ".parcel-cache",
766
- ".turbo",
767
- ".nx",
768
- ".gradle",
769
- // IDE/Editor
770
- ".idea",
771
- ".vscode",
772
- ".vs",
773
- // Coverage
774
- "coverage",
775
- ".coverage",
776
- "htmlcov",
777
- ".nyc_output",
778
- // Temporary
779
- "tmp",
780
- "temp",
781
- ".tmp",
782
- ".temp",
783
- // Lock files
784
- "package-lock.json",
785
- "yarn.lock",
786
- "pnpm-lock.yaml",
787
- "bun.lockb",
788
- "Cargo.lock",
789
- "Gemfile.lock",
790
- "poetry.lock",
791
- // Binary/minified
792
- "*.min.js",
793
- "*.min.css",
794
- "*.bundle.js",
795
- "*.wasm",
796
- "*.so",
797
- "*.dll",
798
- "*.pyc",
799
- "*.map",
800
- "*.js.map",
801
- // Hidden directories catch-all
802
- ".*"
803
- ];
804
- DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || "").split(",").map((s) => s.trim()).filter(Boolean).concat(BUILTIN_EXCLUDES);
805
- DEFAULT_MODEL = "morph-warp-grep-v2.1";
806
- }
807
- });
808
-
809
- // tools/warp_grep/utils/ripgrep.ts
810
- function spawnRg(rgBinary, args, opts) {
811
- return new Promise((resolve2) => {
812
- const child = (0, import_child_process.spawn)(rgBinary, args, {
813
- cwd: opts?.cwd,
814
- env: { ...process.env, ...opts?.env || {} },
815
- stdio: ["ignore", "pipe", "pipe"]
816
- });
817
- let stdout = "";
818
- let stderr = "";
819
- child.stdout.on("data", (d) => stdout += d.toString());
820
- child.stderr.on("data", (d) => stderr += d.toString());
821
- child.on("close", (code) => {
822
- resolve2({ stdout, stderr, exitCode: typeof code === "number" ? code : -1 });
823
- });
824
- child.on("error", () => {
825
- resolve2({ stdout: "", stderr: "Failed to spawn ripgrep.", exitCode: -1 });
826
- });
827
- });
828
- }
829
- async function preferredRgPath() {
830
- try {
831
- return (await import("@vscode/ripgrep")).rgPath ?? "rg";
832
- } catch {
833
- return "rg";
834
- }
835
- }
836
- function isBinaryFailure(result) {
837
- if (result.exitCode === -1) return true;
838
- if (result.stderr.includes("jemalloc") || result.stderr.includes("Unsupported system page size")) return true;
839
- if (result.exitCode === 134) return true;
840
- return false;
841
- }
842
- async function runRipgrep(args, opts) {
843
- if (rgPathChecked && resolvedRgPath) {
844
- return spawnRg(resolvedRgPath, args, opts);
845
- }
846
- if (!rgPathChecked) {
847
- const rgPath = await preferredRgPath();
848
- const result = await spawnRg(rgPath, args, opts);
849
- if (!isBinaryFailure(result)) {
850
- resolvedRgPath = rgPath;
851
- rgPathChecked = true;
852
- return result;
853
- }
854
- const fallbackResult = await spawnRg("rg", args, opts);
855
- if (!isBinaryFailure(fallbackResult)) {
856
- resolvedRgPath = "rg";
857
- rgPathChecked = true;
858
- return fallbackResult;
859
- }
860
- rgPathChecked = true;
861
- return {
862
- stdout: "",
863
- stderr: "Failed to spawn ripgrep. Neither bundled nor system rg is available.",
864
- exitCode: -1
865
- };
866
- }
867
- return {
868
- stdout: "",
869
- stderr: "Failed to spawn ripgrep. Neither bundled nor system rg is available.",
870
- exitCode: -1
871
- };
872
- }
873
- var import_child_process, resolvedRgPath, rgPathChecked;
874
- var init_ripgrep = __esm({
875
- "tools/warp_grep/utils/ripgrep.ts"() {
876
- "use strict";
877
- import_child_process = require("child_process");
878
- resolvedRgPath = null;
879
- rgPathChecked = false;
880
- }
881
- });
882
-
883
- // tools/warp_grep/utils/paths.ts
884
- function resolveUnderRepo(repoRoot, targetPath) {
885
- const absRoot = import_path5.default.resolve(repoRoot);
886
- const resolved = import_path5.default.resolve(absRoot, targetPath);
887
- ensureWithinRepo(absRoot, resolved);
888
- return resolved;
889
- }
890
- function ensureWithinRepo(repoRoot, absTarget) {
891
- const rel = import_path5.default.relative(import_path5.default.resolve(repoRoot), import_path5.default.resolve(absTarget));
892
- if (rel.startsWith("..") || import_path5.default.isAbsolute(rel)) {
893
- throw new Error(`Path outside repository root: ${absTarget}`);
894
- }
895
- }
896
- function toRepoRelative2(repoRoot, absPath) {
897
- return import_path5.default.relative(import_path5.default.resolve(repoRoot), import_path5.default.resolve(absPath));
898
- }
899
- function isSymlink(p) {
900
- try {
901
- const st = import_fs.default.lstatSync(p);
902
- return st.isSymbolicLink();
903
- } catch {
904
- return false;
905
- }
906
- }
907
- function fixPathRepetition(fullPath) {
908
- const segments = fullPath.split(import_path5.default.sep).filter(Boolean);
909
- if (segments.length < 2) return null;
910
- for (let len = Math.floor(segments.length / 2); len >= 1; len--) {
911
- for (let i = 0; i <= segments.length - 2 * len; i++) {
912
- const first = segments.slice(i, i + len);
913
- const second = segments.slice(i + len, i + 2 * len);
914
- if (first.every((seg, idx) => seg === second[idx])) {
915
- const fixed = [...segments.slice(0, i), ...segments.slice(i + len)];
916
- return import_path5.default.sep + fixed.join(import_path5.default.sep);
917
- }
918
- }
919
- }
920
- return null;
921
- }
922
- function isTextualFile(filePath, maxBytes = 2e6) {
923
- try {
924
- const st = import_fs.default.statSync(filePath);
925
- if (!st.isFile()) return false;
926
- if (st.size > maxBytes) return false;
927
- const fd = import_fs.default.openSync(filePath, "r");
928
- const buf = Buffer.alloc(512);
929
- const read = import_fs.default.readSync(fd, buf, 0, buf.length, 0);
930
- import_fs.default.closeSync(fd);
931
- for (let i = 0; i < read; i++) {
932
- const c = buf[i];
933
- if (c === 0) return false;
934
- }
935
- return true;
936
- } catch {
937
- return false;
938
- }
939
- }
940
- var import_fs, import_path5;
941
- var init_paths = __esm({
942
- "tools/warp_grep/utils/paths.ts"() {
943
- "use strict";
944
- import_fs = __toESM(require("fs"), 1);
945
- import_path5 = __toESM(require("path"), 1);
946
- }
947
- });
948
-
949
- // tools/warp_grep/utils/files.ts
950
- async function readAllLines(filePath) {
951
- const content = await import_promises.default.readFile(filePath, "utf8");
952
- return content.split(/\r?\n/);
953
- }
954
- var import_promises;
955
- var init_files = __esm({
956
- "tools/warp_grep/utils/files.ts"() {
957
- "use strict";
958
- import_promises = __toESM(require("fs/promises"), 1);
959
- }
960
- });
961
-
962
- // tools/warp_grep/providers/local.ts
963
- var local_exports = {};
964
- __export(local_exports, {
965
- LocalRipgrepProvider: () => LocalRipgrepProvider
966
- });
967
- function shouldSkip2(name, allowNames) {
968
- if (allowNames?.has(name)) return false;
969
- if (SKIP_NAMES2.has(name)) return true;
970
- if (name.startsWith(".")) return true;
971
- for (const ext of SKIP_EXTENSIONS2) {
972
- if (name.endsWith(ext)) return true;
973
- }
974
- return false;
975
- }
976
- var import_promises2, import_path6, SKIP_NAMES2, SKIP_EXTENSIONS2, LocalRipgrepProvider;
977
- var init_local = __esm({
978
- "tools/warp_grep/providers/local.ts"() {
979
- "use strict";
980
- import_promises2 = __toESM(require("fs/promises"), 1);
981
- import_path6 = __toESM(require("path"), 1);
982
- init_ripgrep();
983
- init_paths();
984
- init_files();
985
- init_config();
986
- SKIP_NAMES2 = /* @__PURE__ */ new Set([
987
- // Version control
988
- ".git",
989
- ".svn",
990
- ".hg",
991
- ".bzr",
992
- // Dependencies
993
- "node_modules",
994
- "bower_components",
995
- ".pnpm",
996
- ".yarn",
997
- "vendor",
998
- "Pods",
999
- ".bundle",
1000
- // Python
1001
- "__pycache__",
1002
- ".pytest_cache",
1003
- ".mypy_cache",
1004
- ".ruff_cache",
1005
- ".venv",
1006
- "venv",
1007
- ".tox",
1008
- ".nox",
1009
- ".eggs",
1010
- // Build outputs
1011
- "dist",
1012
- "build",
1013
- "out",
1014
- "output",
1015
- "target",
1016
- "_build",
1017
- ".next",
1018
- ".nuxt",
1019
- ".output",
1020
- ".vercel",
1021
- ".netlify",
1022
- // Cache
1023
- ".cache",
1024
- ".parcel-cache",
1025
- ".turbo",
1026
- ".nx",
1027
- ".gradle",
1028
- // IDE
1029
- ".idea",
1030
- ".vscode",
1031
- ".vs",
1032
- // Coverage
1033
- "coverage",
1034
- ".coverage",
1035
- "htmlcov",
1036
- ".nyc_output",
1037
- // Temp
1038
- "tmp",
1039
- "temp",
1040
- ".tmp",
1041
- ".temp",
1042
- // Lock files
1043
- "package-lock.json",
1044
- "yarn.lock",
1045
- "pnpm-lock.yaml",
1046
- "bun.lockb",
1047
- "Cargo.lock",
1048
- "Gemfile.lock",
1049
- "poetry.lock"
1050
- ]);
1051
- SKIP_EXTENSIONS2 = /* @__PURE__ */ new Set([
1052
- ".min.js",
1053
- ".min.css",
1054
- ".bundle.js",
1055
- ".wasm",
1056
- ".so",
1057
- ".dll",
1058
- ".pyc",
1059
- ".map",
1060
- ".js.map"
1061
- ]);
1062
- LocalRipgrepProvider = class {
1063
- constructor(repoRoot, excludes = DEFAULT_EXCLUDES, options) {
1064
- this.repoRoot = repoRoot;
1065
- this.excludes = excludes;
1066
- if (options?.allowNames?.length) {
1067
- this.allowNames = new Set(options.allowNames);
1068
- }
1069
- }
1070
- allowNames;
1071
- async grep(params) {
1072
- let abs;
1073
- try {
1074
- abs = resolveUnderRepo(this.repoRoot, params.path);
1075
- } catch (err) {
1076
- return {
1077
- lines: [],
1078
- error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`
1079
- };
1080
- }
1081
- const stat = await import_promises2.default.stat(abs).catch(() => null);
1082
- if (!stat) return { lines: [] };
1083
- const targetArg = abs === import_path6.default.resolve(this.repoRoot) ? "." : toRepoRelative2(this.repoRoot, abs);
1084
- const contextLines = params.context_lines !== void 0 ? String(params.context_lines) : "1";
1085
- const args = [
1086
- "--no-config",
1087
- "--no-heading",
1088
- "--with-filename",
1089
- "--line-number",
1090
- "--color=never",
1091
- "--trim",
1092
- "--max-columns=400",
1093
- "-C",
1094
- contextLines,
1095
- ...params.case_sensitive === false ? ["--ignore-case"] : [],
1096
- ...params.glob ? ["--glob", params.glob] : [],
1097
- ...this.excludes.filter((e) => !this.allowNames?.has(e)).flatMap((e) => ["-g", `!${e}`]),
1098
- params.pattern,
1099
- targetArg || "."
1100
- ];
1101
- const res = await runRipgrep(args, { cwd: this.repoRoot });
1102
- if (res.exitCode === -1) {
1103
- return {
1104
- lines: [],
1105
- error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required but failed to execute. Please install it:
1106
- \u2022 macOS: brew install ripgrep
1107
- \u2022 Ubuntu/Debian: apt install ripgrep
1108
- \u2022 Windows: choco install ripgrep
1109
- \u2022 Or visit: https://github.com/BurntSushi/ripgrep#installation
1110
- Exit code: ${res.exitCode}${res.stderr ? `
1111
- Details: ${res.stderr}` : ""}`
1112
- };
1113
- }
1114
- if (res.exitCode !== 0 && res.exitCode !== 1) {
1115
- return {
1116
- lines: [],
1117
- error: `[RIPGREP ERROR] grep failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ""}`
1118
- };
1119
- }
1120
- const lines = (res.stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
1121
- if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {
1122
- const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);
1123
- truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);
1124
- return { lines: truncated };
1125
- }
1126
- return { lines };
1127
- }
1128
- async read(params) {
1129
- let abs;
1130
- try {
1131
- abs = resolveUnderRepo(this.repoRoot, params.path);
1132
- } catch (err) {
1133
- return {
1134
- lines: [],
1135
- error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`
1136
- };
1137
- }
1138
- let stat = await import_promises2.default.stat(abs).catch(() => null);
1139
- if (!stat || !stat.isFile()) {
1140
- const fixedPath = fixPathRepetition(abs);
1141
- if (fixedPath) {
1142
- const fixedStat = await import_promises2.default.stat(fixedPath).catch(() => null);
1143
- if (fixedStat?.isFile()) {
1144
- abs = fixedPath;
1145
- stat = fixedStat;
1146
- }
1147
- }
1148
- }
1149
- if (!stat || !stat.isFile()) {
1150
- return {
1151
- lines: [],
1152
- 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.`
1153
- };
1154
- }
1155
- if (isSymlink(abs)) {
1156
- return {
1157
- lines: [],
1158
- error: `[SYMLINK] You tried to read "${params.path}" but this is a symlink. Try reading the actual file it points to instead.`
1159
- };
1160
- }
1161
- if (!isTextualFile(abs)) {
1162
- return {
1163
- lines: [],
1164
- 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.`
1165
- };
1166
- }
1167
- let lines;
1168
- try {
1169
- lines = await readAllLines(abs);
1170
- } catch (err) {
1171
- return {
1172
- lines: [],
1173
- error: `[READ ERROR] Failed to read "${params.path}": ${err instanceof Error ? err.message : String(err)}`
1174
- };
1175
- }
1176
- const total = lines.length;
1177
- const rawStart = params.start;
1178
- const rawEnd = params.end;
1179
- let s = 1;
1180
- let e = total;
1181
- const startValid = rawStart === void 0 || Number.isFinite(rawStart) && rawStart > 0;
1182
- const endValid = rawEnd === void 0 || Number.isFinite(rawEnd) && rawEnd > 0;
1183
- if (startValid && endValid) {
1184
- s = rawStart ?? 1;
1185
- e = Math.min(rawEnd ?? total, total);
1186
- if (s > total && total > 0 || s > e) {
1187
- s = 1;
1188
- e = total;
1189
- }
1190
- }
1191
- const out = [];
1192
- for (let i = s; i <= e; i += 1) {
1193
- const content = lines[i - 1] ?? "";
1194
- out.push(`${i}|${content}`);
1195
- }
1196
- if (out.length > AGENT_CONFIG.MAX_READ_LINES) {
1197
- const truncated = out.slice(0, AGENT_CONFIG.MAX_READ_LINES);
1198
- truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${out.length} lines)`);
1199
- return { lines: truncated };
1200
- }
1201
- return { lines: out };
1202
- }
1203
- async listDirectory(params) {
1204
- let abs;
1205
- try {
1206
- abs = resolveUnderRepo(this.repoRoot, params.path);
1207
- } catch {
1208
- return [];
1209
- }
1210
- const stat = await import_promises2.default.stat(abs).catch(() => null);
1211
- if (!stat || !stat.isDirectory()) {
1212
- return [];
1213
- }
1214
- const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
1215
- const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
1216
- const regex = params.pattern ? new RegExp(params.pattern) : null;
1217
- const repoRoot = this.repoRoot;
1218
- const allowNames = this.allowNames;
1219
- const results = [];
1220
- let timedOut = false;
1221
- const startTime = Date.now();
1222
- async function walk(dir, depth) {
1223
- if (Date.now() - startTime > AGENT_CONFIG.LIST_TIMEOUT_MS) {
1224
- timedOut = true;
1225
- return;
1226
- }
1227
- if (depth > maxDepth || results.length >= maxResults) return;
1228
- let entries;
1229
- try {
1230
- entries = await import_promises2.default.readdir(dir, { withFileTypes: true });
1231
- } catch {
1232
- return;
1233
- }
1234
- for (const entry of entries) {
1235
- if (timedOut || results.length >= maxResults) break;
1236
- if (shouldSkip2(entry.name, allowNames)) continue;
1237
- if (regex && !regex.test(entry.name)) continue;
1238
- const full = import_path6.default.join(dir, entry.name);
1239
- const isDir = entry.isDirectory();
1240
- results.push({
1241
- name: entry.name,
1242
- path: toRepoRelative2(repoRoot, full),
1243
- type: isDir ? "dir" : "file",
1244
- depth
1245
- });
1246
- if (isDir) {
1247
- await walk(full, depth + 1);
1248
- }
1249
- }
1250
- }
1251
- await walk(abs, 0);
1252
- return results;
1253
- }
1254
- async glob(params) {
1255
- let abs;
1256
- try {
1257
- abs = params.path ? resolveUnderRepo(this.repoRoot, params.path) : this.repoRoot;
1258
- } catch (err) {
1259
- return { files: [], searchDir: this.repoRoot, totalFound: 0, error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}` };
1260
- }
1261
- const stat = await import_promises2.default.stat(abs).catch(() => null);
1262
- if (!stat || !stat.isDirectory()) {
1263
- return { files: [], searchDir: abs, totalFound: 0, error: `[PATH ERROR] Directory not found: ${params.path || "."}` };
1264
- }
1265
- const targetArg = abs === import_path6.default.resolve(this.repoRoot) ? "." : toRepoRelative2(this.repoRoot, abs);
1266
- const args = [
1267
- "--no-config",
1268
- "--files",
1269
- "--color=never",
1270
- "-g",
1271
- params.pattern,
1272
- ...this.excludes.filter((e) => !this.allowNames?.has(e)).flatMap((e) => ["-g", `!${e}`]),
1273
- targetArg || "."
1274
- ];
1275
- const res = await runRipgrep(args, { cwd: this.repoRoot });
1276
- if (res.exitCode === -1) {
1277
- return { files: [], searchDir: abs, totalFound: 0, error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required for glob search.` };
1278
- }
1279
- if (res.exitCode !== 0 && res.exitCode !== 1) {
1280
- return { files: [], searchDir: abs, totalFound: 0, error: `[GLOB ERROR] glob failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ""}` };
1281
- }
1282
- const absRoot = import_path6.default.resolve(this.repoRoot);
1283
- const relFiles = (res.stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
1284
- const absFiles = relFiles.map((f) => import_path6.default.resolve(absRoot, f));
1285
- const withMtime = [];
1286
- for (const f of absFiles) {
1287
- const s = await import_promises2.default.stat(f).catch(() => null);
1288
- withMtime.push({ file: f, mtime: s?.mtimeMs ?? 0 });
1289
- }
1290
- withMtime.sort((a, b) => b.mtime - a.mtime);
1291
- const totalFound = withMtime.length;
1292
- return { files: withMtime.slice(0, 100).map((f) => f.file), searchDir: abs, totalFound };
1293
- }
1294
- };
1295
- }
1296
- });
1297
-
1298
- // index.ts
1299
- var index_exports = {};
1300
- __export(index_exports, {
1301
- APIResource: () => APIResource,
1302
- AnthropicRouter: () => AnthropicRouter,
1303
- AnthropicToolFactory: () => AnthropicToolFactory,
1304
- CompactClient: () => CompactClient,
1305
- FastApplyAnchorIntegrityError: () => FastApplyAnchorIntegrityError,
1306
- FastApplyClient: () => FastApplyClient,
1307
- FastApplyContextLengthError: () => FastApplyContextLengthError,
1308
- GeminiRouter: () => GeminiRouter,
1309
- LocalRipgrepProvider: () => LocalRipgrepProvider,
1310
- MorphAPIClient: () => MorphAPIClient,
1311
- MorphClient: () => MorphClient,
1312
- OpenAIRouter: () => OpenAIRouter,
1313
- OpenAIToolFactory: () => OpenAIToolFactory,
1314
- RawRouter: () => RawRouter,
1315
- SDK_VERSION: () => SDK_VERSION,
1316
- VercelToolFactory: () => VercelToolFactory,
1317
- WarpGrepClient: () => WarpGrepClient,
1318
- applyEdit: () => applyEdit
1319
- });
1320
- module.exports = __toCommonJS(index_exports);
1321
- init_version();
1322
-
1323
- // tools/utils/resilience.ts
1324
- init_version();
1325
- var DEFAULT_RETRY_CONFIG = {
1326
- maxRetries: 3,
1327
- initialDelay: 1e3,
1328
- maxDelay: 3e4,
1329
- backoffMultiplier: 2,
1330
- retryableErrors: ["ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND"]
1331
- };
1332
- async function fetchWithRetry(url, options, retryConfig = {}) {
1333
- const {
1334
- maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,
1335
- initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,
1336
- maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,
1337
- backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,
1338
- retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,
1339
- onRetry
1340
- } = retryConfig;
1341
- let lastError = null;
1342
- let delay = initialDelay;
1343
- options = { ...options, headers: { "X-Morph-SDK-Version": SDK_VERSION, ...options.headers } };
1344
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
1345
- try {
1346
- const response = await fetch(url, options);
1347
- if (response.status === 429 || response.status === 503) {
1348
- if (attempt < maxRetries) {
1349
- const retryAfter = response.headers.get("Retry-After");
1350
- const waitTime = retryAfter ? parseInt(retryAfter) * 1e3 : Math.min(delay, maxDelay);
1351
- const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);
1352
- if (onRetry) {
1353
- onRetry(attempt + 1, error);
1354
- }
1355
- await sleep(waitTime);
1356
- delay *= backoffMultiplier;
1357
- continue;
1358
- }
1359
- }
1360
- return response;
1361
- } catch (error) {
1362
- lastError = error;
1363
- const isRetryable = retryableErrors.some(
1364
- (errType) => lastError?.message?.includes(errType)
1365
- );
1366
- if (!isRetryable || attempt === maxRetries) {
1367
- throw lastError;
1368
- }
1369
- const waitTime = Math.min(delay, maxDelay);
1370
- if (onRetry) {
1371
- onRetry(attempt + 1, lastError);
1372
- }
1373
- await sleep(waitTime);
1374
- delay *= backoffMultiplier;
1375
- }
1376
- }
1377
- throw lastError || new Error("Max retries exceeded");
1378
- }
1379
- async function withTimeout(promise, timeoutMs, errorMessage) {
1380
- let timeoutId;
1381
- const timeoutPromise = new Promise((_, reject) => {
1382
- timeoutId = setTimeout(() => {
1383
- reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));
1384
- }, timeoutMs);
1385
- });
1386
- try {
1387
- const result = await Promise.race([promise, timeoutPromise]);
1388
- clearTimeout(timeoutId);
1389
- return result;
1390
- } catch (error) {
1391
- clearTimeout(timeoutId);
1392
- throw error;
1393
- }
1394
- }
1395
- function sleep(ms) {
1396
- return new Promise((resolve2) => setTimeout(resolve2, ms));
1397
- }
1398
- var MorphError = class extends Error {
1399
- constructor(message, code, statusCode, retryable = false) {
1400
- super(message);
1401
- this.code = code;
1402
- this.statusCode = statusCode;
1403
- this.retryable = retryable;
1404
- this.name = "MorphError";
1405
- }
1406
- };
1407
-
1408
- // core/client.ts
1409
- init_logger();
1410
- init_version();
1411
-
1412
- // core/error.ts
1413
- async function toMorphError(response) {
1414
- let message = `Morph API request failed (${response.status})`;
1415
- let code = "api_error";
1416
- try {
1417
- const body = await response.json();
1418
- message = body.error?.message ?? body.message ?? message;
1419
- code = body.error?.code ?? body.error?.type ?? code;
1420
- } catch {
1421
- }
1422
- if (response.status === 401) code = "authentication_error";
1423
- if (response.status === 429) code = "rate_limit_exceeded";
1424
- const retryable = response.status === 429 || response.status === 503;
1425
- return new MorphError(message, code, response.status, retryable);
1426
- }
1427
-
1428
- // core/client.ts
1429
- var DEFAULT_BASE_URL = "https://api.morphllm.com";
1430
- var DEFAULT_REPOS_URL = "https://repos.morphllm.com";
1431
- var DEFAULT_TIMEOUT = 6e4;
1432
- var env = (name) => typeof process !== "undefined" ? process.env?.[name] : void 0;
1433
- var stripTrailingSlash = (url) => url.replace(/\/+$/, "");
1434
- var MorphAPIClient = class {
1435
- /** Explicit key as provided; resolved against env at request time. */
1436
- apiKey;
1437
- baseURL;
1438
- reposURL;
1439
- /** Explicit default timeout (ms), if set. The request default is applied lazily so
1440
- * resources can read an undefined value and supply their own fallback. */
1441
- timeout;
1442
- retryConfig;
1443
- debug;
1444
- constructor(options = {}) {
1445
- this.apiKey = options.apiKey;
1446
- this.baseURL = stripTrailingSlash(options.baseURL ?? DEFAULT_BASE_URL);
1447
- this.reposURL = stripTrailingSlash(options.reposURL ?? env("MORPH_SEARCH_URL") ?? DEFAULT_REPOS_URL);
1448
- this.timeout = options.timeout;
1449
- this.retryConfig = options.retryConfig;
1450
- this.debug = options.debug ?? false;
1451
- if (this.debug) logger.enable();
1452
- }
1453
- /** The key actually used for requests: explicit, else `MORPH_API_KEY`. */
1454
- resolveApiKey() {
1455
- return this.apiKey ?? env("MORPH_API_KEY");
1456
- }
1457
- /** Headers shared with tools that bring their own HTTP client (FastApply/WarpGrep via the `openai` package). */
1458
- defaultHeaders() {
1459
- return { "X-Morph-SDK-Version": SDK_VERSION };
1460
- }
1461
- buildURL(path6, baseURL) {
1462
- if (/^https?:\/\//i.test(path6)) return path6;
1463
- const base = stripTrailingSlash(baseURL ?? this.baseURL);
1464
- return `${base}${path6.startsWith("/") ? "" : "/"}${path6}`;
1465
- }
1466
- buildHeaders(apiKey, extra) {
1467
- return {
1468
- "Content-Type": "application/json",
1469
- "X-Morph-SDK-Version": SDK_VERSION,
1470
- Authorization: `Bearer ${apiKey}`,
1471
- ...extra
1472
- };
1473
- }
1474
- applyQuery(url, query) {
1475
- if (!query) return url;
1476
- const params = new URLSearchParams();
1477
- for (const [key, value] of Object.entries(query)) {
1478
- if (value !== void 0 && value !== null) params.set(key, String(value));
1479
- }
1480
- const qs = params.toString();
1481
- return qs ? `${url}${url.includes("?") ? "&" : "?"}${qs}` : url;
1482
- }
1483
- async request(method, path6, opts = {}) {
1484
- const apiKey = this.resolveApiKey();
1485
- if (!apiKey) {
1486
- throw new MorphError(
1487
- "Morph API key not found. Set the MORPH_API_KEY environment variable or pass apiKey in config.",
1488
- "missing_api_key",
1489
- 401
1490
- );
1491
- }
1492
- const url = this.applyQuery(this.buildURL(path6, opts.baseURL), opts.query);
1493
- const timeout = opts.timeout ?? this.timeout ?? DEFAULT_TIMEOUT;
1494
- const init = {
1495
- method,
1496
- headers: this.buildHeaders(apiKey, opts.headers),
1497
- ...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
1498
- ...opts.signal ? { signal: opts.signal } : {}
1499
- };
1500
- logger.debug("MorphAPIClient", "request", { method, url });
1501
- const response = await withTimeout(
1502
- fetchWithRetry(url, init, this.retryConfig ?? {}),
1503
- timeout,
1504
- `Morph request to ${url} timed out after ${timeout}ms`
1505
- );
1506
- if (!response.ok) throw await toMorphError(response);
1507
- if (opts.stream) return response;
1508
- if (response.status === 204) return void 0;
1509
- const text = await response.text();
1510
- return text ? JSON.parse(text) : void 0;
1511
- }
1512
- get(path6, opts) {
1513
- return this.request("GET", path6, opts);
1514
- }
1515
- post(path6, opts) {
1516
- return this.request("POST", path6, opts);
1517
- }
1518
- delete(path6, opts) {
1519
- return this.request("DELETE", path6, opts);
1520
- }
1521
- };
1522
-
1523
- // client.ts
1524
- init_logger();
1525
-
1526
- // tools/fastapply/core.ts
1527
- var import_path = require("path");
1528
- init_logger();
1529
-
1530
- // core/resource.ts
1531
- var APIResource = class {
1532
- _client;
1533
- constructor(client) {
1534
- this._client = client;
1535
- }
1536
- };
1537
-
1538
- // tools/fastapply/core.ts
1539
- init_apply();
1540
- init_apply();
1541
- var DEFAULT_CONFIG = {
1542
- morphApiUrl: "https://api.morphllm.com",
1543
- baseDir: process.cwd(),
1544
- generateUdiff: true,
1545
- autoWrite: true,
1546
- timeout: 6e5,
1547
- anchorCompaction: true,
1548
- anchorCompactionThreshold: 128 * 1024,
1549
- debug: false
1550
- };
1551
- var FastApplyClient = class extends APIResource {
1552
- config;
1553
- constructor(clientOrConfig = {}) {
1554
- const isClient = clientOrConfig instanceof MorphAPIClient;
1555
- super(
1556
- isClient ? clientOrConfig : new MorphAPIClient({
1557
- apiKey: clientOrConfig.apiKey,
1558
- timeout: clientOrConfig.timeout ?? DEFAULT_CONFIG.timeout,
1559
- retryConfig: clientOrConfig.retryConfig,
1560
- debug: clientOrConfig.debug
1561
- })
1562
- );
1563
- this.config = {
1564
- morphApiKey: this._client.resolveApiKey(),
1565
- morphApiUrl: this._client.baseURL,
1566
- debug: this._client.debug,
1567
- timeout: (isClient ? void 0 : clientOrConfig.timeout) ?? DEFAULT_CONFIG.timeout,
1568
- retryConfig: this._client.retryConfig,
1569
- generateUdiff: DEFAULT_CONFIG.generateUdiff,
1570
- autoWrite: DEFAULT_CONFIG.autoWrite
1571
- };
1572
- }
1573
- /**
1574
- * Execute a file edit operation
1575
- *
1576
- * @param input - Edit parameters including filepath, instructions, and code_edit
1577
- * @param overrides - Optional config overrides for this operation
1578
- * @returns Edit result with success status and changes
1579
- */
1580
- async execute(input, overrides) {
1581
- return executeEditFile(input, { ...this.config, ...overrides });
1582
- }
1583
- /**
1584
- * Apply an edit to code directly without file I/O
1585
- *
1586
- * Useful for sandbox environments or when you manage your own file system.
1587
- * Compatible with the earlier OpenAI client API contract.
1588
- *
1589
- * @param input - Code and edit parameters
1590
- * @param overrides - Optional config overrides for this operation
1591
- * @returns Result with merged code
1592
- *
1593
- * @example
1594
- * ```typescript
1595
- * const result = await client.applyEdit({
1596
- * originalCode: 'function hello() { return "world"; }',
1597
- * codeEdit: 'function hello() { return "universe"; }',
1598
- * instructions: 'Change return value'
1599
- * });
1600
- * console.log(result.mergedCode);
1601
- * ```
1602
- */
1603
- async applyEdit(input, overrides) {
1604
- const { applyEdit: applyEdit2 } = await Promise.resolve().then(() => (init_apply(), apply_exports));
1605
- return applyEdit2(input, { ...this.config, ...overrides });
1606
- }
1607
- };
1608
- async function executeEditFile(input, config = {}) {
1609
- const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;
1610
- const fullPath = (0, import_path.resolve)((0, import_path.join)(baseDir, input.target_filepath));
1611
- logger.debug("FastApply", "execute_start", { target_filepath: input.target_filepath, baseDir, autoWrite: config.autoWrite !== false });
1612
- const relativePath = (0, import_path.relative)(baseDir, fullPath);
1613
- if (relativePath.startsWith("..") || fullPath === baseDir) {
1614
- logger.warn("FastApply", "security_check_failed", { target_filepath: input.target_filepath, relative: relativePath });
1615
- return {
1616
- success: false,
1617
- filepath: input.target_filepath,
1618
- changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
1619
- error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`
1620
- };
1621
- }
1622
- logger.debug("FastApply", "security_check", { resolved: fullPath, relative: relativePath });
1623
- try {
1624
- const { readFile, writeFile } = await import("fs/promises");
1625
- const { callMorphAPI: callMorphAPI2, generateUdiff: generateUdiff2, countChanges: countChanges2 } = await Promise.resolve().then(() => (init_apply(), apply_exports));
1626
- let originalCode = "";
1627
- let fileExists = true;
1628
- try {
1629
- originalCode = await readFile(fullPath, "utf-8");
1630
- logger.debug("FastApply", "file_read", { path: fullPath, exists: true, size_bytes: originalCode.length });
1631
- } catch (error) {
1632
- if (error.code !== "ENOENT") {
1633
- throw error;
1634
- }
1635
- fileExists = false;
1636
- logger.debug("FastApply", "file_read", { path: fullPath, exists: false });
1637
- }
1638
- const instruction = input.instruction ?? input.instructions ?? "";
1639
- logger.debug("FastApply", "api_call", { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });
1640
- const { content: mergedCode, completionId } = await callMorphAPI2(originalCode, input.code_edit, instruction, input.target_filepath, config);
1641
- logger.debug("FastApply", "api_response", { completion_id: completionId, merged_len: mergedCode.length });
1642
- const udiff = config.generateUdiff !== false ? generateUdiff2(originalCode, mergedCode, input.target_filepath) : void 0;
1643
- if (config.autoWrite !== false) {
1644
- await writeFile(fullPath, mergedCode, "utf-8");
1645
- logger.debug("FastApply", "file_write", { path: fullPath, size_bytes: mergedCode.length });
1646
- }
1647
- const changes = countChanges2(originalCode, mergedCode);
1648
- logger.debug("FastApply", "changes", { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });
1649
- return {
1650
- success: true,
1651
- filepath: input.target_filepath,
1652
- udiff,
1653
- changes,
1654
- completionId
1655
- };
1656
- } catch (error) {
1657
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1658
- const structuredError = error instanceof FastApplyContextLengthError || error instanceof FastApplyAnchorIntegrityError ? error : void 0;
1659
- logger.error("FastApply", "execute_error", { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : void 0 });
1660
- return {
1661
- success: false,
1662
- filepath: input.target_filepath,
1663
- changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
1664
- error: errorMessage,
1665
- errorCode: structuredError?.code,
1666
- completionId: structuredError?.completionId
1667
- };
1668
- }
1669
- }
1670
-
1671
- // tools/warp_grep/agent/runner.ts
1672
- init_config();
1673
-
1674
- // tools/warp_grep/agent/parser.ts
1675
- function parseReadLines(linesStr) {
1676
- const ranges = [];
1677
- for (const rangeStr of linesStr.split(",")) {
1678
- const trimmed = rangeStr.trim();
1679
- if (!trimmed) continue;
1680
- const parts = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
1681
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
1682
- ranges.push([parts[0], parts[1]]);
1683
- } else if (Number.isFinite(parts[0])) {
1684
- ranges.push([parts[0], parts[0]]);
1685
- }
1686
- }
1687
- if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };
1688
- if (ranges.length > 1) return { lines: ranges };
1689
- return {};
1690
- }
1691
- function parseFinishFiles(filesStr) {
1692
- const files = [];
1693
- for (const line of filesStr.trim().split(/\s+/)) {
1694
- const trimmed = line.trim();
1695
- if (!trimmed) continue;
1696
- const searchFrom = /^[A-Za-z]:/.test(trimmed) ? 2 : 0;
1697
- const colonIdx = trimmed.indexOf(":", searchFrom);
1698
- if (colonIdx === -1) {
1699
- files.push({ path: trimmed, lines: "*" });
1700
- continue;
1701
- }
1702
- const filePath = trimmed.slice(0, colonIdx);
1703
- const rangesPart = trimmed.slice(colonIdx + 1);
1704
- if (!rangesPart.trim() || rangesPart.trim() === "*") {
1705
- files.push({ path: filePath, lines: "*" });
1706
- continue;
1707
- }
1708
- const ranges = [];
1709
- for (const rangeStr of rangesPart.split(",")) {
1710
- const rt = rangeStr.trim();
1711
- if (!rt) continue;
1712
- const parts = rt.split("-").map((v) => parseInt(v.trim(), 10));
1713
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
1714
- ranges.push([parts[0], parts[1]]);
1715
- } else if (Number.isFinite(parts[0])) {
1716
- ranges.push([parts[0], parts[0]]);
1717
- }
1718
- }
1719
- files.push({ path: filePath, lines: ranges.length > 0 ? ranges : "*" });
1720
- }
1721
- return files;
1722
- }
1723
- function extractPathFromCommand(command) {
1724
- const tokens = command.trim().split(/\s+/);
1725
- const pathTokens = tokens.slice(1).filter((t) => !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("\\("));
1726
- return pathTokens[0] || ".";
1727
- }
1728
-
1729
- // tools/warp_grep/agent/tools/grep.ts
1730
- async function toolGrep(provider, args) {
1731
- const res = await provider.grep(args);
1732
- if (res.error) {
1733
- return { output: res.error };
1734
- }
1735
- if (!res.lines.length) {
1736
- return { output: "no matches" };
1737
- }
1738
- return { output: res.lines.join("\n") };
1739
- }
1740
-
1741
- // tools/warp_grep/agent/tools/read.ts
1742
- function isValidRange(start, end) {
1743
- return typeof start === "number" && typeof end === "number" && Number.isFinite(start) && Number.isFinite(end) && start > 0 && end >= start;
1744
- }
1745
- async function toolRead(provider, args) {
1746
- if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {
1747
- const validRanges = [];
1748
- for (const range of args.lines) {
1749
- if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {
1750
- validRanges.push([range[0], range[1]]);
1751
- }
1752
- }
1753
- if (validRanges.length === 0) {
1754
- const res2 = await provider.read({ path: args.path });
1755
- if (res2.error) return res2.error;
1756
- if (!res2.lines.length) return "(empty file)";
1757
- return res2.lines.join("\n");
1758
- }
1759
- const chunks = [];
1760
- for (const [start, end] of validRanges) {
1761
- const res2 = await provider.read({ path: args.path, start, end });
1762
- if (res2.error) return res2.error;
1763
- chunks.push(res2.lines.join("\n"));
1764
- }
1765
- if (chunks.every((c) => c === "")) return "(empty file)";
1766
- return chunks.join("\n...\n");
1767
- }
1768
- const res = await provider.read({ path: args.path, start: args.start, end: args.end });
1769
- if (res.error) {
1770
- return res.error;
1771
- }
1772
- if (!res.lines.length) return "(empty file)";
1773
- return res.lines.join("\n");
1774
- }
1775
-
1776
- // tools/warp_grep/agent/tools/list_directory.ts
1777
- init_config();
1778
- var import_path2 = __toESM(require("path"), 1);
1779
- async function toolListDirectory(provider, args, repoRoot) {
1780
- const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;
1781
- const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
1782
- const entries = await provider.listDirectory({
1783
- path: args.path,
1784
- pattern: args.pattern ?? null,
1785
- maxResults,
1786
- maxDepth
1787
- });
1788
- if (!entries.length) return "empty";
1789
- if (repoRoot) {
1790
- const absRoot = repoRoot;
1791
- const lines = entries.map((e) => import_path2.default.join(absRoot, e.path));
1792
- return lines.join("\n");
1793
- }
1794
- return entries.map((e) => e.path).join("\n");
1795
- }
1796
-
1797
- // tools/warp_grep/agent/tools/glob.ts
1798
- async function toolGlob(provider, args) {
1799
- const res = await provider.glob(args);
1800
- if (res.error) {
1801
- return res.error;
1802
- }
1803
- if (!res.files.length) {
1804
- return "no matches";
1805
- }
1806
- const header = `Found ${res.totalFound} file(s) matching "${args.pattern}" within ${res.searchDir}, sorted by modification time (newest first):`;
1807
- const body = res.files.join("\n");
1808
- const truncated = res.totalFound > res.files.length ? `
1809
- [${res.totalFound - res.files.length} files truncated]` : "";
1810
- return `${header}
1811
- ---
1812
- ${body}
1813
- ---${truncated}`;
1814
- }
1815
-
1816
- // tools/warp_grep/agent/tools/finish.ts
1817
- function isValidRange2(range) {
1818
- 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];
1819
- }
1820
- function extractValidRanges(lines) {
1821
- if (!Array.isArray(lines)) return null;
1822
- const valid = [];
1823
- for (const range of lines) {
1824
- if (isValidRange2(range)) {
1825
- valid.push([range[0], range[1]]);
1826
- }
1827
- }
1828
- return valid.length > 0 ? valid : null;
1829
- }
1830
- async function readFinishFiles(repoRoot, files, reader) {
1831
- const out = [];
1832
- for (const f of files) {
1833
- const validRanges = f.lines === "*" ? null : extractValidRanges(f.lines);
1834
- if (f.lines === "*" || !validRanges) {
1835
- const lines = await reader(f.path);
1836
- out.push({ path: f.path, ranges: "*", content: lines.join("\n") });
1837
- } else {
1838
- const ranges = mergeRanges(validRanges);
1839
- const chunks = [];
1840
- for (let i = 0; i < ranges.length; i++) {
1841
- const [s, e] = ranges[i];
1842
- if (i === 0 && s > 1) {
1843
- chunks.push(`// ... existing code, block starting at line ${s} ...`);
1844
- } else if (i > 0) {
1845
- chunks.push(`// ... existing code, block starting at line ${s} ...`);
1846
- }
1847
- const lines = await reader(f.path, s, e);
1848
- chunks.push(lines.join("\n"));
1849
- }
1850
- out.push({ path: f.path, ranges, content: chunks.join("\n") });
1851
- }
1852
- }
1853
- return out;
1854
- }
1855
- function mergeRanges(ranges) {
1856
- if (!ranges.length) return [];
1857
- const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
1858
- const merged = [];
1859
- let [cs, ce] = sorted[0];
1860
- for (let i = 1; i < sorted.length; i++) {
1861
- const [s, e] = sorted[i];
1862
- if (s <= ce + 1) {
1863
- ce = Math.max(ce, e);
1864
- } else {
1865
- merged.push([cs, ce]);
1866
- cs = s;
1867
- ce = e;
1868
- }
1869
- }
1870
- merged.push([cs, ce]);
1871
- return merged;
1872
- }
1873
-
1874
- // tools/warp_grep/agent/helpers.ts
1875
- var import_path3 = __toESM(require("path"), 1);
1876
- init_config();
1877
- var TRUNCATED_MARKER = "[truncated for context limit]";
1878
- function getMessageSize(m) {
1879
- if (m.role === "tool") return m.content.length;
1880
- if (m.role === "assistant") {
1881
- let size = typeof m.content === "string" ? m.content.length : 0;
1882
- if (m.tool_calls) {
1883
- size += m.tool_calls.reduce((s, tc) => s + tc.function.name.length + tc.function.arguments.length, 0);
1884
- }
1885
- return size;
1886
- }
1887
- return m.content.length;
1888
- }
1889
- function formatTurnMessage(turnsUsed, maxTurns) {
1890
- const turnsRemaining = maxTurns - turnsUsed;
1891
- if (turnsRemaining === 1) {
1892
- return `
1893
- 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`;
1894
- }
1895
- return `
1896
- You have used ${turnsUsed} turn${turnsUsed === 1 ? "" : "s"} and have ${turnsRemaining} remaining`;
1897
- }
1898
- function calculateContextBudget(messages) {
1899
- const totalChars = messages.reduce((sum, m) => sum + getMessageSize(m), 0);
1900
- const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;
1901
- const percent = Math.floor(totalChars / maxChars * 100);
1902
- const usedK = Math.floor(totalChars / 1e3);
1903
- const maxK = Math.floor(maxChars / 1e3);
1904
- return `<context_budget>${percent}% (${usedK}K/${maxK}K chars)</context_budget>`;
1905
- }
1906
- async function buildInitialState(repoRoot, searchTerm, provider, options) {
1907
- const budget = calculateContextBudget([]);
1908
- const turnTag = `You have used 0 turns and have ${AGENT_CONFIG.MAX_TURNS} remaining`;
1909
- const treeDepth = options?.search_type === "node_modules" ? 1 : 2;
1910
- const absRoot = repoRoot;
1911
- try {
1912
- const entries = await provider.listDirectory({
1913
- path: ".",
1914
- maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,
1915
- maxDepth: treeDepth
1916
- });
1917
- const lines = [absRoot];
1918
- for (const e of entries) {
1919
- lines.push(import_path3.default.join(absRoot, e.path));
1920
- }
1921
- return `<repo_structure>
1922
- ${lines.join("\n")}
1923
- </repo_structure>
1924
-
1925
- <search_string>
1926
- ${searchTerm}
1927
- </search_string>
1928
- ${budget}
1929
- ${turnTag}`;
1930
- } catch {
1931
- return `<repo_structure>
1932
- ${absRoot}
1933
- </repo_structure>
1934
-
1935
- <search_string>
1936
- ${searchTerm}
1937
- </search_string>
1938
- ${budget}
1939
- ${turnTag}`;
1940
- }
1941
- }
1942
- function enforceContextLimit(messages, maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS) {
1943
- const getTotalChars = () => messages.reduce((sum, m) => sum + getMessageSize(m), 0);
1944
- if (getTotalChars() <= maxChars) {
1945
- return messages;
1946
- }
1947
- const truncatableIndices = [];
1948
- let firstUserSkipped = false;
1949
- for (let i = 0; i < messages.length; i++) {
1950
- const m = messages[i];
1951
- if (m.role === "tool") {
1952
- truncatableIndices.push(i);
1953
- } else if (m.role === "user") {
1954
- if (!firstUserSkipped) {
1955
- firstUserSkipped = true;
1956
- continue;
1957
- }
1958
- truncatableIndices.push(i);
1959
- }
1960
- }
1961
- for (const idx of truncatableIndices) {
1962
- if (getTotalChars() <= maxChars) {
1963
- break;
1964
- }
1965
- const m = messages[idx];
1966
- if (m.role === "tool" && m.content !== TRUNCATED_MARKER) {
1967
- messages[idx] = { role: "tool", tool_call_id: m.tool_call_id, content: TRUNCATED_MARKER };
1968
- } else if (m.role === "user" && m.content !== TRUNCATED_MARKER) {
1969
- messages[idx] = { role: "user", content: TRUNCATED_MARKER };
1970
- }
1971
- }
1972
- return messages;
1973
- }
1974
-
1975
- // tools/warp_grep/agent/runner.ts
1976
- var import_openai2 = __toESM(require("openai"), 1);
1977
- init_version();
1978
- var import_path4 = __toESM(require("path"), 1);
1979
- init_logger();
1980
- var DEFAULT_API_URL2 = "https://api.morphllm.com";
1981
- var TOOL_SPECS = [
1982
- {
1983
- type: "function",
1984
- function: {
1985
- name: "list_directory",
1986
- description: "Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.",
1987
- parameters: {
1988
- type: "object",
1989
- properties: {
1990
- command: {
1991
- type: "string",
1992
- description: "Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */)."
1993
- }
1994
- },
1995
- required: ["command"]
1996
- }
1997
- }
1998
- },
1999
- {
2000
- type: "function",
2001
- function: {
2002
- name: "grep_search",
2003
- description: "Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.",
2004
- parameters: {
2005
- type: "object",
2006
- properties: {
2007
- pattern: {
2008
- type: "string",
2009
- description: "Regex pattern to search for in file contents (e.g. 'class\\s+\\w+Error', 'import|require|from', 'def (get|set|update)_user')."
2010
- },
2011
- path: {
2012
- type: "string",
2013
- description: "File or directory to search in. Defaults to current working directory."
2014
- },
2015
- glob: {
2016
- type: "string",
2017
- description: "Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*')."
2018
- },
2019
- limit: {
2020
- type: "integer",
2021
- description: "Limit output to first N matching lines. Shows all matches if not specified."
2022
- }
2023
- },
2024
- required: ["pattern"]
2025
- }
2026
- }
2027
- },
2028
- {
2029
- type: "function",
2030
- function: {
2031
- name: "glob",
2032
- description: "Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.",
2033
- parameters: {
2034
- type: "object",
2035
- properties: {
2036
- pattern: {
2037
- type: "string",
2038
- description: "Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py')."
2039
- },
2040
- path: {
2041
- type: "string",
2042
- description: "Directory to search in. Defaults to repository root."
2043
- }
2044
- },
2045
- required: ["pattern"]
2046
- }
2047
- }
2048
- },
2049
- {
2050
- type: "function",
2051
- function: {
2052
- name: "read",
2053
- description: "Read entire files or specific line ranges using absolute paths.",
2054
- parameters: {
2055
- type: "object",
2056
- properties: {
2057
- path: {
2058
- type: "string",
2059
- description: "File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path)."
2060
- },
2061
- lines: {
2062
- type: "string",
2063
- description: "Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file."
2064
- }
2065
- },
2066
- required: ["path"]
2067
- }
2068
- }
2069
- },
2070
- {
2071
- type: "function",
2072
- function: {
2073
- name: "finish",
2074
- description: "Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.",
2075
- parameters: {
2076
- type: "object",
2077
- properties: {
2078
- files: {
2079
- type: "string",
2080
- 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."
2081
- }
2082
- },
2083
- required: ["files"]
2084
- }
2085
- }
2086
- }
2087
- ];
2088
- async function callModel(messages, model, options = {}) {
2089
- const baseUrl = options.morphApiUrl || DEFAULT_API_URL2;
2090
- const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
2091
- const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
2092
- const parsedUrl = new URL(baseUrl);
2093
- const baseURL = parsedUrl.pathname === "/" ? `${baseUrl}/v1` : baseUrl;
2094
- const client = new import_openai2.default({
2095
- apiKey,
2096
- baseURL,
2097
- maxRetries: 0,
2098
- timeout: timeoutMs,
2099
- defaultHeaders: { "X-Morph-SDK-Version": SDK_VERSION }
2100
- });
2101
- const MAX_EMPTY_RETRIES = 1;
2102
- logger.debug("WarpGrep", "model_call", { url: baseURL, model, message_count: messages.length });
2103
- const callStartTime = Date.now();
2104
- for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {
2105
- let data;
2106
- try {
2107
- data = await client.chat.completions.create({
2108
- model,
2109
- temperature: 0,
2110
- max_tokens: 2048,
2111
- messages,
2112
- tools: TOOL_SPECS,
2113
- ...options.search_type ? { search_type: options.search_type } : {}
2114
- });
2115
- } catch (error) {
2116
- const callLatencyMs = Date.now() - callStartTime;
2117
- if (error instanceof import_openai2.default.APIError) {
2118
- logger.error("WarpGrep", "model_call_error", { status: error.status, error: error.message, latency_ms: callLatencyMs });
2119
- if (error.status === 404) {
2120
- 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";
2121
- const errorText = error.message?.trim();
2122
- throw new Error(errorText || defaultMsg);
2123
- }
2124
- } else {
2125
- logger.error("WarpGrep", "model_call_error", { status: void 0, error: error instanceof Error ? error.message : String(error), latency_ms: callLatencyMs });
2126
- }
2127
- throw error;
2128
- }
2129
- const choice = data?.choices?.[0];
2130
- const message = choice?.message;
2131
- if (!message) {
2132
- if (attempt === MAX_EMPTY_RETRIES) {
2133
- throw new Error("Invalid response from model: no message in response");
2134
- }
2135
- await new Promise((resolve2) => setTimeout(resolve2, 200));
2136
- continue;
2137
- }
2138
- const toolCalls = (message.tool_calls || []).map((tc) => ({
2139
- id: tc.id,
2140
- type: "function",
2141
- function: { name: tc.function.name, arguments: tc.function.arguments }
2142
- }));
2143
- if (message.content || toolCalls.length > 0) {
2144
- logger.debug("WarpGrep", "model_call_complete", { latency_ms: Date.now() - callStartTime, tool_calls_count: toolCalls.length, finish_reason: choice?.finish_reason ?? "unknown" });
2145
- return { content: message.content ?? null, tool_calls: toolCalls };
2146
- }
2147
- if (attempt === MAX_EMPTY_RETRIES) {
2148
- const finishReason = choice?.finish_reason ?? "unknown";
2149
- throw new Error(
2150
- `Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`
2151
- );
2152
- }
2153
- await new Promise((resolve2) => setTimeout(resolve2, 200));
2154
- }
2155
- throw new Error("Invalid response from model");
2156
- }
2157
- function safeParseJSON(s) {
2158
- try {
2159
- return JSON.parse(s);
2160
- } catch {
2161
- return {};
2162
- }
2163
- }
2164
- async function executeTool(provider, name, args, repoRoot) {
2165
- switch (name) {
2166
- case "grep_search": {
2167
- const grepArgs = {
2168
- pattern: args.pattern,
2169
- path: args.path || "."
2170
- };
2171
- if (args.glob) grepArgs.glob = args.glob;
2172
- if (args.case_sensitive !== void 0) grepArgs.case_sensitive = args.case_sensitive;
2173
- const result = await toolGrep(provider, grepArgs);
2174
- let output = result.output;
2175
- if (args.limit && typeof args.limit === "number") {
2176
- const lines = output.split("\n");
2177
- if (lines.length > args.limit) {
2178
- output = lines.slice(0, args.limit).join("\n") + `
2179
- ... (truncated at ${args.limit} lines)`;
2180
- }
2181
- }
2182
- return output;
2183
- }
2184
- case "glob": {
2185
- return toolGlob(provider, {
2186
- pattern: args.pattern,
2187
- path: args.path
2188
- });
2189
- }
2190
- case "list_directory": {
2191
- const dirPath = extractPathFromCommand(args.command || ".");
2192
- return toolListDirectory(provider, { path: dirPath }, repoRoot);
2193
- }
2194
- case "read": {
2195
- const readArgs = {
2196
- path: args.path
2197
- };
2198
- if (args.lines && typeof args.lines === "string") {
2199
- Object.assign(readArgs, parseReadLines(args.lines));
2200
- }
2201
- return toolRead(provider, readArgs);
2202
- }
2203
- default:
2204
- return `Unknown tool: ${name}`;
2205
- }
2206
- }
2207
- async function* runWarpGrepStreaming(config) {
2208
- const totalStart = Date.now();
2209
- const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
2210
- const timings = { turns: [], timeout_ms: timeoutMs };
2211
- const repoRoot = config.repoRoot || process.cwd();
2212
- const model = config.model || DEFAULT_MODEL;
2213
- const messages = [];
2214
- const maxTurns = AGENT_CONFIG.MAX_TURNS;
2215
- logger.debug("WarpGrep", "session_start", { search_term: config.searchTerm, model, max_turns: maxTurns });
2216
- const initialStateStart = Date.now();
2217
- const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });
2218
- timings.initial_state_ms = Date.now() - initialStateStart;
2219
- logger.debug("WarpGrep", "initial_state", { system_prompt_len: initialState.length, user_message_len: initialState.length });
2220
- messages.push({ role: "user", content: initialState });
2221
- const provider = config.provider;
2222
- const errors = [];
2223
- let finishMeta;
2224
- let terminationReason = "terminated";
2225
- for (let turn = 1; turn <= maxTurns; turn += 1) {
2226
- const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
2227
- logger.debug("WarpGrep", "turn_start", { turn, message_count: messages.length });
2228
- const beforeChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
2229
- enforceContextLimit(messages);
2230
- const afterChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
2231
- if (afterChars < beforeChars) {
2232
- logger.debug("WarpGrep", "context_truncated", { before_chars: beforeChars, after_chars: afterChars });
2233
- }
2234
- const modelCallStart = Date.now();
2235
- const response = await callModel(messages, model, {
2236
- morphApiKey: config.morphApiKey,
2237
- morphApiUrl: config.morphApiUrl,
2238
- retryConfig: config.retryConfig,
2239
- timeout: timeoutMs,
2240
- search_type: config.search_type
2241
- }).catch((e) => {
2242
- const errMsg = e instanceof Error ? e.message : String(e);
2243
- console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
2244
- logger.error("WarpGrep", "error", { turn, error: errMsg, phase: "model_call" });
2245
- errors.push({ message: errMsg });
2246
- return null;
2247
- });
2248
- turnMetrics.morph_api_ms = Date.now() - modelCallStart;
2249
- if (!response) {
2250
- timings.turns.push(turnMetrics);
2251
- break;
2252
- }
2253
- const toolCalls = response.tool_calls;
2254
- logger.debug("WarpGrep", "model_response", { turn, tool_calls: toolCalls.map((tc) => tc.function.name), latency_ms: turnMetrics.morph_api_ms });
2255
- messages.push({
2256
- role: "assistant",
2257
- content: response.content,
2258
- ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
2259
- });
2260
- if (toolCalls.length === 0) {
2261
- console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || "").slice(0, 500)}`);
2262
- errors.push({ message: "No tool calls produced by the model." });
2263
- terminationReason = "terminated";
2264
- timings.turns.push(turnMetrics);
2265
- break;
2266
- }
2267
- yield {
2268
- turn,
2269
- toolCalls: toolCalls.map((tc) => ({
2270
- name: tc.function.name,
2271
- arguments: safeParseJSON(tc.function.arguments)
2272
- }))
2273
- };
2274
- const finishCall = toolCalls.find((tc) => tc.function.name === "finish");
2275
- if (finishCall) {
2276
- const args = safeParseJSON(finishCall.function.arguments);
2277
- const filesStr = args.files || "";
2278
- const files = parseFinishFiles(filesStr);
2279
- finishMeta = { files };
2280
- terminationReason = "completed";
2281
- logger.debug("WarpGrep", "finish", { turns: turn, files: files.map((f) => f.path) });
2282
- if (files.length === 0) {
2283
- const payload2 = filesStr || "No relevant code found.";
2284
- timings.turns.push(turnMetrics);
2285
- timings.total_ms = Date.now() - totalStart;
2286
- return {
2287
- terminationReason: "completed",
2288
- messages,
2289
- finish: { payload: payload2, metadata: finishMeta },
2290
- timings
2291
- };
2292
- }
2293
- timings.turns.push(turnMetrics);
2294
- break;
2295
- }
2296
- const toolExecStart = Date.now();
2297
- const results = await Promise.all(
2298
- toolCalls.map(async (tc) => {
2299
- const args = safeParseJSON(tc.function.arguments);
2300
- const argsSummary = Object.fromEntries(Object.entries(args).map(([k, v]) => [k, typeof v === "string" && v.length > 100 ? v.slice(0, 100) + "..." : v]));
2301
- logger.debug("WarpGrep", "tool_exec", { turn, tool: tc.function.name, args_summary: argsSummary });
2302
- const toolStart = Date.now();
2303
- const output = await executeTool(provider, tc.function.name, args, repoRoot).catch((err) => String(err));
2304
- logger.debug("WarpGrep", "tool_result", { turn, tool: tc.function.name, result_len: output.length, latency_ms: Date.now() - toolStart });
2305
- return { tool_call_id: tc.id, content: output };
2306
- })
2307
- );
2308
- turnMetrics.local_tools_ms = Date.now() - toolExecStart;
2309
- for (const result of results) {
2310
- messages.push({ role: "tool", tool_call_id: result.tool_call_id, content: result.content });
2311
- }
2312
- const turnMsg = formatTurnMessage(turn, maxTurns);
2313
- const budget = calculateContextBudget(messages);
2314
- messages.push({ role: "user", content: turnMsg + "\n" + budget });
2315
- timings.turns.push(turnMetrics);
2316
- }
2317
- if (terminationReason !== "completed" || !finishMeta) {
2318
- timings.total_ms = Date.now() - totalStart;
2319
- return { terminationReason, messages, errors, timings };
2320
- }
2321
- const parts = ["Relevant context found:"];
2322
- for (const f of finishMeta.files) {
2323
- const ranges = f.lines === "*" ? "*" : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(", ") : "*";
2324
- parts.push(`- ${f.path}: ${ranges}`);
2325
- }
2326
- const payload = parts.join("\n");
2327
- const finishResolutionStart = Date.now();
2328
- const fileReadErrors = [];
2329
- const resolved = await readFinishFiles(
2330
- repoRoot,
2331
- finishMeta.files,
2332
- async (p, s, e) => {
2333
- let resolvedPath = p;
2334
- if (!p.startsWith(repoRoot)) {
2335
- const relative2 = p.startsWith("/") ? p.slice(1) : p;
2336
- resolvedPath = import_path4.default.join(repoRoot, relative2);
2337
- }
2338
- try {
2339
- const rr = await provider.read({ path: resolvedPath, start: s, end: e });
2340
- return rr.lines.map((l) => {
2341
- const idx = l.indexOf("|");
2342
- return idx >= 0 ? l.slice(idx + 1) : l;
2343
- });
2344
- } catch (err) {
2345
- const errorMsg = err instanceof Error ? err.message : String(err);
2346
- fileReadErrors.push({ path: resolvedPath, error: errorMsg });
2347
- console.error(`[warp_grep] Failed to read file: ${resolvedPath} - ${errorMsg}`);
2348
- return [`[couldn't find: ${resolvedPath}]`];
2349
- }
2350
- }
2351
- );
2352
- timings.finish_resolution_ms = Date.now() - finishResolutionStart;
2353
- if (fileReadErrors.length > 0) {
2354
- errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
2355
- }
2356
- timings.total_ms = Date.now() - totalStart;
2357
- return {
2358
- terminationReason: "completed",
2359
- messages,
2360
- finish: { payload, metadata: finishMeta, resolved },
2361
- timings
2362
- };
2363
- }
2364
- async function runWarpGrep(config) {
2365
- const gen = runWarpGrepStreaming(config);
2366
- let result = await gen.next();
2367
- while (!result.done) {
2368
- result = await gen.next();
2369
- }
2370
- return result.value;
2371
- }
2372
-
2373
- // tools/warp_grep/client.ts
2374
- init_logger();
2375
-
2376
- // tools/warp_grep/providers/remote.ts
2377
- init_config();
2378
- var SKIP_NAMES = /* @__PURE__ */ new Set([
2379
- // Version control
2380
- ".git",
2381
- ".svn",
2382
- ".hg",
2383
- ".bzr",
2384
- // Dependencies
2385
- "node_modules",
2386
- "bower_components",
2387
- ".pnpm",
2388
- ".yarn",
2389
- "vendor",
2390
- "Pods",
2391
- ".bundle",
2392
- // Python
2393
- "__pycache__",
2394
- ".pytest_cache",
2395
- ".mypy_cache",
2396
- ".ruff_cache",
2397
- ".venv",
2398
- "venv",
2399
- ".tox",
2400
- ".nox",
2401
- ".eggs",
2402
- // Build outputs
2403
- "dist",
2404
- "build",
2405
- "out",
2406
- "output",
2407
- "target",
2408
- "_build",
2409
- ".next",
2410
- ".nuxt",
2411
- ".output",
2412
- ".vercel",
2413
- ".netlify",
2414
- // Cache
2415
- ".cache",
2416
- ".parcel-cache",
2417
- ".turbo",
2418
- ".nx",
2419
- ".gradle",
2420
- // IDE
2421
- ".idea",
2422
- ".vscode",
2423
- ".vs",
2424
- // Coverage
2425
- "coverage",
2426
- ".coverage",
2427
- "htmlcov",
2428
- ".nyc_output",
2429
- // Temp
2430
- "tmp",
2431
- "temp",
2432
- ".tmp",
2433
- ".temp",
2434
- // Lock files
2435
- "package-lock.json",
2436
- "yarn.lock",
2437
- "pnpm-lock.yaml",
2438
- "bun.lockb",
2439
- "Cargo.lock",
2440
- "Gemfile.lock",
2441
- "poetry.lock"
2442
- ]);
2443
- var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
2444
- ".min.js",
2445
- ".min.css",
2446
- ".bundle.js",
2447
- ".wasm",
2448
- ".so",
2449
- ".dll",
2450
- ".pyc",
2451
- ".map",
2452
- ".js.map"
2453
- ]);
2454
- function shouldSkip(name) {
2455
- if (SKIP_NAMES.has(name)) return true;
2456
- if (name.startsWith(".")) return true;
2457
- for (const ext of SKIP_EXTENSIONS) {
2458
- if (name.endsWith(ext)) return true;
2459
- }
2460
- return false;
2461
- }
2462
- var RemoteCommandsProvider = class {
2463
- constructor(repoRoot, commands) {
2464
- this.repoRoot = repoRoot;
2465
- this.commands = commands;
2466
- }
2467
- /**
2468
- * Run grep command and parse ripgrep output
2469
- */
2470
- async grep(params) {
2471
- try {
2472
- const stdout = await this.commands.grep(params.pattern, params.path, params.glob);
2473
- const lines = (stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
2474
- if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {
2475
- const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);
2476
- truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);
2477
- return { lines: truncated };
2478
- }
2479
- return { lines };
2480
- } catch (error) {
2481
- return {
2482
- lines: [],
2483
- error: `[GREP ERROR] ${error instanceof Error ? error.message : String(error)}`
2484
- };
2485
- }
2486
- }
2487
- /**
2488
- * Read file and add line numbers
2489
- */
2490
- async read(params) {
2491
- const rawStart = params.start;
2492
- const rawEnd = params.end;
2493
- const startValid = rawStart === void 0 || Number.isFinite(rawStart) && rawStart > 0;
2494
- const endValid = rawEnd === void 0 || Number.isFinite(rawEnd) && rawEnd > 0;
2495
- const rangeValid = startValid && endValid && (rawStart === void 0 || rawEnd === void 0 || rawStart <= rawEnd);
2496
- const start = rangeValid && rawStart !== void 0 ? rawStart : 1;
2497
- const end = rangeValid && rawEnd !== void 0 ? rawEnd : 1e6;
2498
- try {
2499
- const stdout = await this.commands.read(params.path, start, end);
2500
- const contentLines = (stdout || "").split("\n");
2501
- if (contentLines.length > 0 && contentLines[contentLines.length - 1] === "") {
2502
- contentLines.pop();
2503
- }
2504
- const lines = contentLines.map((content, idx) => `${start + idx}|${content}`);
2505
- if (lines.length > AGENT_CONFIG.MAX_READ_LINES) {
2506
- const truncated = lines.slice(0, AGENT_CONFIG.MAX_READ_LINES);
2507
- truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${lines.length} lines)`);
2508
- return { lines: truncated };
2509
- }
2510
- return { lines };
2511
- } catch (error) {
2512
- return {
2513
- lines: [],
2514
- error: `[READ ERROR] ${error instanceof Error ? error.message : String(error)}`
2515
- };
2516
- }
2517
- }
2518
- /**
2519
- * List directory and parse find output
2520
- */
2521
- async listDirectory(params) {
2522
- const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
2523
- const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
2524
- try {
2525
- const stdout = await this.commands.listDir(params.path, maxDepth);
2526
- const paths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
2527
- const regex = params.pattern ? new RegExp(params.pattern) : null;
2528
- const entries = [];
2529
- for (const fullPath of paths) {
2530
- if (fullPath === params.path || fullPath === this.repoRoot) continue;
2531
- const name = fullPath.split("/").pop() || "";
2532
- if (shouldSkip(name)) continue;
2533
- if (regex && !regex.test(name)) continue;
2534
- let relativePath = fullPath;
2535
- if (fullPath.startsWith(this.repoRoot)) {
2536
- relativePath = fullPath.slice(this.repoRoot.length).replace(/^\//, "");
2537
- }
2538
- const depth = relativePath.split("/").filter(Boolean).length - 1;
2539
- const hasExtension = name.includes(".") && !name.startsWith(".");
2540
- const type = hasExtension ? "file" : "dir";
2541
- entries.push({
2542
- name,
2543
- path: relativePath,
2544
- type,
2545
- depth: Math.max(0, depth)
2546
- });
2547
- if (entries.length >= maxResults) break;
2548
- }
2549
- return entries;
2550
- } catch (error) {
2551
- return [];
2552
- }
2553
- }
2554
- /**
2555
- * Glob search - finds files matching a pattern.
2556
- * Falls back to a grep --files approach via the listDir command.
2557
- */
2558
- async glob(params) {
2559
- const searchPath = params.path || this.repoRoot;
2560
- try {
2561
- const stdout = await this.commands.listDir(searchPath, 10);
2562
- const allPaths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
2563
- const globToRegex = (glob) => {
2564
- const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
2565
- return new RegExp(escaped);
2566
- };
2567
- const regex = globToRegex(params.pattern);
2568
- const matched = allPaths.filter((p) => {
2569
- const name = p.split("/").pop() || "";
2570
- return regex.test(name) && !shouldSkip(name);
2571
- });
2572
- const totalFound = matched.length;
2573
- return { files: matched.slice(0, 100), searchDir: searchPath, totalFound };
2574
- } catch (error) {
2575
- return {
2576
- files: [],
2577
- searchDir: searchPath,
2578
- totalFound: 0,
2579
- error: `[GLOB ERROR] ${error instanceof Error ? error.message : String(error)}`
2580
- };
2581
- }
2582
- }
2583
- };
2584
-
2585
- // tools/warp_grep/providers/code_storage_http.ts
2586
- var MODEL_REPO_ROOT = /^\/?home\/ubuntu\/repo(?:\/|$)/;
2587
- function toRepoRelative(path6) {
2588
- if (!path6) return path6;
2589
- const stripped = path6.replace(MODEL_REPO_ROOT, "").replace(/^\.?\/+/, "");
2590
- return stripped || ".";
2591
- }
2592
- async function post(url, body, op, apiKey) {
2593
- const res = await fetch(url, {
2594
- method: "POST",
2595
- headers: {
2596
- "Content-Type": "application/json",
2597
- ...apiKey ? { Authorization: `Bearer ${apiKey}` } : {}
2598
- },
2599
- body: JSON.stringify(body)
2600
- });
2601
- if (!res.ok) {
2602
- const text = await res.text().catch(() => res.statusText);
2603
- try {
2604
- const parsed = JSON.parse(text);
2605
- if (parsed.error) return `Error: ${parsed.error}`;
2606
- } catch {
2607
- }
2608
- return `Error: ${op} failed (${res.status}): ${text}`;
2609
- }
2610
- const data = await res.json();
2611
- if (data.error) throw new Error(data.error);
2612
- return data.stdout;
2613
- }
2614
- function createCodeStorageHttpCommands(config) {
2615
- const { baseUrl, repoId, branch, apiKey } = config;
2616
- const encodedRepoId = encodeURIComponent(repoId);
2617
- return {
2618
- grep: (pattern, path6, glob) => post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path: toRepoRelative(path6), glob, branch }, "grep", apiKey),
2619
- read: (path6, start, end) => post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path: toRepoRelative(path6), start, end, branch }, "read", apiKey),
2620
- listDir: (path6, maxDepth) => post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path: toRepoRelative(path6), maxDepth, branch }, "list", apiKey)
2621
- };
2622
- }
2623
-
2624
- // tools/warp_grep/utils/github.ts
2625
- function parseGitHubUrl(input) {
2626
- input = input.trim();
2627
- const urlPattern = /^(?:https?:\/\/)?github\.com\/([^\/]+)\/([^\/\?\#]+)/;
2628
- const match = input.match(urlPattern);
2629
- if (match) {
2630
- return { owner: match[1], repo: match[2].replace(/\.git$/, "") };
2631
- }
2632
- const shortPattern = /^([^\/]+)\/([^\/]+)$/;
2633
- const shortMatch = input.match(shortPattern);
2634
- if (shortMatch && !shortMatch[1].includes(".")) {
2635
- return { owner: shortMatch[1], repo: shortMatch[2].replace(/\.git$/, "") };
2636
- }
2637
- throw new Error(
2638
- `Invalid GitHub URL or shorthand: "${input}". Expected "owner/repo" or "https://github.com/owner/repo"`
2639
- );
2640
- }
2641
-
2642
- // tools/compact/core.ts
2643
- var DEFAULT_API_URL3 = "https://api.morphllm.com";
2644
- var DEFAULT_TIMEOUT3 = 12e4;
2645
- function resolveClient(clientOrConfig) {
2646
- if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
2647
- return new MorphAPIClient({
2648
- apiKey: clientOrConfig.morphApiKey,
2649
- baseURL: clientOrConfig.morphApiUrl ?? DEFAULT_API_URL3,
2650
- timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT3,
2651
- retryConfig: clientOrConfig.retryConfig,
2652
- debug: clientOrConfig.debug
2653
- });
2654
- }
2655
- var CompactClient = class extends APIResource {
2656
- /** Resolved URL/timeout, exposed for backwards-compatible introspection. */
2657
- config;
2658
- constructor(clientOrConfig = {}) {
2659
- super(resolveClient(clientOrConfig));
2660
- const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
2661
- this.config = {
2662
- morphApiUrl: this._client.baseURL,
2663
- timeout: cfg.timeout ?? DEFAULT_TIMEOUT3,
2664
- debug: cfg.debug ?? false
2665
- };
2666
- }
2667
- /**
2668
- * Compact messages or text via /v1/compact.
2669
- * Returns per-message `compacted_line_ranges` showing which lines were removed.
2670
- *
2671
- * @example
2672
- * ```typescript
2673
- * const client = new CompactClient({ morphApiKey: 'sk-...' });
2674
- * const result = await client.compact({
2675
- * input: codeFile,
2676
- * query: "authentication",
2677
- * compressionRatio: 0.5,
2678
- * });
2679
- * console.log(result.output);
2680
- * ```
2681
- */
2682
- async compact(input) {
2683
- const body = {
2684
- compression_ratio: input.compressionRatio ?? 0.5,
2685
- preserve_recent: input.preserveRecent ?? 2,
2686
- model: input.model ?? "morph-compactor",
2687
- include_line_ranges: input.includeLineRanges ?? true,
2688
- include_markers: input.includeMarkers ?? true
2689
- };
2690
- if (input.query !== void 0) body.query = input.query;
2691
- if (input.messages) body.messages = input.messages;
2692
- else if (typeof input.input === "string") body.input = input.input;
2693
- else if (Array.isArray(input.input)) body.messages = input.input;
2694
- else throw new Error("Either 'input' or 'messages' must be provided");
2695
- try {
2696
- return await this._client.post("/v1/compact", { body, timeout: this.config.timeout });
2697
- } catch (err) {
2698
- if (err instanceof MorphError) {
2699
- throw new Error(`Compact API error ${err.statusCode}: ${err.message}`);
2700
- }
2701
- throw err;
2702
- }
2703
- }
2704
- };
2705
-
2706
- // tools/compact/utils.ts
2707
- async function compactFileContexts(files, query, apiKey, apiUrl, maxTokens = 1e4, maxConcurrency = 3) {
2708
- const totalLength = files.reduce((sum, file) => sum + file.content.length, 0);
2709
- const estimatedTokens = totalLength / 3;
2710
- if (estimatedTokens <= maxTokens) {
2711
- return files;
2712
- }
2713
- let compressionRatio = maxTokens / estimatedTokens;
2714
- compressionRatio = Math.max(0.3, Math.min(0.99, compressionRatio));
2715
- const client = new CompactClient({
2716
- morphApiKey: apiKey,
2717
- morphApiUrl: apiUrl
2718
- });
2719
- const results = [];
2720
- const inProgress = /* @__PURE__ */ new Set();
2721
- for (const file of files) {
2722
- if (file.content.length < 500) {
2723
- results.push({ path: file.path, content: file.content });
2724
- continue;
2725
- }
2726
- const task = async () => {
2727
- try {
2728
- const result = await client.compact({
2729
- input: file.content,
2730
- query,
2731
- compressionRatio,
2732
- preserveRecent: 0
2733
- });
2734
- results.push({ path: file.path, content: result.output });
2735
- } catch (error) {
2736
- console.error(`[compactFileContexts] Failed to compact file ${file.path}:`, error);
2737
- results.push({ path: file.path, content: file.content });
2738
- }
2739
- };
2740
- const promise = task().finally(() => inProgress.delete(promise));
2741
- inProgress.add(promise);
2742
- if (inProgress.size >= maxConcurrency) {
2743
- await Promise.race(inProgress);
2744
- }
2745
- }
2746
- await Promise.all(inProgress);
2747
- const orderMap = new Map(files.map((f, i) => [f.path, i]));
2748
- return results.sort((a, b) => (orderMap.get(a.path) ?? 0) - (orderMap.get(b.path) ?? 0));
2749
- }
2750
-
2751
- // tools/warp_grep/client.ts
2752
- var DEFAULT_CODE_SEARCH_URL = "https://api.morphllm.com";
2753
- async function getLocalProvider(repoRoot, excludes, allowNames) {
2754
- const { LocalRipgrepProvider: LocalRipgrepProvider2 } = await Promise.resolve().then(() => (init_local(), local_exports));
2755
- const opts = allowNames?.length ? { allowNames } : void 0;
2756
- return new LocalRipgrepProvider2(repoRoot, excludes, opts);
2757
- }
2758
- var WarpGrepClient = class extends APIResource {
2759
- config;
2760
- constructor(clientOrConfig = {}) {
2761
- const isClient = clientOrConfig instanceof MorphAPIClient;
2762
- super(
2763
- isClient ? clientOrConfig : new MorphAPIClient({
2764
- apiKey: clientOrConfig.morphApiKey,
2765
- baseURL: clientOrConfig.morphApiUrl,
2766
- timeout: clientOrConfig.timeout,
2767
- retryConfig: clientOrConfig.retryConfig,
2768
- debug: clientOrConfig.debug
2769
- })
2770
- );
2771
- const cfg = isClient ? {} : clientOrConfig;
2772
- this.config = {
2773
- ...cfg,
2774
- morphApiKey: this._client.resolveApiKey(),
2775
- morphApiUrl: this._client.baseURL,
2776
- timeout: this._client.timeout,
2777
- retryConfig: this._client.retryConfig,
2778
- debug: this._client.debug
2779
- };
2780
- }
2781
- execute(input) {
2782
- const toolConfig = {
2783
- repoRoot: input.repoRoot,
2784
- remoteCommands: input.remoteCommands,
2785
- provider: input.provider,
2786
- excludes: input.excludes,
2787
- includes: input.includes,
2788
- debug: input.debug ?? this.config.debug,
2789
- morphApiKey: this.config.morphApiKey,
2790
- morphApiUrl: this.config.morphApiUrl,
2791
- retryConfig: this.config.retryConfig,
2792
- timeout: this.config.timeout,
2793
- search_type: input.search_type
2794
- };
2795
- if (input.streamSteps) {
2796
- return executeToolCallStreaming({ search_term: input.searchTerm }, toolConfig);
2797
- }
2798
- return executeToolCall({ search_term: input.searchTerm }, toolConfig);
2799
- }
2800
- searchGitHub(input) {
2801
- if (input.streamSteps) {
2802
- return this._searchGitHubStreaming(input);
2803
- }
2804
- return this._searchGitHubAsync(input);
2805
- }
2806
- /**
2807
- * Read a single file from a public GitHub repository
2808
- *
2809
- * @example
2810
- * ```typescript
2811
- * const result = await client.readGitHubFile({
2812
- * github: 'vercel/next.js',
2813
- * path: 'src/server/app-render/index.tsx',
2814
- * startLine: 1,
2815
- * endLine: 50,
2816
- * });
2817
- * if (result.success) console.log(result.content);
2818
- * ```
2819
- */
2820
- async readGitHubFile(input) {
2821
- return executeGitHubReadFile(input, { timeout: this.config.timeout });
2822
- }
2823
- async _resolveGitHubRepo(input) {
2824
- const { owner, repo } = parseGitHubUrl(input.github);
2825
- const baseUrl = this.config.codeSearchUrl || DEFAULT_CODE_SEARCH_URL;
2826
- logger.debug("WarpGrep", "github_resolve", { owner_repo: `${owner}/${repo}`, branch: input.branch });
2827
- const resolveStart = Date.now();
2828
- const importRes = await fetch(`${baseUrl}/api/code-search/get-or-create?url=${encodeURIComponent(`${owner}/${repo}`)}`, {
2829
- headers: this.config.morphApiKey ? { Authorization: `Bearer ${this.config.morphApiKey}` } : void 0
2830
- });
2831
- if (!importRes.ok) {
2832
- const text = await importRes.text().catch(() => importRes.statusText);
2833
- logger.error("WarpGrep", "github_resolve_failed", { owner_repo: `${owner}/${repo}`, status: importRes.status, error: text });
2834
- throw new Error(`Failed to import repo ${owner}/${repo}: ${text}`);
2835
- }
2836
- const { repoId, defaultBranch } = await importRes.json();
2837
- logger.debug("WarpGrep", "github_repo_fetched", { repo_id: repoId, default_branch: defaultBranch, latency_ms: Date.now() - resolveStart });
2838
- return {
2839
- repo,
2840
- remoteCommands: createCodeStorageHttpCommands({
2841
- baseUrl,
2842
- repoId,
2843
- branch: input.branch || defaultBranch,
2844
- apiKey: this.config.morphApiKey
2845
- })
2846
- };
2847
- }
2848
- async _searchGitHubAsync(input) {
2849
- try {
2850
- const { remoteCommands } = await this._resolveGitHubRepo(input);
2851
- return this.execute({
2852
- searchTerm: input.searchTerm,
2853
- repoRoot: ".",
2854
- remoteCommands
2855
- });
2856
- } catch (error) {
2857
- return { success: false, error: error instanceof Error ? error.message : String(error) };
2858
- }
2859
- }
2860
- async *_searchGitHubStreaming(input) {
2861
- let remoteCommands;
2862
- try {
2863
- ({ remoteCommands } = await this._resolveGitHubRepo(input));
2864
- } catch (error) {
2865
- return { success: false, error: error instanceof Error ? error.message : String(error) };
2866
- }
2867
- const generator = this.execute({
2868
- searchTerm: input.searchTerm,
2869
- repoRoot: ".",
2870
- remoteCommands,
2871
- streamSteps: true
2872
- });
2873
- let result;
2874
- for (; ; ) {
2875
- const { value, done } = await generator.next();
2876
- if (done) {
2877
- result = value;
2878
- break;
2879
- }
2880
- yield value;
2881
- }
2882
- return result;
2883
- }
2884
- };
2885
- async function executeToolCall(input, config) {
2886
- const parsed = typeof input === "string" ? JSON.parse(input) : input;
2887
- const allowNames = config.search_type === "node_modules" ? ["node_modules"] : void 0;
2888
- const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);
2889
- const result = await runWarpGrep({
2890
- searchTerm: parsed.search_term,
2891
- repoRoot: config.repoRoot,
2892
- provider,
2893
- excludes: config.excludes,
2894
- includes: config.includes,
2895
- debug: config.debug ?? false,
2896
- morphApiKey: config.morphApiKey,
2897
- morphApiUrl: config.morphApiUrl,
2898
- retryConfig: config.retryConfig,
2899
- timeout: config.timeout,
2900
- search_type: config.search_type
2901
- });
2902
- return processAgentResult(result, parsed.search_term, config.morphApiKey, config.morphApiUrl);
2903
- }
2904
- async function processAgentResult(result, searchTerm, apiKey, apiUrl) {
2905
- const finish = result.finish;
2906
- if (result.terminationReason !== "completed" || !finish?.metadata) {
2907
- const errorDetails = result.errors?.map((e) => e.message).join("; ") || "unknown reason";
2908
- console.error(`[warp_grep] processAgentResult failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);
2909
- return { success: false, error: `Search did not complete: ${errorDetails}` };
2910
- }
2911
- const contexts = (finish.resolved ?? []).map((r) => ({
2912
- file: r.path,
2913
- content: r.content,
2914
- lines: r.ranges
2915
- }));
2916
- try {
2917
- const compactable = contexts.map((c) => ({ path: c.file, content: c.content }));
2918
- const compacted = await compactFileContexts(compactable, searchTerm, apiKey, apiUrl);
2919
- for (let i = 0; i < contexts.length; i++) {
2920
- contexts[i].content = compacted[i].content;
2921
- }
2922
- } catch (error) {
2923
- console.error(`[warp_grep] Failed to compact result contexts:`, error);
2924
- }
2925
- return { success: true, contexts, summary: finish.payload };
2926
- }
2927
- async function* executeToolCallStreaming(input, config) {
2928
- const parsed = typeof input === "string" ? JSON.parse(input) : input;
2929
- const allowNames = config.search_type === "node_modules" ? ["node_modules"] : void 0;
2930
- const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);
2931
- const generator = runWarpGrepStreaming({
2932
- searchTerm: parsed.search_term,
2933
- repoRoot: config.repoRoot,
2934
- provider,
2935
- excludes: config.excludes,
2936
- includes: config.includes,
2937
- debug: config.debug ?? false,
2938
- morphApiKey: config.morphApiKey,
2939
- morphApiUrl: config.morphApiUrl,
2940
- retryConfig: config.retryConfig,
2941
- timeout: config.timeout,
2942
- search_type: config.search_type
2943
- });
2944
- let agentResult;
2945
- for (; ; ) {
2946
- const { value, done } = await generator.next();
2947
- if (done) {
2948
- agentResult = value;
2949
- break;
2950
- }
2951
- yield value;
2952
- }
2953
- return await processAgentResult(agentResult, parsed.search_term, config.morphApiKey, config.morphApiUrl);
2954
- }
2955
- async function fetchRawGitHubFile(owner, repo, filePath, branch, timeout) {
2956
- const branches = branch ? [branch] : ["HEAD"];
2957
- const fallbacks = ["main", "master", "develop"];
2958
- const fetchWithTimeout = (url) => timeout ? fetch(url, { signal: AbortSignal.timeout(timeout) }) : fetch(url);
2959
- for (const b of branches) {
2960
- const url = `https://raw.githubusercontent.com/${owner}/${repo}/${b}/${filePath}`;
2961
- const res = await fetchWithTimeout(url);
2962
- if (res.ok) return { content: await res.text(), branch: b };
2963
- }
2964
- for (const fb of fallbacks) {
2965
- if (branch && fb === branch) continue;
2966
- const url = `https://raw.githubusercontent.com/${owner}/${repo}/${fb}/${filePath}`;
2967
- const res = await fetchWithTimeout(url);
2968
- if (res.ok) return { content: await res.text(), branch: fb };
2969
- }
2970
- throw new Error(`File not found: ${owner}/${repo}/${filePath}`);
2971
- }
2972
- async function executeGitHubReadFile(input, config) {
2973
- try {
2974
- const { owner, repo } = parseGitHubUrl(input.github);
2975
- const { content: raw, branch } = await fetchRawGitHubFile(
2976
- owner,
2977
- repo,
2978
- input.path,
2979
- input.branch,
2980
- config?.timeout
2981
- );
2982
- const allLines = raw.split("\n");
2983
- const totalLines = allLines.length;
2984
- const start = Math.max(1, input.startLine ?? 1);
2985
- const end = Math.min(totalLines, input.endLine ?? totalLines);
2986
- const selected = allLines.slice(start - 1, end);
2987
- const padWidth = String(end).length;
2988
- const numbered = selected.map((line, i) => `${String(start + i).padStart(padWidth)}|${line}`).join("\n");
2989
- return {
2990
- success: true,
2991
- content: numbered,
2992
- path: input.path,
2993
- github: `${owner}/${repo}`,
2994
- branch,
2995
- lineRange: [start, end],
2996
- totalLines
2997
- };
2998
- } catch (error) {
2999
- return {
3000
- success: false,
3001
- error: error instanceof Error ? error.message : String(error)
3002
- };
3003
- }
3004
- }
3005
- function formatResult(result) {
3006
- if (!result.success) {
3007
- return `Search failed: ${result.error}`;
3008
- }
3009
- if (!result.contexts || result.contexts.length === 0) {
3010
- return "No relevant code found. Try rephrasing your search term.";
3011
- }
3012
- const parts = [];
3013
- parts.push(`Morph Fast Context subagent performed search on repository:
3014
- `);
3015
- parts.push("Relevant context found:");
3016
- for (const ctx of result.contexts) {
3017
- const rangeStr = !ctx.lines || ctx.lines === "*" ? "*" : ctx.lines.map(([s, e]) => `${s}-${e}`).join(",");
3018
- parts.push(`- ${ctx.file}:${rangeStr}`);
3019
- }
3020
- parts.push("\nHere is the content of files:\n");
3021
- for (const ctx of result.contexts) {
3022
- const rangeStr = !ctx.lines || ctx.lines === "*" ? "" : ` lines="${ctx.lines.map(([s, e]) => `${s}-${e}`).join(",")}"`;
3023
- parts.push(`<file path="${ctx.file}"${rangeStr}>`);
3024
- parts.push(ctx.content);
3025
- parts.push("</file>\n");
3026
- }
3027
- return parts.join("\n");
3028
- }
3029
-
3030
- // modelrouter/core.ts
3031
- init_logger();
3032
- var DEFAULT_API_URL4 = "https://api.morphllm.com";
3033
- var DEFAULT_TIMEOUT4 = 5e3;
3034
- function resolveClient2(clientOrConfig) {
3035
- if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
3036
- return new MorphAPIClient({
3037
- apiKey: clientOrConfig.apiKey,
3038
- baseURL: clientOrConfig.apiUrl ?? DEFAULT_API_URL4,
3039
- timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT4,
3040
- retryConfig: clientOrConfig.retryConfig,
3041
- debug: clientOrConfig.debug
3042
- });
3043
- }
3044
- var BaseRouter = class extends APIResource {
3045
- provider;
3046
- timeout;
3047
- constructor(provider, clientOrConfig = {}) {
3048
- super(resolveClient2(clientOrConfig));
3049
- this.provider = provider;
3050
- const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
3051
- this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT4;
3052
- }
3053
- /** Throw the historical "API key is required" message when no key is resolvable. */
3054
- requireApiKey() {
3055
- if (!this._client.resolveApiKey()) {
3056
- throw new Error(
3057
- "Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config."
3058
- );
3059
- }
3060
- }
3061
- /** POST to the router and surface failures as `Router API error (<status>): ...`. */
3062
- async route(provider, input) {
3063
- try {
3064
- return await this._client.post(`/v1/router/${provider}`, {
3065
- body: { input: input.input, mode: input.mode || "balanced" },
3066
- timeout: this.timeout
3067
- });
3068
- } catch (error) {
3069
- if (error instanceof MorphError) {
3070
- throw new Error(`Router API error (${error.statusCode}): ${error.message}`);
3071
- }
3072
- throw error;
3073
- }
3074
- }
3075
- /**
3076
- * Select the optimal model for a given input and mode
3077
- */
3078
- async selectModel(input) {
3079
- this.requireApiKey();
3080
- logger.debug("ModelRouter", "request", { provider: this.provider, mode: input.mode || "balanced" });
3081
- const apiResult = await this.route(this.provider, input);
3082
- logger.debug("ModelRouter", "selected", { provider: this.provider, model: apiResult.model });
3083
- return { model: apiResult.model };
3084
- }
3085
- };
3086
- var OpenAIRouter = class extends BaseRouter {
3087
- constructor(clientOrConfig = {}) {
3088
- super("openai", clientOrConfig);
3089
- }
3090
- /**
3091
- * Select optimal GPT-5 model
3092
- *
3093
- * @param input - User input and mode
3094
- * @returns Selected model name (gpt-5-mini | gpt-5-low | gpt-5-medium | gpt-5-high)
3095
- */
3096
- async selectModel(input) {
3097
- return super.selectModel(input);
3098
- }
3099
- };
3100
- var AnthropicRouter = class extends BaseRouter {
3101
- constructor(clientOrConfig = {}) {
3102
- super("anthropic", clientOrConfig);
3103
- }
3104
- /**
3105
- * Select optimal Claude model
3106
- *
3107
- * @param input - User input and mode
3108
- * @returns Selected model name (claude-4.5-haiku | claude-4.5-sonnet)
3109
- */
3110
- async selectModel(input) {
3111
- return super.selectModel(input);
3112
- }
3113
- };
3114
- var GeminiRouter = class extends BaseRouter {
3115
- constructor(clientOrConfig = {}) {
3116
- super("gemini", clientOrConfig);
3117
- }
3118
- /**
3119
- * Select optimal Gemini model
3120
- *
3121
- * @param input - User input and mode
3122
- * @returns Selected model name (gemini-2.5-flash | gemini-2.5-pro)
3123
- */
3124
- async selectModel(input) {
3125
- return super.selectModel(input);
3126
- }
3127
- };
3128
- var RawRouter = class extends BaseRouter {
3129
- constructor(clientOrConfig = {}) {
3130
- super("raw", clientOrConfig);
3131
- }
3132
- /**
3133
- * Get raw difficulty classification
3134
- *
3135
- * @param input - User input and mode
3136
- * @returns Raw difficulty (easy | medium | hard | needs_info)
3137
- */
3138
- async classify(input) {
3139
- this.requireApiKey();
3140
- logger.debug("RawRouter", "request", { mode: input.mode || "balanced" });
3141
- const apiResult = await this.route("raw", input);
3142
- let difficulty;
3143
- if (apiResult.difficulty === "") {
3144
- difficulty = "medium";
3145
- } else {
3146
- difficulty = apiResult.difficulty || apiResult.model;
3147
- }
3148
- logger.debug("RawRouter", "classified", { difficulty });
3149
- return { difficulty };
3150
- }
3151
- };
3152
- var RouterClassifier = class extends APIResource {
3153
- timeout;
3154
- constructor(clientOrConfig = {}) {
3155
- super(resolveClient2(clientOrConfig));
3156
- const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
3157
- this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT4;
3158
- }
3159
- /** Classify an input across the requested axes (all three by default). */
3160
- async classify(input) {
3161
- if (!this._client.resolveApiKey()) {
3162
- throw new Error(
3163
- "Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config."
3164
- );
3165
- }
3166
- logger.debug("RouterClassifier", "request", { classes: input.classes ?? "all" });
3167
- try {
3168
- const res = await this._client.post("/v1/router/classify", {
3169
- body: { input: input.input, ...input.classes ? { classes: input.classes } : {} },
3170
- timeout: this.timeout
3171
- });
3172
- logger.debug("RouterClassifier", "classified", {
3173
- difficulty: res.classifications.difficulty?.label,
3174
- ambiguity: res.classifications.ambiguity?.label,
3175
- domain: res.classifications.domain?.label
3176
- });
3177
- return res.classifications;
3178
- } catch (error) {
3179
- if (error instanceof MorphError) {
3180
- throw new Error(`Router API error (${error.statusCode}): ${error.message}`);
3181
- }
3182
- throw error;
3183
- }
3184
- }
3185
- };
3186
-
3187
- // tools/warp_grep/prompts.ts
3188
- var WARP_GREP_TOOL_NAME = "codebase_search";
3189
- var WARP_GREP_DESCRIPTION = 'Very fast code search exploration subagent (not a grep tool) that runs parallel grep and file read calls over multiple turns to locate relevant files and line ranges. The search term should be a targeted natural-language query describing what you are trying to find or accomplish, e.g. "Find where authentication requests are handled in the Express routes" or "How do callers of processOrder handle the error case?". Fill in extra context you can infer to make the query specific. Do not pass bare keywords or symbol names \u2014 use grep directly for exact symbol lookups. Use this tool first when exploring unfamiliar code. The results may be partial \u2014 follow up with classical search tools or direct file reads if needed.';
3190
- var GITHUB_WARP_GREP_SEARCH_TOOL_NAME = "github_codebase_search";
3191
- var GITHUB_WARP_GREP_SEARCH_DESCRIPTION = "Always use this when debugging errors in third-party dependencies to check for upstream fixes, open issues, or newer code pathsSearch tool for public GitHub repositories.Code search exploration subagent for public GitHub repositories (not your local workspace \u2014 use codebase_search for that). Runs parallel grep and file read calls to locate relevant files and line ranges in external github repositories without cloning the repository. Pass a targeted natural-language query, not bare keywords. Useful for understanding how a library works or investigating upstream bugs. You must provide either github_url or owner_repo (at least one required). ";
3192
- var GITHUB_WARP_GREP_SEARCH_INPUT_SCHEMA = {
3193
- type: "object",
3194
- properties: {
3195
- search_term: { type: "string", description: 'A targeted natural-language query describing what to find (e.g. "How does auth work for SSO users?"). Not a keyword or symbol name.' },
3196
- github_url: { type: "string", description: 'GitHub repository URL to search (e.g. "https://github.com/vercel/next.js"). You must provide either github_url or owner_repo.' },
3197
- owner_repo: { type: "string", description: 'Repository owner/repo shorthand (e.g. "vercel/next.js"). You must provide either github_url or owner_repo.' },
3198
- branch: { type: "string", description: "Branch to search (defaults to the repository default branch)" }
3199
- },
3200
- required: ["search_term"]
3201
- };
3202
- var GITHUB_SEARCH_TOOL_NAME = GITHUB_WARP_GREP_SEARCH_TOOL_NAME;
3203
- var GITHUB_SEARCH_DESCRIPTION = GITHUB_WARP_GREP_SEARCH_DESCRIPTION;
3204
- var GITHUB_SEARCH_INPUT_SCHEMA = GITHUB_WARP_GREP_SEARCH_INPUT_SCHEMA;
3205
-
3206
- // tools/warp_grep/openai.ts
3207
- var TOOL_PARAMETERS = {
3208
- type: "object",
3209
- properties: {
3210
- search_term: { type: "string", description: "Search problem statement that this subagent is supposed to research for" }
3211
- },
3212
- required: ["search_term"]
3213
- };
3214
- function createWarpGrepTool(config) {
3215
- const tool4 = {
3216
- type: "function",
3217
- function: {
3218
- name: config.name ?? WARP_GREP_TOOL_NAME,
3219
- description: config.description ?? WARP_GREP_DESCRIPTION,
3220
- parameters: TOOL_PARAMETERS
3221
- }
3222
- };
3223
- return Object.assign(tool4, {
3224
- execute: async (input) => {
3225
- return executeToolCall(input, config);
3226
- },
3227
- formatResult: (result) => {
3228
- return formatResult(result);
3229
- }
3230
- });
3231
- }
3232
- function createGitHubSearchTool(config) {
3233
- const client = new WarpGrepClient(config);
3234
- const tool4 = {
3235
- type: "function",
3236
- function: {
3237
- name: GITHUB_SEARCH_TOOL_NAME,
3238
- description: GITHUB_SEARCH_DESCRIPTION,
3239
- parameters: GITHUB_SEARCH_INPUT_SCHEMA
3240
- }
3241
- };
3242
- return Object.assign(tool4, {
3243
- execute: async (input) => {
3244
- const github = input.github_url || input.owner_repo;
3245
- if (!github) {
3246
- throw new Error("Please provide github search url or owner/repo id");
3247
- }
3248
- return client.searchGitHub({ searchTerm: input.search_term, github, branch: input.branch });
3249
- },
3250
- formatResult: (result) => {
3251
- return formatResult(result);
3252
- }
3253
- });
3254
- }
3255
-
3256
- // tools/fastapply/prompts.ts
3257
- var EDIT_FILE_TOOL_DESCRIPTION = `Use this tool to make an edit to an existing file.
3258
-
3259
- This will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.
3260
-
3261
- When writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.
3262
-
3263
- For example:
3264
-
3265
- // ... existing code ...
3266
- FIRST_EDIT
3267
- // ... existing code ...
3268
- SECOND_EDIT
3269
- // ... existing code ...
3270
- THIRD_EDIT
3271
- // ... existing code ...
3272
-
3273
- You should still bias towards repeating as few lines of the original file as possible to convey the change.
3274
- But, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.
3275
-
3276
- DO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.
3277
-
3278
- If you plan on deleting a section, you must provide context before and after to delete it.
3279
-
3280
- Make sure it is clear what the edit should be, and where it should be applied.
3281
- Make edits to a file in a single edit_file call instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.`;
3282
- var EDIT_FILE_SYSTEM_PROMPT = `When the user is asking for edits to their code, use the edit_file tool to highlight the changes necessary and add comments to indicate where unchanged code has been skipped. For example:
3283
-
3284
- // ... existing code ...
3285
- {{ edit_1 }}
3286
- // ... existing code ...
3287
- {{ edit_2 }}
3288
- // ... existing code ...
3289
-
3290
- Often this will mean that the start/end of the file will be skipped, but that's okay! Rewrite the entire file ONLY if specifically requested. Always provide a brief explanation of the updates, unless the user specifically requests only the code.
3291
-
3292
- These edit codeblocks are also read by a less intelligent language model, colloquially called the apply model, to update the file. To help specify the edit to the apply model, you will be very careful when generating the codeblock to not introduce ambiguity. You will specify all unchanged regions (code and comments) of the file with "// ... existing code ..." comment markers. This will ensure the apply model will not delete existing unchanged code or comments when editing the file.`;
3293
-
3294
- // tools/fastapply/openai.ts
3295
- var editFileTool = {
3296
- type: "function",
3297
- function: {
3298
- name: "edit_file",
3299
- description: EDIT_FILE_TOOL_DESCRIPTION,
3300
- parameters: {
3301
- type: "object",
3302
- properties: {
3303
- target_filepath: {
3304
- type: "string",
3305
- description: "The path of the target file to modify"
3306
- },
3307
- instruction: {
3308
- type: "string",
3309
- description: "A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."
3310
- },
3311
- code_edit: {
3312
- type: "string",
3313
- description: "Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections."
3314
- }
3315
- },
3316
- required: ["target_filepath", "instruction", "code_edit"]
3317
- }
3318
- }
3319
- };
3320
- async function execute(input, config) {
3321
- return executeEditFile(input, config);
3322
- }
3323
- function getSystemPrompt() {
3324
- return EDIT_FILE_SYSTEM_PROMPT;
3325
- }
3326
- function formatResult2(result) {
3327
- if (!result.success) {
3328
- return `Error editing file: ${result.error}`;
3329
- }
3330
- const { changes } = result;
3331
- return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;
3332
- }
3333
- function createEditFileTool(config = {}) {
3334
- const toolDef = {
3335
- ...editFileTool,
3336
- ...config.description && {
3337
- function: {
3338
- ...editFileTool.function,
3339
- description: config.description
3340
- }
3341
- }
3342
- };
3343
- return Object.assign({}, toolDef, {
3344
- execute: async (input) => {
3345
- const parsedInput = typeof input === "string" ? JSON.parse(input) : input;
3346
- return execute(parsedInput, config);
3347
- },
3348
- formatResult: (result) => {
3349
- return formatResult2(result);
3350
- },
3351
- getSystemPrompt: () => {
3352
- return getSystemPrompt();
3353
- }
3354
- });
3355
- }
3356
-
3357
- // factories/openai.ts
3358
- var OpenAIToolFactory = class {
3359
- constructor(config) {
3360
- this.config = config;
3361
- }
3362
- /**
3363
- * Create an OpenAI-compatible warp grep tool
3364
- *
3365
- * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
3366
- * @returns OpenAI ChatCompletionTool with execute and formatResult methods
3367
- */
3368
- createWarpGrepTool(toolConfig) {
3369
- return createWarpGrepTool({
3370
- ...toolConfig,
3371
- morphApiKey: this.config.apiKey
3372
- });
3373
- }
3374
- /**
3375
- * Create an OpenAI-compatible edit file tool
3376
- *
3377
- * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
3378
- * @returns OpenAI ChatCompletionTool with execute and formatResult methods
3379
- */
3380
- createEditFileTool(toolConfig = {}) {
3381
- return createEditFileTool({
3382
- ...toolConfig,
3383
- morphApiKey: this.config.apiKey
3384
- });
3385
- }
3386
- /**
3387
- * Create an OpenAI-compatible GitHub search tool
3388
- *
3389
- * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
3390
- * @returns OpenAI ChatCompletionTool with execute and formatResult methods
3391
- */
3392
- createGitHubSearchTool(toolConfig) {
3393
- return createGitHubSearchTool({
3394
- ...toolConfig,
3395
- morphApiKey: this.config.apiKey
3396
- });
3397
- }
3398
- };
3399
-
3400
- // tools/warp_grep/anthropic.ts
3401
- var INPUT_SCHEMA = {
3402
- type: "object",
3403
- properties: {
3404
- search_term: { type: "string", description: "Search problem statement that this subagent is supposed to research for" }
3405
- },
3406
- required: ["search_term"]
3407
- };
3408
- function createWarpGrepTool2(config) {
3409
- const tool4 = {
3410
- name: config.name ?? WARP_GREP_TOOL_NAME,
3411
- description: config.description ?? WARP_GREP_DESCRIPTION,
3412
- input_schema: INPUT_SCHEMA
3413
- };
3414
- return Object.assign(tool4, {
3415
- execute: async (input) => {
3416
- return executeToolCall(input, config);
3417
- },
3418
- formatResult: (result) => {
3419
- return formatResult(result);
3420
- }
3421
- });
3422
- }
3423
- function createGitHubSearchTool2(config) {
3424
- const client = new WarpGrepClient(config);
3425
- const tool4 = {
3426
- name: GITHUB_SEARCH_TOOL_NAME,
3427
- description: GITHUB_SEARCH_DESCRIPTION,
3428
- input_schema: GITHUB_SEARCH_INPUT_SCHEMA
3429
- };
3430
- return Object.assign(tool4, {
3431
- execute: async (input) => {
3432
- const github = input.github_url || input.owner_repo;
3433
- if (!github) {
3434
- throw new Error("Please provide github search url or owner/repo id");
3435
- }
3436
- return client.searchGitHub({ searchTerm: input.search_term, github, branch: input.branch });
3437
- },
3438
- formatResult: (result) => {
3439
- return formatResult(result);
3440
- }
3441
- });
3442
- }
3443
-
3444
- // tools/fastapply/anthropic.ts
3445
- var editFileTool2 = {
3446
- name: "edit_file",
3447
- description: EDIT_FILE_TOOL_DESCRIPTION,
3448
- input_schema: {
3449
- type: "object",
3450
- properties: {
3451
- target_filepath: {
3452
- type: "string",
3453
- description: "The path of the target file to modify"
3454
- },
3455
- instruction: {
3456
- type: "string",
3457
- description: "A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."
3458
- },
3459
- code_edit: {
3460
- type: "string",
3461
- description: "Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections."
3462
- }
3463
- },
3464
- required: ["target_filepath", "instruction", "code_edit"]
3465
- }
3466
- };
3467
- function formatResult3(result) {
3468
- if (!result.success) {
3469
- return `Error editing file: ${result.error}`;
3470
- }
3471
- const { changes } = result;
3472
- return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;
3473
- }
3474
- function createEditFileTool2(config = {}) {
3475
- const toolDef = {
3476
- ...editFileTool2,
3477
- ...config.description && { description: config.description }
3478
- };
3479
- return Object.assign({}, toolDef, {
3480
- execute: async (input) => {
3481
- return executeEditFile(input, config);
3482
- },
3483
- formatResult: (result) => {
3484
- return formatResult3(result);
3485
- },
3486
- getSystemPrompt: () => {
3487
- return EDIT_FILE_SYSTEM_PROMPT;
3488
- }
3489
- });
3490
- }
3491
-
3492
- // subagents/prompts.ts
3493
- var THOROUGHNESS_INSTRUCTIONS = {
3494
- quick: `Do 1-2 targeted searches. Find the most relevant file/function quickly and summarize. Don't go deep.`,
3495
- medium: `Do 2-4 searches. Start broad, then follow up on the most promising leads. Cover the main aspects.`,
3496
- 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.`
3497
- };
3498
- function getSystemPrompt2(thoroughness = "medium") {
3499
- return `You are a codebase exploration specialist. Your job is to search a codebase and return a concise, accurate summary of what you find.
3500
-
3501
- ## Mode
3502
- READ-ONLY. You cannot modify files. You can only search and read code.
3503
-
3504
- ## Strategy
3505
- ${THOROUGHNESS_INSTRUCTIONS[thoroughness]}
3506
-
3507
- - Use multiple focused searches rather than one vague search
3508
- - Follow imports, function calls, and type references to build complete understanding
3509
- - If a search returns no results, try alternative terms (e.g., "auth" vs "authentication" vs "login")
3510
- - Look at both implementation and tests when relevant
3511
-
3512
- ## Communication
3513
- You have a \`send_message\` tool. Use it when:
3514
- - You hit a fork in the road and need guidance ("Found auth in both src/middleware/ and legacy/auth/. Which should I focus on?")
3515
- - You need clarification on ambiguous requests ("There are 3 auth strategies: JWT, session, OAuth. Which one?")
3516
- - 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.")
3517
-
3518
- 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.
3519
-
3520
- ## Output
3521
- When you have enough information, output your final summary. Structure it as:
3522
- 1. Direct answer to the question
3523
- 2. Key files and their roles
3524
- 3. How the pieces connect
3525
-
3526
- Be concise. The summary should be useful to another AI model that will use your findings to complete a task.`;
3527
- }
3528
- var CODEBASE_SEARCH_TOOL = {
3529
- name: "codebase_search",
3530
- 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.",
3531
- input_schema: {
3532
- type: "object",
3533
- properties: {
3534
- searchRequest: {
3535
- type: "string",
3536
- description: "Natural language description of what to search for in the codebase"
3537
- }
3538
- },
3539
- required: ["searchRequest"],
3540
- additionalProperties: false
3541
- }
3542
- };
3543
- var SEND_MESSAGE_TOOL = {
3544
- name: "send_message",
3545
- 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.",
3546
- input_schema: {
3547
- type: "object",
3548
- properties: {
3549
- message: {
3550
- type: "string",
3551
- description: "The message to send to the orchestrator"
3552
- }
3553
- },
3554
- required: ["message"],
3555
- additionalProperties: false
3556
- }
3557
- };
3558
-
3559
- // subagents/anthropic.ts
3560
- var DEFAULT_MAX_TURNS = {
3561
- quick: 3,
3562
- medium: 6,
3563
- thorough: 12
3564
- };
3565
- function getMaxTurns(config) {
3566
- return config.maxTurns ?? DEFAULT_MAX_TURNS[config.thoroughness ?? "medium"] ?? 6;
3567
- }
3568
- var TOOLS = [
3569
- {
3570
- name: CODEBASE_SEARCH_TOOL.name,
3571
- description: CODEBASE_SEARCH_TOOL.description,
3572
- input_schema: CODEBASE_SEARCH_TOOL.input_schema
3573
- },
3574
- {
3575
- name: SEND_MESSAGE_TOOL.name,
3576
- description: SEND_MESSAGE_TOOL.description,
3577
- input_schema: SEND_MESSAGE_TOOL.input_schema
3578
- }
3579
- ];
3580
- function createExploreSubagent(config) {
3581
- if (!config.repoRoot) {
3582
- throw new Error("repoRoot is required for Explore subagent");
3583
- }
3584
- const warpGrep = new WarpGrepClient({
3585
- morphApiKey: config.morphApiKey
3586
- });
3587
- const thoroughness = config.thoroughness ?? "medium";
3588
- const maxTurns = getMaxTurns(config);
3589
- const replyTimeout = config.replyTimeout ?? 3e4;
3590
- async function runExplore(prompt, callbacks = {}) {
3591
- const startTime = Date.now();
3592
- const allContexts = [];
3593
- let searchCount = 0;
3594
- const timeoutMs = config.timeout;
3595
- try {
3596
- const messages = [{ role: "user", content: prompt }];
3597
- let turns = 0;
3598
- while (turns < maxTurns) {
3599
- if (timeoutMs && Date.now() - startTime > timeoutMs) {
3600
- return {
3601
- success: false,
3602
- summary: "",
3603
- contexts: deduplicateContexts(allContexts),
3604
- searchCount,
3605
- durationMs: Date.now() - startTime,
3606
- error: `Exploration timed out after ${timeoutMs}ms`
3607
- };
3608
- }
3609
- const response = await config.client.messages.create({
3610
- model: config.model,
3611
- max_tokens: 4096,
3612
- system: getSystemPrompt2(thoroughness),
3613
- tools: TOOLS,
3614
- messages
3615
- });
3616
- turns++;
3617
- if (response.stop_reason === "end_turn" || !response.content.some((b) => b.type === "tool_use")) {
3618
- const textBlock = response.content.find((b) => b.type === "text");
3619
- const summary = textBlock?.text || "Exploration completed but no summary was generated.";
3620
- callbacks.onStep?.({
3621
- step: searchCount,
3622
- searchRequest: "",
3623
- contextsFound: allContexts.length,
3624
- isFinal: true
3625
- });
3626
- return {
3627
- success: true,
3628
- summary,
3629
- contexts: deduplicateContexts(allContexts),
3630
- searchCount,
3631
- durationMs: Date.now() - startTime
3632
- };
3633
- }
3634
- messages.push({ role: "assistant", content: response.content });
3635
- const toolResults = [];
3636
- for (const block of response.content) {
3637
- if (block.type !== "tool_use") continue;
3638
- if (block.name === "codebase_search") {
3639
- searchCount++;
3640
- const input = block.input;
3641
- const warpResult = await warpGrep.execute({
3642
- searchTerm: input.searchRequest,
3643
- repoRoot: config.repoRoot,
3644
- excludes: config.excludes,
3645
- includes: config.includes
3646
- });
3647
- if (warpResult.contexts) {
3648
- allContexts.push(...warpResult.contexts);
3649
- }
3650
- callbacks.onStep?.({
3651
- step: searchCount,
3652
- searchRequest: input.searchRequest,
3653
- contextsFound: warpResult.contexts?.length ?? 0,
3654
- isFinal: false
3655
- });
3656
- toolResults.push({
3657
- type: "tool_result",
3658
- tool_use_id: block.id,
3659
- content: formatResult(warpResult)
3660
- });
3661
- } else if (block.name === "send_message") {
3662
- const input = block.input;
3663
- const subagentMsg = {
3664
- from: "explore",
3665
- content: input.message,
3666
- timestamp: Date.now()
3667
- };
3668
- let replyText = "";
3669
- if (callbacks.onMessage) {
3670
- replyText = await Promise.race([
3671
- new Promise((resolve2) => {
3672
- callbacks.onMessage(subagentMsg, (text) => {
3673
- resolve2(text);
3674
- });
3675
- }),
3676
- new Promise(
3677
- (resolve2) => setTimeout(() => resolve2(""), replyTimeout)
3678
- )
3679
- ]);
3680
- }
3681
- const toolResponse = replyText ? `Response from orchestrator: ${replyText}` : "No response. Continue with your best judgment.";
3682
- toolResults.push({
3683
- type: "tool_result",
3684
- tool_use_id: block.id,
3685
- content: toolResponse
3686
- });
3687
- }
3688
- }
3689
- messages.push({ role: "user", content: toolResults });
3690
- }
3691
- return {
3692
- success: true,
3693
- summary: "Exploration completed (max turns reached).",
3694
- contexts: deduplicateContexts(allContexts),
3695
- searchCount,
3696
- durationMs: Date.now() - startTime
3697
- };
3698
- } catch (error) {
3699
- return {
3700
- success: false,
3701
- summary: "",
3702
- contexts: deduplicateContexts(allContexts),
3703
- searchCount,
3704
- durationMs: Date.now() - startTime,
3705
- error: error instanceof Error ? error.message : String(error)
3706
- };
3707
- }
3708
- }
3709
- const exploreTool = Object.assign(
3710
- {
3711
- name: "explore",
3712
- description: "Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings.",
3713
- input_schema: {
3714
- type: "object",
3715
- properties: {
3716
- searchRequest: {
3717
- type: "string",
3718
- description: "What to explore in the codebase. Be specific about what you want to understand."
3719
- }
3720
- },
3721
- required: ["searchRequest"]
3722
- }
3723
- },
3724
- {
3725
- execute: async (input) => {
3726
- return runExplore(input.searchRequest);
3727
- },
3728
- formatResult: (result) => {
3729
- if (!result.success) {
3730
- return `Exploration failed: ${result.error}`;
3731
- }
3732
- return result.summary;
3733
- }
3734
- }
3735
- );
3736
- return {
3737
- /** Anthropic Tool definition for use in parent agents */
3738
- tool: exploreTool,
3739
- /** Run exploration with messaging support */
3740
- run(prompt) {
3741
- const messageHandlers = [];
3742
- const stepHandlers = [];
3743
- let resultPromise = null;
3744
- const session = {
3745
- on(event, handler) {
3746
- if (event === "message") messageHandlers.push(handler);
3747
- if (event === "step") stepHandlers.push(handler);
3748
- return session;
3749
- },
3750
- send(_text) {
3751
- },
3752
- get result() {
3753
- if (!resultPromise) {
3754
- resultPromise = runExplore(prompt, {
3755
- onStep: (step) => {
3756
- for (const handler of stepHandlers) handler(step);
3757
- },
3758
- onMessage: (msg, reply) => {
3759
- if (messageHandlers.length > 0) {
3760
- for (const handler of messageHandlers) handler(msg, reply);
3761
- } else {
3762
- reply("");
3763
- }
3764
- }
3765
- });
3766
- }
3767
- return resultPromise;
3768
- }
3769
- };
3770
- return session;
3771
- },
3772
- /** Stream exploration events as an async generator */
3773
- async *stream(prompt) {
3774
- const events = [];
3775
- let resolveNext = null;
3776
- let done = false;
3777
- const resultPromise = runExplore(prompt, {
3778
- onStep: (step) => {
3779
- events.push({
3780
- type: "step",
3781
- step: step.step,
3782
- searchRequest: step.searchRequest,
3783
- contextsFound: step.contextsFound,
3784
- isFinal: step.isFinal
3785
- });
3786
- resolveNext?.();
3787
- },
3788
- onMessage: (msg, reply) => {
3789
- events.push({
3790
- type: "message",
3791
- from: msg.from,
3792
- content: msg.content,
3793
- timestamp: msg.timestamp
3794
- });
3795
- resolveNext?.();
3796
- reply("Continue with your best judgment.");
3797
- }
3798
- });
3799
- while (!done) {
3800
- if (events.length > 0) {
3801
- yield events.shift();
3802
- } else {
3803
- const raceResult = await Promise.race([
3804
- resultPromise.then((r) => ({ type: "done", result: r })),
3805
- new Promise((resolve2) => {
3806
- resolveNext = () => resolve2({ type: "event" });
3807
- })
3808
- ]);
3809
- if (raceResult.type === "done") {
3810
- while (events.length > 0) {
3811
- yield events.shift();
3812
- }
3813
- done = true;
3814
- return raceResult.result;
3815
- }
3816
- }
3817
- }
3818
- return await resultPromise;
3819
- }
3820
- };
3821
- }
3822
- function deduplicateContexts(contexts) {
3823
- const map = /* @__PURE__ */ new Map();
3824
- for (const ctx of contexts) {
3825
- const existing = map.get(ctx.file);
3826
- if (!existing || ctx.content.length > existing.content.length) {
3827
- map.set(ctx.file, ctx);
3828
- }
3829
- }
3830
- return Array.from(map.values());
3831
- }
3832
-
3833
- // factories/anthropic.ts
3834
- var AnthropicToolFactory = class {
3835
- constructor(config) {
3836
- this.config = config;
3837
- }
3838
- /**
3839
- * Create an Anthropic-compatible warp grep tool
3840
- *
3841
- * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
3842
- * @returns Anthropic Tool with execute and formatResult methods
3843
- */
3844
- createWarpGrepTool(toolConfig) {
3845
- return createWarpGrepTool2({
3846
- ...toolConfig,
3847
- morphApiKey: this.config.apiKey
3848
- });
3849
- }
3850
- /**
3851
- * Create an Anthropic-compatible edit file tool
3852
- *
3853
- * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
3854
- * @returns Anthropic Tool with execute and formatResult methods
3855
- */
3856
- createEditFileTool(toolConfig = {}) {
3857
- return createEditFileTool2({
3858
- ...toolConfig,
3859
- morphApiKey: this.config.apiKey
3860
- });
3861
- }
3862
- /**
3863
- * Create an Anthropic-compatible GitHub search tool
3864
- *
3865
- * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
3866
- * @returns Anthropic Tool with execute and formatResult methods
3867
- */
3868
- createGitHubSearchTool(toolConfig) {
3869
- return createGitHubSearchTool2({
3870
- ...toolConfig,
3871
- morphApiKey: this.config.apiKey
3872
- });
3873
- }
3874
- /**
3875
- * Create an Explore subagent that searches the codebase and returns summaries
3876
- *
3877
- * @param config - Subagent configuration including client and model (morphApiKey inherited from MorphClient)
3878
- * @returns Explore subagent with .tool, .run(), and .stream() methods
3879
- */
3880
- createExploreSubagent(config) {
3881
- return createExploreSubagent({
3882
- ...config,
3883
- morphApiKey: this.config.apiKey
3884
- });
3885
- }
3886
- };
3887
-
3888
- // tools/warp_grep/vercel.ts
3889
- var import_ai = require("ai");
3890
- var import_zod = require("zod");
3891
- function createWarpGrepTool3(config) {
3892
- const schema = config.inputSchema ?? import_zod.z.object({
3893
- search_term: import_zod.z.string().describe("Search problem statement that this subagent is supposed to research for")
3894
- });
3895
- return (0, import_ai.tool)({
3896
- description: config.description ?? WARP_GREP_DESCRIPTION,
3897
- inputSchema: schema,
3898
- execute: async (params) => {
3899
- const steps = [];
3900
- const generator = executeToolCallStreaming(params, config);
3901
- let result;
3902
- for (; ; ) {
3903
- const { value, done } = await generator.next();
3904
- if (done) {
3905
- result = value;
3906
- break;
3907
- }
3908
- steps.push(value);
3909
- }
3910
- if (!result.success) {
3911
- throw new Error(`Failed to search codebase: ${result.error}`);
3912
- }
3913
- const allToolCalls = steps.flatMap((s) => s.toolCalls);
3914
- return {
3915
- success: true,
3916
- contexts: result.contexts,
3917
- summary: result.summary,
3918
- progress: allToolCalls.length > 0 ? { turn: steps.length, toolCalls: allToolCalls } : void 0
3919
- };
3920
- }
3921
- });
3922
- }
3923
- function createGitHubSearchTool3(config) {
3924
- const client = new WarpGrepClient(config);
3925
- return (0, import_ai.tool)({
3926
- description: GITHUB_SEARCH_DESCRIPTION,
3927
- inputSchema: import_zod.z.object({
3928
- search_term: import_zod.z.string().describe("Search problem statement that this subagent is supposed to research for"),
3929
- github_url: import_zod.z.string().optional().describe('GitHub repository URL to search (e.g. "https://github.com/vercel/next.js"). You must provide either github_url or owner_repo.'),
3930
- owner_repo: import_zod.z.string().optional().describe('Repository owner/repo shorthand (e.g. "vercel/next.js"). You must provide either github_url or owner_repo.'),
3931
- branch: import_zod.z.string().optional().describe("Branch to search (defaults to repo default branch)")
3932
- }),
3933
- execute: async (params) => {
3934
- const github = params.github_url || params.owner_repo;
3935
- if (!github) {
3936
- throw new Error("Please provide github search url or owner/repo id");
3937
- }
3938
- const result = await client.searchGitHub({ searchTerm: params.search_term, github, branch: params.branch });
3939
- if (!result.success) {
3940
- throw new Error(`GitHub search failed: ${result.error}`);
3941
- }
3942
- return {
3943
- success: true,
3944
- contexts: result.contexts,
3945
- summary: result.summary
3946
- };
3947
- }
3948
- });
3949
- }
3950
-
3951
- // tools/fastapply/vercel.ts
3952
- var import_ai2 = require("ai");
3953
- var import_zod2 = require("zod");
3954
- var editFileSchema = import_zod2.z.object({
3955
- target_filepath: import_zod2.z.string().describe("The path of the target file to modify"),
3956
- instruction: import_zod2.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
3957
- code_edit: import_zod2.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
3958
- });
3959
- var editFileTool3 = (0, import_ai2.tool)({
3960
- description: EDIT_FILE_TOOL_DESCRIPTION,
3961
- inputSchema: editFileSchema,
3962
- execute: async (params) => {
3963
- const result = await executeEditFile({
3964
- target_filepath: params.target_filepath,
3965
- instruction: params.instruction,
3966
- code_edit: params.code_edit
3967
- });
3968
- if (!result.success) {
3969
- throw new Error(`Failed to edit file: ${result.error}`);
3970
- }
3971
- return {
3972
- success: true,
3973
- filepath: result.filepath,
3974
- changes: result.changes,
3975
- udiff: result.udiff
3976
- };
3977
- }
3978
- });
3979
- function createEditFileTool3(config = {}) {
3980
- const schema = import_zod2.z.object({
3981
- target_filepath: import_zod2.z.string().describe("The path of the target file to modify"),
3982
- instruction: import_zod2.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
3983
- code_edit: import_zod2.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
3984
- });
3985
- return (0, import_ai2.tool)({
3986
- description: config.description || EDIT_FILE_TOOL_DESCRIPTION,
3987
- inputSchema: schema,
3988
- execute: async (params) => {
3989
- const result = await executeEditFile(
3990
- {
3991
- target_filepath: params.target_filepath,
3992
- instruction: params.instruction,
3993
- code_edit: params.code_edit
3994
- },
3995
- config
3996
- );
3997
- if (!result.success) {
3998
- throw new Error(`Failed to edit file: ${result.error}`);
3999
- }
4000
- return {
4001
- success: true,
4002
- filepath: result.filepath,
4003
- changes: result.changes,
4004
- udiff: result.udiff
4005
- };
4006
- }
4007
- });
4008
- }
4009
-
4010
- // subagents/vercel.ts
4011
- var import_ai3 = require("ai");
4012
- var import_zod3 = require("zod");
4013
- var DEFAULT_MAX_TURNS2 = {
4014
- quick: 3,
4015
- medium: 6,
4016
- thorough: 12
4017
- };
4018
- function getMaxTurns2(config) {
4019
- return config.maxTurns ?? DEFAULT_MAX_TURNS2[config.thoroughness ?? "medium"] ?? 6;
4020
- }
4021
- function createExploreSubagent2(config) {
4022
- if (!config.repoRoot) {
4023
- throw new Error("repoRoot is required for Explore subagent");
4024
- }
4025
- const warpGrep = new WarpGrepClient({
4026
- morphApiKey: config.morphApiKey
4027
- });
4028
- const thoroughness = config.thoroughness ?? "medium";
4029
- const replyTimeout = config.replyTimeout ?? 3e4;
4030
- async function runExplore(prompt, callbacks = {}) {
4031
- const startTime = Date.now();
4032
- const allContexts = [];
4033
- let searchCount = 0;
4034
- const timeoutMs = config.timeout;
4035
- const timeoutPromise = timeoutMs ? new Promise(
4036
- (_, reject) => setTimeout(() => reject(new Error(`Exploration timed out after ${timeoutMs}ms`)), timeoutMs)
4037
- ) : null;
4038
- const runPromise = (async () => {
4039
- try {
4040
- const codebaseSearchSchema = import_zod3.z.object({
4041
- searchRequest: import_zod3.z.string().describe("Natural language description of what to search for")
4042
- });
4043
- const sendMessageSchema = import_zod3.z.object({
4044
- message: import_zod3.z.string().describe("The message to send to the orchestrator")
4045
- });
4046
- const result = await (0, import_ai3.generateText)({
4047
- model: config.model,
4048
- system: getSystemPrompt2(thoroughness),
4049
- prompt,
4050
- tools: {
4051
- codebase_search: (0, import_ai3.tool)({
4052
- description: CODEBASE_SEARCH_TOOL.description,
4053
- inputSchema: codebaseSearchSchema,
4054
- execute: async (params) => {
4055
- searchCount++;
4056
- const warpResult = await warpGrep.execute({
4057
- searchTerm: params.searchRequest,
4058
- repoRoot: config.repoRoot,
4059
- excludes: config.excludes,
4060
- includes: config.includes
4061
- });
4062
- if (warpResult.contexts) {
4063
- allContexts.push(...warpResult.contexts);
4064
- }
4065
- callbacks.onStep?.({
4066
- step: searchCount,
4067
- searchRequest: params.searchRequest,
4068
- contextsFound: warpResult.contexts?.length ?? 0,
4069
- isFinal: false
4070
- });
4071
- return formatResult(warpResult);
4072
- }
4073
- }),
4074
- send_message: (0, import_ai3.tool)({
4075
- description: SEND_MESSAGE_TOOL.description,
4076
- inputSchema: sendMessageSchema,
4077
- execute: async (params) => {
4078
- const subagentMsg = {
4079
- from: "explore",
4080
- content: params.message,
4081
- timestamp: Date.now()
4082
- };
4083
- const replyPromise = new Promise((resolve2) => {
4084
- if (callbacks.onMessage) {
4085
- callbacks.onMessage(subagentMsg, (replyText) => {
4086
- resolve2(replyText);
4087
- });
4088
- } else {
4089
- setTimeout(() => resolve2(""), replyTimeout);
4090
- }
4091
- });
4092
- const reply = await Promise.race([
4093
- replyPromise,
4094
- new Promise(
4095
- (resolve2) => setTimeout(() => resolve2(""), replyTimeout)
4096
- )
4097
- ]);
4098
- if (reply) {
4099
- return `Response from orchestrator: ${reply}`;
4100
- }
4101
- return "No response. Continue with your best judgment.";
4102
- }
4103
- })
4104
- },
4105
- stopWhen: (0, import_ai3.stepCountIs)(getMaxTurns2(config))
4106
- });
4107
- callbacks.onStep?.({
4108
- step: searchCount,
4109
- searchRequest: "",
4110
- contextsFound: allContexts.length,
4111
- isFinal: true
4112
- });
4113
- const uniqueContexts = deduplicateContexts2(allContexts);
4114
- return {
4115
- success: true,
4116
- summary: result.text || "Exploration completed but no summary was generated.",
4117
- contexts: uniqueContexts,
4118
- searchCount,
4119
- durationMs: Date.now() - startTime
4120
- };
4121
- } catch (error) {
4122
- return {
4123
- success: false,
4124
- summary: "",
4125
- contexts: deduplicateContexts2(allContexts),
4126
- searchCount,
4127
- durationMs: Date.now() - startTime,
4128
- error: error instanceof Error ? error.message : String(error)
4129
- };
4130
- }
4131
- })();
4132
- if (timeoutPromise) {
4133
- try {
4134
- return await Promise.race([runPromise, timeoutPromise]);
4135
- } catch (error) {
4136
- return {
4137
- success: false,
4138
- summary: "",
4139
- contexts: deduplicateContexts2(allContexts),
4140
- searchCount,
4141
- durationMs: Date.now() - startTime,
4142
- error: error instanceof Error ? error.message : String(error)
4143
- };
4144
- }
4145
- }
4146
- return runPromise;
4147
- }
4148
- const exploreToolSchema = import_zod3.z.object({
4149
- searchRequest: import_zod3.z.string().describe("What to explore in the codebase. Be specific about what you want to understand.")
4150
- });
4151
- const exploreTool = (0, import_ai3.tool)({
4152
- description: "Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings. Use this for broad exploration rather than pinpoint keyword searches.",
4153
- inputSchema: exploreToolSchema,
4154
- execute: async (params) => {
4155
- const result = await runExplore(params.searchRequest);
4156
- return {
4157
- success: result.success,
4158
- summary: result.summary,
4159
- searchCount: result.searchCount,
4160
- error: result.error
4161
- };
4162
- }
4163
- });
4164
- return {
4165
- /** Vercel AI SDK tool for use as a tool in parent agents */
4166
- tool: exploreTool,
4167
- /** Run exploration with messaging support */
4168
- run(prompt) {
4169
- const messageHandlers = [];
4170
- const stepHandlers = [];
4171
- let resultPromise = null;
4172
- const session = {
4173
- on(event, handler) {
4174
- if (event === "message") messageHandlers.push(handler);
4175
- if (event === "step") stepHandlers.push(handler);
4176
- return session;
4177
- },
4178
- send(_text) {
4179
- },
4180
- get result() {
4181
- if (!resultPromise) {
4182
- resultPromise = runExplore(prompt, {
4183
- onStep: (step) => {
4184
- for (const handler of stepHandlers) handler(step);
4185
- },
4186
- onMessage: (msg, reply) => {
4187
- if (messageHandlers.length > 0) {
4188
- for (const handler of messageHandlers) handler(msg, reply);
4189
- } else {
4190
- reply("");
4191
- }
4192
- }
4193
- });
4194
- }
4195
- return resultPromise;
4196
- }
4197
- };
4198
- return session;
4199
- },
4200
- /** Stream exploration events as an async generator */
4201
- async *stream(prompt) {
4202
- const events = [];
4203
- let resolveNext = null;
4204
- let done = false;
4205
- const resultPromise = runExplore(prompt, {
4206
- onStep: (step) => {
4207
- events.push({
4208
- type: "step",
4209
- step: step.step,
4210
- searchRequest: step.searchRequest,
4211
- contextsFound: step.contextsFound,
4212
- isFinal: step.isFinal
4213
- });
4214
- resolveNext?.();
4215
- },
4216
- onMessage: (msg, reply) => {
4217
- events.push({
4218
- type: "message",
4219
- from: msg.from,
4220
- content: msg.content,
4221
- timestamp: msg.timestamp
4222
- });
4223
- resolveNext?.();
4224
- reply("Continue with your best judgment.");
4225
- }
4226
- });
4227
- while (!done) {
4228
- if (events.length > 0) {
4229
- yield events.shift();
4230
- } else {
4231
- const raceResult = await Promise.race([
4232
- resultPromise.then((r) => ({ type: "done", result: r })),
4233
- new Promise((resolve2) => {
4234
- resolveNext = () => resolve2({ type: "event" });
4235
- })
4236
- ]);
4237
- if (raceResult.type === "done") {
4238
- while (events.length > 0) {
4239
- yield events.shift();
4240
- }
4241
- done = true;
4242
- return raceResult.result;
4243
- }
4244
- }
4245
- }
4246
- return await resultPromise;
4247
- }
4248
- };
4249
- }
4250
- function deduplicateContexts2(contexts) {
4251
- const map = /* @__PURE__ */ new Map();
4252
- for (const ctx of contexts) {
4253
- const existing = map.get(ctx.file);
4254
- if (!existing || ctx.content.length > existing.content.length) {
4255
- map.set(ctx.file, ctx);
4256
- }
4257
- }
4258
- return Array.from(map.values());
4259
- }
4260
-
4261
- // factories/vercel.ts
4262
- var VercelToolFactory = class {
4263
- constructor(config) {
4264
- this.config = config;
4265
- }
4266
- /**
4267
- * Create a Vercel AI SDK-compatible warp grep tool
4268
- *
4269
- * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
4270
- * @returns Vercel AI SDK tool
4271
- */
4272
- createWarpGrepTool(toolConfig) {
4273
- return createWarpGrepTool3({
4274
- ...toolConfig,
4275
- morphApiKey: this.config.apiKey
4276
- });
4277
- }
4278
- /**
4279
- * Create a Vercel AI SDK-compatible edit file tool
4280
- *
4281
- * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
4282
- * @returns Vercel AI SDK tool
4283
- */
4284
- createEditFileTool(toolConfig = {}) {
4285
- return createEditFileTool3({
4286
- ...toolConfig,
4287
- morphApiKey: this.config.apiKey
4288
- });
4289
- }
4290
- /**
4291
- * Create a Vercel AI SDK-compatible GitHub search tool
4292
- *
4293
- * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
4294
- * @returns Vercel AI SDK tool
4295
- */
4296
- createGitHubSearchTool(toolConfig) {
4297
- return createGitHubSearchTool3({
4298
- ...toolConfig,
4299
- morphApiKey: this.config.apiKey
4300
- });
4301
- }
4302
- /**
4303
- * Create an Explore subagent that searches the codebase and returns summaries
4304
- *
4305
- * @param config - Subagent configuration including model (morphApiKey inherited from MorphClient)
4306
- * @returns Explore subagent with .tool, .run(), and .stream() methods
4307
- */
4308
- createExploreSubagent(config) {
4309
- return createExploreSubagent2({
4310
- ...config,
4311
- morphApiKey: this.config.apiKey
4312
- });
4313
- }
4314
- };
4315
-
4316
- // client.ts
4317
- var MorphClient = class extends MorphAPIClient {
4318
- /** Client configuration */
4319
- config;
4320
- /** FastApply tool for editing files with AI-powered merge */
4321
- fastApply;
4322
- /** WarpGrep tool for fast code search using ripgrep */
4323
- warpGrep;
4324
- /** Model routers for intelligent model selection */
4325
- routers;
4326
- /** OpenAI-compatible tool factories */
4327
- openai;
4328
- /** Anthropic-compatible tool factories */
4329
- anthropic;
4330
- /** Vercel AI SDK tool factories */
4331
- vercel;
4332
- /** Compact context with line ranges */
4333
- compact;
4334
- /**
4335
- * Create a new Morph SDK client
4336
- *
4337
- * @param config - Client configuration (apiKey, debug, timeout, retryConfig)
4338
- *
4339
- * @example
4340
- * ```typescript
4341
- * const morph = new MorphClient({
4342
- * apiKey: process.env.MORPH_API_KEY,
4343
- * debug: true,
4344
- * timeout: 60000
4345
- * });
4346
- * ```
4347
- */
4348
- constructor(config = {}) {
4349
- super({
4350
- apiKey: config.apiKey,
4351
- timeout: config.timeout,
4352
- retryConfig: config.retryConfig,
4353
- debug: config.debug
4354
- });
4355
- if (!config.apiKey) {
4356
- throw new Error("Morph API key is required. Pass it as { apiKey } when constructing MorphClient.");
4357
- }
4358
- this.config = config;
4359
- logger.debug("MorphClient", "initialized", { debug: !!config.debug, timeout: config.timeout });
4360
- this.fastApply = new FastApplyClient(this);
4361
- this.warpGrep = new WarpGrepClient(this);
4362
- this.routers = {
4363
- openai: new OpenAIRouter(this),
4364
- anthropic: new AnthropicRouter(this),
4365
- gemini: new GeminiRouter(this),
4366
- raw: new RawRouter(this),
4367
- classify: new RouterClassifier(this)
4368
- };
4369
- const compactClient = new CompactClient(this);
4370
- this.compact = compactClient.compact.bind(compactClient);
4371
- this.openai = new OpenAIToolFactory(config);
4372
- this.anthropic = new AnthropicToolFactory(config);
4373
- this.vercel = new VercelToolFactory(config);
4374
- }
4375
- };
4376
-
4377
- // tools/warp_grep/index.ts
4378
- var import_zod4 = require("zod");
4379
-
4380
- // tools/warp_grep/providers/index.ts
4381
- init_local();
4382
-
4383
- // tools/warp_grep/index.ts
4384
- init_paths();
4385
-
4386
- // tools/warp_grep/agent/index.ts
4387
- init_config();
4388
-
4389
- // tools/warp_grep/agent/formatter.ts
4390
- var ToolOutputFormatter = class {
4391
- format(toolName, _args, output, options = {}) {
4392
- const name = (toolName ?? "").trim();
4393
- if (!name) {
4394
- return "";
4395
- }
4396
- const payload = output?.toString?.()?.trim?.() ?? "";
4397
- const isError = Boolean(options.isError);
4398
- if (!payload && !isError) {
4399
- return "";
4400
- }
4401
- return `<tool_response>
4402
- ${payload}
4403
- </tool_response>`;
4404
- }
4405
- };
4406
- var sharedFormatter = new ToolOutputFormatter();
4407
-
4408
- // tools/warp_grep/index.ts
4409
- var warpGrepInputSchema = import_zod4.z.object({
4410
- search_term: import_zod4.z.string().describe("Search problem statement that this subagent is supposed to research for")
4411
- });
4412
- // Annotate the CommonJS export names for ESM import in node:
4413
- 0 && (module.exports = {
4414
- APIResource,
4415
- AnthropicRouter,
4416
- AnthropicToolFactory,
4417
- CompactClient,
4418
- FastApplyAnchorIntegrityError,
4419
- FastApplyClient,
4420
- FastApplyContextLengthError,
4421
- GeminiRouter,
4422
- LocalRipgrepProvider,
4423
- MorphAPIClient,
4424
- MorphClient,
4425
- OpenAIRouter,
4426
- OpenAIToolFactory,
4427
- RawRouter,
4428
- SDK_VERSION,
4429
- VercelToolFactory,
4430
- WarpGrepClient,
4431
- applyEdit
1
+ 'use strict';
2
+
3
+ require('./chunk-IPJA3ZS6.cjs');
4
+ require('./chunk-UF5IKELS.cjs');
5
+ var chunkE6V75LI6_cjs = require('./chunk-E6V75LI6.cjs');
6
+ require('./chunk-NNKBKENK.cjs');
7
+ require('./chunk-QEEAIXL5.cjs');
8
+ require('./chunk-XE6D4J63.cjs');
9
+ require('./chunk-OKLAYEBC.cjs');
10
+ var chunkMMX5PUGC_cjs = require('./chunk-MMX5PUGC.cjs');
11
+ require('./chunk-UZMMJ47A.cjs');
12
+ require('./chunk-5H3FKFOI.cjs');
13
+ require('./chunk-ST2OXLT5.cjs');
14
+ require('./chunk-EJTL2BOZ.cjs');
15
+ require('./chunk-GUNGJC6X.cjs');
16
+ require('./chunk-HNMEBYIS.cjs');
17
+ require('./chunk-HP3PCOTW.cjs');
18
+ require('./chunk-3HAHJYZQ.cjs');
19
+ require('./chunk-74A4HLIO.cjs');
20
+ var chunkNJWOWXUR_cjs = require('./chunk-NJWOWXUR.cjs');
21
+ require('./chunk-UKBSXYKE.cjs');
22
+ var chunkJHC2R3HU_cjs = require('./chunk-JHC2R3HU.cjs');
23
+ require('./chunk-WR7LSUIR.cjs');
24
+ require('./chunk-MWXJ6DZ2.cjs');
25
+ require('./chunk-OCKEEEYE.cjs');
26
+ require('./chunk-VHD7CW5O.cjs');
27
+ require('./chunk-KVGZ2TSG.cjs');
28
+ require('./chunk-UNX7V6P6.cjs');
29
+ require('./chunk-4EQQGUZ7.cjs');
30
+ require('./chunk-VYE7O4FM.cjs');
31
+ require('./chunk-TPZHMD7J.cjs');
32
+ var chunkWIYVT4UO_cjs = require('./chunk-WIYVT4UO.cjs');
33
+ var chunkUHFVWYSP_cjs = require('./chunk-UHFVWYSP.cjs');
34
+ var chunkF633IVQA_cjs = require('./chunk-F633IVQA.cjs');
35
+ require('./chunk-7PJYY46L.cjs');
36
+ var chunk5TTZQF4X_cjs = require('./chunk-5TTZQF4X.cjs');
37
+ require('./chunk-VL4QNALG.cjs');
38
+ var chunkKF6S3EPJ_cjs = require('./chunk-KF6S3EPJ.cjs');
39
+ var chunk6HAYJA6M_cjs = require('./chunk-6HAYJA6M.cjs');
40
+ var chunkR3TUE7O2_cjs = require('./chunk-R3TUE7O2.cjs');
41
+ require('./chunk-DLYDIYDK.cjs');
42
+ require('./chunk-YAUXTFIN.cjs');
43
+ require('./chunk-WJHHO24M.cjs');
44
+ var chunkQT5LGZG3_cjs = require('./chunk-QT5LGZG3.cjs');
45
+ var chunkAWFZKS27_cjs = require('./chunk-AWFZKS27.cjs');
46
+ require('./chunk-75ZPJI57.cjs');
47
+
48
+
49
+
50
+ Object.defineProperty(exports, "LocalRipgrepProvider", {
51
+ enumerable: true,
52
+ get: function () { return chunkE6V75LI6_cjs.LocalRipgrepProvider; }
53
+ });
54
+ Object.defineProperty(exports, "AnthropicToolFactory", {
55
+ enumerable: true,
56
+ get: function () { return chunkMMX5PUGC_cjs.AnthropicToolFactory; }
57
+ });
58
+ Object.defineProperty(exports, "MorphClient", {
59
+ enumerable: true,
60
+ get: function () { return chunkMMX5PUGC_cjs.MorphClient; }
61
+ });
62
+ Object.defineProperty(exports, "OpenAIToolFactory", {
63
+ enumerable: true,
64
+ get: function () { return chunkMMX5PUGC_cjs.OpenAIToolFactory; }
65
+ });
66
+ Object.defineProperty(exports, "VercelToolFactory", {
67
+ enumerable: true,
68
+ get: function () { return chunkMMX5PUGC_cjs.VercelToolFactory; }
69
+ });
70
+ Object.defineProperty(exports, "FastApplyClient", {
71
+ enumerable: true,
72
+ get: function () { return chunkNJWOWXUR_cjs.FastApplyClient; }
73
+ });
74
+ Object.defineProperty(exports, "WarpGrepClient", {
75
+ enumerable: true,
76
+ get: function () { return chunkJHC2R3HU_cjs.WarpGrepClient; }
77
+ });
78
+ Object.defineProperty(exports, "AnthropicRouter", {
79
+ enumerable: true,
80
+ get: function () { return chunkWIYVT4UO_cjs.AnthropicRouter; }
81
+ });
82
+ Object.defineProperty(exports, "GeminiRouter", {
83
+ enumerable: true,
84
+ get: function () { return chunkWIYVT4UO_cjs.GeminiRouter; }
85
+ });
86
+ Object.defineProperty(exports, "OpenAIRouter", {
87
+ enumerable: true,
88
+ get: function () { return chunkWIYVT4UO_cjs.OpenAIRouter; }
89
+ });
90
+ Object.defineProperty(exports, "RawRouter", {
91
+ enumerable: true,
92
+ get: function () { return chunkWIYVT4UO_cjs.RawRouter; }
93
+ });
94
+ Object.defineProperty(exports, "FastApplyAnchorIntegrityError", {
95
+ enumerable: true,
96
+ get: function () { return chunkUHFVWYSP_cjs.FastApplyAnchorIntegrityError; }
97
+ });
98
+ Object.defineProperty(exports, "FastApplyContextLengthError", {
99
+ enumerable: true,
100
+ get: function () { return chunkUHFVWYSP_cjs.FastApplyContextLengthError; }
101
+ });
102
+ Object.defineProperty(exports, "applyEdit", {
103
+ enumerable: true,
104
+ get: function () { return chunkUHFVWYSP_cjs.applyEdit; }
105
+ });
106
+ Object.defineProperty(exports, "CompactClient", {
107
+ enumerable: true,
108
+ get: function () { return chunkF633IVQA_cjs.CompactClient; }
109
+ });
110
+ Object.defineProperty(exports, "MorphAPIClient", {
111
+ enumerable: true,
112
+ get: function () { return chunk5TTZQF4X_cjs.MorphAPIClient; }
113
+ });
114
+ Object.defineProperty(exports, "PIIRestoreError", {
115
+ enumerable: true,
116
+ get: function () { return chunkKF6S3EPJ_cjs.PIIRestoreError; }
117
+ });
118
+ Object.defineProperty(exports, "DEFAULT_PII_ALLOW", {
119
+ enumerable: true,
120
+ get: function () { return chunk6HAYJA6M_cjs.DEFAULT_PII_ALLOW; }
121
+ });
122
+ Object.defineProperty(exports, "createPIIRedactor", {
123
+ enumerable: true,
124
+ get: function () { return chunk6HAYJA6M_cjs.createPIIRedactor; }
125
+ });
126
+ Object.defineProperty(exports, "detectPII", {
127
+ enumerable: true,
128
+ get: function () { return chunkR3TUE7O2_cjs.detectPII; }
129
+ });
130
+ Object.defineProperty(exports, "redactPII", {
131
+ enumerable: true,
132
+ get: function () { return chunkR3TUE7O2_cjs.redactPII; }
133
+ });
134
+ Object.defineProperty(exports, "SDK_VERSION", {
135
+ enumerable: true,
136
+ get: function () { return chunkQT5LGZG3_cjs.SDK_VERSION; }
137
+ });
138
+ Object.defineProperty(exports, "APIResource", {
139
+ enumerable: true,
140
+ get: function () { return chunkAWFZKS27_cjs.APIResource; }
4432
141
  });