@morphllm/morphsdk 0.2.198 → 0.2.199

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/README.md +1 -147
  2. package/dist/{chunk-CAFREMIT.js → chunk-5KQ2WRBU.js} +2 -2
  3. package/dist/{chunk-FUYX2MNM.js → chunk-7UU4NF4G.js} +4 -10
  4. package/dist/chunk-7UU4NF4G.js.map +1 -0
  5. package/dist/{chunk-XTFRHVCW.js → chunk-BLCCGRKT.js} +2 -2
  6. package/dist/{chunk-6XFL2NER.js → chunk-BTMMUG3E.js} +2 -2
  7. package/dist/{chunk-4JUIEYAH.js → chunk-CEXBKXWU.js} +3 -3
  8. package/dist/{chunk-FESO6TDQ.js → chunk-DP2PT36G.js} +2 -2
  9. package/dist/chunk-GKRPR5PZ.js +322 -0
  10. package/dist/chunk-GKRPR5PZ.js.map +1 -0
  11. package/dist/{chunk-ZQNTXHBQ.js → chunk-GTV27THY.js} +2 -2
  12. package/dist/{chunk-ZU5YYGBJ.js → chunk-JOC3ZI56.js} +3 -29
  13. package/dist/chunk-JOC3ZI56.js.map +1 -0
  14. package/dist/{chunk-WLMPQFER.js → chunk-K2JR2NFQ.js} +4 -4
  15. package/dist/{chunk-YQ2G5YLI.js → chunk-KXEPBLVD.js} +10 -10
  16. package/dist/{chunk-T6TXYTKH.js → chunk-MEZTHMB2.js} +4 -4
  17. package/dist/{chunk-ZGERT23F.js → chunk-O7LJEVZO.js} +2 -2
  18. package/dist/{chunk-LN7GNFET.js → chunk-OPNTDMHH.js} +4 -4
  19. package/dist/{chunk-QKNGVBE2.js → chunk-PKJ7ODTG.js} +3 -3
  20. package/dist/{chunk-4DNEBVGV.js → chunk-PW6K6OJL.js} +2 -2
  21. package/dist/{chunk-PV6EF6NG.js → chunk-Q3NH3NPD.js} +2 -2
  22. package/dist/{chunk-O5264GI4.js → chunk-RL3ZTXT3.js} +4 -4
  23. package/dist/{chunk-D2RFP6R2.js → chunk-ULHHMZRL.js} +3 -3
  24. package/dist/{chunk-PEFXG5M6.js → chunk-UT3NQLCF.js} +2 -2
  25. package/dist/{chunk-VBZ7BG47.js → chunk-VS5F2ORN.js} +3 -3
  26. package/dist/{chunk-YUH3MTP3.js → chunk-W37OFBSG.js} +2 -2
  27. package/dist/{chunk-SKN2L5CE.js → chunk-WDBYAXZ5.js} +2 -2
  28. package/dist/{chunk-XK3PQZW6.js → chunk-YSFEKIYQ.js} +2 -2
  29. package/dist/{chunk-3XS5P5XH.js → chunk-ZHB57ORD.js} +6 -6
  30. package/dist/client-CGW0Cevz.d.ts +402 -0
  31. package/dist/client.cjs +12 -1644
  32. package/dist/client.cjs.map +1 -1
  33. package/dist/client.d.ts +3 -7
  34. package/dist/client.js +27 -32
  35. package/dist/core/client.cjs +2 -34
  36. package/dist/core/client.cjs.map +1 -1
  37. package/dist/core/client.d.ts +0 -8
  38. package/dist/core/client.js +4 -4
  39. package/dist/core/error.cjs +2 -28
  40. package/dist/core/error.cjs.map +1 -1
  41. package/dist/core/error.js +3 -3
  42. package/dist/core/index.cjs +2 -34
  43. package/dist/core/index.cjs.map +1 -1
  44. package/dist/core/index.js +4 -4
  45. package/dist/edge.cjs +2 -34
  46. package/dist/edge.cjs.map +1 -1
  47. package/dist/edge.js +7 -7
  48. package/dist/index.cjs +12 -1656
  49. package/dist/index.cjs.map +1 -1
  50. package/dist/index.d.ts +1 -5
  51. package/dist/index.js +31 -49
  52. package/dist/modelrouter/core.cjs +2 -34
  53. package/dist/modelrouter/core.cjs.map +1 -1
  54. package/dist/modelrouter/core.js +5 -5
  55. package/dist/modelrouter/index.cjs +2 -34
  56. package/dist/modelrouter/index.cjs.map +1 -1
  57. package/dist/modelrouter/index.js +5 -5
  58. package/dist/subagents/anthropic.cjs +2 -34
  59. package/dist/subagents/anthropic.cjs.map +1 -1
  60. package/dist/subagents/anthropic.js +11 -11
  61. package/dist/subagents/vercel.cjs +2 -34
  62. package/dist/subagents/vercel.cjs.map +1 -1
  63. package/dist/subagents/vercel.js +11 -11
  64. package/dist/tools/codebase_search/anthropic.cjs +2 -34
  65. package/dist/tools/codebase_search/anthropic.cjs.map +1 -1
  66. package/dist/tools/codebase_search/anthropic.js +6 -6
  67. package/dist/tools/codebase_search/core.cjs +2 -34
  68. package/dist/tools/codebase_search/core.cjs.map +1 -1
  69. package/dist/tools/codebase_search/core.js +5 -5
  70. package/dist/tools/codebase_search/index.cjs +2 -34
  71. package/dist/tools/codebase_search/index.cjs.map +1 -1
  72. package/dist/tools/codebase_search/index.js +10 -10
  73. package/dist/tools/codebase_search/openai.cjs +2 -34
  74. package/dist/tools/codebase_search/openai.cjs.map +1 -1
  75. package/dist/tools/codebase_search/openai.js +6 -6
  76. package/dist/tools/codebase_search/vercel.cjs +2 -34
  77. package/dist/tools/codebase_search/vercel.cjs.map +1 -1
  78. package/dist/tools/codebase_search/vercel.js +6 -6
  79. package/dist/tools/compact/core.cjs +2 -34
  80. package/dist/tools/compact/core.cjs.map +1 -1
  81. package/dist/tools/compact/core.js +5 -5
  82. package/dist/tools/compact/index.cjs +2 -34
  83. package/dist/tools/compact/index.cjs.map +1 -1
  84. package/dist/tools/compact/index.js +6 -6
  85. package/dist/tools/fastapply/anthropic.cjs +2 -28
  86. package/dist/tools/fastapply/anthropic.cjs.map +1 -1
  87. package/dist/tools/fastapply/anthropic.js +7 -7
  88. package/dist/tools/fastapply/apply.cjs +2 -28
  89. package/dist/tools/fastapply/apply.cjs.map +1 -1
  90. package/dist/tools/fastapply/apply.js +2 -2
  91. package/dist/tools/fastapply/core.cjs +2 -34
  92. package/dist/tools/fastapply/core.cjs.map +1 -1
  93. package/dist/tools/fastapply/core.js +6 -6
  94. package/dist/tools/fastapply/index.cjs +2 -28
  95. package/dist/tools/fastapply/index.cjs.map +1 -1
  96. package/dist/tools/fastapply/index.js +11 -11
  97. package/dist/tools/fastapply/openai.cjs +2 -28
  98. package/dist/tools/fastapply/openai.cjs.map +1 -1
  99. package/dist/tools/fastapply/openai.js +7 -7
  100. package/dist/tools/fastapply/vercel.cjs +2 -28
  101. package/dist/tools/fastapply/vercel.cjs.map +1 -1
  102. package/dist/tools/fastapply/vercel.js +7 -7
  103. package/dist/tools/index.cjs +2 -28
  104. package/dist/tools/index.cjs.map +1 -1
  105. package/dist/tools/index.js +11 -11
  106. package/dist/tools/utils/resilience.cjs +2 -28
  107. package/dist/tools/utils/resilience.cjs.map +1 -1
  108. package/dist/tools/utils/resilience.js +2 -2
  109. package/dist/tools/warp_grep/agent/runner.cjs +2 -28
  110. package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
  111. package/dist/tools/warp_grep/agent/runner.js +3 -3
  112. package/dist/tools/warp_grep/anthropic.cjs +2 -34
  113. package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
  114. package/dist/tools/warp_grep/anthropic.js +11 -11
  115. package/dist/tools/warp_grep/client.cjs +2 -34
  116. package/dist/tools/warp_grep/client.cjs.map +1 -1
  117. package/dist/tools/warp_grep/client.js +10 -10
  118. package/dist/tools/warp_grep/gemini.cjs +2 -34
  119. package/dist/tools/warp_grep/gemini.cjs.map +1 -1
  120. package/dist/tools/warp_grep/gemini.js +10 -10
  121. package/dist/tools/warp_grep/harness.js +9 -9
  122. package/dist/tools/warp_grep/index.cjs +2 -34
  123. package/dist/tools/warp_grep/index.cjs.map +1 -1
  124. package/dist/tools/warp_grep/index.js +16 -16
  125. package/dist/tools/warp_grep/openai.cjs +2 -34
  126. package/dist/tools/warp_grep/openai.cjs.map +1 -1
  127. package/dist/tools/warp_grep/openai.js +11 -11
  128. package/dist/tools/warp_grep/providers/local.js +2 -2
  129. package/dist/tools/warp_grep/vercel.cjs +2 -34
  130. package/dist/tools/warp_grep/vercel.cjs.map +1 -1
  131. package/dist/tools/warp_grep/vercel.js +11 -11
  132. package/dist/version.cjs +2 -28
  133. package/dist/version.cjs.map +1 -1
  134. package/dist/version.js +1 -1
  135. package/package.json +2 -28
  136. package/dist/anthropic-B6my2oBx.d.ts +0 -56
  137. package/dist/chunk-2AMEQAO2.js +0 -46
  138. package/dist/chunk-2AMEQAO2.js.map +0 -1
  139. package/dist/chunk-2HMEZZKK.js +0 -44
  140. package/dist/chunk-2HMEZZKK.js.map +0 -1
  141. package/dist/chunk-2VERUKO2.js +0 -177
  142. package/dist/chunk-2VERUKO2.js.map +0 -1
  143. package/dist/chunk-FUYX2MNM.js.map +0 -1
  144. package/dist/chunk-GJ42MYUU.js +0 -57
  145. package/dist/chunk-GJ42MYUU.js.map +0 -1
  146. package/dist/chunk-KQKLQHJF.js +0 -96
  147. package/dist/chunk-KQKLQHJF.js.map +0 -1
  148. package/dist/chunk-PIIXU2H3.js +0 -389
  149. package/dist/chunk-PIIXU2H3.js.map +0 -1
  150. package/dist/chunk-XH6KJJDI.js +0 -80
  151. package/dist/chunk-XH6KJJDI.js.map +0 -1
  152. package/dist/chunk-YD6TNDR4.js +0 -622
  153. package/dist/chunk-YD6TNDR4.js.map +0 -1
  154. package/dist/chunk-YHZJYCOU.js +0 -680
  155. package/dist/chunk-YHZJYCOU.js.map +0 -1
  156. package/dist/chunk-YTYCHRQ2.js +0 -106
  157. package/dist/chunk-YTYCHRQ2.js.map +0 -1
  158. package/dist/chunk-ZU5YYGBJ.js.map +0 -1
  159. package/dist/client-DCeydotn.d.ts +0 -1015
  160. package/dist/openai-BQMeDFef.d.ts +0 -81
  161. package/dist/tools/browser/anthropic.cjs +0 -645
  162. package/dist/tools/browser/anthropic.cjs.map +0 -1
  163. package/dist/tools/browser/anthropic.d.ts +0 -4
  164. package/dist/tools/browser/anthropic.js +0 -22
  165. package/dist/tools/browser/anthropic.js.map +0 -1
  166. package/dist/tools/browser/core.cjs +0 -1821
  167. package/dist/tools/browser/core.cjs.map +0 -1
  168. package/dist/tools/browser/core.d.ts +0 -245
  169. package/dist/tools/browser/core.js +0 -32
  170. package/dist/tools/browser/core.js.map +0 -1
  171. package/dist/tools/browser/errors.cjs +0 -208
  172. package/dist/tools/browser/errors.cjs.map +0 -1
  173. package/dist/tools/browser/errors.d.ts +0 -158
  174. package/dist/tools/browser/errors.js +0 -22
  175. package/dist/tools/browser/errors.js.map +0 -1
  176. package/dist/tools/browser/index.cjs +0 -2159
  177. package/dist/tools/browser/index.cjs.map +0 -1
  178. package/dist/tools/browser/index.d.ts +0 -134
  179. package/dist/tools/browser/index.js +0 -163
  180. package/dist/tools/browser/index.js.map +0 -1
  181. package/dist/tools/browser/live.cjs +0 -134
  182. package/dist/tools/browser/live.cjs.map +0 -1
  183. package/dist/tools/browser/live.d.ts +0 -75
  184. package/dist/tools/browser/live.js +0 -16
  185. package/dist/tools/browser/live.js.map +0 -1
  186. package/dist/tools/browser/openai.cjs +0 -661
  187. package/dist/tools/browser/openai.cjs.map +0 -1
  188. package/dist/tools/browser/openai.d.ts +0 -4
  189. package/dist/tools/browser/openai.js +0 -28
  190. package/dist/tools/browser/openai.js.map +0 -1
  191. package/dist/tools/browser/profiles/core.cjs +0 -932
  192. package/dist/tools/browser/profiles/core.cjs.map +0 -1
  193. package/dist/tools/browser/profiles/core.d.ts +0 -187
  194. package/dist/tools/browser/profiles/core.js +0 -30
  195. package/dist/tools/browser/profiles/core.js.map +0 -1
  196. package/dist/tools/browser/profiles/index.cjs +0 -932
  197. package/dist/tools/browser/profiles/index.cjs.map +0 -1
  198. package/dist/tools/browser/profiles/index.d.ts +0 -4
  199. package/dist/tools/browser/profiles/index.js +0 -30
  200. package/dist/tools/browser/profiles/index.js.map +0 -1
  201. package/dist/tools/browser/profiles/types.cjs +0 -74
  202. package/dist/tools/browser/profiles/types.cjs.map +0 -1
  203. package/dist/tools/browser/profiles/types.d.ts +0 -195
  204. package/dist/tools/browser/profiles/types.js +0 -16
  205. package/dist/tools/browser/profiles/types.js.map +0 -1
  206. package/dist/tools/browser/prompts.cjs +0 -69
  207. package/dist/tools/browser/prompts.cjs.map +0 -1
  208. package/dist/tools/browser/prompts.d.ts +0 -7
  209. package/dist/tools/browser/prompts.js +0 -10
  210. package/dist/tools/browser/prompts.js.map +0 -1
  211. package/dist/tools/browser/types.cjs +0 -19
  212. package/dist/tools/browser/types.cjs.map +0 -1
  213. package/dist/tools/browser/types.d.ts +0 -338
  214. package/dist/tools/browser/types.js +0 -1
  215. package/dist/tools/browser/types.js.map +0 -1
  216. package/dist/tools/browser/vercel.cjs +0 -622
  217. package/dist/tools/browser/vercel.cjs.map +0 -1
  218. package/dist/tools/browser/vercel.d.ts +0 -4
  219. package/dist/tools/browser/vercel.js +0 -22
  220. package/dist/tools/browser/vercel.js.map +0 -1
  221. package/dist/vercel-CVF27qFK.d.ts +0 -74
  222. /package/dist/{chunk-CAFREMIT.js.map → chunk-5KQ2WRBU.js.map} +0 -0
  223. /package/dist/{chunk-XTFRHVCW.js.map → chunk-BLCCGRKT.js.map} +0 -0
  224. /package/dist/{chunk-6XFL2NER.js.map → chunk-BTMMUG3E.js.map} +0 -0
  225. /package/dist/{chunk-4JUIEYAH.js.map → chunk-CEXBKXWU.js.map} +0 -0
  226. /package/dist/{chunk-FESO6TDQ.js.map → chunk-DP2PT36G.js.map} +0 -0
  227. /package/dist/{chunk-ZQNTXHBQ.js.map → chunk-GTV27THY.js.map} +0 -0
  228. /package/dist/{chunk-WLMPQFER.js.map → chunk-K2JR2NFQ.js.map} +0 -0
  229. /package/dist/{chunk-YQ2G5YLI.js.map → chunk-KXEPBLVD.js.map} +0 -0
  230. /package/dist/{chunk-T6TXYTKH.js.map → chunk-MEZTHMB2.js.map} +0 -0
  231. /package/dist/{chunk-ZGERT23F.js.map → chunk-O7LJEVZO.js.map} +0 -0
  232. /package/dist/{chunk-LN7GNFET.js.map → chunk-OPNTDMHH.js.map} +0 -0
  233. /package/dist/{chunk-QKNGVBE2.js.map → chunk-PKJ7ODTG.js.map} +0 -0
  234. /package/dist/{chunk-4DNEBVGV.js.map → chunk-PW6K6OJL.js.map} +0 -0
  235. /package/dist/{chunk-PV6EF6NG.js.map → chunk-Q3NH3NPD.js.map} +0 -0
  236. /package/dist/{chunk-O5264GI4.js.map → chunk-RL3ZTXT3.js.map} +0 -0
  237. /package/dist/{chunk-D2RFP6R2.js.map → chunk-ULHHMZRL.js.map} +0 -0
  238. /package/dist/{chunk-PEFXG5M6.js.map → chunk-UT3NQLCF.js.map} +0 -0
  239. /package/dist/{chunk-VBZ7BG47.js.map → chunk-VS5F2ORN.js.map} +0 -0
  240. /package/dist/{chunk-YUH3MTP3.js.map → chunk-W37OFBSG.js.map} +0 -0
  241. /package/dist/{chunk-SKN2L5CE.js.map → chunk-WDBYAXZ5.js.map} +0 -0
  242. /package/dist/{chunk-XK3PQZW6.js.map → chunk-YSFEKIYQ.js.map} +0 -0
  243. /package/dist/{chunk-3XS5P5XH.js.map → chunk-ZHB57ORD.js.map} +0 -0
@@ -1,2159 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // tools/browser/index.ts
31
- var browser_exports = {};
32
- __export(browser_exports, {
33
- BROWSER_SYSTEM_PROMPT: () => BROWSER_SYSTEM_PROMPT,
34
- BROWSER_TOOL_DESCRIPTION: () => BROWSER_TOOL_DESCRIPTION,
35
- BrowserClient: () => BrowserClient,
36
- LIVE_PRESETS: () => LIVE_PRESETS,
37
- MorphAPIError: () => MorphAPIError,
38
- MorphAuthenticationError: () => MorphAuthenticationError,
39
- MorphError: () => MorphError2,
40
- MorphNotFoundError: () => MorphNotFoundError,
41
- MorphProfileLimitError: () => MorphProfileLimitError,
42
- MorphRateLimitError: () => MorphRateLimitError,
43
- MorphValidationError: () => MorphValidationError,
44
- ProfilesClient: () => ProfilesClient,
45
- anthropic: () => anthropic_exports,
46
- buildEmbedCode: () => buildEmbedCode,
47
- buildLiveIframe: () => buildLiveIframe,
48
- buildLiveUrl: () => buildLiveUrl,
49
- checkHealth: () => checkHealth,
50
- executeBrowserTask: () => executeBrowserTask,
51
- executeWithRecording: () => executeWithRecording,
52
- gemini: () => gemini_exports,
53
- getErrors: () => getErrors,
54
- getRecording: () => getRecording,
55
- getWebp: () => getWebp,
56
- openai: () => openai_exports,
57
- parseAPIError: () => parseAPIError,
58
- vercel: () => vercel_exports,
59
- waitForRecording: () => waitForRecording
60
- });
61
- module.exports = __toCommonJS(browser_exports);
62
-
63
- // package.json
64
- var package_default = {
65
- name: "@morphllm/morphsdk",
66
- version: "0.2.198",
67
- description: "TypeScript SDK and CLI for Morph Fast Apply integration",
68
- type: "module",
69
- main: "./dist/index.cjs",
70
- module: "./dist/index.js",
71
- types: "./dist/index.d.ts",
72
- exports: {
73
- ".": {
74
- types: "./dist/index.d.ts",
75
- import: "./dist/index.js",
76
- require: "./dist/index.cjs"
77
- },
78
- "./logger": {
79
- types: "./dist/logger.d.ts",
80
- import: "./dist/logger.js",
81
- require: "./dist/logger.cjs"
82
- },
83
- "./edge": {
84
- types: "./dist/edge.d.ts",
85
- import: "./dist/edge.js",
86
- require: "./dist/edge.cjs"
87
- },
88
- "./tools/warp-grep": {
89
- types: "./dist/tools/warp_grep/index.d.ts",
90
- import: "./dist/tools/warp_grep/index.js",
91
- require: "./dist/tools/warp_grep/index.cjs"
92
- },
93
- "./tools/warp-grep/openai": {
94
- types: "./dist/tools/warp_grep/openai.d.ts",
95
- import: "./dist/tools/warp_grep/openai.js",
96
- require: "./dist/tools/warp_grep/openai.cjs"
97
- },
98
- "./tools/warp-grep/anthropic": {
99
- types: "./dist/tools/warp_grep/anthropic.d.ts",
100
- import: "./dist/tools/warp_grep/anthropic.js",
101
- require: "./dist/tools/warp_grep/anthropic.cjs"
102
- },
103
- "./tools/warp-grep/vercel": {
104
- types: "./dist/tools/warp_grep/vercel.d.ts",
105
- import: "./dist/tools/warp_grep/vercel.js",
106
- require: "./dist/tools/warp_grep/vercel.cjs"
107
- },
108
- "./tools/warp-grep/client": {
109
- types: "./dist/tools/warp_grep/client.d.ts",
110
- import: "./dist/tools/warp_grep/client.js",
111
- require: "./dist/tools/warp_grep/client.cjs"
112
- },
113
- "./tools/warp-grep/gemini": {
114
- types: "./dist/tools/warp_grep/gemini.d.ts",
115
- import: "./dist/tools/warp_grep/gemini.js",
116
- require: "./dist/tools/warp_grep/gemini.cjs"
117
- },
118
- "./tools/warp-grep/harness": {
119
- types: "./dist/tools/warp_grep/harness.d.ts",
120
- import: "./dist/tools/warp_grep/harness.js",
121
- require: "./dist/tools/warp_grep/harness.cjs"
122
- },
123
- "./tracing": {
124
- types: "./dist/tracing/index.d.ts",
125
- import: "./dist/tracing/index.js",
126
- require: "./dist/tracing/index.cjs"
127
- },
128
- "./tracing/otel": {
129
- types: "./dist/tracing/otel.d.ts",
130
- import: "./dist/tracing/otel.js",
131
- require: "./dist/tracing/otel.cjs"
132
- },
133
- "./tools/fastapply": {
134
- types: "./dist/tools/fastapply/index.d.ts",
135
- import: "./dist/tools/fastapply/index.js",
136
- require: "./dist/tools/fastapply/index.cjs"
137
- },
138
- "./tools/fastapply/anthropic": {
139
- types: "./dist/tools/fastapply/anthropic.d.ts",
140
- import: "./dist/tools/fastapply/anthropic.js",
141
- require: "./dist/tools/fastapply/anthropic.cjs"
142
- },
143
- "./tools/fastapply/openai": {
144
- types: "./dist/tools/fastapply/openai.d.ts",
145
- import: "./dist/tools/fastapply/openai.js",
146
- require: "./dist/tools/fastapply/openai.cjs"
147
- },
148
- "./tools/fastapply/vercel": {
149
- types: "./dist/tools/fastapply/vercel.d.ts",
150
- import: "./dist/tools/fastapply/vercel.js",
151
- require: "./dist/tools/fastapply/vercel.cjs"
152
- },
153
- "./tools/codebase-search": {
154
- types: "./dist/tools/codebase_search/index.d.ts",
155
- import: "./dist/tools/codebase_search/index.js",
156
- require: "./dist/tools/codebase_search/index.cjs"
157
- },
158
- "./tools/codebase-search/anthropic": {
159
- types: "./dist/tools/codebase_search/anthropic.d.ts",
160
- import: "./dist/tools/codebase_search/anthropic.js",
161
- require: "./dist/tools/codebase_search/anthropic.cjs"
162
- },
163
- "./tools/codebase-search/openai": {
164
- types: "./dist/tools/codebase_search/openai.d.ts",
165
- import: "./dist/tools/codebase_search/openai.js",
166
- require: "./dist/tools/codebase_search/openai.cjs"
167
- },
168
- "./tools/codebase-search/vercel": {
169
- types: "./dist/tools/codebase_search/vercel.d.ts",
170
- import: "./dist/tools/codebase_search/vercel.js",
171
- require: "./dist/tools/codebase_search/vercel.cjs"
172
- },
173
- "./tools/browser": {
174
- types: "./dist/tools/browser/index.d.ts",
175
- import: "./dist/tools/browser/index.js",
176
- require: "./dist/tools/browser/index.cjs"
177
- },
178
- "./tools/browser/anthropic": {
179
- types: "./dist/tools/browser/anthropic.d.ts",
180
- import: "./dist/tools/browser/anthropic.js",
181
- require: "./dist/tools/browser/anthropic.cjs"
182
- },
183
- "./tools/browser/openai": {
184
- types: "./dist/tools/browser/openai.d.ts",
185
- import: "./dist/tools/browser/openai.js",
186
- require: "./dist/tools/browser/openai.cjs"
187
- },
188
- "./tools/browser/vercel": {
189
- types: "./dist/tools/browser/vercel.d.ts",
190
- import: "./dist/tools/browser/vercel.js",
191
- require: "./dist/tools/browser/vercel.cjs"
192
- },
193
- "./tools/browser/profiles": {
194
- types: "./dist/tools/browser/profiles/index.d.ts",
195
- import: "./dist/tools/browser/profiles/index.js",
196
- require: "./dist/tools/browser/profiles/index.cjs"
197
- },
198
- "./modelrouter": {
199
- types: "./dist/modelrouter/index.d.ts",
200
- import: "./dist/modelrouter/index.js",
201
- require: "./dist/modelrouter/index.cjs"
202
- },
203
- "./tools/compact": {
204
- types: "./dist/tools/compact/index.d.ts",
205
- import: "./dist/tools/compact/index.js",
206
- require: "./dist/tools/compact/index.cjs"
207
- },
208
- "./subagents": {
209
- types: "./dist/subagents/index.d.ts",
210
- import: "./dist/subagents/index.js",
211
- require: "./dist/subagents/index.cjs"
212
- },
213
- "./subagents/vercel": {
214
- types: "./dist/subagents/vercel.d.ts",
215
- import: "./dist/subagents/vercel.js",
216
- require: "./dist/subagents/vercel.cjs"
217
- },
218
- "./subagents/anthropic": {
219
- types: "./dist/subagents/anthropic.d.ts",
220
- import: "./dist/subagents/anthropic.js",
221
- require: "./dist/subagents/anthropic.cjs"
222
- },
223
- "./ai-sdk": {
224
- types: "./dist/ai-sdk/index.d.ts",
225
- import: "./dist/ai-sdk/index.js",
226
- require: "./dist/ai-sdk/index.cjs"
227
- }
228
- },
229
- files: [
230
- "dist/**/*.js",
231
- "dist/**/*.cjs",
232
- "dist/**/*.d.ts",
233
- "dist/**/*.map",
234
- "!dist/**/__tests__/**",
235
- "!dist/**/*.test.*"
236
- ],
237
- scripts: {
238
- 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",
239
- prepare: "npm run build",
240
- typecheck: "tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json",
241
- lint: "eslint .",
242
- test: "vitest run",
243
- "test:watch": "vitest watch",
244
- "test:anthropic": "vitest run anthropic",
245
- "test:openai": "vitest run openai",
246
- "test:vercel": "vitest run vercel",
247
- "test:git": "vitest run git",
248
- "test:browser": "vitest run browser",
249
- "test:agent": "npx tsx tests/fullAgentTest.ts",
250
- "test:integration": "npx tsx tests/fullIntegrationTest.ts",
251
- "test:e2e": "vitest run --config vitest.e2e.config.ts",
252
- "release:patch": "npm version patch && npm publish",
253
- "release:minor": "npm version minor && npm publish",
254
- "release:major": "npm version major && npm publish"
255
- },
256
- keywords: [
257
- "morph",
258
- "fast-apply",
259
- "cli",
260
- "sdk",
261
- "edit-file"
262
- ],
263
- engines: {
264
- node: ">=18"
265
- },
266
- license: "MIT",
267
- dependencies: {
268
- "@opentelemetry/api": "^1.9.0",
269
- "@opentelemetry/exporter-trace-otlp-http": "^0.203.0",
270
- "@opentelemetry/sdk-trace-base": "^2.7.1",
271
- "@traceloop/node-server-sdk": "^0.27.0",
272
- "@vscode/ripgrep": "^1.17.0",
273
- ai: ">=5.0.0",
274
- diff: "^7.0.0",
275
- openai: "^4.52.7",
276
- zod: ">=3.23.0"
277
- },
278
- devDependencies: {
279
- "@ai-sdk/anthropic": "^2.0.70",
280
- "@ai-sdk/openai": "^2.0.35",
281
- "@anthropic-ai/sdk": "^0.30.1",
282
- "@google/generative-ai": "^0.24.1",
283
- "@types/diff": "^7.0.2",
284
- "@types/node": "^20.14.10",
285
- "@typescript-eslint/eslint-plugin": "^7.18.0",
286
- "@typescript-eslint/parser": "^7.18.0",
287
- dotenv: "^16.4.5",
288
- eslint: "^8.57.0",
289
- shx: "^0.3.4",
290
- tsup: "^8.5.0",
291
- tsx: "^4.16.2",
292
- typescript: "^5.5.4",
293
- vitest: "^2.1.6"
294
- },
295
- peerDependencies: {
296
- "@ai-sdk/openai-compatible": ">=2.0.74 <4",
297
- "@anthropic-ai/sdk": ">=0.25.0",
298
- "@google/generative-ai": ">=0.21.0",
299
- ai: ">=5.0.0",
300
- zod: ">=3.23.0"
301
- },
302
- peerDependenciesMeta: {
303
- "@anthropic-ai/sdk": {
304
- optional: true
305
- },
306
- "@google/generative-ai": {
307
- optional: true
308
- },
309
- ai: {
310
- optional: true
311
- },
312
- zod: {
313
- optional: true
314
- }
315
- },
316
- publishConfig: {
317
- access: "public"
318
- }
319
- };
320
-
321
- // version.ts
322
- var SDK_VERSION = package_default.version;
323
-
324
- // tools/utils/resilience.ts
325
- var DEFAULT_RETRY_CONFIG = {
326
- maxRetries: 3,
327
- initialDelay: 1e3,
328
- maxDelay: 3e4,
329
- backoffMultiplier: 2,
330
- retryableErrors: ["ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND"]
331
- };
332
- async function fetchWithRetry(url, options, retryConfig = {}) {
333
- const {
334
- maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,
335
- initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,
336
- maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,
337
- backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,
338
- retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,
339
- onRetry
340
- } = retryConfig;
341
- let lastError = null;
342
- let delay = initialDelay;
343
- options = { ...options, headers: { "X-Morph-SDK-Version": SDK_VERSION, ...options.headers } };
344
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
345
- try {
346
- const response = await fetch(url, options);
347
- if (response.status === 429 || response.status === 503) {
348
- if (attempt < maxRetries) {
349
- const retryAfter = response.headers.get("Retry-After");
350
- const waitTime = retryAfter ? parseInt(retryAfter) * 1e3 : Math.min(delay, maxDelay);
351
- const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);
352
- if (onRetry) {
353
- onRetry(attempt + 1, error);
354
- }
355
- await sleep(waitTime);
356
- delay *= backoffMultiplier;
357
- continue;
358
- }
359
- }
360
- return response;
361
- } catch (error) {
362
- lastError = error;
363
- const isRetryable = retryableErrors.some(
364
- (errType) => lastError?.message?.includes(errType)
365
- );
366
- if (!isRetryable || attempt === maxRetries) {
367
- throw lastError;
368
- }
369
- const waitTime = Math.min(delay, maxDelay);
370
- if (onRetry) {
371
- onRetry(attempt + 1, lastError);
372
- }
373
- await sleep(waitTime);
374
- delay *= backoffMultiplier;
375
- }
376
- }
377
- throw lastError || new Error("Max retries exceeded");
378
- }
379
- async function withTimeout(promise, timeoutMs, errorMessage) {
380
- let timeoutId;
381
- const timeoutPromise = new Promise((_, reject) => {
382
- timeoutId = setTimeout(() => {
383
- reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));
384
- }, timeoutMs);
385
- });
386
- try {
387
- const result = await Promise.race([promise, timeoutPromise]);
388
- clearTimeout(timeoutId);
389
- return result;
390
- } catch (error) {
391
- clearTimeout(timeoutId);
392
- throw error;
393
- }
394
- }
395
- function sleep(ms) {
396
- return new Promise((resolve) => setTimeout(resolve, ms));
397
- }
398
- var MorphError = class extends Error {
399
- constructor(message, code, statusCode, retryable = false) {
400
- super(message);
401
- this.code = code;
402
- this.statusCode = statusCode;
403
- this.retryable = retryable;
404
- this.name = "MorphError";
405
- }
406
- };
407
-
408
- // logger.ts
409
- var MorphLogger = class {
410
- enabled;
411
- fileStream;
412
- /** Resolves once the file stream is initialized (or immediately if no file logging). */
413
- ready;
414
- constructor() {
415
- this.enabled = typeof process !== "undefined" && (process.env.MORPH_DEBUG === "1" || !!process.env.MORPH_LOG_FILE);
416
- this.fileStream = null;
417
- const f = typeof process !== "undefined" ? process.env.MORPH_LOG_FILE : void 0;
418
- if (f) {
419
- this.ready = import("fs").then((fs) => {
420
- this.fileStream = fs.createWriteStream(f, { flags: "a" });
421
- }).catch(() => {
422
- });
423
- } else {
424
- this.ready = Promise.resolve();
425
- }
426
- }
427
- debug(component, msg, data) {
428
- this._log("debug", component, msg, data);
429
- }
430
- info(component, msg, data) {
431
- this._log("info", component, msg, data);
432
- }
433
- warn(component, msg, data) {
434
- this._log("warn", component, msg, data);
435
- }
436
- error(component, msg, data) {
437
- this._log("error", component, msg, data);
438
- }
439
- enable() {
440
- this.enabled = true;
441
- }
442
- get isEnabled() {
443
- return this.enabled;
444
- }
445
- _log(level, component, msg, data) {
446
- if (level !== "error" && !this.enabled) return;
447
- const ts = (/* @__PURE__ */ new Date()).toISOString();
448
- const prefix = `[${ts}] [${level.toUpperCase()}] [${component}]`;
449
- console.error(data ? `${prefix} ${msg} ${JSON.stringify(data)}` : `${prefix} ${msg}`);
450
- this.fileStream?.write(JSON.stringify({ ts, level, component, msg, ...data && { data } }) + "\n");
451
- }
452
- };
453
- var logger = new MorphLogger();
454
-
455
- // tools/browser/live.ts
456
- var LIVE_PRESETS = {
457
- /** Read-only monitoring (no interaction) */
458
- readonly: { interactive: false },
459
- /** Interactive control (human-in-the-loop) */
460
- interactive: { interactive: true },
461
- /** Watch-only without controls */
462
- monitoring: { interactive: false, showControls: false }
463
- };
464
- function buildLiveUrl(debugUrl, options = {}) {
465
- if (!debugUrl) {
466
- throw new Error(
467
- "debugUrl is required. Ensure your backend returns debugUrl in the task response. Contact support@morphllm.com if you need help."
468
- );
469
- }
470
- const normalized = normalizeLiveUrl(debugUrl);
471
- const url = new URL(normalized);
472
- if (options.interactive !== void 0) {
473
- url.searchParams.set("interactive", String(options.interactive));
474
- }
475
- if (options.theme) {
476
- url.searchParams.set("theme", options.theme);
477
- }
478
- if (options.showControls !== void 0) {
479
- url.searchParams.set("showControls", String(options.showControls));
480
- }
481
- if (options.pageId) {
482
- url.searchParams.set("pageId", options.pageId);
483
- }
484
- if (options.pageIndex) {
485
- url.searchParams.set("pageIndex", options.pageIndex);
486
- }
487
- return url.toString();
488
- }
489
- function cdpToHttps(wsUrl) {
490
- return wsUrl.replace(/^wss:\/\//, "https://").replace(/^ws:\/\//, "http://");
491
- }
492
- function normalizeLiveUrl(debugUrl) {
493
- const trimmed = debugUrl.trim();
494
- if (!trimmed) return trimmed;
495
- if (trimmed.startsWith("wss://") || trimmed.startsWith("ws://")) {
496
- return `https://live.browser-use.com?wss=${encodeURIComponent(cdpToHttps(trimmed))}`;
497
- }
498
- let url;
499
- try {
500
- url = new URL(trimmed);
501
- } catch {
502
- return trimmed;
503
- }
504
- const wssParam = url.searchParams.get("wss");
505
- if (wssParam && (wssParam.startsWith("wss://") || wssParam.startsWith("ws://"))) {
506
- url.searchParams.set("wss", cdpToHttps(wssParam));
507
- }
508
- return url.toString();
509
- }
510
- function buildLiveIframe(debugUrl, options = {}) {
511
- const {
512
- width = "100%",
513
- height = "600px",
514
- style = "",
515
- className = "",
516
- ...sessionOptions
517
- } = options;
518
- const src = buildLiveUrl(debugUrl, sessionOptions);
519
- const widthStr = typeof width === "number" ? `${width}px` : width;
520
- const heightStr = typeof height === "number" ? `${height}px` : height;
521
- const baseStyle = `width: ${widthStr}; height: ${heightStr}; border: none;`;
522
- const fullStyle = style ? `${baseStyle} ${style}` : baseStyle;
523
- const attributes = [
524
- `src="${src}"`,
525
- `style="${fullStyle}"`
526
- ];
527
- if (className) {
528
- attributes.push(`class="${className}"`);
529
- }
530
- return `<iframe ${attributes.join(" ")}></iframe>`;
531
- }
532
- function buildEmbedCode(debugUrl, options = {}) {
533
- const iframe = buildLiveIframe(debugUrl, options);
534
- return `<!-- Embed Morph Live Session -->
535
- ${iframe}`;
536
- }
537
- function resolvePreset(optionsOrPreset) {
538
- if (!optionsOrPreset) {
539
- return {};
540
- }
541
- if (typeof optionsOrPreset === "string") {
542
- const preset = LIVE_PRESETS[optionsOrPreset];
543
- if (!preset) {
544
- throw new Error(
545
- `Unknown preset: ${optionsOrPreset}. Available presets: ${Object.keys(LIVE_PRESETS).join(", ")}`
546
- );
547
- }
548
- return preset;
549
- }
550
- return optionsOrPreset;
551
- }
552
-
553
- // tools/browser/errors.ts
554
- var MorphError2 = class extends Error {
555
- /** Error code for programmatic handling */
556
- code;
557
- /** Original cause of the error, if any */
558
- cause;
559
- constructor(message, code, cause) {
560
- super(message);
561
- this.name = "MorphError";
562
- this.code = code;
563
- this.cause = cause;
564
- if (Error.captureStackTrace) {
565
- Error.captureStackTrace(this, this.constructor);
566
- }
567
- }
568
- /**
569
- * Returns a JSON representation of the error for logging.
570
- */
571
- toJSON() {
572
- return {
573
- name: this.name,
574
- message: this.message,
575
- code: this.code,
576
- cause: this.cause?.message
577
- };
578
- }
579
- };
580
- var MorphValidationError = class extends MorphError2 {
581
- /** The field that failed validation */
582
- field;
583
- constructor(message, field) {
584
- super(message, "validation_error");
585
- this.name = "MorphValidationError";
586
- this.field = field;
587
- }
588
- toJSON() {
589
- return {
590
- ...super.toJSON(),
591
- field: this.field
592
- };
593
- }
594
- };
595
- var MorphAPIError = class extends MorphError2 {
596
- /** HTTP status code */
597
- statusCode;
598
- /** Request ID for debugging (if available) */
599
- requestId;
600
- /** Raw response body */
601
- rawResponse;
602
- constructor(message, code, statusCode, options) {
603
- super(message, code, options?.cause);
604
- this.name = "MorphAPIError";
605
- this.statusCode = statusCode;
606
- this.requestId = options?.requestId;
607
- this.rawResponse = options?.rawResponse;
608
- }
609
- toJSON() {
610
- return {
611
- ...super.toJSON(),
612
- statusCode: this.statusCode,
613
- requestId: this.requestId
614
- };
615
- }
616
- };
617
- var MorphAuthenticationError = class extends MorphAPIError {
618
- constructor(message = "Authentication required. Please provide a valid API key.") {
619
- super(message, "authentication_required", 401);
620
- this.name = "MorphAuthenticationError";
621
- }
622
- };
623
- var MorphRateLimitError = class extends MorphAPIError {
624
- /** When the rate limit resets (Unix timestamp) */
625
- resetAt;
626
- /** Number of seconds until reset */
627
- retryAfter;
628
- constructor(message = "Rate limit exceeded. Please retry later.", options) {
629
- super(message, "rate_limit_exceeded", 429, { requestId: options?.requestId });
630
- this.name = "MorphRateLimitError";
631
- this.resetAt = options?.resetAt;
632
- this.retryAfter = options?.retryAfter;
633
- }
634
- toJSON() {
635
- return {
636
- ...super.toJSON(),
637
- resetAt: this.resetAt,
638
- retryAfter: this.retryAfter
639
- };
640
- }
641
- };
642
- var MorphNotFoundError = class extends MorphAPIError {
643
- /** The type of resource that was not found */
644
- resourceType;
645
- /** The ID of the resource that was not found */
646
- resourceId;
647
- constructor(resourceType, resourceId) {
648
- const message = resourceId ? `${resourceType} '${resourceId}' not found` : `${resourceType} not found`;
649
- super(message, "resource_not_found", 404);
650
- this.name = "MorphNotFoundError";
651
- this.resourceType = resourceType;
652
- this.resourceId = resourceId;
653
- }
654
- toJSON() {
655
- return {
656
- ...super.toJSON(),
657
- resourceType: this.resourceType,
658
- resourceId: this.resourceId
659
- };
660
- }
661
- };
662
- var MorphProfileLimitError = class extends MorphAPIError {
663
- /** Current number of profiles */
664
- currentCount;
665
- /** Maximum allowed profiles for the plan */
666
- maxAllowed;
667
- constructor(message = "Profile limit exceeded for your plan.", options) {
668
- super(message, "profile_limit_exceeded", 403, { requestId: options?.requestId });
669
- this.name = "MorphProfileLimitError";
670
- this.currentCount = options?.currentCount;
671
- this.maxAllowed = options?.maxAllowed;
672
- }
673
- toJSON() {
674
- return {
675
- ...super.toJSON(),
676
- currentCount: this.currentCount,
677
- maxAllowed: this.maxAllowed
678
- };
679
- }
680
- };
681
- function parseAPIError(statusCode, responseText, requestId) {
682
- let errorData = {};
683
- try {
684
- errorData = JSON.parse(responseText);
685
- } catch {
686
- }
687
- const message = errorData.detail || errorData.message || responseText || "Unknown error";
688
- const code = errorData.code;
689
- switch (statusCode) {
690
- case 401:
691
- return new MorphAuthenticationError(message);
692
- case 403:
693
- if (code === "profile_limit_exceeded" || message.toLowerCase().includes("limit")) {
694
- return new MorphProfileLimitError(message, { requestId });
695
- }
696
- return new MorphAPIError(message, "insufficient_permissions", statusCode, { requestId, rawResponse: responseText });
697
- case 404:
698
- if (message.toLowerCase().includes("profile")) {
699
- return new MorphNotFoundError("Profile", void 0);
700
- }
701
- if (message.toLowerCase().includes("session")) {
702
- return new MorphNotFoundError("Session", void 0);
703
- }
704
- return new MorphAPIError(message, "resource_not_found", statusCode, { requestId, rawResponse: responseText });
705
- case 429:
706
- return new MorphRateLimitError(message, { requestId });
707
- case 422:
708
- return new MorphAPIError(message, "validation_error", statusCode, { requestId, rawResponse: responseText });
709
- case 500:
710
- case 502:
711
- case 503:
712
- case 504:
713
- return new MorphAPIError(message, "service_unavailable", statusCode, { requestId, rawResponse: responseText });
714
- default:
715
- return new MorphAPIError(message, "network_error", statusCode, { requestId, rawResponse: responseText });
716
- }
717
- }
718
-
719
- // tools/browser/profiles/types.ts
720
- function transformProfile(api) {
721
- return {
722
- id: api.id,
723
- name: api.name,
724
- repoId: api.repo_id,
725
- cookieDomains: api.cookie_domains,
726
- lastUsedAt: api.last_used_at,
727
- createdAt: api.created_at,
728
- updatedAt: api.updated_at
729
- };
730
- }
731
- function transformCreateInput(input) {
732
- return {
733
- name: input.name,
734
- repo_id: input.repoId
735
- };
736
- }
737
- function transformSession(api) {
738
- return {
739
- sessionId: api.session_id,
740
- debugUrl: api.debug_url || ""
741
- };
742
- }
743
- function transformSaveInput(input) {
744
- return {
745
- session_id: input.sessionId,
746
- profile_id: input.profileId
747
- };
748
- }
749
- function transformStateResponse(api) {
750
- return {
751
- profileId: api.profile_id,
752
- stateUrl: api.state_url,
753
- expiresIn: api.expires_in
754
- };
755
- }
756
-
757
- // tools/browser/profiles/core.ts
758
- var DEFAULT_API_URL = process.env.MORPH_ENVIRONMENT === "DEV" ? "http://localhost:8000" : "https://browser.morphllm.com";
759
- var ProfilesClient = class {
760
- config;
761
- constructor(config) {
762
- this.config = config;
763
- }
764
- /**
765
- * Create a new browser profile and immediately start a live session.
766
- *
767
- * @param input - Profile creation parameters
768
- * @returns Profile setup handle with live URL + save()
769
- * @throws {MorphValidationError} If input validation fails
770
- * @throws {MorphProfileLimitError} If profile limit is exceeded
771
- * @throws {MorphAuthenticationError} If API key is missing or invalid
772
- *
773
- * @example
774
- * ```typescript
775
- * const setup = await morph.browser.profiles.createProfile({
776
- * name: 'LinkedIn Production',
777
- * repoId: 'owner/repo'
778
- * });
779
- * console.log(setup.session.debugUrl);
780
- * await setup.save();
781
- * ```
782
- */
783
- async createProfile(input) {
784
- return createProfile(input, this.config);
785
- }
786
- /**
787
- * List all profiles for the authenticated user.
788
- *
789
- * @param repoId - Optional repository ID to filter by
790
- * @returns Array of profiles
791
- *
792
- * @example
793
- * ```typescript
794
- * // List all profiles
795
- * const allProfiles = await morph.browser.profiles.listProfiles();
796
- *
797
- * // List profiles for a specific repo
798
- * const repoProfiles = await morph.browser.profiles.listProfiles('owner/repo');
799
- * ```
800
- */
801
- async listProfiles(repoId) {
802
- return listProfiles(this.config, repoId);
803
- }
804
- /**
805
- * Get a profile by ID with convenience methods.
806
- *
807
- * @param id - Profile ID
808
- * @returns Profile with attached methods
809
- * @throws {MorphNotFoundError} If profile is not found
810
- *
811
- * @example
812
- * ```typescript
813
- * const profile = await morph.browser.profiles.getProfile('profile-id');
814
- * const state = await profile.getState();
815
- * await profile.delete();
816
- * ```
817
- */
818
- async getProfile(id) {
819
- return getProfile(id, this.config);
820
- }
821
- /**
822
- * Update a profile by opening a live session (no rename).
823
- *
824
- * @param id - Profile ID
825
- * @returns Profile setup handle with live URL + save()
826
- */
827
- async updateProfile(id) {
828
- return updateProfile(id, this.config);
829
- }
830
- /**
831
- * Delete a profile.
832
- *
833
- * @param id - Profile ID
834
- * @throws {MorphNotFoundError} If profile is not found
835
- */
836
- async deleteProfile(id) {
837
- return deleteProfile(id, this.config);
838
- }
839
- /**
840
- * Start a browser session for profile setup.
841
- *
842
- * Returns a live URL where the user can sign into accounts.
843
- * After signing in, call `saveSession` to persist the state.
844
- *
845
- * @param input - Optional session parameters
846
- * @returns Session with debug URL
847
- *
848
- * @example
849
- * ```typescript
850
- * const session = await morph.browser.profiles.startSession();
851
- * console.log('Sign in at:', session.debugUrl);
852
- * // Open debugUrl in browser, user signs in...
853
- * await morph.browser.profiles.saveSession(session.sessionId, profile.id);
854
- * ```
855
- */
856
- async startSession(input) {
857
- return startProfileSession(this.config, input);
858
- }
859
- /**
860
- * Save browser state from a session to a profile.
861
- *
862
- * Call this after the user is done signing into accounts.
863
- * Extracts cookies, localStorage, and sessionStorage.
864
- *
865
- * @param sessionId - Browser session ID from startSession
866
- * @param profileId - Profile ID to save state to
867
- * @returns Updated profile with cookie domains
868
- */
869
- async saveSession(sessionId, profileId) {
870
- return saveProfileSession({ sessionId, profileId }, this.config);
871
- }
872
- /**
873
- * List available repo IDs (discovery).
874
- *
875
- * @returns Repo summaries with profile counts
876
- */
877
- async listRepos() {
878
- return listRepos(this.config);
879
- }
880
- /**
881
- * Get the presigned URL for a profile's state.
882
- *
883
- * Use this to download the raw state JSON for debugging
884
- * or to restore state manually.
885
- *
886
- * @param profileId - Profile ID
887
- * @returns State URL with expiry information
888
- */
889
- async getProfileState(profileId) {
890
- return getProfileState(profileId, this.config);
891
- }
892
- };
893
- function validateCreateInput(input) {
894
- if (!input.name || typeof input.name !== "string") {
895
- throw new MorphValidationError("name is required", "name");
896
- }
897
- const trimmedName = input.name.trim();
898
- if (trimmedName.length === 0) {
899
- throw new MorphValidationError("name cannot be empty", "name");
900
- }
901
- if (trimmedName.length > 100) {
902
- throw new MorphValidationError("name must be 100 characters or less", "name");
903
- }
904
- if (!input.repoId || typeof input.repoId !== "string") {
905
- throw new MorphValidationError("repoId is required", "repoId");
906
- }
907
- if (input.repoId.trim().length === 0) {
908
- throw new MorphValidationError("repoId cannot be empty", "repoId");
909
- }
910
- }
911
- function validateId(id, fieldName) {
912
- if (!id || typeof id !== "string") {
913
- throw new MorphValidationError(`${fieldName} is required`, fieldName);
914
- }
915
- if (id.trim().length === 0) {
916
- throw new MorphValidationError(`${fieldName} cannot be empty`, fieldName);
917
- }
918
- }
919
- async function createProfile(input, config = {}) {
920
- validateCreateInput(input);
921
- const apiUrl = config.apiUrl || DEFAULT_API_URL;
922
- const headers = buildHeaders(config);
923
- const response = await fetchWithRetry(
924
- `${apiUrl}/profiles`,
925
- {
926
- method: "POST",
927
- headers,
928
- body: JSON.stringify(transformCreateInput(input))
929
- },
930
- config.retryConfig
931
- );
932
- if (!response.ok) {
933
- const errorText = await response.text().catch(() => response.statusText);
934
- const requestId = response.headers.get("x-request-id") || void 0;
935
- throw parseAPIError(response.status, errorText, requestId);
936
- }
937
- const apiProfile = await response.json();
938
- const profile = transformProfile(apiProfile);
939
- const session = await startProfileSession(config, { profileId: profile.id });
940
- return buildProfileSetup(profile, session, config);
941
- }
942
- async function listProfiles(config = {}, repoId) {
943
- const apiUrl = config.apiUrl || DEFAULT_API_URL;
944
- const headers = buildHeaders(config);
945
- const url = repoId ? `${apiUrl}/profiles?repo_id=${encodeURIComponent(repoId)}` : `${apiUrl}/profiles`;
946
- const response = await fetchWithRetry(
947
- url,
948
- { method: "GET", headers },
949
- config.retryConfig
950
- );
951
- if (!response.ok) {
952
- const errorText = await response.text().catch(() => response.statusText);
953
- const requestId = response.headers.get("x-request-id") || void 0;
954
- throw parseAPIError(response.status, errorText, requestId);
955
- }
956
- const data = await response.json();
957
- return data.profiles.map(transformProfile);
958
- }
959
- async function getProfile(id, config = {}) {
960
- validateId(id, "id");
961
- const apiUrl = config.apiUrl || DEFAULT_API_URL;
962
- const headers = buildHeaders(config);
963
- const response = await fetchWithRetry(
964
- `${apiUrl}/profiles/${encodeURIComponent(id)}`,
965
- { method: "GET", headers },
966
- config.retryConfig
967
- );
968
- if (!response.ok) {
969
- const errorText = await response.text().catch(() => response.statusText);
970
- const requestId = response.headers.get("x-request-id") || void 0;
971
- throw parseAPIError(response.status, errorText, requestId);
972
- }
973
- const apiProfile = await response.json();
974
- const profile = transformProfile(apiProfile);
975
- return {
976
- ...profile,
977
- getState: () => getProfileState(id, config),
978
- delete: () => deleteProfile(id, config)
979
- };
980
- }
981
- async function updateProfile(id, config = {}) {
982
- validateId(id, "id");
983
- const profile = await fetchProfile(id, config);
984
- const session = await startProfileSession(config, { profileId: profile.id });
985
- return buildProfileSetup(profile, session, config);
986
- }
987
- async function deleteProfile(id, config = {}) {
988
- validateId(id, "id");
989
- const apiUrl = config.apiUrl || DEFAULT_API_URL;
990
- const headers = buildHeaders(config);
991
- const response = await fetchWithRetry(
992
- `${apiUrl}/profiles/${encodeURIComponent(id)}`,
993
- { method: "DELETE", headers },
994
- config.retryConfig
995
- );
996
- if (!response.ok) {
997
- const errorText = await response.text().catch(() => response.statusText);
998
- const requestId = response.headers.get("x-request-id") || void 0;
999
- throw parseAPIError(response.status, errorText, requestId);
1000
- }
1001
- }
1002
- async function startProfileSession(config = {}, input) {
1003
- if (!config.apiKey) {
1004
- throw new MorphAuthenticationError();
1005
- }
1006
- const apiUrl = config.apiUrl || DEFAULT_API_URL;
1007
- const headers = buildHeaders(config);
1008
- const body = input?.profileId ? { profile_id: input.profileId } : {};
1009
- const response = await fetchWithRetry(
1010
- `${apiUrl}/profiles/session/start`,
1011
- {
1012
- method: "POST",
1013
- headers,
1014
- body: JSON.stringify(body)
1015
- },
1016
- config.retryConfig
1017
- );
1018
- if (!response.ok) {
1019
- const errorText = await response.text().catch(() => response.statusText);
1020
- const requestId = response.headers.get("x-request-id") || void 0;
1021
- throw parseAPIError(response.status, errorText, requestId);
1022
- }
1023
- const apiSession = await response.json();
1024
- return transformSession(apiSession);
1025
- }
1026
- async function saveProfileSession(input, config = {}) {
1027
- validateId(input.sessionId, "sessionId");
1028
- validateId(input.profileId, "profileId");
1029
- const apiUrl = config.apiUrl || DEFAULT_API_URL;
1030
- const headers = buildHeaders(config);
1031
- const response = await fetchWithRetry(
1032
- `${apiUrl}/profiles/session/save`,
1033
- {
1034
- method: "POST",
1035
- headers,
1036
- body: JSON.stringify(transformSaveInput(input))
1037
- },
1038
- config.retryConfig
1039
- );
1040
- if (!response.ok) {
1041
- const errorText = await response.text().catch(() => response.statusText);
1042
- const requestId = response.headers.get("x-request-id") || void 0;
1043
- throw parseAPIError(response.status, errorText, requestId);
1044
- }
1045
- const apiProfile = await response.json();
1046
- return transformProfile(apiProfile);
1047
- }
1048
- async function listRepos(config = {}) {
1049
- const apiUrl = config.apiUrl || DEFAULT_API_URL;
1050
- const headers = buildHeaders(config);
1051
- const response = await fetchWithRetry(
1052
- `${apiUrl}/repos`,
1053
- { method: "GET", headers },
1054
- config.retryConfig
1055
- );
1056
- if (!response.ok) {
1057
- const errorText = await response.text().catch(() => response.statusText);
1058
- const requestId = response.headers.get("x-request-id") || void 0;
1059
- throw parseAPIError(response.status, errorText, requestId);
1060
- }
1061
- const data = await response.json();
1062
- const repos = Array.isArray(data?.repos) ? data.repos : [];
1063
- return repos.map((repo) => ({
1064
- repoId: repo.repo_id,
1065
- repoFullName: repo.repo_full_name,
1066
- profileCount: repo.profile_count ?? 0
1067
- }));
1068
- }
1069
- async function getProfileState(profileId, config = {}) {
1070
- validateId(profileId, "profileId");
1071
- const apiUrl = config.apiUrl || DEFAULT_API_URL;
1072
- const headers = buildHeaders(config);
1073
- const response = await fetchWithRetry(
1074
- `${apiUrl}/profiles/${encodeURIComponent(profileId)}/state`,
1075
- { method: "GET", headers },
1076
- config.retryConfig
1077
- );
1078
- if (!response.ok) {
1079
- const errorText = await response.text().catch(() => response.statusText);
1080
- const requestId = response.headers.get("x-request-id") || void 0;
1081
- throw parseAPIError(response.status, errorText, requestId);
1082
- }
1083
- const apiState = await response.json();
1084
- return transformStateResponse(apiState);
1085
- }
1086
- function buildHeaders(config) {
1087
- const headers = { "Content-Type": "application/json" };
1088
- if (config.apiKey) {
1089
- headers["Authorization"] = `Bearer ${config.apiKey}`;
1090
- }
1091
- return headers;
1092
- }
1093
- async function fetchProfile(id, config) {
1094
- const apiUrl = config.apiUrl || DEFAULT_API_URL;
1095
- const headers = buildHeaders(config);
1096
- const response = await fetchWithRetry(
1097
- `${apiUrl}/profiles/${encodeURIComponent(id)}`,
1098
- { method: "GET", headers },
1099
- config.retryConfig
1100
- );
1101
- if (!response.ok) {
1102
- const errorText = await response.text().catch(() => response.statusText);
1103
- const requestId = response.headers.get("x-request-id") || void 0;
1104
- throw parseAPIError(response.status, errorText, requestId);
1105
- }
1106
- const apiProfile = await response.json();
1107
- return transformProfile(apiProfile);
1108
- }
1109
- function buildProfileSetup(profile, session, config) {
1110
- return {
1111
- profile,
1112
- session,
1113
- save: () => saveProfileSession({ sessionId: session.sessionId, profileId: profile.id }, config)
1114
- };
1115
- }
1116
-
1117
- // core/error.ts
1118
- async function toMorphError(response) {
1119
- let message = `Morph API request failed (${response.status})`;
1120
- let code = "api_error";
1121
- try {
1122
- const body = await response.json();
1123
- message = body.error?.message ?? body.message ?? message;
1124
- code = body.error?.code ?? body.error?.type ?? code;
1125
- } catch {
1126
- }
1127
- if (response.status === 401) code = "authentication_error";
1128
- if (response.status === 429) code = "rate_limit_exceeded";
1129
- const retryable = response.status === 429 || response.status === 503;
1130
- return new MorphError(message, code, response.status, retryable);
1131
- }
1132
-
1133
- // core/client.ts
1134
- var DEFAULT_BASE_URL = "https://api.morphllm.com";
1135
- var DEFAULT_REPOS_URL = "https://repos.morphllm.com";
1136
- var DEFAULT_BROWSER_URL = "https://browser.morphllm.com";
1137
- var DEFAULT_TIMEOUT = 6e4;
1138
- var env = (name) => typeof process !== "undefined" ? process.env?.[name] : void 0;
1139
- var stripTrailingSlash = (url) => url.replace(/\/+$/, "");
1140
- var MorphAPIClient = class {
1141
- /** Explicit key as provided; resolved against env at request time. */
1142
- apiKey;
1143
- baseURL;
1144
- reposURL;
1145
- browserURL;
1146
- /** Explicit default timeout (ms), if set. The request default is applied lazily so
1147
- * resources can read an undefined value and supply their own fallback. */
1148
- timeout;
1149
- retryConfig;
1150
- debug;
1151
- constructor(options = {}) {
1152
- this.apiKey = options.apiKey;
1153
- this.baseURL = stripTrailingSlash(options.baseURL ?? DEFAULT_BASE_URL);
1154
- this.reposURL = stripTrailingSlash(options.reposURL ?? env("MORPH_SEARCH_URL") ?? DEFAULT_REPOS_URL);
1155
- this.browserURL = stripTrailingSlash(
1156
- options.browserURL ?? (env("MORPH_ENVIRONMENT") === "DEV" ? "http://localhost:8000" : DEFAULT_BROWSER_URL)
1157
- );
1158
- this.timeout = options.timeout;
1159
- this.retryConfig = options.retryConfig;
1160
- this.debug = options.debug ?? false;
1161
- if (this.debug) logger.enable();
1162
- }
1163
- /** The key actually used for requests: explicit, else `MORPH_API_KEY`. */
1164
- resolveApiKey() {
1165
- return this.apiKey ?? env("MORPH_API_KEY");
1166
- }
1167
- /** Headers shared with tools that bring their own HTTP client (FastApply/WarpGrep via the `openai` package). */
1168
- defaultHeaders() {
1169
- return { "X-Morph-SDK-Version": SDK_VERSION };
1170
- }
1171
- buildURL(path, baseURL) {
1172
- if (/^https?:\/\//i.test(path)) return path;
1173
- const base = stripTrailingSlash(baseURL ?? this.baseURL);
1174
- return `${base}${path.startsWith("/") ? "" : "/"}${path}`;
1175
- }
1176
- buildHeaders(apiKey, extra) {
1177
- return {
1178
- "Content-Type": "application/json",
1179
- "X-Morph-SDK-Version": SDK_VERSION,
1180
- Authorization: `Bearer ${apiKey}`,
1181
- ...extra
1182
- };
1183
- }
1184
- applyQuery(url, query) {
1185
- if (!query) return url;
1186
- const params = new URLSearchParams();
1187
- for (const [key, value] of Object.entries(query)) {
1188
- if (value !== void 0 && value !== null) params.set(key, String(value));
1189
- }
1190
- const qs = params.toString();
1191
- return qs ? `${url}${url.includes("?") ? "&" : "?"}${qs}` : url;
1192
- }
1193
- async request(method, path, opts = {}) {
1194
- const apiKey = this.resolveApiKey();
1195
- if (!apiKey) {
1196
- throw new MorphError(
1197
- "Morph API key not found. Set the MORPH_API_KEY environment variable or pass apiKey in config.",
1198
- "missing_api_key",
1199
- 401
1200
- );
1201
- }
1202
- const url = this.applyQuery(this.buildURL(path, opts.baseURL), opts.query);
1203
- const timeout = opts.timeout ?? this.timeout ?? DEFAULT_TIMEOUT;
1204
- const init = {
1205
- method,
1206
- headers: this.buildHeaders(apiKey, opts.headers),
1207
- ...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
1208
- ...opts.signal ? { signal: opts.signal } : {}
1209
- };
1210
- logger.debug("MorphAPIClient", "request", { method, url });
1211
- const response = await withTimeout(
1212
- fetchWithRetry(url, init, this.retryConfig ?? {}),
1213
- timeout,
1214
- `Morph request to ${url} timed out after ${timeout}ms`
1215
- );
1216
- if (opts.raw) return response;
1217
- if (!response.ok) throw await toMorphError(response);
1218
- if (opts.stream) return response;
1219
- if (response.status === 204) return void 0;
1220
- const text = await response.text();
1221
- return text ? JSON.parse(text) : void 0;
1222
- }
1223
- get(path, opts) {
1224
- return this.request("GET", path, opts);
1225
- }
1226
- post(path, opts) {
1227
- return this.request("POST", path, opts);
1228
- }
1229
- delete(path, opts) {
1230
- return this.request("DELETE", path, opts);
1231
- }
1232
- };
1233
-
1234
- // core/resource.ts
1235
- var APIResource = class {
1236
- _client;
1237
- constructor(client) {
1238
- this._client = client;
1239
- }
1240
- };
1241
-
1242
- // tools/browser/core.ts
1243
- var DEFAULT_CONFIG = {
1244
- apiUrl: process.env.MORPH_ENVIRONMENT === "DEV" ? "http://localhost:8000" : "https://browser.morphllm.com",
1245
- timeout: 1e6,
1246
- // 10 minutes for complex tasks
1247
- debug: false
1248
- };
1249
- var BrowserClient = class extends APIResource {
1250
- config;
1251
- /**
1252
- * Profile management - create and manage browser profiles for storing login state.
1253
- */
1254
- profiles;
1255
- constructor(clientOrConfig = {}) {
1256
- const isClient = clientOrConfig instanceof MorphAPIClient;
1257
- super(
1258
- isClient ? clientOrConfig : new MorphAPIClient({
1259
- apiKey: clientOrConfig.apiKey,
1260
- browserURL: clientOrConfig.apiUrl,
1261
- timeout: clientOrConfig.timeout,
1262
- retryConfig: clientOrConfig.retryConfig,
1263
- debug: clientOrConfig.debug
1264
- })
1265
- );
1266
- this.config = isClient ? {
1267
- ...DEFAULT_CONFIG,
1268
- apiUrl: clientOrConfig.browserURL,
1269
- apiKey: clientOrConfig.resolveApiKey(),
1270
- retryConfig: clientOrConfig.retryConfig,
1271
- debug: clientOrConfig.debug
1272
- } : { ...DEFAULT_CONFIG, ...clientOrConfig };
1273
- this.profiles = new ProfilesClient(this.config);
1274
- }
1275
- /**
1276
- * Execute a browser automation task
1277
- */
1278
- async execute(input) {
1279
- return executeBrowserTask(input, this.config);
1280
- }
1281
- async createTask(input) {
1282
- const apiUrl = this.config.apiUrl || DEFAULT_CONFIG.apiUrl;
1283
- const debug = this.config.debug || false;
1284
- const hasTask = typeof input.task === "string" && input.task.trim().length > 0;
1285
- const hasDiff = typeof input.diff === "string" && input.diff.trim().length > 0;
1286
- if (!hasTask && !hasDiff) {
1287
- throw new Error('Browser task requires either "task" (natural language) or "diff" (PR-review planning)');
1288
- }
1289
- logger.debug("Browser", "create_task", { task: (input.task ?? "").slice(0, 100), url: input.url, endpoint: `${apiUrl}/browser-task/async` });
1290
- const headers = { "Content-Type": "application/json" };
1291
- if (this.config.apiKey) headers["Authorization"] = `Bearer ${this.config.apiKey}`;
1292
- const response = await fetch(`${apiUrl}/browser-task/async`, {
1293
- method: "POST",
1294
- headers,
1295
- body: JSON.stringify({
1296
- task: input.task,
1297
- diff: input.diff,
1298
- url: input.url,
1299
- max_steps: input.maxSteps ?? 10,
1300
- model: input.model ?? "morph-computer-use-v0",
1301
- viewport_width: input.viewportWidth ?? 1280,
1302
- viewport_height: input.viewportHeight ?? 720,
1303
- external_id: input.externalId,
1304
- repo_id: input.repoId,
1305
- repo_full_name: input.repoFullName,
1306
- commit_id: input.commitId,
1307
- record_video: input.recordVideo ?? false,
1308
- video_width: input.videoWidth ?? input.viewportWidth ?? 1280,
1309
- video_height: input.videoHeight ?? input.viewportHeight ?? 720,
1310
- allow_resizing: input.allowResizing ?? false,
1311
- structured_output: "schema" in input ? stringifyStructuredOutput(input.schema) : void 0,
1312
- auth: input.auth,
1313
- profile_id: input.profileId,
1314
- force_query_params: input.forceQueryParams
1315
- })
1316
- });
1317
- if (!response.ok) {
1318
- const errorText = await response.text().catch(() => response.statusText);
1319
- logger.error("Browser", "create_task_error", { status: response.status, error: errorText });
1320
- throw new Error(`HTTP ${response.status}: ${errorText}`);
1321
- }
1322
- const result = mapTaskResult(await response.json());
1323
- logger.debug("Browser", "task_created", { recording_id: result.recordingId, task_id: result.taskId, debug_url: !!result.debugUrl });
1324
- if ("schema" in input) {
1325
- return wrapTaskResponseWithSchema(result, this.config, input.schema);
1326
- } else {
1327
- return wrapTaskResponse(result, this.config);
1328
- }
1329
- }
1330
- /**
1331
- * Execute task with recording and wait for video to be ready
1332
- */
1333
- async executeWithRecording(input) {
1334
- return executeWithRecording(input, this.config);
1335
- }
1336
- /**
1337
- * Get recording status and URLs
1338
- */
1339
- async getRecording(recordingId) {
1340
- return getRecording(recordingId, this.config);
1341
- }
1342
- /**
1343
- * Wait for recording to complete with automatic polling
1344
- */
1345
- async waitForRecording(recordingId, options) {
1346
- return waitForRecording(recordingId, this.config, options);
1347
- }
1348
- /**
1349
- * Get errors from recording with screenshots
1350
- */
1351
- async getErrors(recordingId) {
1352
- return getErrors(recordingId, this.config);
1353
- }
1354
- /**
1355
- * Get animated WebP preview of recording
1356
- */
1357
- async getWebp(recordingId, options) {
1358
- return getWebp(recordingId, this.config, options);
1359
- }
1360
- /**
1361
- * Check if browser worker service is healthy
1362
- */
1363
- async checkHealth() {
1364
- return checkHealth(this.config);
1365
- }
1366
- };
1367
- async function executeBrowserTask(input, config = {}) {
1368
- const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;
1369
- const timeout = config.timeout || DEFAULT_CONFIG.timeout;
1370
- const debug = config.debug || false;
1371
- if (!input.task || input.task.trim().length === 0) {
1372
- return {
1373
- success: false,
1374
- error: 'Task description is required. Example: "Go to example.com and click the login button"'
1375
- };
1376
- }
1377
- if (input.maxSteps !== void 0 && (input.maxSteps < 1 || input.maxSteps > 50)) {
1378
- return {
1379
- success: false,
1380
- error: "maxSteps must be between 1 and 50. Use more steps for complex multi-page flows."
1381
- };
1382
- }
1383
- logger.debug("Browser", "execute_start", { task: input.task.slice(0, 100), url: input.url, max_steps: input.maxSteps ?? 10, record_video: input.recordVideo ?? false });
1384
- const startTime = Date.now();
1385
- try {
1386
- const headers = { "Content-Type": "application/json" };
1387
- if (config.apiKey) headers["Authorization"] = `Bearer ${config.apiKey}`;
1388
- const fetchPromise = fetchWithRetry(
1389
- `${apiUrl}/browser-task`,
1390
- {
1391
- method: "POST",
1392
- headers,
1393
- body: JSON.stringify({
1394
- task: input.task,
1395
- url: input.url,
1396
- max_steps: input.maxSteps ?? 10,
1397
- model: input.model ?? "morph-computer-use-v0",
1398
- viewport_width: input.viewportWidth ?? 1280,
1399
- viewport_height: input.viewportHeight ?? 720,
1400
- external_id: input.externalId,
1401
- repo_id: input.repoId,
1402
- commit_id: input.commitId,
1403
- record_video: input.recordVideo ?? false,
1404
- video_width: input.videoWidth ?? input.viewportWidth ?? 1280,
1405
- video_height: input.videoHeight ?? input.viewportHeight ?? 720,
1406
- allow_resizing: input.allowResizing ?? false,
1407
- structured_output: input.structuredOutput,
1408
- auth: input.auth,
1409
- profile_id: input.profileId,
1410
- force_query_params: input.forceQueryParams
1411
- })
1412
- },
1413
- config.retryConfig
1414
- );
1415
- const response = await withTimeout(
1416
- fetchPromise,
1417
- timeout,
1418
- `Browser task timed out after ${timeout}ms. Consider increasing timeout or reducing maxSteps.`
1419
- );
1420
- if (!response.ok) {
1421
- const errorText = await response.text().catch(() => response.statusText);
1422
- logger.error("Browser", "execute_error", { status: response.status, error: errorText });
1423
- throw new Error(`HTTP ${response.status}: ${errorText}`);
1424
- }
1425
- const result = mapTaskResult(await response.json());
1426
- const elapsed = Date.now() - startTime;
1427
- logger.debug("Browser", "execute_complete", { success: result.success, latency_ms: elapsed, steps: result.stepsTaken ?? 0, recording_id: result.recordingId });
1428
- return result;
1429
- } catch (error) {
1430
- if (error instanceof Error) {
1431
- if (error.message.includes("ECONNREFUSED") || error.message.includes("fetch failed")) {
1432
- return {
1433
- success: false,
1434
- error: `Cannot connect to browser worker at ${apiUrl}. Ensure the service is running and accessible. For local dev, set MORPH_ENVIRONMENT=DEV.`
1435
- };
1436
- }
1437
- return {
1438
- success: false,
1439
- error: error.message
1440
- };
1441
- }
1442
- return {
1443
- success: false,
1444
- error: String(error)
1445
- };
1446
- }
1447
- }
1448
- async function getRecording(recordingId, config = {}) {
1449
- const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;
1450
- const debug = config.debug || false;
1451
- if (!config.apiKey) {
1452
- throw new Error("API key required for getRecording");
1453
- }
1454
- if (debug) console.log(`[Browser] getRecording: ${recordingId}`);
1455
- const response = await fetch(`${apiUrl}/recordings/${recordingId}`, {
1456
- method: "GET",
1457
- headers: { "Authorization": `Bearer ${config.apiKey}` }
1458
- });
1459
- if (!response.ok) {
1460
- const errorText = await response.text().catch(() => response.statusText);
1461
- if (debug) console.error(`[Browser] getRecording error: ${response.status} - ${errorText}`);
1462
- throw new Error(`HTTP ${response.status}: ${errorText}`);
1463
- }
1464
- const data = mapRecordingStatus(await response.json());
1465
- if (debug) console.log(`[Browser] Recording status: ${data.status}`);
1466
- return {
1467
- ...data,
1468
- getWebp: (options) => getWebp(recordingId, config, options),
1469
- getErrors: () => getErrors(recordingId, config)
1470
- };
1471
- }
1472
- async function waitForRecording(recordingId, config = {}, options = {}) {
1473
- const timeout = options.timeout ?? 6e4;
1474
- const pollInterval = options.pollInterval ?? 2e3;
1475
- const startTime = Date.now();
1476
- while (Date.now() - startTime < timeout) {
1477
- const status = await getRecording(recordingId, config);
1478
- if (status.status === "COMPLETED" || status.status === "ERROR") {
1479
- return status;
1480
- }
1481
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1482
- }
1483
- throw new Error(`Recording timeout after ${timeout}ms - status still pending`);
1484
- }
1485
- async function executeWithRecording(input, config = {}) {
1486
- const taskResult = await executeBrowserTask(input, config);
1487
- if (taskResult.recordingId) {
1488
- try {
1489
- const recording = await waitForRecording(
1490
- taskResult.recordingId,
1491
- config,
1492
- { timeout: 6e4, pollInterval: 2e3 }
1493
- );
1494
- return {
1495
- ...taskResult,
1496
- recording
1497
- };
1498
- } catch (error) {
1499
- const errorRecording = {
1500
- id: taskResult.recordingId,
1501
- status: "ERROR",
1502
- error: error instanceof Error ? error.message : String(error),
1503
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1504
- getWebp: (options) => getWebp(taskResult.recordingId, config, options),
1505
- getErrors: () => getErrors(taskResult.recordingId, config)
1506
- };
1507
- return {
1508
- ...taskResult,
1509
- recording: errorRecording
1510
- };
1511
- }
1512
- }
1513
- return taskResult;
1514
- }
1515
- async function getErrors(recordingId, config = {}) {
1516
- const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;
1517
- const debug = config.debug || false;
1518
- if (!config.apiKey) {
1519
- throw new Error("API key required for getErrors");
1520
- }
1521
- if (debug) console.log(`[Browser] getErrors: ${recordingId}`);
1522
- const response = await fetch(`${apiUrl}/recordings/${recordingId}/errors`, {
1523
- method: "GET",
1524
- headers: { "Authorization": `Bearer ${config.apiKey}` }
1525
- });
1526
- if (!response.ok) {
1527
- const errorText = await response.text().catch(() => response.statusText);
1528
- if (debug) console.error(`[Browser] getErrors error: ${response.status} - ${errorText}`);
1529
- throw new Error(`HTTP ${response.status}: ${errorText}`);
1530
- }
1531
- const errors = mapErrorsResponse(await response.json());
1532
- if (debug) console.log(`[Browser] Found ${errors.totalErrors} errors`);
1533
- return errors;
1534
- }
1535
- function stringifyStructuredOutput(schema) {
1536
- try {
1537
- return JSON.stringify({
1538
- type: "object",
1539
- description: "Zod schema definition (Zod v3)",
1540
- zodDef: schema._def
1541
- });
1542
- } catch (error) {
1543
- console.warn("[Browser] Failed to serialize Zod schema:", error);
1544
- return JSON.stringify({
1545
- type: "object",
1546
- description: "Schema serialization failed"
1547
- });
1548
- }
1549
- }
1550
- function parseStructuredTaskOutput(result, schema) {
1551
- if (!result.output) {
1552
- return { ...result, parsed: null };
1553
- }
1554
- try {
1555
- const parsed = JSON.parse(result.output);
1556
- const validated = schema.parse(parsed);
1557
- return { ...result, parsed: validated };
1558
- } catch (error) {
1559
- if (error instanceof SyntaxError) {
1560
- return { ...result, parsed: null };
1561
- }
1562
- throw error;
1563
- }
1564
- }
1565
- function mapTaskResult(api) {
1566
- if (!api || typeof api !== "object") {
1567
- return api;
1568
- }
1569
- return {
1570
- success: api.success,
1571
- result: api.result,
1572
- error: api.error,
1573
- stepsTaken: api.steps_taken,
1574
- executionTimeMs: api.execution_time_ms,
1575
- urls: api.urls,
1576
- actionNames: api.action_names,
1577
- errors: api.errors,
1578
- modelActions: api.model_actions,
1579
- isDone: api.is_done,
1580
- actionHistory: api.action_history,
1581
- actionResults: api.action_results,
1582
- hasErrors: api.has_errors,
1583
- numberOfSteps: api.number_of_steps,
1584
- judgement: api.judgement,
1585
- isValidated: api.is_validated,
1586
- replayId: api.replay_id,
1587
- replayUrl: api.replay_url,
1588
- recordingId: api.recording_id,
1589
- recordingStatus: api.recording_status,
1590
- taskId: api.task_id,
1591
- status: api.status,
1592
- output: api.output,
1593
- debugUrl: api.debug_url
1594
- };
1595
- }
1596
- function mapRecordingStatus(api) {
1597
- return {
1598
- id: api.id,
1599
- status: api.status,
1600
- replayUrl: api.replay_url,
1601
- networkUrl: api.network_url,
1602
- consoleUrl: api.console_url,
1603
- videoUrl: api.video_url,
1604
- result: api.result,
1605
- totalEvents: api.total_events,
1606
- fileSize: api.file_size,
1607
- duration: api.duration,
1608
- error: api.error,
1609
- createdAt: api.created_at
1610
- };
1611
- }
1612
- function mapBrowserError(api) {
1613
- return {
1614
- type: api.type,
1615
- message: api.message,
1616
- url: api.url,
1617
- timestamp: api.timestamp,
1618
- screenshotUrl: api.screenshot_url,
1619
- capturedAt: api.captured_at,
1620
- status: api.status
1621
- };
1622
- }
1623
- function mapErrorsResponse(api) {
1624
- return {
1625
- recordingId: api.recording_id,
1626
- totalErrors: api.total_errors,
1627
- errors: Array.isArray(api.errors) ? api.errors.map(mapBrowserError) : []
1628
- };
1629
- }
1630
- function mapWebpResponse(api) {
1631
- return {
1632
- webpUrl: api.webp_url,
1633
- cached: api.cached,
1634
- width: api.width,
1635
- fps: api.fps,
1636
- maxDuration: api.max_duration,
1637
- fileSize: api.file_size,
1638
- maxSizeMb: api.max_size_mb,
1639
- budgetMet: api.budget_met,
1640
- qualityUsed: api.quality_used,
1641
- attempts: api.attempts
1642
- };
1643
- }
1644
- async function getTaskStatus(taskId, config) {
1645
- const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;
1646
- const debug = config.debug || false;
1647
- if (debug) console.log(`[Browser] getTaskStatus: ${taskId}`);
1648
- const headers = {};
1649
- if (config.apiKey) headers["Authorization"] = `Bearer ${config.apiKey}`;
1650
- const response = await fetch(`${apiUrl}/tasks/${taskId}`, {
1651
- method: "GET",
1652
- headers
1653
- });
1654
- if (!response.ok) {
1655
- const errorText = await response.text().catch(() => response.statusText);
1656
- if (debug) console.error(`[Browser] getTaskStatus error: ${response.status} - ${errorText}`);
1657
- throw new Error(`HTTP ${response.status}: ${errorText}`);
1658
- }
1659
- const result = mapTaskResult(await response.json());
1660
- if (debug) console.log(`[Browser] Task status: ${result.status}`);
1661
- return result;
1662
- }
1663
- function generateLiveUrl(taskId, config) {
1664
- const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;
1665
- const baseUrl = apiUrl.replace("/api", "");
1666
- return `${baseUrl}/tasks/${taskId}/live`;
1667
- }
1668
- async function pollTaskUntilComplete(taskId, config, pollConfig = {}) {
1669
- const interval = pollConfig.interval ?? 2e3;
1670
- const timeout = pollConfig.timeout ?? 3e5;
1671
- const startTime = Date.now();
1672
- while (Date.now() - startTime < timeout) {
1673
- const status = await getTaskStatus(taskId, config);
1674
- if (status.status === "completed" || status.status === "failed") {
1675
- return status;
1676
- }
1677
- await new Promise((resolve) => setTimeout(resolve, interval));
1678
- }
1679
- throw new Error(`Task polling timeout after ${timeout}ms`);
1680
- }
1681
- function wrapTaskResponse(result, config) {
1682
- const debugUrl = result.debugUrl ?? "";
1683
- const wrapped = {
1684
- ...result,
1685
- debugUrl,
1686
- taskId: result.taskId || "",
1687
- liveUrl: result.taskId ? generateLiveUrl(result.taskId, config) : debugUrl,
1688
- complete: async (pollConfig) => {
1689
- if (result.taskId) {
1690
- return pollTaskUntilComplete(result.taskId, config, pollConfig);
1691
- }
1692
- if (result.recordingId) {
1693
- const recording = await waitForRecording(
1694
- result.recordingId,
1695
- config,
1696
- pollConfig
1697
- );
1698
- return {
1699
- ...result,
1700
- recordingStatus: recording.status
1701
- };
1702
- }
1703
- throw new Error("Cannot poll completion: no taskId or recordingId available");
1704
- },
1705
- // Add Steel live session helpers - either functional or error-throwing
1706
- getLiveUrl: debugUrl ? (options) => buildLiveUrl(debugUrl, options) : () => {
1707
- throw new Error(
1708
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
1709
- );
1710
- },
1711
- getLiveIframe: debugUrl ? (optionsOrPreset) => {
1712
- const options = resolvePreset(optionsOrPreset);
1713
- return buildLiveIframe(debugUrl, options);
1714
- } : () => {
1715
- throw new Error(
1716
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
1717
- );
1718
- },
1719
- getEmbedCode: debugUrl ? () => buildEmbedCode(debugUrl) : () => {
1720
- throw new Error(
1721
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help."
1722
- );
1723
- }
1724
- };
1725
- return wrapped;
1726
- }
1727
- function wrapTaskResponseWithSchema(result, config, schema) {
1728
- const debugUrl = result.debugUrl ?? "";
1729
- const parsed = result.output ? parseStructuredTaskOutput(result, schema) : { ...result, parsed: null };
1730
- const wrapped = {
1731
- ...parsed,
1732
- debugUrl,
1733
- taskId: result.taskId || "",
1734
- liveUrl: result.taskId ? generateLiveUrl(result.taskId, config) : debugUrl,
1735
- complete: async (pollConfig) => {
1736
- if (result.taskId) {
1737
- const finalResult = await pollTaskUntilComplete(result.taskId, config, pollConfig);
1738
- return parseStructuredTaskOutput(finalResult, schema);
1739
- }
1740
- if (result.recordingId) {
1741
- const recording = await waitForRecording(
1742
- result.recordingId,
1743
- config,
1744
- pollConfig
1745
- );
1746
- return {
1747
- ...parsed,
1748
- recordingStatus: recording.status
1749
- };
1750
- }
1751
- throw new Error("Cannot poll completion: no taskId or recordingId available");
1752
- },
1753
- // Add Steel live session helpers - either functional or error-throwing
1754
- getLiveUrl: debugUrl ? (options) => buildLiveUrl(debugUrl, options) : () => {
1755
- throw new Error(
1756
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions. "
1757
- );
1758
- },
1759
- getLiveIframe: debugUrl ? (optionsOrPreset) => {
1760
- const options = resolvePreset(optionsOrPreset);
1761
- return buildLiveIframe(debugUrl, options);
1762
- } : () => {
1763
- throw new Error(
1764
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions."
1765
- );
1766
- },
1767
- getEmbedCode: debugUrl ? () => buildEmbedCode(debugUrl) : () => {
1768
- throw new Error(
1769
- "Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help enabling live sessions."
1770
- );
1771
- }
1772
- };
1773
- return wrapped;
1774
- }
1775
- async function getWebp(recordingId, config = {}, options = {}) {
1776
- const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;
1777
- const debug = config.debug || false;
1778
- if (!config.apiKey) {
1779
- throw new Error("API key required for getWebp");
1780
- }
1781
- const params = new URLSearchParams();
1782
- if (options.maxDuration !== void 0) params.set("max_duration", String(options.maxDuration));
1783
- if (options.fps !== void 0) params.set("fps", String(options.fps));
1784
- if (options.width !== void 0) params.set("width", String(options.width));
1785
- if (options.quality !== void 0) params.set("quality", String(options.quality));
1786
- if (options.maxSizeMb !== void 0) params.set("max_size_mb", String(options.maxSizeMb));
1787
- const url = `${apiUrl}/recordings/${recordingId}/webp${params.toString() ? "?" + params.toString() : ""}`;
1788
- if (debug) console.log(`[Browser] getWebp: ${url}`);
1789
- const response = await fetch(url, {
1790
- method: "GET",
1791
- headers: { "Authorization": `Bearer ${config.apiKey}` }
1792
- });
1793
- if (!response.ok) {
1794
- const errorText = await response.text().catch(() => response.statusText);
1795
- if (debug) console.error(`[Browser] getWebp error: ${response.status} - ${errorText}`);
1796
- throw new Error(`HTTP ${response.status}: ${errorText}`);
1797
- }
1798
- const result = mapWebpResponse(await response.json());
1799
- if (debug) console.log(`[Browser] WebP ready: ${result.webpUrl} (cached: ${result.cached})`);
1800
- return result;
1801
- }
1802
- async function checkHealth(config = {}) {
1803
- const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;
1804
- try {
1805
- const response = await fetch(`${apiUrl}/health`, {
1806
- method: "GET",
1807
- headers: config.apiKey ? { "Authorization": `Bearer ${config.apiKey}` } : {}
1808
- });
1809
- if (!response.ok) {
1810
- throw new Error(`HTTP ${response.status}`);
1811
- }
1812
- const data = await response.json();
1813
- return {
1814
- ok: true,
1815
- google_configured: data.google_configured ?? false,
1816
- database_configured: data.database_configured ?? false,
1817
- s3_configured: data.s3_configured ?? false
1818
- };
1819
- } catch (error) {
1820
- return {
1821
- ok: false,
1822
- google_configured: false,
1823
- database_configured: false,
1824
- s3_configured: false,
1825
- error: error instanceof Error ? error.message : String(error)
1826
- };
1827
- }
1828
- }
1829
-
1830
- // tools/browser/prompts.ts
1831
- var BROWSER_TOOL_DESCRIPTION = `Test and verify your implemented code in a live browser. This tool executes natural language test instructions and returns a video recording plus detailed logs to help you debug issues.
1832
-
1833
- ## When to Use
1834
- Use this AFTER coding is complete to verify your implementation:
1835
- - You've finished writing/modifying code and need to verify it works
1836
- - You need to test user interactions end-to-end (clicks, forms, navigation)
1837
- - You want to catch runtime errors, console warnings, or network failures
1838
- - You need visual confirmation that UI elements render and behave correctly
1839
-
1840
- ## What You Get Back
1841
- The tool returns debugging artifacts to help you identify and fix issues:
1842
- - **Video recording**: Watch exactly what happened in the browser session
1843
- - **Console logs**: All console.log, warnings, and errors with timestamps
1844
- - **Network logs**: Failed requests, 404s, API errors with screenshots
1845
- - **Error screenshots**: Visual snapshots captured when errors occur
1846
-
1847
- ## How to Write Good Tests
1848
- Be specific about the user journey you're testing:
1849
- \u274C Bad: "Test the login feature"
1850
- \u2705 Good: "Navigate to /login, enter 'test@example.com' and 'password123', click the Login button, verify we reach the /dashboard page"
1851
-
1852
- Include verification steps:
1853
- \u2705 "Click the Add Item button, verify the item appears in the list"
1854
- \u2705 "Submit the form, verify a success message is displayed"
1855
-
1856
- ## Iterating on Failures
1857
- 1. Run the test and review the video + logs
1858
- 2. Identify the specific issue (console error, failed request, wrong behavior)
1859
- 3. Fix the code based on the evidence
1860
- 4. Re-run the test to verify the fix
1861
- 5. Repeat until test passes
1862
-
1863
- ## Requirements
1864
- - **URL**: Must be publicly accessible (use tunnels like ngrok, Cloudflare, or deploy to staging)
1865
- - **Timing**: Use this after implementation, not during coding
1866
- - **Complexity**: Set maxSteps higher (20-30) for multi-step user workflows`;
1867
- var BROWSER_SYSTEM_PROMPT = `You are an AI agent designed to automate browser tasks to accomplish the <user_request>. Respond with a valid JSON object in the format: {"thinking": "Reason step-by-step about your current state, history, and the user request to decide your next goal and action. Analyze the browser state and screenshot to confirm the outcome of your last action.", "evaluation_previous_goal": "A concise, one-sentence evaluation of your last action's outcome (e.g., Success, Failure, or Uncertain).", "memory": "1-3 sentences summarizing key information and progress so far. This helps you track progress across multiple steps (e.g., items collected, pages visited).", "next_goal": "A clear, one-sentence description of your immediate next objective.", "action": [{"action_name": {"parameter": "value"}}]}`;
1868
-
1869
- // tools/browser/anthropic.ts
1870
- var anthropic_exports = {};
1871
- __export(anthropic_exports, {
1872
- browserTool: () => browserTool,
1873
- createBrowserTool: () => createBrowserTool
1874
- });
1875
- var browserTool = {
1876
- name: "browser_task",
1877
- description: BROWSER_TOOL_DESCRIPTION,
1878
- input_schema: {
1879
- type: "object",
1880
- properties: {
1881
- task: {
1882
- type: "string",
1883
- description: 'Natural language description of what to do (e.g., "Test checkout flow for buying a pineapple")'
1884
- },
1885
- url: {
1886
- type: "string",
1887
- description: "Starting URL (e.g., https://3000-xyz.e2b.dev). Required if navigating to a specific page."
1888
- },
1889
- maxSteps: {
1890
- type: "number",
1891
- description: "Maximum number of browser actions to take (1-50). Default: 10. Use 15-30 for complex flows.",
1892
- default: 10
1893
- },
1894
- region: {
1895
- type: "string",
1896
- enum: ["sfo", "lon"],
1897
- description: "Browserless region: sfo (US West Coast) or lon (Europe). Default: sfo.",
1898
- default: "sfo"
1899
- }
1900
- },
1901
- required: ["task"]
1902
- }
1903
- };
1904
- function formatResult(result) {
1905
- if (result.success) {
1906
- const parts = [
1907
- "\u2705 Browser task completed successfully",
1908
- `Steps taken: ${result.stepsTaken ?? 0}`,
1909
- result.executionTimeMs ? `Execution time: ${result.executionTimeMs}ms` : null,
1910
- "",
1911
- "Result:",
1912
- result.result || "Task completed"
1913
- ];
1914
- return parts.filter(Boolean).join("\n");
1915
- }
1916
- return `\u274C Browser task failed: ${result.error || "Unknown error"}`;
1917
- }
1918
- function createBrowserTool(config) {
1919
- return Object.assign({}, browserTool, {
1920
- execute: async (input) => {
1921
- return executeBrowserTask(input, config);
1922
- },
1923
- formatResult: (result) => {
1924
- return formatResult(result);
1925
- },
1926
- getSystemPrompt: () => {
1927
- return BROWSER_SYSTEM_PROMPT;
1928
- }
1929
- });
1930
- }
1931
-
1932
- // tools/browser/openai.ts
1933
- var openai_exports = {};
1934
- __export(openai_exports, {
1935
- browserTool: () => browserTool2,
1936
- createBrowserTool: () => createBrowserTool2,
1937
- execute: () => execute,
1938
- formatResult: () => formatResult2,
1939
- getSystemPrompt: () => getSystemPrompt
1940
- });
1941
- var browserTool2 = {
1942
- type: "function",
1943
- function: {
1944
- name: "browser_task",
1945
- description: BROWSER_TOOL_DESCRIPTION,
1946
- parameters: {
1947
- type: "object",
1948
- properties: {
1949
- task: {
1950
- type: "string",
1951
- description: 'Natural language description of what to do (e.g., "Test checkout flow for buying a pineapple")'
1952
- },
1953
- url: {
1954
- type: "string",
1955
- description: "Starting URL (e.g., https://3000-xyz.e2b.dev). Required if navigating to a specific page."
1956
- },
1957
- maxSteps: {
1958
- type: "number",
1959
- description: "Maximum number of browser actions to take (1-50). Default: 10. Use 15-30 for complex flows.",
1960
- default: 10
1961
- },
1962
- region: {
1963
- type: "string",
1964
- enum: ["sfo", "lon"],
1965
- description: "Browserless region: sfo (US West Coast) or lon (Europe). Default: sfo.",
1966
- default: "sfo"
1967
- }
1968
- },
1969
- required: ["task"]
1970
- }
1971
- }
1972
- };
1973
- async function execute(input, config) {
1974
- const parsedInput = typeof input === "string" ? JSON.parse(input) : input;
1975
- return executeBrowserTask(parsedInput, config);
1976
- }
1977
- function formatResult2(result) {
1978
- if (result.success) {
1979
- const parts = [
1980
- "\u2705 Browser task completed successfully",
1981
- `Steps taken: ${result.stepsTaken ?? 0}`,
1982
- result.executionTimeMs ? `Execution time: ${result.executionTimeMs}ms` : null,
1983
- "",
1984
- "Result:",
1985
- result.result || "Task completed"
1986
- ];
1987
- return parts.filter(Boolean).join("\n");
1988
- }
1989
- return `\u274C Browser task failed: ${result.error || "Unknown error"}`;
1990
- }
1991
- function getSystemPrompt() {
1992
- return BROWSER_SYSTEM_PROMPT;
1993
- }
1994
- function createBrowserTool2(config) {
1995
- return Object.assign({}, browserTool2, {
1996
- execute: async (input) => {
1997
- return execute(input, config);
1998
- },
1999
- formatResult: (result) => {
2000
- return formatResult2(result);
2001
- },
2002
- getSystemPrompt: () => {
2003
- return getSystemPrompt();
2004
- }
2005
- });
2006
- }
2007
-
2008
- // tools/browser/vercel.ts
2009
- var vercel_exports = {};
2010
- __export(vercel_exports, {
2011
- browserTool: () => browserTool3,
2012
- createBrowserTool: () => createBrowserTool3
2013
- });
2014
- var import_ai = require("ai");
2015
- var import_zod = require("zod");
2016
- function createBrowserTool3(config) {
2017
- const schema = import_zod.z.object({
2018
- task: import_zod.z.string().describe('Natural language description of what to do (e.g., "Test checkout flow for buying a pineapple")'),
2019
- url: import_zod.z.string().optional().describe("Starting URL (e.g., https://3000-xyz.e2b.dev)"),
2020
- maxSteps: import_zod.z.number().min(1).max(50).default(10).describe("Maximum number of browser actions to take"),
2021
- region: import_zod.z.enum(["sfo", "lon"]).default("sfo").describe("Browserless region: sfo (US West) or lon (Europe)")
2022
- });
2023
- return (0, import_ai.tool)({
2024
- description: BROWSER_TOOL_DESCRIPTION,
2025
- inputSchema: schema,
2026
- execute: async (params) => {
2027
- const { task, url, maxSteps, region } = params;
2028
- const result = await executeBrowserTask(
2029
- { task, url, maxSteps, region },
2030
- config
2031
- );
2032
- if (result.success) {
2033
- return {
2034
- success: true,
2035
- result: result.result,
2036
- stepsTaken: result.stepsTaken,
2037
- executionTimeMs: result.executionTimeMs
2038
- };
2039
- }
2040
- return {
2041
- success: false,
2042
- error: result.error
2043
- };
2044
- }
2045
- });
2046
- }
2047
- var browserTool3 = createBrowserTool3();
2048
-
2049
- // tools/browser/gemini.ts
2050
- var gemini_exports = {};
2051
- __export(gemini_exports, {
2052
- browserFunctionDeclaration: () => browserFunctionDeclaration,
2053
- browserTool: () => browserTool4,
2054
- createBrowserTool: () => createBrowserTool4,
2055
- default: () => gemini_default,
2056
- execute: () => execute2,
2057
- formatResult: () => formatResult3,
2058
- getSystemPrompt: () => getSystemPrompt2
2059
- });
2060
- var import_generative_ai = require("@google/generative-ai");
2061
- var TOOL_PARAMETERS = {
2062
- type: import_generative_ai.SchemaType.OBJECT,
2063
- properties: {
2064
- task: {
2065
- type: import_generative_ai.SchemaType.STRING,
2066
- description: 'Natural language description of what to do (e.g., "Test checkout flow for buying a pineapple")'
2067
- },
2068
- url: {
2069
- type: import_generative_ai.SchemaType.STRING,
2070
- description: "Starting URL (e.g., https://3000-xyz.e2b.dev). Required if navigating to a specific page."
2071
- },
2072
- maxSteps: {
2073
- type: import_generative_ai.SchemaType.NUMBER,
2074
- description: "Maximum number of browser actions to take (1-50). Default: 10. Use 15-30 for complex flows."
2075
- },
2076
- region: {
2077
- type: import_generative_ai.SchemaType.STRING,
2078
- description: "Browserless region: sfo (US West Coast) or lon (Europe). Default: sfo."
2079
- }
2080
- },
2081
- required: ["task"]
2082
- };
2083
- var browserFunctionDeclaration = {
2084
- name: "browser_task",
2085
- description: BROWSER_TOOL_DESCRIPTION,
2086
- parameters: TOOL_PARAMETERS
2087
- };
2088
- async function execute2(input, config) {
2089
- const parsedInput = typeof input === "string" ? JSON.parse(input) : input;
2090
- return executeBrowserTask(parsedInput, config);
2091
- }
2092
- function formatResult3(result) {
2093
- if (result.success) {
2094
- const parts = [
2095
- "\u2705 Browser task completed successfully",
2096
- `Steps taken: ${result.stepsTaken ?? 0}`,
2097
- result.executionTimeMs ? `Execution time: ${result.executionTimeMs}ms` : null,
2098
- "",
2099
- "Result:",
2100
- result.result || "Task completed"
2101
- ];
2102
- return parts.filter(Boolean).join("\n");
2103
- }
2104
- return `\u274C Browser task failed: ${result.error || "Unknown error"}`;
2105
- }
2106
- function getSystemPrompt2() {
2107
- return BROWSER_SYSTEM_PROMPT;
2108
- }
2109
- function createBrowserTool4(config) {
2110
- const declaration = {
2111
- name: "browser_task",
2112
- description: BROWSER_TOOL_DESCRIPTION,
2113
- parameters: TOOL_PARAMETERS
2114
- };
2115
- return Object.assign(declaration, {
2116
- execute: async (input) => {
2117
- return execute2(input, config);
2118
- },
2119
- formatResult: (result) => {
2120
- return formatResult3(result);
2121
- },
2122
- getSystemPrompt: () => {
2123
- return getSystemPrompt2();
2124
- }
2125
- });
2126
- }
2127
- var browserTool4 = browserFunctionDeclaration;
2128
- var gemini_default = browserFunctionDeclaration;
2129
- // Annotate the CommonJS export names for ESM import in node:
2130
- 0 && (module.exports = {
2131
- BROWSER_SYSTEM_PROMPT,
2132
- BROWSER_TOOL_DESCRIPTION,
2133
- BrowserClient,
2134
- LIVE_PRESETS,
2135
- MorphAPIError,
2136
- MorphAuthenticationError,
2137
- MorphError,
2138
- MorphNotFoundError,
2139
- MorphProfileLimitError,
2140
- MorphRateLimitError,
2141
- MorphValidationError,
2142
- ProfilesClient,
2143
- anthropic,
2144
- buildEmbedCode,
2145
- buildLiveIframe,
2146
- buildLiveUrl,
2147
- checkHealth,
2148
- executeBrowserTask,
2149
- executeWithRecording,
2150
- gemini,
2151
- getErrors,
2152
- getRecording,
2153
- getWebp,
2154
- openai,
2155
- parseAPIError,
2156
- vercel,
2157
- waitForRecording
2158
- });
2159
- //# sourceMappingURL=index.cjs.map