@morphllm/morphsdk 0.2.93 → 0.2.95

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 (135) hide show
  1. package/dist/chunk-2AMEQAO2.js +46 -0
  2. package/dist/chunk-2AMEQAO2.js.map +1 -0
  3. package/dist/{chunk-EI4UKP24.js → chunk-2HMEZZKK.js} +2 -2
  4. package/dist/{chunk-EI4UKP24.js.map → chunk-2HMEZZKK.js.map} +1 -1
  5. package/dist/chunk-2VERUKO2.js +177 -0
  6. package/dist/chunk-2VERUKO2.js.map +1 -0
  7. package/dist/{chunk-VHOWYK66.js → chunk-43LQLGP6.js} +23 -33
  8. package/dist/chunk-43LQLGP6.js.map +1 -0
  9. package/dist/{chunk-LMUZ3NGC.js → chunk-73RV6EXR.js} +2 -2
  10. package/dist/{chunk-PBLPZ6AU.js → chunk-7D6TXC7X.js} +2 -2
  11. package/dist/{chunk-GU6DACME.js → chunk-O7LDZA52.js} +2 -2
  12. package/dist/{chunk-5QIWYEHJ.js → chunk-PE4KGDA6.js} +1 -8
  13. package/dist/chunk-PE4KGDA6.js.map +1 -0
  14. package/dist/{chunk-SQN4DUQS.js → chunk-Q6Y4R236.js} +26 -2
  15. package/dist/chunk-Q6Y4R236.js.map +1 -0
  16. package/dist/{chunk-PUGIOVSP.js → chunk-QAT5UVPX.js} +2 -2
  17. package/dist/{chunk-MIIJWDOQ.js → chunk-QJP62BXH.js} +166 -71
  18. package/dist/chunk-QJP62BXH.js.map +1 -0
  19. package/dist/{chunk-EYGBUH2R.js → chunk-R7IQWNSA.js} +8 -8
  20. package/dist/chunk-R7IQWNSA.js.map +1 -0
  21. package/dist/chunk-SI2CKRKJ.js +389 -0
  22. package/dist/chunk-SI2CKRKJ.js.map +1 -0
  23. package/dist/{chunk-4WLGDYWQ.js → chunk-TSENDJQI.js} +6 -6
  24. package/dist/chunk-TSENDJQI.js.map +1 -0
  25. package/dist/{chunk-IUG2FHNN.js → chunk-XH7P7HVT.js} +1 -8
  26. package/dist/chunk-XH7P7HVT.js.map +1 -0
  27. package/dist/{chunk-FNLNDMIX.js → chunk-YZ5NCWO2.js} +6 -6
  28. package/dist/chunk-YZ5NCWO2.js.map +1 -0
  29. package/dist/{chunk-IJ54DTJ3.js → chunk-ZYTAKEBW.js} +13 -13
  30. package/dist/client.cjs +770 -110
  31. package/dist/client.cjs.map +1 -1
  32. package/dist/client.d.ts +2 -0
  33. package/dist/client.js +16 -13
  34. package/dist/index.cjs +770 -110
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.ts +2 -0
  37. package/dist/index.js +16 -13
  38. package/dist/tools/browser/anthropic.cjs +58 -23
  39. package/dist/tools/browser/anthropic.cjs.map +1 -1
  40. package/dist/tools/browser/anthropic.js +7 -4
  41. package/dist/tools/browser/core.cjs +750 -70
  42. package/dist/tools/browser/core.cjs.map +1 -1
  43. package/dist/tools/browser/core.d.ts +30 -24
  44. package/dist/tools/browser/core.js +5 -2
  45. package/dist/tools/browser/errors.cjs +208 -0
  46. package/dist/tools/browser/errors.cjs.map +1 -0
  47. package/dist/tools/browser/errors.d.ts +158 -0
  48. package/dist/tools/browser/errors.js +22 -0
  49. package/dist/tools/browser/errors.js.map +1 -0
  50. package/dist/tools/browser/index.cjs +783 -85
  51. package/dist/tools/browser/index.cjs.map +1 -1
  52. package/dist/tools/browser/index.d.ts +5 -2
  53. package/dist/tools/browser/index.js +32 -9
  54. package/dist/tools/browser/index.js.map +1 -1
  55. package/dist/tools/browser/live.cjs +25 -1
  56. package/dist/tools/browser/live.cjs.map +1 -1
  57. package/dist/tools/browser/live.js +1 -1
  58. package/dist/tools/browser/openai.cjs +58 -23
  59. package/dist/tools/browser/openai.cjs.map +1 -1
  60. package/dist/tools/browser/openai.js +7 -4
  61. package/dist/tools/browser/profiles/core.cjs +670 -0
  62. package/dist/tools/browser/profiles/core.cjs.map +1 -0
  63. package/dist/tools/browser/profiles/core.d.ts +187 -0
  64. package/dist/tools/browser/profiles/core.js +29 -0
  65. package/dist/tools/browser/profiles/core.js.map +1 -0
  66. package/dist/tools/browser/profiles/index.cjs +670 -0
  67. package/dist/tools/browser/profiles/index.cjs.map +1 -0
  68. package/dist/tools/browser/profiles/index.d.ts +4 -0
  69. package/dist/tools/browser/profiles/index.js +29 -0
  70. package/dist/tools/browser/profiles/index.js.map +1 -0
  71. package/dist/tools/browser/profiles/types.cjs +74 -0
  72. package/dist/tools/browser/profiles/types.cjs.map +1 -0
  73. package/dist/tools/browser/profiles/types.d.ts +195 -0
  74. package/dist/tools/browser/profiles/types.js +16 -0
  75. package/dist/tools/browser/profiles/types.js.map +1 -0
  76. package/dist/tools/browser/prompts.cjs +1 -1
  77. package/dist/tools/browser/prompts.cjs.map +1 -1
  78. package/dist/tools/browser/prompts.d.ts +1 -1
  79. package/dist/tools/browser/prompts.js +1 -1
  80. package/dist/tools/browser/types.cjs.map +1 -1
  81. package/dist/tools/browser/types.d.ts +55 -51
  82. package/dist/tools/browser/vercel.cjs +60 -25
  83. package/dist/tools/browser/vercel.cjs.map +1 -1
  84. package/dist/tools/browser/vercel.d.ts +1 -1
  85. package/dist/tools/browser/vercel.js +7 -4
  86. package/dist/tools/fastapply/anthropic.cjs +0 -7
  87. package/dist/tools/fastapply/anthropic.cjs.map +1 -1
  88. package/dist/tools/fastapply/anthropic.js +1 -1
  89. package/dist/tools/fastapply/index.cjs +0 -14
  90. package/dist/tools/fastapply/index.cjs.map +1 -1
  91. package/dist/tools/fastapply/index.js +5 -5
  92. package/dist/tools/fastapply/openai.cjs +0 -7
  93. package/dist/tools/fastapply/openai.cjs.map +1 -1
  94. package/dist/tools/fastapply/openai.js +1 -1
  95. package/dist/tools/index.cjs +0 -14
  96. package/dist/tools/index.cjs.map +1 -1
  97. package/dist/tools/index.js +5 -5
  98. package/dist/tools/warp_grep/agent/runner.cjs +18 -98
  99. package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
  100. package/dist/tools/warp_grep/agent/runner.js +2 -3
  101. package/dist/tools/warp_grep/anthropic.cjs +18 -98
  102. package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
  103. package/dist/tools/warp_grep/anthropic.js +8 -9
  104. package/dist/tools/warp_grep/client.cjs +18 -98
  105. package/dist/tools/warp_grep/client.cjs.map +1 -1
  106. package/dist/tools/warp_grep/client.js +5 -6
  107. package/dist/tools/warp_grep/gemini.cjs +18 -98
  108. package/dist/tools/warp_grep/gemini.cjs.map +1 -1
  109. package/dist/tools/warp_grep/gemini.js +7 -8
  110. package/dist/tools/warp_grep/gemini.js.map +1 -1
  111. package/dist/tools/warp_grep/harness.js +10 -10
  112. package/dist/tools/warp_grep/index.cjs +18 -98
  113. package/dist/tools/warp_grep/index.cjs.map +1 -1
  114. package/dist/tools/warp_grep/index.js +8 -9
  115. package/dist/tools/warp_grep/openai.cjs +18 -98
  116. package/dist/tools/warp_grep/openai.cjs.map +1 -1
  117. package/dist/tools/warp_grep/openai.js +8 -9
  118. package/dist/tools/warp_grep/vercel.cjs +18 -98
  119. package/dist/tools/warp_grep/vercel.cjs.map +1 -1
  120. package/dist/tools/warp_grep/vercel.js +8 -9
  121. package/dist/{vercel-CsnNSdze.d.ts → vercel-CVF27qFK.d.ts} +10 -10
  122. package/package.json +7 -2
  123. package/dist/chunk-4WLGDYWQ.js.map +0 -1
  124. package/dist/chunk-5QIWYEHJ.js.map +0 -1
  125. package/dist/chunk-EYGBUH2R.js.map +0 -1
  126. package/dist/chunk-FNLNDMIX.js.map +0 -1
  127. package/dist/chunk-IUG2FHNN.js.map +0 -1
  128. package/dist/chunk-MIIJWDOQ.js.map +0 -1
  129. package/dist/chunk-SQN4DUQS.js.map +0 -1
  130. package/dist/chunk-VHOWYK66.js.map +0 -1
  131. /package/dist/{chunk-LMUZ3NGC.js.map → chunk-73RV6EXR.js.map} +0 -0
  132. /package/dist/{chunk-PBLPZ6AU.js.map → chunk-7D6TXC7X.js.map} +0 -0
  133. /package/dist/{chunk-GU6DACME.js.map → chunk-O7LDZA52.js.map} +0 -0
  134. /package/dist/{chunk-PUGIOVSP.js.map → chunk-QAT5UVPX.js.map} +0 -0
  135. /package/dist/{chunk-IJ54DTJ3.js.map → chunk-ZYTAKEBW.js.map} +0 -0
@@ -0,0 +1,46 @@
1
+ // tools/browser/profiles/types.ts
2
+ function transformProfile(api) {
3
+ return {
4
+ id: api.id,
5
+ name: api.name,
6
+ repoId: api.repo_id,
7
+ cookieDomains: api.cookie_domains,
8
+ lastUsedAt: api.last_used_at,
9
+ createdAt: api.created_at,
10
+ updatedAt: api.updated_at
11
+ };
12
+ }
13
+ function transformCreateInput(input) {
14
+ return {
15
+ name: input.name,
16
+ repo_id: input.repoId
17
+ };
18
+ }
19
+ function transformSession(api) {
20
+ return {
21
+ sessionId: api.session_id,
22
+ debugUrl: api.debug_url || ""
23
+ };
24
+ }
25
+ function transformSaveInput(input) {
26
+ return {
27
+ session_id: input.sessionId,
28
+ profile_id: input.profileId
29
+ };
30
+ }
31
+ function transformStateResponse(api) {
32
+ return {
33
+ profileId: api.profile_id,
34
+ stateUrl: api.state_url,
35
+ expiresIn: api.expires_in
36
+ };
37
+ }
38
+
39
+ export {
40
+ transformProfile,
41
+ transformCreateInput,
42
+ transformSession,
43
+ transformSaveInput,
44
+ transformStateResponse
45
+ };
46
+ //# sourceMappingURL=chunk-2AMEQAO2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../tools/browser/profiles/types.ts"],"sourcesContent":["/**\n * Type definitions for browser profiles.\n *\n * All types use camelCase for SDK ergonomics.\n * API responses are normalized from snake_case to camelCase.\n */\n\n/**\n * A browser profile that stores login state (cookies, localStorage).\n *\n * @example\n * ```typescript\n * const profile = await morph.browser.profiles.getProfile('profile-id');\n * console.log(profile.cookieDomains); // ['linkedin.com', 'google.com']\n * ```\n */\nexport interface Profile {\n /** Unique profile identifier (UUID) */\n id: string;\n /** Human-readable profile name */\n name: string;\n /** Repository ID this profile is associated with */\n repoId: string;\n /** List of domains with stored cookies */\n cookieDomains?: string[];\n /** ISO 8601 timestamp of last use */\n lastUsedAt?: string;\n /** ISO 8601 timestamp of creation */\n createdAt: string;\n /** ISO 8601 timestamp of last update */\n updatedAt: string;\n}\n\n/**\n * Input for creating a new profile.\n *\n * @example\n * ```typescript\n * await morph.browser.profiles.createProfile({\n * name: 'LinkedIn Production',\n * repoId: 'owner/repo'\n * });\n * ```\n */\nexport interface CreateProfileInput {\n /** Profile name (1-100 characters) */\n name: string;\n /** Repository ID - profiles are repo-specific */\n repoId: string;\n}\n\n/**\n * Input for updating a profile.\n */\n// Intentionally no UpdateProfileInput: update means \"open a live session\"\n\n/**\n * Response for listing profiles.\n */\nexport interface ProfileListResponse {\n profiles: Profile[];\n}\n\n/**\n * A browser session for profile setup.\n *\n * @example\n * ```typescript\n * const session = await morph.browser.profiles.startSession();\n * console.log('Sign in at:', session.debugUrl);\n * // After user signs in...\n * await morph.browser.profiles.saveSession(session.sessionId, profile.id);\n * ```\n */\nexport interface ProfileSession {\n /** Unique session identifier */\n sessionId: string;\n /** Live session URL for viewing/interacting with the browser */\n debugUrl: string;\n}\n\n/**\n * Profile setup handle returned by create/update.\n *\n * Provides a live URL for login and an explicit save() helper.\n */\nexport interface ProfileSetup {\n profile: Profile;\n session: ProfileSession;\n save: () => Promise<Profile>;\n}\n/**\n * Input for starting a profile session.\n */\nexport interface ProfileSessionInput {\n /** Optional profile ID to update an existing profile */\n profileId?: string;\n}\n\n/**\n * Input for saving a profile session.\n */\nexport interface SaveProfileSessionInput {\n /** The browser session ID to extract state from */\n sessionId: string;\n /** The profile ID to save state to */\n profileId: string;\n}\n\n/**\n * Response for profile state URL.\n */\nexport interface ProfileStateResponse {\n /** Profile ID */\n profileId: string;\n /** Presigned URL to download the profile state (expires in `expiresIn` seconds) */\n stateUrl: string;\n /** URL expiry time in seconds */\n expiresIn: number;\n}\n\n/**\n * Repo summary for profile discovery.\n */\nexport interface RepoSummary {\n repoId: string;\n repoFullName?: string;\n profileCount: number;\n}\n\n/**\n * Response for repo discovery.\n */\nexport interface RepoListResponse {\n repos: RepoSummary[];\n}\n\n/**\n * Profile with convenience methods attached.\n *\n * @example\n * ```typescript\n * const profile = await morph.browser.profiles.getProfile('id');\n * const state = await profile.getState();\n * await profile.delete();\n * ```\n */\nexport interface ProfileWithMethods extends Profile {\n /** Get presigned URL for profile state */\n getState: () => Promise<ProfileStateResponse>;\n /** Delete this profile */\n delete: () => Promise<void>;\n}\n\n// ============================================================================\n// Internal API types (snake_case - matches backend response)\n// ============================================================================\n\n/** @internal API response format */\nexport interface APIProfile {\n id: string;\n name: string;\n repo_id: string;\n cookie_domains?: string[];\n last_used_at?: string;\n created_at: string;\n updated_at: string;\n}\n\n/** @internal API response format */\nexport interface APIProfileSession {\n session_id: string;\n debug_url?: string;\n}\n\n/** @internal API response format */\nexport interface APIProfileStateResponse {\n profile_id: string;\n state_url: string;\n expires_in: number;\n}\n\n// ============================================================================\n// Transformers\n// ============================================================================\n\n/**\n * Transform API profile response to SDK format.\n * @internal\n */\nexport function transformProfile(api: APIProfile): Profile {\n return {\n id: api.id,\n name: api.name,\n repoId: api.repo_id,\n cookieDomains: api.cookie_domains,\n lastUsedAt: api.last_used_at,\n createdAt: api.created_at,\n updatedAt: api.updated_at,\n };\n}\n\n/**\n * Transform SDK input to API format.\n * @internal\n */\nexport function transformCreateInput(input: CreateProfileInput): { name: string; repo_id: string } {\n return {\n name: input.name,\n repo_id: input.repoId,\n };\n}\n\n/**\n * Transform API session response to SDK format.\n * @internal\n */\nexport function transformSession(api: APIProfileSession): ProfileSession {\n return {\n sessionId: api.session_id,\n debugUrl: api.debug_url || '',\n };\n}\n\n/**\n * Transform SDK save input to API format.\n * @internal\n */\nexport function transformSaveInput(input: SaveProfileSessionInput): { session_id: string; profile_id: string } {\n return {\n session_id: input.sessionId,\n profile_id: input.profileId,\n };\n}\n\n/**\n * Transform API state response to SDK format.\n * @internal\n */\nexport function transformStateResponse(api: APIProfileStateResponse): ProfileStateResponse {\n return {\n profileId: api.profile_id,\n stateUrl: api.state_url,\n expiresIn: api.expires_in,\n };\n}\n"],"mappings":";AA8LO,SAAS,iBAAiB,KAA0B;AACzD,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,MAAM,IAAI;AAAA,IACV,QAAQ,IAAI;AAAA,IACZ,eAAe,IAAI;AAAA,IACnB,YAAY,IAAI;AAAA,IAChB,WAAW,IAAI;AAAA,IACf,WAAW,IAAI;AAAA,EACjB;AACF;AAMO,SAAS,qBAAqB,OAA8D;AACjG,SAAO;AAAA,IACL,MAAM,MAAM;AAAA,IACZ,SAAS,MAAM;AAAA,EACjB;AACF;AAMO,SAAS,iBAAiB,KAAwC;AACvE,SAAO;AAAA,IACL,WAAW,IAAI;AAAA,IACf,UAAU,IAAI,aAAa;AAAA,EAC7B;AACF;AAMO,SAAS,mBAAmB,OAA4E;AAC7G,SAAO;AAAA,IACL,YAAY,MAAM;AAAA,IAClB,YAAY,MAAM;AAAA,EACpB;AACF;AAMO,SAAS,uBAAuB,KAAoD;AACzF,SAAO;AAAA,IACL,WAAW,IAAI;AAAA,IACf,UAAU,IAAI;AAAA,IACd,WAAW,IAAI;AAAA,EACjB;AACF;","names":[]}
@@ -34,11 +34,11 @@ Include verification steps:
34
34
  ## Requirements
35
35
  - **URL**: Must be publicly accessible (use tunnels like ngrok, Cloudflare, or deploy to staging)
36
36
  - **Timing**: Use this after implementation, not during coding
37
- - **Complexity**: Set max_steps higher (20-30) for multi-step user workflows`;
37
+ - **Complexity**: Set maxSteps higher (20-30) for multi-step user workflows`;
38
38
  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"}}]}`;
39
39
 
40
40
  export {
41
41
  BROWSER_TOOL_DESCRIPTION,
42
42
  BROWSER_SYSTEM_PROMPT
43
43
  };
44
- //# sourceMappingURL=chunk-EI4UKP24.js.map
44
+ //# sourceMappingURL=chunk-2HMEZZKK.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../tools/browser/prompts.ts"],"sourcesContent":["/**\n * Tool descriptions and prompts for AI models\n */\n\nexport const 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.\n\n## When to Use\nUse this AFTER coding is complete to verify your implementation:\n- You've finished writing/modifying code and need to verify it works\n- You need to test user interactions end-to-end (clicks, forms, navigation)\n- You want to catch runtime errors, console warnings, or network failures\n- You need visual confirmation that UI elements render and behave correctly\n\n## What You Get Back\nThe tool returns debugging artifacts to help you identify and fix issues:\n- **Video recording**: Watch exactly what happened in the browser session\n- **Console logs**: All console.log, warnings, and errors with timestamps\n- **Network logs**: Failed requests, 404s, API errors with screenshots\n- **Error screenshots**: Visual snapshots captured when errors occur\n\n## How to Write Good Tests\nBe specific about the user journey you're testing:\n❌ Bad: \"Test the login feature\"\n✅ Good: \"Navigate to /login, enter 'test@example.com' and 'password123', click the Login button, verify we reach the /dashboard page\"\n\nInclude verification steps:\n✅ \"Click the Add Item button, verify the item appears in the list\"\n✅ \"Submit the form, verify a success message is displayed\"\n\n## Iterating on Failures\n1. Run the test and review the video + logs\n2. Identify the specific issue (console error, failed request, wrong behavior)\n3. Fix the code based on the evidence\n4. Re-run the test to verify the fix\n5. Repeat until test passes\n\n## Requirements\n- **URL**: Must be publicly accessible (use tunnels like ngrok, Cloudflare, or deploy to staging)\n- **Timing**: Use this after implementation, not during coding\n- **Complexity**: Set max_steps higher (20-30) for multi-step user workflows`;\n\n\nexport const 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\"}}]}`;\n"],"mappings":";AAIO,IAAM,2BAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsCjC,IAAM,wBAAwB;","names":[]}
1
+ {"version":3,"sources":["../tools/browser/prompts.ts"],"sourcesContent":["/**\n * Tool descriptions and prompts for AI models\n */\n\nexport const 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.\n\n## When to Use\nUse this AFTER coding is complete to verify your implementation:\n- You've finished writing/modifying code and need to verify it works\n- You need to test user interactions end-to-end (clicks, forms, navigation)\n- You want to catch runtime errors, console warnings, or network failures\n- You need visual confirmation that UI elements render and behave correctly\n\n## What You Get Back\nThe tool returns debugging artifacts to help you identify and fix issues:\n- **Video recording**: Watch exactly what happened in the browser session\n- **Console logs**: All console.log, warnings, and errors with timestamps\n- **Network logs**: Failed requests, 404s, API errors with screenshots\n- **Error screenshots**: Visual snapshots captured when errors occur\n\n## How to Write Good Tests\nBe specific about the user journey you're testing:\n❌ Bad: \"Test the login feature\"\n✅ Good: \"Navigate to /login, enter 'test@example.com' and 'password123', click the Login button, verify we reach the /dashboard page\"\n\nInclude verification steps:\n✅ \"Click the Add Item button, verify the item appears in the list\"\n✅ \"Submit the form, verify a success message is displayed\"\n\n## Iterating on Failures\n1. Run the test and review the video + logs\n2. Identify the specific issue (console error, failed request, wrong behavior)\n3. Fix the code based on the evidence\n4. Re-run the test to verify the fix\n5. Repeat until test passes\n\n## Requirements\n- **URL**: Must be publicly accessible (use tunnels like ngrok, Cloudflare, or deploy to staging)\n- **Timing**: Use this after implementation, not during coding\n- **Complexity**: Set maxSteps higher (20-30) for multi-step user workflows`;\n\n\nexport const 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\"}}]}`;\n"],"mappings":";AAIO,IAAM,2BAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsCjC,IAAM,wBAAwB;","names":[]}
@@ -0,0 +1,177 @@
1
+ // tools/browser/errors.ts
2
+ var MorphError = class extends Error {
3
+ /** Error code for programmatic handling */
4
+ code;
5
+ /** Original cause of the error, if any */
6
+ cause;
7
+ constructor(message, code, cause) {
8
+ super(message);
9
+ this.name = "MorphError";
10
+ this.code = code;
11
+ this.cause = cause;
12
+ if (Error.captureStackTrace) {
13
+ Error.captureStackTrace(this, this.constructor);
14
+ }
15
+ }
16
+ /**
17
+ * Returns a JSON representation of the error for logging.
18
+ */
19
+ toJSON() {
20
+ return {
21
+ name: this.name,
22
+ message: this.message,
23
+ code: this.code,
24
+ cause: this.cause?.message
25
+ };
26
+ }
27
+ };
28
+ var MorphValidationError = class extends MorphError {
29
+ /** The field that failed validation */
30
+ field;
31
+ constructor(message, field) {
32
+ super(message, "validation_error");
33
+ this.name = "MorphValidationError";
34
+ this.field = field;
35
+ }
36
+ toJSON() {
37
+ return {
38
+ ...super.toJSON(),
39
+ field: this.field
40
+ };
41
+ }
42
+ };
43
+ var MorphAPIError = class extends MorphError {
44
+ /** HTTP status code */
45
+ statusCode;
46
+ /** Request ID for debugging (if available) */
47
+ requestId;
48
+ /** Raw response body */
49
+ rawResponse;
50
+ constructor(message, code, statusCode, options) {
51
+ super(message, code, options?.cause);
52
+ this.name = "MorphAPIError";
53
+ this.statusCode = statusCode;
54
+ this.requestId = options?.requestId;
55
+ this.rawResponse = options?.rawResponse;
56
+ }
57
+ toJSON() {
58
+ return {
59
+ ...super.toJSON(),
60
+ statusCode: this.statusCode,
61
+ requestId: this.requestId
62
+ };
63
+ }
64
+ };
65
+ var MorphAuthenticationError = class extends MorphAPIError {
66
+ constructor(message = "Authentication required. Please provide a valid API key.") {
67
+ super(message, "authentication_required", 401);
68
+ this.name = "MorphAuthenticationError";
69
+ }
70
+ };
71
+ var MorphRateLimitError = class extends MorphAPIError {
72
+ /** When the rate limit resets (Unix timestamp) */
73
+ resetAt;
74
+ /** Number of seconds until reset */
75
+ retryAfter;
76
+ constructor(message = "Rate limit exceeded. Please retry later.", options) {
77
+ super(message, "rate_limit_exceeded", 429, { requestId: options?.requestId });
78
+ this.name = "MorphRateLimitError";
79
+ this.resetAt = options?.resetAt;
80
+ this.retryAfter = options?.retryAfter;
81
+ }
82
+ toJSON() {
83
+ return {
84
+ ...super.toJSON(),
85
+ resetAt: this.resetAt,
86
+ retryAfter: this.retryAfter
87
+ };
88
+ }
89
+ };
90
+ var MorphNotFoundError = class extends MorphAPIError {
91
+ /** The type of resource that was not found */
92
+ resourceType;
93
+ /** The ID of the resource that was not found */
94
+ resourceId;
95
+ constructor(resourceType, resourceId) {
96
+ const message = resourceId ? `${resourceType} '${resourceId}' not found` : `${resourceType} not found`;
97
+ super(message, "resource_not_found", 404);
98
+ this.name = "MorphNotFoundError";
99
+ this.resourceType = resourceType;
100
+ this.resourceId = resourceId;
101
+ }
102
+ toJSON() {
103
+ return {
104
+ ...super.toJSON(),
105
+ resourceType: this.resourceType,
106
+ resourceId: this.resourceId
107
+ };
108
+ }
109
+ };
110
+ var MorphProfileLimitError = class extends MorphAPIError {
111
+ /** Current number of profiles */
112
+ currentCount;
113
+ /** Maximum allowed profiles for the plan */
114
+ maxAllowed;
115
+ constructor(message = "Profile limit exceeded for your plan.", options) {
116
+ super(message, "profile_limit_exceeded", 403, { requestId: options?.requestId });
117
+ this.name = "MorphProfileLimitError";
118
+ this.currentCount = options?.currentCount;
119
+ this.maxAllowed = options?.maxAllowed;
120
+ }
121
+ toJSON() {
122
+ return {
123
+ ...super.toJSON(),
124
+ currentCount: this.currentCount,
125
+ maxAllowed: this.maxAllowed
126
+ };
127
+ }
128
+ };
129
+ function parseAPIError(statusCode, responseText, requestId) {
130
+ let errorData = {};
131
+ try {
132
+ errorData = JSON.parse(responseText);
133
+ } catch {
134
+ }
135
+ const message = errorData.detail || errorData.message || responseText || "Unknown error";
136
+ const code = errorData.code;
137
+ switch (statusCode) {
138
+ case 401:
139
+ return new MorphAuthenticationError(message);
140
+ case 403:
141
+ if (code === "profile_limit_exceeded" || message.toLowerCase().includes("limit")) {
142
+ return new MorphProfileLimitError(message, { requestId });
143
+ }
144
+ return new MorphAPIError(message, "insufficient_permissions", statusCode, { requestId, rawResponse: responseText });
145
+ case 404:
146
+ if (message.toLowerCase().includes("profile")) {
147
+ return new MorphNotFoundError("Profile", void 0);
148
+ }
149
+ if (message.toLowerCase().includes("session")) {
150
+ return new MorphNotFoundError("Session", void 0);
151
+ }
152
+ return new MorphAPIError(message, "resource_not_found", statusCode, { requestId, rawResponse: responseText });
153
+ case 429:
154
+ return new MorphRateLimitError(message, { requestId });
155
+ case 422:
156
+ return new MorphAPIError(message, "validation_error", statusCode, { requestId, rawResponse: responseText });
157
+ case 500:
158
+ case 502:
159
+ case 503:
160
+ case 504:
161
+ return new MorphAPIError(message, "service_unavailable", statusCode, { requestId, rawResponse: responseText });
162
+ default:
163
+ return new MorphAPIError(message, "network_error", statusCode, { requestId, rawResponse: responseText });
164
+ }
165
+ }
166
+
167
+ export {
168
+ MorphError,
169
+ MorphValidationError,
170
+ MorphAPIError,
171
+ MorphAuthenticationError,
172
+ MorphRateLimitError,
173
+ MorphNotFoundError,
174
+ MorphProfileLimitError,
175
+ parseAPIError
176
+ };
177
+ //# sourceMappingURL=chunk-2VERUKO2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../tools/browser/errors.ts"],"sourcesContent":["/**\n * Custom error classes for browser automation and profiles.\n *\n * @example\n * ```typescript\n * try {\n * await morph.browser.profiles.createProfile({ name: '', repoId: 'owner/repo' });\n * } catch (e) {\n * if (e instanceof MorphValidationError) {\n * console.log('Validation failed:', e.field, e.message);\n * } else if (e instanceof MorphAPIError) {\n * console.log('API error:', e.code, e.statusCode);\n * }\n * }\n * ```\n */\n\n/**\n * Error codes for Morph Browser SDK\n */\nexport type MorphErrorCode =\n // Validation errors\n | 'validation_error'\n | 'invalid_parameter'\n | 'missing_required_field'\n // Authentication errors\n | 'authentication_required'\n | 'invalid_api_key'\n | 'insufficient_permissions'\n // Resource errors\n | 'profile_not_found'\n | 'session_not_found'\n | 'resource_not_found'\n // Limit errors\n | 'profile_limit_exceeded'\n | 'rate_limit_exceeded'\n // Session errors\n | 'session_expired'\n | 'session_save_failed'\n // Network errors\n | 'network_error'\n | 'timeout'\n | 'service_unavailable';\n\n/**\n * Base error class for all Morph SDK errors.\n */\nexport class MorphError extends Error {\n /** Error code for programmatic handling */\n readonly code: MorphErrorCode;\n /** Original cause of the error, if any */\n readonly cause?: Error;\n\n constructor(message: string, code: MorphErrorCode, cause?: Error) {\n super(message);\n this.name = 'MorphError';\n this.code = code;\n this.cause = cause;\n\n // Maintains proper stack trace in V8 environments\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Returns a JSON representation of the error for logging.\n */\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n cause: this.cause?.message,\n };\n }\n}\n\n/**\n * Error thrown when API request validation fails.\n */\nexport class MorphValidationError extends MorphError {\n /** The field that failed validation */\n readonly field?: string;\n\n constructor(message: string, field?: string) {\n super(message, 'validation_error');\n this.name = 'MorphValidationError';\n this.field = field;\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n field: this.field,\n };\n }\n}\n\n/**\n * Error thrown when an API request fails.\n */\nexport class MorphAPIError extends MorphError {\n /** HTTP status code */\n readonly statusCode: number;\n /** Request ID for debugging (if available) */\n readonly requestId?: string;\n /** Raw response body */\n readonly rawResponse?: string;\n\n constructor(\n message: string,\n code: MorphErrorCode,\n statusCode: number,\n options?: {\n requestId?: string;\n rawResponse?: string;\n cause?: Error;\n }\n ) {\n super(message, code, options?.cause);\n this.name = 'MorphAPIError';\n this.statusCode = statusCode;\n this.requestId = options?.requestId;\n this.rawResponse = options?.rawResponse;\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n statusCode: this.statusCode,\n requestId: this.requestId,\n };\n }\n}\n\n/**\n * Error thrown when authentication fails.\n */\nexport class MorphAuthenticationError extends MorphAPIError {\n constructor(message: string = 'Authentication required. Please provide a valid API key.') {\n super(message, 'authentication_required', 401);\n this.name = 'MorphAuthenticationError';\n }\n}\n\n/**\n * Error thrown when rate limit is exceeded.\n */\nexport class MorphRateLimitError extends MorphAPIError {\n /** When the rate limit resets (Unix timestamp) */\n readonly resetAt?: number;\n /** Number of seconds until reset */\n readonly retryAfter?: number;\n\n constructor(\n message: string = 'Rate limit exceeded. Please retry later.',\n options?: {\n resetAt?: number;\n retryAfter?: number;\n requestId?: string;\n }\n ) {\n super(message, 'rate_limit_exceeded', 429, { requestId: options?.requestId });\n this.name = 'MorphRateLimitError';\n this.resetAt = options?.resetAt;\n this.retryAfter = options?.retryAfter;\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n resetAt: this.resetAt,\n retryAfter: this.retryAfter,\n };\n }\n}\n\n/**\n * Error thrown when a resource is not found.\n */\nexport class MorphNotFoundError extends MorphAPIError {\n /** The type of resource that was not found */\n readonly resourceType: string;\n /** The ID of the resource that was not found */\n readonly resourceId?: string;\n\n constructor(resourceType: string, resourceId?: string) {\n const message = resourceId\n ? `${resourceType} '${resourceId}' not found`\n : `${resourceType} not found`;\n super(message, 'resource_not_found', 404);\n this.name = 'MorphNotFoundError';\n this.resourceType = resourceType;\n this.resourceId = resourceId;\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n resourceType: this.resourceType,\n resourceId: this.resourceId,\n };\n }\n}\n\n/**\n * Error thrown when profile limit is exceeded.\n */\nexport class MorphProfileLimitError extends MorphAPIError {\n /** Current number of profiles */\n readonly currentCount?: number;\n /** Maximum allowed profiles for the plan */\n readonly maxAllowed?: number;\n\n constructor(\n message: string = 'Profile limit exceeded for your plan.',\n options?: {\n currentCount?: number;\n maxAllowed?: number;\n requestId?: string;\n }\n ) {\n super(message, 'profile_limit_exceeded', 403, { requestId: options?.requestId });\n this.name = 'MorphProfileLimitError';\n this.currentCount = options?.currentCount;\n this.maxAllowed = options?.maxAllowed;\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n currentCount: this.currentCount,\n maxAllowed: this.maxAllowed,\n };\n }\n}\n\n/**\n * Parse an API error response and return the appropriate error class.\n */\nexport function parseAPIError(\n statusCode: number,\n responseText: string,\n requestId?: string\n): MorphAPIError {\n // Try to parse JSON error response\n let errorData: { detail?: string; code?: string; message?: string } = {};\n try {\n errorData = JSON.parse(responseText);\n } catch {\n // Not JSON, use raw text\n }\n\n const message = errorData.detail || errorData.message || responseText || 'Unknown error';\n const code = errorData.code;\n\n // Map status codes to specific error classes\n switch (statusCode) {\n case 401:\n return new MorphAuthenticationError(message);\n\n case 403:\n if (code === 'profile_limit_exceeded' || message.toLowerCase().includes('limit')) {\n return new MorphProfileLimitError(message, { requestId });\n }\n return new MorphAPIError(message, 'insufficient_permissions', statusCode, { requestId, rawResponse: responseText });\n\n case 404:\n if (message.toLowerCase().includes('profile')) {\n return new MorphNotFoundError('Profile', undefined);\n }\n if (message.toLowerCase().includes('session')) {\n return new MorphNotFoundError('Session', undefined);\n }\n return new MorphAPIError(message, 'resource_not_found', statusCode, { requestId, rawResponse: responseText });\n\n case 429:\n return new MorphRateLimitError(message, { requestId });\n\n case 422:\n return new MorphAPIError(message, 'validation_error', statusCode, { requestId, rawResponse: responseText });\n\n case 500:\n case 502:\n case 503:\n case 504:\n return new MorphAPIError(message, 'service_unavailable', statusCode, { requestId, rawResponse: responseText });\n\n default:\n return new MorphAPIError(message, 'network_error', statusCode, { requestId, rawResponse: responseText });\n }\n}\n"],"mappings":";AA+CO,IAAM,aAAN,cAAyB,MAAM;AAAA;AAAA,EAE3B;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,SAAiB,MAAsB,OAAe;AAChE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,QAAQ;AAGb,QAAI,MAAM,mBAAmB;AAC3B,YAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,IAChD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,SAAS;AACP,WAAO;AAAA,MACL,MAAM,KAAK;AAAA,MACX,SAAS,KAAK;AAAA,MACd,MAAM,KAAK;AAAA,MACX,OAAO,KAAK,OAAO;AAAA,IACrB;AAAA,EACF;AACF;AAKO,IAAM,uBAAN,cAAmC,WAAW;AAAA;AAAA,EAE1C;AAAA,EAET,YAAY,SAAiB,OAAgB;AAC3C,UAAM,SAAS,kBAAkB;AACjC,SAAK,OAAO;AACZ,SAAK,Q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AAS,GAAG;AAC7C,eAAO,IAAI,mBAAmB,WAAW,MAAS;AAAA,MACpD;AACA,aAAO,IAAI,cAAc,SAAS,sBAAsB,YAAY,EAAE,WAAW,aAAa,aAAa,CAAC;AAAA,IAE9G,KAAK;AACH,aAAO,IAAI,oBAAoB,SAAS,EAAE,UAAU,CAAC;AAAA,IAEvD,KAAK;AACH,aAAO,IAAI,cAAc,SAAS,oBAAoB,YAAY,EAAE,WAAW,aAAa,aAAa,CAAC;AAAA,IAE5G,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO,IAAI,cAAc,SAAS,uBAAuB,YAAY,EAAE,WAAW,aAAa,aAAa,CAAC;AAAA,IAE/G;AACE,aAAO,IAAI,cAAc,SAAS,iBAAiB,YAAY,EAAE,WAAW,aAAa,aAAa,CAAC;AAAA,EAC3G;AACF;","names":[]}
@@ -8,6 +8,10 @@ import {
8
8
  toolListDirectory,
9
9
  toolRead
10
10
  } from "./chunk-KRDIR7GG.js";
11
+ import {
12
+ AGENT_CONFIG,
13
+ DEFAULT_MODEL
14
+ } from "./chunk-5PNMAWLC.js";
11
15
  import {
12
16
  formatAgentToolOutput
13
17
  } from "./chunk-APP75CBN.js";
@@ -17,52 +21,38 @@ import {
17
21
  import {
18
22
  getSystemPrompt
19
23
  } from "./chunk-FMLHRJDF.js";
20
- import {
21
- AGENT_CONFIG,
22
- DEFAULT_MODEL
23
- } from "./chunk-5PNMAWLC.js";
24
- import {
25
- fetchWithRetry,
26
- withTimeout
27
- } from "./chunk-4VWJFZVS.js";
28
24
 
29
25
  // tools/warp_grep/agent/runner.ts
26
+ import OpenAI from "openai";
30
27
  import path from "path";
31
28
  var parser = new LLMResponseParser();
32
29
  var DEFAULT_API_URL = "https://api.morphllm.com";
33
30
  async function callModel(messages, model, options = {}) {
34
31
  const baseUrl = options.morphApiUrl || DEFAULT_API_URL;
35
32
  const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
36
- const fetchPromise = fetchWithRetry(
37
- `${baseUrl}/v1/chat/completions`,
38
- {
39
- method: "POST",
40
- headers: {
41
- "Content-Type": "application/json",
42
- Authorization: `Bearer ${apiKey}`
43
- },
44
- body: JSON.stringify({
45
- model,
46
- temperature: 0,
47
- max_tokens: 1024,
48
- repetition_penalty: 1.05,
49
- messages
50
- })
51
- },
52
- options.retryConfig
53
- );
54
33
  const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
55
- const resp = await withTimeout(fetchPromise, timeoutMs, "morph-warp-grep request timed out");
56
- if (!resp.ok) {
57
- if (resp.status === 404) {
34
+ const client = new OpenAI({
35
+ apiKey,
36
+ baseURL: baseUrl,
37
+ maxRetries: options.retryConfig?.maxRetries,
38
+ timeout: timeoutMs
39
+ });
40
+ let data;
41
+ try {
42
+ data = await client.chat.completions.create({
43
+ model,
44
+ temperature: 0,
45
+ max_tokens: 1024,
46
+ messages
47
+ });
48
+ } catch (error) {
49
+ if (error instanceof OpenAI.APIError && error.status === 404) {
58
50
  throw new Error(
59
51
  "The endpoint you are trying to call is likely deprecated. Please update with: npm cache clean --force && npx -y @morphllm/morphmcp@latest or visit: https://morphllm.com/mcp"
60
52
  );
61
53
  }
62
- const t = await resp.text();
63
- throw new Error(`morph-warp-grep error ${resp.status}: ${t}`);
54
+ throw error;
64
55
  }
65
- const data = await resp.json();
66
56
  const content = data?.choices?.[0]?.message?.content;
67
57
  if (!content || typeof content !== "string") {
68
58
  throw new Error("Invalid response from model");
@@ -367,4 +357,4 @@ export {
367
357
  runWarpGrep,
368
358
  runWarpGrepStreaming
369
359
  };
370
- //# sourceMappingURL=chunk-VHOWYK66.js.map
360
+ //# sourceMappingURL=chunk-43LQLGP6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../tools/warp_grep/agent/runner.ts"],"sourcesContent":["import { AGENT_CONFIG, DEFAULT_MODEL } from './config.js';\nimport { getSystemPrompt } from './prompt.js';\nimport type { AgentRunResult, ChatMessage, SessionConfig, AgentFinish, WarpGrepExecutionMetrics, WarpGrepTurnMetrics, WarpGrepStep } from './types.js';\nimport { LLMResponseParser } from './parser.js';\nimport type { WarpGrepProvider } from '../providers/types.js';\nimport { toolGrep } from './tools/grep.js';\nimport { toolRead } from './tools/read.js';\nimport { toolListDirectory } from './tools/list_directory.js';\nimport { readFinishFiles } from './tools/finish.js';\nimport type { RetryConfig } from '../../utils/resilience.js';\nimport { formatAgentToolOutput } from './formatter.js';\nimport { formatTurnMessage, calculateContextBudget, buildInitialState, enforceContextLimit } from './helpers.js';\nimport OpenAI from 'openai';\nimport path from 'path';\n\ntype EventName =\n | 'initial_state'\n | 'round_start'\n | 'round_end'\n | 'finish'\n | 'error';\n\nexport type EventCallback = (name: EventName, payload: Record<string, unknown>) => void;\n\nconst parser = new LLMResponseParser();\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\n\ninterface CallModelOptions {\n morphApiKey?: string;\n morphApiUrl?: string;\n retryConfig?: RetryConfig;\n timeout?: number;\n}\n\nasync function callModel(\n messages: ChatMessage[],\n model: string,\n options: CallModelOptions = {}\n): Promise<string> {\n const baseUrl = options.morphApiUrl || DEFAULT_API_URL;\n const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || '';\n const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;\n\n const client = new OpenAI({\n apiKey,\n baseURL: baseUrl,\n maxRetries: options.retryConfig?.maxRetries,\n timeout: timeoutMs,\n });\n\n let data;\n try {\n data = await client.chat.completions.create({\n model,\n temperature: 0.0,\n max_tokens: 1024,\n messages,\n });\n } catch (error) {\n if (error instanceof OpenAI.APIError && error.status === 404) {\n throw new Error(\n 'The endpoint you are trying to call is likely deprecated. Please update with: npm cache clean --force && npx -y @morphllm/morphmcp@latest or visit: https://morphllm.com/mcp'\n );\n }\n throw error;\n }\n\n const content = data?.choices?.[0]?.message?.content;\n if (!content || typeof content !== 'string') {\n throw new Error('Invalid response from model');\n }\n return content;\n}\n\nexport async function runWarpGrep(config: SessionConfig & { provider: WarpGrepProvider }): Promise<AgentRunResult> {\n const totalStart = Date.now();\n const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;\n const timings: Partial<WarpGrepExecutionMetrics> = { turns: [], timeout_ms: timeoutMs };\n \n const repoRoot = path.resolve(config.repoRoot || process.cwd());\n const messages: ChatMessage[] = [];\n\n messages.push({ role: 'system' as const, content: getSystemPrompt() });\n \n const initialStateStart = Date.now();\n const initialState = await buildInitialState(repoRoot, config.query, config.provider);\n timings.initial_state_ms = Date.now() - initialStateStart;\n \n messages.push({ role: 'user', content: initialState });\n\n const maxTurns = AGENT_CONFIG.MAX_TURNS;\n const model = config.model || DEFAULT_MODEL;\n const provider = config.provider;\n const errors: Array<{ message: string }> = [];\n\n let finishMeta: AgentFinish | undefined;\n let terminationReason: AgentRunResult['terminationReason'] = 'terminated';\n\n for (let turn = 1; turn <= maxTurns; turn += 1) {\n const turnMetrics: WarpGrepTurnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };\n \n // Enforce hard context limit before calling model\n enforceContextLimit(messages);\n \n // call model\n const modelCallStart = Date.now();\n const assistantContent = await callModel(messages, model, {\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: timeoutMs,\n }).catch((e: unknown) => {\n errors.push({ message: e instanceof Error ? e.message : String(e) });\n return '';\n });\n turnMetrics.morph_api_ms = Date.now() - modelCallStart;\n \n if (!assistantContent) {\n timings.turns!.push(turnMetrics);\n break;\n }\n messages.push({ role: 'assistant', content: assistantContent });\n\n // parse tool calls (no longer throws - returns _skip calls for malformed commands)\n const toolCalls = parser.parse(assistantContent);\n if (toolCalls.length === 0) {\n errors.push({ message: 'No tool calls produced by the model. Your MCP is likely out of date! Update it by running: rm -rf ~/.npm/_npx && npm cache clean --force && npx -y @morphllm/morphmcp@latest' });\n terminationReason = 'terminated';\n timings.turns!.push(turnMetrics);\n break;\n }\n\n const finishCalls = toolCalls.filter(c => c.name === 'finish');\n const grepCalls = toolCalls.filter(c => c.name === 'grep');\n const listDirCalls = toolCalls.filter(c => c.name === 'list_directory');\n const readCalls = toolCalls.filter(c => c.name === 'read');\n const skipCalls = toolCalls.filter(c => c.name === '_skip');\n\n const formatted: string[] = [];\n\n // Surface any skipped commands as feedback to the LLM\n for (const c of skipCalls) {\n const msg = (c.arguments as { message?: string })?.message || 'Command skipped due to parsing error';\n formatted.push(msg);\n }\n\n const allPromises: Array<Promise<string>> = [];\n \n for (const c of grepCalls) {\n const args = (c.arguments ?? {}) as { pattern: string; path: string; glob?: string };\n allPromises.push(\n toolGrep(provider, args).then(\n ({ output }) => formatAgentToolOutput('grep', args, output, { isError: false }),\n err => formatAgentToolOutput('grep', args, String(err), { isError: true })\n )\n );\n }\n \n for (const c of listDirCalls) {\n const args = (c.arguments ?? {}) as { path: string; pattern?: string | null };\n allPromises.push(\n toolListDirectory(provider, args).then(\n p => formatAgentToolOutput('list_directory', args, p, { isError: false }),\n err => formatAgentToolOutput('list_directory', args, String(err), { isError: true })\n )\n );\n }\n \n for (const c of readCalls) {\n const args = (c.arguments ?? {}) as { path: string; start?: number; end?: number; lines?: Array<[number, number]> };\n allPromises.push(\n toolRead(provider, args).then(\n p => formatAgentToolOutput('read', args, p, { isError: false }),\n err => formatAgentToolOutput('read', args, String(err), { isError: true })\n )\n );\n }\n \n const toolExecStart = Date.now();\n const allResults = await Promise.all(allPromises);\n turnMetrics.local_tools_ms = Date.now() - toolExecStart;\n \n for (const result of allResults) {\n formatted.push(result);\n }\n\n if (formatted.length > 0) {\n const turnMessage = formatTurnMessage(turn, maxTurns);\n const contextBudget = calculateContextBudget(messages);\n messages.push({ role: 'user', content: formatted.join('\\n') + turnMessage + '\\n' + contextBudget });\n }\n\n timings.turns!.push(turnMetrics);\n\n if (finishCalls.length) {\n const fc = finishCalls[0];\n const files = ((fc.arguments as any)?.files ?? []) as AgentFinish['files'];\n finishMeta = { files };\n terminationReason = 'completed';\n break;\n }\n }\n\n if (terminationReason !== 'completed' || !finishMeta) {\n timings.total_ms = Date.now() - totalStart;\n return { terminationReason, messages, errors, timings: timings as WarpGrepExecutionMetrics };\n }\n\n // Build finish payload\n const parts: string[] = ['Relevant context found:'];\n for (const f of finishMeta.files) {\n const ranges = f.lines === '*' ? '*' \n : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(', ') \n : '*';\n parts.push(`- ${f.path}: ${ranges}`);\n }\n const payload = parts.join('\\n');\n\n // Resolve file contents for returned ranges\n // Wrap reader in try-catch to handle non-existent or unreadable files gracefully\n // Track files that couldn't be read for error reporting\n const finishResolutionStart = Date.now();\n const fileReadErrors: Array<{ path: string; error: string }> = [];\n const resolved = await readFinishFiles(\n repoRoot,\n finishMeta.files,\n async (p: string, s?: number, e?: number) => {\n try {\n const rr = await provider.read({ path: p, start: s, end: e });\n // rr.lines are \"line|content\" → strip the \"line|\" prefix\n return rr.lines.map(l => {\n const idx = l.indexOf('|');\n return idx >= 0 ? l.slice(idx + 1) : l;\n });\n } catch (err) {\n // File doesn't exist or can't be read - log error but don't throw\n // This handles cases where the agent hallucinated a path or the file was deleted\n const errorMsg = err instanceof Error ? err.message : String(err);\n fileReadErrors.push({ path: p, error: errorMsg });\n console.error(`[warp_grep] Failed to read file: ${p} - ${errorMsg}`);\n return [`[couldn't find: ${p}]`];\n }\n }\n );\n\n timings.finish_resolution_ms = Date.now() - finishResolutionStart;\n\n // Add file read errors to the result so MCP can report them\n if (fileReadErrors.length > 0) {\n errors.push(...fileReadErrors.map(e => ({ message: `File read error: ${e.path} - ${e.error}` })));\n }\n\n timings.total_ms = Date.now() - totalStart;\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: finishMeta, resolved },\n timings: timings as WarpGrepExecutionMetrics,\n };\n}\n\n/**\n * Streaming version of runWarpGrep that yields step information after each turn.\n * Yields WarpGrepStep with tool calls for each turn, then returns the final AgentRunResult.\n */\nexport async function* runWarpGrepStreaming(\n config: SessionConfig & { provider: WarpGrepProvider }\n): AsyncGenerator<WarpGrepStep, AgentRunResult, undefined> {\n const totalStart = Date.now();\n const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;\n const timings: Partial<WarpGrepExecutionMetrics> = { turns: [], timeout_ms: timeoutMs };\n\n const repoRoot = path.resolve(config.repoRoot || process.cwd());\n const messages: ChatMessage[] = [];\n\n messages.push({ role: 'system' as const, content: getSystemPrompt() });\n\n const initialStateStart = Date.now();\n const initialState = await buildInitialState(repoRoot, config.query, config.provider);\n timings.initial_state_ms = Date.now() - initialStateStart;\n\n messages.push({ role: 'user', content: initialState });\n\n const maxTurns = AGENT_CONFIG.MAX_TURNS;\n const model = config.model || DEFAULT_MODEL;\n const provider = config.provider;\n const errors: Array<{ message: string }> = [];\n\n let finishMeta: AgentFinish | undefined;\n let terminationReason: AgentRunResult['terminationReason'] = 'terminated';\n\n for (let turn = 1; turn <= maxTurns; turn += 1) {\n const turnMetrics: WarpGrepTurnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };\n\n // Enforce hard context limit before calling model\n enforceContextLimit(messages);\n\n // call model\n const modelCallStart = Date.now();\n const assistantContent = await callModel(messages, model, {\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: timeoutMs,\n }).catch((e: unknown) => {\n errors.push({ message: e instanceof Error ? e.message : String(e) });\n return '';\n });\n turnMetrics.morph_api_ms = Date.now() - modelCallStart;\n\n if (!assistantContent) {\n timings.turns!.push(turnMetrics);\n break;\n }\n messages.push({ role: 'assistant', content: assistantContent });\n\n // parse tool calls (no longer throws - returns _skip calls for malformed commands)\n const toolCalls = parser.parse(assistantContent);\n if (toolCalls.length === 0) {\n errors.push({ message: 'No tool calls produced by the model. Your MCP is likely out of date! Update it by running: rm -rf ~/.npm/_npx && npm cache clean --force && npx -y @morphllm/morphmcp@latest' });\n terminationReason = 'terminated';\n timings.turns!.push(turnMetrics);\n break;\n }\n\n // Yield step with tool calls (before execution)\n yield {\n turn,\n toolCalls: toolCalls.map(c => ({\n name: c.name,\n arguments: c.arguments ?? {}\n }))\n };\n\n const finishCalls = toolCalls.filter(c => c.name === 'finish');\n const grepCalls = toolCalls.filter(c => c.name === 'grep');\n const listDirCalls = toolCalls.filter(c => c.name === 'list_directory');\n const readCalls = toolCalls.filter(c => c.name === 'read');\n const skipCalls = toolCalls.filter(c => c.name === '_skip');\n\n const formatted: string[] = [];\n\n // Surface any skipped commands as feedback to the LLM\n for (const c of skipCalls) {\n const msg = (c.arguments as { message?: string })?.message || 'Command skipped due to parsing error';\n formatted.push(msg);\n }\n\n const allPromises: Array<Promise<string>> = [];\n\n for (const c of grepCalls) {\n const args = (c.arguments ?? {}) as { pattern: string; path: string; glob?: string };\n allPromises.push(\n toolGrep(provider, args).then(\n ({ output }) => formatAgentToolOutput('grep', args, output, { isError: false }),\n err => formatAgentToolOutput('grep', args, String(err), { isError: true })\n )\n );\n }\n\n for (const c of listDirCalls) {\n const args = (c.arguments ?? {}) as { path: string; pattern?: string | null };\n allPromises.push(\n toolListDirectory(provider, args).then(\n p => formatAgentToolOutput('list_directory', args, p, { isError: false }),\n err => formatAgentToolOutput('list_directory', args, String(err), { isError: true })\n )\n );\n }\n\n for (const c of readCalls) {\n const args = (c.arguments ?? {}) as { path: string; start?: number; end?: number; lines?: Array<[number, number]> };\n allPromises.push(\n toolRead(provider, args).then(\n p => formatAgentToolOutput('read', args, p, { isError: false }),\n err => formatAgentToolOutput('read', args, String(err), { isError: true })\n )\n );\n }\n\n const toolExecStart = Date.now();\n const allResults = await Promise.all(allPromises);\n turnMetrics.local_tools_ms = Date.now() - toolExecStart;\n\n for (const result of allResults) {\n formatted.push(result);\n }\n\n if (formatted.length > 0) {\n const turnMessage = formatTurnMessage(turn, maxTurns);\n const contextBudget = calculateContextBudget(messages);\n messages.push({ role: 'user', content: formatted.join('\\n') + turnMessage + '\\n' + contextBudget });\n }\n\n timings.turns!.push(turnMetrics);\n\n if (finishCalls.length) {\n const fc = finishCalls[0];\n const files = ((fc.arguments as any)?.files ?? []) as AgentFinish['files'];\n finishMeta = { files };\n terminationReason = 'completed';\n break;\n }\n }\n\n if (terminationReason !== 'completed' || !finishMeta) {\n timings.total_ms = Date.now() - totalStart;\n return { terminationReason, messages, errors, timings: timings as WarpGrepExecutionMetrics };\n }\n\n // Build finish payload\n const parts: string[] = ['Relevant context found:'];\n for (const f of finishMeta.files) {\n const ranges = f.lines === '*' ? '*'\n : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(', ')\n : '*';\n parts.push(`- ${f.path}: ${ranges}`);\n }\n const payload = parts.join('\\n');\n\n // Resolve file contents for returned ranges\n const finishResolutionStart = Date.now();\n const fileReadErrors: Array<{ path: string; error: string }> = [];\n const resolved = await readFinishFiles(\n repoRoot,\n finishMeta.files,\n async (p: string, s?: number, e?: number) => {\n try {\n const rr = await provider.read({ path: p, start: s, end: e });\n return rr.lines.map(l => {\n const idx = l.indexOf('|');\n return idx >= 0 ? l.slice(idx + 1) : l;\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n fileReadErrors.push({ path: p, error: errorMsg });\n console.error(`[warp_grep] Failed to read file: ${p} - ${errorMsg}`);\n return [`[couldn't find: ${p}]`];\n }\n }\n );\n\n timings.finish_resolution_ms = Date.now() - finishResolutionStart;\n\n if (fileReadErrors.length > 0) {\n errors.push(...fileReadErrors.map(e => ({ message: `File read error: ${e.path} - ${e.error}` })));\n }\n\n timings.total_ms = Date.now() - totalStart;\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: finishMeta, resolved },\n timings: timings as WarpGrepExecutionMetrics,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAYA,OAAO,YAAY;AACnB,OAAO,UAAU;AAWjB,IAAM,SAAS,IAAI,kBAAkB;AAErC,IAAM,kBAAkB;AASxB,eAAe,UACb,UACA,OACA,UAA4B,CAAC,GACZ;AACjB,QAA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iBAAO,OAAO,IAAI,EAAE,MAAM,MAAM,CAAC,IAAI;AAAA,QACvC,CAAC;AAAA,MACH,SAAS,KAAK;AACZ,cAAM,WAAW,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAChE,uBAAe,KAAK,EAAE,MAAM,GAAG,OAAO,SAAS,CAAC;AAChD,gBAAQ,MAAM,oCAAoC,CAAC,MAAM,QAAQ,EAAE;AACnE,eAAO,CAAC,mBAAmB,CAAC,GAAG;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AAEA,UAAQ,uBAAuB,KAAK,IAAI,IAAI;AAE5C,MAAI,eAAe,SAAS,GAAG;AAC7B,WAAO,KAAK,GAAG,eAAe,IAAI,QAAM,EAAE,SAAS,oBAAoB,EAAE,IAAI,MAAM,EAAE,KAAK,GAAG,EAAE,CAAC;AAAA,EAClG;AAEA,UAAQ,WAAW,KAAK,IAAI,IAAI;AAChC,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB;AAAA,IACA,QAAQ,EAAE,SAAS,UAAU,YAAY,SAAS;AAAA,IAClD;AAAA,EACF;AACF;","names":[]}
@@ -5,7 +5,7 @@ import {
5
5
  import {
6
6
  executeToolCall,
7
7
  formatResult
8
- } from "./chunk-PUGIOVSP.js";
8
+ } from "./chunk-QAT5UVPX.js";
9
9
  import {
10
10
  getSystemPrompt
11
11
  } from "./chunk-FMLHRJDF.js";
@@ -58,4 +58,4 @@ export {
58
58
  createWarpGrepTool,
59
59
  openai_default
60
60
  };
61
- //# sourceMappingURL=chunk-LMUZ3NGC.js.map
61
+ //# sourceMappingURL=chunk-73RV6EXR.js.map
@@ -5,7 +5,7 @@ import {
5
5
  import {
6
6
  executeToolCall,
7
7
  formatResult
8
- } from "./chunk-PUGIOVSP.js";
8
+ } from "./chunk-QAT5UVPX.js";
9
9
  import {
10
10
  getSystemPrompt
11
11
  } from "./chunk-FMLHRJDF.js";
@@ -50,4 +50,4 @@ export {
50
50
  execute,
51
51
  createWarpGrepTool
52
52
  };
53
- //# sourceMappingURL=chunk-PBLPZ6AU.js.map
53
+ //# sourceMappingURL=chunk-7D6TXC7X.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-KW7OEGZK.js";
4
4
  import {
5
5
  executeToolCall
6
- } from "./chunk-PUGIOVSP.js";
6
+ } from "./chunk-QAT5UVPX.js";
7
7
 
8
8
  // tools/warp_grep/vercel.ts
9
9
  import { tool } from "ai";
@@ -50,4 +50,4 @@ export {
50
50
  createWarpGrepTool,
51
51
  vercel_default
52
52
  };
53
- //# sourceMappingURL=chunk-GU6DACME.js.map
53
+ //# sourceMappingURL=chunk-O7LDZA52.js.map
@@ -60,13 +60,6 @@ function formatResult(result) {
60
60
  changes.linesRemoved && `-${changes.linesRemoved} lines`,
61
61
  changes.linesModified && `~${changes.linesModified} lines modified`
62
62
  ].filter(Boolean).join(", ");
63
- if (result.udiff) {
64
- return `Successfully applied changes to ${result.filepath}:
65
-
66
- ${result.udiff}
67
-
68
- Summary: ${summary}`;
69
- }
70
63
  return `Successfully applied changes to ${result.filepath}. ${summary}`;
71
64
  }
72
65
  function createEditFileTool(config = {}) {
@@ -103,4 +96,4 @@ export {
103
96
  openai_default,
104
97
  openai_exports
105
98
  };
106
- //# sourceMappingURL=chunk-5QIWYEHJ.js.map
99
+ //# sourceMappingURL=chunk-PE4KGDA6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../tools/fastapply/openai.ts"],"sourcesContent":["/**\n * OpenAI SDK adapter for edit_file tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * OpenAI-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { editFileTool } from 'morphsdk/tools/openai';\n * \n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * \n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instructions: {\n type: 'string',\n description: 'A single sentence describing what you are changing (first person)',\n },\n code_edit: {\n type: 'string',\n description: 'The lazy edit with // ... existing code ... markers',\n },\n },\n required: ['target_filepath', 'instructions', 'code_edit'],\n },\n },\n};\n\n/**\n * Execute an edit_file tool call\n * \n * @param input - The tool input from GPT (parsed from tool_calls)\n * @param config - Optional configuration\n * @returns The result of the edit operation\n * \n * @example\n * ```ts\n * const args = JSON.parse(toolCall.function.arguments);\n * const result = await execute(args);\n * console.log('Changes applied:', result.udiff);\n * ```\n */\nexport async function execute(\n input: EditFileInput,\n config?: EditFileConfig\n): Promise<EditFileResult> {\n return executeEditFile(input, config);\n}\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide GPT on using edit_file properly.\n * \n * @example\n * ```ts\n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * messages: [\n * { role: \"system\", content: getSystemPrompt() },\n * { role: \"user\", content: \"Fix bugs\" }\n * ],\n * tools: [editFileTool]\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Format the result for passing back to GPT\n * \n * @param result - The edit result\n * @returns Formatted string for tool message\n */\nexport function formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n const summary = [\n changes.linesAdded && `+${changes.linesAdded} lines`,\n changes.linesRemoved && `-${changes.linesRemoved} lines`,\n changes.linesModified && `~${changes.linesModified} lines modified`,\n ]\n .filter(Boolean)\n .join(', ');\n \n return `Successfully applied changes to ${result.filepath}. ${summary}`;\n}\n\n/**\n * Create a custom edit_file tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { createEditFileTool } from 'morphsdk/tools/fastapply/openai';\n * \n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const client = new OpenAI();\n * \n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool], // tool itself is the ChatCompletionTool\n * messages: [{ role: 'user', content: 'Fix bug in app.ts' }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: ChatCompletionTool = {\n ...editFileTool,\n ...(config.description && {\n function: {\n ...editFileTool.function,\n description: config.description,\n },\n }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput | string): Promise<EditFileResult> => {\n const parsedInput = typeof input === 'string' ? JSON.parse(input) : input;\n return execute(parsedInput, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return getSystemPrompt();\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0BO,IAAM,eAAmC;AAAA,EAC9C,MAAM;AAAA,EACN,UAAU;AAAA,IACR,MAAM;AAAA,IACN,aAAa;AAAA,IACb,YAAY;AAAA,MACV,MAAM;AAAA,MACN,YAAY;AAAA,QACV,iBAAiB;AAAA,UACf,MAAM;AAAA,UACN,aAAa;AAAA,QACf;AAAA,QACA,cAAc;AAAA,UACZ,MAAM;AAAA,UACN,aAAa;AAAA,QACf;AAAA,QACA,WAAW;AAAA,UACT,MAAM;AAAA,UACN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end returns debugUrl in the task response. Contact support@morphllm.com if you need help."
14
14
  );
15
15
  }
16
- const url = new URL(debugUrl);
16
+ const normalized = normalizeLiveUrl(debugUrl);
17
+ const url = new URL(normalized);
17
18
  if (options.interactive !== void 0) {
18
19
  url.searchParams.set("interactive", String(options.interactive));
19
20
  }
@@ -31,6 +32,29 @@ function buildLiveUrl(debugUrl, options = {}) {
31
32
  }
32
33
  return url.toString();
33
34
  }
35
+ function normalizeLiveUrl(debugUrl) {
36
+ const trimmed = debugUrl.trim();
37
+ if (!trimmed) {
38
+ return trimmed;
39
+ }
40
+ if (trimmed.startsWith("wss://") || trimmed.startsWith("ws://")) {
41
+ return `https://live.browser-use.com?wss=${encodeURIComponent(trimmed)}`;
42
+ }
43
+ let url;
44
+ try {
45
+ url = new URL(trimmed);
46
+ } catch {
47
+ return trimmed;
48
+ }
49
+ if (url.protocol === "wss:" || url.protocol === "ws:") {
50
+ return `https://live.browser-use.com?wss=${encodeURIComponent(trimmed)}`;
51
+ }
52
+ const wssParam = url.searchParams.get("wss");
53
+ if (wssParam && (wssParam.startsWith("wss://") || wssParam.startsWith("ws://"))) {
54
+ url.searchParams.set("wss", wssParam);
55
+ }
56
+ return url.toString();
57
+ }
34
58
  function buildLiveIframe(debugUrl, options = {}) {
35
59
  const {
36
60
  width = "100%",
@@ -81,4 +105,4 @@ export {
81
105
  buildEmbedCode,
82
106
  resolvePreset
83
107
  };
84
- //# sourceMappingURL=chunk-SQN4DUQS.js.map
108
+ //# sourceMappingURL=chunk-Q6Y4R236.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../tools/browser/live.ts"],"sourcesContent":["/**\n * Live session utilities for Morph browser sessions\n * \n * Provides helpers for embedding and sharing live browser sessions with WebRTC streaming.\n */\n\nimport type { LiveSessionOptions, IframeOptions } from './types.js';\n\n/**\n * Preset configurations for common use cases\n */\nexport const LIVE_PRESETS = {\n /** Read-only monitoring (no interaction) */\n readonly: { interactive: false } as LiveSessionOptions,\n /** Interactive control (human-in-the-loop) */\n interactive: { interactive: true } as LiveSessionOptions,\n /** Watch-only without controls */\n monitoring: { interactive: false, showControls: false } as LiveSessionOptions,\n} as const;\n\n/**\n * Build a live session URL with query parameters\n * \n * @param debugUrl - Live session debug URL (e.g., from task.debugUrl)\n * @param options - Live session configuration options\n * @returns URL with query parameters for iframe embedding\n * \n * @example\n * ```typescript\n * const url = buildLiveUrl(task.debugUrl, { interactive: true });\n * // Returns: https://example.com/sessions/abc?interactive=true\n * ```\n */\nexport function buildLiveUrl(\n debugUrl: string,\n options: LiveSessionOptions = {}\n): string {\n if (!debugUrl) {\n throw new Error(\n 'debugUrl is required. Ensure your backend returns debugUrl in the task response. ' +\n 'Contact support@morphllm.com if you need help.'\n );\n }\n\n const normalized = normalizeLiveUrl(debugUrl);\n const url = new URL(normalized);\n \n // Add query parameters for supported options\n if (options.interactive !== undefined) {\n url.searchParams.set('interactive', String(options.interactive));\n }\n \n if (options.theme) {\n url.searchParams.set('theme', options.theme);\n }\n \n if (options.showControls !== undefined) {\n url.searchParams.set('showControls', String(options.showControls));\n }\n \n if (options.pageId) {\n url.searchParams.set('pageId', options.pageId);\n }\n \n if (options.pageIndex) {\n url.searchParams.set('pageIndex', options.pageIndex);\n }\n \n return url.toString();\n}\n\nfunction normalizeLiveUrl(debugUrl: string): string {\n const trimmed = debugUrl.trim();\n if (!trimmed) {\n return trimmed;\n }\n\n if (trimmed.startsWith('wss://') || trimmed.startsWith('ws://')) {\n return `https://live.browser-use.com?wss=${encodeURIComponent(trimmed)}`;\n }\n\n let url: URL;\n try {\n url = new URL(trimmed);\n } catch {\n return trimmed;\n }\n\n if (url.protocol === 'wss:' || url.protocol === 'ws:') {\n return `https://live.browser-use.com?wss=${encodeURIComponent(trimmed)}`;\n }\n\n const wssParam = url.searchParams.get('wss');\n if (wssParam && (wssParam.startsWith('wss://') || wssParam.startsWith('ws://'))) {\n url.searchParams.set('wss', wssParam);\n }\n\n return url.toString();\n}\n\n/**\n * Build iframe HTML for embedding a live session\n * \n * @param debugUrl - Live session debug URL\n * @param options - Iframe configuration including dimensions and session options\n * @returns HTML iframe element as string\n * \n * @example\n * ```typescript\n * const iframe = buildLiveIframe(task.debugUrl, {\n * interactive: true,\n * width: '100%',\n * height: '600px'\n * });\n * ```\n */\nexport function buildLiveIframe(\n debugUrl: string,\n options: IframeOptions = {}\n): string {\n const {\n width = '100%',\n height = '600px',\n style = '',\n className = '',\n ...sessionOptions\n } = options;\n\n const src = buildLiveUrl(debugUrl, sessionOptions);\n \n // Convert numeric dimensions to pixels\n const widthStr = typeof width === 'number' ? `${width}px` : width;\n const heightStr = typeof height === 'number' ? `${height}px` : height;\n \n // Build style attribute\n const baseStyle = `width: ${widthStr}; height: ${heightStr}; border: none;`;\n const fullStyle = style ? `${baseStyle} ${style}` : baseStyle;\n \n // Build iframe attributes\n const attributes = [\n `src=\"${src}\"`,\n `style=\"${fullStyle}\"`,\n ];\n \n if (className) {\n attributes.push(`class=\"${className}\"`);\n }\n \n return `<iframe ${attributes.join(' ')}></iframe>`;\n}\n\n/**\n * Build complete embed code with HTML snippet\n * \n * @param debugUrl - Live session debug URL\n * @param options - Iframe configuration\n * @returns Multi-line HTML snippet ready to copy-paste\n * \n * @example\n * ```typescript\n * const code = buildEmbedCode(task.debugUrl, { interactive: false });\n * console.log(code);\n * // <!-- Embed Morph Live Session -->\n * // <iframe src=\"...\" style=\"...\"></iframe>\n * ```\n */\nexport function buildEmbedCode(\n debugUrl: string,\n options: IframeOptions = {}\n): string {\n const iframe = buildLiveIframe(debugUrl, options);\n return `<!-- Embed Morph Live Session -->\\n${iframe}`;\n}\n\n/**\n * Get live session options from preset name or custom config\n * \n * @internal\n */\nexport function resolvePreset(\n optionsOrPreset?: string | IframeOptions\n): IframeOptions {\n if (!optionsOrPreset) {\n return {};\n }\n \n if (typeof optionsOrPreset === 'string') {\n const preset = LIVE_PRESETS[optionsOrPreset as keyof typeof LIVE_PRESETS];\n if (!preset) {\n throw new Error(\n `Unknown preset: ${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AAe,wBAAwB,OAAO,KAAK,YAAY,EAAE,KAAK,IAAI,CAAC;AAAA,MAChG;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  runWarpGrep,
3
3
  runWarpGrepStreaming
4
- } from "./chunk-VHOWYK66.js";
4
+ } from "./chunk-43LQLGP6.js";
5
5
  import {
6
6
  RemoteCommandsProvider
7
7
  } from "./chunk-PUGSTXLO.js";
@@ -138,4 +138,4 @@ export {
138
138
  executeToolCall,
139
139
  formatResult
140
140
  };
141
- //# sourceMappingURL=chunk-PUGIOVSP.js.map
141
+ //# sourceMappingURL=chunk-QAT5UVPX.js.map