@morphllm/morphsdk 0.2.197 → 0.2.199

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 (301) hide show
  1. package/README.md +1 -147
  2. package/dist/{chunk-GE5MNVT7.js → chunk-5KQ2WRBU.js} +2 -2
  3. package/dist/{chunk-LKFZBBTD.js → chunk-5TOJD2C5.js} +1 -1
  4. package/dist/chunk-5TOJD2C5.js.map +1 -0
  5. package/dist/{chunk-PQCOBN7L.js → chunk-7UU4NF4G.js} +4 -10
  6. package/dist/chunk-7UU4NF4G.js.map +1 -0
  7. package/dist/{chunk-6YZCPCAY.js → chunk-BLCCGRKT.js} +2 -2
  8. package/dist/{chunk-2BT4UGKH.js → chunk-BTMMUG3E.js} +2 -2
  9. package/dist/{chunk-VJD6MF3M.js → chunk-CEXBKXWU.js} +4 -4
  10. package/dist/{chunk-UOS3XKJD.js → chunk-DP2PT36G.js} +2 -2
  11. package/dist/{chunk-CZ74CRGH.js → chunk-EMURAU6J.js} +4 -6
  12. package/dist/chunk-EMURAU6J.js.map +1 -0
  13. package/dist/chunk-GKRPR5PZ.js +322 -0
  14. package/dist/chunk-GKRPR5PZ.js.map +1 -0
  15. package/dist/{chunk-DNL4DMMS.js → chunk-GTV27THY.js} +2 -2
  16. package/dist/{chunk-ATAKRJQZ.js → chunk-IDMKQWQG.js} +1 -36
  17. package/dist/chunk-IDMKQWQG.js.map +1 -0
  18. package/dist/{chunk-EGI642TV.js → chunk-JOC3ZI56.js} +3 -39
  19. package/dist/chunk-JOC3ZI56.js.map +1 -0
  20. package/dist/{chunk-VGCPVDFP.js → chunk-K2JR2NFQ.js} +4 -4
  21. package/dist/{chunk-DHGXGVHC.js → chunk-KXEPBLVD.js} +8 -8
  22. package/dist/{chunk-SVD3YRWM.js → chunk-MEZTHMB2.js} +4 -4
  23. package/dist/{chunk-BECYWCEZ.js → chunk-O7LJEVZO.js} +2 -2
  24. package/dist/{chunk-7QOGUY4A.js → chunk-PKJ7ODTG.js} +4 -4
  25. package/dist/{chunk-2HXELZI5.js → chunk-PW6K6OJL.js} +2 -2
  26. package/dist/chunk-PW6K6OJL.js.map +1 -0
  27. package/dist/{chunk-YVKRPVOM.js → chunk-Q3NH3NPD.js} +2 -2
  28. package/dist/{chunk-ZA3UJRSE.js → chunk-RL3ZTXT3.js} +4 -4
  29. package/dist/{chunk-WN6YLBEH.js → chunk-ULHHMZRL.js} +4 -4
  30. package/dist/{chunk-TJUZAO7T.js → chunk-UT3NQLCF.js} +2 -2
  31. package/dist/{chunk-DW6ZIVCM.js → chunk-VS5F2ORN.js} +4 -4
  32. package/dist/{chunk-UZA2ODNU.js → chunk-W37OFBSG.js} +2 -2
  33. package/dist/{chunk-JU6TCHVI.js → chunk-WDBYAXZ5.js} +2 -2
  34. package/dist/{chunk-2XDSHAB5.js → chunk-YSFEKIYQ.js} +2 -2
  35. package/dist/{chunk-WDLDKJHT.js → chunk-ZHB57ORD.js} +6 -6
  36. package/dist/client-CGW0Cevz.d.ts +402 -0
  37. package/dist/client.cjs +195 -2068
  38. package/dist/client.cjs.map +1 -1
  39. package/dist/client.d.ts +3 -11
  40. package/dist/client.js +28 -35
  41. package/dist/core/client.cjs +2 -44
  42. package/dist/core/client.cjs.map +1 -1
  43. package/dist/core/client.d.ts +2 -10
  44. package/dist/core/client.js +4 -4
  45. package/dist/core/error.cjs +2 -38
  46. package/dist/core/error.cjs.map +1 -1
  47. package/dist/core/error.d.ts +1 -1
  48. package/dist/core/error.js +3 -3
  49. package/dist/core/index.cjs +2 -44
  50. package/dist/core/index.cjs.map +1 -1
  51. package/dist/core/index.js +5 -5
  52. package/dist/core/resource.cjs.map +1 -1
  53. package/dist/core/resource.d.ts +1 -1
  54. package/dist/core/resource.js +1 -1
  55. package/dist/edge.cjs +2 -44
  56. package/dist/edge.cjs.map +1 -1
  57. package/dist/edge.js +8 -8
  58. package/dist/index.cjs +195 -2086
  59. package/dist/index.cjs.map +1 -1
  60. package/dist/index.d.ts +1 -9
  61. package/dist/index.js +30 -58
  62. package/dist/modelrouter/core.cjs +2 -44
  63. package/dist/modelrouter/core.cjs.map +1 -1
  64. package/dist/modelrouter/core.js +6 -6
  65. package/dist/modelrouter/index.cjs +2 -44
  66. package/dist/modelrouter/index.cjs.map +1 -1
  67. package/dist/modelrouter/index.js +6 -6
  68. package/dist/subagents/anthropic.cjs +2 -44
  69. package/dist/subagents/anthropic.cjs.map +1 -1
  70. package/dist/subagents/anthropic.js +12 -12
  71. package/dist/subagents/vercel.cjs +2 -44
  72. package/dist/subagents/vercel.cjs.map +1 -1
  73. package/dist/subagents/vercel.js +12 -12
  74. package/dist/tools/codebase_search/anthropic.cjs +2 -44
  75. package/dist/tools/codebase_search/anthropic.cjs.map +1 -1
  76. package/dist/tools/codebase_search/anthropic.js +7 -7
  77. package/dist/tools/codebase_search/core.cjs +2 -44
  78. package/dist/tools/codebase_search/core.cjs.map +1 -1
  79. package/dist/tools/codebase_search/core.js +6 -6
  80. package/dist/tools/codebase_search/index.cjs +2 -44
  81. package/dist/tools/codebase_search/index.cjs.map +1 -1
  82. package/dist/tools/codebase_search/index.js +11 -11
  83. package/dist/tools/codebase_search/openai.cjs +2 -44
  84. package/dist/tools/codebase_search/openai.cjs.map +1 -1
  85. package/dist/tools/codebase_search/openai.js +7 -7
  86. package/dist/tools/codebase_search/vercel.cjs +2 -44
  87. package/dist/tools/codebase_search/vercel.cjs.map +1 -1
  88. package/dist/tools/codebase_search/vercel.js +7 -7
  89. package/dist/tools/compact/core.cjs +2 -44
  90. package/dist/tools/compact/core.cjs.map +1 -1
  91. package/dist/tools/compact/core.js +6 -6
  92. package/dist/tools/compact/index.cjs +2 -44
  93. package/dist/tools/compact/index.cjs.map +1 -1
  94. package/dist/tools/compact/index.js +7 -7
  95. package/dist/tools/fastapply/anthropic.cjs +2 -38
  96. package/dist/tools/fastapply/anthropic.cjs.map +1 -1
  97. package/dist/tools/fastapply/anthropic.js +8 -8
  98. package/dist/tools/fastapply/apply.cjs +2 -38
  99. package/dist/tools/fastapply/apply.cjs.map +1 -1
  100. package/dist/tools/fastapply/apply.js +2 -2
  101. package/dist/tools/fastapply/core.cjs +2 -44
  102. package/dist/tools/fastapply/core.cjs.map +1 -1
  103. package/dist/tools/fastapply/core.js +7 -7
  104. package/dist/tools/fastapply/index.cjs +2 -38
  105. package/dist/tools/fastapply/index.cjs.map +1 -1
  106. package/dist/tools/fastapply/index.js +12 -12
  107. package/dist/tools/fastapply/openai.cjs +2 -38
  108. package/dist/tools/fastapply/openai.cjs.map +1 -1
  109. package/dist/tools/fastapply/openai.js +8 -8
  110. package/dist/tools/fastapply/vercel.cjs +2 -38
  111. package/dist/tools/fastapply/vercel.cjs.map +1 -1
  112. package/dist/tools/fastapply/vercel.js +8 -8
  113. package/dist/tools/index.cjs +2 -38
  114. package/dist/tools/index.cjs.map +1 -1
  115. package/dist/tools/index.js +12 -12
  116. package/dist/tools/utils/resilience.cjs +2 -38
  117. package/dist/tools/utils/resilience.cjs.map +1 -1
  118. package/dist/tools/utils/resilience.js +2 -2
  119. package/dist/tools/warp_grep/agent/runner.cjs +2 -38
  120. package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
  121. package/dist/tools/warp_grep/agent/runner.js +3 -3
  122. package/dist/tools/warp_grep/anthropic.cjs +2 -44
  123. package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
  124. package/dist/tools/warp_grep/anthropic.js +12 -12
  125. package/dist/tools/warp_grep/client.cjs +2 -44
  126. package/dist/tools/warp_grep/client.cjs.map +1 -1
  127. package/dist/tools/warp_grep/client.js +11 -11
  128. package/dist/tools/warp_grep/gemini.cjs +2 -44
  129. package/dist/tools/warp_grep/gemini.cjs.map +1 -1
  130. package/dist/tools/warp_grep/gemini.js +11 -11
  131. package/dist/tools/warp_grep/harness.js +7 -7
  132. package/dist/tools/warp_grep/index.cjs +2 -44
  133. package/dist/tools/warp_grep/index.cjs.map +1 -1
  134. package/dist/tools/warp_grep/index.js +14 -14
  135. package/dist/tools/warp_grep/openai.cjs +2 -44
  136. package/dist/tools/warp_grep/openai.cjs.map +1 -1
  137. package/dist/tools/warp_grep/openai.js +12 -12
  138. package/dist/tools/warp_grep/vercel.cjs +2 -44
  139. package/dist/tools/warp_grep/vercel.cjs.map +1 -1
  140. package/dist/tools/warp_grep/vercel.js +12 -12
  141. package/dist/tracing/core.cjs +2 -34
  142. package/dist/tracing/core.cjs.map +1 -1
  143. package/dist/tracing/core.d.ts +1 -2
  144. package/dist/tracing/core.js +2 -2
  145. package/dist/tracing/index.cjs +4 -42
  146. package/dist/tracing/index.cjs.map +1 -1
  147. package/dist/tracing/index.d.ts +0 -34
  148. package/dist/tracing/index.js +3 -10
  149. package/dist/tracing/interaction.cjs +0 -30
  150. package/dist/tracing/interaction.cjs.map +1 -1
  151. package/dist/tracing/interaction.js +1 -1
  152. package/dist/tracing/types.cjs.map +1 -1
  153. package/dist/tracing/types.d.ts +1 -27
  154. package/dist/version.cjs +2 -38
  155. package/dist/version.cjs.map +1 -1
  156. package/dist/version.js +1 -1
  157. package/package.json +2 -38
  158. package/dist/anthropic-B6my2oBx.d.ts +0 -56
  159. package/dist/chunk-2AMEQAO2.js +0 -46
  160. package/dist/chunk-2AMEQAO2.js.map +0 -1
  161. package/dist/chunk-2HMEZZKK.js +0 -44
  162. package/dist/chunk-2HMEZZKK.js.map +0 -1
  163. package/dist/chunk-2HXELZI5.js.map +0 -1
  164. package/dist/chunk-2VERUKO2.js +0 -177
  165. package/dist/chunk-2VERUKO2.js.map +0 -1
  166. package/dist/chunk-4FWK3CEH.js +0 -692
  167. package/dist/chunk-4FWK3CEH.js.map +0 -1
  168. package/dist/chunk-ATAKRJQZ.js.map +0 -1
  169. package/dist/chunk-CZ74CRGH.js.map +0 -1
  170. package/dist/chunk-EGI642TV.js.map +0 -1
  171. package/dist/chunk-FLWBVHDC.js +0 -622
  172. package/dist/chunk-FLWBVHDC.js.map +0 -1
  173. package/dist/chunk-JZJY2XFQ.js +0 -96
  174. package/dist/chunk-JZJY2XFQ.js.map +0 -1
  175. package/dist/chunk-LKFZBBTD.js.map +0 -1
  176. package/dist/chunk-LRHJVSSD.js +0 -57
  177. package/dist/chunk-LRHJVSSD.js.map +0 -1
  178. package/dist/chunk-NKFAMQF2.js +0 -202
  179. package/dist/chunk-NKFAMQF2.js.map +0 -1
  180. package/dist/chunk-PQCOBN7L.js.map +0 -1
  181. package/dist/chunk-TCCZBGG5.js +0 -46
  182. package/dist/chunk-TCCZBGG5.js.map +0 -1
  183. package/dist/chunk-W34BUTVR.js +0 -389
  184. package/dist/chunk-W34BUTVR.js.map +0 -1
  185. package/dist/chunk-WFOGTZF6.js +0 -80
  186. package/dist/chunk-WFOGTZF6.js.map +0 -1
  187. package/dist/chunk-YTYCHRQ2.js +0 -106
  188. package/dist/chunk-YTYCHRQ2.js.map +0 -1
  189. package/dist/client-B3fWTCcL.d.ts +0 -1021
  190. package/dist/openai-BQMeDFef.d.ts +0 -81
  191. package/dist/tools/browser/anthropic.cjs +0 -655
  192. package/dist/tools/browser/anthropic.cjs.map +0 -1
  193. package/dist/tools/browser/anthropic.d.ts +0 -4
  194. package/dist/tools/browser/anthropic.js +0 -22
  195. package/dist/tools/browser/anthropic.js.map +0 -1
  196. package/dist/tools/browser/core.cjs +0 -1831
  197. package/dist/tools/browser/core.cjs.map +0 -1
  198. package/dist/tools/browser/core.d.ts +0 -245
  199. package/dist/tools/browser/core.js +0 -32
  200. package/dist/tools/browser/core.js.map +0 -1
  201. package/dist/tools/browser/errors.cjs +0 -208
  202. package/dist/tools/browser/errors.cjs.map +0 -1
  203. package/dist/tools/browser/errors.d.ts +0 -158
  204. package/dist/tools/browser/errors.js +0 -22
  205. package/dist/tools/browser/errors.js.map +0 -1
  206. package/dist/tools/browser/index.cjs +0 -2169
  207. package/dist/tools/browser/index.cjs.map +0 -1
  208. package/dist/tools/browser/index.d.ts +0 -134
  209. package/dist/tools/browser/index.js +0 -163
  210. package/dist/tools/browser/index.js.map +0 -1
  211. package/dist/tools/browser/live.cjs +0 -134
  212. package/dist/tools/browser/live.cjs.map +0 -1
  213. package/dist/tools/browser/live.d.ts +0 -75
  214. package/dist/tools/browser/live.js +0 -16
  215. package/dist/tools/browser/live.js.map +0 -1
  216. package/dist/tools/browser/openai.cjs +0 -671
  217. package/dist/tools/browser/openai.cjs.map +0 -1
  218. package/dist/tools/browser/openai.d.ts +0 -4
  219. package/dist/tools/browser/openai.js +0 -28
  220. package/dist/tools/browser/openai.js.map +0 -1
  221. package/dist/tools/browser/profiles/core.cjs +0 -942
  222. package/dist/tools/browser/profiles/core.cjs.map +0 -1
  223. package/dist/tools/browser/profiles/core.d.ts +0 -187
  224. package/dist/tools/browser/profiles/core.js +0 -30
  225. package/dist/tools/browser/profiles/core.js.map +0 -1
  226. package/dist/tools/browser/profiles/index.cjs +0 -942
  227. package/dist/tools/browser/profiles/index.cjs.map +0 -1
  228. package/dist/tools/browser/profiles/index.d.ts +0 -4
  229. package/dist/tools/browser/profiles/index.js +0 -30
  230. package/dist/tools/browser/profiles/index.js.map +0 -1
  231. package/dist/tools/browser/profiles/types.cjs +0 -74
  232. package/dist/tools/browser/profiles/types.cjs.map +0 -1
  233. package/dist/tools/browser/profiles/types.d.ts +0 -195
  234. package/dist/tools/browser/profiles/types.js +0 -16
  235. package/dist/tools/browser/profiles/types.js.map +0 -1
  236. package/dist/tools/browser/prompts.cjs +0 -69
  237. package/dist/tools/browser/prompts.cjs.map +0 -1
  238. package/dist/tools/browser/prompts.d.ts +0 -7
  239. package/dist/tools/browser/prompts.js +0 -10
  240. package/dist/tools/browser/prompts.js.map +0 -1
  241. package/dist/tools/browser/types.cjs +0 -19
  242. package/dist/tools/browser/types.cjs.map +0 -1
  243. package/dist/tools/browser/types.d.ts +0 -338
  244. package/dist/tools/browser/types.js +0 -1
  245. package/dist/tools/browser/types.js.map +0 -1
  246. package/dist/tools/browser/vercel.cjs +0 -632
  247. package/dist/tools/browser/vercel.cjs.map +0 -1
  248. package/dist/tools/browser/vercel.d.ts +0 -4
  249. package/dist/tools/browser/vercel.js +0 -22
  250. package/dist/tools/browser/vercel.js.map +0 -1
  251. package/dist/tools/reflex/core.cjs +0 -756
  252. package/dist/tools/reflex/core.cjs.map +0 -1
  253. package/dist/tools/reflex/core.d.ts +0 -59
  254. package/dist/tools/reflex/core.js +0 -16
  255. package/dist/tools/reflex/core.js.map +0 -1
  256. package/dist/tools/reflex/index.cjs +0 -756
  257. package/dist/tools/reflex/index.cjs.map +0 -1
  258. package/dist/tools/reflex/index.d.ts +0 -5
  259. package/dist/tools/reflex/index.js +0 -16
  260. package/dist/tools/reflex/index.js.map +0 -1
  261. package/dist/tools/reflex/types.cjs +0 -19
  262. package/dist/tools/reflex/types.cjs.map +0 -1
  263. package/dist/tools/reflex/types.d.ts +0 -171
  264. package/dist/tools/reflex/types.js +0 -1
  265. package/dist/tools/reflex/types.js.map +0 -1
  266. package/dist/tools/traces/core.cjs +0 -76
  267. package/dist/tools/traces/core.cjs.map +0 -1
  268. package/dist/tools/traces/core.d.ts +0 -24
  269. package/dist/tools/traces/core.js +0 -9
  270. package/dist/tools/traces/core.js.map +0 -1
  271. package/dist/tools/traces/index.cjs +0 -76
  272. package/dist/tools/traces/index.cjs.map +0 -1
  273. package/dist/tools/traces/index.d.ts +0 -5
  274. package/dist/tools/traces/index.js +0 -9
  275. package/dist/tools/traces/index.js.map +0 -1
  276. package/dist/tools/traces/types.cjs +0 -19
  277. package/dist/tools/traces/types.cjs.map +0 -1
  278. package/dist/tools/traces/types.d.ts +0 -56
  279. package/dist/tools/traces/types.js +0 -1
  280. package/dist/tools/traces/types.js.map +0 -1
  281. package/dist/vercel-CVF27qFK.d.ts +0 -74
  282. /package/dist/{chunk-GE5MNVT7.js.map → chunk-5KQ2WRBU.js.map} +0 -0
  283. /package/dist/{chunk-6YZCPCAY.js.map → chunk-BLCCGRKT.js.map} +0 -0
  284. /package/dist/{chunk-2BT4UGKH.js.map → chunk-BTMMUG3E.js.map} +0 -0
  285. /package/dist/{chunk-VJD6MF3M.js.map → chunk-CEXBKXWU.js.map} +0 -0
  286. /package/dist/{chunk-UOS3XKJD.js.map → chunk-DP2PT36G.js.map} +0 -0
  287. /package/dist/{chunk-DNL4DMMS.js.map → chunk-GTV27THY.js.map} +0 -0
  288. /package/dist/{chunk-VGCPVDFP.js.map → chunk-K2JR2NFQ.js.map} +0 -0
  289. /package/dist/{chunk-DHGXGVHC.js.map → chunk-KXEPBLVD.js.map} +0 -0
  290. /package/dist/{chunk-SVD3YRWM.js.map → chunk-MEZTHMB2.js.map} +0 -0
  291. /package/dist/{chunk-BECYWCEZ.js.map → chunk-O7LJEVZO.js.map} +0 -0
  292. /package/dist/{chunk-7QOGUY4A.js.map → chunk-PKJ7ODTG.js.map} +0 -0
  293. /package/dist/{chunk-YVKRPVOM.js.map → chunk-Q3NH3NPD.js.map} +0 -0
  294. /package/dist/{chunk-ZA3UJRSE.js.map → chunk-RL3ZTXT3.js.map} +0 -0
  295. /package/dist/{chunk-WN6YLBEH.js.map → chunk-ULHHMZRL.js.map} +0 -0
  296. /package/dist/{chunk-TJUZAO7T.js.map → chunk-UT3NQLCF.js.map} +0 -0
  297. /package/dist/{chunk-DW6ZIVCM.js.map → chunk-VS5F2ORN.js.map} +0 -0
  298. /package/dist/{chunk-UZA2ODNU.js.map → chunk-W37OFBSG.js.map} +0 -0
  299. /package/dist/{chunk-JU6TCHVI.js.map → chunk-WDBYAXZ5.js.map} +0 -0
  300. /package/dist/{chunk-2XDSHAB5.js.map → chunk-YSFEKIYQ.js.map} +0 -0
  301. /package/dist/{chunk-WDLDKJHT.js.map → chunk-ZHB57ORD.js.map} +0 -0
package/dist/index.cjs CHANGED
@@ -36,7 +36,7 @@ var init_package = __esm({
36
36
  "package.json"() {
37
37
  package_default = {
38
38
  name: "@morphllm/morphsdk",
39
- version: "0.2.197",
39
+ version: "0.2.199",
40
40
  description: "TypeScript SDK and CLI for Morph Fast Apply integration",
41
41
  type: "module",
42
42
  main: "./dist/index.cjs",
@@ -143,31 +143,6 @@ var init_package = __esm({
143
143
  import: "./dist/tools/codebase_search/vercel.js",
144
144
  require: "./dist/tools/codebase_search/vercel.cjs"
145
145
  },
146
- "./tools/browser": {
147
- types: "./dist/tools/browser/index.d.ts",
148
- import: "./dist/tools/browser/index.js",
149
- require: "./dist/tools/browser/index.cjs"
150
- },
151
- "./tools/browser/anthropic": {
152
- types: "./dist/tools/browser/anthropic.d.ts",
153
- import: "./dist/tools/browser/anthropic.js",
154
- require: "./dist/tools/browser/anthropic.cjs"
155
- },
156
- "./tools/browser/openai": {
157
- types: "./dist/tools/browser/openai.d.ts",
158
- import: "./dist/tools/browser/openai.js",
159
- require: "./dist/tools/browser/openai.cjs"
160
- },
161
- "./tools/browser/vercel": {
162
- types: "./dist/tools/browser/vercel.d.ts",
163
- import: "./dist/tools/browser/vercel.js",
164
- require: "./dist/tools/browser/vercel.cjs"
165
- },
166
- "./tools/browser/profiles": {
167
- types: "./dist/tools/browser/profiles/index.d.ts",
168
- import: "./dist/tools/browser/profiles/index.js",
169
- require: "./dist/tools/browser/profiles/index.cjs"
170
- },
171
146
  "./modelrouter": {
172
147
  types: "./dist/modelrouter/index.d.ts",
173
148
  import: "./dist/modelrouter/index.js",
@@ -178,16 +153,6 @@ var init_package = __esm({
178
153
  import: "./dist/tools/compact/index.js",
179
154
  require: "./dist/tools/compact/index.cjs"
180
155
  },
181
- "./tools/reflex": {
182
- types: "./dist/tools/reflex/index.d.ts",
183
- import: "./dist/tools/reflex/index.js",
184
- require: "./dist/tools/reflex/index.cjs"
185
- },
186
- "./tools/traces": {
187
- types: "./dist/tools/traces/index.d.ts",
188
- import: "./dist/tools/traces/index.js",
189
- require: "./dist/tools/traces/index.cjs"
190
- },
191
156
  "./subagents": {
192
157
  types: "./dist/subagents/index.d.ts",
193
158
  import: "./dist/subagents/index.js",
@@ -218,7 +183,7 @@ var init_package = __esm({
218
183
  "!dist/**/*.test.*"
219
184
  ],
220
185
  scripts: {
221
- 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/codebase_search/index.ts tools/codebase_search/core.ts tools/codebase_search/types.ts tools/codebase_search/prompts.ts tools/codebase_search/anthropic.ts tools/codebase_search/openai.ts tools/codebase_search/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 tools/browser/index.ts tools/browser/core.ts tools/browser/types.ts tools/browser/prompts.ts tools/browser/anthropic.ts tools/browser/openai.ts tools/browser/vercel.ts tools/browser/live.ts tools/browser/errors.ts tools/browser/profiles/index.ts tools/browser/profiles/core.ts tools/browser/profiles/types.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/reflex/index.ts tools/reflex/core.ts tools/reflex/types.ts tools/traces/index.ts tools/traces/core.ts tools/traces/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts tracing/index.ts tracing/core.ts tracing/interaction.ts tracing/otel.ts tracing/types.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve && tsup ai-sdk/index.ts --format esm,cjs --sourcemap --dts --no-clean --out-dir dist/ai-sdk",
186
+ 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/codebase_search/index.ts tools/codebase_search/core.ts tools/codebase_search/types.ts tools/codebase_search/prompts.ts tools/codebase_search/anthropic.ts tools/codebase_search/openai.ts tools/codebase_search/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 tracing/index.ts tracing/core.ts tracing/interaction.ts tracing/otel.ts tracing/types.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve && tsup ai-sdk/index.ts --format esm,cjs --sourcemap --dts --no-clean --out-dir dist/ai-sdk",
222
187
  prepare: "npm run build",
223
188
  typecheck: "tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json",
224
189
  lint: "eslint .",
@@ -228,7 +193,6 @@ var init_package = __esm({
228
193
  "test:openai": "vitest run openai",
229
194
  "test:vercel": "vitest run vercel",
230
195
  "test:git": "vitest run git",
231
- "test:browser": "vitest run browser",
232
196
  "test:agent": "npx tsx tests/fullAgentTest.ts",
233
197
  "test:integration": "npx tsx tests/fullIntegrationTest.ts",
234
198
  "test:e2e": "vitest run --config vitest.e2e.config.ts",
@@ -1365,28 +1329,19 @@ __export(index_exports, {
1365
1329
  APIResource: () => APIResource,
1366
1330
  AnthropicRouter: () => AnthropicRouter,
1367
1331
  AnthropicToolFactory: () => AnthropicToolFactory,
1368
- BrowserClient: () => BrowserClient,
1369
1332
  CodebaseSearchClient: () => CodebaseSearchClient,
1370
1333
  CompactClient: () => CompactClient,
1371
1334
  FastApplyAnchorIntegrityError: () => FastApplyAnchorIntegrityError,
1372
1335
  FastApplyClient: () => FastApplyClient,
1373
1336
  FastApplyContextLengthError: () => FastApplyContextLengthError,
1374
1337
  GeminiRouter: () => GeminiRouter,
1375
- GitHubClient: () => GitHubClient,
1376
- GitHubError: () => GitHubError,
1377
1338
  LocalRipgrepProvider: () => LocalRipgrepProvider,
1378
1339
  MorphAPIClient: () => MorphAPIClient,
1379
1340
  MorphClient: () => MorphClient,
1380
- NoInstallationError: () => NoInstallationError,
1381
- NotFoundError: () => NotFoundError,
1382
1341
  OpenAIRouter: () => OpenAIRouter,
1383
1342
  OpenAIToolFactory: () => OpenAIToolFactory,
1384
- PermissionError: () => PermissionError,
1385
1343
  RawRouter: () => RawRouter,
1386
- ReflexClient: () => ReflexClient,
1387
- ReflexJobsResource: () => ReflexJobsResource,
1388
1344
  SDK_VERSION: () => SDK_VERSION,
1389
- TracesClient: () => TracesClient,
1390
1345
  VercelToolFactory: () => VercelToolFactory,
1391
1346
  WarpGrepClient: () => WarpGrepClient,
1392
1347
  applyEdit: () => applyEdit
@@ -1502,7 +1457,6 @@ async function toMorphError(response) {
1502
1457
  // core/client.ts
1503
1458
  var DEFAULT_BASE_URL = "https://api.morphllm.com";
1504
1459
  var DEFAULT_REPOS_URL = "https://repos.morphllm.com";
1505
- var DEFAULT_BROWSER_URL = "https://browser.morphllm.com";
1506
1460
  var DEFAULT_TIMEOUT = 6e4;
1507
1461
  var env = (name) => typeof process !== "undefined" ? process.env?.[name] : void 0;
1508
1462
  var stripTrailingSlash = (url) => url.replace(/\/+$/, "");
@@ -1511,7 +1465,6 @@ var MorphAPIClient = class {
1511
1465
  apiKey;
1512
1466
  baseURL;
1513
1467
  reposURL;
1514
- browserURL;
1515
1468
  /** Explicit default timeout (ms), if set. The request default is applied lazily so
1516
1469
  * resources can read an undefined value and supply their own fallback. */
1517
1470
  timeout;
@@ -1521,9 +1474,6 @@ var MorphAPIClient = class {
1521
1474
  this.apiKey = options.apiKey;
1522
1475
  this.baseURL = stripTrailingSlash(options.baseURL ?? DEFAULT_BASE_URL);
1523
1476
  this.reposURL = stripTrailingSlash(options.reposURL ?? env("MORPH_SEARCH_URL") ?? DEFAULT_REPOS_URL);
1524
- this.browserURL = stripTrailingSlash(
1525
- options.browserURL ?? (env("MORPH_ENVIRONMENT") === "DEV" ? "http://localhost:8000" : DEFAULT_BROWSER_URL)
1526
- );
1527
1477
  this.timeout = options.timeout;
1528
1478
  this.retryConfig = options.retryConfig;
1529
1479
  this.debug = options.debug ?? false;
@@ -1582,7 +1532,6 @@ var MorphAPIClient = class {
1582
1532
  timeout,
1583
1533
  `Morph request to ${url} timed out after ${timeout}ms`
1584
1534
  );
1585
- if (opts.raw) return response;
1586
1535
  if (!response.ok) throw await toMorphError(response);
1587
1536
  if (opts.stream) return response;
1588
1537
  if (response.status === 204) return void 0;
@@ -1828,1460 +1777,207 @@ async function executeCodebaseSearch(input, config) {
1828
1777
  return runSearch(client, input, config.repoId, config.timeout ?? DEFAULT_TIMEOUT3, config.searchUrl);
1829
1778
  }
1830
1779
 
1831
- // tools/browser/core.ts
1832
- init_logger();
1780
+ // tools/warp_grep/agent/runner.ts
1781
+ init_config();
1833
1782
 
1834
- // tools/browser/live.ts
1835
- var LIVE_PRESETS = {
1836
- /** Read-only monitoring (no interaction) */
1837
- readonly: { interactive: false },
1838
- /** Interactive control (human-in-the-loop) */
1839
- interactive: { interactive: true },
1840
- /** Watch-only without controls */
1841
- monitoring: { interactive: false, showControls: false }
1842
- };
1843
- function buildLiveUrl(debugUrl, options = {}) {
1844
- if (!debugUrl) {
1845
- throw new Error(
1846
- "debugUrl is required. Ensure your backend returns debugUrl in the task response. Contact support@morphllm.com if you need help."
1847
- );
1848
- }
1849
- const normalized = normalizeLiveUrl(debugUrl);
1850
- const url = new URL(normalized);
1851
- if (options.interactive !== void 0) {
1852
- url.searchParams.set("interactive", String(options.interactive));
1853
- }
1854
- if (options.theme) {
1855
- url.searchParams.set("theme", options.theme);
1856
- }
1857
- if (options.showControls !== void 0) {
1858
- url.searchParams.set("showControls", String(options.showControls));
1859
- }
1860
- if (options.pageId) {
1861
- url.searchParams.set("pageId", options.pageId);
1862
- }
1863
- if (options.pageIndex) {
1864
- url.searchParams.set("pageIndex", options.pageIndex);
1783
+ // tools/warp_grep/agent/parser.ts
1784
+ function parseReadLines(linesStr) {
1785
+ const ranges = [];
1786
+ for (const rangeStr of linesStr.split(",")) {
1787
+ const trimmed = rangeStr.trim();
1788
+ if (!trimmed) continue;
1789
+ const parts = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
1790
+ if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
1791
+ ranges.push([parts[0], parts[1]]);
1792
+ } else if (Number.isFinite(parts[0])) {
1793
+ ranges.push([parts[0], parts[0]]);
1794
+ }
1865
1795
  }
1866
- return url.toString();
1867
- }
1868
- function cdpToHttps(wsUrl) {
1869
- return wsUrl.replace(/^wss:\/\//, "https://").replace(/^ws:\/\//, "http://");
1796
+ if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };
1797
+ if (ranges.length > 1) return { lines: ranges };
1798
+ return {};
1870
1799
  }
1871
- function normalizeLiveUrl(debugUrl) {
1872
- const trimmed = debugUrl.trim();
1873
- if (!trimmed) return trimmed;
1874
- if (trimmed.startsWith("wss://") || trimmed.startsWith("ws://")) {
1875
- return `https://live.browser-use.com?wss=${encodeURIComponent(cdpToHttps(trimmed))}`;
1876
- }
1877
- let url;
1878
- try {
1879
- url = new URL(trimmed);
1880
- } catch {
1881
- return trimmed;
1882
- }
1883
- const wssParam = url.searchParams.get("wss");
1884
- if (wssParam && (wssParam.startsWith("wss://") || wssParam.startsWith("ws://"))) {
1885
- url.searchParams.set("wss", cdpToHttps(wssParam));
1800
+ function parseFinishFiles(filesStr) {
1801
+ const files = [];
1802
+ for (const line of filesStr.trim().split(/\s+/)) {
1803
+ const trimmed = line.trim();
1804
+ if (!trimmed) continue;
1805
+ const searchFrom = /^[A-Za-z]:/.test(trimmed) ? 2 : 0;
1806
+ const colonIdx = trimmed.indexOf(":", searchFrom);
1807
+ if (colonIdx === -1) {
1808
+ files.push({ path: trimmed, lines: "*" });
1809
+ continue;
1810
+ }
1811
+ const filePath = trimmed.slice(0, colonIdx);
1812
+ const rangesPart = trimmed.slice(colonIdx + 1);
1813
+ if (!rangesPart.trim() || rangesPart.trim() === "*") {
1814
+ files.push({ path: filePath, lines: "*" });
1815
+ continue;
1816
+ }
1817
+ const ranges = [];
1818
+ for (const rangeStr of rangesPart.split(",")) {
1819
+ const rt = rangeStr.trim();
1820
+ if (!rt) continue;
1821
+ const parts = rt.split("-").map((v) => parseInt(v.trim(), 10));
1822
+ if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
1823
+ ranges.push([parts[0], parts[1]]);
1824
+ } else if (Number.isFinite(parts[0])) {
1825
+ ranges.push([parts[0], parts[0]]);
1826
+ }
1827
+ }
1828
+ files.push({ path: filePath, lines: ranges.length > 0 ? ranges : "*" });
1886
1829
  }
1887
- return url.toString();
1888
- }
1889
- function buildLiveIframe(debugUrl, options = {}) {
1890
- const {
1891
- width = "100%",
1892
- height = "600px",
1893
- style = "",
1894
- className = "",
1895
- ...sessionOptions
1896
- } = options;
1897
- const src = buildLiveUrl(debugUrl, sessionOptions);
1898
- const widthStr = typeof width === "number" ? `${width}px` : width;
1899
- const heightStr = typeof height === "number" ? `${height}px` : height;
1900
- const baseStyle = `width: ${widthStr}; height: ${heightStr}; border: none;`;
1901
- const fullStyle = style ? `${baseStyle} ${style}` : baseStyle;
1902
- const attributes = [
1903
- `src="${src}"`,
1904
- `style="${fullStyle}"`
1905
- ];
1906
- if (className) {
1907
- attributes.push(`class="${className}"`);
1908
- }
1909
- return `<iframe ${attributes.join(" ")}></iframe>`;
1830
+ return files;
1910
1831
  }
1911
- function buildEmbedCode(debugUrl, options = {}) {
1912
- const iframe = buildLiveIframe(debugUrl, options);
1913
- return `<!-- Embed Morph Live Session -->
1914
- ${iframe}`;
1832
+ function extractPathFromCommand(command) {
1833
+ const tokens = command.trim().split(/\s+/);
1834
+ const pathTokens = tokens.slice(1).filter((t) => !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("\\("));
1835
+ return pathTokens[0] || ".";
1915
1836
  }
1916
- function resolvePreset(optionsOrPreset) {
1917
- if (!optionsOrPreset) {
1918
- return {};
1837
+
1838
+ // tools/warp_grep/agent/tools/grep.ts
1839
+ async function toolGrep(provider, args) {
1840
+ const res = await provider.grep(args);
1841
+ if (res.error) {
1842
+ return { output: res.error };
1919
1843
  }
1920
- if (typeof optionsOrPreset === "string") {
1921
- const preset = LIVE_PRESETS[optionsOrPreset];
1922
- if (!preset) {
1923
- throw new Error(
1924
- `Unknown preset: ${optionsOrPreset}. Available presets: ${Object.keys(LIVE_PRESETS).join(", ")}`
1925
- );
1926
- }
1927
- return preset;
1844
+ if (!res.lines.length) {
1845
+ return { output: "no matches" };
1928
1846
  }
1929
- return optionsOrPreset;
1847
+ return { output: res.lines.join("\n") };
1930
1848
  }
1931
1849
 
1932
- // tools/browser/errors.ts
1933
- var MorphError2 = class extends Error {
1934
- /** Error code for programmatic handling */
1935
- code;
1936
- /** Original cause of the error, if any */
1937
- cause;
1938
- constructor(message, code, cause) {
1939
- super(message);
1940
- this.name = "MorphError";
1941
- this.code = code;
1942
- this.cause = cause;
1943
- if (Error.captureStackTrace) {
1944
- Error.captureStackTrace(this, this.constructor);
1850
+ // tools/warp_grep/agent/tools/read.ts
1851
+ function isValidRange(start, end) {
1852
+ return typeof start === "number" && typeof end === "number" && Number.isFinite(start) && Number.isFinite(end) && start > 0 && end >= start;
1853
+ }
1854
+ async function toolRead(provider, args) {
1855
+ if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {
1856
+ const validRanges = [];
1857
+ for (const range of args.lines) {
1858
+ if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {
1859
+ validRanges.push([range[0], range[1]]);
1860
+ }
1945
1861
  }
1862
+ if (validRanges.length === 0) {
1863
+ const res2 = await provider.read({ path: args.path });
1864
+ if (res2.error) return res2.error;
1865
+ if (!res2.lines.length) return "(empty file)";
1866
+ return res2.lines.join("\n");
1867
+ }
1868
+ const chunks = [];
1869
+ for (const [start, end] of validRanges) {
1870
+ const res2 = await provider.read({ path: args.path, start, end });
1871
+ if (res2.error) return res2.error;
1872
+ chunks.push(res2.lines.join("\n"));
1873
+ }
1874
+ if (chunks.every((c) => c === "")) return "(empty file)";
1875
+ return chunks.join("\n...\n");
1946
1876
  }
1947
- /**
1948
- * Returns a JSON representation of the error for logging.
1949
- */
1950
- toJSON() {
1951
- return {
1952
- name: this.name,
1953
- message: this.message,
1954
- code: this.code,
1955
- cause: this.cause?.message
1956
- };
1957
- }
1958
- };
1959
- var MorphValidationError = class extends MorphError2 {
1960
- /** The field that failed validation */
1961
- field;
1962
- constructor(message, field) {
1963
- super(message, "validation_error");
1964
- this.name = "MorphValidationError";
1965
- this.field = field;
1966
- }
1967
- toJSON() {
1968
- return {
1969
- ...super.toJSON(),
1970
- field: this.field
1971
- };
1972
- }
1973
- };
1974
- var MorphAPIError = class extends MorphError2 {
1975
- /** HTTP status code */
1976
- statusCode;
1977
- /** Request ID for debugging (if available) */
1978
- requestId;
1979
- /** Raw response body */
1980
- rawResponse;
1981
- constructor(message, code, statusCode, options) {
1982
- super(message, code, options?.cause);
1983
- this.name = "MorphAPIError";
1984
- this.statusCode = statusCode;
1985
- this.requestId = options?.requestId;
1986
- this.rawResponse = options?.rawResponse;
1987
- }
1988
- toJSON() {
1989
- return {
1990
- ...super.toJSON(),
1991
- statusCode: this.statusCode,
1992
- requestId: this.requestId
1993
- };
1994
- }
1995
- };
1996
- var MorphAuthenticationError = class extends MorphAPIError {
1997
- constructor(message = "Authentication required. Please provide a valid API key.") {
1998
- super(message, "authentication_required", 401);
1999
- this.name = "MorphAuthenticationError";
2000
- }
2001
- };
2002
- var MorphRateLimitError = class extends MorphAPIError {
2003
- /** When the rate limit resets (Unix timestamp) */
2004
- resetAt;
2005
- /** Number of seconds until reset */
2006
- retryAfter;
2007
- constructor(message = "Rate limit exceeded. Please retry later.", options) {
2008
- super(message, "rate_limit_exceeded", 429, { requestId: options?.requestId });
2009
- this.name = "MorphRateLimitError";
2010
- this.resetAt = options?.resetAt;
2011
- this.retryAfter = options?.retryAfter;
2012
- }
2013
- toJSON() {
2014
- return {
2015
- ...super.toJSON(),
2016
- resetAt: this.resetAt,
2017
- retryAfter: this.retryAfter
2018
- };
2019
- }
2020
- };
2021
- var MorphNotFoundError = class extends MorphAPIError {
2022
- /** The type of resource that was not found */
2023
- resourceType;
2024
- /** The ID of the resource that was not found */
2025
- resourceId;
2026
- constructor(resourceType, resourceId) {
2027
- const message = resourceId ? `${resourceType} '${resourceId}' not found` : `${resourceType} not found`;
2028
- super(message, "resource_not_found", 404);
2029
- this.name = "MorphNotFoundError";
2030
- this.resourceType = resourceType;
2031
- this.resourceId = resourceId;
2032
- }
2033
- toJSON() {
2034
- return {
2035
- ...super.toJSON(),
2036
- resourceType: this.resourceType,
2037
- resourceId: this.resourceId
2038
- };
1877
+ const res = await provider.read({ path: args.path, start: args.start, end: args.end });
1878
+ if (res.error) {
1879
+ return res.error;
2039
1880
  }
2040
- };
2041
- var MorphProfileLimitError = class extends MorphAPIError {
2042
- /** Current number of profiles */
2043
- currentCount;
2044
- /** Maximum allowed profiles for the plan */
2045
- maxAllowed;
2046
- constructor(message = "Profile limit exceeded for your plan.", options) {
2047
- super(message, "profile_limit_exceeded", 403, { requestId: options?.requestId });
2048
- this.name = "MorphProfileLimitError";
2049
- this.currentCount = options?.currentCount;
2050
- this.maxAllowed = options?.maxAllowed;
2051
- }
2052
- toJSON() {
2053
- return {
2054
- ...super.toJSON(),
2055
- currentCount: this.currentCount,
2056
- maxAllowed: this.maxAllowed
2057
- };
1881
+ if (!res.lines.length) return "(empty file)";
1882
+ return res.lines.join("\n");
1883
+ }
1884
+
1885
+ // tools/warp_grep/agent/tools/list_directory.ts
1886
+ init_config();
1887
+ var import_path2 = __toESM(require("path"), 1);
1888
+ async function toolListDirectory(provider, args, repoRoot) {
1889
+ const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;
1890
+ const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
1891
+ const entries = await provider.listDirectory({
1892
+ path: args.path,
1893
+ pattern: args.pattern ?? null,
1894
+ maxResults,
1895
+ maxDepth
1896
+ });
1897
+ if (!entries.length) return "empty";
1898
+ if (repoRoot) {
1899
+ const absRoot = repoRoot;
1900
+ const lines = entries.map((e) => import_path2.default.join(absRoot, e.path));
1901
+ return lines.join("\n");
2058
1902
  }
2059
- };
2060
- function parseAPIError(statusCode, responseText, requestId) {
2061
- let errorData = {};
2062
- try {
2063
- errorData = JSON.parse(responseText);
2064
- } catch {
1903
+ return entries.map((e) => e.path).join("\n");
1904
+ }
1905
+
1906
+ // tools/warp_grep/agent/tools/glob.ts
1907
+ async function toolGlob(provider, args) {
1908
+ const res = await provider.glob(args);
1909
+ if (res.error) {
1910
+ return res.error;
2065
1911
  }
2066
- const message = errorData.detail || errorData.message || responseText || "Unknown error";
2067
- const code = errorData.code;
2068
- switch (statusCode) {
2069
- case 401:
2070
- return new MorphAuthenticationError(message);
2071
- case 403:
2072
- if (code === "profile_limit_exceeded" || message.toLowerCase().includes("limit")) {
2073
- return new MorphProfileLimitError(message, { requestId });
2074
- }
2075
- return new MorphAPIError(message, "insufficient_permissions", statusCode, { requestId, rawResponse: responseText });
2076
- case 404:
2077
- if (message.toLowerCase().includes("profile")) {
2078
- return new MorphNotFoundError("Profile", void 0);
2079
- }
2080
- if (message.toLowerCase().includes("session")) {
2081
- return new MorphNotFoundError("Session", void 0);
2082
- }
2083
- return new MorphAPIError(message, "resource_not_found", statusCode, { requestId, rawResponse: responseText });
2084
- case 429:
2085
- return new MorphRateLimitError(message, { requestId });
2086
- case 422:
2087
- return new MorphAPIError(message, "validation_error", statusCode, { requestId, rawResponse: responseText });
2088
- case 500:
2089
- case 502:
2090
- case 503:
2091
- case 504:
2092
- return new MorphAPIError(message, "service_unavailable", statusCode, { requestId, rawResponse: responseText });
2093
- default:
2094
- return new MorphAPIError(message, "network_error", statusCode, { requestId, rawResponse: responseText });
1912
+ if (!res.files.length) {
1913
+ return "no matches";
2095
1914
  }
1915
+ const header = `Found ${res.totalFound} file(s) matching "${args.pattern}" within ${res.searchDir}, sorted by modification time (newest first):`;
1916
+ const body = res.files.join("\n");
1917
+ const truncated = res.totalFound > res.files.length ? `
1918
+ [${res.totalFound - res.files.length} files truncated]` : "";
1919
+ return `${header}
1920
+ ---
1921
+ ${body}
1922
+ ---${truncated}`;
2096
1923
  }
2097
1924
 
2098
- // tools/browser/profiles/types.ts
2099
- function transformProfile(api) {
2100
- return {
2101
- id: api.id,
2102
- name: api.name,
2103
- repoId: api.repo_id,
2104
- cookieDomains: api.cookie_domains,
2105
- lastUsedAt: api.last_used_at,
2106
- createdAt: api.created_at,
2107
- updatedAt: api.updated_at
2108
- };
2109
- }
2110
- function transformCreateInput(input) {
2111
- return {
2112
- name: input.name,
2113
- repo_id: input.repoId
2114
- };
1925
+ // tools/warp_grep/agent/tools/finish.ts
1926
+ function isValidRange2(range) {
1927
+ 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];
2115
1928
  }
2116
- function transformSession(api) {
2117
- return {
2118
- sessionId: api.session_id,
2119
- debugUrl: api.debug_url || ""
2120
- };
1929
+ function extractValidRanges(lines) {
1930
+ if (!Array.isArray(lines)) return null;
1931
+ const valid = [];
1932
+ for (const range of lines) {
1933
+ if (isValidRange2(range)) {
1934
+ valid.push([range[0], range[1]]);
1935
+ }
1936
+ }
1937
+ return valid.length > 0 ? valid : null;
2121
1938
  }
2122
- function transformSaveInput(input) {
2123
- return {
2124
- session_id: input.sessionId,
2125
- profile_id: input.profileId
2126
- };
1939
+ async function readFinishFiles(repoRoot, files, reader) {
1940
+ const out = [];
1941
+ for (const f of files) {
1942
+ const validRanges = f.lines === "*" ? null : extractValidRanges(f.lines);
1943
+ if (f.lines === "*" || !validRanges) {
1944
+ const lines = await reader(f.path);
1945
+ out.push({ path: f.path, ranges: "*", content: lines.join("\n") });
1946
+ } else {
1947
+ const ranges = mergeRanges(validRanges);
1948
+ const chunks = [];
1949
+ for (let i = 0; i < ranges.length; i++) {
1950
+ const [s, e] = ranges[i];
1951
+ if (i === 0 && s > 1) {
1952
+ chunks.push(`// ... existing code, block starting at line ${s} ...`);
1953
+ } else if (i > 0) {
1954
+ chunks.push(`// ... existing code, block starting at line ${s} ...`);
1955
+ }
1956
+ const lines = await reader(f.path, s, e);
1957
+ chunks.push(lines.join("\n"));
1958
+ }
1959
+ out.push({ path: f.path, ranges, content: chunks.join("\n") });
1960
+ }
1961
+ }
1962
+ return out;
2127
1963
  }
2128
- function transformStateResponse(api) {
2129
- return {
2130
- profileId: api.profile_id,
2131
- stateUrl: api.state_url,
2132
- expiresIn: api.expires_in
2133
- };
2134
- }
2135
-
2136
- // tools/browser/profiles/core.ts
2137
- var DEFAULT_API_URL2 = process.env.MORPH_ENVIRONMENT === "DEV" ? "http://localhost:8000" : "https://browser.morphllm.com";
2138
- var ProfilesClient = class {
2139
- config;
2140
- constructor(config) {
2141
- this.config = config;
2142
- }
2143
- /**
2144
- * Create a new browser profile and immediately start a live session.
2145
- *
2146
- * @param input - Profile creation parameters
2147
- * @returns Profile setup handle with live URL + save()
2148
- * @throws {MorphValidationError} If input validation fails
2149
- * @throws {MorphProfileLimitError} If profile limit is exceeded
2150
- * @throws {MorphAuthenticationError} If API key is missing or invalid
2151
- *
2152
- * @example
2153
- * ```typescript
2154
- * const setup = await morph.browser.profiles.createProfile({
2155
- * name: 'LinkedIn Production',
2156
- * repoId: 'owner/repo'
2157
- * });
2158
- * console.log(setup.session.debugUrl);
2159
- * await setup.save();
2160
- * ```
2161
- */
2162
- async createProfile(input) {
2163
- return createProfile(input, this.config);
2164
- }
2165
- /**
2166
- * List all profiles for the authenticated user.
2167
- *
2168
- * @param repoId - Optional repository ID to filter by
2169
- * @returns Array of profiles
2170
- *
2171
- * @example
2172
- * ```typescript
2173
- * // List all profiles
2174
- * const allProfiles = await morph.browser.profiles.listProfiles();
2175
- *
2176
- * // List profiles for a specific repo
2177
- * const repoProfiles = await morph.browser.profiles.listProfiles('owner/repo');
2178
- * ```
2179
- */
2180
- async listProfiles(repoId) {
2181
- return listProfiles(this.config, repoId);
2182
- }
2183
- /**
2184
- * Get a profile by ID with convenience methods.
2185
- *
2186
- * @param id - Profile ID
2187
- * @returns Profile with attached methods
2188
- * @throws {MorphNotFoundError} If profile is not found
2189
- *
2190
- * @example
2191
- * ```typescript
2192
- * const profile = await morph.browser.profiles.getProfile('profile-id');
2193
- * const state = await profile.getState();
2194
- * await profile.delete();
2195
- * ```
2196
- */
2197
- async getProfile(id) {
2198
- return getProfile(id, this.config);
2199
- }
2200
- /**
2201
- * Update a profile by opening a live session (no rename).
2202
- *
2203
- * @param id - Profile ID
2204
- * @returns Profile setup handle with live URL + save()
2205
- */
2206
- async updateProfile(id) {
2207
- return updateProfile(id, this.config);
2208
- }
2209
- /**
2210
- * Delete a profile.
2211
- *
2212
- * @param id - Profile ID
2213
- * @throws {MorphNotFoundError} If profile is not found
2214
- */
2215
- async deleteProfile(id) {
2216
- return deleteProfile(id, this.config);
2217
- }
2218
- /**
2219
- * Start a browser session for profile setup.
2220
- *
2221
- * Returns a live URL where the user can sign into accounts.
2222
- * After signing in, call `saveSession` to persist the state.
2223
- *
2224
- * @param input - Optional session parameters
2225
- * @returns Session with debug URL
2226
- *
2227
- * @example
2228
- * ```typescript
2229
- * const session = await morph.browser.profiles.startSession();
2230
- * console.log('Sign in at:', session.debugUrl);
2231
- * // Open debugUrl in browser, user signs in...
2232
- * await morph.browser.profiles.saveSession(session.sessionId, profile.id);
2233
- * ```
2234
- */
2235
- async startSession(input) {
2236
- return startProfileSession(this.config, input);
2237
- }
2238
- /**
2239
- * Save browser state from a session to a profile.
2240
- *
2241
- * Call this after the user is done signing into accounts.
2242
- * Extracts cookies, localStorage, and sessionStorage.
2243
- *
2244
- * @param sessionId - Browser session ID from startSession
2245
- * @param profileId - Profile ID to save state to
2246
- * @returns Updated profile with cookie domains
2247
- */
2248
- async saveSession(sessionId, profileId) {
2249
- return saveProfileSession({ sessionId, profileId }, this.config);
2250
- }
2251
- /**
2252
- * List available repo IDs (discovery).
2253
- *
2254
- * @returns Repo summaries with profile counts
2255
- */
2256
- async listRepos() {
2257
- return listRepos(this.config);
2258
- }
2259
- /**
2260
- * Get the presigned URL for a profile's state.
2261
- *
2262
- * Use this to download the raw state JSON for debugging
2263
- * or to restore state manually.
2264
- *
2265
- * @param profileId - Profile ID
2266
- * @returns State URL with expiry information
2267
- */
2268
- async getProfileState(profileId) {
2269
- return getProfileState(profileId, this.config);
2270
- }
2271
- };
2272
- function validateCreateInput(input) {
2273
- if (!input.name || typeof input.name !== "string") {
2274
- throw new MorphValidationError("name is required", "name");
2275
- }
2276
- const trimmedName = input.name.trim();
2277
- if (trimmedName.length === 0) {
2278
- throw new MorphValidationError("name cannot be empty", "name");
2279
- }
2280
- if (trimmedName.length > 100) {
2281
- throw new MorphValidationError("name must be 100 characters or less", "name");
2282
- }
2283
- if (!input.repoId || typeof input.repoId !== "string") {
2284
- throw new MorphValidationError("repoId is required", "repoId");
2285
- }
2286
- if (input.repoId.trim().length === 0) {
2287
- throw new MorphValidationError("repoId cannot be empty", "repoId");
2288
- }
2289
- }
2290
- function validateId(id, fieldName) {
2291
- if (!id || typeof id !== "string") {
2292
- throw new MorphValidationError(`${fieldName} is required`, fieldName);
2293
- }
2294
- if (id.trim().length === 0) {
2295
- throw new MorphValidationError(`${fieldName} cannot be empty`, fieldName);
2296
- }
2297
- }
2298
- async function createProfile(input, config = {}) {
2299
- validateCreateInput(input);
2300
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2301
- const headers = buildHeaders(config);
2302
- const response = await fetchWithRetry(
2303
- `${apiUrl}/profiles`,
2304
- {
2305
- method: "POST",
2306
- headers,
2307
- body: JSON.stringify(transformCreateInput(input))
2308
- },
2309
- config.retryConfig
2310
- );
2311
- if (!response.ok) {
2312
- const errorText = await response.text().catch(() => response.statusText);
2313
- const requestId = response.headers.get("x-request-id") || void 0;
2314
- throw parseAPIError(response.status, errorText, requestId);
2315
- }
2316
- const apiProfile = await response.json();
2317
- const profile = transformProfile(apiProfile);
2318
- const session = await startProfileSession(config, { profileId: profile.id });
2319
- return buildProfileSetup(profile, session, config);
2320
- }
2321
- async function listProfiles(config = {}, repoId) {
2322
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2323
- const headers = buildHeaders(config);
2324
- const url = repoId ? `${apiUrl}/profiles?repo_id=${encodeURIComponent(repoId)}` : `${apiUrl}/profiles`;
2325
- const response = await fetchWithRetry(
2326
- url,
2327
- { method: "GET", headers },
2328
- config.retryConfig
2329
- );
2330
- if (!response.ok) {
2331
- const errorText = await response.text().catch(() => response.statusText);
2332
- const requestId = response.headers.get("x-request-id") || void 0;
2333
- throw parseAPIError(response.status, errorText, requestId);
2334
- }
2335
- const data = await response.json();
2336
- return data.profiles.map(transformProfile);
2337
- }
2338
- async function getProfile(id, config = {}) {
2339
- validateId(id, "id");
2340
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2341
- const headers = buildHeaders(config);
2342
- const response = await fetchWithRetry(
2343
- `${apiUrl}/profiles/${encodeURIComponent(id)}`,
2344
- { method: "GET", headers },
2345
- config.retryConfig
2346
- );
2347
- if (!response.ok) {
2348
- const errorText = await response.text().catch(() => response.statusText);
2349
- const requestId = response.headers.get("x-request-id") || void 0;
2350
- throw parseAPIError(response.status, errorText, requestId);
2351
- }
2352
- const apiProfile = await response.json();
2353
- const profile = transformProfile(apiProfile);
2354
- return {
2355
- ...profile,
2356
- getState: () => getProfileState(id, config),
2357
- delete: () => deleteProfile(id, config)
2358
- };
2359
- }
2360
- async function updateProfile(id, config = {}) {
2361
- validateId(id, "id");
2362
- const profile = await fetchProfile(id, config);
2363
- const session = await startProfileSession(config, { profileId: profile.id });
2364
- return buildProfileSetup(profile, session, config);
2365
- }
2366
- async function deleteProfile(id, config = {}) {
2367
- validateId(id, "id");
2368
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2369
- const headers = buildHeaders(config);
2370
- const response = await fetchWithRetry(
2371
- `${apiUrl}/profiles/${encodeURIComponent(id)}`,
2372
- { method: "DELETE", headers },
2373
- config.retryConfig
2374
- );
2375
- if (!response.ok) {
2376
- const errorText = await response.text().catch(() => response.statusText);
2377
- const requestId = response.headers.get("x-request-id") || void 0;
2378
- throw parseAPIError(response.status, errorText, requestId);
2379
- }
2380
- }
2381
- async function startProfileSession(config = {}, input) {
2382
- if (!config.apiKey) {
2383
- throw new MorphAuthenticationError();
2384
- }
2385
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2386
- const headers = buildHeaders(config);
2387
- const body = input?.profileId ? { profile_id: input.profileId } : {};
2388
- const response = await fetchWithRetry(
2389
- `${apiUrl}/profiles/session/start`,
2390
- {
2391
- method: "POST",
2392
- headers,
2393
- body: JSON.stringify(body)
2394
- },
2395
- config.retryConfig
2396
- );
2397
- if (!response.ok) {
2398
- const errorText = await response.text().catch(() => response.statusText);
2399
- const requestId = response.headers.get("x-request-id") || void 0;
2400
- throw parseAPIError(response.status, errorText, requestId);
2401
- }
2402
- const apiSession = await response.json();
2403
- return transformSession(apiSession);
2404
- }
2405
- async function saveProfileSession(input, config = {}) {
2406
- validateId(input.sessionId, "sessionId");
2407
- validateId(input.profileId, "profileId");
2408
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2409
- const headers = buildHeaders(config);
2410
- const response = await fetchWithRetry(
2411
- `${apiUrl}/profiles/session/save`,
2412
- {
2413
- method: "POST",
2414
- headers,
2415
- body: JSON.stringify(transformSaveInput(input))
2416
- },
2417
- config.retryConfig
2418
- );
2419
- if (!response.ok) {
2420
- const errorText = await response.text().catch(() => response.statusText);
2421
- const requestId = response.headers.get("x-request-id") || void 0;
2422
- throw parseAPIError(response.status, errorText, requestId);
2423
- }
2424
- const apiProfile = await response.json();
2425
- return transformProfile(apiProfile);
2426
- }
2427
- async function listRepos(config = {}) {
2428
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2429
- const headers = buildHeaders(config);
2430
- const response = await fetchWithRetry(
2431
- `${apiUrl}/repos`,
2432
- { method: "GET", headers },
2433
- config.retryConfig
2434
- );
2435
- if (!response.ok) {
2436
- const errorText = await response.text().catch(() => response.statusText);
2437
- const requestId = response.headers.get("x-request-id") || void 0;
2438
- throw parseAPIError(response.status, errorText, requestId);
2439
- }
2440
- const data = await response.json();
2441
- const repos = Array.isArray(data?.repos) ? data.repos : [];
2442
- return repos.map((repo) => ({
2443
- repoId: repo.repo_id,
2444
- repoFullName: repo.repo_full_name,
2445
- profileCount: repo.profile_count ?? 0
2446
- }));
2447
- }
2448
- async function getProfileState(profileId, config = {}) {
2449
- validateId(profileId, "profileId");
2450
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2451
- const headers = buildHeaders(config);
2452
- const response = await fetchWithRetry(
2453
- `${apiUrl}/profiles/${encodeURIComponent(profileId)}/state`,
2454
- { method: "GET", headers },
2455
- config.retryConfig
2456
- );
2457
- if (!response.ok) {
2458
- const errorText = await response.text().catch(() => response.statusText);
2459
- const requestId = response.headers.get("x-request-id") || void 0;
2460
- throw parseAPIError(response.status, errorText, requestId);
2461
- }
2462
- const apiState = await response.json();
2463
- return transformStateResponse(apiState);
2464
- }
2465
- function buildHeaders(config) {
2466
- const headers = { "Content-Type": "application/json" };
2467
- if (config.apiKey) {
2468
- headers["Authorization"] = `Bearer ${config.apiKey}`;
2469
- }
2470
- return headers;
2471
- }
2472
- async function fetchProfile(id, config) {
2473
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2474
- const headers = buildHeaders(config);
2475
- const response = await fetchWithRetry(
2476
- `${apiUrl}/profiles/${encodeURIComponent(id)}`,
2477
- { method: "GET", headers },
2478
- config.retryConfig
2479
- );
2480
- if (!response.ok) {
2481
- const errorText = await response.text().catch(() => response.statusText);
2482
- const requestId = response.headers.get("x-request-id") || void 0;
2483
- throw parseAPIError(response.status, errorText, requestId);
2484
- }
2485
- const apiProfile = await response.json();
2486
- return transformProfile(apiProfile);
2487
- }
2488
- function buildProfileSetup(profile, session, config) {
2489
- return {
2490
- profile,
2491
- session,
2492
- save: () => saveProfileSession({ sessionId: session.sessionId, profileId: profile.id }, config)
2493
- };
2494
- }
2495
-
2496
- // tools/browser/core.ts
2497
- var DEFAULT_CONFIG2 = {
2498
- apiUrl: process.env.MORPH_ENVIRONMENT === "DEV" ? "http://localhost:8000" : "https://browser.morphllm.com",
2499
- timeout: 1e6,
2500
- // 10 minutes for complex tasks
2501
- debug: false
2502
- };
2503
- var BrowserClient = class extends APIResource {
2504
- config;
2505
- /**
2506
- * Profile management - create and manage browser profiles for storing login state.
2507
- */
2508
- profiles;
2509
- constructor(clientOrConfig = {}) {
2510
- const isClient = clientOrConfig instanceof MorphAPIClient;
2511
- super(
2512
- isClient ? clientOrConfig : new MorphAPIClient({
2513
- apiKey: clientOrConfig.apiKey,
2514
- browserURL: clientOrConfig.apiUrl,
2515
- timeout: clientOrConfig.timeout,
2516
- retryConfig: clientOrConfig.retryConfig,
2517
- debug: clientOrConfig.debug
2518
- })
2519
- );
2520
- this.config = isClient ? {
2521
- ...DEFAULT_CONFIG2,
2522
- apiUrl: clientOrConfig.browserURL,
2523
- apiKey: clientOrConfig.resolveApiKey(),
2524
- retryConfig: clientOrConfig.retryConfig,
2525
- debug: clientOrConfig.debug
2526
- } : { ...DEFAULT_CONFIG2, ...clientOrConfig };
2527
- this.profiles = new ProfilesClient(this.config);
2528
- }
2529
- /**
2530
- * Execute a browser automation task
2531
- */
2532
- async execute(input) {
2533
- return executeBrowserTask(input, this.config);
2534
- }
2535
- async createTask(input) {
2536
- const apiUrl = this.config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2537
- const debug = this.config.debug || false;
2538
- const hasTask = typeof input.task === "string" && input.task.trim().length > 0;
2539
- const hasDiff = typeof input.diff === "string" && input.diff.trim().length > 0;
2540
- if (!hasTask && !hasDiff) {
2541
- throw new Error('Browser task requires either "task" (natural language) or "diff" (PR-review planning)');
2542
- }
2543
- logger.debug("Browser", "create_task", { task: (input.task ?? "").slice(0, 100), url: input.url, endpoint: `${apiUrl}/browser-task/async` });
2544
- const headers = { "Content-Type": "application/json" };
2545
- if (this.config.apiKey) headers["Authorization"] = `Bearer ${this.config.apiKey}`;
2546
- const response = await fetch(`${apiUrl}/browser-task/async`, {
2547
- method: "POST",
2548
- headers,
2549
- body: JSON.stringify({
2550
- task: input.task,
2551
- diff: input.diff,
2552
- url: input.url,
2553
- max_steps: input.maxSteps ?? 10,
2554
- model: input.model ?? "morph-computer-use-v0",
2555
- viewport_width: input.viewportWidth ?? 1280,
2556
- viewport_height: input.viewportHeight ?? 720,
2557
- external_id: input.externalId,
2558
- repo_id: input.repoId,
2559
- repo_full_name: input.repoFullName,
2560
- commit_id: input.commitId,
2561
- record_video: input.recordVideo ?? false,
2562
- video_width: input.videoWidth ?? input.viewportWidth ?? 1280,
2563
- video_height: input.videoHeight ?? input.viewportHeight ?? 720,
2564
- allow_resizing: input.allowResizing ?? false,
2565
- structured_output: "schema" in input ? stringifyStructuredOutput(input.schema) : void 0,
2566
- auth: input.auth,
2567
- profile_id: input.profileId,
2568
- force_query_params: input.forceQueryParams
2569
- })
2570
- });
2571
- if (!response.ok) {
2572
- const errorText = await response.text().catch(() => response.statusText);
2573
- logger.error("Browser", "create_task_error", { status: response.status, error: errorText });
2574
- throw new Error(`HTTP ${response.status}: ${errorText}`);
2575
- }
2576
- const result = mapTaskResult(await response.json());
2577
- logger.debug("Browser", "task_created", { recording_id: result.recordingId, task_id: result.taskId, debug_url: !!result.debugUrl });
2578
- if ("schema" in input) {
2579
- return wrapTaskResponseWithSchema(result, this.config, input.schema);
2580
- } else {
2581
- return wrapTaskResponse(result, this.config);
2582
- }
2583
- }
2584
- /**
2585
- * Execute task with recording and wait for video to be ready
2586
- */
2587
- async executeWithRecording(input) {
2588
- return executeWithRecording(input, this.config);
2589
- }
2590
- /**
2591
- * Get recording status and URLs
2592
- */
2593
- async getRecording(recordingId) {
2594
- return getRecording(recordingId, this.config);
2595
- }
2596
- /**
2597
- * Wait for recording to complete with automatic polling
2598
- */
2599
- async waitForRecording(recordingId, options) {
2600
- return waitForRecording(recordingId, this.config, options);
2601
- }
2602
- /**
2603
- * Get errors from recording with screenshots
2604
- */
2605
- async getErrors(recordingId) {
2606
- return getErrors(recordingId, this.config);
2607
- }
2608
- /**
2609
- * Get animated WebP preview of recording
2610
- */
2611
- async getWebp(recordingId, options) {
2612
- return getWebp(recordingId, this.config, options);
2613
- }
2614
- /**
2615
- * Check if browser worker service is healthy
2616
- */
2617
- async checkHealth() {
2618
- return checkHealth(this.config);
2619
- }
2620
- };
2621
- async function executeBrowserTask(input, config = {}) {
2622
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2623
- const timeout = config.timeout || DEFAULT_CONFIG2.timeout;
2624
- const debug = config.debug || false;
2625
- if (!input.task || input.task.trim().length === 0) {
2626
- return {
2627
- success: false,
2628
- error: 'Task description is required. Example: "Go to example.com and click the login button"'
2629
- };
2630
- }
2631
- if (input.maxSteps !== void 0 && (input.maxSteps < 1 || input.maxSteps > 50)) {
2632
- return {
2633
- success: false,
2634
- error: "maxSteps must be between 1 and 50. Use more steps for complex multi-page flows."
2635
- };
2636
- }
2637
- logger.debug("Browser", "execute_start", { task: input.task.slice(0, 100), url: input.url, max_steps: input.maxSteps ?? 10, record_video: input.recordVideo ?? false });
2638
- const startTime = Date.now();
2639
- try {
2640
- const headers = { "Content-Type": "application/json" };
2641
- if (config.apiKey) headers["Authorization"] = `Bearer ${config.apiKey}`;
2642
- const fetchPromise = fetchWithRetry(
2643
- `${apiUrl}/browser-task`,
2644
- {
2645
- method: "POST",
2646
- headers,
2647
- body: JSON.stringify({
2648
- task: input.task,
2649
- url: input.url,
2650
- max_steps: input.maxSteps ?? 10,
2651
- model: input.model ?? "morph-computer-use-v0",
2652
- viewport_width: input.viewportWidth ?? 1280,
2653
- viewport_height: input.viewportHeight ?? 720,
2654
- external_id: input.externalId,
2655
- repo_id: input.repoId,
2656
- commit_id: input.commitId,
2657
- record_video: input.recordVideo ?? false,
2658
- video_width: input.videoWidth ?? input.viewportWidth ?? 1280,
2659
- video_height: input.videoHeight ?? input.viewportHeight ?? 720,
2660
- allow_resizing: input.allowResizing ?? false,
2661
- structured_output: input.structuredOutput,
2662
- auth: input.auth,
2663
- profile_id: input.profileId,
2664
- force_query_params: input.forceQueryParams
2665
- })
2666
- },
2667
- config.retryConfig
2668
- );
2669
- const response = await withTimeout(
2670
- fetchPromise,
2671
- timeout,
2672
- `Browser task timed out after ${timeout}ms. Consider increasing timeout or reducing maxSteps.`
2673
- );
2674
- if (!response.ok) {
2675
- const errorText = await response.text().catch(() => response.statusText);
2676
- logger.error("Browser", "execute_error", { status: response.status, error: errorText });
2677
- throw new Error(`HTTP ${response.status}: ${errorText}`);
2678
- }
2679
- const result = mapTaskResult(await response.json());
2680
- const elapsed = Date.now() - startTime;
2681
- logger.debug("Browser", "execute_complete", { success: result.success, latency_ms: elapsed, steps: result.stepsTaken ?? 0, recording_id: result.recordingId });
2682
- return result;
2683
- } catch (error) {
2684
- if (error instanceof Error) {
2685
- if (error.message.includes("ECONNREFUSED") || error.message.includes("fetch failed")) {
2686
- return {
2687
- success: false,
2688
- error: `Cannot connect to browser worker at ${apiUrl}. Ensure the service is running and accessible. For local dev, set MORPH_ENVIRONMENT=DEV.`
2689
- };
2690
- }
2691
- return {
2692
- success: false,
2693
- error: error.message
2694
- };
2695
- }
2696
- return {
2697
- success: false,
2698
- error: String(error)
2699
- };
2700
- }
2701
- }
2702
- async function getRecording(recordingId, config = {}) {
2703
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2704
- const debug = config.debug || false;
2705
- if (!config.apiKey) {
2706
- throw new Error("API key required for getRecording");
2707
- }
2708
- if (debug) console.log(`[Browser] getRecording: ${recordingId}`);
2709
- const response = await fetch(`${apiUrl}/recordings/${recordingId}`, {
2710
- method: "GET",
2711
- headers: { "Authorization": `Bearer ${config.apiKey}` }
2712
- });
2713
- if (!response.ok) {
2714
- const errorText = await response.text().catch(() => response.statusText);
2715
- if (debug) console.error(`[Browser] getRecording error: ${response.status} - ${errorText}`);
2716
- throw new Error(`HTTP ${response.status}: ${errorText}`);
2717
- }
2718
- const data = mapRecordingStatus(await response.json());
2719
- if (debug) console.log(`[Browser] Recording status: ${data.status}`);
2720
- return {
2721
- ...data,
2722
- getWebp: (options) => getWebp(recordingId, config, options),
2723
- getErrors: () => getErrors(recordingId, config)
2724
- };
2725
- }
2726
- async function waitForRecording(recordingId, config = {}, options = {}) {
2727
- const timeout = options.timeout ?? 6e4;
2728
- const pollInterval = options.pollInterval ?? 2e3;
2729
- const startTime = Date.now();
2730
- while (Date.now() - startTime < timeout) {
2731
- const status = await getRecording(recordingId, config);
2732
- if (status.status === "COMPLETED" || status.status === "ERROR") {
2733
- return status;
2734
- }
2735
- await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
2736
- }
2737
- throw new Error(`Recording timeout after ${timeout}ms - status still pending`);
2738
- }
2739
- async function executeWithRecording(input, config = {}) {
2740
- const taskResult = await executeBrowserTask(input, config);
2741
- if (taskResult.recordingId) {
2742
- try {
2743
- const recording = await waitForRecording(
2744
- taskResult.recordingId,
2745
- config,
2746
- { timeout: 6e4, pollInterval: 2e3 }
2747
- );
2748
- return {
2749
- ...taskResult,
2750
- recording
2751
- };
2752
- } catch (error) {
2753
- const errorRecording = {
2754
- id: taskResult.recordingId,
2755
- status: "ERROR",
2756
- error: error instanceof Error ? error.message : String(error),
2757
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2758
- getWebp: (options) => getWebp(taskResult.recordingId, config, options),
2759
- getErrors: () => getErrors(taskResult.recordingId, config)
2760
- };
2761
- return {
2762
- ...taskResult,
2763
- recording: errorRecording
2764
- };
2765
- }
2766
- }
2767
- return taskResult;
2768
- }
2769
- async function getErrors(recordingId, config = {}) {
2770
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2771
- const debug = config.debug || false;
2772
- if (!config.apiKey) {
2773
- throw new Error("API key required for getErrors");
2774
- }
2775
- if (debug) console.log(`[Browser] getErrors: ${recordingId}`);
2776
- const response = await fetch(`${apiUrl}/recordings/${recordingId}/errors`, {
2777
- method: "GET",
2778
- headers: { "Authorization": `Bearer ${config.apiKey}` }
2779
- });
2780
- if (!response.ok) {
2781
- const errorText = await response.text().catch(() => response.statusText);
2782
- if (debug) console.error(`[Browser] getErrors error: ${response.status} - ${errorText}`);
2783
- throw new Error(`HTTP ${response.status}: ${errorText}`);
2784
- }
2785
- const errors = mapErrorsResponse(await response.json());
2786
- if (debug) console.log(`[Browser] Found ${errors.totalErrors} errors`);
2787
- return errors;
2788
- }
2789
- function stringifyStructuredOutput(schema) {
2790
- try {
2791
- return JSON.stringify({
2792
- type: "object",
2793
- description: "Zod schema definition (Zod v3)",
2794
- zodDef: schema._def
2795
- });
2796
- } catch (error) {
2797
- console.warn("[Browser] Failed to serialize Zod schema:", error);
2798
- return JSON.stringify({
2799
- type: "object",
2800
- description: "Schema serialization failed"
2801
- });
2802
- }
2803
- }
2804
- function parseStructuredTaskOutput(result, schema) {
2805
- if (!result.output) {
2806
- return { ...result, parsed: null };
2807
- }
2808
- try {
2809
- const parsed = JSON.parse(result.output);
2810
- const validated = schema.parse(parsed);
2811
- return { ...result, parsed: validated };
2812
- } catch (error) {
2813
- if (error instanceof SyntaxError) {
2814
- return { ...result, parsed: null };
2815
- }
2816
- throw error;
2817
- }
2818
- }
2819
- function mapTaskResult(api) {
2820
- if (!api || typeof api !== "object") {
2821
- return api;
2822
- }
2823
- return {
2824
- success: api.success,
2825
- result: api.result,
2826
- error: api.error,
2827
- stepsTaken: api.steps_taken,
2828
- executionTimeMs: api.execution_time_ms,
2829
- urls: api.urls,
2830
- actionNames: api.action_names,
2831
- errors: api.errors,
2832
- modelActions: api.model_actions,
2833
- isDone: api.is_done,
2834
- actionHistory: api.action_history,
2835
- actionResults: api.action_results,
2836
- hasErrors: api.has_errors,
2837
- numberOfSteps: api.number_of_steps,
2838
- judgement: api.judgement,
2839
- isValidated: api.is_validated,
2840
- replayId: api.replay_id,
2841
- replayUrl: api.replay_url,
2842
- recordingId: api.recording_id,
2843
- recordingStatus: api.recording_status,
2844
- taskId: api.task_id,
2845
- status: api.status,
2846
- output: api.output,
2847
- debugUrl: api.debug_url
2848
- };
2849
- }
2850
- function mapRecordingStatus(api) {
2851
- return {
2852
- id: api.id,
2853
- status: api.status,
2854
- replayUrl: api.replay_url,
2855
- networkUrl: api.network_url,
2856
- consoleUrl: api.console_url,
2857
- videoUrl: api.video_url,
2858
- result: api.result,
2859
- totalEvents: api.total_events,
2860
- fileSize: api.file_size,
2861
- duration: api.duration,
2862
- error: api.error,
2863
- createdAt: api.created_at
2864
- };
2865
- }
2866
- function mapBrowserError(api) {
2867
- return {
2868
- type: api.type,
2869
- message: api.message,
2870
- url: api.url,
2871
- timestamp: api.timestamp,
2872
- screenshotUrl: api.screenshot_url,
2873
- capturedAt: api.captured_at,
2874
- status: api.status
2875
- };
2876
- }
2877
- function mapErrorsResponse(api) {
2878
- return {
2879
- recordingId: api.recording_id,
2880
- totalErrors: api.total_errors,
2881
- errors: Array.isArray(api.errors) ? api.errors.map(mapBrowserError) : []
2882
- };
2883
- }
2884
- function mapWebpResponse(api) {
2885
- return {
2886
- webpUrl: api.webp_url,
2887
- cached: api.cached,
2888
- width: api.width,
2889
- fps: api.fps,
2890
- maxDuration: api.max_duration,
2891
- fileSize: api.file_size,
2892
- maxSizeMb: api.max_size_mb,
2893
- budgetMet: api.budget_met,
2894
- qualityUsed: api.quality_used,
2895
- attempts: api.attempts
2896
- };
2897
- }
2898
- async function getTaskStatus(taskId, config) {
2899
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2900
- const debug = config.debug || false;
2901
- if (debug) console.log(`[Browser] getTaskStatus: ${taskId}`);
2902
- const headers = {};
2903
- if (config.apiKey) headers["Authorization"] = `Bearer ${config.apiKey}`;
2904
- const response = await fetch(`${apiUrl}/tasks/${taskId}`, {
2905
- method: "GET",
2906
- headers
2907
- });
2908
- if (!response.ok) {
2909
- const errorText = await response.text().catch(() => response.statusText);
2910
- if (debug) console.error(`[Browser] getTaskStatus error: ${response.status} - ${errorText}`);
2911
- throw new Error(`HTTP ${response.status}: ${errorText}`);
2912
- }
2913
- const result = mapTaskResult(await response.json());
2914
- if (debug) console.log(`[Browser] Task status: ${result.status}`);
2915
- return result;
2916
- }
2917
- function generateLiveUrl(taskId, config) {
2918
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2919
- const baseUrl = apiUrl.replace("/api", "");
2920
- return `${baseUrl}/tasks/${taskId}/live`;
2921
- }
2922
- async function pollTaskUntilComplete(taskId, config, pollConfig = {}) {
2923
- const interval = pollConfig.interval ?? 2e3;
2924
- const timeout = pollConfig.timeout ?? 3e5;
2925
- const startTime = Date.now();
2926
- while (Date.now() - startTime < timeout) {
2927
- const status = await getTaskStatus(taskId, config);
2928
- if (status.status === "completed" || status.status === "failed") {
2929
- return status;
2930
- }
2931
- await new Promise((resolve2) => setTimeout(resolve2, interval));
2932
- }
2933
- throw new Error(`Task polling timeout after ${timeout}ms`);
2934
- }
2935
- function wrapTaskResponse(result, config) {
2936
- const debugUrl = result.debugUrl ?? "";
2937
- const wrapped = {
2938
- ...result,
2939
- debugUrl,
2940
- taskId: result.taskId || "",
2941
- liveUrl: result.taskId ? generateLiveUrl(result.taskId, config) : debugUrl,
2942
- complete: async (pollConfig) => {
2943
- if (result.taskId) {
2944
- return pollTaskUntilComplete(result.taskId, config, pollConfig);
2945
- }
2946
- if (result.recordingId) {
2947
- const recording = await waitForRecording(
2948
- result.recordingId,
2949
- config,
2950
- pollConfig
2951
- );
2952
- return {
2953
- ...result,
2954
- recordingStatus: recording.status
2955
- };
2956
- }
2957
- throw new Error("Cannot poll completion: no taskId or recordingId available");
2958
- },
2959
- // Add Steel live session helpers - either functional or error-throwing
2960
- getLiveUrl: debugUrl ? (options) => buildLiveUrl(debugUrl, options) : () => {
2961
- throw new Error(
2962
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
2963
- );
2964
- },
2965
- getLiveIframe: debugUrl ? (optionsOrPreset) => {
2966
- const options = resolvePreset(optionsOrPreset);
2967
- return buildLiveIframe(debugUrl, options);
2968
- } : () => {
2969
- throw new Error(
2970
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
2971
- );
2972
- },
2973
- getEmbedCode: debugUrl ? () => buildEmbedCode(debugUrl) : () => {
2974
- throw new Error(
2975
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
2976
- );
2977
- }
2978
- };
2979
- return wrapped;
2980
- }
2981
- function wrapTaskResponseWithSchema(result, config, schema) {
2982
- const debugUrl = result.debugUrl ?? "";
2983
- const parsed = result.output ? parseStructuredTaskOutput(result, schema) : { ...result, parsed: null };
2984
- const wrapped = {
2985
- ...parsed,
2986
- debugUrl,
2987
- taskId: result.taskId || "",
2988
- liveUrl: result.taskId ? generateLiveUrl(result.taskId, config) : debugUrl,
2989
- complete: async (pollConfig) => {
2990
- if (result.taskId) {
2991
- const finalResult = await pollTaskUntilComplete(result.taskId, config, pollConfig);
2992
- return parseStructuredTaskOutput(finalResult, schema);
2993
- }
2994
- if (result.recordingId) {
2995
- const recording = await waitForRecording(
2996
- result.recordingId,
2997
- config,
2998
- pollConfig
2999
- );
3000
- return {
3001
- ...parsed,
3002
- recordingStatus: recording.status
3003
- };
3004
- }
3005
- throw new Error("Cannot poll completion: no taskId or recordingId available");
3006
- },
3007
- // Add Steel live session helpers - either functional or error-throwing
3008
- getLiveUrl: debugUrl ? (options) => buildLiveUrl(debugUrl, options) : () => {
3009
- throw new Error(
3010
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions. "
3011
- );
3012
- },
3013
- getLiveIframe: debugUrl ? (optionsOrPreset) => {
3014
- const options = resolvePreset(optionsOrPreset);
3015
- return buildLiveIframe(debugUrl, options);
3016
- } : () => {
3017
- throw new Error(
3018
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions."
3019
- );
3020
- },
3021
- getEmbedCode: debugUrl ? () => buildEmbedCode(debugUrl) : () => {
3022
- throw new Error(
3023
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions."
3024
- );
3025
- }
3026
- };
3027
- return wrapped;
3028
- }
3029
- async function getWebp(recordingId, config = {}, options = {}) {
3030
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
3031
- const debug = config.debug || false;
3032
- if (!config.apiKey) {
3033
- throw new Error("API key required for getWebp");
3034
- }
3035
- const params = new URLSearchParams();
3036
- if (options.maxDuration !== void 0) params.set("max_duration", String(options.maxDuration));
3037
- if (options.fps !== void 0) params.set("fps", String(options.fps));
3038
- if (options.width !== void 0) params.set("width", String(options.width));
3039
- if (options.quality !== void 0) params.set("quality", String(options.quality));
3040
- if (options.maxSizeMb !== void 0) params.set("max_size_mb", String(options.maxSizeMb));
3041
- const url = `${apiUrl}/recordings/${recordingId}/webp${params.toString() ? "?" + params.toString() : ""}`;
3042
- if (debug) console.log(`[Browser] getWebp: ${url}`);
3043
- const response = await fetch(url, {
3044
- method: "GET",
3045
- headers: { "Authorization": `Bearer ${config.apiKey}` }
3046
- });
3047
- if (!response.ok) {
3048
- const errorText = await response.text().catch(() => response.statusText);
3049
- if (debug) console.error(`[Browser] getWebp error: ${response.status} - ${errorText}`);
3050
- throw new Error(`HTTP ${response.status}: ${errorText}`);
3051
- }
3052
- const result = mapWebpResponse(await response.json());
3053
- if (debug) console.log(`[Browser] WebP ready: ${result.webpUrl} (cached: ${result.cached})`);
3054
- return result;
3055
- }
3056
- async function checkHealth(config = {}) {
3057
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
3058
- try {
3059
- const response = await fetch(`${apiUrl}/health`, {
3060
- method: "GET",
3061
- headers: config.apiKey ? { "Authorization": `Bearer ${config.apiKey}` } : {}
3062
- });
3063
- if (!response.ok) {
3064
- throw new Error(`HTTP ${response.status}`);
3065
- }
3066
- const data = await response.json();
3067
- return {
3068
- ok: true,
3069
- google_configured: data.google_configured ?? false,
3070
- database_configured: data.database_configured ?? false,
3071
- s3_configured: data.s3_configured ?? false
3072
- };
3073
- } catch (error) {
3074
- return {
3075
- ok: false,
3076
- google_configured: false,
3077
- database_configured: false,
3078
- s3_configured: false,
3079
- error: error instanceof Error ? error.message : String(error)
3080
- };
3081
- }
3082
- }
3083
-
3084
- // tools/warp_grep/agent/runner.ts
3085
- init_config();
3086
-
3087
- // tools/warp_grep/agent/parser.ts
3088
- function parseReadLines(linesStr) {
3089
- const ranges = [];
3090
- for (const rangeStr of linesStr.split(",")) {
3091
- const trimmed = rangeStr.trim();
3092
- if (!trimmed) continue;
3093
- const parts = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
3094
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
3095
- ranges.push([parts[0], parts[1]]);
3096
- } else if (Number.isFinite(parts[0])) {
3097
- ranges.push([parts[0], parts[0]]);
3098
- }
3099
- }
3100
- if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };
3101
- if (ranges.length > 1) return { lines: ranges };
3102
- return {};
3103
- }
3104
- function parseFinishFiles(filesStr) {
3105
- const files = [];
3106
- for (const line of filesStr.trim().split(/\s+/)) {
3107
- const trimmed = line.trim();
3108
- if (!trimmed) continue;
3109
- const searchFrom = /^[A-Za-z]:/.test(trimmed) ? 2 : 0;
3110
- const colonIdx = trimmed.indexOf(":", searchFrom);
3111
- if (colonIdx === -1) {
3112
- files.push({ path: trimmed, lines: "*" });
3113
- continue;
3114
- }
3115
- const filePath = trimmed.slice(0, colonIdx);
3116
- const rangesPart = trimmed.slice(colonIdx + 1);
3117
- if (!rangesPart.trim() || rangesPart.trim() === "*") {
3118
- files.push({ path: filePath, lines: "*" });
3119
- continue;
3120
- }
3121
- const ranges = [];
3122
- for (const rangeStr of rangesPart.split(",")) {
3123
- const rt = rangeStr.trim();
3124
- if (!rt) continue;
3125
- const parts = rt.split("-").map((v) => parseInt(v.trim(), 10));
3126
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
3127
- ranges.push([parts[0], parts[1]]);
3128
- } else if (Number.isFinite(parts[0])) {
3129
- ranges.push([parts[0], parts[0]]);
3130
- }
3131
- }
3132
- files.push({ path: filePath, lines: ranges.length > 0 ? ranges : "*" });
3133
- }
3134
- return files;
3135
- }
3136
- function extractPathFromCommand(command) {
3137
- const tokens = command.trim().split(/\s+/);
3138
- const pathTokens = tokens.slice(1).filter((t) => !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("\\("));
3139
- return pathTokens[0] || ".";
3140
- }
3141
-
3142
- // tools/warp_grep/agent/tools/grep.ts
3143
- async function toolGrep(provider, args) {
3144
- const res = await provider.grep(args);
3145
- if (res.error) {
3146
- return { output: res.error };
3147
- }
3148
- if (!res.lines.length) {
3149
- return { output: "no matches" };
3150
- }
3151
- return { output: res.lines.join("\n") };
3152
- }
3153
-
3154
- // tools/warp_grep/agent/tools/read.ts
3155
- function isValidRange(start, end) {
3156
- return typeof start === "number" && typeof end === "number" && Number.isFinite(start) && Number.isFinite(end) && start > 0 && end >= start;
3157
- }
3158
- async function toolRead(provider, args) {
3159
- if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {
3160
- const validRanges = [];
3161
- for (const range of args.lines) {
3162
- if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {
3163
- validRanges.push([range[0], range[1]]);
3164
- }
3165
- }
3166
- if (validRanges.length === 0) {
3167
- const res2 = await provider.read({ path: args.path });
3168
- if (res2.error) return res2.error;
3169
- if (!res2.lines.length) return "(empty file)";
3170
- return res2.lines.join("\n");
3171
- }
3172
- const chunks = [];
3173
- for (const [start, end] of validRanges) {
3174
- const res2 = await provider.read({ path: args.path, start, end });
3175
- if (res2.error) return res2.error;
3176
- chunks.push(res2.lines.join("\n"));
3177
- }
3178
- if (chunks.every((c) => c === "")) return "(empty file)";
3179
- return chunks.join("\n...\n");
3180
- }
3181
- const res = await provider.read({ path: args.path, start: args.start, end: args.end });
3182
- if (res.error) {
3183
- return res.error;
3184
- }
3185
- if (!res.lines.length) return "(empty file)";
3186
- return res.lines.join("\n");
3187
- }
3188
-
3189
- // tools/warp_grep/agent/tools/list_directory.ts
3190
- init_config();
3191
- var import_path2 = __toESM(require("path"), 1);
3192
- async function toolListDirectory(provider, args, repoRoot) {
3193
- const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;
3194
- const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
3195
- const entries = await provider.listDirectory({
3196
- path: args.path,
3197
- pattern: args.pattern ?? null,
3198
- maxResults,
3199
- maxDepth
3200
- });
3201
- if (!entries.length) return "empty";
3202
- if (repoRoot) {
3203
- const absRoot = repoRoot;
3204
- const lines = entries.map((e) => import_path2.default.join(absRoot, e.path));
3205
- return lines.join("\n");
3206
- }
3207
- return entries.map((e) => e.path).join("\n");
3208
- }
3209
-
3210
- // tools/warp_grep/agent/tools/glob.ts
3211
- async function toolGlob(provider, args) {
3212
- const res = await provider.glob(args);
3213
- if (res.error) {
3214
- return res.error;
3215
- }
3216
- if (!res.files.length) {
3217
- return "no matches";
3218
- }
3219
- const header = `Found ${res.totalFound} file(s) matching "${args.pattern}" within ${res.searchDir}, sorted by modification time (newest first):`;
3220
- const body = res.files.join("\n");
3221
- const truncated = res.totalFound > res.files.length ? `
3222
- [${res.totalFound - res.files.length} files truncated]` : "";
3223
- return `${header}
3224
- ---
3225
- ${body}
3226
- ---${truncated}`;
3227
- }
3228
-
3229
- // tools/warp_grep/agent/tools/finish.ts
3230
- function isValidRange2(range) {
3231
- 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];
3232
- }
3233
- function extractValidRanges(lines) {
3234
- if (!Array.isArray(lines)) return null;
3235
- const valid = [];
3236
- for (const range of lines) {
3237
- if (isValidRange2(range)) {
3238
- valid.push([range[0], range[1]]);
3239
- }
3240
- }
3241
- return valid.length > 0 ? valid : null;
3242
- }
3243
- async function readFinishFiles(repoRoot, files, reader) {
3244
- const out = [];
3245
- for (const f of files) {
3246
- const validRanges = f.lines === "*" ? null : extractValidRanges(f.lines);
3247
- if (f.lines === "*" || !validRanges) {
3248
- const lines = await reader(f.path);
3249
- out.push({ path: f.path, ranges: "*", content: lines.join("\n") });
3250
- } else {
3251
- const ranges = mergeRanges(validRanges);
3252
- const chunks = [];
3253
- for (let i = 0; i < ranges.length; i++) {
3254
- const [s, e] = ranges[i];
3255
- if (i === 0 && s > 1) {
3256
- chunks.push(`// ... existing code, block starting at line ${s} ...`);
3257
- } else if (i > 0) {
3258
- chunks.push(`// ... existing code, block starting at line ${s} ...`);
3259
- }
3260
- const lines = await reader(f.path, s, e);
3261
- chunks.push(lines.join("\n"));
3262
- }
3263
- out.push({ path: f.path, ranges, content: chunks.join("\n") });
3264
- }
3265
- }
3266
- return out;
3267
- }
3268
- function mergeRanges(ranges) {
3269
- if (!ranges.length) return [];
3270
- const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
3271
- const merged = [];
3272
- let [cs, ce] = sorted[0];
3273
- for (let i = 1; i < sorted.length; i++) {
3274
- const [s, e] = sorted[i];
3275
- if (s <= ce + 1) {
3276
- ce = Math.max(ce, e);
3277
- } else {
3278
- merged.push([cs, ce]);
3279
- cs = s;
3280
- ce = e;
3281
- }
3282
- }
3283
- merged.push([cs, ce]);
3284
- return merged;
1964
+ function mergeRanges(ranges) {
1965
+ if (!ranges.length) return [];
1966
+ const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
1967
+ const merged = [];
1968
+ let [cs, ce] = sorted[0];
1969
+ for (let i = 1; i < sorted.length; i++) {
1970
+ const [s, e] = sorted[i];
1971
+ if (s <= ce + 1) {
1972
+ ce = Math.max(ce, e);
1973
+ } else {
1974
+ merged.push([cs, ce]);
1975
+ cs = s;
1976
+ ce = e;
1977
+ }
1978
+ }
1979
+ merged.push([cs, ce]);
1980
+ return merged;
3285
1981
  }
3286
1982
 
3287
1983
  // tools/warp_grep/agent/helpers.ts
@@ -3390,7 +2086,7 @@ var import_openai2 = __toESM(require("openai"), 1);
3390
2086
  init_version();
3391
2087
  var import_path4 = __toESM(require("path"), 1);
3392
2088
  init_logger();
3393
- var DEFAULT_API_URL3 = "https://api.morphllm.com";
2089
+ var DEFAULT_API_URL2 = "https://api.morphllm.com";
3394
2090
  var TOOL_SPECS = [
3395
2091
  {
3396
2092
  type: "function",
@@ -3499,7 +2195,7 @@ var TOOL_SPECS = [
3499
2195
  }
3500
2196
  ];
3501
2197
  async function callModel(messages, model, options = {}) {
3502
- const baseUrl = options.morphApiUrl || DEFAULT_API_URL3;
2198
+ const baseUrl = options.morphApiUrl || DEFAULT_API_URL2;
3503
2199
  const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
3504
2200
  const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
3505
2201
  const parsedUrl = new URL(baseUrl);
@@ -4053,13 +2749,13 @@ function parseGitHubUrl(input) {
4053
2749
  }
4054
2750
 
4055
2751
  // tools/compact/core.ts
4056
- var DEFAULT_API_URL4 = "https://api.morphllm.com";
2752
+ var DEFAULT_API_URL3 = "https://api.morphllm.com";
4057
2753
  var DEFAULT_TIMEOUT4 = 12e4;
4058
2754
  function resolveClient(clientOrConfig) {
4059
2755
  if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
4060
2756
  return new MorphAPIClient({
4061
2757
  apiKey: clientOrConfig.morphApiKey,
4062
- baseURL: clientOrConfig.morphApiUrl ?? DEFAULT_API_URL4,
2758
+ baseURL: clientOrConfig.morphApiUrl ?? DEFAULT_API_URL3,
4063
2759
  timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT4,
4064
2760
  retryConfig: clientOrConfig.retryConfig,
4065
2761
  debug: clientOrConfig.debug
@@ -4440,582 +3136,16 @@ function formatResult(result) {
4440
3136
  return parts.join("\n");
4441
3137
  }
4442
3138
 
4443
- // tools/github/types.ts
4444
- var GitHubError = class extends Error {
4445
- /** HTTP status code */
4446
- status;
4447
- /** Error code from API */
4448
- code;
4449
- constructor(message, status, code) {
4450
- super(message);
4451
- this.name = "GitHubError";
4452
- this.status = status;
4453
- this.code = code;
4454
- }
4455
- };
4456
- var NoInstallationError = class extends GitHubError {
4457
- constructor(message = "No GitHub installation found. Connect GitHub at morphllm.com/dashboard/integrations/github") {
4458
- super(message, 404, "NO_INSTALLATION");
4459
- }
4460
- };
4461
- var NotFoundError = class extends GitHubError {
4462
- constructor(resource) {
4463
- super(`${resource} not found`, 404, "NOT_FOUND");
4464
- }
4465
- };
4466
- var PermissionError = class extends GitHubError {
4467
- constructor(message = "Insufficient permissions for this operation") {
4468
- super(message, 403, "PERMISSION_DENIED");
4469
- }
4470
- };
4471
-
4472
- // tools/github/core.ts
4473
- var DEFAULT_BASE_URL2 = "https://api.morphllm.com";
4474
- var DEFAULT_TIMEOUT5 = 3e4;
4475
- var GitHubClient = class extends APIResource {
4476
- timeout;
4477
- debug;
4478
- defaultInstallationId;
4479
- /** Installation operations */
4480
- installations;
4481
- /** Repository operations */
4482
- repos;
4483
- /** Project operations (monorepo sub-projects) */
4484
- projects;
4485
- /** Pull request operations */
4486
- pullRequests;
4487
- /** Deployment operations */
4488
- deployments;
4489
- /** Comment operations */
4490
- comments;
4491
- /** Check run operations */
4492
- checkRuns;
4493
- /**
4494
- * Get the GitHub App installation URL.
4495
- * Users visit this URL once to install the Morph GitHub App on their account/org.
4496
- */
4497
- getInstallUrl() {
4498
- return "https://github.com/apps/morph-subagents/installations/new";
4499
- }
4500
- constructor(clientOrConfig = {}, options = {}) {
4501
- const isClient = clientOrConfig instanceof MorphAPIClient;
4502
- const config = isClient ? {} : clientOrConfig;
4503
- super(
4504
- isClient ? clientOrConfig : new MorphAPIClient({
4505
- apiKey: config.apiKey,
4506
- baseURL: config.baseUrl ?? DEFAULT_BASE_URL2,
4507
- timeout: config.timeout ?? DEFAULT_TIMEOUT5,
4508
- debug: config.debug
4509
- })
4510
- );
4511
- this.timeout = config.timeout || DEFAULT_TIMEOUT5;
4512
- this.debug = config.debug || false;
4513
- this.defaultInstallationId = isClient ? options.installationId : config.installationId;
4514
- if (!this._client.resolveApiKey()) {
4515
- throw new Error("API key required. Set MORPH_API_KEY or pass apiKey in config.");
4516
- }
4517
- this.installations = {
4518
- list: this.listInstallations.bind(this),
4519
- get: this.getInstallation.bind(this),
4520
- update: this.updateInstallation.bind(this),
4521
- disconnect: this.disconnectInstallation.bind(this)
4522
- };
4523
- this.repos = {
4524
- list: this.listRepos.bind(this),
4525
- get: this.getRepo.bind(this),
4526
- update: this.updateRepo.bind(this),
4527
- remove: this.removeRepo.bind(this),
4528
- sync: this.syncRepos.bind(this)
4529
- };
4530
- this.projects = {
4531
- list: this.listProjects.bind(this),
4532
- create: this.createProject.bind(this),
4533
- update: this.updateProject.bind(this),
4534
- delete: this.deleteProject.bind(this)
4535
- };
4536
- this.pullRequests = {
4537
- list: this.listPullRequests.bind(this),
4538
- get: this.getPullRequest.bind(this)
4539
- };
4540
- this.deployments = {
4541
- list: this.listDeployments.bind(this)
4542
- };
4543
- this.comments = {
4544
- list: this.listComments.bind(this),
4545
- create: this.createComment.bind(this),
4546
- update: this.updateComment.bind(this),
4547
- delete: this.deleteComment.bind(this)
4548
- };
4549
- this.checkRuns = {
4550
- create: this.createCheckRun.bind(this),
4551
- update: this.updateCheckRun.bind(this)
4552
- };
4553
- }
4554
- /**
4555
- * Make an authenticated API request
4556
- */
4557
- async request(method, path6, body) {
4558
- if (this.debug) {
4559
- console.log(`[GitHub SDK] ${method} ${path6}`, body || "");
4560
- }
4561
- let response;
4562
- try {
4563
- response = await this._client.request(method, path6, {
4564
- body,
4565
- timeout: this.timeout,
4566
- raw: true
4567
- });
4568
- } catch (error) {
4569
- if (error instanceof Error && /timed out/i.test(error.message)) {
4570
- throw new GitHubError("Request timeout", 408, "TIMEOUT");
4571
- }
4572
- throw new GitHubError(error instanceof Error ? error.message : "Unknown error", 500, "UNKNOWN");
4573
- }
4574
- if (!response.ok) {
4575
- const errorData = await response.json().catch(() => ({}));
4576
- const message = errorData.error || errorData.detail || errorData.message || response.statusText;
4577
- if (this.debug) {
4578
- console.error(`[GitHub SDK] Error ${response.status}:`, message);
4579
- }
4580
- if (response.status === 404) {
4581
- if (message.includes("installation")) {
4582
- throw new NoInstallationError(message);
4583
- }
4584
- throw new NotFoundError(message);
4585
- }
4586
- if (response.status === 403) {
4587
- throw new PermissionError(message);
4588
- }
4589
- throw new GitHubError(message, response.status, errorData.code);
4590
- }
4591
- const data = await response.json();
4592
- if (this.debug) {
4593
- console.log(`[GitHub SDK] Response:`, JSON.stringify(data).slice(0, 200));
4594
- }
4595
- return data;
4596
- }
4597
- /**
4598
- * Get the installation ID to use for a request
4599
- */
4600
- getInstallationId(input) {
4601
- return input?.installationId || this.defaultInstallationId;
4602
- }
4603
- // ==========================================================================
4604
- // Installations
4605
- // ==========================================================================
4606
- async listInstallations() {
4607
- return this.request("GET", "/api/v1/github/installations");
4608
- }
4609
- async getInstallation(installationId) {
4610
- return this.request("GET", `/api/v1/github/installations/${installationId}`);
4611
- }
4612
- async updateInstallation(input) {
4613
- if (this.debug) console.log("[GitHub SDK] updateInstallation", input.installationId);
4614
- const { installationId, ...body } = input;
4615
- return this.request("PATCH", `/api/v1/github/installations/${installationId}`, body);
4616
- }
4617
- async disconnectInstallation(installationId) {
4618
- if (this.debug) console.log("[GitHub SDK] disconnectInstallation", installationId);
4619
- return this.request("DELETE", `/api/v1/github/installations/${installationId}`);
4620
- }
4621
- // ==========================================================================
4622
- // Repositories
4623
- // ==========================================================================
4624
- async listRepos(input) {
4625
- const installationId = input.installationId || this.defaultInstallationId;
4626
- if (!installationId) {
4627
- throw new NoInstallationError("installationId required. Call installations.list() first.");
4628
- }
4629
- return this.request("GET", `/api/v1/github/installations/${installationId}/repos`);
4630
- }
4631
- async getRepo(repoId) {
4632
- if (this.debug) console.log("[GitHub SDK] getRepo", repoId);
4633
- return this.request("GET", `/api/v1/github/repos/${repoId}`);
4634
- }
4635
- async updateRepo(input) {
4636
- if (this.debug) console.log("[GitHub SDK] updateRepo", input.repoId);
4637
- const { repoId, ...body } = input;
4638
- return this.request("PATCH", `/api/v1/github/repos/${repoId}`, body);
4639
- }
4640
- async removeRepo(repoId) {
4641
- if (this.debug) console.log("[GitHub SDK] removeRepo", repoId);
4642
- return this.request("DELETE", `/api/v1/github/repos/${repoId}`);
4643
- }
4644
- async syncRepos(input) {
4645
- const installationId = input.installationId || this.defaultInstallationId;
4646
- if (!installationId) {
4647
- throw new NoInstallationError("installationId required. Call installations.list() first.");
4648
- }
4649
- if (this.debug) console.log("[GitHub SDK] syncRepos", installationId);
4650
- return this.request("POST", `/api/v1/github/installations/${installationId}/repos/sync`);
4651
- }
4652
- // ==========================================================================
4653
- // Projects (monorepo sub-projects)
4654
- // ==========================================================================
4655
- async listProjects(input) {
4656
- if (this.debug) console.log("[GitHub SDK] listProjects", input.repoId);
4657
- return this.request("GET", `/api/v1/github/repos/${input.repoId}/projects`);
4658
- }
4659
- async createProject(input) {
4660
- if (this.debug) console.log("[GitHub SDK] createProject", input.repoId, input.name);
4661
- const { repoId, ...body } = input;
4662
- return this.request("POST", `/api/v1/github/repos/${repoId}/projects`, body);
4663
- }
4664
- async updateProject(input) {
4665
- if (this.debug) console.log("[GitHub SDK] updateProject", input.projectId);
4666
- const { projectId, ...body } = input;
4667
- return this.request("PATCH", `/api/v1/github/projects/${projectId}`, body);
4668
- }
4669
- async deleteProject(projectId) {
4670
- if (this.debug) console.log("[GitHub SDK] deleteProject", projectId);
4671
- return this.request("DELETE", `/api/v1/github/projects/${projectId}`);
4672
- }
4673
- // ==========================================================================
4674
- // Pull Requests
4675
- // ==========================================================================
4676
- async listPullRequests(input) {
4677
- const installationId = this.getInstallationId(input);
4678
- const params = new URLSearchParams({
4679
- owner: input.owner,
4680
- repo: input.repo,
4681
- ...input.state && { state: input.state },
4682
- ...installationId && { installationId }
4683
- });
4684
- return this.request("GET", `/api/v1/github/pulls?${params}`);
4685
- }
4686
- async getPullRequest(input) {
4687
- const installationId = this.getInstallationId(input);
4688
- const params = new URLSearchParams({
4689
- owner: input.owner,
4690
- repo: input.repo,
4691
- ...installationId && { installationId }
4692
- });
4693
- return this.request(
4694
- "GET",
4695
- `/api/v1/github/pulls/${input.number}?${params}`
4696
- );
4697
- }
4698
- // ==========================================================================
4699
- // Deployments
4700
- // ==========================================================================
4701
- async listDeployments(input) {
4702
- const installationId = this.getInstallationId(input);
4703
- const params = new URLSearchParams({
4704
- owner: input.owner,
4705
- repo: input.repo,
4706
- ...input.sha && { sha: input.sha },
4707
- ...input.environment && { environment: input.environment },
4708
- ...installationId && { installationId }
4709
- });
4710
- return this.request("GET", `/api/v1/github/deployments?${params}`);
4711
- }
4712
- // ==========================================================================
4713
- // Comments
4714
- // ==========================================================================
4715
- async listComments(input) {
4716
- const installationId = this.getInstallationId(input);
4717
- const params = new URLSearchParams({
4718
- owner: input.owner,
4719
- repo: input.repo,
4720
- pr: String(input.pr),
4721
- ...installationId && { installationId }
4722
- });
4723
- return this.request("GET", `/api/v1/github/comments?${params}`);
4724
- }
4725
- async createComment(input) {
4726
- const installationId = this.getInstallationId(input);
4727
- return this.request("POST", "/api/v1/github/comments", {
4728
- owner: input.owner,
4729
- repo: input.repo,
4730
- pr: input.pr,
4731
- body: input.body,
4732
- ...installationId && { installationId }
4733
- });
4734
- }
4735
- async updateComment(input) {
4736
- const installationId = this.getInstallationId(input);
4737
- return this.request("PATCH", `/api/v1/github/comments/${input.commentId}`, {
4738
- owner: input.owner,
4739
- repo: input.repo,
4740
- body: input.body,
4741
- ...installationId && { installationId }
4742
- });
4743
- }
4744
- async deleteComment(input) {
4745
- const installationId = this.getInstallationId(input);
4746
- const params = new URLSearchParams({
4747
- owner: input.owner,
4748
- repo: input.repo,
4749
- ...installationId && { installationId }
4750
- });
4751
- await this.request("DELETE", `/api/v1/github/comments/${input.commentId}?${params}`);
4752
- }
4753
- // ==========================================================================
4754
- // Check Runs
4755
- // ==========================================================================
4756
- async createCheckRun(input) {
4757
- const installationId = this.getInstallationId(input);
4758
- return this.request("POST", "/api/v1/github/check-runs", {
4759
- owner: input.owner,
4760
- repo: input.repo,
4761
- sha: input.sha,
4762
- name: input.name,
4763
- status: input.status,
4764
- ...input.title && { title: input.title },
4765
- ...input.summary && { summary: input.summary },
4766
- ...installationId && { installationId }
4767
- });
4768
- }
4769
- async updateCheckRun(input) {
4770
- const installationId = this.getInstallationId(input);
4771
- return this.request("PATCH", `/api/v1/github/check-runs/${input.checkRunId}`, {
4772
- owner: input.owner,
4773
- repo: input.repo,
4774
- ...input.status && { status: input.status },
4775
- ...input.conclusion && { conclusion: input.conclusion },
4776
- ...input.title && { title: input.title },
4777
- ...input.summary && { summary: input.summary },
4778
- ...input.text && { text: input.text },
4779
- ...installationId && { installationId }
4780
- });
4781
- }
4782
- };
4783
-
4784
- // tools/reflex/core.ts
4785
- var BASE_MODEL = "morph-reflex-v1";
4786
- function resolveClient2(clientOrConfig) {
4787
- if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
4788
- return new MorphAPIClient({
4789
- apiKey: clientOrConfig.apiKey,
4790
- baseURL: clientOrConfig.baseUrl,
4791
- timeout: clientOrConfig.timeout,
4792
- retryConfig: clientOrConfig.retryConfig,
4793
- debug: clientOrConfig.debug
4794
- });
4795
- }
4796
- var ReflexClient = class extends APIResource {
4797
- /** Train, retrieve, and manage classifier jobs. */
4798
- jobs;
4799
- constructor(clientOrConfig = {}) {
4800
- super(resolveClient2(clientOrConfig));
4801
- this.jobs = new ReflexJobsResource(this._client);
4802
- }
4803
- /** Classify text against one trained model. The model must be `succeeded`. */
4804
- async predict(input) {
4805
- const completionId = input.completionId ?? crypto.randomUUID();
4806
- const raw = await this._client.post("/v1/reflex/predict", {
4807
- body: { model: input.model, text: input.text },
4808
- headers: { "X-Completion-Id": completionId }
4809
- });
4810
- return {
4811
- ...toClassification(raw),
4812
- inferenceTimeMs: raw.inference_time_ms,
4813
- prefillTokens: raw.prefill_tokens ?? 0,
4814
- completionId
4815
- };
4816
- }
4817
- /**
4818
- * Classify text against several models in one request. They share a single
4819
- * prefill, so the input is tokenized once — cheaper and faster than a call per
4820
- * model. Each model returns its own prediction (or an `error` if it failed).
4821
- */
4822
- async predictMany(input) {
4823
- const completionId = input.completionId ?? crypto.randomUUID();
4824
- const raw = await this._client.post("/v1/reflex/predict", {
4825
- body: { models: input.models, text: input.text },
4826
- headers: { "X-Completion-Id": completionId }
4827
- });
4828
- return {
4829
- predictions: (raw.predictions ?? []).map(toPrediction),
4830
- inferenceTimeMs: raw.inference_time_ms,
4831
- prefillTokens: raw.prefill_tokens ?? 0,
4832
- completionId
4833
- };
4834
- }
4835
- };
4836
- var ReflexJobsResource = class extends APIResource {
4837
- /** Start a training job from labeled data, a description, or unlabeled text. */
4838
- async create(input) {
4839
- return toReflexJob(await this._client.post("/v1/fine_tuning/jobs", { body: createBody(input) }));
4840
- }
4841
- /** Fetch a job by id. */
4842
- async retrieve(id) {
4843
- return toReflexJob(await this._client.get(`/v1/fine_tuning/jobs/${encodeURIComponent(id)}`));
4844
- }
4845
- /** List the caller's jobs, newest first. */
4846
- async list(input = {}) {
4847
- const raw = await this._client.get("/v1/fine_tuning/jobs", {
4848
- query: { limit: input.limit, after: input.after }
4849
- });
4850
- return { data: (raw.data ?? []).map(toReflexJob), hasMore: Boolean(raw.has_more) };
4851
- }
4852
- /** Stop a queued or running job. */
4853
- async cancel(id) {
4854
- return toReflexJob(await this._client.post(`/v1/fine_tuning/jobs/${encodeURIComponent(id)}/cancel`));
4855
- }
4856
- /** Delete a job and its trained model. */
4857
- async delete(id) {
4858
- const raw = await this._client.delete(
4859
- `/v1/fine_tuning/jobs/${encodeURIComponent(id)}`
4860
- );
4861
- return { id: raw.id, deleted: Boolean(raw.deleted) };
4862
- }
4863
- /** The training loss curve as events, plus a terminal event. */
4864
- async events(id) {
4865
- const raw = await this._client.get(
4866
- `/v1/fine_tuning/jobs/${encodeURIComponent(id)}/events`
4867
- );
4868
- return (raw.data ?? []).map(toReflexEvent);
4869
- }
4870
- /**
4871
- * Poll until the job reaches a terminal status and return it on success.
4872
- * Throws a `MorphError` if it fails, is cancelled, or exceeds `timeoutMs`.
4873
- */
4874
- async waitForReady(id, opts = {}) {
4875
- const pollMs = opts.pollMs ?? 3e3;
4876
- const deadline = Date.now() + (opts.timeoutMs ?? 15 * 6e4);
4877
- for (; ; ) {
4878
- const job = await this.retrieve(id);
4879
- if (job.status === "succeeded") return job;
4880
- if (job.status === "failed" || job.status === "cancelled") {
4881
- throw new MorphError(job.error?.message ?? `Reflex job ${job.status}`, `reflex_job_${job.status}`);
4882
- }
4883
- if (Date.now() >= deadline) {
4884
- throw new MorphError(`Reflex job ${id} did not finish in time`, "reflex_timeout");
4885
- }
4886
- await sleep2(pollMs);
4887
- }
4888
- }
4889
- };
4890
- function createBody(input) {
4891
- const base = { model: BASE_MODEL };
4892
- if (input.suffix) base.suffix = input.suffix;
4893
- if ("trainingData" in input) {
4894
- if (input.labels) base.labels = input.labels;
4895
- return { ...base, training_data: input.trainingData };
4896
- }
4897
- if ("generate" in input) {
4898
- return {
4899
- ...base,
4900
- labels: input.labels,
4901
- generate: {
4902
- description: input.generate.description,
4903
- ...input.generate.examplesPerLabel != null ? { examples_per_label: input.generate.examplesPerLabel } : {}
4904
- }
4905
- };
4906
- }
4907
- return {
4908
- ...base,
4909
- labels: input.labels,
4910
- label_data: {
4911
- texts: input.labelData.texts,
4912
- ...input.labelData.description ? { description: input.labelData.description } : {}
4913
- }
4914
- };
4915
- }
4916
- function toReflexJob(raw) {
4917
- return {
4918
- id: raw.id,
4919
- object: "fine_tuning.job",
4920
- model: raw.model,
4921
- createdAt: raw.created_at,
4922
- finishedAt: raw.finished_at ?? null,
4923
- fineTunedModel: raw.fine_tuned_model ?? null,
4924
- status: raw.status,
4925
- labels: raw.labels ?? [],
4926
- trainedExamples: raw.trained_examples ?? 0,
4927
- result: raw.result ? { accuracy: raw.result.accuracy ?? null, f1Score: raw.result.f1_score ?? null } : null,
4928
- error: raw.error ? { message: raw.error.message } : null,
4929
- suffix: raw.suffix ?? null
4930
- };
4931
- }
4932
- function toClassification(raw) {
4933
- const classes = (raw.classes ?? []).map((c) => ({
4934
- classId: c.class_id,
4935
- label: c.label,
4936
- score: c.score,
4937
- selected: c.selected
4938
- }));
4939
- const selectedClasses = classes.filter((c) => c.selected);
4940
- const top = selectedClasses.reduce(
4941
- (best, c) => best === null || c.score > best.score ? c : best,
4942
- null
4943
- );
4944
- return {
4945
- model: raw.model,
4946
- mode: raw.mode === "multi_label" ? "multi_label" : "single_label",
4947
- classes,
4948
- selected: selectedClasses.map((c) => c.label),
4949
- label: top ? top.label : null,
4950
- confidence: top ? top.score : null
4951
- };
4952
- }
4953
- function toPrediction(raw) {
4954
- const error = raw.error ? { message: typeof raw.error === "string" ? raw.error : raw.error.message } : null;
4955
- return { ...toClassification(raw), error };
4956
- }
4957
- function toReflexEvent(raw) {
4958
- return {
4959
- id: raw.id,
4960
- createdAt: raw.created_at,
4961
- level: raw.level,
4962
- message: raw.message,
4963
- type: raw.type,
4964
- data: { epoch: raw.data?.epoch ?? 0, step: raw.data?.step ?? 0, trainLoss: raw.data?.train_loss ?? 0 }
4965
- };
4966
- }
4967
- function sleep2(ms) {
4968
- return new Promise((resolve2) => setTimeout(resolve2, ms));
4969
- }
4970
-
4971
- // tools/traces/core.ts
4972
- var TracesClient = class extends APIResource {
4973
- /** List traced turns, newest first. Filter by `convoId`; page with `limit`/`offset`. */
4974
- async list(input = {}) {
4975
- const raw = await this._client.get("/v1/reflex/traces", {
4976
- query: { convo_id: input.convoId, limit: input.limit, offset: input.offset }
4977
- });
4978
- return {
4979
- data: (raw.data ?? []).map(toTrace),
4980
- hasMore: Boolean(raw.has_more),
4981
- offset: raw.offset ?? 0
4982
- };
4983
- }
4984
- };
4985
- function toReflexResult(raw) {
4986
- return {
4987
- model: raw.model,
4988
- transform: raw.transform,
4989
- label: raw.label ?? null,
4990
- score: raw.score,
4991
- selected: raw.selected ?? [],
4992
- status: raw.status,
4993
- transformVersion: raw.transform_version
4994
- };
4995
- }
4996
- function toTrace(raw) {
4997
- return {
4998
- convoId: raw.convo_id,
4999
- eventId: raw.event_id,
5000
- spanKind: raw.span_kind,
5001
- model: raw.model,
5002
- inputText: raw.input_text,
5003
- outputText: raw.output_text,
5004
- startTime: raw.start_time,
5005
- reflexResults: (raw.reflex_results ?? []).map(toReflexResult)
5006
- };
5007
- }
5008
-
5009
3139
  // modelrouter/core.ts
5010
3140
  init_logger();
5011
- var DEFAULT_API_URL5 = "https://api.morphllm.com";
5012
- var DEFAULT_TIMEOUT6 = 5e3;
5013
- function resolveClient3(clientOrConfig) {
3141
+ var DEFAULT_API_URL4 = "https://api.morphllm.com";
3142
+ var DEFAULT_TIMEOUT5 = 5e3;
3143
+ function resolveClient2(clientOrConfig) {
5014
3144
  if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
5015
3145
  return new MorphAPIClient({
5016
3146
  apiKey: clientOrConfig.apiKey,
5017
- baseURL: clientOrConfig.apiUrl ?? DEFAULT_API_URL5,
5018
- timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT6,
3147
+ baseURL: clientOrConfig.apiUrl ?? DEFAULT_API_URL4,
3148
+ timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT5,
5019
3149
  retryConfig: clientOrConfig.retryConfig,
5020
3150
  debug: clientOrConfig.debug
5021
3151
  });
@@ -5024,10 +3154,10 @@ var BaseRouter = class extends APIResource {
5024
3154
  provider;
5025
3155
  timeout;
5026
3156
  constructor(provider, clientOrConfig = {}) {
5027
- super(resolveClient3(clientOrConfig));
3157
+ super(resolveClient2(clientOrConfig));
5028
3158
  this.provider = provider;
5029
3159
  const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
5030
- this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT6;
3160
+ this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT5;
5031
3161
  }
5032
3162
  /** Throw the historical "API key is required" message when no key is resolvable. */
5033
3163
  requireApiKey() {
@@ -5131,9 +3261,9 @@ var RawRouter = class extends BaseRouter {
5131
3261
  var RouterClassifier = class extends APIResource {
5132
3262
  timeout;
5133
3263
  constructor(clientOrConfig = {}) {
5134
- super(resolveClient3(clientOrConfig));
3264
+ super(resolveClient2(clientOrConfig));
5135
3265
  const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
5136
- this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT6;
3266
+ this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT5;
5137
3267
  }
5138
3268
  /** Classify an input across the requested axes (all three by default). */
5139
3269
  async classify(input) {
@@ -6551,10 +4681,6 @@ var MorphClient = class extends MorphAPIClient {
6551
4681
  codebaseSearch;
6552
4682
  /** WarpGrep tool for fast code search using ripgrep */
6553
4683
  warpGrep;
6554
- /** Browser tool for AI-powered browser automation */
6555
- browser;
6556
- /** GitHub tool for PR context, comments, and check runs */
6557
- github;
6558
4684
  /** Model routers for intelligent model selection */
6559
4685
  routers;
6560
4686
  /** OpenAI-compatible tool factories */
@@ -6565,10 +4691,6 @@ var MorphClient = class extends MorphAPIClient {
6565
4691
  vercel;
6566
4692
  /** Compact context with line ranges */
6567
4693
  compact;
6568
- /** Reflex: train and serve small text classifiers */
6569
- reflex;
6570
- /** Traces: read back turns shipped with `morphTracing()`, with their Reflex labels */
6571
- traces;
6572
4694
  /**
6573
4695
  * Create a new Morph SDK client
6574
4696
  *
@@ -6598,8 +4720,6 @@ var MorphClient = class extends MorphAPIClient {
6598
4720
  this.fastApply = new FastApplyClient(this);
6599
4721
  this.codebaseSearch = new CodebaseSearchClient(this);
6600
4722
  this.warpGrep = new WarpGrepClient(this);
6601
- this.browser = new BrowserClient(this);
6602
- this.github = new GitHubClient(this, { installationId: config.github?.installationId });
6603
4723
  this.routers = {
6604
4724
  openai: new OpenAIRouter(this),
6605
4725
  anthropic: new AnthropicRouter(this),
@@ -6609,8 +4729,6 @@ var MorphClient = class extends MorphAPIClient {
6609
4729
  };
6610
4730
  const compactClient = new CompactClient(this);
6611
4731
  this.compact = compactClient.compact.bind(compactClient);
6612
- this.reflex = new ReflexClient(this);
6613
- this.traces = new TracesClient(this);
6614
4732
  this.openai = new OpenAIToolFactory(config);
6615
4733
  this.anthropic = new AnthropicToolFactory(config);
6616
4734
  this.vercel = new VercelToolFactory(config);
@@ -6657,28 +4775,19 @@ var warpGrepInputSchema = import_zod5.z.object({
6657
4775
  APIResource,
6658
4776
  AnthropicRouter,
6659
4777
  AnthropicToolFactory,
6660
- BrowserClient,
6661
4778
  CodebaseSearchClient,
6662
4779
  CompactClient,
6663
4780
  FastApplyAnchorIntegrityError,
6664
4781
  FastApplyClient,
6665
4782
  FastApplyContextLengthError,
6666
4783
  GeminiRouter,
6667
- GitHubClient,
6668
- GitHubError,
6669
4784
  LocalRipgrepProvider,
6670
4785
  MorphAPIClient,
6671
4786
  MorphClient,
6672
- NoInstallationError,
6673
- NotFoundError,
6674
4787
  OpenAIRouter,
6675
4788
  OpenAIToolFactory,
6676
- PermissionError,
6677
4789
  RawRouter,
6678
- ReflexClient,
6679
- ReflexJobsResource,
6680
4790
  SDK_VERSION,
6681
- TracesClient,
6682
4791
  VercelToolFactory,
6683
4792
  WarpGrepClient,
6684
4793
  applyEdit