@morphllm/morphsdk 0.2.198 → 0.2.200

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 (307) hide show
  1. package/README.md +1 -147
  2. package/dist/{chunk-ZQNTXHBQ.js → chunk-3CCWSLQW.js} +2 -2
  3. package/dist/{chunk-FESO6TDQ.js → chunk-7I2A7GGJ.js} +2 -2
  4. package/dist/{chunk-4JUIEYAH.js → chunk-AKSXZBPT.js} +3 -3
  5. package/dist/chunk-B4X5RWLR.js +271 -0
  6. package/dist/chunk-B4X5RWLR.js.map +1 -0
  7. package/dist/{chunk-QKNGVBE2.js → chunk-L6YOMTFU.js} +3 -3
  8. package/dist/{chunk-YQ2G5YLI.js → chunk-MLROWLS6.js} +4 -4
  9. package/dist/{chunk-4DNEBVGV.js → chunk-MPL6BDR6.js} +2 -2
  10. package/dist/{chunk-3XS5P5XH.js → chunk-PD3EDFQD.js} +2 -2
  11. package/dist/{chunk-CAFREMIT.js → chunk-PJNL35DC.js} +2 -2
  12. package/dist/{chunk-PEFXG5M6.js → chunk-Q65LL6UM.js} +2 -2
  13. package/dist/{chunk-YUH3MTP3.js → chunk-QTBFL4DG.js} +2 -2
  14. package/dist/{chunk-XTFRHVCW.js → chunk-SNYHVDE4.js} +4 -4
  15. package/dist/{chunk-ZGERT23F.js → chunk-TIMDDHYB.js} +4 -4
  16. package/dist/{chunk-PV6EF6NG.js → chunk-UHIANNKC.js} +4 -4
  17. package/dist/{chunk-FUYX2MNM.js → chunk-UKAAT6KT.js} +4 -10
  18. package/dist/chunk-UKAAT6KT.js.map +1 -0
  19. package/dist/{chunk-ZU5YYGBJ.js → chunk-UZ42MHTR.js} +3 -63
  20. package/dist/chunk-UZ42MHTR.js.map +1 -0
  21. package/dist/{chunk-XK3PQZW6.js → chunk-WTENYKJP.js} +2 -2
  22. package/dist/{chunk-6XFL2NER.js → chunk-XTLPA7ZP.js} +2 -2
  23. package/dist/{chunk-D2RFP6R2.js → chunk-Z57GJLCG.js} +3 -3
  24. package/dist/{chunk-SKN2L5CE.js → chunk-ZE64EWUV.js} +2 -2
  25. package/dist/client-BWhi-vSj.d.ts +341 -0
  26. package/dist/client.cjs +88 -2086
  27. package/dist/client.cjs.map +1 -1
  28. package/dist/client.d.ts +4 -10
  29. package/dist/client.js +20 -30
  30. package/dist/core/client.cjs +2 -68
  31. package/dist/core/client.cjs.map +1 -1
  32. package/dist/core/client.d.ts +0 -8
  33. package/dist/core/client.js +4 -4
  34. package/dist/core/error.cjs +2 -62
  35. package/dist/core/error.cjs.map +1 -1
  36. package/dist/core/error.js +3 -3
  37. package/dist/core/index.cjs +2 -68
  38. package/dist/core/index.cjs.map +1 -1
  39. package/dist/core/index.js +4 -4
  40. package/dist/edge.cjs +2 -68
  41. package/dist/edge.cjs.map +1 -1
  42. package/dist/edge.js +7 -7
  43. package/dist/index.cjs +89 -2101
  44. package/dist/index.cjs.map +1 -1
  45. package/dist/index.d.ts +2 -8
  46. package/dist/index.js +21 -47
  47. package/dist/modelrouter/core.cjs +2 -68
  48. package/dist/modelrouter/core.cjs.map +1 -1
  49. package/dist/modelrouter/core.js +5 -5
  50. package/dist/modelrouter/index.cjs +2 -68
  51. package/dist/modelrouter/index.cjs.map +1 -1
  52. package/dist/modelrouter/index.js +5 -5
  53. package/dist/subagents/anthropic.cjs +2 -68
  54. package/dist/subagents/anthropic.cjs.map +1 -1
  55. package/dist/subagents/anthropic.d.ts +1 -1
  56. package/dist/subagents/anthropic.js +9 -9
  57. package/dist/subagents/index.d.ts +1 -1
  58. package/dist/subagents/prompts.d.ts +1 -1
  59. package/dist/subagents/types.d.ts +1 -1
  60. package/dist/subagents/vercel.cjs +2 -68
  61. package/dist/subagents/vercel.cjs.map +1 -1
  62. package/dist/subagents/vercel.d.ts +1 -1
  63. package/dist/subagents/vercel.js +9 -9
  64. package/dist/tools/compact/core.cjs +2 -68
  65. package/dist/tools/compact/core.cjs.map +1 -1
  66. package/dist/tools/compact/core.js +5 -5
  67. package/dist/tools/compact/index.cjs +2 -68
  68. package/dist/tools/compact/index.cjs.map +1 -1
  69. package/dist/tools/compact/index.js +6 -6
  70. package/dist/tools/fastapply/anthropic.cjs +2 -62
  71. package/dist/tools/fastapply/anthropic.cjs.map +1 -1
  72. package/dist/tools/fastapply/anthropic.js +7 -7
  73. package/dist/tools/fastapply/apply.cjs +2 -62
  74. package/dist/tools/fastapply/apply.cjs.map +1 -1
  75. package/dist/tools/fastapply/apply.js +2 -2
  76. package/dist/tools/fastapply/core.cjs +2 -68
  77. package/dist/tools/fastapply/core.cjs.map +1 -1
  78. package/dist/tools/fastapply/core.js +6 -6
  79. package/dist/tools/fastapply/index.cjs +2 -62
  80. package/dist/tools/fastapply/index.cjs.map +1 -1
  81. package/dist/tools/fastapply/index.js +13 -13
  82. package/dist/tools/fastapply/openai.cjs +2 -62
  83. package/dist/tools/fastapply/openai.cjs.map +1 -1
  84. package/dist/tools/fastapply/openai.js +7 -7
  85. package/dist/tools/fastapply/vercel.cjs +2 -62
  86. package/dist/tools/fastapply/vercel.cjs.map +1 -1
  87. package/dist/tools/fastapply/vercel.js +7 -7
  88. package/dist/tools/index.cjs +2 -62
  89. package/dist/tools/index.cjs.map +1 -1
  90. package/dist/tools/index.js +13 -13
  91. package/dist/tools/utils/resilience.cjs +2 -62
  92. package/dist/tools/utils/resilience.cjs.map +1 -1
  93. package/dist/tools/utils/resilience.js +2 -2
  94. package/dist/tools/warp_grep/agent/runner.cjs +2 -62
  95. package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
  96. package/dist/tools/warp_grep/agent/runner.js +2 -2
  97. package/dist/tools/warp_grep/anthropic.cjs +2 -68
  98. package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
  99. package/dist/tools/warp_grep/anthropic.d.ts +1 -1
  100. package/dist/tools/warp_grep/anthropic.js +9 -9
  101. package/dist/tools/warp_grep/client.cjs +2 -68
  102. package/dist/tools/warp_grep/client.cjs.map +1 -1
  103. package/dist/tools/warp_grep/client.d.ts +1 -1
  104. package/dist/tools/warp_grep/client.js +8 -8
  105. package/dist/tools/warp_grep/gemini.cjs +2 -68
  106. package/dist/tools/warp_grep/gemini.cjs.map +1 -1
  107. package/dist/tools/warp_grep/gemini.d.ts +1 -1
  108. package/dist/tools/warp_grep/gemini.js +8 -8
  109. package/dist/tools/warp_grep/index.cjs +2 -68
  110. package/dist/tools/warp_grep/index.cjs.map +1 -1
  111. package/dist/tools/warp_grep/index.d.ts +1 -1
  112. package/dist/tools/warp_grep/index.js +8 -8
  113. package/dist/tools/warp_grep/openai.cjs +2 -68
  114. package/dist/tools/warp_grep/openai.cjs.map +1 -1
  115. package/dist/tools/warp_grep/openai.d.ts +1 -1
  116. package/dist/tools/warp_grep/openai.js +9 -9
  117. package/dist/tools/warp_grep/providers/code_storage_http.d.ts +1 -1
  118. package/dist/tools/warp_grep/providers/remote.d.ts +1 -1
  119. package/dist/tools/warp_grep/vercel.cjs +2 -68
  120. package/dist/tools/warp_grep/vercel.cjs.map +1 -1
  121. package/dist/tools/warp_grep/vercel.d.ts +1 -1
  122. package/dist/tools/warp_grep/vercel.js +9 -9
  123. package/dist/{types-qwD753FR.d.ts → types-DxZLPogx.d.ts} +1 -1
  124. package/dist/version.cjs +2 -62
  125. package/dist/version.cjs.map +1 -1
  126. package/dist/version.js +1 -1
  127. package/package.json +2 -62
  128. package/dist/anthropic-B6my2oBx.d.ts +0 -56
  129. package/dist/chunk-2AMEQAO2.js +0 -46
  130. package/dist/chunk-2AMEQAO2.js.map +0 -1
  131. package/dist/chunk-2HMEZZKK.js +0 -44
  132. package/dist/chunk-2HMEZZKK.js.map +0 -1
  133. package/dist/chunk-2VERUKO2.js +0 -177
  134. package/dist/chunk-2VERUKO2.js.map +0 -1
  135. package/dist/chunk-EMURAU6J.js +0 -148
  136. package/dist/chunk-EMURAU6J.js.map +0 -1
  137. package/dist/chunk-FUYX2MNM.js.map +0 -1
  138. package/dist/chunk-GJ42MYUU.js +0 -57
  139. package/dist/chunk-GJ42MYUU.js.map +0 -1
  140. package/dist/chunk-IDMKQWQG.js +0 -214
  141. package/dist/chunk-IDMKQWQG.js.map +0 -1
  142. package/dist/chunk-KQKLQHJF.js +0 -96
  143. package/dist/chunk-KQKLQHJF.js.map +0 -1
  144. package/dist/chunk-O5264GI4.js +0 -58
  145. package/dist/chunk-O5264GI4.js.map +0 -1
  146. package/dist/chunk-PIIXU2H3.js +0 -389
  147. package/dist/chunk-PIIXU2H3.js.map +0 -1
  148. package/dist/chunk-T6TXYTKH.js +0 -83
  149. package/dist/chunk-T6TXYTKH.js.map +0 -1
  150. package/dist/chunk-TLXVGE4R.js +0 -42
  151. package/dist/chunk-TLXVGE4R.js.map +0 -1
  152. package/dist/chunk-VBZ7BG47.js +0 -97
  153. package/dist/chunk-VBZ7BG47.js.map +0 -1
  154. package/dist/chunk-WLMPQFER.js +0 -128
  155. package/dist/chunk-WLMPQFER.js.map +0 -1
  156. package/dist/chunk-XH6KJJDI.js +0 -80
  157. package/dist/chunk-XH6KJJDI.js.map +0 -1
  158. package/dist/chunk-YD6TNDR4.js +0 -622
  159. package/dist/chunk-YD6TNDR4.js.map +0 -1
  160. package/dist/chunk-YHZJYCOU.js +0 -680
  161. package/dist/chunk-YHZJYCOU.js.map +0 -1
  162. package/dist/chunk-YQMPVJ2L.js +0 -32
  163. package/dist/chunk-YQMPVJ2L.js.map +0 -1
  164. package/dist/chunk-YTYCHRQ2.js +0 -106
  165. package/dist/chunk-YTYCHRQ2.js.map +0 -1
  166. package/dist/chunk-ZU5YYGBJ.js.map +0 -1
  167. package/dist/client-DCeydotn.d.ts +0 -1015
  168. package/dist/openai-BQMeDFef.d.ts +0 -81
  169. package/dist/otel-CG0uqXjp.d.ts +0 -42
  170. package/dist/tools/browser/anthropic.cjs +0 -645
  171. package/dist/tools/browser/anthropic.cjs.map +0 -1
  172. package/dist/tools/browser/anthropic.d.ts +0 -4
  173. package/dist/tools/browser/anthropic.js +0 -22
  174. package/dist/tools/browser/anthropic.js.map +0 -1
  175. package/dist/tools/browser/core.cjs +0 -1821
  176. package/dist/tools/browser/core.cjs.map +0 -1
  177. package/dist/tools/browser/core.d.ts +0 -245
  178. package/dist/tools/browser/core.js +0 -32
  179. package/dist/tools/browser/core.js.map +0 -1
  180. package/dist/tools/browser/errors.cjs +0 -208
  181. package/dist/tools/browser/errors.cjs.map +0 -1
  182. package/dist/tools/browser/errors.d.ts +0 -158
  183. package/dist/tools/browser/errors.js +0 -22
  184. package/dist/tools/browser/errors.js.map +0 -1
  185. package/dist/tools/browser/index.cjs +0 -2159
  186. package/dist/tools/browser/index.cjs.map +0 -1
  187. package/dist/tools/browser/index.d.ts +0 -134
  188. package/dist/tools/browser/index.js +0 -163
  189. package/dist/tools/browser/index.js.map +0 -1
  190. package/dist/tools/browser/live.cjs +0 -134
  191. package/dist/tools/browser/live.cjs.map +0 -1
  192. package/dist/tools/browser/live.d.ts +0 -75
  193. package/dist/tools/browser/live.js +0 -16
  194. package/dist/tools/browser/live.js.map +0 -1
  195. package/dist/tools/browser/openai.cjs +0 -661
  196. package/dist/tools/browser/openai.cjs.map +0 -1
  197. package/dist/tools/browser/openai.d.ts +0 -4
  198. package/dist/tools/browser/openai.js +0 -28
  199. package/dist/tools/browser/openai.js.map +0 -1
  200. package/dist/tools/browser/profiles/core.cjs +0 -932
  201. package/dist/tools/browser/profiles/core.cjs.map +0 -1
  202. package/dist/tools/browser/profiles/core.d.ts +0 -187
  203. package/dist/tools/browser/profiles/core.js +0 -30
  204. package/dist/tools/browser/profiles/core.js.map +0 -1
  205. package/dist/tools/browser/profiles/index.cjs +0 -932
  206. package/dist/tools/browser/profiles/index.cjs.map +0 -1
  207. package/dist/tools/browser/profiles/index.d.ts +0 -4
  208. package/dist/tools/browser/profiles/index.js +0 -30
  209. package/dist/tools/browser/profiles/index.js.map +0 -1
  210. package/dist/tools/browser/profiles/types.cjs +0 -74
  211. package/dist/tools/browser/profiles/types.cjs.map +0 -1
  212. package/dist/tools/browser/profiles/types.d.ts +0 -195
  213. package/dist/tools/browser/profiles/types.js +0 -16
  214. package/dist/tools/browser/profiles/types.js.map +0 -1
  215. package/dist/tools/browser/prompts.cjs +0 -69
  216. package/dist/tools/browser/prompts.cjs.map +0 -1
  217. package/dist/tools/browser/prompts.d.ts +0 -7
  218. package/dist/tools/browser/prompts.js +0 -10
  219. package/dist/tools/browser/prompts.js.map +0 -1
  220. package/dist/tools/browser/types.cjs +0 -19
  221. package/dist/tools/browser/types.cjs.map +0 -1
  222. package/dist/tools/browser/types.d.ts +0 -338
  223. package/dist/tools/browser/types.js +0 -1
  224. package/dist/tools/browser/types.js.map +0 -1
  225. package/dist/tools/browser/vercel.cjs +0 -622
  226. package/dist/tools/browser/vercel.cjs.map +0 -1
  227. package/dist/tools/browser/vercel.d.ts +0 -4
  228. package/dist/tools/browser/vercel.js +0 -22
  229. package/dist/tools/browser/vercel.js.map +0 -1
  230. package/dist/tools/codebase_search/anthropic.cjs +0 -696
  231. package/dist/tools/codebase_search/anthropic.cjs.map +0 -1
  232. package/dist/tools/codebase_search/anthropic.d.ts +0 -40
  233. package/dist/tools/codebase_search/anthropic.js +0 -16
  234. package/dist/tools/codebase_search/anthropic.js.map +0 -1
  235. package/dist/tools/codebase_search/core.cjs +0 -638
  236. package/dist/tools/codebase_search/core.cjs.map +0 -1
  237. package/dist/tools/codebase_search/core.d.ts +0 -51
  238. package/dist/tools/codebase_search/core.js +0 -16
  239. package/dist/tools/codebase_search/core.js.map +0 -1
  240. package/dist/tools/codebase_search/index.cjs +0 -821
  241. package/dist/tools/codebase_search/index.cjs.map +0 -1
  242. package/dist/tools/codebase_search/index.d.ts +0 -12
  243. package/dist/tools/codebase_search/index.js +0 -32
  244. package/dist/tools/codebase_search/index.js.map +0 -1
  245. package/dist/tools/codebase_search/openai.cjs +0 -745
  246. package/dist/tools/codebase_search/openai.cjs.map +0 -1
  247. package/dist/tools/codebase_search/openai.d.ts +0 -87
  248. package/dist/tools/codebase_search/openai.js +0 -26
  249. package/dist/tools/codebase_search/openai.js.map +0 -1
  250. package/dist/tools/codebase_search/prompts.cjs +0 -57
  251. package/dist/tools/codebase_search/prompts.cjs.map +0 -1
  252. package/dist/tools/codebase_search/prompts.d.ts +0 -7
  253. package/dist/tools/codebase_search/prompts.js +0 -10
  254. package/dist/tools/codebase_search/prompts.js.map +0 -1
  255. package/dist/tools/codebase_search/types.cjs +0 -19
  256. package/dist/tools/codebase_search/types.cjs.map +0 -1
  257. package/dist/tools/codebase_search/types.d.ts +0 -50
  258. package/dist/tools/codebase_search/types.js +0 -1
  259. package/dist/tools/codebase_search/types.js.map +0 -1
  260. package/dist/tools/codebase_search/vercel.cjs +0 -658
  261. package/dist/tools/codebase_search/vercel.cjs.map +0 -1
  262. package/dist/tools/codebase_search/vercel.d.ts +0 -65
  263. package/dist/tools/codebase_search/vercel.js +0 -20
  264. package/dist/tools/codebase_search/vercel.js.map +0 -1
  265. package/dist/tracing/core.cjs +0 -410
  266. package/dist/tracing/core.cjs.map +0 -1
  267. package/dist/tracing/core.d.ts +0 -58
  268. package/dist/tracing/core.js +0 -12
  269. package/dist/tracing/core.js.map +0 -1
  270. package/dist/tracing/index.cjs +0 -422
  271. package/dist/tracing/index.cjs.map +0 -1
  272. package/dist/tracing/index.d.ts +0 -5
  273. package/dist/tracing/index.js +0 -17
  274. package/dist/tracing/index.js.map +0 -1
  275. package/dist/tracing/interaction.cjs +0 -273
  276. package/dist/tracing/interaction.cjs.map +0 -1
  277. package/dist/tracing/interaction.d.ts +0 -41
  278. package/dist/tracing/interaction.js +0 -11
  279. package/dist/tracing/interaction.js.map +0 -1
  280. package/dist/tracing/otel.cjs +0 -56
  281. package/dist/tracing/otel.cjs.map +0 -1
  282. package/dist/tracing/otel.d.ts +0 -2
  283. package/dist/tracing/otel.js +0 -10
  284. package/dist/tracing/otel.js.map +0 -1
  285. package/dist/tracing/types.cjs +0 -19
  286. package/dist/tracing/types.cjs.map +0 -1
  287. package/dist/tracing/types.d.ts +0 -124
  288. package/dist/tracing/types.js +0 -1
  289. package/dist/tracing/types.js.map +0 -1
  290. package/dist/vercel-CVF27qFK.d.ts +0 -74
  291. /package/dist/{chunk-ZQNTXHBQ.js.map → chunk-3CCWSLQW.js.map} +0 -0
  292. /package/dist/{chunk-FESO6TDQ.js.map → chunk-7I2A7GGJ.js.map} +0 -0
  293. /package/dist/{chunk-4JUIEYAH.js.map → chunk-AKSXZBPT.js.map} +0 -0
  294. /package/dist/{chunk-QKNGVBE2.js.map → chunk-L6YOMTFU.js.map} +0 -0
  295. /package/dist/{chunk-YQ2G5YLI.js.map → chunk-MLROWLS6.js.map} +0 -0
  296. /package/dist/{chunk-4DNEBVGV.js.map → chunk-MPL6BDR6.js.map} +0 -0
  297. /package/dist/{chunk-3XS5P5XH.js.map → chunk-PD3EDFQD.js.map} +0 -0
  298. /package/dist/{chunk-CAFREMIT.js.map → chunk-PJNL35DC.js.map} +0 -0
  299. /package/dist/{chunk-PEFXG5M6.js.map → chunk-Q65LL6UM.js.map} +0 -0
  300. /package/dist/{chunk-YUH3MTP3.js.map → chunk-QTBFL4DG.js.map} +0 -0
  301. /package/dist/{chunk-XTFRHVCW.js.map → chunk-SNYHVDE4.js.map} +0 -0
  302. /package/dist/{chunk-ZGERT23F.js.map → chunk-TIMDDHYB.js.map} +0 -0
  303. /package/dist/{chunk-PV6EF6NG.js.map → chunk-UHIANNKC.js.map} +0 -0
  304. /package/dist/{chunk-XK3PQZW6.js.map → chunk-WTENYKJP.js.map} +0 -0
  305. /package/dist/{chunk-6XFL2NER.js.map → chunk-XTLPA7ZP.js.map} +0 -0
  306. /package/dist/{chunk-D2RFP6R2.js.map → chunk-Z57GJLCG.js.map} +0 -0
  307. /package/dist/{chunk-SKN2L5CE.js.map → chunk-ZE64EWUV.js.map} +0 -0
package/dist/client.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.198",
39
+ version: "0.2.200",
40
40
  description: "TypeScript SDK and CLI for Morph Fast Apply integration",
41
41
  type: "module",
42
42
  main: "./dist/index.cjs",
@@ -93,16 +93,6 @@ var init_package = __esm({
93
93
  import: "./dist/tools/warp_grep/harness.js",
94
94
  require: "./dist/tools/warp_grep/harness.cjs"
95
95
  },
96
- "./tracing": {
97
- types: "./dist/tracing/index.d.ts",
98
- import: "./dist/tracing/index.js",
99
- require: "./dist/tracing/index.cjs"
100
- },
101
- "./tracing/otel": {
102
- types: "./dist/tracing/otel.d.ts",
103
- import: "./dist/tracing/otel.js",
104
- require: "./dist/tracing/otel.cjs"
105
- },
106
96
  "./tools/fastapply": {
107
97
  types: "./dist/tools/fastapply/index.d.ts",
108
98
  import: "./dist/tools/fastapply/index.js",
@@ -123,51 +113,6 @@ var init_package = __esm({
123
113
  import: "./dist/tools/fastapply/vercel.js",
124
114
  require: "./dist/tools/fastapply/vercel.cjs"
125
115
  },
126
- "./tools/codebase-search": {
127
- types: "./dist/tools/codebase_search/index.d.ts",
128
- import: "./dist/tools/codebase_search/index.js",
129
- require: "./dist/tools/codebase_search/index.cjs"
130
- },
131
- "./tools/codebase-search/anthropic": {
132
- types: "./dist/tools/codebase_search/anthropic.d.ts",
133
- import: "./dist/tools/codebase_search/anthropic.js",
134
- require: "./dist/tools/codebase_search/anthropic.cjs"
135
- },
136
- "./tools/codebase-search/openai": {
137
- types: "./dist/tools/codebase_search/openai.d.ts",
138
- import: "./dist/tools/codebase_search/openai.js",
139
- require: "./dist/tools/codebase_search/openai.cjs"
140
- },
141
- "./tools/codebase-search/vercel": {
142
- types: "./dist/tools/codebase_search/vercel.d.ts",
143
- import: "./dist/tools/codebase_search/vercel.js",
144
- require: "./dist/tools/codebase_search/vercel.cjs"
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
116
  "./modelrouter": {
172
117
  types: "./dist/modelrouter/index.d.ts",
173
118
  import: "./dist/modelrouter/index.js",
@@ -208,7 +153,7 @@ var init_package = __esm({
208
153
  "!dist/**/*.test.*"
209
154
  ],
210
155
  scripts: {
211
- 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/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",
156
+ build: "tsup version.ts index.ts edge.ts client.ts core/index.ts core/client.ts core/resource.ts core/error.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve && tsup ai-sdk/index.ts --format esm,cjs --sourcemap --dts --no-clean --out-dir dist/ai-sdk",
212
157
  prepare: "npm run build",
213
158
  typecheck: "tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json",
214
159
  lint: "eslint .",
@@ -218,7 +163,6 @@ var init_package = __esm({
218
163
  "test:openai": "vitest run openai",
219
164
  "test:vercel": "vitest run vercel",
220
165
  "test:git": "vitest run git",
221
- "test:browser": "vitest run browser",
222
166
  "test:agent": "npx tsx tests/fullAgentTest.ts",
223
167
  "test:integration": "npx tsx tests/fullIntegrationTest.ts",
224
168
  "test:e2e": "vitest run --config vitest.e2e.config.ts",
@@ -238,10 +182,6 @@ var init_package = __esm({
238
182
  },
239
183
  license: "MIT",
240
184
  dependencies: {
241
- "@opentelemetry/api": "^1.9.0",
242
- "@opentelemetry/exporter-trace-otlp-http": "^0.203.0",
243
- "@opentelemetry/sdk-trace-base": "^2.7.1",
244
- "@traceloop/node-server-sdk": "^0.27.0",
245
185
  "@vscode/ripgrep": "^1.17.0",
246
186
  ai: ">=5.0.0",
247
187
  diff: "^7.0.0",
@@ -1464,7 +1404,6 @@ async function toMorphError(response) {
1464
1404
  // core/client.ts
1465
1405
  var DEFAULT_BASE_URL = "https://api.morphllm.com";
1466
1406
  var DEFAULT_REPOS_URL = "https://repos.morphllm.com";
1467
- var DEFAULT_BROWSER_URL = "https://browser.morphllm.com";
1468
1407
  var DEFAULT_TIMEOUT = 6e4;
1469
1408
  var env = (name) => typeof process !== "undefined" ? process.env?.[name] : void 0;
1470
1409
  var stripTrailingSlash = (url) => url.replace(/\/+$/, "");
@@ -1473,7 +1412,6 @@ var MorphAPIClient = class {
1473
1412
  apiKey;
1474
1413
  baseURL;
1475
1414
  reposURL;
1476
- browserURL;
1477
1415
  /** Explicit default timeout (ms), if set. The request default is applied lazily so
1478
1416
  * resources can read an undefined value and supply their own fallback. */
1479
1417
  timeout;
@@ -1483,9 +1421,6 @@ var MorphAPIClient = class {
1483
1421
  this.apiKey = options.apiKey;
1484
1422
  this.baseURL = stripTrailingSlash(options.baseURL ?? DEFAULT_BASE_URL);
1485
1423
  this.reposURL = stripTrailingSlash(options.reposURL ?? env("MORPH_SEARCH_URL") ?? DEFAULT_REPOS_URL);
1486
- this.browserURL = stripTrailingSlash(
1487
- options.browserURL ?? (env("MORPH_ENVIRONMENT") === "DEV" ? "http://localhost:8000" : DEFAULT_BROWSER_URL)
1488
- );
1489
1424
  this.timeout = options.timeout;
1490
1425
  this.retryConfig = options.retryConfig;
1491
1426
  this.debug = options.debug ?? false;
@@ -1544,7 +1479,6 @@ var MorphAPIClient = class {
1544
1479
  timeout,
1545
1480
  `Morph request to ${url} timed out after ${timeout}ms`
1546
1481
  );
1547
- if (opts.raw) return response;
1548
1482
  if (!response.ok) throw await toMorphError(response);
1549
1483
  if (opts.stream) return response;
1550
1484
  if (response.status === 204) return void 0;
@@ -1662,1383 +1596,50 @@ async function executeEditFile(input, config = {}) {
1662
1596
  };
1663
1597
  }
1664
1598
  logger.debug("FastApply", "security_check", { resolved: fullPath, relative: relativePath });
1665
- try {
1666
- const { readFile, writeFile } = await import("fs/promises");
1667
- const { callMorphAPI: callMorphAPI2, generateUdiff: generateUdiff2, countChanges: countChanges2 } = await Promise.resolve().then(() => (init_apply(), apply_exports));
1668
- let originalCode = "";
1669
- let fileExists = true;
1670
- try {
1671
- originalCode = await readFile(fullPath, "utf-8");
1672
- logger.debug("FastApply", "file_read", { path: fullPath, exists: true, size_bytes: originalCode.length });
1673
- } catch (error) {
1674
- if (error.code !== "ENOENT") {
1675
- throw error;
1676
- }
1677
- fileExists = false;
1678
- logger.debug("FastApply", "file_read", { path: fullPath, exists: false });
1679
- }
1680
- const instruction = input.instruction ?? input.instructions ?? "";
1681
- logger.debug("FastApply", "api_call", { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });
1682
- const { content: mergedCode, completionId } = await callMorphAPI2(originalCode, input.code_edit, instruction, input.target_filepath, config);
1683
- logger.debug("FastApply", "api_response", { completion_id: completionId, merged_len: mergedCode.length });
1684
- const udiff = config.generateUdiff !== false ? generateUdiff2(originalCode, mergedCode, input.target_filepath) : void 0;
1685
- if (config.autoWrite !== false) {
1686
- await writeFile(fullPath, mergedCode, "utf-8");
1687
- logger.debug("FastApply", "file_write", { path: fullPath, size_bytes: mergedCode.length });
1688
- }
1689
- const changes = countChanges2(originalCode, mergedCode);
1690
- logger.debug("FastApply", "changes", { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });
1691
- return {
1692
- success: true,
1693
- filepath: input.target_filepath,
1694
- udiff,
1695
- changes,
1696
- completionId
1697
- };
1698
- } catch (error) {
1699
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1700
- const structuredError = error instanceof FastApplyContextLengthError || error instanceof FastApplyAnchorIntegrityError ? error : void 0;
1701
- logger.error("FastApply", "execute_error", { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : void 0 });
1702
- return {
1703
- success: false,
1704
- filepath: input.target_filepath,
1705
- changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
1706
- error: errorMessage,
1707
- errorCode: structuredError?.code,
1708
- completionId: structuredError?.completionId
1709
- };
1710
- }
1711
- }
1712
-
1713
- // tools/codebase_search/core.ts
1714
- init_logger();
1715
- var DEFAULT_TIMEOUT3 = 3e4;
1716
- var emptyStats = { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 };
1717
- async function runSearch(client, input, repoId, timeout, baseURL) {
1718
- const startTime = Date.now();
1719
- logger.debug("CodebaseSearch", "request", { query: input.query.slice(0, 100), repo_id: repoId });
1720
- try {
1721
- const data = await client.post(
1722
- "/v1/codebase_search",
1723
- {
1724
- baseURL: baseURL ?? client.reposURL,
1725
- timeout,
1726
- body: {
1727
- query: input.query,
1728
- repoId,
1729
- targetDirectories: input.target_directories || [],
1730
- limit: input.limit || 10,
1731
- candidateLimit: 50
1732
- }
1733
- }
1734
- );
1735
- const elapsed = Date.now() - startTime;
1736
- logger.debug("CodebaseSearch", "response", { results_count: data.results?.length || 0, latency_ms: elapsed });
1737
- return {
1738
- success: true,
1739
- results: data.results || [],
1740
- stats: data.stats || { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: elapsed }
1741
- };
1742
- } catch (error) {
1743
- const message = error instanceof MorphError && error.statusCode ? `Search failed (${error.statusCode}): ${error.message}` : error instanceof Error ? error.message : "Unknown error";
1744
- logger.error("CodebaseSearch", "error", { error: message, latency_ms: Date.now() - startTime });
1745
- return { success: false, results: [], stats: { ...emptyStats }, error: message };
1746
- }
1747
- }
1748
- var CodebaseSearchClient = class extends APIResource {
1749
- timeout;
1750
- constructor(clientOrConfig = {}) {
1751
- super(
1752
- clientOrConfig instanceof MorphAPIClient ? clientOrConfig : new MorphAPIClient({
1753
- apiKey: clientOrConfig.apiKey,
1754
- timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT3,
1755
- retryConfig: clientOrConfig.retryConfig,
1756
- debug: clientOrConfig.debug
1757
- })
1758
- );
1759
- this.timeout = (clientOrConfig instanceof MorphAPIClient ? void 0 : clientOrConfig.timeout) ?? DEFAULT_TIMEOUT3;
1760
- }
1761
- /**
1762
- * Execute a semantic code search
1763
- *
1764
- * @param input - Search parameters including query, repoId, and target directories
1765
- * @param overrides - Optional config overrides for this operation
1766
- * @returns Search results with ranked code matches
1767
- */
1768
- async search(input, overrides) {
1769
- return runSearch(
1770
- this._client,
1771
- { query: input.query, target_directories: input.target_directories, explanation: input.explanation, limit: input.limit },
1772
- input.repoId,
1773
- overrides?.timeout ?? this.timeout,
1774
- overrides?.searchUrl
1775
- );
1776
- }
1777
- };
1778
- async function executeCodebaseSearch(input, config) {
1779
- const apiKey = config.apiKey || process.env.MORPH_API_KEY;
1780
- if (!apiKey) {
1781
- throw new Error("MORPH_API_KEY not found. Set environment variable or pass in config");
1782
- }
1783
- const client = new MorphAPIClient({
1784
- apiKey,
1785
- reposURL: config.searchUrl,
1786
- timeout: config.timeout ?? DEFAULT_TIMEOUT3,
1787
- retryConfig: config.retryConfig,
1788
- debug: config.debug
1789
- });
1790
- return runSearch(client, input, config.repoId, config.timeout ?? DEFAULT_TIMEOUT3, config.searchUrl);
1791
- }
1792
-
1793
- // tools/browser/core.ts
1794
- init_logger();
1795
-
1796
- // tools/browser/live.ts
1797
- var LIVE_PRESETS = {
1798
- /** Read-only monitoring (no interaction) */
1799
- readonly: { interactive: false },
1800
- /** Interactive control (human-in-the-loop) */
1801
- interactive: { interactive: true },
1802
- /** Watch-only without controls */
1803
- monitoring: { interactive: false, showControls: false }
1804
- };
1805
- function buildLiveUrl(debugUrl, options = {}) {
1806
- if (!debugUrl) {
1807
- throw new Error(
1808
- "debugUrl is required. Ensure your backend returns debugUrl in the task response. Contact support@morphllm.com if you need help."
1809
- );
1810
- }
1811
- const normalized = normalizeLiveUrl(debugUrl);
1812
- const url = new URL(normalized);
1813
- if (options.interactive !== void 0) {
1814
- url.searchParams.set("interactive", String(options.interactive));
1815
- }
1816
- if (options.theme) {
1817
- url.searchParams.set("theme", options.theme);
1818
- }
1819
- if (options.showControls !== void 0) {
1820
- url.searchParams.set("showControls", String(options.showControls));
1821
- }
1822
- if (options.pageId) {
1823
- url.searchParams.set("pageId", options.pageId);
1824
- }
1825
- if (options.pageIndex) {
1826
- url.searchParams.set("pageIndex", options.pageIndex);
1827
- }
1828
- return url.toString();
1829
- }
1830
- function cdpToHttps(wsUrl) {
1831
- return wsUrl.replace(/^wss:\/\//, "https://").replace(/^ws:\/\//, "http://");
1832
- }
1833
- function normalizeLiveUrl(debugUrl) {
1834
- const trimmed = debugUrl.trim();
1835
- if (!trimmed) return trimmed;
1836
- if (trimmed.startsWith("wss://") || trimmed.startsWith("ws://")) {
1837
- return `https://live.browser-use.com?wss=${encodeURIComponent(cdpToHttps(trimmed))}`;
1838
- }
1839
- let url;
1840
- try {
1841
- url = new URL(trimmed);
1842
- } catch {
1843
- return trimmed;
1844
- }
1845
- const wssParam = url.searchParams.get("wss");
1846
- if (wssParam && (wssParam.startsWith("wss://") || wssParam.startsWith("ws://"))) {
1847
- url.searchParams.set("wss", cdpToHttps(wssParam));
1848
- }
1849
- return url.toString();
1850
- }
1851
- function buildLiveIframe(debugUrl, options = {}) {
1852
- const {
1853
- width = "100%",
1854
- height = "600px",
1855
- style = "",
1856
- className = "",
1857
- ...sessionOptions
1858
- } = options;
1859
- const src = buildLiveUrl(debugUrl, sessionOptions);
1860
- const widthStr = typeof width === "number" ? `${width}px` : width;
1861
- const heightStr = typeof height === "number" ? `${height}px` : height;
1862
- const baseStyle = `width: ${widthStr}; height: ${heightStr}; border: none;`;
1863
- const fullStyle = style ? `${baseStyle} ${style}` : baseStyle;
1864
- const attributes = [
1865
- `src="${src}"`,
1866
- `style="${fullStyle}"`
1867
- ];
1868
- if (className) {
1869
- attributes.push(`class="${className}"`);
1870
- }
1871
- return `<iframe ${attributes.join(" ")}></iframe>`;
1872
- }
1873
- function buildEmbedCode(debugUrl, options = {}) {
1874
- const iframe = buildLiveIframe(debugUrl, options);
1875
- return `<!-- Embed Morph Live Session -->
1876
- ${iframe}`;
1877
- }
1878
- function resolvePreset(optionsOrPreset) {
1879
- if (!optionsOrPreset) {
1880
- return {};
1881
- }
1882
- if (typeof optionsOrPreset === "string") {
1883
- const preset = LIVE_PRESETS[optionsOrPreset];
1884
- if (!preset) {
1885
- throw new Error(
1886
- `Unknown preset: ${optionsOrPreset}. Available presets: ${Object.keys(LIVE_PRESETS).join(", ")}`
1887
- );
1888
- }
1889
- return preset;
1890
- }
1891
- return optionsOrPreset;
1892
- }
1893
-
1894
- // tools/browser/errors.ts
1895
- var MorphError2 = class extends Error {
1896
- /** Error code for programmatic handling */
1897
- code;
1898
- /** Original cause of the error, if any */
1899
- cause;
1900
- constructor(message, code, cause) {
1901
- super(message);
1902
- this.name = "MorphError";
1903
- this.code = code;
1904
- this.cause = cause;
1905
- if (Error.captureStackTrace) {
1906
- Error.captureStackTrace(this, this.constructor);
1907
- }
1908
- }
1909
- /**
1910
- * Returns a JSON representation of the error for logging.
1911
- */
1912
- toJSON() {
1913
- return {
1914
- name: this.name,
1915
- message: this.message,
1916
- code: this.code,
1917
- cause: this.cause?.message
1918
- };
1919
- }
1920
- };
1921
- var MorphValidationError = class extends MorphError2 {
1922
- /** The field that failed validation */
1923
- field;
1924
- constructor(message, field) {
1925
- super(message, "validation_error");
1926
- this.name = "MorphValidationError";
1927
- this.field = field;
1928
- }
1929
- toJSON() {
1930
- return {
1931
- ...super.toJSON(),
1932
- field: this.field
1933
- };
1934
- }
1935
- };
1936
- var MorphAPIError = class extends MorphError2 {
1937
- /** HTTP status code */
1938
- statusCode;
1939
- /** Request ID for debugging (if available) */
1940
- requestId;
1941
- /** Raw response body */
1942
- rawResponse;
1943
- constructor(message, code, statusCode, options) {
1944
- super(message, code, options?.cause);
1945
- this.name = "MorphAPIError";
1946
- this.statusCode = statusCode;
1947
- this.requestId = options?.requestId;
1948
- this.rawResponse = options?.rawResponse;
1949
- }
1950
- toJSON() {
1951
- return {
1952
- ...super.toJSON(),
1953
- statusCode: this.statusCode,
1954
- requestId: this.requestId
1955
- };
1956
- }
1957
- };
1958
- var MorphAuthenticationError = class extends MorphAPIError {
1959
- constructor(message = "Authentication required. Please provide a valid API key.") {
1960
- super(message, "authentication_required", 401);
1961
- this.name = "MorphAuthenticationError";
1962
- }
1963
- };
1964
- var MorphRateLimitError = class extends MorphAPIError {
1965
- /** When the rate limit resets (Unix timestamp) */
1966
- resetAt;
1967
- /** Number of seconds until reset */
1968
- retryAfter;
1969
- constructor(message = "Rate limit exceeded. Please retry later.", options) {
1970
- super(message, "rate_limit_exceeded", 429, { requestId: options?.requestId });
1971
- this.name = "MorphRateLimitError";
1972
- this.resetAt = options?.resetAt;
1973
- this.retryAfter = options?.retryAfter;
1974
- }
1975
- toJSON() {
1976
- return {
1977
- ...super.toJSON(),
1978
- resetAt: this.resetAt,
1979
- retryAfter: this.retryAfter
1980
- };
1981
- }
1982
- };
1983
- var MorphNotFoundError = class extends MorphAPIError {
1984
- /** The type of resource that was not found */
1985
- resourceType;
1986
- /** The ID of the resource that was not found */
1987
- resourceId;
1988
- constructor(resourceType, resourceId) {
1989
- const message = resourceId ? `${resourceType} '${resourceId}' not found` : `${resourceType} not found`;
1990
- super(message, "resource_not_found", 404);
1991
- this.name = "MorphNotFoundError";
1992
- this.resourceType = resourceType;
1993
- this.resourceId = resourceId;
1994
- }
1995
- toJSON() {
1996
- return {
1997
- ...super.toJSON(),
1998
- resourceType: this.resourceType,
1999
- resourceId: this.resourceId
2000
- };
2001
- }
2002
- };
2003
- var MorphProfileLimitError = class extends MorphAPIError {
2004
- /** Current number of profiles */
2005
- currentCount;
2006
- /** Maximum allowed profiles for the plan */
2007
- maxAllowed;
2008
- constructor(message = "Profile limit exceeded for your plan.", options) {
2009
- super(message, "profile_limit_exceeded", 403, { requestId: options?.requestId });
2010
- this.name = "MorphProfileLimitError";
2011
- this.currentCount = options?.currentCount;
2012
- this.maxAllowed = options?.maxAllowed;
2013
- }
2014
- toJSON() {
2015
- return {
2016
- ...super.toJSON(),
2017
- currentCount: this.currentCount,
2018
- maxAllowed: this.maxAllowed
2019
- };
2020
- }
2021
- };
2022
- function parseAPIError(statusCode, responseText, requestId) {
2023
- let errorData = {};
2024
- try {
2025
- errorData = JSON.parse(responseText);
2026
- } catch {
2027
- }
2028
- const message = errorData.detail || errorData.message || responseText || "Unknown error";
2029
- const code = errorData.code;
2030
- switch (statusCode) {
2031
- case 401:
2032
- return new MorphAuthenticationError(message);
2033
- case 403:
2034
- if (code === "profile_limit_exceeded" || message.toLowerCase().includes("limit")) {
2035
- return new MorphProfileLimitError(message, { requestId });
2036
- }
2037
- return new MorphAPIError(message, "insufficient_permissions", statusCode, { requestId, rawResponse: responseText });
2038
- case 404:
2039
- if (message.toLowerCase().includes("profile")) {
2040
- return new MorphNotFoundError("Profile", void 0);
2041
- }
2042
- if (message.toLowerCase().includes("session")) {
2043
- return new MorphNotFoundError("Session", void 0);
2044
- }
2045
- return new MorphAPIError(message, "resource_not_found", statusCode, { requestId, rawResponse: responseText });
2046
- case 429:
2047
- return new MorphRateLimitError(message, { requestId });
2048
- case 422:
2049
- return new MorphAPIError(message, "validation_error", statusCode, { requestId, rawResponse: responseText });
2050
- case 500:
2051
- case 502:
2052
- case 503:
2053
- case 504:
2054
- return new MorphAPIError(message, "service_unavailable", statusCode, { requestId, rawResponse: responseText });
2055
- default:
2056
- return new MorphAPIError(message, "network_error", statusCode, { requestId, rawResponse: responseText });
2057
- }
2058
- }
2059
-
2060
- // tools/browser/profiles/types.ts
2061
- function transformProfile(api) {
2062
- return {
2063
- id: api.id,
2064
- name: api.name,
2065
- repoId: api.repo_id,
2066
- cookieDomains: api.cookie_domains,
2067
- lastUsedAt: api.last_used_at,
2068
- createdAt: api.created_at,
2069
- updatedAt: api.updated_at
2070
- };
2071
- }
2072
- function transformCreateInput(input) {
2073
- return {
2074
- name: input.name,
2075
- repo_id: input.repoId
2076
- };
2077
- }
2078
- function transformSession(api) {
2079
- return {
2080
- sessionId: api.session_id,
2081
- debugUrl: api.debug_url || ""
2082
- };
2083
- }
2084
- function transformSaveInput(input) {
2085
- return {
2086
- session_id: input.sessionId,
2087
- profile_id: input.profileId
2088
- };
2089
- }
2090
- function transformStateResponse(api) {
2091
- return {
2092
- profileId: api.profile_id,
2093
- stateUrl: api.state_url,
2094
- expiresIn: api.expires_in
2095
- };
2096
- }
2097
-
2098
- // tools/browser/profiles/core.ts
2099
- var DEFAULT_API_URL2 = process.env.MORPH_ENVIRONMENT === "DEV" ? "http://localhost:8000" : "https://browser.morphllm.com";
2100
- var ProfilesClient = class {
2101
- config;
2102
- constructor(config) {
2103
- this.config = config;
2104
- }
2105
- /**
2106
- * Create a new browser profile and immediately start a live session.
2107
- *
2108
- * @param input - Profile creation parameters
2109
- * @returns Profile setup handle with live URL + save()
2110
- * @throws {MorphValidationError} If input validation fails
2111
- * @throws {MorphProfileLimitError} If profile limit is exceeded
2112
- * @throws {MorphAuthenticationError} If API key is missing or invalid
2113
- *
2114
- * @example
2115
- * ```typescript
2116
- * const setup = await morph.browser.profiles.createProfile({
2117
- * name: 'LinkedIn Production',
2118
- * repoId: 'owner/repo'
2119
- * });
2120
- * console.log(setup.session.debugUrl);
2121
- * await setup.save();
2122
- * ```
2123
- */
2124
- async createProfile(input) {
2125
- return createProfile(input, this.config);
2126
- }
2127
- /**
2128
- * List all profiles for the authenticated user.
2129
- *
2130
- * @param repoId - Optional repository ID to filter by
2131
- * @returns Array of profiles
2132
- *
2133
- * @example
2134
- * ```typescript
2135
- * // List all profiles
2136
- * const allProfiles = await morph.browser.profiles.listProfiles();
2137
- *
2138
- * // List profiles for a specific repo
2139
- * const repoProfiles = await morph.browser.profiles.listProfiles('owner/repo');
2140
- * ```
2141
- */
2142
- async listProfiles(repoId) {
2143
- return listProfiles(this.config, repoId);
2144
- }
2145
- /**
2146
- * Get a profile by ID with convenience methods.
2147
- *
2148
- * @param id - Profile ID
2149
- * @returns Profile with attached methods
2150
- * @throws {MorphNotFoundError} If profile is not found
2151
- *
2152
- * @example
2153
- * ```typescript
2154
- * const profile = await morph.browser.profiles.getProfile('profile-id');
2155
- * const state = await profile.getState();
2156
- * await profile.delete();
2157
- * ```
2158
- */
2159
- async getProfile(id) {
2160
- return getProfile(id, this.config);
2161
- }
2162
- /**
2163
- * Update a profile by opening a live session (no rename).
2164
- *
2165
- * @param id - Profile ID
2166
- * @returns Profile setup handle with live URL + save()
2167
- */
2168
- async updateProfile(id) {
2169
- return updateProfile(id, this.config);
2170
- }
2171
- /**
2172
- * Delete a profile.
2173
- *
2174
- * @param id - Profile ID
2175
- * @throws {MorphNotFoundError} If profile is not found
2176
- */
2177
- async deleteProfile(id) {
2178
- return deleteProfile(id, this.config);
2179
- }
2180
- /**
2181
- * Start a browser session for profile setup.
2182
- *
2183
- * Returns a live URL where the user can sign into accounts.
2184
- * After signing in, call `saveSession` to persist the state.
2185
- *
2186
- * @param input - Optional session parameters
2187
- * @returns Session with debug URL
2188
- *
2189
- * @example
2190
- * ```typescript
2191
- * const session = await morph.browser.profiles.startSession();
2192
- * console.log('Sign in at:', session.debugUrl);
2193
- * // Open debugUrl in browser, user signs in...
2194
- * await morph.browser.profiles.saveSession(session.sessionId, profile.id);
2195
- * ```
2196
- */
2197
- async startSession(input) {
2198
- return startProfileSession(this.config, input);
2199
- }
2200
- /**
2201
- * Save browser state from a session to a profile.
2202
- *
2203
- * Call this after the user is done signing into accounts.
2204
- * Extracts cookies, localStorage, and sessionStorage.
2205
- *
2206
- * @param sessionId - Browser session ID from startSession
2207
- * @param profileId - Profile ID to save state to
2208
- * @returns Updated profile with cookie domains
2209
- */
2210
- async saveSession(sessionId, profileId) {
2211
- return saveProfileSession({ sessionId, profileId }, this.config);
2212
- }
2213
- /**
2214
- * List available repo IDs (discovery).
2215
- *
2216
- * @returns Repo summaries with profile counts
2217
- */
2218
- async listRepos() {
2219
- return listRepos(this.config);
2220
- }
2221
- /**
2222
- * Get the presigned URL for a profile's state.
2223
- *
2224
- * Use this to download the raw state JSON for debugging
2225
- * or to restore state manually.
2226
- *
2227
- * @param profileId - Profile ID
2228
- * @returns State URL with expiry information
2229
- */
2230
- async getProfileState(profileId) {
2231
- return getProfileState(profileId, this.config);
2232
- }
2233
- };
2234
- function validateCreateInput(input) {
2235
- if (!input.name || typeof input.name !== "string") {
2236
- throw new MorphValidationError("name is required", "name");
2237
- }
2238
- const trimmedName = input.name.trim();
2239
- if (trimmedName.length === 0) {
2240
- throw new MorphValidationError("name cannot be empty", "name");
2241
- }
2242
- if (trimmedName.length > 100) {
2243
- throw new MorphValidationError("name must be 100 characters or less", "name");
2244
- }
2245
- if (!input.repoId || typeof input.repoId !== "string") {
2246
- throw new MorphValidationError("repoId is required", "repoId");
2247
- }
2248
- if (input.repoId.trim().length === 0) {
2249
- throw new MorphValidationError("repoId cannot be empty", "repoId");
2250
- }
2251
- }
2252
- function validateId(id, fieldName) {
2253
- if (!id || typeof id !== "string") {
2254
- throw new MorphValidationError(`${fieldName} is required`, fieldName);
2255
- }
2256
- if (id.trim().length === 0) {
2257
- throw new MorphValidationError(`${fieldName} cannot be empty`, fieldName);
2258
- }
2259
- }
2260
- async function createProfile(input, config = {}) {
2261
- validateCreateInput(input);
2262
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2263
- const headers = buildHeaders(config);
2264
- const response = await fetchWithRetry(
2265
- `${apiUrl}/profiles`,
2266
- {
2267
- method: "POST",
2268
- headers,
2269
- body: JSON.stringify(transformCreateInput(input))
2270
- },
2271
- config.retryConfig
2272
- );
2273
- if (!response.ok) {
2274
- const errorText = await response.text().catch(() => response.statusText);
2275
- const requestId = response.headers.get("x-request-id") || void 0;
2276
- throw parseAPIError(response.status, errorText, requestId);
2277
- }
2278
- const apiProfile = await response.json();
2279
- const profile = transformProfile(apiProfile);
2280
- const session = await startProfileSession(config, { profileId: profile.id });
2281
- return buildProfileSetup(profile, session, config);
2282
- }
2283
- async function listProfiles(config = {}, repoId) {
2284
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2285
- const headers = buildHeaders(config);
2286
- const url = repoId ? `${apiUrl}/profiles?repo_id=${encodeURIComponent(repoId)}` : `${apiUrl}/profiles`;
2287
- const response = await fetchWithRetry(
2288
- url,
2289
- { method: "GET", headers },
2290
- config.retryConfig
2291
- );
2292
- if (!response.ok) {
2293
- const errorText = await response.text().catch(() => response.statusText);
2294
- const requestId = response.headers.get("x-request-id") || void 0;
2295
- throw parseAPIError(response.status, errorText, requestId);
2296
- }
2297
- const data = await response.json();
2298
- return data.profiles.map(transformProfile);
2299
- }
2300
- async function getProfile(id, config = {}) {
2301
- validateId(id, "id");
2302
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2303
- const headers = buildHeaders(config);
2304
- const response = await fetchWithRetry(
2305
- `${apiUrl}/profiles/${encodeURIComponent(id)}`,
2306
- { method: "GET", headers },
2307
- config.retryConfig
2308
- );
2309
- if (!response.ok) {
2310
- const errorText = await response.text().catch(() => response.statusText);
2311
- const requestId = response.headers.get("x-request-id") || void 0;
2312
- throw parseAPIError(response.status, errorText, requestId);
2313
- }
2314
- const apiProfile = await response.json();
2315
- const profile = transformProfile(apiProfile);
2316
- return {
2317
- ...profile,
2318
- getState: () => getProfileState(id, config),
2319
- delete: () => deleteProfile(id, config)
2320
- };
2321
- }
2322
- async function updateProfile(id, config = {}) {
2323
- validateId(id, "id");
2324
- const profile = await fetchProfile(id, config);
2325
- const session = await startProfileSession(config, { profileId: profile.id });
2326
- return buildProfileSetup(profile, session, config);
2327
- }
2328
- async function deleteProfile(id, config = {}) {
2329
- validateId(id, "id");
2330
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2331
- const headers = buildHeaders(config);
2332
- const response = await fetchWithRetry(
2333
- `${apiUrl}/profiles/${encodeURIComponent(id)}`,
2334
- { method: "DELETE", headers },
2335
- config.retryConfig
2336
- );
2337
- if (!response.ok) {
2338
- const errorText = await response.text().catch(() => response.statusText);
2339
- const requestId = response.headers.get("x-request-id") || void 0;
2340
- throw parseAPIError(response.status, errorText, requestId);
2341
- }
2342
- }
2343
- async function startProfileSession(config = {}, input) {
2344
- if (!config.apiKey) {
2345
- throw new MorphAuthenticationError();
2346
- }
2347
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2348
- const headers = buildHeaders(config);
2349
- const body = input?.profileId ? { profile_id: input.profileId } : {};
2350
- const response = await fetchWithRetry(
2351
- `${apiUrl}/profiles/session/start`,
2352
- {
2353
- method: "POST",
2354
- headers,
2355
- body: JSON.stringify(body)
2356
- },
2357
- config.retryConfig
2358
- );
2359
- if (!response.ok) {
2360
- const errorText = await response.text().catch(() => response.statusText);
2361
- const requestId = response.headers.get("x-request-id") || void 0;
2362
- throw parseAPIError(response.status, errorText, requestId);
2363
- }
2364
- const apiSession = await response.json();
2365
- return transformSession(apiSession);
2366
- }
2367
- async function saveProfileSession(input, config = {}) {
2368
- validateId(input.sessionId, "sessionId");
2369
- validateId(input.profileId, "profileId");
2370
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2371
- const headers = buildHeaders(config);
2372
- const response = await fetchWithRetry(
2373
- `${apiUrl}/profiles/session/save`,
2374
- {
2375
- method: "POST",
2376
- headers,
2377
- body: JSON.stringify(transformSaveInput(input))
2378
- },
2379
- config.retryConfig
2380
- );
2381
- if (!response.ok) {
2382
- const errorText = await response.text().catch(() => response.statusText);
2383
- const requestId = response.headers.get("x-request-id") || void 0;
2384
- throw parseAPIError(response.status, errorText, requestId);
2385
- }
2386
- const apiProfile = await response.json();
2387
- return transformProfile(apiProfile);
2388
- }
2389
- async function listRepos(config = {}) {
2390
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2391
- const headers = buildHeaders(config);
2392
- const response = await fetchWithRetry(
2393
- `${apiUrl}/repos`,
2394
- { method: "GET", headers },
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 data = await response.json();
2403
- const repos = Array.isArray(data?.repos) ? data.repos : [];
2404
- return repos.map((repo) => ({
2405
- repoId: repo.repo_id,
2406
- repoFullName: repo.repo_full_name,
2407
- profileCount: repo.profile_count ?? 0
2408
- }));
2409
- }
2410
- async function getProfileState(profileId, config = {}) {
2411
- validateId(profileId, "profileId");
2412
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2413
- const headers = buildHeaders(config);
2414
- const response = await fetchWithRetry(
2415
- `${apiUrl}/profiles/${encodeURIComponent(profileId)}/state`,
2416
- { method: "GET", headers },
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 apiState = await response.json();
2425
- return transformStateResponse(apiState);
2426
- }
2427
- function buildHeaders(config) {
2428
- const headers = { "Content-Type": "application/json" };
2429
- if (config.apiKey) {
2430
- headers["Authorization"] = `Bearer ${config.apiKey}`;
2431
- }
2432
- return headers;
2433
- }
2434
- async function fetchProfile(id, config) {
2435
- const apiUrl = config.apiUrl || DEFAULT_API_URL2;
2436
- const headers = buildHeaders(config);
2437
- const response = await fetchWithRetry(
2438
- `${apiUrl}/profiles/${encodeURIComponent(id)}`,
2439
- { method: "GET", headers },
2440
- config.retryConfig
2441
- );
2442
- if (!response.ok) {
2443
- const errorText = await response.text().catch(() => response.statusText);
2444
- const requestId = response.headers.get("x-request-id") || void 0;
2445
- throw parseAPIError(response.status, errorText, requestId);
2446
- }
2447
- const apiProfile = await response.json();
2448
- return transformProfile(apiProfile);
2449
- }
2450
- function buildProfileSetup(profile, session, config) {
2451
- return {
2452
- profile,
2453
- session,
2454
- save: () => saveProfileSession({ sessionId: session.sessionId, profileId: profile.id }, config)
2455
- };
2456
- }
2457
-
2458
- // tools/browser/core.ts
2459
- var DEFAULT_CONFIG2 = {
2460
- apiUrl: process.env.MORPH_ENVIRONMENT === "DEV" ? "http://localhost:8000" : "https://browser.morphllm.com",
2461
- timeout: 1e6,
2462
- // 10 minutes for complex tasks
2463
- debug: false
2464
- };
2465
- var BrowserClient = class extends APIResource {
2466
- config;
2467
- /**
2468
- * Profile management - create and manage browser profiles for storing login state.
2469
- */
2470
- profiles;
2471
- constructor(clientOrConfig = {}) {
2472
- const isClient = clientOrConfig instanceof MorphAPIClient;
2473
- super(
2474
- isClient ? clientOrConfig : new MorphAPIClient({
2475
- apiKey: clientOrConfig.apiKey,
2476
- browserURL: clientOrConfig.apiUrl,
2477
- timeout: clientOrConfig.timeout,
2478
- retryConfig: clientOrConfig.retryConfig,
2479
- debug: clientOrConfig.debug
2480
- })
2481
- );
2482
- this.config = isClient ? {
2483
- ...DEFAULT_CONFIG2,
2484
- apiUrl: clientOrConfig.browserURL,
2485
- apiKey: clientOrConfig.resolveApiKey(),
2486
- retryConfig: clientOrConfig.retryConfig,
2487
- debug: clientOrConfig.debug
2488
- } : { ...DEFAULT_CONFIG2, ...clientOrConfig };
2489
- this.profiles = new ProfilesClient(this.config);
2490
- }
2491
- /**
2492
- * Execute a browser automation task
2493
- */
2494
- async execute(input) {
2495
- return executeBrowserTask(input, this.config);
2496
- }
2497
- async createTask(input) {
2498
- const apiUrl = this.config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2499
- const debug = this.config.debug || false;
2500
- const hasTask = typeof input.task === "string" && input.task.trim().length > 0;
2501
- const hasDiff = typeof input.diff === "string" && input.diff.trim().length > 0;
2502
- if (!hasTask && !hasDiff) {
2503
- throw new Error('Browser task requires either "task" (natural language) or "diff" (PR-review planning)');
2504
- }
2505
- logger.debug("Browser", "create_task", { task: (input.task ?? "").slice(0, 100), url: input.url, endpoint: `${apiUrl}/browser-task/async` });
2506
- const headers = { "Content-Type": "application/json" };
2507
- if (this.config.apiKey) headers["Authorization"] = `Bearer ${this.config.apiKey}`;
2508
- const response = await fetch(`${apiUrl}/browser-task/async`, {
2509
- method: "POST",
2510
- headers,
2511
- body: JSON.stringify({
2512
- task: input.task,
2513
- diff: input.diff,
2514
- url: input.url,
2515
- max_steps: input.maxSteps ?? 10,
2516
- model: input.model ?? "morph-computer-use-v0",
2517
- viewport_width: input.viewportWidth ?? 1280,
2518
- viewport_height: input.viewportHeight ?? 720,
2519
- external_id: input.externalId,
2520
- repo_id: input.repoId,
2521
- repo_full_name: input.repoFullName,
2522
- commit_id: input.commitId,
2523
- record_video: input.recordVideo ?? false,
2524
- video_width: input.videoWidth ?? input.viewportWidth ?? 1280,
2525
- video_height: input.videoHeight ?? input.viewportHeight ?? 720,
2526
- allow_resizing: input.allowResizing ?? false,
2527
- structured_output: "schema" in input ? stringifyStructuredOutput(input.schema) : void 0,
2528
- auth: input.auth,
2529
- profile_id: input.profileId,
2530
- force_query_params: input.forceQueryParams
2531
- })
2532
- });
2533
- if (!response.ok) {
2534
- const errorText = await response.text().catch(() => response.statusText);
2535
- logger.error("Browser", "create_task_error", { status: response.status, error: errorText });
2536
- throw new Error(`HTTP ${response.status}: ${errorText}`);
2537
- }
2538
- const result = mapTaskResult(await response.json());
2539
- logger.debug("Browser", "task_created", { recording_id: result.recordingId, task_id: result.taskId, debug_url: !!result.debugUrl });
2540
- if ("schema" in input) {
2541
- return wrapTaskResponseWithSchema(result, this.config, input.schema);
2542
- } else {
2543
- return wrapTaskResponse(result, this.config);
2544
- }
2545
- }
2546
- /**
2547
- * Execute task with recording and wait for video to be ready
2548
- */
2549
- async executeWithRecording(input) {
2550
- return executeWithRecording(input, this.config);
2551
- }
2552
- /**
2553
- * Get recording status and URLs
2554
- */
2555
- async getRecording(recordingId) {
2556
- return getRecording(recordingId, this.config);
2557
- }
2558
- /**
2559
- * Wait for recording to complete with automatic polling
2560
- */
2561
- async waitForRecording(recordingId, options) {
2562
- return waitForRecording(recordingId, this.config, options);
2563
- }
2564
- /**
2565
- * Get errors from recording with screenshots
2566
- */
2567
- async getErrors(recordingId) {
2568
- return getErrors(recordingId, this.config);
2569
- }
2570
- /**
2571
- * Get animated WebP preview of recording
2572
- */
2573
- async getWebp(recordingId, options) {
2574
- return getWebp(recordingId, this.config, options);
2575
- }
2576
- /**
2577
- * Check if browser worker service is healthy
2578
- */
2579
- async checkHealth() {
2580
- return checkHealth(this.config);
2581
- }
2582
- };
2583
- async function executeBrowserTask(input, config = {}) {
2584
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2585
- const timeout = config.timeout || DEFAULT_CONFIG2.timeout;
2586
- const debug = config.debug || false;
2587
- if (!input.task || input.task.trim().length === 0) {
2588
- return {
2589
- success: false,
2590
- error: 'Task description is required. Example: "Go to example.com and click the login button"'
2591
- };
2592
- }
2593
- if (input.maxSteps !== void 0 && (input.maxSteps < 1 || input.maxSteps > 50)) {
2594
- return {
2595
- success: false,
2596
- error: "maxSteps must be between 1 and 50. Use more steps for complex multi-page flows."
2597
- };
2598
- }
2599
- logger.debug("Browser", "execute_start", { task: input.task.slice(0, 100), url: input.url, max_steps: input.maxSteps ?? 10, record_video: input.recordVideo ?? false });
2600
- const startTime = Date.now();
2601
- try {
2602
- const headers = { "Content-Type": "application/json" };
2603
- if (config.apiKey) headers["Authorization"] = `Bearer ${config.apiKey}`;
2604
- const fetchPromise = fetchWithRetry(
2605
- `${apiUrl}/browser-task`,
2606
- {
2607
- method: "POST",
2608
- headers,
2609
- body: JSON.stringify({
2610
- task: input.task,
2611
- url: input.url,
2612
- max_steps: input.maxSteps ?? 10,
2613
- model: input.model ?? "morph-computer-use-v0",
2614
- viewport_width: input.viewportWidth ?? 1280,
2615
- viewport_height: input.viewportHeight ?? 720,
2616
- external_id: input.externalId,
2617
- repo_id: input.repoId,
2618
- commit_id: input.commitId,
2619
- record_video: input.recordVideo ?? false,
2620
- video_width: input.videoWidth ?? input.viewportWidth ?? 1280,
2621
- video_height: input.videoHeight ?? input.viewportHeight ?? 720,
2622
- allow_resizing: input.allowResizing ?? false,
2623
- structured_output: input.structuredOutput,
2624
- auth: input.auth,
2625
- profile_id: input.profileId,
2626
- force_query_params: input.forceQueryParams
2627
- })
2628
- },
2629
- config.retryConfig
2630
- );
2631
- const response = await withTimeout(
2632
- fetchPromise,
2633
- timeout,
2634
- `Browser task timed out after ${timeout}ms. Consider increasing timeout or reducing maxSteps.`
2635
- );
2636
- if (!response.ok) {
2637
- const errorText = await response.text().catch(() => response.statusText);
2638
- logger.error("Browser", "execute_error", { status: response.status, error: errorText });
2639
- throw new Error(`HTTP ${response.status}: ${errorText}`);
2640
- }
2641
- const result = mapTaskResult(await response.json());
2642
- const elapsed = Date.now() - startTime;
2643
- logger.debug("Browser", "execute_complete", { success: result.success, latency_ms: elapsed, steps: result.stepsTaken ?? 0, recording_id: result.recordingId });
2644
- return result;
2645
- } catch (error) {
2646
- if (error instanceof Error) {
2647
- if (error.message.includes("ECONNREFUSED") || error.message.includes("fetch failed")) {
2648
- return {
2649
- success: false,
2650
- error: `Cannot connect to browser worker at ${apiUrl}. Ensure the service is running and accessible. For local dev, set MORPH_ENVIRONMENT=DEV.`
2651
- };
2652
- }
2653
- return {
2654
- success: false,
2655
- error: error.message
2656
- };
2657
- }
2658
- return {
2659
- success: false,
2660
- error: String(error)
2661
- };
2662
- }
2663
- }
2664
- async function getRecording(recordingId, config = {}) {
2665
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2666
- const debug = config.debug || false;
2667
- if (!config.apiKey) {
2668
- throw new Error("API key required for getRecording");
2669
- }
2670
- if (debug) console.log(`[Browser] getRecording: ${recordingId}`);
2671
- const response = await fetch(`${apiUrl}/recordings/${recordingId}`, {
2672
- method: "GET",
2673
- headers: { "Authorization": `Bearer ${config.apiKey}` }
2674
- });
2675
- if (!response.ok) {
2676
- const errorText = await response.text().catch(() => response.statusText);
2677
- if (debug) console.error(`[Browser] getRecording error: ${response.status} - ${errorText}`);
2678
- throw new Error(`HTTP ${response.status}: ${errorText}`);
2679
- }
2680
- const data = mapRecordingStatus(await response.json());
2681
- if (debug) console.log(`[Browser] Recording status: ${data.status}`);
2682
- return {
2683
- ...data,
2684
- getWebp: (options) => getWebp(recordingId, config, options),
2685
- getErrors: () => getErrors(recordingId, config)
2686
- };
2687
- }
2688
- async function waitForRecording(recordingId, config = {}, options = {}) {
2689
- const timeout = options.timeout ?? 6e4;
2690
- const pollInterval = options.pollInterval ?? 2e3;
2691
- const startTime = Date.now();
2692
- while (Date.now() - startTime < timeout) {
2693
- const status = await getRecording(recordingId, config);
2694
- if (status.status === "COMPLETED" || status.status === "ERROR") {
2695
- return status;
2696
- }
2697
- await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
2698
- }
2699
- throw new Error(`Recording timeout after ${timeout}ms - status still pending`);
2700
- }
2701
- async function executeWithRecording(input, config = {}) {
2702
- const taskResult = await executeBrowserTask(input, config);
2703
- if (taskResult.recordingId) {
2704
- try {
2705
- const recording = await waitForRecording(
2706
- taskResult.recordingId,
2707
- config,
2708
- { timeout: 6e4, pollInterval: 2e3 }
2709
- );
2710
- return {
2711
- ...taskResult,
2712
- recording
2713
- };
2714
- } catch (error) {
2715
- const errorRecording = {
2716
- id: taskResult.recordingId,
2717
- status: "ERROR",
2718
- error: error instanceof Error ? error.message : String(error),
2719
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2720
- getWebp: (options) => getWebp(taskResult.recordingId, config, options),
2721
- getErrors: () => getErrors(taskResult.recordingId, config)
2722
- };
2723
- return {
2724
- ...taskResult,
2725
- recording: errorRecording
2726
- };
2727
- }
2728
- }
2729
- return taskResult;
2730
- }
2731
- async function getErrors(recordingId, config = {}) {
2732
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2733
- const debug = config.debug || false;
2734
- if (!config.apiKey) {
2735
- throw new Error("API key required for getErrors");
2736
- }
2737
- if (debug) console.log(`[Browser] getErrors: ${recordingId}`);
2738
- const response = await fetch(`${apiUrl}/recordings/${recordingId}/errors`, {
2739
- method: "GET",
2740
- headers: { "Authorization": `Bearer ${config.apiKey}` }
2741
- });
2742
- if (!response.ok) {
2743
- const errorText = await response.text().catch(() => response.statusText);
2744
- if (debug) console.error(`[Browser] getErrors error: ${response.status} - ${errorText}`);
2745
- throw new Error(`HTTP ${response.status}: ${errorText}`);
2746
- }
2747
- const errors = mapErrorsResponse(await response.json());
2748
- if (debug) console.log(`[Browser] Found ${errors.totalErrors} errors`);
2749
- return errors;
2750
- }
2751
- function stringifyStructuredOutput(schema) {
2752
- try {
2753
- return JSON.stringify({
2754
- type: "object",
2755
- description: "Zod schema definition (Zod v3)",
2756
- zodDef: schema._def
2757
- });
2758
- } catch (error) {
2759
- console.warn("[Browser] Failed to serialize Zod schema:", error);
2760
- return JSON.stringify({
2761
- type: "object",
2762
- description: "Schema serialization failed"
2763
- });
2764
- }
2765
- }
2766
- function parseStructuredTaskOutput(result, schema) {
2767
- if (!result.output) {
2768
- return { ...result, parsed: null };
2769
- }
2770
- try {
2771
- const parsed = JSON.parse(result.output);
2772
- const validated = schema.parse(parsed);
2773
- return { ...result, parsed: validated };
2774
- } catch (error) {
2775
- if (error instanceof SyntaxError) {
2776
- return { ...result, parsed: null };
2777
- }
2778
- throw error;
2779
- }
2780
- }
2781
- function mapTaskResult(api) {
2782
- if (!api || typeof api !== "object") {
2783
- return api;
2784
- }
2785
- return {
2786
- success: api.success,
2787
- result: api.result,
2788
- error: api.error,
2789
- stepsTaken: api.steps_taken,
2790
- executionTimeMs: api.execution_time_ms,
2791
- urls: api.urls,
2792
- actionNames: api.action_names,
2793
- errors: api.errors,
2794
- modelActions: api.model_actions,
2795
- isDone: api.is_done,
2796
- actionHistory: api.action_history,
2797
- actionResults: api.action_results,
2798
- hasErrors: api.has_errors,
2799
- numberOfSteps: api.number_of_steps,
2800
- judgement: api.judgement,
2801
- isValidated: api.is_validated,
2802
- replayId: api.replay_id,
2803
- replayUrl: api.replay_url,
2804
- recordingId: api.recording_id,
2805
- recordingStatus: api.recording_status,
2806
- taskId: api.task_id,
2807
- status: api.status,
2808
- output: api.output,
2809
- debugUrl: api.debug_url
2810
- };
2811
- }
2812
- function mapRecordingStatus(api) {
2813
- return {
2814
- id: api.id,
2815
- status: api.status,
2816
- replayUrl: api.replay_url,
2817
- networkUrl: api.network_url,
2818
- consoleUrl: api.console_url,
2819
- videoUrl: api.video_url,
2820
- result: api.result,
2821
- totalEvents: api.total_events,
2822
- fileSize: api.file_size,
2823
- duration: api.duration,
2824
- error: api.error,
2825
- createdAt: api.created_at
2826
- };
2827
- }
2828
- function mapBrowserError(api) {
2829
- return {
2830
- type: api.type,
2831
- message: api.message,
2832
- url: api.url,
2833
- timestamp: api.timestamp,
2834
- screenshotUrl: api.screenshot_url,
2835
- capturedAt: api.captured_at,
2836
- status: api.status
2837
- };
2838
- }
2839
- function mapErrorsResponse(api) {
2840
- return {
2841
- recordingId: api.recording_id,
2842
- totalErrors: api.total_errors,
2843
- errors: Array.isArray(api.errors) ? api.errors.map(mapBrowserError) : []
2844
- };
2845
- }
2846
- function mapWebpResponse(api) {
2847
- return {
2848
- webpUrl: api.webp_url,
2849
- cached: api.cached,
2850
- width: api.width,
2851
- fps: api.fps,
2852
- maxDuration: api.max_duration,
2853
- fileSize: api.file_size,
2854
- maxSizeMb: api.max_size_mb,
2855
- budgetMet: api.budget_met,
2856
- qualityUsed: api.quality_used,
2857
- attempts: api.attempts
2858
- };
2859
- }
2860
- async function getTaskStatus(taskId, config) {
2861
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2862
- const debug = config.debug || false;
2863
- if (debug) console.log(`[Browser] getTaskStatus: ${taskId}`);
2864
- const headers = {};
2865
- if (config.apiKey) headers["Authorization"] = `Bearer ${config.apiKey}`;
2866
- const response = await fetch(`${apiUrl}/tasks/${taskId}`, {
2867
- method: "GET",
2868
- headers
2869
- });
2870
- if (!response.ok) {
2871
- const errorText = await response.text().catch(() => response.statusText);
2872
- if (debug) console.error(`[Browser] getTaskStatus error: ${response.status} - ${errorText}`);
2873
- throw new Error(`HTTP ${response.status}: ${errorText}`);
2874
- }
2875
- const result = mapTaskResult(await response.json());
2876
- if (debug) console.log(`[Browser] Task status: ${result.status}`);
2877
- return result;
2878
- }
2879
- function generateLiveUrl(taskId, config) {
2880
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2881
- const baseUrl = apiUrl.replace("/api", "");
2882
- return `${baseUrl}/tasks/${taskId}/live`;
2883
- }
2884
- async function pollTaskUntilComplete(taskId, config, pollConfig = {}) {
2885
- const interval = pollConfig.interval ?? 2e3;
2886
- const timeout = pollConfig.timeout ?? 3e5;
2887
- const startTime = Date.now();
2888
- while (Date.now() - startTime < timeout) {
2889
- const status = await getTaskStatus(taskId, config);
2890
- if (status.status === "completed" || status.status === "failed") {
2891
- return status;
2892
- }
2893
- await new Promise((resolve2) => setTimeout(resolve2, interval));
2894
- }
2895
- throw new Error(`Task polling timeout after ${timeout}ms`);
2896
- }
2897
- function wrapTaskResponse(result, config) {
2898
- const debugUrl = result.debugUrl ?? "";
2899
- const wrapped = {
2900
- ...result,
2901
- debugUrl,
2902
- taskId: result.taskId || "",
2903
- liveUrl: result.taskId ? generateLiveUrl(result.taskId, config) : debugUrl,
2904
- complete: async (pollConfig) => {
2905
- if (result.taskId) {
2906
- return pollTaskUntilComplete(result.taskId, config, pollConfig);
2907
- }
2908
- if (result.recordingId) {
2909
- const recording = await waitForRecording(
2910
- result.recordingId,
2911
- config,
2912
- pollConfig
2913
- );
2914
- return {
2915
- ...result,
2916
- recordingStatus: recording.status
2917
- };
2918
- }
2919
- throw new Error("Cannot poll completion: no taskId or recordingId available");
2920
- },
2921
- // Add Steel live session helpers - either functional or error-throwing
2922
- getLiveUrl: debugUrl ? (options) => buildLiveUrl(debugUrl, options) : () => {
2923
- throw new Error(
2924
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
2925
- );
2926
- },
2927
- getLiveIframe: debugUrl ? (optionsOrPreset) => {
2928
- const options = resolvePreset(optionsOrPreset);
2929
- return buildLiveIframe(debugUrl, options);
2930
- } : () => {
2931
- throw new Error(
2932
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
2933
- );
2934
- },
2935
- getEmbedCode: debugUrl ? () => buildEmbedCode(debugUrl) : () => {
2936
- throw new Error(
2937
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
2938
- );
2939
- }
2940
- };
2941
- return wrapped;
2942
- }
2943
- function wrapTaskResponseWithSchema(result, config, schema) {
2944
- const debugUrl = result.debugUrl ?? "";
2945
- const parsed = result.output ? parseStructuredTaskOutput(result, schema) : { ...result, parsed: null };
2946
- const wrapped = {
2947
- ...parsed,
2948
- debugUrl,
2949
- taskId: result.taskId || "",
2950
- liveUrl: result.taskId ? generateLiveUrl(result.taskId, config) : debugUrl,
2951
- complete: async (pollConfig) => {
2952
- if (result.taskId) {
2953
- const finalResult = await pollTaskUntilComplete(result.taskId, config, pollConfig);
2954
- return parseStructuredTaskOutput(finalResult, schema);
2955
- }
2956
- if (result.recordingId) {
2957
- const recording = await waitForRecording(
2958
- result.recordingId,
2959
- config,
2960
- pollConfig
2961
- );
2962
- return {
2963
- ...parsed,
2964
- recordingStatus: recording.status
2965
- };
1599
+ try {
1600
+ const { readFile, writeFile } = await import("fs/promises");
1601
+ const { callMorphAPI: callMorphAPI2, generateUdiff: generateUdiff2, countChanges: countChanges2 } = await Promise.resolve().then(() => (init_apply(), apply_exports));
1602
+ let originalCode = "";
1603
+ let fileExists = true;
1604
+ try {
1605
+ originalCode = await readFile(fullPath, "utf-8");
1606
+ logger.debug("FastApply", "file_read", { path: fullPath, exists: true, size_bytes: originalCode.length });
1607
+ } catch (error) {
1608
+ if (error.code !== "ENOENT") {
1609
+ throw error;
2966
1610
  }
2967
- throw new Error("Cannot poll completion: no taskId or recordingId available");
2968
- },
2969
- // Add Steel live session helpers - either functional or error-throwing
2970
- getLiveUrl: debugUrl ? (options) => buildLiveUrl(debugUrl, options) : () => {
2971
- throw new Error(
2972
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions. "
2973
- );
2974
- },
2975
- getLiveIframe: debugUrl ? (optionsOrPreset) => {
2976
- const options = resolvePreset(optionsOrPreset);
2977
- return buildLiveIframe(debugUrl, options);
2978
- } : () => {
2979
- throw new Error(
2980
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions."
2981
- );
2982
- },
2983
- getEmbedCode: debugUrl ? () => buildEmbedCode(debugUrl) : () => {
2984
- throw new Error(
2985
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions."
2986
- );
1611
+ fileExists = false;
1612
+ logger.debug("FastApply", "file_read", { path: fullPath, exists: false });
2987
1613
  }
2988
- };
2989
- return wrapped;
2990
- }
2991
- async function getWebp(recordingId, config = {}, options = {}) {
2992
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
2993
- const debug = config.debug || false;
2994
- if (!config.apiKey) {
2995
- throw new Error("API key required for getWebp");
2996
- }
2997
- const params = new URLSearchParams();
2998
- if (options.maxDuration !== void 0) params.set("max_duration", String(options.maxDuration));
2999
- if (options.fps !== void 0) params.set("fps", String(options.fps));
3000
- if (options.width !== void 0) params.set("width", String(options.width));
3001
- if (options.quality !== void 0) params.set("quality", String(options.quality));
3002
- if (options.maxSizeMb !== void 0) params.set("max_size_mb", String(options.maxSizeMb));
3003
- const url = `${apiUrl}/recordings/${recordingId}/webp${params.toString() ? "?" + params.toString() : ""}`;
3004
- if (debug) console.log(`[Browser] getWebp: ${url}`);
3005
- const response = await fetch(url, {
3006
- method: "GET",
3007
- headers: { "Authorization": `Bearer ${config.apiKey}` }
3008
- });
3009
- if (!response.ok) {
3010
- const errorText = await response.text().catch(() => response.statusText);
3011
- if (debug) console.error(`[Browser] getWebp error: ${response.status} - ${errorText}`);
3012
- throw new Error(`HTTP ${response.status}: ${errorText}`);
3013
- }
3014
- const result = mapWebpResponse(await response.json());
3015
- if (debug) console.log(`[Browser] WebP ready: ${result.webpUrl} (cached: ${result.cached})`);
3016
- return result;
3017
- }
3018
- async function checkHealth(config = {}) {
3019
- const apiUrl = config.apiUrl || DEFAULT_CONFIG2.apiUrl;
3020
- try {
3021
- const response = await fetch(`${apiUrl}/health`, {
3022
- method: "GET",
3023
- headers: config.apiKey ? { "Authorization": `Bearer ${config.apiKey}` } : {}
3024
- });
3025
- if (!response.ok) {
3026
- throw new Error(`HTTP ${response.status}`);
1614
+ const instruction = input.instruction ?? input.instructions ?? "";
1615
+ logger.debug("FastApply", "api_call", { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });
1616
+ const { content: mergedCode, completionId } = await callMorphAPI2(originalCode, input.code_edit, instruction, input.target_filepath, config);
1617
+ logger.debug("FastApply", "api_response", { completion_id: completionId, merged_len: mergedCode.length });
1618
+ const udiff = config.generateUdiff !== false ? generateUdiff2(originalCode, mergedCode, input.target_filepath) : void 0;
1619
+ if (config.autoWrite !== false) {
1620
+ await writeFile(fullPath, mergedCode, "utf-8");
1621
+ logger.debug("FastApply", "file_write", { path: fullPath, size_bytes: mergedCode.length });
3027
1622
  }
3028
- const data = await response.json();
1623
+ const changes = countChanges2(originalCode, mergedCode);
1624
+ logger.debug("FastApply", "changes", { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });
3029
1625
  return {
3030
- ok: true,
3031
- google_configured: data.google_configured ?? false,
3032
- database_configured: data.database_configured ?? false,
3033
- s3_configured: data.s3_configured ?? false
1626
+ success: true,
1627
+ filepath: input.target_filepath,
1628
+ udiff,
1629
+ changes,
1630
+ completionId
3034
1631
  };
3035
1632
  } catch (error) {
1633
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1634
+ const structuredError = error instanceof FastApplyContextLengthError || error instanceof FastApplyAnchorIntegrityError ? error : void 0;
1635
+ logger.error("FastApply", "execute_error", { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : void 0 });
3036
1636
  return {
3037
- ok: false,
3038
- google_configured: false,
3039
- database_configured: false,
3040
- s3_configured: false,
3041
- error: error instanceof Error ? error.message : String(error)
1637
+ success: false,
1638
+ filepath: input.target_filepath,
1639
+ changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
1640
+ error: errorMessage,
1641
+ errorCode: structuredError?.code,
1642
+ completionId: structuredError?.completionId
3042
1643
  };
3043
1644
  }
3044
1645
  }
@@ -3352,7 +1953,7 @@ var import_openai2 = __toESM(require("openai"), 1);
3352
1953
  init_version();
3353
1954
  var import_path4 = __toESM(require("path"), 1);
3354
1955
  init_logger();
3355
- var DEFAULT_API_URL3 = "https://api.morphllm.com";
1956
+ var DEFAULT_API_URL2 = "https://api.morphllm.com";
3356
1957
  var TOOL_SPECS = [
3357
1958
  {
3358
1959
  type: "function",
@@ -3461,7 +2062,7 @@ var TOOL_SPECS = [
3461
2062
  }
3462
2063
  ];
3463
2064
  async function callModel(messages, model, options = {}) {
3464
- const baseUrl = options.morphApiUrl || DEFAULT_API_URL3;
2065
+ const baseUrl = options.morphApiUrl || DEFAULT_API_URL2;
3465
2066
  const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
3466
2067
  const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
3467
2068
  const parsedUrl = new URL(baseUrl);
@@ -4015,14 +2616,14 @@ function parseGitHubUrl(input) {
4015
2616
  }
4016
2617
 
4017
2618
  // tools/compact/core.ts
4018
- var DEFAULT_API_URL4 = "https://api.morphllm.com";
4019
- var DEFAULT_TIMEOUT4 = 12e4;
2619
+ var DEFAULT_API_URL3 = "https://api.morphllm.com";
2620
+ var DEFAULT_TIMEOUT3 = 12e4;
4020
2621
  function resolveClient(clientOrConfig) {
4021
2622
  if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
4022
2623
  return new MorphAPIClient({
4023
2624
  apiKey: clientOrConfig.morphApiKey,
4024
- baseURL: clientOrConfig.morphApiUrl ?? DEFAULT_API_URL4,
4025
- timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT4,
2625
+ baseURL: clientOrConfig.morphApiUrl ?? DEFAULT_API_URL3,
2626
+ timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT3,
4026
2627
  retryConfig: clientOrConfig.retryConfig,
4027
2628
  debug: clientOrConfig.debug
4028
2629
  });
@@ -4035,7 +2636,7 @@ var CompactClient = class extends APIResource {
4035
2636
  const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
4036
2637
  this.config = {
4037
2638
  morphApiUrl: this._client.baseURL,
4038
- timeout: cfg.timeout ?? DEFAULT_TIMEOUT4,
2639
+ timeout: cfg.timeout ?? DEFAULT_TIMEOUT3,
4039
2640
  debug: cfg.debug ?? false
4040
2641
  };
4041
2642
  }
@@ -4402,357 +3003,16 @@ function formatResult(result) {
4402
3003
  return parts.join("\n");
4403
3004
  }
4404
3005
 
4405
- // tools/github/types.ts
4406
- var GitHubError = class extends Error {
4407
- /** HTTP status code */
4408
- status;
4409
- /** Error code from API */
4410
- code;
4411
- constructor(message, status, code) {
4412
- super(message);
4413
- this.name = "GitHubError";
4414
- this.status = status;
4415
- this.code = code;
4416
- }
4417
- };
4418
- var NoInstallationError = class extends GitHubError {
4419
- constructor(message = "No GitHub installation found. Connect GitHub at morphllm.com/dashboard/integrations/github") {
4420
- super(message, 404, "NO_INSTALLATION");
4421
- }
4422
- };
4423
- var NotFoundError = class extends GitHubError {
4424
- constructor(resource) {
4425
- super(`${resource} not found`, 404, "NOT_FOUND");
4426
- }
4427
- };
4428
- var PermissionError = class extends GitHubError {
4429
- constructor(message = "Insufficient permissions for this operation") {
4430
- super(message, 403, "PERMISSION_DENIED");
4431
- }
4432
- };
4433
-
4434
- // tools/github/core.ts
4435
- var DEFAULT_BASE_URL2 = "https://api.morphllm.com";
4436
- var DEFAULT_TIMEOUT5 = 3e4;
4437
- var GitHubClient = class extends APIResource {
4438
- timeout;
4439
- debug;
4440
- defaultInstallationId;
4441
- /** Installation operations */
4442
- installations;
4443
- /** Repository operations */
4444
- repos;
4445
- /** Project operations (monorepo sub-projects) */
4446
- projects;
4447
- /** Pull request operations */
4448
- pullRequests;
4449
- /** Deployment operations */
4450
- deployments;
4451
- /** Comment operations */
4452
- comments;
4453
- /** Check run operations */
4454
- checkRuns;
4455
- /**
4456
- * Get the GitHub App installation URL.
4457
- * Users visit this URL once to install the Morph GitHub App on their account/org.
4458
- */
4459
- getInstallUrl() {
4460
- return "https://github.com/apps/morph-subagents/installations/new";
4461
- }
4462
- constructor(clientOrConfig = {}, options = {}) {
4463
- const isClient = clientOrConfig instanceof MorphAPIClient;
4464
- const config = isClient ? {} : clientOrConfig;
4465
- super(
4466
- isClient ? clientOrConfig : new MorphAPIClient({
4467
- apiKey: config.apiKey,
4468
- baseURL: config.baseUrl ?? DEFAULT_BASE_URL2,
4469
- timeout: config.timeout ?? DEFAULT_TIMEOUT5,
4470
- debug: config.debug
4471
- })
4472
- );
4473
- this.timeout = config.timeout || DEFAULT_TIMEOUT5;
4474
- this.debug = config.debug || false;
4475
- this.defaultInstallationId = isClient ? options.installationId : config.installationId;
4476
- if (!this._client.resolveApiKey()) {
4477
- throw new Error("API key required. Set MORPH_API_KEY or pass apiKey in config.");
4478
- }
4479
- this.installations = {
4480
- list: this.listInstallations.bind(this),
4481
- get: this.getInstallation.bind(this),
4482
- update: this.updateInstallation.bind(this),
4483
- disconnect: this.disconnectInstallation.bind(this)
4484
- };
4485
- this.repos = {
4486
- list: this.listRepos.bind(this),
4487
- get: this.getRepo.bind(this),
4488
- update: this.updateRepo.bind(this),
4489
- remove: this.removeRepo.bind(this),
4490
- sync: this.syncRepos.bind(this)
4491
- };
4492
- this.projects = {
4493
- list: this.listProjects.bind(this),
4494
- create: this.createProject.bind(this),
4495
- update: this.updateProject.bind(this),
4496
- delete: this.deleteProject.bind(this)
4497
- };
4498
- this.pullRequests = {
4499
- list: this.listPullRequests.bind(this),
4500
- get: this.getPullRequest.bind(this)
4501
- };
4502
- this.deployments = {
4503
- list: this.listDeployments.bind(this)
4504
- };
4505
- this.comments = {
4506
- list: this.listComments.bind(this),
4507
- create: this.createComment.bind(this),
4508
- update: this.updateComment.bind(this),
4509
- delete: this.deleteComment.bind(this)
4510
- };
4511
- this.checkRuns = {
4512
- create: this.createCheckRun.bind(this),
4513
- update: this.updateCheckRun.bind(this)
4514
- };
4515
- }
4516
- /**
4517
- * Make an authenticated API request
4518
- */
4519
- async request(method, path6, body) {
4520
- if (this.debug) {
4521
- console.log(`[GitHub SDK] ${method} ${path6}`, body || "");
4522
- }
4523
- let response;
4524
- try {
4525
- response = await this._client.request(method, path6, {
4526
- body,
4527
- timeout: this.timeout,
4528
- raw: true
4529
- });
4530
- } catch (error) {
4531
- if (error instanceof Error && /timed out/i.test(error.message)) {
4532
- throw new GitHubError("Request timeout", 408, "TIMEOUT");
4533
- }
4534
- throw new GitHubError(error instanceof Error ? error.message : "Unknown error", 500, "UNKNOWN");
4535
- }
4536
- if (!response.ok) {
4537
- const errorData = await response.json().catch(() => ({}));
4538
- const message = errorData.error || errorData.detail || errorData.message || response.statusText;
4539
- if (this.debug) {
4540
- console.error(`[GitHub SDK] Error ${response.status}:`, message);
4541
- }
4542
- if (response.status === 404) {
4543
- if (message.includes("installation")) {
4544
- throw new NoInstallationError(message);
4545
- }
4546
- throw new NotFoundError(message);
4547
- }
4548
- if (response.status === 403) {
4549
- throw new PermissionError(message);
4550
- }
4551
- throw new GitHubError(message, response.status, errorData.code);
4552
- }
4553
- const data = await response.json();
4554
- if (this.debug) {
4555
- console.log(`[GitHub SDK] Response:`, JSON.stringify(data).slice(0, 200));
4556
- }
4557
- return data;
4558
- }
4559
- /**
4560
- * Get the installation ID to use for a request
4561
- */
4562
- getInstallationId(input) {
4563
- return input?.installationId || this.defaultInstallationId;
4564
- }
4565
- // ==========================================================================
4566
- // Installations
4567
- // ==========================================================================
4568
- async listInstallations() {
4569
- return this.request("GET", "/api/v1/github/installations");
4570
- }
4571
- async getInstallation(installationId) {
4572
- return this.request("GET", `/api/v1/github/installations/${installationId}`);
4573
- }
4574
- async updateInstallation(input) {
4575
- if (this.debug) console.log("[GitHub SDK] updateInstallation", input.installationId);
4576
- const { installationId, ...body } = input;
4577
- return this.request("PATCH", `/api/v1/github/installations/${installationId}`, body);
4578
- }
4579
- async disconnectInstallation(installationId) {
4580
- if (this.debug) console.log("[GitHub SDK] disconnectInstallation", installationId);
4581
- return this.request("DELETE", `/api/v1/github/installations/${installationId}`);
4582
- }
4583
- // ==========================================================================
4584
- // Repositories
4585
- // ==========================================================================
4586
- async listRepos(input) {
4587
- const installationId = input.installationId || this.defaultInstallationId;
4588
- if (!installationId) {
4589
- throw new NoInstallationError("installationId required. Call installations.list() first.");
4590
- }
4591
- return this.request("GET", `/api/v1/github/installations/${installationId}/repos`);
4592
- }
4593
- async getRepo(repoId) {
4594
- if (this.debug) console.log("[GitHub SDK] getRepo", repoId);
4595
- return this.request("GET", `/api/v1/github/repos/${repoId}`);
4596
- }
4597
- async updateRepo(input) {
4598
- if (this.debug) console.log("[GitHub SDK] updateRepo", input.repoId);
4599
- const { repoId, ...body } = input;
4600
- return this.request("PATCH", `/api/v1/github/repos/${repoId}`, body);
4601
- }
4602
- async removeRepo(repoId) {
4603
- if (this.debug) console.log("[GitHub SDK] removeRepo", repoId);
4604
- return this.request("DELETE", `/api/v1/github/repos/${repoId}`);
4605
- }
4606
- async syncRepos(input) {
4607
- const installationId = input.installationId || this.defaultInstallationId;
4608
- if (!installationId) {
4609
- throw new NoInstallationError("installationId required. Call installations.list() first.");
4610
- }
4611
- if (this.debug) console.log("[GitHub SDK] syncRepos", installationId);
4612
- return this.request("POST", `/api/v1/github/installations/${installationId}/repos/sync`);
4613
- }
4614
- // ==========================================================================
4615
- // Projects (monorepo sub-projects)
4616
- // ==========================================================================
4617
- async listProjects(input) {
4618
- if (this.debug) console.log("[GitHub SDK] listProjects", input.repoId);
4619
- return this.request("GET", `/api/v1/github/repos/${input.repoId}/projects`);
4620
- }
4621
- async createProject(input) {
4622
- if (this.debug) console.log("[GitHub SDK] createProject", input.repoId, input.name);
4623
- const { repoId, ...body } = input;
4624
- return this.request("POST", `/api/v1/github/repos/${repoId}/projects`, body);
4625
- }
4626
- async updateProject(input) {
4627
- if (this.debug) console.log("[GitHub SDK] updateProject", input.projectId);
4628
- const { projectId, ...body } = input;
4629
- return this.request("PATCH", `/api/v1/github/projects/${projectId}`, body);
4630
- }
4631
- async deleteProject(projectId) {
4632
- if (this.debug) console.log("[GitHub SDK] deleteProject", projectId);
4633
- return this.request("DELETE", `/api/v1/github/projects/${projectId}`);
4634
- }
4635
- // ==========================================================================
4636
- // Pull Requests
4637
- // ==========================================================================
4638
- async listPullRequests(input) {
4639
- const installationId = this.getInstallationId(input);
4640
- const params = new URLSearchParams({
4641
- owner: input.owner,
4642
- repo: input.repo,
4643
- ...input.state && { state: input.state },
4644
- ...installationId && { installationId }
4645
- });
4646
- return this.request("GET", `/api/v1/github/pulls?${params}`);
4647
- }
4648
- async getPullRequest(input) {
4649
- const installationId = this.getInstallationId(input);
4650
- const params = new URLSearchParams({
4651
- owner: input.owner,
4652
- repo: input.repo,
4653
- ...installationId && { installationId }
4654
- });
4655
- return this.request(
4656
- "GET",
4657
- `/api/v1/github/pulls/${input.number}?${params}`
4658
- );
4659
- }
4660
- // ==========================================================================
4661
- // Deployments
4662
- // ==========================================================================
4663
- async listDeployments(input) {
4664
- const installationId = this.getInstallationId(input);
4665
- const params = new URLSearchParams({
4666
- owner: input.owner,
4667
- repo: input.repo,
4668
- ...input.sha && { sha: input.sha },
4669
- ...input.environment && { environment: input.environment },
4670
- ...installationId && { installationId }
4671
- });
4672
- return this.request("GET", `/api/v1/github/deployments?${params}`);
4673
- }
4674
- // ==========================================================================
4675
- // Comments
4676
- // ==========================================================================
4677
- async listComments(input) {
4678
- const installationId = this.getInstallationId(input);
4679
- const params = new URLSearchParams({
4680
- owner: input.owner,
4681
- repo: input.repo,
4682
- pr: String(input.pr),
4683
- ...installationId && { installationId }
4684
- });
4685
- return this.request("GET", `/api/v1/github/comments?${params}`);
4686
- }
4687
- async createComment(input) {
4688
- const installationId = this.getInstallationId(input);
4689
- return this.request("POST", "/api/v1/github/comments", {
4690
- owner: input.owner,
4691
- repo: input.repo,
4692
- pr: input.pr,
4693
- body: input.body,
4694
- ...installationId && { installationId }
4695
- });
4696
- }
4697
- async updateComment(input) {
4698
- const installationId = this.getInstallationId(input);
4699
- return this.request("PATCH", `/api/v1/github/comments/${input.commentId}`, {
4700
- owner: input.owner,
4701
- repo: input.repo,
4702
- body: input.body,
4703
- ...installationId && { installationId }
4704
- });
4705
- }
4706
- async deleteComment(input) {
4707
- const installationId = this.getInstallationId(input);
4708
- const params = new URLSearchParams({
4709
- owner: input.owner,
4710
- repo: input.repo,
4711
- ...installationId && { installationId }
4712
- });
4713
- await this.request("DELETE", `/api/v1/github/comments/${input.commentId}?${params}`);
4714
- }
4715
- // ==========================================================================
4716
- // Check Runs
4717
- // ==========================================================================
4718
- async createCheckRun(input) {
4719
- const installationId = this.getInstallationId(input);
4720
- return this.request("POST", "/api/v1/github/check-runs", {
4721
- owner: input.owner,
4722
- repo: input.repo,
4723
- sha: input.sha,
4724
- name: input.name,
4725
- status: input.status,
4726
- ...input.title && { title: input.title },
4727
- ...input.summary && { summary: input.summary },
4728
- ...installationId && { installationId }
4729
- });
4730
- }
4731
- async updateCheckRun(input) {
4732
- const installationId = this.getInstallationId(input);
4733
- return this.request("PATCH", `/api/v1/github/check-runs/${input.checkRunId}`, {
4734
- owner: input.owner,
4735
- repo: input.repo,
4736
- ...input.status && { status: input.status },
4737
- ...input.conclusion && { conclusion: input.conclusion },
4738
- ...input.title && { title: input.title },
4739
- ...input.summary && { summary: input.summary },
4740
- ...input.text && { text: input.text },
4741
- ...installationId && { installationId }
4742
- });
4743
- }
4744
- };
4745
-
4746
3006
  // modelrouter/core.ts
4747
3007
  init_logger();
4748
- var DEFAULT_API_URL5 = "https://api.morphllm.com";
4749
- var DEFAULT_TIMEOUT6 = 5e3;
3008
+ var DEFAULT_API_URL4 = "https://api.morphllm.com";
3009
+ var DEFAULT_TIMEOUT4 = 5e3;
4750
3010
  function resolveClient2(clientOrConfig) {
4751
3011
  if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
4752
3012
  return new MorphAPIClient({
4753
3013
  apiKey: clientOrConfig.apiKey,
4754
- baseURL: clientOrConfig.apiUrl ?? DEFAULT_API_URL5,
4755
- timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT6,
3014
+ baseURL: clientOrConfig.apiUrl ?? DEFAULT_API_URL4,
3015
+ timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT4,
4756
3016
  retryConfig: clientOrConfig.retryConfig,
4757
3017
  debug: clientOrConfig.debug
4758
3018
  });
@@ -4764,7 +3024,7 @@ var BaseRouter = class extends APIResource {
4764
3024
  super(resolveClient2(clientOrConfig));
4765
3025
  this.provider = provider;
4766
3026
  const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
4767
- this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT6;
3027
+ this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT4;
4768
3028
  }
4769
3029
  /** Throw the historical "API key is required" message when no key is resolvable. */
4770
3030
  requireApiKey() {
@@ -4870,7 +3130,7 @@ var RouterClassifier = class extends APIResource {
4870
3130
  constructor(clientOrConfig = {}) {
4871
3131
  super(resolveClient2(clientOrConfig));
4872
3132
  const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
4873
- this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT6;
3133
+ this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT4;
4874
3134
  }
4875
3135
  /** Classify an input across the requested axes (all three by default). */
4876
3136
  async classify(input) {
@@ -4928,7 +3188,7 @@ var TOOL_PARAMETERS = {
4928
3188
  required: ["search_term"]
4929
3189
  };
4930
3190
  function createWarpGrepTool(config) {
4931
- const tool5 = {
3191
+ const tool4 = {
4932
3192
  type: "function",
4933
3193
  function: {
4934
3194
  name: config.name ?? WARP_GREP_TOOL_NAME,
@@ -4936,7 +3196,7 @@ function createWarpGrepTool(config) {
4936
3196
  parameters: TOOL_PARAMETERS
4937
3197
  }
4938
3198
  };
4939
- return Object.assign(tool5, {
3199
+ return Object.assign(tool4, {
4940
3200
  execute: async (input) => {
4941
3201
  return executeToolCall(input, config);
4942
3202
  },
@@ -4947,7 +3207,7 @@ function createWarpGrepTool(config) {
4947
3207
  }
4948
3208
  function createGitHubSearchTool(config) {
4949
3209
  const client = new WarpGrepClient(config);
4950
- const tool5 = {
3210
+ const tool4 = {
4951
3211
  type: "function",
4952
3212
  function: {
4953
3213
  name: GITHUB_SEARCH_TOOL_NAME,
@@ -4955,7 +3215,7 @@ function createGitHubSearchTool(config) {
4955
3215
  parameters: GITHUB_SEARCH_INPUT_SCHEMA
4956
3216
  }
4957
3217
  };
4958
- return Object.assign(tool5, {
3218
+ return Object.assign(tool4, {
4959
3219
  execute: async (input) => {
4960
3220
  const github = input.github_url || input.owner_repo;
4961
3221
  if (!github) {
@@ -4969,107 +3229,6 @@ function createGitHubSearchTool(config) {
4969
3229
  });
4970
3230
  }
4971
3231
 
4972
- // tools/codebase_search/prompts.ts
4973
- var CODEBASE_SEARCH_DESCRIPTION = `Semantic search that finds code by meaning, not exact text.
4974
-
4975
- Use this to explore unfamiliar codebases or ask "how/where/what" questions:
4976
- - "How does X work?" - Find implementation details
4977
- - "Where is Y handled?" - Locate specific functionality
4978
- - "What happens when Z?" - Understand flow
4979
-
4980
- The tool uses two-stage retrieval (embedding similarity + reranking) to find the most semantically relevant code chunks.
4981
-
4982
- Returns code chunks with file paths, line ranges, and full content ranked by relevance.`;
4983
- var CODEBASE_SEARCH_SYSTEM_PROMPT = `You have access to the codebase_search tool that performs semantic code search.
4984
-
4985
- When searching:
4986
- - Use natural language queries describing what you're looking for
4987
- - Be specific about functionality, not variable names
4988
- - Use target_directories to narrow search if you know the area
4989
- - Results are ranked by relevance (rerank score is most important)
4990
-
4991
- The tool returns:
4992
- - File paths with symbol names (e.g. "src/auth.ts::AuthService@L1-L17")
4993
- - Line ranges for precise navigation
4994
- - Full code content for each match
4995
- - Dual relevance scores: embedding similarity + rerank score
4996
-
4997
- Use results to understand code or answer questions. The content is provided in full - avoid re-reading unless you need more context.`;
4998
-
4999
- // tools/codebase_search/openai.ts
5000
- function createCodebaseSearchTool(config) {
5001
- const toolDefinition = {
5002
- type: "function",
5003
- function: {
5004
- name: "codebase_search",
5005
- description: CODEBASE_SEARCH_DESCRIPTION,
5006
- parameters: {
5007
- type: "object",
5008
- properties: {
5009
- query: {
5010
- type: "string",
5011
- description: 'A complete question about what you want to understand. Ask as if talking to a colleague: "How does X work?", "What happens when Y?", "Where is Z handled?"'
5012
- },
5013
- target_directories: {
5014
- type: "array",
5015
- items: { type: "string" },
5016
- description: "Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo."
5017
- },
5018
- explanation: {
5019
- type: "string",
5020
- description: "One sentence explanation as to why this tool is being used, and how it contributes to the goal."
5021
- },
5022
- limit: {
5023
- type: "number",
5024
- description: "Maximum results to return (default: 10)"
5025
- }
5026
- },
5027
- required: ["query", "target_directories", "explanation"]
5028
- }
5029
- }
5030
- };
5031
- return Object.assign(toolDefinition, {
5032
- execute: async (input) => {
5033
- const parsedInput = typeof input === "string" ? JSON.parse(input) : input;
5034
- return executeCodebaseSearch(parsedInput, config);
5035
- },
5036
- formatResult: (result) => {
5037
- return formatResult2(result);
5038
- },
5039
- getSystemPrompt: () => {
5040
- return CODEBASE_SEARCH_SYSTEM_PROMPT;
5041
- }
5042
- });
5043
- }
5044
- function formatResult2(result) {
5045
- if (!result.success) {
5046
- return `Search failed: ${result.error}`;
5047
- }
5048
- if (result.results.length === 0) {
5049
- return "No matching code found. Try rephrasing your query or removing directory filters.";
5050
- }
5051
- const lines = [];
5052
- lines.push(`Found ${result.results.length} relevant code sections (${result.stats.searchTimeMs}ms):
5053
- `);
5054
- result.results.forEach((r, i) => {
5055
- const relevance = (r.rerankScore * 100).toFixed(1);
5056
- lines.push(`${i + 1}. ${r.filepath} (${relevance}% relevant)`);
5057
- lines.push(` Symbol: ${r.symbolPath}`);
5058
- lines.push(` Language: ${r.language}`);
5059
- lines.push(` Lines: ${r.startLine}-${r.endLine}`);
5060
- lines.push(` Code:`);
5061
- const codeLines = r.content.split("\n");
5062
- codeLines.slice(0, Math.min(codeLines.length, 20)).forEach((line) => {
5063
- lines.push(` ${line}`);
5064
- });
5065
- if (codeLines.length > 20) {
5066
- lines.push(` ... (${codeLines.length - 20} more lines)`);
5067
- }
5068
- lines.push("");
5069
- });
5070
- return lines.join("\n");
5071
- }
5072
-
5073
3232
  // tools/fastapply/prompts.ts
5074
3233
  var EDIT_FILE_TOOL_DESCRIPTION = `Use this tool to make an edit to an existing file.
5075
3234
 
@@ -5140,7 +3299,7 @@ async function execute(input, config) {
5140
3299
  function getSystemPrompt() {
5141
3300
  return EDIT_FILE_SYSTEM_PROMPT;
5142
3301
  }
5143
- function formatResult3(result) {
3302
+ function formatResult2(result) {
5144
3303
  if (!result.success) {
5145
3304
  return `Error editing file: ${result.error}`;
5146
3305
  }
@@ -5163,7 +3322,7 @@ function createEditFileTool(config = {}) {
5163
3322
  return execute(parsedInput, config);
5164
3323
  },
5165
3324
  formatResult: (result) => {
5166
- return formatResult3(result);
3325
+ return formatResult2(result);
5167
3326
  },
5168
3327
  getSystemPrompt: () => {
5169
3328
  return getSystemPrompt();
@@ -5188,18 +3347,6 @@ var OpenAIToolFactory = class {
5188
3347
  morphApiKey: this.config.apiKey
5189
3348
  });
5190
3349
  }
5191
- /**
5192
- * Create an OpenAI-compatible codebase search tool
5193
- *
5194
- * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)
5195
- * @returns OpenAI ChatCompletionTool with execute and formatResult methods
5196
- */
5197
- createCodebaseSearchTool(toolConfig) {
5198
- return createCodebaseSearchTool({
5199
- ...toolConfig,
5200
- apiKey: this.config.apiKey
5201
- });
5202
- }
5203
3350
  /**
5204
3351
  * Create an OpenAI-compatible edit file tool
5205
3352
  *
@@ -5235,12 +3382,12 @@ var INPUT_SCHEMA = {
5235
3382
  required: ["search_term"]
5236
3383
  };
5237
3384
  function createWarpGrepTool2(config) {
5238
- const tool5 = {
3385
+ const tool4 = {
5239
3386
  name: config.name ?? WARP_GREP_TOOL_NAME,
5240
3387
  description: config.description ?? WARP_GREP_DESCRIPTION,
5241
3388
  input_schema: INPUT_SCHEMA
5242
3389
  };
5243
- return Object.assign(tool5, {
3390
+ return Object.assign(tool4, {
5244
3391
  execute: async (input) => {
5245
3392
  return executeToolCall(input, config);
5246
3393
  },
@@ -5251,12 +3398,12 @@ function createWarpGrepTool2(config) {
5251
3398
  }
5252
3399
  function createGitHubSearchTool2(config) {
5253
3400
  const client = new WarpGrepClient(config);
5254
- const tool5 = {
3401
+ const tool4 = {
5255
3402
  name: GITHUB_SEARCH_TOOL_NAME,
5256
3403
  description: GITHUB_SEARCH_DESCRIPTION,
5257
3404
  input_schema: GITHUB_SEARCH_INPUT_SCHEMA
5258
3405
  };
5259
- return Object.assign(tool5, {
3406
+ return Object.assign(tool4, {
5260
3407
  execute: async (input) => {
5261
3408
  const github = input.github_url || input.owner_repo;
5262
3409
  if (!github) {
@@ -5270,77 +3417,6 @@ function createGitHubSearchTool2(config) {
5270
3417
  });
5271
3418
  }
5272
3419
 
5273
- // tools/codebase_search/anthropic.ts
5274
- function createCodebaseSearchTool2(config) {
5275
- const toolDefinition = {
5276
- name: "codebase_search",
5277
- description: CODEBASE_SEARCH_DESCRIPTION,
5278
- input_schema: {
5279
- type: "object",
5280
- properties: {
5281
- explanation: {
5282
- type: "string",
5283
- description: "One sentence explanation as to why this tool is being used, and how it contributes to the goal."
5284
- },
5285
- query: {
5286
- type: "string",
5287
- description: 'A complete question about what you want to understand. Ask as if talking to a colleague: "How does X work?", "What happens when Y?", "Where is Z handled?"'
5288
- },
5289
- target_directories: {
5290
- type: "array",
5291
- items: { type: "string" },
5292
- description: "Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo."
5293
- },
5294
- limit: {
5295
- type: "number",
5296
- description: "Maximum results to return (default: 10)"
5297
- }
5298
- },
5299
- required: ["query", "target_directories", "explanation"]
5300
- },
5301
- cache_control: { type: "ephemeral" }
5302
- };
5303
- return Object.assign(toolDefinition, {
5304
- execute: async (input) => {
5305
- return executeCodebaseSearch(input, config);
5306
- },
5307
- formatResult: (result) => {
5308
- return formatResult4(result);
5309
- },
5310
- getSystemPrompt: () => {
5311
- return CODEBASE_SEARCH_SYSTEM_PROMPT;
5312
- }
5313
- });
5314
- }
5315
- function formatResult4(result) {
5316
- if (!result.success) {
5317
- return `Search failed: ${result.error}`;
5318
- }
5319
- if (result.results.length === 0) {
5320
- return "No matching code found. Try rephrasing your query or broadening the search scope.";
5321
- }
5322
- const lines = [];
5323
- lines.push(`Found ${result.results.length} relevant code sections (searched ${result.stats.candidatesRetrieved} candidates in ${result.stats.searchTimeMs}ms):
5324
- `);
5325
- result.results.forEach((r, i) => {
5326
- const relevance = (r.rerankScore * 100).toFixed(1);
5327
- lines.push(`${i + 1}. ${r.filepath} (${relevance}% relevant)`);
5328
- lines.push(` Symbol: ${r.symbolPath}`);
5329
- lines.push(` Language: ${r.language}`);
5330
- lines.push(` Lines: ${r.startLine}-${r.endLine}`);
5331
- lines.push(` Code:`);
5332
- const codeLines = r.content.split("\n");
5333
- codeLines.slice(0, Math.min(codeLines.length, 20)).forEach((line) => {
5334
- lines.push(` ${line}`);
5335
- });
5336
- if (codeLines.length > 20) {
5337
- lines.push(` ... (${codeLines.length - 20} more lines)`);
5338
- }
5339
- lines.push("");
5340
- });
5341
- return lines.join("\n");
5342
- }
5343
-
5344
3420
  // tools/fastapply/anthropic.ts
5345
3421
  var editFileTool2 = {
5346
3422
  name: "edit_file",
@@ -5364,7 +3440,7 @@ var editFileTool2 = {
5364
3440
  required: ["target_filepath", "instruction", "code_edit"]
5365
3441
  }
5366
3442
  };
5367
- function formatResult5(result) {
3443
+ function formatResult3(result) {
5368
3444
  if (!result.success) {
5369
3445
  return `Error editing file: ${result.error}`;
5370
3446
  }
@@ -5381,7 +3457,7 @@ function createEditFileTool2(config = {}) {
5381
3457
  return executeEditFile(input, config);
5382
3458
  },
5383
3459
  formatResult: (result) => {
5384
- return formatResult5(result);
3460
+ return formatResult3(result);
5385
3461
  },
5386
3462
  getSystemPrompt: () => {
5387
3463
  return EDIT_FILE_SYSTEM_PROMPT;
@@ -5747,18 +3823,6 @@ var AnthropicToolFactory = class {
5747
3823
  morphApiKey: this.config.apiKey
5748
3824
  });
5749
3825
  }
5750
- /**
5751
- * Create an Anthropic-compatible codebase search tool
5752
- *
5753
- * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)
5754
- * @returns Anthropic Tool with execute and formatResult methods
5755
- */
5756
- createCodebaseSearchTool(toolConfig) {
5757
- return createCodebaseSearchTool2({
5758
- ...toolConfig,
5759
- apiKey: this.config.apiKey
5760
- });
5761
- }
5762
3826
  /**
5763
3827
  * Create an Anthropic-compatible edit file tool
5764
3828
  *
@@ -5860,56 +3924,15 @@ function createGitHubSearchTool3(config) {
5860
3924
  });
5861
3925
  }
5862
3926
 
5863
- // tools/codebase_search/vercel.ts
3927
+ // tools/fastapply/vercel.ts
5864
3928
  var import_ai2 = require("ai");
5865
3929
  var import_zod2 = require("zod");
5866
- function createCodebaseSearchTool3(config) {
5867
- const schema = import_zod2.z.object({
5868
- query: import_zod2.z.string().describe('A complete question about what you want to understand. Ask as if talking to a colleague: "How does X work?", "What happens when Y?", "Where is Z handled?"'),
5869
- target_directories: import_zod2.z.array(import_zod2.z.string()).describe("Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo."),
5870
- explanation: import_zod2.z.string().describe("One sentence explanation as to why this tool is being used, and how it contributes to the goal."),
5871
- limit: import_zod2.z.number().optional().describe("Max results to return (default: 10)")
5872
- });
5873
- return (0, import_ai2.tool)({
5874
- description: CODEBASE_SEARCH_DESCRIPTION,
5875
- inputSchema: schema,
5876
- execute: async (params) => {
5877
- const { query, target_directories, explanation, limit } = params;
5878
- const result = await executeCodebaseSearch(
5879
- { query, target_directories, explanation, limit },
5880
- config
5881
- );
5882
- if (!result.success) {
5883
- return {
5884
- error: result.error,
5885
- results: []
5886
- };
5887
- }
5888
- return {
5889
- found: result.results.length,
5890
- searchTime: `${result.stats.searchTimeMs}ms`,
5891
- results: result.results.map((r) => ({
5892
- file: r.filepath,
5893
- symbol: r.symbolPath,
5894
- lines: `${r.startLine}-${r.endLine}`,
5895
- language: r.language,
5896
- relevance: `${(r.rerankScore * 100).toFixed(1)}%`,
5897
- code: r.content
5898
- }))
5899
- };
5900
- }
5901
- });
5902
- }
5903
-
5904
- // tools/fastapply/vercel.ts
5905
- var import_ai3 = require("ai");
5906
- var import_zod3 = require("zod");
5907
- var editFileSchema = import_zod3.z.object({
5908
- target_filepath: import_zod3.z.string().describe("The path of the target file to modify"),
5909
- instruction: import_zod3.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
5910
- code_edit: import_zod3.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
3930
+ var editFileSchema = import_zod2.z.object({
3931
+ target_filepath: import_zod2.z.string().describe("The path of the target file to modify"),
3932
+ instruction: import_zod2.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
3933
+ code_edit: import_zod2.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
5911
3934
  });
5912
- var editFileTool3 = (0, import_ai3.tool)({
3935
+ var editFileTool3 = (0, import_ai2.tool)({
5913
3936
  description: EDIT_FILE_TOOL_DESCRIPTION,
5914
3937
  inputSchema: editFileSchema,
5915
3938
  execute: async (params) => {
@@ -5930,12 +3953,12 @@ var editFileTool3 = (0, import_ai3.tool)({
5930
3953
  }
5931
3954
  });
5932
3955
  function createEditFileTool3(config = {}) {
5933
- const schema = import_zod3.z.object({
5934
- target_filepath: import_zod3.z.string().describe("The path of the target file to modify"),
5935
- instruction: import_zod3.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
5936
- code_edit: import_zod3.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
3956
+ const schema = import_zod2.z.object({
3957
+ target_filepath: import_zod2.z.string().describe("The path of the target file to modify"),
3958
+ instruction: import_zod2.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
3959
+ code_edit: import_zod2.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
5937
3960
  });
5938
- return (0, import_ai3.tool)({
3961
+ return (0, import_ai2.tool)({
5939
3962
  description: config.description || EDIT_FILE_TOOL_DESCRIPTION,
5940
3963
  inputSchema: schema,
5941
3964
  execute: async (params) => {
@@ -5961,8 +3984,8 @@ function createEditFileTool3(config = {}) {
5961
3984
  }
5962
3985
 
5963
3986
  // subagents/vercel.ts
5964
- var import_ai4 = require("ai");
5965
- var import_zod4 = require("zod");
3987
+ var import_ai3 = require("ai");
3988
+ var import_zod3 = require("zod");
5966
3989
  var DEFAULT_MAX_TURNS2 = {
5967
3990
  quick: 3,
5968
3991
  medium: 6,
@@ -5990,18 +4013,18 @@ function createExploreSubagent2(config) {
5990
4013
  ) : null;
5991
4014
  const runPromise = (async () => {
5992
4015
  try {
5993
- const codebaseSearchSchema = import_zod4.z.object({
5994
- searchRequest: import_zod4.z.string().describe("Natural language description of what to search for")
4016
+ const codebaseSearchSchema = import_zod3.z.object({
4017
+ searchRequest: import_zod3.z.string().describe("Natural language description of what to search for")
5995
4018
  });
5996
- const sendMessageSchema = import_zod4.z.object({
5997
- message: import_zod4.z.string().describe("The message to send to the orchestrator")
4019
+ const sendMessageSchema = import_zod3.z.object({
4020
+ message: import_zod3.z.string().describe("The message to send to the orchestrator")
5998
4021
  });
5999
- const result = await (0, import_ai4.generateText)({
4022
+ const result = await (0, import_ai3.generateText)({
6000
4023
  model: config.model,
6001
4024
  system: getSystemPrompt2(thoroughness),
6002
4025
  prompt,
6003
4026
  tools: {
6004
- codebase_search: (0, import_ai4.tool)({
4027
+ codebase_search: (0, import_ai3.tool)({
6005
4028
  description: CODEBASE_SEARCH_TOOL.description,
6006
4029
  inputSchema: codebaseSearchSchema,
6007
4030
  execute: async (params) => {
@@ -6024,7 +4047,7 @@ function createExploreSubagent2(config) {
6024
4047
  return formatResult(warpResult);
6025
4048
  }
6026
4049
  }),
6027
- send_message: (0, import_ai4.tool)({
4050
+ send_message: (0, import_ai3.tool)({
6028
4051
  description: SEND_MESSAGE_TOOL.description,
6029
4052
  inputSchema: sendMessageSchema,
6030
4053
  execute: async (params) => {
@@ -6055,7 +4078,7 @@ function createExploreSubagent2(config) {
6055
4078
  }
6056
4079
  })
6057
4080
  },
6058
- stopWhen: (0, import_ai4.stepCountIs)(getMaxTurns2(config))
4081
+ stopWhen: (0, import_ai3.stepCountIs)(getMaxTurns2(config))
6059
4082
  });
6060
4083
  callbacks.onStep?.({
6061
4084
  step: searchCount,
@@ -6098,10 +4121,10 @@ function createExploreSubagent2(config) {
6098
4121
  }
6099
4122
  return runPromise;
6100
4123
  }
6101
- const exploreToolSchema = import_zod4.z.object({
6102
- searchRequest: import_zod4.z.string().describe("What to explore in the codebase. Be specific about what you want to understand.")
4124
+ const exploreToolSchema = import_zod3.z.object({
4125
+ searchRequest: import_zod3.z.string().describe("What to explore in the codebase. Be specific about what you want to understand.")
6103
4126
  });
6104
- const exploreTool = (0, import_ai4.tool)({
4127
+ const exploreTool = (0, import_ai3.tool)({
6105
4128
  description: "Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings. Use this for broad exploration rather than pinpoint keyword searches.",
6106
4129
  inputSchema: exploreToolSchema,
6107
4130
  execute: async (params) => {
@@ -6228,18 +4251,6 @@ var VercelToolFactory = class {
6228
4251
  morphApiKey: this.config.apiKey
6229
4252
  });
6230
4253
  }
6231
- /**
6232
- * Create a Vercel AI SDK-compatible codebase search tool
6233
- *
6234
- * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)
6235
- * @returns Vercel AI SDK tool
6236
- */
6237
- createCodebaseSearchTool(toolConfig) {
6238
- return createCodebaseSearchTool3({
6239
- ...toolConfig,
6240
- apiKey: this.config.apiKey
6241
- });
6242
- }
6243
4254
  /**
6244
4255
  * Create a Vercel AI SDK-compatible edit file tool
6245
4256
  *
@@ -6284,14 +4295,8 @@ var MorphClient = class extends MorphAPIClient {
6284
4295
  config;
6285
4296
  /** FastApply tool for editing files with AI-powered merge */
6286
4297
  fastApply;
6287
- /** CodebaseSearch tool for semantic code search */
6288
- codebaseSearch;
6289
4298
  /** WarpGrep tool for fast code search using ripgrep */
6290
4299
  warpGrep;
6291
- /** Browser tool for AI-powered browser automation */
6292
- browser;
6293
- /** GitHub tool for PR context, comments, and check runs */
6294
- github;
6295
4300
  /** Model routers for intelligent model selection */
6296
4301
  routers;
6297
4302
  /** OpenAI-compatible tool factories */
@@ -6329,10 +4334,7 @@ var MorphClient = class extends MorphAPIClient {
6329
4334
  this.config = config;
6330
4335
  logger.debug("MorphClient", "initialized", { debug: !!config.debug, timeout: config.timeout });
6331
4336
  this.fastApply = new FastApplyClient(this);
6332
- this.codebaseSearch = new CodebaseSearchClient(this);
6333
4337
  this.warpGrep = new WarpGrepClient(this);
6334
- this.browser = new BrowserClient(this);
6335
- this.github = new GitHubClient(this, { installationId: config.github?.installationId });
6336
4338
  this.routers = {
6337
4339
  openai: new OpenAIRouter(this),
6338
4340
  anthropic: new AnthropicRouter(this),