@morphllm/morphsdk 0.2.150 → 0.2.152

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 (160) hide show
  1. package/dist/{chunk-3UL7BVDI.js → chunk-3TARZOBZ.js} +2 -2
  2. package/dist/{chunk-KCDIVAVA.js → chunk-3ZR5RSJQ.js} +2 -2
  3. package/dist/{chunk-KCDIVAVA.js.map → chunk-3ZR5RSJQ.js.map} +1 -1
  4. package/dist/{chunk-23EB2N66.js → chunk-55ESIZID.js} +2 -2
  5. package/dist/{chunk-HSR3SQNH.js → chunk-75C4DV27.js} +2 -2
  6. package/dist/{chunk-63GEUXAG.js → chunk-BN6IXTDU.js} +20 -20
  7. package/dist/{chunk-KYTJEG7F.js → chunk-DOWJVFKI.js} +2 -2
  8. package/dist/{chunk-ZKQI7KGZ.js → chunk-G7FGC7EQ.js} +3 -3
  9. package/dist/{chunk-HFTF2NON.js → chunk-I6CWGOEL.js} +3 -3
  10. package/dist/chunk-I6CWGOEL.js.map +1 -0
  11. package/dist/{chunk-GAPZBV4P.js → chunk-KXN4YMCP.js} +2 -2
  12. package/dist/{chunk-LJX5QBDP.js → chunk-L7EVPMOK.js} +2 -2
  13. package/dist/{chunk-7EQOAK6V.js → chunk-LYL2MWM6.js} +2 -2
  14. package/dist/{chunk-4WZPGIRU.js → chunk-OLL7QI3Y.js} +2 -2
  15. package/dist/{chunk-MUWQA4QI.js → chunk-P7USBFIJ.js} +1 -1
  16. package/dist/{chunk-K2ATEMGS.js → chunk-PIBNTOS7.js} +2 -2
  17. package/dist/{chunk-4RYUAMA5.js → chunk-PO6IPUDB.js} +2 -2
  18. package/dist/{chunk-JHYH3NEP.js → chunk-Q6QCHAMD.js} +2 -2
  19. package/dist/chunk-Q6QCHAMD.js.map +1 -0
  20. package/dist/{chunk-HXTGDRE4.js → chunk-Q72OV4VF.js} +2 -2
  21. package/dist/{chunk-72Q3QRXJ.js → chunk-R5IYAFFN.js} +2 -2
  22. package/dist/{chunk-6TUOW6R4.js → chunk-SVLY35WI.js} +3 -3
  23. package/dist/{chunk-T4SKN6IN.js → chunk-U253YYNH.js} +2 -2
  24. package/dist/{chunk-GINC6ZQJ.js → chunk-UAGEVTXM.js} +2 -2
  25. package/dist/{chunk-NFK7BUMT.js → chunk-WKHAZ732.js} +2 -2
  26. package/dist/{chunk-FVMQTLGC.js → chunk-WU2325QJ.js} +2 -2
  27. package/dist/{chunk-X6OZX6KV.js → chunk-YLWVLRWH.js} +3 -3
  28. package/dist/{chunk-FFBKJYME.js → chunk-ZFYFLNRE.js} +2 -2
  29. package/dist/{chunk-O3DGRBQ3.js → chunk-ZHRXNOXP.js} +3 -3
  30. package/dist/client.cjs +2 -2
  31. package/dist/client.cjs.map +1 -1
  32. package/dist/client.js +23 -23
  33. package/dist/edge.cjs +1 -1
  34. package/dist/edge.cjs.map +1 -1
  35. package/dist/edge.js +4 -4
  36. package/dist/index.cjs +2 -2
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.js +23 -23
  39. package/dist/modelrouter/core.cjs +1 -1
  40. package/dist/modelrouter/core.cjs.map +1 -1
  41. package/dist/modelrouter/core.js +3 -3
  42. package/dist/modelrouter/index.cjs +1 -1
  43. package/dist/modelrouter/index.cjs.map +1 -1
  44. package/dist/modelrouter/index.js +3 -3
  45. package/dist/subagents/anthropic.cjs +1 -1
  46. package/dist/subagents/anthropic.cjs.map +1 -1
  47. package/dist/subagents/anthropic.js +4 -4
  48. package/dist/subagents/vercel.cjs +1 -1
  49. package/dist/subagents/vercel.cjs.map +1 -1
  50. package/dist/subagents/vercel.js +4 -4
  51. package/dist/tools/browser/anthropic.cjs +1 -1
  52. package/dist/tools/browser/anthropic.cjs.map +1 -1
  53. package/dist/tools/browser/anthropic.js +5 -5
  54. package/dist/tools/browser/core.cjs +1 -1
  55. package/dist/tools/browser/core.cjs.map +1 -1
  56. package/dist/tools/browser/core.js +4 -4
  57. package/dist/tools/browser/index.cjs +1 -1
  58. package/dist/tools/browser/index.cjs.map +1 -1
  59. package/dist/tools/browser/index.js +7 -7
  60. package/dist/tools/browser/openai.cjs +1 -1
  61. package/dist/tools/browser/openai.cjs.map +1 -1
  62. package/dist/tools/browser/openai.js +5 -5
  63. package/dist/tools/browser/profiles/core.cjs +1 -1
  64. package/dist/tools/browser/profiles/core.cjs.map +1 -1
  65. package/dist/tools/browser/profiles/core.js +3 -3
  66. package/dist/tools/browser/profiles/index.cjs +1 -1
  67. package/dist/tools/browser/profiles/index.cjs.map +1 -1
  68. package/dist/tools/browser/profiles/index.js +3 -3
  69. package/dist/tools/browser/vercel.cjs +1 -1
  70. package/dist/tools/browser/vercel.cjs.map +1 -1
  71. package/dist/tools/browser/vercel.js +5 -5
  72. package/dist/tools/codebase_search/anthropic.cjs +1 -1
  73. package/dist/tools/codebase_search/anthropic.cjs.map +1 -1
  74. package/dist/tools/codebase_search/anthropic.js +4 -4
  75. package/dist/tools/codebase_search/core.cjs +1 -1
  76. package/dist/tools/codebase_search/core.cjs.map +1 -1
  77. package/dist/tools/codebase_search/core.js +3 -3
  78. package/dist/tools/codebase_search/index.cjs +1 -1
  79. package/dist/tools/codebase_search/index.cjs.map +1 -1
  80. package/dist/tools/codebase_search/index.js +6 -6
  81. package/dist/tools/codebase_search/openai.cjs +2 -2
  82. package/dist/tools/codebase_search/openai.cjs.map +1 -1
  83. package/dist/tools/codebase_search/openai.js +4 -4
  84. package/dist/tools/codebase_search/vercel.cjs +1 -1
  85. package/dist/tools/codebase_search/vercel.cjs.map +1 -1
  86. package/dist/tools/codebase_search/vercel.js +4 -4
  87. package/dist/tools/fastapply/anthropic.cjs +1 -1
  88. package/dist/tools/fastapply/anthropic.cjs.map +1 -1
  89. package/dist/tools/fastapply/anthropic.js +4 -4
  90. package/dist/tools/fastapply/apply.cjs +1 -1
  91. package/dist/tools/fastapply/apply.cjs.map +1 -1
  92. package/dist/tools/fastapply/apply.js +2 -2
  93. package/dist/tools/fastapply/core.cjs +1 -1
  94. package/dist/tools/fastapply/core.cjs.map +1 -1
  95. package/dist/tools/fastapply/core.js +3 -3
  96. package/dist/tools/fastapply/index.cjs +1 -1
  97. package/dist/tools/fastapply/index.cjs.map +1 -1
  98. package/dist/tools/fastapply/index.js +6 -6
  99. package/dist/tools/fastapply/openai.cjs +1 -1
  100. package/dist/tools/fastapply/openai.cjs.map +1 -1
  101. package/dist/tools/fastapply/openai.js +4 -4
  102. package/dist/tools/fastapply/vercel.cjs +1 -1
  103. package/dist/tools/fastapply/vercel.cjs.map +1 -1
  104. package/dist/tools/fastapply/vercel.js +4 -4
  105. package/dist/tools/index.cjs +1 -1
  106. package/dist/tools/index.cjs.map +1 -1
  107. package/dist/tools/index.js +6 -6
  108. package/dist/tools/utils/resilience.cjs +1 -1
  109. package/dist/tools/utils/resilience.cjs.map +1 -1
  110. package/dist/tools/utils/resilience.js +2 -2
  111. package/dist/tools/warp_grep/agent/runner.cjs +1 -1
  112. package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
  113. package/dist/tools/warp_grep/agent/runner.js +2 -2
  114. package/dist/tools/warp_grep/anthropic.cjs +2 -2
  115. package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
  116. package/dist/tools/warp_grep/anthropic.js +5 -5
  117. package/dist/tools/warp_grep/client.cjs +1 -1
  118. package/dist/tools/warp_grep/client.cjs.map +1 -1
  119. package/dist/tools/warp_grep/client.js +3 -3
  120. package/dist/tools/warp_grep/gemini.cjs +2 -2
  121. package/dist/tools/warp_grep/gemini.cjs.map +1 -1
  122. package/dist/tools/warp_grep/gemini.js +4 -4
  123. package/dist/tools/warp_grep/index.cjs +2 -2
  124. package/dist/tools/warp_grep/index.cjs.map +1 -1
  125. package/dist/tools/warp_grep/index.js +4 -4
  126. package/dist/tools/warp_grep/openai.cjs +2 -2
  127. package/dist/tools/warp_grep/openai.cjs.map +1 -1
  128. package/dist/tools/warp_grep/openai.js +5 -5
  129. package/dist/tools/warp_grep/vercel.cjs +2 -2
  130. package/dist/tools/warp_grep/vercel.cjs.map +1 -1
  131. package/dist/tools/warp_grep/vercel.js +5 -5
  132. package/dist/version.cjs +1 -1
  133. package/dist/version.cjs.map +1 -1
  134. package/dist/version.js +1 -1
  135. package/package.json +1 -1
  136. package/dist/chunk-HFTF2NON.js.map +0 -1
  137. package/dist/chunk-JHYH3NEP.js.map +0 -1
  138. /package/dist/{chunk-3UL7BVDI.js.map → chunk-3TARZOBZ.js.map} +0 -0
  139. /package/dist/{chunk-23EB2N66.js.map → chunk-55ESIZID.js.map} +0 -0
  140. /package/dist/{chunk-HSR3SQNH.js.map → chunk-75C4DV27.js.map} +0 -0
  141. /package/dist/{chunk-63GEUXAG.js.map → chunk-BN6IXTDU.js.map} +0 -0
  142. /package/dist/{chunk-KYTJEG7F.js.map → chunk-DOWJVFKI.js.map} +0 -0
  143. /package/dist/{chunk-ZKQI7KGZ.js.map → chunk-G7FGC7EQ.js.map} +0 -0
  144. /package/dist/{chunk-GAPZBV4P.js.map → chunk-KXN4YMCP.js.map} +0 -0
  145. /package/dist/{chunk-LJX5QBDP.js.map → chunk-L7EVPMOK.js.map} +0 -0
  146. /package/dist/{chunk-7EQOAK6V.js.map → chunk-LYL2MWM6.js.map} +0 -0
  147. /package/dist/{chunk-4WZPGIRU.js.map → chunk-OLL7QI3Y.js.map} +0 -0
  148. /package/dist/{chunk-MUWQA4QI.js.map → chunk-P7USBFIJ.js.map} +0 -0
  149. /package/dist/{chunk-K2ATEMGS.js.map → chunk-PIBNTOS7.js.map} +0 -0
  150. /package/dist/{chunk-4RYUAMA5.js.map → chunk-PO6IPUDB.js.map} +0 -0
  151. /package/dist/{chunk-HXTGDRE4.js.map → chunk-Q72OV4VF.js.map} +0 -0
  152. /package/dist/{chunk-72Q3QRXJ.js.map → chunk-R5IYAFFN.js.map} +0 -0
  153. /package/dist/{chunk-6TUOW6R4.js.map → chunk-SVLY35WI.js.map} +0 -0
  154. /package/dist/{chunk-T4SKN6IN.js.map → chunk-U253YYNH.js.map} +0 -0
  155. /package/dist/{chunk-GINC6ZQJ.js.map → chunk-UAGEVTXM.js.map} +0 -0
  156. /package/dist/{chunk-NFK7BUMT.js.map → chunk-WKHAZ732.js.map} +0 -0
  157. /package/dist/{chunk-FVMQTLGC.js.map → chunk-WU2325QJ.js.map} +0 -0
  158. /package/dist/{chunk-X6OZX6KV.js.map → chunk-YLWVLRWH.js.map} +0 -0
  159. /package/dist/{chunk-FFBKJYME.js.map → chunk-ZFYFLNRE.js.map} +0 -0
  160. /package/dist/{chunk-O3DGRBQ3.js.map → chunk-ZHRXNOXP.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../package.json","../version.ts","../tools/fastapply/apply.ts","../tools/warp_grep/agent/config.ts","../tools/warp_grep/utils/ripgrep.ts","../tools/warp_grep/utils/paths.ts","../tools/warp_grep/utils/files.ts","../tools/warp_grep/providers/local.ts","../client.ts","../tools/fastapply/core.ts","../tools/utils/resilience.ts","../tools/codebase_search/core.ts","../tools/browser/live.ts","../tools/browser/errors.ts","../tools/browser/profiles/types.ts","../tools/browser/profiles/core.ts","../tools/browser/core.ts","../tools/warp_grep/agent/runner.ts","../tools/warp_grep/agent/parser.ts","../tools/warp_grep/agent/tools/grep.ts","../tools/warp_grep/agent/tools/read.ts","../tools/warp_grep/agent/tools/list_directory.ts","../tools/warp_grep/agent/tools/glob.ts","../tools/warp_grep/agent/tools/finish.ts","../tools/warp_grep/agent/helpers.ts","../tools/warp_grep/providers/remote.ts","../tools/warp_grep/providers/code_storage_http.ts","../tools/warp_grep/utils/github.ts","../tools/warp_grep/client.ts","../tools/github/types.ts","../tools/github/core.ts","../git/client.ts","../git/index.ts","../tools/compact/core.ts","../modelrouter/core.ts","../tools/warp_grep/prompts.ts","../tools/warp_grep/openai.ts","../tools/codebase_search/prompts.ts","../tools/codebase_search/openai.ts","../tools/fastapply/prompts.ts","../tools/fastapply/openai.ts","../factories/openai.ts","../tools/warp_grep/anthropic.ts","../tools/codebase_search/anthropic.ts","../tools/fastapply/anthropic.ts","../subagents/prompts.ts","../subagents/anthropic.ts","../factories/anthropic.ts","../tools/warp_grep/vercel.ts","../tools/codebase_search/vercel.ts","../tools/fastapply/vercel.ts","../subagents/vercel.ts","../factories/vercel.ts"],"sourcesContent":["{\n \"name\": \"@morphllm/morphsdk\",\n \"version\": \"0.2.150\",\n \"description\": \"TypeScript SDK and CLI for Morph Fast Apply integration\",\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./edge\": {\n \"types\": \"./dist/edge.d.ts\",\n \"import\": \"./dist/edge.js\",\n \"require\": \"./dist/edge.cjs\"\n },\n \"./tools/warp-grep\": {\n \"types\": \"./dist/tools/warp_grep/index.d.ts\",\n \"import\": \"./dist/tools/warp_grep/index.js\",\n \"require\": \"./dist/tools/warp_grep/index.cjs\"\n },\n \"./tools/warp-grep/openai\": {\n \"types\": \"./dist/tools/warp_grep/openai.d.ts\",\n \"import\": \"./dist/tools/warp_grep/openai.js\",\n \"require\": \"./dist/tools/warp_grep/openai.cjs\"\n },\n \"./tools/warp-grep/anthropic\": {\n \"types\": \"./dist/tools/warp_grep/anthropic.d.ts\",\n \"import\": \"./dist/tools/warp_grep/anthropic.js\",\n \"require\": \"./dist/tools/warp_grep/anthropic.cjs\"\n },\n \"./tools/warp-grep/vercel\": {\n \"types\": \"./dist/tools/warp_grep/vercel.d.ts\",\n \"import\": \"./dist/tools/warp_grep/vercel.js\",\n \"require\": \"./dist/tools/warp_grep/vercel.cjs\"\n },\n \"./tools/warp-grep/client\": {\n \"types\": \"./dist/tools/warp_grep/client.d.ts\",\n \"import\": \"./dist/tools/warp_grep/client.js\",\n \"require\": \"./dist/tools/warp_grep/client.cjs\"\n },\n \"./tools/warp-grep/gemini\": {\n \"types\": \"./dist/tools/warp_grep/gemini.d.ts\",\n \"import\": \"./dist/tools/warp_grep/gemini.js\",\n \"require\": \"./dist/tools/warp_grep/gemini.cjs\"\n },\n \"./tools/warp-grep/harness\": {\n \"types\": \"./dist/tools/warp_grep/harness.d.ts\",\n \"import\": \"./dist/tools/warp_grep/harness.js\",\n \"require\": \"./dist/tools/warp_grep/harness.cjs\"\n },\n \"./tools/fastapply\": {\n \"types\": \"./dist/tools/fastapply/index.d.ts\",\n \"import\": \"./dist/tools/fastapply/index.js\",\n \"require\": \"./dist/tools/fastapply/index.cjs\"\n },\n \"./tools/fastapply/anthropic\": {\n \"types\": \"./dist/tools/fastapply/anthropic.d.ts\",\n \"import\": \"./dist/tools/fastapply/anthropic.js\",\n \"require\": \"./dist/tools/fastapply/anthropic.cjs\"\n },\n \"./tools/fastapply/openai\": {\n \"types\": \"./dist/tools/fastapply/openai.d.ts\",\n \"import\": \"./dist/tools/fastapply/openai.js\",\n \"require\": \"./dist/tools/fastapply/openai.cjs\"\n },\n \"./tools/fastapply/vercel\": {\n \"types\": \"./dist/tools/fastapply/vercel.d.ts\",\n \"import\": \"./dist/tools/fastapply/vercel.js\",\n \"require\": \"./dist/tools/fastapply/vercel.cjs\"\n },\n \"./tools/codebase-search\": {\n \"types\": \"./dist/tools/codebase_search/index.d.ts\",\n \"import\": \"./dist/tools/codebase_search/index.js\",\n \"require\": \"./dist/tools/codebase_search/index.cjs\"\n },\n \"./tools/codebase-search/anthropic\": {\n \"types\": \"./dist/tools/codebase_search/anthropic.d.ts\",\n \"import\": \"./dist/tools/codebase_search/anthropic.js\",\n \"require\": \"./dist/tools/codebase_search/anthropic.cjs\"\n },\n \"./tools/codebase-search/openai\": {\n \"types\": \"./dist/tools/codebase_search/openai.d.ts\",\n \"import\": \"./dist/tools/codebase_search/openai.js\",\n \"require\": \"./dist/tools/codebase_search/openai.cjs\"\n },\n \"./tools/codebase-search/vercel\": {\n \"types\": \"./dist/tools/codebase_search/vercel.d.ts\",\n \"import\": \"./dist/tools/codebase_search/vercel.js\",\n \"require\": \"./dist/tools/codebase_search/vercel.cjs\"\n },\n \"./tools/git\": {\n \"types\": \"./dist/git/index.d.ts\",\n \"import\": \"./dist/git/index.js\",\n \"require\": \"./dist/git/index.cjs\"\n },\n \"./tools/browser\": {\n \"types\": \"./dist/tools/browser/index.d.ts\",\n \"import\": \"./dist/tools/browser/index.js\",\n \"require\": \"./dist/tools/browser/index.cjs\"\n },\n \"./tools/browser/anthropic\": {\n \"types\": \"./dist/tools/browser/anthropic.d.ts\",\n \"import\": \"./dist/tools/browser/anthropic.js\",\n \"require\": \"./dist/tools/browser/anthropic.cjs\"\n },\n \"./tools/browser/openai\": {\n \"types\": \"./dist/tools/browser/openai.d.ts\",\n \"import\": \"./dist/tools/browser/openai.js\",\n \"require\": \"./dist/tools/browser/openai.cjs\"\n },\n \"./tools/browser/vercel\": {\n \"types\": \"./dist/tools/browser/vercel.d.ts\",\n \"import\": \"./dist/tools/browser/vercel.js\",\n \"require\": \"./dist/tools/browser/vercel.cjs\"\n },\n \"./tools/browser/profiles\": {\n \"types\": \"./dist/tools/browser/profiles/index.d.ts\",\n \"import\": \"./dist/tools/browser/profiles/index.js\",\n \"require\": \"./dist/tools/browser/profiles/index.cjs\"\n },\n \"./modelrouter\": {\n \"types\": \"./dist/modelrouter/index.d.ts\",\n \"import\": \"./dist/modelrouter/index.js\",\n \"require\": \"./dist/modelrouter/index.cjs\"\n },\n \"./tools/compact\": {\n \"types\": \"./dist/tools/compact/index.d.ts\",\n \"import\": \"./dist/tools/compact/index.js\",\n \"require\": \"./dist/tools/compact/index.cjs\"\n },\n \"./subagents\": {\n \"types\": \"./dist/subagents/index.d.ts\",\n \"import\": \"./dist/subagents/index.js\",\n \"require\": \"./dist/subagents/index.cjs\"\n },\n \"./subagents/vercel\": {\n \"types\": \"./dist/subagents/vercel.d.ts\",\n \"import\": \"./dist/subagents/vercel.js\",\n \"require\": \"./dist/subagents/vercel.cjs\"\n },\n \"./subagents/anthropic\": {\n \"types\": \"./dist/subagents/anthropic.d.ts\",\n \"import\": \"./dist/subagents/anthropic.js\",\n \"require\": \"./dist/subagents/anthropic.cjs\"\n }\n },\n \"files\": [\n \"dist/**/*.js\",\n \"dist/**/*.cjs\",\n \"dist/**/*.d.ts\",\n \"dist/**/*.map\",\n \"!dist/**/__tests__/**\",\n \"!dist/**/*.test.*\"\n ],\n \"scripts\": {\n \"build\": \"tsup version.ts index.ts edge.ts client.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 git/index.ts git/client.ts git/config.ts git/types.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 --format esm,cjs --sourcemap --clean --dts --dts-resolve\",\n \"prepare\": \"npm run build\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest watch\",\n \"test:anthropic\": \"vitest run anthropic\",\n \"test:openai\": \"vitest run openai\",\n \"test:vercel\": \"vitest run vercel\",\n \"test:git\": \"vitest run git\",\n \"test:browser\": \"vitest run browser\",\n \"test:agent\": \"npx tsx tests/fullAgentTest.ts\",\n \"test:integration\": \"npx tsx tests/fullIntegrationTest.ts\",\n \"release:patch\": \"npm version patch && npm publish\",\n \"release:minor\": \"npm version minor && npm publish\",\n \"release:major\": \"npm version major && npm publish\"\n },\n \"keywords\": [\n \"morph\",\n \"fast-apply\",\n \"cli\",\n \"sdk\",\n \"edit-file\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@vscode/ripgrep\": \"^1.17.0\",\n \"ai\": \">=5.0.0\",\n \"diff\": \"^7.0.0\",\n \"isomorphic-git\": \"^1.25.10\",\n \"openai\": \"^4.52.7\",\n \"zod\": \">=3.23.0\"\n },\n \"devDependencies\": {\n \"@ai-sdk/anthropic\": \"^2.0.70\",\n \"@ai-sdk/openai\": \"^2.0.35\",\n \"@anthropic-ai/sdk\": \"^0.30.1\",\n \"@google/generative-ai\": \"^0.24.1\",\n \"@types/diff\": \"^7.0.2\",\n \"@types/node\": \"^20.14.10\",\n \"@typescript-eslint/eslint-plugin\": \"^7.18.0\",\n \"@typescript-eslint/parser\": \"^7.18.0\",\n \"dotenv\": \"^16.4.5\",\n \"eslint\": \"^8.57.0\",\n \"shx\": \"^0.3.4\",\n \"tsup\": \"^8.5.0\",\n \"tsx\": \"^4.16.2\",\n \"typescript\": \"^5.5.4\",\n \"vitest\": \"^2.1.6\"\n },\n \"peerDependencies\": {\n \"@anthropic-ai/sdk\": \">=0.25.0\",\n \"@google/generative-ai\": \">=0.21.0\",\n \"ai\": \">=5.0.0\",\n \"zod\": \">=3.23.0\"\n },\n \"peerDependenciesMeta\": {\n \"@anthropic-ai/sdk\": {\n \"optional\": true\n },\n \"@google/generative-ai\": {\n \"optional\": true\n },\n \"ai\": {\n \"optional\": true\n },\n \"zod\": {\n \"optional\": true\n }\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","import pkg from './package.json' with { type: 'json' };\nexport const SDK_VERSION: string = pkg.version;\n","/**\n * Edge-compatible code application API\n *\n * This module works on:\n * - Node.js\n * - Cloudflare Workers\n * - Vercel Edge Functions\n * - Deno Deploy\n * - Browser environments\n *\n * For file-based operations, use executeEditFile from core.ts\n */\n\nimport { createTwoFilesPatch } from 'diff';\nimport OpenAI from 'openai';\nimport { SDK_VERSION } from '../../version.js';\nimport type {\n EditChanges,\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n} from './types.js';\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\nconst DEFAULT_TIMEOUT = 30000;\n\n/**\n * Generate a unified diff between two strings\n */\nexport function generateUdiff(\n original: string,\n modified: string,\n filepath: string\n): string {\n return createTwoFilesPatch(\n filepath,\n filepath,\n original,\n modified,\n 'Original',\n 'Modified'\n );\n}\n\n/**\n * Count changes from a unified diff\n */\nexport function countChanges(original: string, modified: string): EditChanges {\n const diff = generateUdiff(original, modified, 'file');\n const lines = diff.split('\\n');\n\n let linesAdded = 0;\n let linesRemoved = 0;\n\n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n linesAdded++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n linesRemoved++;\n }\n }\n\n const linesModified = Math.min(linesAdded, linesRemoved);\n\n return {\n linesAdded: linesAdded - linesModified,\n linesRemoved: linesRemoved - linesModified,\n linesModified,\n };\n}\n\n/**\n * Call Morph Apply API to merge code edits\n * Uses OpenAI SDK for reliable connection handling, retries, and timeouts\n */\nexport async function callMorphAPI(\n originalCode: string,\n codeEdit: string,\n instructions: string,\n filepath: string,\n config: ApplyEditConfig\n): Promise<{ content: string; completionId?: string }> {\n const apiKey = config.morphApiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n const apiUrl = config.morphApiUrl || DEFAULT_API_URL;\n const timeout = config.timeout || DEFAULT_TIMEOUT;\n const debug = config.debug || false;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n\n // Format message with XML tags as per Morph Fast Apply spec\n const message = `<instruction>${instructions}</instruction>\\n<code>${originalCode}</code>\\n<update>${codeEdit}</update>`;\n\n if (debug) {\n console.log(`[FastApply] Calling ${apiUrl}/v1/chat/completions`);\n console.log(`[FastApply] File: ${filepath}, Instructions: ${instructions.slice(0, 60)}...`);\n console.log(`[FastApply] Original: ${originalCode.length} chars, Edit: ${codeEdit.length} chars`);\n }\n\n const startTime = Date.now();\n\n const client = new OpenAI({\n apiKey,\n baseURL: `${apiUrl}/v1`,\n timeout,\n maxRetries: config.retryConfig?.maxRetries ?? 3,\n defaultHeaders: { 'X-Morph-SDK-Version': SDK_VERSION },\n });\n\n const completion = await client.chat.completions.create({\n model: 'morph-v3-fast',\n messages: [{ role: 'user', content: message }],\n });\n\n const content = completion.choices[0]?.message?.content;\n if (!content) {\n throw new Error('Morph API returned empty response');\n }\n\n const elapsed = Date.now() - startTime;\n\n if (debug) {\n console.log(`[FastApply] Success in ${elapsed}ms, merged: ${content.length} chars`);\n }\n\n return { content, completionId: completion.id };\n}\n\n/**\n * Apply an edit to code directly without file I/O\n *\n * This is the edge-compatible code-in/code-out API that accepts code content directly\n * and returns the merged result without reading or writing any files.\n *\n * Works on Cloudflare Workers, Vercel Edge Functions, Deno, and browsers.\n *\n * @param input - Code and edit parameters\n * @param config - Optional configuration\n * @returns Result with merged code\n *\n * @example\n * ```typescript\n * import { applyEdit } from '@morphllm/morphsdk';\n *\n * const result = await applyEdit({\n * originalCode: fs.readFileSync('file.ts', 'utf-8'),\n * codeEdit: '// ... existing code ...\\nconst newVar = 42;\\n// ... existing code ...',\n * instructions: 'Add a new variable',\n * filepath: 'file.ts' // optional, for udiff context\n * });\n *\n * if (result.success) {\n * fs.writeFileSync('file.ts', result.mergedCode);\n * }\n * ```\n */\nexport async function applyEdit(\n input: ApplyEditInput,\n config: ApplyEditConfig = {}\n): Promise<ApplyEditResult> {\n const debug = config.debug || false;\n const filepath = input.filepath || 'file';\n\n try {\n if (debug) {\n console.log(`[FastApply] Applying edit to code (${input.originalCode.length} chars)`);\n }\n\n const { content: mergedCode, completionId } = await callMorphAPI(\n input.originalCode,\n input.codeEdit,\n input.instructions,\n filepath,\n config\n );\n\n const udiff = config.generateUdiff !== false\n ? generateUdiff(input.originalCode, mergedCode, filepath)\n : undefined;\n\n const changes = countChanges(input.originalCode, mergedCode);\n\n return {\n success: true,\n mergedCode,\n udiff,\n changes,\n completionId,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n if (debug) console.error(`[FastApply] Error: ${errorMessage}`);\n\n return {\n success: false,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\n}\n","// Parse timeout from env, defaulting to 30 seconds\nconst parseEnvTimeout = (envValue: string | undefined, defaultMs: number): number => {\n if (!envValue) return defaultMs;\n const parsed = parseInt(envValue, 10);\n return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;\n};\n\nexport const AGENT_CONFIG = {\n MAX_TURNS: 6,\n /** Default timeout for model calls. Can be overridden via MORPH_WARP_GREP_TIMEOUT env var (in ms) */\n TIMEOUT_MS: parseEnvTimeout(process.env.MORPH_WARP_GREP_TIMEOUT, 30_000),\n MAX_CONTEXT_CHARS: 321_600,\n MAX_OUTPUT_LINES: 200,\n MAX_LIST_RESULTS: 500,\n MAX_READ_LINES: 800,\n MAX_LIST_DEPTH: 3,\n LIST_TIMEOUT_MS: 2_000,\n};\n\n/**\n * Comprehensive exclusion list for directories and files\n * These patterns are used with ripgrep's -g flag\n */\nconst BUILTIN_EXCLUDES = [\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n \n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'packages', 'Pods', '.bundle',\n \n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs', '*.egg-info',\n \n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n \n // Cache directories\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n \n // IDE/Editor\n '.idea', '.vscode', '.vs',\n \n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n \n // Temporary\n 'tmp', 'temp', '.tmp', '.temp',\n \n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n \n // Binary/minified\n '*.min.js', '*.min.css', '*.bundle.js',\n '*.wasm', '*.so', '*.dll', '*.pyc',\n '*.map', '*.js.map',\n \n // Hidden directories catch-all\n '.*',\n];\n\nexport const DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || '')\n .split(',')\n .map(s => s.trim())\n .filter(Boolean)\n .concat(BUILTIN_EXCLUDES);\n\nexport const DEFAULT_MODEL = 'morph-warp-grep-v2.1';\n","import { spawn } from 'child_process';\nimport { rgPath } from '@vscode/ripgrep';\n\nexport type ExecResult = { stdout: string; stderr: string; exitCode: number };\n\n// Cache the working ripgrep path to avoid repeated fallback checks\nlet resolvedRgPath: string | null = null;\nlet rgPathChecked = false;\n\nfunction spawnRg(rgBinary: string, args: string[], opts?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult> {\n return new Promise((resolve) => {\n const child = spawn(rgBinary, args, {\n cwd: opts?.cwd,\n env: { ...process.env, ...(opts?.env || {}) },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (d) => (stdout += d.toString()));\n child.stderr.on('data', (d) => (stderr += d.toString()));\n child.on('close', (code) => {\n resolve({ stdout, stderr, exitCode: typeof code === 'number' ? code : -1 });\n });\n child.on('error', () => {\n resolve({ stdout: '', stderr: 'Failed to spawn ripgrep.', exitCode: -1 });\n });\n });\n}\n\n// Check if a result indicates a binary compatibility failure (not a normal rg error)\nfunction isBinaryFailure(result: ExecResult): boolean {\n // Spawn error\n if (result.exitCode === -1) return true;\n // jemalloc page size issue (common on ARM64 with non-standard page sizes)\n if (result.stderr.includes('jemalloc') || result.stderr.includes('Unsupported system page size')) return true;\n // SIGABRT (134 = 128 + 6)\n if (result.exitCode === 134) return true;\n return false;\n}\n\nexport async function runRipgrep(args: string[], opts?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult> {\n // If we've already determined the working path, use it\n if (rgPathChecked && resolvedRgPath) {\n return spawnRg(resolvedRgPath, args, opts);\n }\n\n // First attempt: bundled ripgrep\n if (!rgPathChecked) {\n const result = await spawnRg(rgPath, args, opts);\n \n if (!isBinaryFailure(result)) {\n // Bundled binary works, cache it\n resolvedRgPath = rgPath;\n rgPathChecked = true;\n return result;\n }\n\n // Bundled binary failed, try system rg\n const fallbackResult = await spawnRg('rg', args, opts);\n \n if (!isBinaryFailure(fallbackResult)) {\n // System rg works, cache it\n resolvedRgPath = 'rg';\n rgPathChecked = true;\n return fallbackResult;\n }\n\n // Neither works, mark as checked and return the original error\n rgPathChecked = true;\n return { \n stdout: '', \n stderr: 'Failed to spawn ripgrep. Neither bundled nor system rg is available.', \n exitCode: -1 \n };\n }\n\n // rgPathChecked is true but resolvedRgPath is null - no working rg found\n return { \n stdout: '', \n stderr: 'Failed to spawn ripgrep. Neither bundled nor system rg is available.', \n exitCode: -1 \n };\n}\n\n\n","import fs from 'fs';\nimport path from 'path';\n\nexport function resolveUnderRepo(repoRoot: string, targetPath: string): string {\n const absRoot = path.resolve(repoRoot);\n const resolved = path.resolve(absRoot, targetPath);\n ensureWithinRepo(absRoot, resolved);\n return resolved;\n}\n\nexport function ensureWithinRepo(repoRoot: string, absTarget: string): void {\n const rel = path.relative(path.resolve(repoRoot), path.resolve(absTarget));\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path outside repository root: ${absTarget}`);\n }\n}\n\nexport function toRepoRelative(repoRoot: string, absPath: string): string {\n return path.relative(path.resolve(repoRoot), path.resolve(absPath));\n}\n\nexport function isSymlink(p: string): boolean {\n try {\n const st = fs.lstatSync(p);\n return st.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\n/**\n * Detects and removes consecutive duplicate path segments.\n *\n * When the model predicts a path that includes the repo directory name,\n * joining with repoRoot creates duplication:\n * repoRoot=\"/Users/dhruv/repo\" + predicted=\"repo/src/file.ts\"\n * → \"/Users/dhruv/repo/repo/src/file.ts\"\n *\n * This function detects such patterns and returns the corrected path,\n * or null if no duplication is found.\n */\nexport function fixPathRepetition(fullPath: string): string | null {\n const segments = fullPath.split(path.sep).filter(Boolean);\n if (segments.length < 2) return null;\n\n for (let len = Math.floor(segments.length / 2); len >= 1; len--) {\n for (let i = 0; i <= segments.length - 2 * len; i++) {\n const first = segments.slice(i, i + len);\n const second = segments.slice(i + len, i + 2 * len);\n\n if (first.every((seg, idx) => seg === second[idx])) {\n const fixed = [...segments.slice(0, i), ...segments.slice(i + len)];\n return path.sep + fixed.join(path.sep);\n }\n }\n }\n\n return null;\n}\n\nexport function isTextualFile(filePath: string, maxBytes = 2_000_000): boolean {\n try {\n const st = fs.statSync(filePath);\n if (!st.isFile()) return false;\n if (st.size > maxBytes) return false;\n const fd = fs.openSync(filePath, 'r');\n const buf = Buffer.alloc(512);\n const read = fs.readSync(fd, buf, 0, buf.length, 0);\n fs.closeSync(fd);\n for (let i = 0; i < read; i++) {\n const c = buf[i];\n if (c === 0) return false; // binary heuristic\n }\n return true;\n } catch {\n return false;\n }\n}\n\n\n","import fs from 'fs/promises';\n\nexport async function readAllLines(filePath: string): Promise<string[]> {\n const content = await fs.readFile(filePath, 'utf8');\n // Preserve newlines; split keeping consistency\n return content.split(/\\r?\\n/);\n}\n\n\n","import fs from 'fs/promises';\nimport fssync from 'fs';\nimport path from 'path';\nimport { runRipgrep } from '../utils/ripgrep.js';\nimport { ensureWithinRepo, resolveUnderRepo, toRepoRelative, isSymlink, isTextualFile, fixPathRepetition } from '../utils/paths.js';\nimport type { WarpGrepProvider, GrepResult, ReadResult, GlobResult, ListDirectoryEntry } from './types.js';\nimport { readAllLines } from '../utils/files.js';\nimport { DEFAULT_EXCLUDES, AGENT_CONFIG } from '../agent/config.js';\n\n/**\n * Directories/files to always skip (exact name match)\n */\nconst SKIP_NAMES = new Set([\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'Pods', '.bundle',\n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs',\n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n // Cache\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n // IDE\n '.idea', '.vscode', '.vs',\n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n // Temp\n 'tmp', 'temp', '.tmp', '.temp',\n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n]);\n\n/**\n * File extensions to skip\n */\n\nconst SKIP_EXTENSIONS = new Set([\n '.min.js', '.min.css', '.bundle.js',\n '.wasm', '.so', '.dll', '.pyc',\n '.map', '.js.map',\n]);\n\n/**\n * Check if a filename should be skipped\n */\nfunction shouldSkip(name: string, allowNames?: Set<string>): boolean {\n // Allow explicitly permitted names through\n if (allowNames?.has(name)) return false;\n\n // Skip exact name matches\n if (SKIP_NAMES.has(name)) return true;\n\n // Skip hidden files/directories (start with .)\n if (name.startsWith('.')) return true;\n\n // Skip files with certain extensions\n for (const ext of SKIP_EXTENSIONS) {\n if (name.endsWith(ext)) return true;\n }\n\n return false;\n}\n\nexport class LocalRipgrepProvider implements WarpGrepProvider {\n private readonly allowNames?: Set<string>;\n\n constructor(\n private readonly repoRoot: string,\n private readonly excludes: string[] = DEFAULT_EXCLUDES,\n options?: { allowNames?: string[] },\n ) {\n if (options?.allowNames?.length) {\n this.allowNames = new Set(options.allowNames);\n }\n }\n\n async grep(params: { pattern: string; path: string; glob?: string; context_lines?: number; case_sensitive?: boolean }): Promise<GrepResult> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch (err) {\n return {\n lines: [],\n error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat) return { lines: [] };\n const targetArg = abs === path.resolve(this.repoRoot) ? '.' : toRepoRelative(this.repoRoot, abs);\n const contextLines = params.context_lines !== undefined ? String(params.context_lines) : '1';\n const args = [\n '--no-config',\n '--no-heading',\n '--with-filename',\n '--line-number',\n '--color=never',\n '--trim',\n '--max-columns=400',\n '-C', contextLines,\n ...(params.case_sensitive === false ? ['--ignore-case'] : []),\n ...(params.glob ? ['--glob', params.glob] : []),\n ...this.excludes.filter(e => !this.allowNames?.has(e)).flatMap((e) => ['-g', `!${e}`]),\n params.pattern,\n targetArg || '.',\n ];\n const res = await runRipgrep(args, { cwd: this.repoRoot });\n \n // Gracefully handle ripgrep not being available\n if (res.exitCode === -1) {\n return {\n lines: [],\n error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required but failed to execute. Please install it:\\n` +\n ` • macOS: brew install ripgrep\\n` +\n ` • Ubuntu/Debian: apt install ripgrep\\n` +\n ` • Windows: choco install ripgrep\\n` +\n ` • Or visit: https://github.com/BurntSushi/ripgrep#installation\\n` +\n `Exit code: ${res.exitCode}${res.stderr ? `\\nDetails: ${res.stderr}` : ''}`,\n };\n }\n \n // Handle other ripgrep errors gracefully\n if (res.exitCode !== 0 && res.exitCode !== 1) {\n return {\n lines: [],\n error: `[RIPGREP ERROR] grep failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ''}`,\n };\n }\n \n const lines = (res.stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((l) => l.length > 0);\n if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {\n const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines };\n }\n\n async read(params: { path: string; start?: number; end?: number }): Promise<ReadResult> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch (err) {\n return {\n lines: [],\n error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n let stat = await fs.stat(abs).catch(() => null);\n\n // Handle duplicate path segments from model predictions\n if (!stat || !stat.isFile()) {\n const fixedPath = fixPathRepetition(abs);\n if (fixedPath) {\n const fixedStat = await fs.stat(fixedPath).catch(() => null);\n if (fixedStat?.isFile()) {\n abs = fixedPath;\n stat = fixedStat;\n }\n }\n }\n\n // Gracefully handle file not found / not a file\n if (!stat || !stat.isFile()) {\n return {\n lines: [],\n error: `[FILE NOT FOUND] You tried to read \"${params.path}\" but there is no file at this path. ` +\n `Double-check the path exists and is spelled correctly.`,\n };\n }\n \n // Gracefully handle symlinks\n if (isSymlink(abs)) {\n return {\n lines: [],\n error: `[SYMLINK] You tried to read \"${params.path}\" but this is a symlink. ` +\n `Try reading the actual file it points to instead.`,\n };\n }\n \n // Gracefully handle non-text or too-large files\n if (!isTextualFile(abs)) {\n return {\n lines: [],\n error: `[UNREADABLE FILE] You tried to read \"${params.path}\" but this file is either too large ` +\n `or not a text file, so it cannot be read. Try a different file.`,\n };\n }\n \n let lines: string[];\n try {\n lines = await readAllLines(abs);\n } catch (err) {\n return {\n lines: [],\n error: `[READ ERROR] Failed to read \"${params.path}\": ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n const total = lines.length;\n const rawStart = params.start;\n const rawEnd = params.end;\n \n let s = 1;\n let e = total;\n \n const startValid = rawStart === undefined || (Number.isFinite(rawStart) && rawStart > 0);\n const endValid = rawEnd === undefined || (Number.isFinite(rawEnd) && rawEnd > 0);\n \n if (startValid && endValid) {\n s = rawStart ?? 1;\n e = Math.min(rawEnd ?? total, total);\n if ((s > total && total > 0) || (s > e)) {\n s = 1;\n e = total;\n }\n }\n const out: string[] = [];\n for (let i = s; i <= e; i += 1) {\n const content = lines[i - 1] ?? '';\n out.push(`${i}|${content}`);\n }\n if (out.length > AGENT_CONFIG.MAX_READ_LINES) {\n const truncated = out.slice(0, AGENT_CONFIG.MAX_READ_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${out.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines: out };\n }\n\n async listDirectory(params: { path: string; pattern?: string | null; maxResults?: number; maxDepth?: number }): Promise<ListDirectoryEntry[]> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch {\n // Path outside repo - return empty (graceful failure)\n return [];\n }\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat || !stat.isDirectory()) {\n return [];\n }\n const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;\n const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n const regex = params.pattern ? new RegExp(params.pattern) : null;\n const repoRoot = this.repoRoot;\n const allowNames = this.allowNames;\n\n const results: ListDirectoryEntry[] = [];\n let timedOut = false;\n const startTime = Date.now();\n\n async function walk(dir: string, depth: number) {\n if (Date.now() - startTime > AGENT_CONFIG.LIST_TIMEOUT_MS) {\n timedOut = true;\n return;\n }\n if (depth > maxDepth || results.length >= maxResults) return;\n let entries: import('fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return; // skip unreadable directories (ENOENT, EACCES, etc.)\n }\n for (const entry of entries) {\n if (timedOut || results.length >= maxResults) break;\n\n // Simple name-based filtering - skip junk dirs/files\n if (shouldSkip(entry.name, allowNames)) continue;\n \n // Apply user-provided pattern filter\n if (regex && !regex.test(entry.name)) continue;\n \n const full = path.join(dir, entry.name);\n const isDir = entry.isDirectory();\n \n results.push({\n name: entry.name,\n path: toRepoRelative(repoRoot, full),\n type: isDir ? 'dir' : 'file',\n depth,\n });\n if (isDir) {\n await walk(full, depth + 1);\n }\n }\n }\n await walk(abs, 0);\n return results;\n }\n\n async glob(params: { pattern: string; path?: string }): Promise<GlobResult> {\n let abs: string;\n try {\n abs = params.path ? resolveUnderRepo(this.repoRoot, params.path) : this.repoRoot;\n } catch (err) {\n return { files: [], searchDir: this.repoRoot, totalFound: 0, error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}` };\n }\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat || !stat.isDirectory()) {\n return { files: [], searchDir: abs, totalFound: 0, error: `[PATH ERROR] Directory not found: ${params.path || '.'}` };\n }\n\n const targetArg = abs === path.resolve(this.repoRoot) ? '.' : toRepoRelative(this.repoRoot, abs);\n const args = [\n '--no-config',\n '--files',\n '--color=never',\n '-g', params.pattern,\n ...this.excludes.filter(e => !this.allowNames?.has(e)).flatMap(e => ['-g', `!${e}`]),\n targetArg || '.',\n ];\n\n const res = await runRipgrep(args, { cwd: this.repoRoot });\n if (res.exitCode === -1) {\n return { files: [], searchDir: abs, totalFound: 0, error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required for glob search.` };\n }\n if (res.exitCode !== 0 && res.exitCode !== 1) {\n return { files: [], searchDir: abs, totalFound: 0, error: `[GLOB ERROR] glob failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ''}` };\n }\n\n // Convert to absolute paths\n const absRoot = path.resolve(this.repoRoot);\n const relFiles = (res.stdout || '').trim().split(/\\r?\\n/).filter(l => l.length > 0);\n const absFiles = relFiles.map(f => path.resolve(absRoot, f));\n\n // Sort by mtime descending (newest first), matching training format\n const withMtime: Array<{ file: string; mtime: number }> = [];\n for (const f of absFiles) {\n const s = await fs.stat(f).catch(() => null);\n withMtime.push({ file: f, mtime: s?.mtimeMs ?? 0 });\n }\n withMtime.sort((a, b) => b.mtime - a.mtime);\n\n const totalFound = withMtime.length;\n return { files: withMtime.slice(0, 100).map(f => f.file), searchDir: abs, totalFound };\n }\n}\n","/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface\n * \n * @example\n * ```typescript\n * import { MorphClient } from '@morphllm/morphsdk';\n * \n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * \n * // Direct execution\n * await morph.fastApply.execute({ target_filepath: 'src/index.ts', ... });\n * await morph.warpGrep.execute({ query: 'Find auth', repoRoot: '.' });\n * await morph.codebaseSearch.search({ query: 'auth logic', repoId: 'x' });\n * \n * // Tool creation for AI agents (API key inherited)\n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.anthropic.createCodebaseSearchTool({ repoId: 'x' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * \n * // Use tools with OpenAI\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [grepTool],\n * messages: [{ role: 'user', content: 'Find the bug' }]\n * });\n * ```\n */\n\nimport type { RetryConfig } from './tools/utils/resilience.js';\nimport { FastApplyClient } from './tools/fastapply/core.js';\nimport { CodebaseSearchClient } from './tools/codebase_search/core.js';\nimport { BrowserClient } from './tools/browser/core.js';\nimport { WarpGrepClient } from './tools/warp_grep/client.js';\nimport { GitHubClient } from './tools/github/core.js';\nimport { MorphGit } from './git/index.js';\nimport { CompactClient } from './tools/compact/core.js';\nimport { OpenAIRouter, AnthropicRouter, GeminiRouter, RawRouter } from './modelrouter/core.js';\nimport { OpenAIToolFactory, AnthropicToolFactory, VercelToolFactory } from './factories/index.js';\n\n/**\n * Configuration for the MorphClient\n */\nexport interface MorphClientConfig {\n /** Morph API key for authentication (defaults to MORPH_API_KEY env var) */\n apiKey?: string;\n /** Enable debug logging across all tools */\n debug?: boolean;\n /** Default timeout in milliseconds for API requests */\n timeout?: number;\n /** Retry configuration for failed requests */\n retryConfig?: RetryConfig;\n /** GitHub-specific configuration */\n github?: {\n /** Default installation ID for GitHub operations */\n installationId?: string;\n };\n}\n\n/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface:\n * - fastApply: AI-powered file editing with intelligent merging\n * - codebaseSearch: Semantic code search\n * - warpGrep: Fast code search with ripgrep\n * - browser: AI-powered browser automation\n * - git: Version control operations\n * - routers: Intelligent model selection (OpenAI, Anthropic, Gemini)\n * - openai/anthropic/vercel: Tool factories for agent frameworks\n */\nexport class MorphClient {\n /** Client configuration */\n public config: MorphClientConfig;\n\n /** FastApply tool for editing files with AI-powered merge */\n public fastApply: FastApplyClient;\n\n /** CodebaseSearch tool for semantic code search */\n public codebaseSearch: CodebaseSearchClient;\n\n /** WarpGrep tool for fast code search using ripgrep */\n public warpGrep: WarpGrepClient;\n\n /** Browser tool for AI-powered browser automation */\n public browser: BrowserClient;\n\n /** GitHub tool for PR context, comments, and check runs */\n public github: GitHubClient;\n\n /** Git tool for version control operations */\n public git: MorphGit;\n\n /** Model routers for intelligent model selection */\n public routers: {\n openai: OpenAIRouter;\n anthropic: AnthropicRouter;\n gemini: GeminiRouter;\n raw: RawRouter;\n };\n\n /** OpenAI-compatible tool factories */\n public openai: OpenAIToolFactory;\n\n /** Anthropic-compatible tool factories */\n public anthropic: AnthropicToolFactory;\n\n /** Vercel AI SDK tool factories */\n public vercel: VercelToolFactory;\n\n /** Compact context with line ranges */\n public compact: CompactClient['compact'];\n\n /**\n * Create a new Morph SDK client\n * \n * @param config - Client configuration (apiKey, debug, timeout, retryConfig)\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * ```\n */\n constructor(config: MorphClientConfig = {}) {\n this.config = config;\n\n // Initialize all sub-clients with shared config\n this.fastApply = new FastApplyClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.codebaseSearch = new CodebaseSearchClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.warpGrep = new WarpGrepClient({\n morphApiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.browser = new BrowserClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.github = new GitHubClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n installationId: config.github?.installationId,\n });\n\n this.git = new MorphGit({\n apiKey: config.apiKey,\n retryConfig: config.retryConfig,\n });\n\n this.routers = {\n openai: new OpenAIRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n anthropic: new AnthropicRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n gemini: new GeminiRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n raw: new RawRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n };\n\n const compactClient = new CompactClient({\n morphApiKey: config.apiKey,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n debug: config.debug,\n });\n this.compact = compactClient.compact.bind(compactClient);\n\n // Initialize tool factories\n this.openai = new OpenAIToolFactory(config);\n this.anthropic = new AnthropicToolFactory(config);\n this.vercel = new VercelToolFactory(config);\n }\n}\n","/**\n * Core implementation of Morph Fast Apply\n *\n * This module provides file-based operations that require Node.js.\n * For edge-compatible code-in/code-out operations, use applyEdit from ./apply.ts\n */\n\nimport { join, resolve, relative } from 'path';\nimport type {\n EditFileInput,\n EditFileResult,\n EditFileConfig,\n} from './types.js';\n\n// Re-export edge-compatible functions\nexport { applyEdit, generateUdiff, countChanges, callMorphAPI } from './apply.js';\n\nconst DEFAULT_CONFIG: Required<Omit<EditFileConfig, 'morphApiKey' | 'systemPrompt' | 'retryConfig' | 'description'>> = {\n morphApiUrl: 'https://api.morphllm.com',\n baseDir: process.cwd(),\n generateUdiff: true,\n autoWrite: true,\n timeout: 30000,\n debug: false,\n};\n\n/**\n * FastApply client for programmatic file editing\n * Note: This client requires Node.js for file operations\n */\nexport class FastApplyClient {\n private config: EditFileConfig;\n\n constructor(config: { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n this.config = {\n morphApiKey: config.apiKey,\n morphApiUrl: DEFAULT_CONFIG.morphApiUrl,\n debug: config.debug,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n retryConfig: config.retryConfig,\n generateUdiff: DEFAULT_CONFIG.generateUdiff,\n autoWrite: DEFAULT_CONFIG.autoWrite,\n };\n }\n\n /**\n * Execute a file edit operation\n *\n * @param input - Edit parameters including filepath, instructions, and code_edit\n * @param overrides - Optional config overrides for this operation\n * @returns Edit result with success status and changes\n */\n async execute(input: EditFileInput, overrides?: Partial<EditFileConfig>): Promise<EditFileResult> {\n return executeEditFile(input, { ...this.config, ...overrides });\n }\n\n /**\n * Apply an edit to code directly without file I/O\n *\n * Useful for sandbox environments or when you manage your own file system.\n * Compatible with the earlier OpenAI client API contract.\n *\n * @param input - Code and edit parameters\n * @param overrides - Optional config overrides for this operation\n * @returns Result with merged code\n *\n * @example\n * ```typescript\n * const result = await client.applyEdit({\n * originalCode: 'function hello() { return \"world\"; }',\n * codeEdit: 'function hello() { return \"universe\"; }',\n * instructions: 'Change return value'\n * });\n * console.log(result.mergedCode);\n * ```\n */\n async applyEdit(input: import('./types.js').ApplyEditInput, overrides?: Partial<import('./types.js').ApplyEditConfig>): Promise<import('./types.js').ApplyEditResult> {\n const { applyEdit } = await import('./apply.js');\n return applyEdit(input, { ...this.config, ...overrides });\n }\n}\n\n/**\n * Execute a file edit using Morph Fast Apply\n * Note: This function requires Node.js for file I/O\n */\nexport async function executeEditFile(\n input: EditFileInput,\n config: EditFileConfig = {}\n): Promise<EditFileResult> {\n const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;\n const fullPath = resolve(join(baseDir, input.target_filepath));\n const debug = config.debug || false;\n\n // Security: ensure file is within baseDir\n const relativePath = relative(baseDir, fullPath);\n if (relativePath.startsWith('..') || fullPath === baseDir) {\n return {\n success: false,\n filepath: input.target_filepath,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`,\n };\n }\n\n try {\n if (debug) console.log(`[FastApply] Reading file: ${input.target_filepath}`);\n\n // Dynamic import to avoid loading Node.js fs module at module evaluation time\n const { readFile, writeFile } = await import('fs/promises');\n const { callMorphAPI, generateUdiff, countChanges } = await import('./apply.js');\n\n // Handle both existing and non-existent files\n let originalCode = '';\n try {\n originalCode = await readFile(fullPath, 'utf-8');\n } catch (error: any) {\n if (error.code !== 'ENOENT') {\n throw error; // Re-throw if it's not a \"file not found\" error\n }\n // File doesn't exist, proceed with empty content (will create new file)\n if (debug) console.log(`[FastApply] File doesn't exist, will create new file`);\n }\n\n const { content: mergedCode, completionId } = await callMorphAPI(originalCode, input.code_edit, input.instructions, input.target_filepath, config);\n\n const udiff = config.generateUdiff !== false ? generateUdiff(originalCode, mergedCode, input.target_filepath) : undefined;\n\n if (config.autoWrite !== false) {\n await writeFile(fullPath, mergedCode, 'utf-8');\n if (debug) console.log(`[FastApply] Wrote ${mergedCode.length} chars to ${input.target_filepath}`);\n }\n\n const changes = countChanges(originalCode, mergedCode);\n\n return {\n success: true,\n filepath: input.target_filepath,\n udiff,\n changes,\n completionId,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n if (debug) console.error(`[FastApply] Error: ${errorMessage}`);\n\n return {\n success: false,\n filepath: input.target_filepath,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\n}\n","/**\n * Resilience utilities for retry logic and timeout handling\n */\n\nimport { SDK_VERSION } from '../../version.js';\n\nexport interface RetryConfig {\n maxRetries?: number; // Default: 3\n initialDelay?: number; // Default: 1000ms\n maxDelay?: number; // Default: 30000ms\n backoffMultiplier?: number; // Default: 2\n retryableErrors?: string[]; // Default: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND']\n onRetry?: (attempt: number, error: Error) => void;\n}\n\nconst DEFAULT_RETRY_CONFIG: Required<Omit<RetryConfig, 'onRetry'>> = {\n maxRetries: 3,\n initialDelay: 1000,\n maxDelay: 30000,\n backoffMultiplier: 2,\n retryableErrors: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'],\n};\n\n/**\n * Retry a fetch request with exponential backoff\n * \n * @param url - Request URL\n * @param options - Fetch options\n * @param retryConfig - Retry configuration\n * @returns Response from fetch\n * \n * @example\n * ```typescript\n * const response = await fetchWithRetry(\n * 'https://api.example.com/data',\n * { method: 'POST', body: JSON.stringify(data) },\n * { maxRetries: 5, initialDelay: 500 }\n * );\n * ```\n */\nexport async function fetchWithRetry(\n url: string,\n options: RequestInit,\n retryConfig: RetryConfig = {}\n): Promise<Response> {\n const {\n maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,\n initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,\n maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,\n backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,\n retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,\n onRetry,\n } = retryConfig;\n\n let lastError: Error | null = null;\n let delay = initialDelay;\n\n // Inject SDK version header (caller-provided headers can override)\n options = { ...options, headers: { 'X-Morph-SDK-Version': SDK_VERSION, ...options.headers } };\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n \n // Retry on 429 (rate limit) or 503 (service unavailable)\n if (response.status === 429 || response.status === 503) {\n if (attempt < maxRetries) {\n // Check for Retry-After header\n const retryAfter = response.headers.get('Retry-After');\n const waitTime = retryAfter \n ? parseInt(retryAfter) * 1000 \n : Math.min(delay, maxDelay);\n \n const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);\n if (onRetry) {\n onRetry(attempt + 1, error);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n continue;\n }\n }\n\n return response;\n } catch (error) {\n lastError = error as Error;\n \n // Check if error is retryable\n const isRetryable = retryableErrors.some(errType => \n lastError?.message?.includes(errType)\n );\n\n if (!isRetryable || attempt === maxRetries) {\n throw lastError;\n }\n\n // Exponential backoff\n const waitTime = Math.min(delay, maxDelay);\n if (onRetry) {\n onRetry(attempt + 1, lastError);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n }\n }\n\n throw lastError || new Error('Max retries exceeded');\n}\n\n/**\n * Add timeout to any promise\n * \n * @param promise - Promise to wrap with timeout\n * @param timeoutMs - Timeout in milliseconds\n * @param errorMessage - Optional custom error message\n * @returns Promise that rejects if timeout is reached\n * \n * @example\n * ```typescript\n * const result = await withTimeout(\n * fetchData(),\n * 5000,\n * 'Data fetch timed out'\n * );\n * ```\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n errorMessage?: string\n): Promise<T> {\n let timeoutId: NodeJS.Timeout | number;\n \n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n\n try {\n const result = await Promise.race([promise, timeoutPromise]);\n clearTimeout(timeoutId!);\n return result;\n } catch (error) {\n clearTimeout(timeoutId!);\n throw error;\n }\n}\n\n/**\n * Sleep for specified milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Unified error type for all tools\n */\nexport class MorphError extends Error {\n constructor(\n message: string,\n public code: string,\n public statusCode?: number,\n public retryable: boolean = false\n ) {\n super(message);\n this.name = 'MorphError';\n }\n}\n\n\n","/**\n * Core implementation for codebase search\n * Calls Morph rerank service for two-stage semantic search\n */\n\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n/**\n * CodebaseSearch client for programmatic semantic search\n */\nexport class CodebaseSearchClient {\n private config: { \n apiKey?: string; \n searchUrl?: string; \n debug?: boolean; \n timeout?: number; \n retryConfig?: any;\n };\n\n constructor(config: { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n this.config = {\n apiKey: config.apiKey,\n searchUrl: process.env.MORPH_SEARCH_URL || 'https://repos.morphllm.com',\n debug: config.debug,\n timeout: config.timeout || 30000,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Execute a semantic code search\n * \n * @param input - Search parameters including query, repoId, and target directories\n * @param overrides - Optional config overrides for this operation\n * @returns Search results with ranked code matches\n */\n async search(\n input: { query: string; repoId: string; target_directories?: string[]; explanation?: string; limit?: number },\n overrides?: any\n ): Promise<CodebaseSearchResult> {\n return executeCodebaseSearch(\n {\n query: input.query,\n target_directories: input.target_directories,\n explanation: input.explanation,\n limit: input.limit,\n },\n { ...this.config, repoId: input.repoId, ...overrides }\n );\n }\n}\n\n/**\n * Execute semantic code search\n */\nexport async function executeCodebaseSearch(\n input: CodebaseSearchInput,\n config: CodebaseSearchConfig\n): Promise<CodebaseSearchResult> {\n const apiKey = config.apiKey || process.env.MORPH_API_KEY;\n if (!apiKey) {\n throw new Error('MORPH_API_KEY not found. Set environment variable or pass in config');\n }\n\n const searchUrl = config.searchUrl || process.env.MORPH_SEARCH_URL || 'https://repos.morphllm.com';\n const timeout = config.timeout || 30000;\n const debug = config.debug || false;\n\n if (debug) {\n console.log(`[CodebaseSearch] Query: \"${input.query.slice(0, 60)}...\" repo=${config.repoId}`);\n console.log(`[CodebaseSearch] URL: ${searchUrl}/v1/codebase_search`);\n }\n\n const startTime = Date.now();\n\n try {\n const fetchPromise = fetchWithRetry(\n `${searchUrl}/v1/codebase_search`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n query: input.query,\n repoId: config.repoId,\n targetDirectories: input.target_directories || [],\n limit: input.limit || 10,\n candidateLimit: 50,\n }),\n },\n config.retryConfig\n );\n\n const response = await withTimeout(fetchPromise, timeout, `Codebase search timed out after ${timeout}ms`);\n\n if (!response.ok) {\n const errorText = await response.text();\n if (debug) console.error(`[CodebaseSearch] Error: ${response.status} - ${errorText}`);\n return {\n success: false,\n results: [],\n stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },\n error: `Search failed (${response.status}): ${errorText}`,\n };\n }\n\n const data = await response.json();\n const elapsed = Date.now() - startTime;\n\n if (debug) {\n console.log(`[CodebaseSearch] ✅ ${data.results?.length || 0} results in ${elapsed}ms`);\n }\n\n return {\n success: true,\n results: data.results || [],\n stats: data.stats || { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: elapsed },\n };\n\n } catch (error) {\n if (debug) console.error(`[CodebaseSearch] Exception: ${error instanceof Error ? error.message : error}`);\n return {\n success: false,\n results: [],\n stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n}\n\n","/**\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\n/**\n * Convert a CDP WebSocket scheme to HTTPS.\n *\n * Browser-use's live viewer expects `wss=https://UUID.cdpN.browser-use.com`\n * but CDP URLs use `wss://`. This swaps the scheme.\n */\nfunction cdpToHttps(wsUrl: string): string {\n return wsUrl.replace(/^wss:\\/\\//, 'https://').replace(/^ws:\\/\\//, 'http://');\n}\n\n/**\n * Normalize any debug URL into a valid browser-use live viewer URL.\n *\n * Handles three input formats:\n * 1. Already-correct `https://live.browser-use.com?wss=https://...` — pass through\n * 2. Already-correct but with wrong scheme `...?wss=wss://...` — fix the wss param\n * 3. Raw CDP URL `wss://UUID.cdpN.browser-use.com` — wrap into live viewer URL\n */\nfunction normalizeLiveUrl(debugUrl: string): string {\n const trimmed = debugUrl.trim();\n if (!trimmed) return trimmed;\n\n // Case 3: raw CDP WebSocket URL → wrap into live viewer\n if (trimmed.startsWith('wss://') || trimmed.startsWith('ws://')) {\n return `https://live.browser-use.com?wss=${encodeURIComponent(cdpToHttps(trimmed))}`;\n }\n\n let url: URL;\n try {\n url = new URL(trimmed);\n } catch {\n return trimmed;\n }\n\n // Case 2: live viewer URL with wrong scheme in wss param → fix it\n const wssParam = url.searchParams.get('wss');\n if (wssParam && (wssParam.startsWith('wss://') || wssParam.startsWith('ws://'))) {\n url.searchParams.set('wss', cdpToHttps(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: ${optionsOrPreset}. Available presets: ${Object.keys(LIVE_PRESETS).join(', ')}`\n );\n }\n return preset;\n }\n \n return optionsOrPreset;\n}\n","/**\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","/**\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","/**\n * ProfilesClient - Manage browser profiles for storing login state.\n *\n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: '...' });\n *\n * // Create a profile + live setup session\n * const setup = await morph.browser.profiles.createProfile({\n * name: 'LinkedIn',\n * repoId: 'owner/repo'\n * });\n *\n * console.log('Sign in at:', setup.session.debugUrl);\n * // User logs in, then explicitly save\n * await setup.save();\n *\n * // Use profile in browser tasks\n * await morph.browser.execute({\n * task: 'Check notifications',\n * url: 'https://linkedin.com',\n * profileId: profile.id\n * });\n * ```\n */\n\nimport { fetchWithRetry } from '../../utils/resilience.js';\nimport type { BrowserConfig } from '../types.js';\nimport {\n MorphValidationError,\n MorphAuthenticationError,\n parseAPIError,\n} from '../errors.js';\nimport type {\n Profile,\n ProfileSetup,\n ProfileWithMethods,\n CreateProfileInput,\n ProfileListResponse,\n ProfileSession,\n ProfileSessionInput,\n SaveProfileSessionInput,\n ProfileStateResponse,\n RepoSummary,\n RepoListResponse,\n APIProfile,\n APIProfileSession,\n APIProfileStateResponse,\n} from './types.js';\nimport {\n transformProfile,\n transformCreateInput,\n transformSession,\n transformSaveInput,\n transformStateResponse,\n} from './types.js';\n\nconst DEFAULT_API_URL = process.env.MORPH_ENVIRONMENT === 'DEV'\n ? 'http://localhost:8000'\n : 'https://browser.morphllm.com';\n\n/**\n * ProfilesClient class for managing browser profiles.\n *\n * Access via `morph.browser.profiles` on a MorphClient instance.\n */\nexport class ProfilesClient {\n private config: BrowserConfig;\n\n constructor(config: BrowserConfig) {\n this.config = config;\n }\n\n /**\n * Create a new browser profile and immediately start a live session.\n *\n * @param input - Profile creation parameters\n * @returns Profile setup handle with live URL + save()\n * @throws {MorphValidationError} If input validation fails\n * @throws {MorphProfileLimitError} If profile limit is exceeded\n * @throws {MorphAuthenticationError} If API key is missing or invalid\n *\n * @example\n * ```typescript\n * const setup = await morph.browser.profiles.createProfile({\n * name: 'LinkedIn Production',\n * repoId: 'owner/repo'\n * });\n * console.log(setup.session.debugUrl);\n * await setup.save();\n * ```\n */\n async createProfile(input: CreateProfileInput): Promise<ProfileSetup> {\n return createProfile(input, this.config);\n }\n\n /**\n * List all profiles for the authenticated user.\n *\n * @param repoId - Optional repository ID to filter by\n * @returns Array of profiles\n *\n * @example\n * ```typescript\n * // List all profiles\n * const allProfiles = await morph.browser.profiles.listProfiles();\n *\n * // List profiles for a specific repo\n * const repoProfiles = await morph.browser.profiles.listProfiles('owner/repo');\n * ```\n */\n async listProfiles(repoId?: string): Promise<Profile[]> {\n return listProfiles(this.config, repoId);\n }\n\n /**\n * Get a profile by ID with convenience methods.\n *\n * @param id - Profile ID\n * @returns Profile with attached methods\n * @throws {MorphNotFoundError} If profile is not found\n *\n * @example\n * ```typescript\n * const profile = await morph.browser.profiles.getProfile('profile-id');\n * const state = await profile.getState();\n * await profile.delete();\n * ```\n */\n async getProfile(id: string): Promise<ProfileWithMethods> {\n return getProfile(id, this.config);\n }\n\n /**\n * Update a profile by opening a live session (no rename).\n *\n * @param id - Profile ID\n * @returns Profile setup handle with live URL + save()\n */\n async updateProfile(id: string): Promise<ProfileSetup> {\n return updateProfile(id, this.config);\n }\n\n /**\n * Delete a profile.\n *\n * @param id - Profile ID\n * @throws {MorphNotFoundError} If profile is not found\n */\n async deleteProfile(id: string): Promise<void> {\n return deleteProfile(id, this.config);\n }\n\n /**\n * Start a browser session for profile setup.\n *\n * Returns a live URL where the user can sign into accounts.\n * After signing in, call `saveSession` to persist the state.\n *\n * @param input - Optional session parameters\n * @returns Session with debug URL\n *\n * @example\n * ```typescript\n * const session = await morph.browser.profiles.startSession();\n * console.log('Sign in at:', session.debugUrl);\n * // Open debugUrl in browser, user signs in...\n * await morph.browser.profiles.saveSession(session.sessionId, profile.id);\n * ```\n */\n async startSession(input?: ProfileSessionInput): Promise<ProfileSession> {\n return startProfileSession(this.config, input);\n }\n\n /**\n * Save browser state from a session to a profile.\n *\n * Call this after the user is done signing into accounts.\n * Extracts cookies, localStorage, and sessionStorage.\n *\n * @param sessionId - Browser session ID from startSession\n * @param profileId - Profile ID to save state to\n * @returns Updated profile with cookie domains\n */\n async saveSession(sessionId: string, profileId: string): Promise<Profile> {\n return saveProfileSession({ sessionId, profileId }, this.config);\n }\n\n /**\n * List available repo IDs (discovery).\n *\n * @returns Repo summaries with profile counts\n */\n async listRepos(): Promise<RepoSummary[]> {\n return listRepos(this.config);\n }\n\n /**\n * Get the presigned URL for a profile's state.\n *\n * Use this to download the raw state JSON for debugging\n * or to restore state manually.\n *\n * @param profileId - Profile ID\n * @returns State URL with expiry information\n */\n async getProfileState(profileId: string): Promise<ProfileStateResponse> {\n return getProfileState(profileId, this.config);\n }\n}\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\nfunction validateCreateInput(input: CreateProfileInput): void {\n if (!input.name || typeof input.name !== 'string') {\n throw new MorphValidationError('name is required', 'name');\n }\n\n const trimmedName = input.name.trim();\n if (trimmedName.length === 0) {\n throw new MorphValidationError('name cannot be empty', 'name');\n }\n\n if (trimmedName.length > 100) {\n throw new MorphValidationError('name must be 100 characters or less', 'name');\n }\n\n if (!input.repoId || typeof input.repoId !== 'string') {\n throw new MorphValidationError('repoId is required', 'repoId');\n }\n\n if (input.repoId.trim().length === 0) {\n throw new MorphValidationError('repoId cannot be empty', 'repoId');\n }\n}\n\nfunction validateId(id: string, fieldName: string): void {\n if (!id || typeof id !== 'string') {\n throw new MorphValidationError(`${fieldName} is required`, fieldName);\n }\n\n if (id.trim().length === 0) {\n throw new MorphValidationError(`${fieldName} cannot be empty`, fieldName);\n }\n}\n\n// ============================================================================\n// Standalone Functions\n// ============================================================================\n\n/**\n * Create a new browser profile.\n */\nexport async function createProfile(\n input: CreateProfileInput,\n config: BrowserConfig = {}\n): Promise<ProfileSetup> {\n validateCreateInput(input);\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(transformCreateInput(input)),\n },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiProfile: APIProfile = await response.json();\n const profile = transformProfile(apiProfile);\n const session = await startProfileSession(config, { profileId: profile.id });\n return buildProfileSetup(profile, session, config);\n}\n\n/**\n * List all profiles for the authenticated user.\n */\nexport async function listProfiles(\n config: BrowserConfig = {},\n repoId?: string\n): Promise<Profile[]> {\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const url = repoId\n ? `${apiUrl}/profiles?repo_id=${encodeURIComponent(repoId)}`\n : `${apiUrl}/profiles`;\n\n const response = await fetchWithRetry(\n url,\n { method: 'GET', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const data: { profiles: APIProfile[] } = await response.json();\n return data.profiles.map(transformProfile);\n}\n\n/**\n * Get a profile by ID with convenience methods.\n */\nexport async function getProfile(\n id: string,\n config: BrowserConfig = {}\n): Promise<ProfileWithMethods> {\n validateId(id, 'id');\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/${encodeURIComponent(id)}`,\n { method: 'GET', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiProfile: APIProfile = await response.json();\n const profile = transformProfile(apiProfile);\n\n // Attach convenience methods\n return {\n ...profile,\n getState: () => getProfileState(id, config),\n delete: () => deleteProfile(id, config),\n };\n}\n\n/**\n * Update a profile.\n */\nexport async function updateProfile(\n id: string,\n config: BrowserConfig = {}\n): Promise<ProfileSetup> {\n validateId(id, 'id');\n const profile = await fetchProfile(id, config);\n const session = await startProfileSession(config, { profileId: profile.id });\n return buildProfileSetup(profile, session, config);\n}\n\n/**\n * Delete a profile.\n */\nexport async function deleteProfile(\n id: string,\n config: BrowserConfig = {}\n): Promise<void> {\n validateId(id, 'id');\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/${encodeURIComponent(id)}`,\n { method: 'DELETE', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n}\n\n/**\n * Start a browser session for profile setup.\n */\nexport async function startProfileSession(\n config: BrowserConfig = {},\n input?: ProfileSessionInput\n): Promise<ProfileSession> {\n if (!config.apiKey) {\n throw new MorphAuthenticationError();\n }\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n // Transform input if provided\n const body = input?.profileId\n ? { profile_id: input.profileId }\n : {};\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/session/start`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiSession: APIProfileSession = await response.json();\n return transformSession(apiSession);\n}\n\n/**\n * Save browser state from a session to a profile.\n */\nexport async function saveProfileSession(\n input: SaveProfileSessionInput,\n config: BrowserConfig = {}\n): Promise<Profile> {\n validateId(input.sessionId, 'sessionId');\n validateId(input.profileId, 'profileId');\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/session/save`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(transformSaveInput(input)),\n },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiProfile: APIProfile = await response.json();\n return transformProfile(apiProfile);\n}\n\n/**\n * List repo IDs available to the authenticated user/org.\n */\nexport async function listRepos(config: BrowserConfig = {}): Promise<RepoSummary[]> {\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/repos`,\n { method: 'GET', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const data = await response.json();\n const repos = Array.isArray(data?.repos) ? data.repos : [];\n\n return repos.map((repo: any) => ({\n repoId: repo.repo_id,\n repoFullName: repo.repo_full_name,\n profileCount: repo.profile_count ?? 0,\n })) satisfies RepoSummary[];\n}\n\n/**\n * Get the presigned URL for a profile's state.\n */\nexport async function getProfileState(\n profileId: string,\n config: BrowserConfig = {}\n): Promise<ProfileStateResponse> {\n validateId(profileId, 'profileId');\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/${encodeURIComponent(profileId)}/state`,\n { method: 'GET', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiState: APIProfileStateResponse = await response.json();\n return transformStateResponse(apiState);\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction buildHeaders(config: BrowserConfig): Record<string, string> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n }\n return headers;\n}\n\nasync function fetchProfile(id: string, config: BrowserConfig): Promise<Profile> {\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/${encodeURIComponent(id)}`,\n { method: 'GET', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiProfile: APIProfile = await response.json();\n return transformProfile(apiProfile);\n}\n\nfunction buildProfileSetup(profile: Profile, session: ProfileSession, config: BrowserConfig): ProfileSetup {\n return {\n profile,\n session,\n save: () => saveProfileSession({ sessionId: session.sessionId, profileId: profile.id }, config),\n };\n}\n","/**\n * Core implementation for browser automation tasks\n */\n\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport type {\n BrowserConfig,\n BrowserTaskInput,\n BrowserTaskInputWithSchema,\n BrowserTaskResult,\n BrowserTaskWithPromise,\n BrowserTaskWithPromiseAndSchema,\n RecordingStatus,\n RecordingWithMethods,\n ErrorsResponse,\n LiveSessionOptions,\n IframeOptions,\n WebpOptions,\n WebpResponse,\n} from './types.js';\nimport { buildLiveUrl, buildLiveIframe, buildEmbedCode, resolvePreset } from './live.js';\nimport { ProfilesClient } from './profiles/core.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: process.env.MORPH_ENVIRONMENT === 'DEV' \n ? 'http://localhost:8000'\n : 'https://browser.morphllm.com',\n timeout: 1000000, // 10 minutes for complex tasks\n debug: false,\n};\n\n/**\n * BrowserClient class for easier usage with instance configuration\n */\nexport class BrowserClient {\n private config: BrowserConfig;\n\n /**\n * Profile management - create and manage browser profiles for storing login state.\n */\n public profiles: ProfilesClient;\n\n constructor(config: BrowserConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n this.profiles = new ProfilesClient(this.config);\n }\n\n /**\n * Execute a browser automation task\n */\n async execute(input: BrowserTaskInput): Promise<BrowserTaskResult> {\n return executeBrowserTask(input, this.config);\n }\n\n async createTask(input: BrowserTaskInput): Promise<BrowserTaskWithPromise>;\n async createTask<T>(input: BrowserTaskInputWithSchema<T>): Promise<BrowserTaskWithPromiseAndSchema<T>>;\n async createTask<T>(\n input: BrowserTaskInput | BrowserTaskInputWithSchema<T>\n ): Promise<BrowserTaskWithPromise | BrowserTaskWithPromiseAndSchema<T>> {\n const apiUrl = this.config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = this.config.debug || false;\n \n const hasTask = typeof input.task === 'string' && input.task.trim().length > 0;\n const hasDiff = typeof (input as any).diff === 'string' && (input as any).diff.trim().length > 0;\n\n if (!hasTask && !hasDiff) {\n throw new Error('Browser task requires either \"task\" (natural language) or \"diff\" (PR-review planning)');\n }\n\n if (debug) {\n const preview = (input.task ?? '').slice(0, 60);\n console.log(`[Browser] createTask: \"${preview}...\" url=${input.url || 'none'}`);\n console.log(`[Browser] Calling async endpoint: ${apiUrl}/browser-task/async`);\n }\n \n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.config.apiKey) headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n \n // Call ASYNC endpoint for immediate return with live URL\n const response = await fetch(`${apiUrl}/browser-task/async`, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n task: input.task,\n diff: input.diff,\n url: input.url,\n max_steps: input.maxSteps ?? 10,\n model: input.model ?? 'morph-computer-use-v0',\n viewport_width: input.viewportWidth ?? 1280,\n viewport_height: input.viewportHeight ?? 720,\n external_id: input.externalId,\n repo_id: input.repoId,\n repo_full_name: input.repoFullName,\n commit_id: input.commitId,\n record_video: input.recordVideo ?? false,\n video_width: input.videoWidth ?? input.viewportWidth ?? 1280,\n video_height: input.videoHeight ?? input.viewportHeight ?? 720,\n allow_resizing: input.allowResizing ?? false,\n structured_output: 'schema' in input ? stringifyStructuredOutput(input.schema) : undefined,\n auth: input.auth,\n profile_id: input.profileId,\n force_query_params: input.forceQueryParams,\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] Error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n \n const result = mapTaskResult(await response.json());\n \n if (debug) {\n const debugUrl = result.debugUrl;\n console.log(`[Browser] ✅ Task created: recordingId=${result.recordingId ?? 'none'} debugUrl=${debugUrl ? 'available' : 'none'}`);\n }\n \n if ('schema' in input) {\n return wrapTaskResponseWithSchema(result, this.config, input.schema);\n } else {\n return wrapTaskResponse(result, this.config);\n }\n }\n\n /**\n * Execute task with recording and wait for video to be ready\n */\n async executeWithRecording(\n input: BrowserTaskInput & { recordVideo: true }\n ): Promise<BrowserTaskResult & { recording?: RecordingWithMethods }> {\n return executeWithRecording(input, this.config);\n }\n\n /**\n * Get recording status and URLs\n */\n async getRecording(recordingId: string): Promise<RecordingWithMethods> {\n return getRecording(recordingId, this.config);\n }\n\n /**\n * Wait for recording to complete with automatic polling\n */\n async waitForRecording(\n recordingId: string,\n options?: { timeout?: number; pollInterval?: number }\n ): Promise<RecordingWithMethods> {\n return waitForRecording(recordingId, this.config, options);\n }\n\n /**\n * Get errors from recording with screenshots\n */\n async getErrors(recordingId: string): Promise<ErrorsResponse> {\n return getErrors(recordingId, this.config);\n }\n\n /**\n * Get animated WebP preview of recording\n */\n async getWebp(\n recordingId: string,\n options?: WebpOptions\n ): Promise<WebpResponse> {\n return getWebp(recordingId, this.config, options);\n }\n\n /**\n * Check if browser worker service is healthy\n */\n async checkHealth(): Promise<{\n ok: boolean;\n google_configured: boolean;\n database_configured: boolean;\n s3_configured: boolean;\n error?: string;\n }> {\n return checkHealth(this.config);\n }\n}\n\n/**\n * Execute a natural language browser automation task\n * \n * Returns the full task result including rich agent history data (urls, errors, \n * action_history, judgement, etc.). When using this as an agent tool, use the\n * formatResult() functions from the SDK adapters to return a concise summary.\n * \n * @param input - Task parameters\n * @param config - Optional configuration (apiKey, apiUrl to override default)\n * @returns Task result with success status, findings, and comprehensive execution history\n * \n * @example\n * ```typescript\n * const result = await executeBrowserTask(\n * {\n * task: \"Test checkout flow for buying a pineapple\",\n * url: \"https://3000-abc.e2b.dev\",\n * maxSteps: 20,\n * repoId: \"my-project\",\n * commitId: \"uuid-here\"\n * },\n * {\n * apiKey: process.env.MORPH_API_KEY,\n * // apiUrl: 'http://localhost:8001' // Override for local testing\n * }\n * );\n * \n * if (result.success) {\n * console.log('Task completed:', result.result);\n * console.log('URLs visited:', result.urls);\n * console.log('Actions taken:', result.actionNames);\n * console.log('Has errors:', result.hasErrors);\n * console.log('Replay:', result.replayUrl);\n * }\n * ```\n */\nexport async function executeBrowserTask(\n input: BrowserTaskInput,\n config: BrowserConfig = {}\n): Promise<BrowserTaskResult> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const timeout = config.timeout || DEFAULT_CONFIG.timeout;\n const debug = config.debug || false;\n\n if (!input.task || input.task.trim().length === 0) {\n return { \n success: false, \n error: 'Task description is required. Example: \"Go to example.com and click the login button\"' \n };\n }\n\n if (input.maxSteps !== undefined && (input.maxSteps < 1 || input.maxSteps > 50)) {\n return { \n success: false, \n error: 'maxSteps must be between 1 and 50. Use more steps for complex multi-page flows.'\n };\n }\n\n if (debug) {\n console.log(`[Browser] Task: \"${input.task.slice(0, 60)}...\" url=${input.url || 'none'} maxSteps=${input.maxSteps ?? 10}`);\n console.log(`[Browser] Recording: ${input.recordVideo ? 'yes' : 'no'} | Calling ${apiUrl}/browser-task`);\n }\n\n const startTime = Date.now();\n\n try {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) headers['Authorization'] = `Bearer ${config.apiKey}`;\n\n const fetchPromise = fetchWithRetry(\n `${apiUrl}/browser-task`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n task: input.task,\n url: input.url,\n max_steps: input.maxSteps ?? 10,\n model: input.model ?? 'morph-computer-use-v0',\n viewport_width: input.viewportWidth ?? 1280,\n viewport_height: input.viewportHeight ?? 720,\n external_id: input.externalId,\n repo_id: input.repoId,\n commit_id: input.commitId,\n record_video: input.recordVideo ?? false,\n video_width: input.videoWidth ?? input.viewportWidth ?? 1280,\n video_height: input.videoHeight ?? input.viewportHeight ?? 720,\n allow_resizing: input.allowResizing ?? false,\n structured_output: input.structuredOutput,\n auth: input.auth,\n profile_id: input.profileId,\n force_query_params: input.forceQueryParams,\n }),\n },\n config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n timeout,\n `Browser task timed out after ${timeout}ms. Consider increasing timeout or reducing maxSteps.`\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] Error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result: BrowserTaskResult = mapTaskResult(await response.json());\n const elapsed = Date.now() - startTime;\n \n if (debug) {\n console.log(`[Browser] ✅ ${result.success ? 'Success' : 'Failed'} in ${elapsed}ms | steps=${result.stepsTaken ?? 0} recordingId=${result.recordingId ?? 'none'}`);\n }\n\n return result;\n\n } catch (error) {\n if (error instanceof Error) {\n // Handle network errors\n if (error.message.includes('ECONNREFUSED') || error.message.includes('fetch failed')) {\n return {\n success: false,\n error: `Cannot connect to browser worker at ${apiUrl}. Ensure the service is running and accessible. For local dev, set MORPH_ENVIRONMENT=DEV.`,\n };\n }\n\n return {\n success: false,\n error: error.message,\n };\n }\n\n return {\n success: false,\n error: String(error),\n };\n }\n}\n\n/**\n * Get recording status and video URL\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @returns Recording with convenience methods (.getWebp(), .getErrors())\n * \n * @example\n * ```typescript\n * const recording = await getRecording('uuid-here', { apiKey: 'key' });\n * \n * // Get animated WebP\n * const { webpUrl } = await recording.getWebp({ width: 780 });\n * \n * // Get errors with screenshots\n * const { errors } = await recording.getErrors();\n * ```\n */\nexport async function getRecording(\n recordingId: string,\n config: BrowserConfig = {}\n): Promise<RecordingWithMethods> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getRecording');\n }\n\n if (debug) console.log(`[Browser] getRecording: ${recordingId}`);\n\n const response = await fetch(`${apiUrl}/recordings/${recordingId}`, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getRecording error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const data: RecordingStatus = mapRecordingStatus(await response.json());\n if (debug) console.log(`[Browser] Recording status: ${data.status}`);\n\n // Return recording with convenience methods\n return {\n ...data,\n getWebp: (options?: WebpOptions) => getWebp(recordingId, config, options),\n getErrors: () => getErrors(recordingId, config),\n };\n}\n\n/**\n * Wait for recording to complete with automatic polling\n * \n * @param recordingId - Recording UUID\n * @param config - Configuration with apiKey\n * @param options - Polling options\n * @returns Recording status when completed or errored\n * \n * @example\n * ```typescript\n * const result = await executeBrowserTask({ task: '...', recordVideo: true }, config);\n * if (result.recordingId) {\n * const recording = await waitForRecording(result.recordingId, config, {\n * timeout: 60000, // 1 minute\n * pollInterval: 2000 // Check every 2 seconds\n * });\n * console.log('Video URL:', recording.videoUrl);\n * }\n * ```\n */\nexport async function waitForRecording(\n recordingId: string,\n config: BrowserConfig = {},\n options: { timeout?: number; pollInterval?: number } = {}\n): Promise<RecordingWithMethods> {\n const timeout = options.timeout ?? 60000; // Default 1 minute\n const pollInterval = options.pollInterval ?? 2000; // Default 2 seconds\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const status = await getRecording(recordingId, config);\n \n if (status.status === 'COMPLETED' || status.status === 'ERROR') {\n return status;\n }\n\n // Wait before next poll\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error(`Recording timeout after ${timeout}ms - status still pending`);\n}\n\n/**\n * Execute task with recording and wait for video to be ready\n * \n * @param input - Task parameters with recordVideo=true\n * @param config - Configuration with apiKey\n * @returns Task result with ready video URL\n * \n * @example\n * ```typescript\n * const result = await executeWithRecording(\n * {\n * task: \"Test checkout flow\",\n * url: \"https://example.com\",\n * recordVideo: true,\n * repoId: \"my-project\"\n * },\n * { apiKey: process.env.MORPH_API_KEY }\n * );\n * \n * console.log('Task result:', result.result);\n * console.log('Video URL:', result.recording?.videoUrl);\n * ```\n */\nexport async function executeWithRecording(\n input: BrowserTaskInput & { recordVideo: true },\n config: BrowserConfig = {}\n): Promise<BrowserTaskResult & { recording?: RecordingWithMethods }> {\n // Execute task with recording\n const taskResult = await executeBrowserTask(input, config);\n\n // If recording was created, wait for it to complete\n if (taskResult.recordingId) {\n try {\n const recording = await waitForRecording(\n taskResult.recordingId,\n config,\n { timeout: 60000, pollInterval: 2000 }\n );\n return {\n ...taskResult,\n recording,\n };\n } catch (error) {\n // Return task result even if recording fails\n // Still attach convenience methods for consistent API\n const errorRecording: RecordingWithMethods = {\n id: taskResult.recordingId,\n status: 'ERROR',\n error: error instanceof Error ? error.message : String(error),\n createdAt: new Date().toISOString(),\n getWebp: (options?: WebpOptions) => getWebp(taskResult.recordingId!, config, options),\n getErrors: () => getErrors(taskResult.recordingId!, config),\n };\n return {\n ...taskResult,\n recording: errorRecording,\n };\n }\n }\n\n return taskResult;\n}\n\n/**\n * Get errors from recording with screenshots\n * \n * Screenshots are captured in real-time (500ms after error occurs) during the browser session.\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @returns Errors with real-time screenshots\n * \n * @example\n * ```typescript\n * const { errors, totalErrors } = await getErrors('uuid-here', { apiKey: 'key' });\n * \n * console.log(`Found ${totalErrors} errors`);\n * \n * errors.forEach(err => {\n * console.log(`[${err.type}] ${err.message}`);\n * if (err.url) console.log(` URL: ${err.url}`);\n * if (err.screenshotUrl) console.log(` Screenshot: ${err.screenshotUrl}`);\n * \n * // Download screenshot\n * if (err.screenshotUrl) {\n * const response = await fetch(err.screenshotUrl);\n * const screenshot = await response.arrayBuffer();\n * // Save or process screenshot\n * }\n * });\n * ```\n */\nexport async function getErrors(\n recordingId: string,\n config: BrowserConfig = {}\n): Promise<ErrorsResponse> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getErrors');\n }\n\n if (debug) console.log(`[Browser] getErrors: ${recordingId}`);\n\n const response = await fetch(`${apiUrl}/recordings/${recordingId}/errors`, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getErrors error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const errors = mapErrorsResponse(await response.json());\n if (debug) console.log(`[Browser] Found ${errors.totalErrors} errors`);\n\n return errors;\n}\n\n/**\n * Helper to serialize Zod schema for API\n */\nfunction stringifyStructuredOutput(schema: any): string {\n try {\n return JSON.stringify({\n type: 'object',\n description: 'Zod schema definition (Zod v3)',\n zodDef: schema._def,\n });\n } catch (error) {\n console.warn('[Browser] Failed to serialize Zod schema:', error);\n return JSON.stringify({\n type: 'object',\n description: 'Schema serialization failed',\n });\n }\n}\n\n/**\n * Parse and validate structured task output\n */\nfunction parseStructuredTaskOutput<T>(\n result: BrowserTaskResult,\n schema: any\n): BrowserTaskResult & { parsed: T | null } {\n if (!result.output) {\n return { ...result, parsed: null };\n }\n\n try {\n const parsed = JSON.parse(result.output);\n const validated = schema.parse(parsed) as T;\n return { ...result, parsed: validated };\n } catch (error) {\n if (error instanceof SyntaxError) {\n return { ...result, parsed: null };\n }\n throw error;\n }\n}\n\nfunction mapTaskResult(api: any): BrowserTaskResult {\n if (!api || typeof api !== 'object') {\n return api as BrowserTaskResult;\n }\n\n return {\n success: api.success,\n result: api.result,\n error: api.error,\n stepsTaken: api.steps_taken,\n executionTimeMs: api.execution_time_ms,\n urls: api.urls,\n actionNames: api.action_names,\n errors: api.errors,\n modelActions: api.model_actions,\n isDone: api.is_done,\n actionHistory: api.action_history,\n actionResults: api.action_results,\n hasErrors: api.has_errors,\n numberOfSteps: api.number_of_steps,\n judgement: api.judgement,\n isValidated: api.is_validated,\n replayId: api.replay_id,\n replayUrl: api.replay_url,\n recordingId: api.recording_id,\n recordingStatus: api.recording_status,\n taskId: api.task_id,\n status: api.status,\n output: api.output,\n debugUrl: api.debug_url,\n };\n}\n\nfunction mapRecordingStatus(api: any): RecordingStatus {\n return {\n id: api.id,\n status: api.status,\n replayUrl: api.replay_url,\n networkUrl: api.network_url,\n consoleUrl: api.console_url,\n videoUrl: api.video_url,\n result: api.result,\n totalEvents: api.total_events,\n fileSize: api.file_size,\n duration: api.duration,\n error: api.error,\n createdAt: api.created_at,\n };\n}\n\nfunction mapBrowserError(api: any): ErrorsResponse['errors'][number] {\n return {\n type: api.type,\n message: api.message,\n url: api.url,\n timestamp: api.timestamp,\n screenshotUrl: api.screenshot_url,\n capturedAt: api.captured_at,\n status: api.status,\n };\n}\n\nfunction mapErrorsResponse(api: any): ErrorsResponse {\n return {\n recordingId: api.recording_id,\n totalErrors: api.total_errors,\n errors: Array.isArray(api.errors) ? api.errors.map(mapBrowserError) : [],\n };\n}\n\nfunction mapWebpResponse(api: any): WebpResponse {\n return {\n webpUrl: api.webp_url,\n cached: api.cached,\n width: api.width,\n fps: api.fps,\n maxDuration: api.max_duration,\n fileSize: api.file_size,\n maxSizeMb: api.max_size_mb,\n budgetMet: api.budget_met,\n qualityUsed: api.quality_used,\n attempts: api.attempts,\n };\n}\n\n/**\n * Get current task status\n */\nasync function getTaskStatus(\n taskId: string,\n config: BrowserConfig\n): Promise<BrowserTaskResult> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (debug) console.log(`[Browser] getTaskStatus: ${taskId}`);\n\n const headers: Record<string, string> = {};\n if (config.apiKey) headers['Authorization'] = `Bearer ${config.apiKey}`;\n\n const response = await fetch(`${apiUrl}/tasks/${taskId}`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getTaskStatus error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result: BrowserTaskResult = mapTaskResult(await response.json());\n if (debug) console.log(`[Browser] Task status: ${result.status}`);\n\n return result;\n}\n\n/**\n * Generate live URL for watching task execution in real-time\n */\nfunction generateLiveUrl(taskId: string, config: BrowserConfig): string {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const baseUrl = apiUrl.replace('/api', '');\n return `${baseUrl}/tasks/${taskId}/live`;\n}\n\n/**\n * Poll task until completion\n */\nasync function pollTaskUntilComplete(\n taskId: string,\n config: BrowserConfig,\n pollConfig: { interval?: number; timeout?: number } = {}\n): Promise<BrowserTaskResult> {\n const interval = pollConfig.interval ?? 2000; // 2 seconds\n const timeout = pollConfig.timeout ?? 300000; // 5 minutes\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const status = await getTaskStatus(taskId, config);\n \n if (status.status === 'completed' || status.status === 'failed') {\n return status;\n }\n\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n\n throw new Error(`Task polling timeout after ${timeout}ms`);\n}\n\n/**\n * Wrap task response with convenience methods\n */\nfunction wrapTaskResponse(\n result: BrowserTaskResult,\n config: BrowserConfig\n): BrowserTaskWithPromise {\n const debugUrl = result.debugUrl ?? '';\n\n const wrapped: BrowserTaskWithPromise = {\n ...result,\n debugUrl,\n taskId: result.taskId || '',\n liveUrl: result.taskId\n ? generateLiveUrl(result.taskId, config)\n : debugUrl,\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n // If we have a taskId, poll task status endpoint\n if (result.taskId) {\n return pollTaskUntilComplete(result.taskId!, config, pollConfig);\n }\n // If we have a recordingId, poll recording status instead\n if (result.recordingId) {\n const recording = await waitForRecording(\n result.recordingId,\n config,\n pollConfig\n );\n // Return a result-like object (recording doesn't have full task result)\n return {\n ...result,\n recordingStatus: recording.status,\n } as BrowserTaskResult;\n }\n // No way to poll completion\n throw new Error('Cannot poll completion: no taskId or recordingId available');\n },\n // Add Steel live session helpers - either functional or error-throwing\n getLiveUrl: debugUrl\n ? (options?: LiveSessionOptions) => buildLiveUrl(debugUrl, options)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n getLiveIframe: debugUrl\n ? (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(debugUrl, options);\n }\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n getEmbedCode: debugUrl\n ? () => buildEmbedCode(debugUrl)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n };\n\n return wrapped;\n}\n\n/**\n * Wrap task response with schema validation\n */\nfunction wrapTaskResponseWithSchema<T>(\n result: BrowserTaskResult,\n config: BrowserConfig,\n schema: any\n): BrowserTaskWithPromiseAndSchema<T> {\n const debugUrl = result.debugUrl ?? '';\n const parsed = result.output\n ? parseStructuredTaskOutput<T>(result, schema)\n : { ...result, parsed: null };\n\n const wrapped: BrowserTaskWithPromiseAndSchema<T> = {\n ...parsed,\n debugUrl,\n taskId: result.taskId || '',\n liveUrl: result.taskId\n ? generateLiveUrl(result.taskId, config)\n : debugUrl,\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n // If we have a taskId, poll task status endpoint\n if (result.taskId) {\n const finalResult = await pollTaskUntilComplete(result.taskId!, config, pollConfig);\n return parseStructuredTaskOutput<T>(finalResult, schema);\n }\n // If we have a recordingId, poll recording status instead\n if (result.recordingId) {\n const recording = await waitForRecording(\n result.recordingId,\n config,\n pollConfig\n );\n // Return parsed result (recording doesn't have task output)\n return {\n ...parsed,\n recordingStatus: recording.status,\n };\n }\n // No way to poll completion\n throw new Error('Cannot poll completion: no taskId or recordingId available');\n },\n // Add Steel live session helpers - either functional or error-throwing\n getLiveUrl: debugUrl\n ? (options?: LiveSessionOptions) => buildLiveUrl(debugUrl, options)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions. '\n );\n },\n getLiveIframe: debugUrl\n ? (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(debugUrl, options);\n }\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions.'\n );\n },\n getEmbedCode: debugUrl\n ? () => buildEmbedCode(debugUrl)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions.'\n );\n },\n };\n\n return wrapped;\n}\n\n/**\n * Get animated WebP preview of recording\n * \n * Converts the native video recording to an animated WebP. Results are cached in S3.\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @param options - WebP generation options\n * @returns WebP URL and metadata\n * \n * @example\n * ```typescript\n * const webp = await getWebp('uuid-here', { apiKey: 'key' }, {\n * width: 780,\n * fps: 10,\n * quality: 65,\n * maxDuration: 15\n * });\n * console.log('WebP URL:', webp.webpUrl);\n * console.log('From cache:', webp.cached);\n * ```\n */\nexport async function getWebp(\n recordingId: string,\n config: BrowserConfig = {},\n options: WebpOptions = {}\n): Promise<WebpResponse> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getWebp');\n }\n\n // Build query params\n const params = new URLSearchParams();\n if (options.maxDuration !== undefined) params.set('max_duration', String(options.maxDuration));\n if (options.fps !== undefined) params.set('fps', String(options.fps));\n if (options.width !== undefined) params.set('width', String(options.width));\n if (options.quality !== undefined) params.set('quality', String(options.quality));\n if (options.maxSizeMb !== undefined) params.set('max_size_mb', String(options.maxSizeMb));\n\n const url = `${apiUrl}/recordings/${recordingId}/webp${params.toString() ? '?' + params.toString() : ''}`;\n \n if (debug) console.log(`[Browser] getWebp: ${url}`);\n\n const response = await fetch(url, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getWebp error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result = mapWebpResponse(await response.json());\n if (debug) console.log(`[Browser] WebP ready: ${result.webpUrl} (cached: ${result.cached})`);\n\n return result;\n}\n\n/**\n * Check if browser worker service is healthy\n * \n * @param config - Optional configuration\n * @returns Health status\n */\nexport async function checkHealth(config: BrowserConfig = {}): Promise<{\n ok: boolean;\n google_configured: boolean;\n database_configured: boolean;\n s3_configured: boolean;\n error?: string;\n}> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n\n try {\n const response = await fetch(`${apiUrl}/health`, {\n method: 'GET',\n headers: config.apiKey\n ? { 'Authorization': `Bearer ${config.apiKey}` }\n : {},\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n\n const data = await response.json();\n return {\n ok: true,\n google_configured: data.google_configured ?? false,\n database_configured: data.database_configured ?? false,\n s3_configured: data.s3_configured ?? false,\n };\n } catch (error) {\n return {\n ok: false,\n google_configured: false,\n database_configured: false,\n s3_configured: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n","import { AGENT_CONFIG, DEFAULT_MODEL } from './config.js';\nimport type { AgentRunResult, ChatMessage, SessionConfig, AgentFinish, ToolCallRef, WarpGrepExecutionMetrics, WarpGrepTurnMetrics, WarpGrepStep } from './types.js';\nimport { parseFinishFiles, parseReadLines, extractPathFromCommand } 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 { toolGlob } from './tools/glob.js';\nimport { readFinishFiles } from './tools/finish.js';\nimport type { RetryConfig } from '../../utils/resilience.js';\nimport { formatTurnMessage, calculateContextBudget, buildInitialState, enforceContextLimit } from './helpers.js';\nimport OpenAI from 'openai';\nimport { SDK_VERSION } from '../../../version.js';\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 DEFAULT_API_URL = 'https://api.morphllm.com';\n\n// Tool definitions sent to the model (OpenAI function calling format)\nconst TOOL_SPECS: OpenAI.Chat.ChatCompletionTool[] = [\n {\n type: 'function',\n function: {\n name: 'list_directory',\n description: 'Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.',\n parameters: {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: \"Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */).\",\n },\n },\n required: ['command'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'grep_search',\n description: 'Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.',\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: \"Regex pattern to search for in file contents (e.g. 'class\\\\s+\\\\w+Error', 'import|require|from', 'def (get|set|update)_user').\",\n },\n path: {\n type: 'string',\n description: 'File or directory to search in. Defaults to current working directory.',\n },\n glob: {\n type: 'string',\n description: \"Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*').\",\n },\n limit: {\n type: 'integer',\n description: 'Limit output to first N matching lines. Shows all matches if not specified.',\n },\n },\n required: ['pattern'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'glob',\n description: 'Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.',\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: \"Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py').\",\n },\n path: {\n type: 'string',\n description: 'Directory to search in. Defaults to repository root.',\n },\n },\n required: ['pattern'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'read',\n description: 'Read entire files or specific line ranges using absolute paths.',\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: \"File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path).\",\n },\n lines: {\n type: 'string',\n description: \"Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file.\",\n },\n },\n required: ['path'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'finish',\n description: 'Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.',\n parameters: {\n type: 'object',\n properties: {\n files: {\n type: 'string',\n description: \"One file per line as path:lines (e.g. 'src/auth.py:1-15,25-50\\\\nsrc/user.py'). Omit line range to include entire file.\",\n },\n },\n required: ['files'],\n },\n },\n },\n];\n\ninterface CallModelOptions {\n morphApiKey?: string;\n morphApiUrl?: string;\n retryConfig?: RetryConfig;\n timeout?: number;\n search_type?: string;\n}\n\ntype ModelResponse = {\n content: string | null;\n tool_calls: ToolCallRef[];\n};\n\nasync function callModel(\n messages: ChatMessage[],\n model: string,\n options: CallModelOptions = {}\n): Promise<ModelResponse> {\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 parsedUrl = new URL(baseUrl);\n const baseURL = parsedUrl.pathname === '/' ? `${baseUrl}/v1` : baseUrl;\n\n const client = new OpenAI({\n apiKey,\n baseURL,\n maxRetries: options.retryConfig?.maxRetries,\n timeout: timeoutMs,\n defaultHeaders: { 'X-Morph-SDK-Version': SDK_VERSION },\n });\n\n const MAX_EMPTY_RETRIES = 1;\n\n for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {\n let data;\n try {\n data = await client.chat.completions.create({\n model,\n temperature: 0.0,\n max_tokens: 2048,\n messages: messages as OpenAI.Chat.ChatCompletionMessageParam[],\n tools: TOOL_SPECS,\n ...(options.search_type ? { search_type: options.search_type } as Record<string, unknown> : {}),\n });\n } catch (error) {\n if (error instanceof OpenAI.APIError && error.status === 404) {\n const defaultMsg =\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 const errorText = error.message?.trim();\n throw new Error(errorText || defaultMsg);\n }\n throw error;\n }\n\n const choice = data?.choices?.[0];\n const message = choice?.message;\n\n if (!message) {\n if (attempt === MAX_EMPTY_RETRIES) {\n throw new Error('Invalid response from model: no message in response');\n }\n await new Promise(resolve => setTimeout(resolve, 200));\n continue;\n }\n\n const toolCalls: ToolCallRef[] = (message.tool_calls || []).map(tc => ({\n id: tc.id,\n type: 'function' as const,\n function: { name: tc.function.name, arguments: tc.function.arguments },\n }));\n\n if (message.content || toolCalls.length > 0) {\n return { content: message.content ?? null, tool_calls: toolCalls };\n }\n\n if (attempt === MAX_EMPTY_RETRIES) {\n const finishReason = choice?.finish_reason ?? 'unknown';\n throw new Error(\n `Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`\n );\n }\n await new Promise(resolve => setTimeout(resolve, 200));\n }\n\n throw new Error('Invalid response from model');\n}\n\n/** Safely parse JSON, returning empty object on failure */\nfunction safeParseJSON(s: string): Record<string, unknown> {\n try {\n return JSON.parse(s);\n } catch {\n return {};\n }\n}\n\n/**\n * Execute a single tool call against the provider, returning the output string.\n */\nasync function executeTool(\n provider: WarpGrepProvider,\n name: string,\n args: Record<string, unknown>,\n repoRoot?: string,\n): Promise<string> {\n switch (name) {\n case 'grep_search': {\n const grepArgs: { pattern: string; path: string; glob?: string; case_sensitive?: boolean } = {\n pattern: args.pattern as string,\n path: (args.path as string) || '.',\n };\n if (args.glob) grepArgs.glob = args.glob as string;\n if (args.case_sensitive !== undefined) grepArgs.case_sensitive = args.case_sensitive as boolean;\n const result = await toolGrep(provider, grepArgs);\n let output = result.output;\n if (args.limit && typeof args.limit === 'number') {\n const lines = output.split('\\n');\n if (lines.length > args.limit) {\n output = lines.slice(0, args.limit).join('\\n') + `\\n... (truncated at ${args.limit} lines)`;\n }\n }\n return output;\n }\n case 'glob': {\n return toolGlob(provider, {\n pattern: args.pattern as string,\n path: args.path as string | undefined,\n });\n }\n case 'list_directory': {\n const dirPath = extractPathFromCommand((args.command as string) || '.');\n return toolListDirectory(provider, { path: dirPath }, repoRoot);\n }\n case 'read': {\n const readArgs: { path: string; start?: number; end?: number; lines?: Array<[number, number]> } = {\n path: args.path as string,\n };\n if (args.lines && typeof args.lines === 'string') {\n Object.assign(readArgs, parseReadLines(args.lines));\n }\n return toolRead(provider, readArgs);\n }\n default:\n return `Unknown tool: ${name}`;\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 = config.repoRoot || process.cwd();\n const model = config.model || DEFAULT_MODEL;\n const messages: ChatMessage[] = [];\n\n const maxTurns = AGENT_CONFIG.MAX_TURNS;\n\n const initialStateStart = Date.now();\n const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });\n timings.initial_state_ms = Date.now() - initialStateStart;\n\n messages.push({ role: 'user', content: initialState });\n\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 enforceContextLimit(messages);\n\n // Call model\n const modelCallStart = Date.now();\n const response = await callModel(messages, model, {\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: timeoutMs,\n search_type: config.search_type,\n }).catch((e: unknown) => {\n const errMsg = e instanceof Error ? e.message : String(e);\n console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);\n errors.push({ message: errMsg });\n return null;\n });\n turnMetrics.morph_api_ms = Date.now() - modelCallStart;\n\n if (!response) {\n timings.turns!.push(turnMetrics);\n break;\n }\n\n const toolCalls = response.tool_calls;\n\n // Add assistant message to history\n messages.push({\n role: 'assistant',\n content: response.content,\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n });\n\n if (toolCalls.length === 0) {\n console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || '').slice(0, 500)}`);\n errors.push({ message: 'No tool calls produced by the model.' });\n terminationReason = 'terminated';\n timings.turns!.push(turnMetrics);\n break;\n }\n\n // Yield step for streaming consumers\n yield {\n turn,\n toolCalls: toolCalls.map(tc => ({\n name: tc.function.name,\n arguments: safeParseJSON(tc.function.arguments),\n })),\n };\n\n // Check for finish call\n const finishCall = toolCalls.find(tc => tc.function.name === 'finish');\n if (finishCall) {\n const args = safeParseJSON(finishCall.function.arguments) as { files?: string };\n const filesStr = args.files || '';\n const files = parseFinishFiles(filesStr);\n finishMeta = { files };\n terminationReason = 'completed';\n\n if (files.length === 0) {\n const payload = filesStr || 'No relevant code found.';\n timings.turns!.push(turnMetrics);\n timings.total_ms = Date.now() - totalStart;\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: finishMeta },\n timings: timings as WarpGrepExecutionMetrics,\n };\n }\n\n timings.turns!.push(turnMetrics);\n break;\n }\n\n // Execute non-finish tool calls in parallel\n const toolExecStart = Date.now();\n const results = await Promise.all(\n toolCalls.map(async (tc) => {\n const args = safeParseJSON(tc.function.arguments);\n const output = await executeTool(provider, tc.function.name, args, repoRoot).catch(err => String(err));\n return { tool_call_id: tc.id, content: output };\n })\n );\n turnMetrics.local_tools_ms = Date.now() - toolExecStart;\n\n // Add tool result messages\n for (const result of results) {\n messages.push({ role: 'tool', tool_call_id: result.tool_call_id, content: result.content });\n }\n\n // Add turn counter hint\n const turnMsg = formatTurnMessage(turn, maxTurns);\n const budget = calculateContextBudget(messages);\n messages.push({ role: 'user', content: turnMsg + '\\n' + budget });\n\n timings.turns!.push(turnMetrics);\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 // If the model returned a path that doesn't start with repoRoot,\n // try resolving it against repoRoot (handles truncated absolute paths)\n let resolvedPath = p;\n if (!p.startsWith(repoRoot)) {\n // Strip leading slash for path.join, then try the resolved path\n const relative = p.startsWith('/') ? p.slice(1) : p;\n resolvedPath = path.join(repoRoot, relative);\n }\n try {\n const rr = await provider.read({ path: resolvedPath, 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: resolvedPath, error: errorMsg });\n console.error(`[warp_grep] Failed to read file: ${resolvedPath} - ${errorMsg}`);\n return [`[couldn't find: ${resolvedPath}]`];\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\n/**\n * Non-streaming version. Runs the agent loop and returns the final result.\n */\nexport async function runWarpGrep(config: SessionConfig & { provider: WarpGrepProvider }): Promise<AgentRunResult> {\n const gen = runWarpGrepStreaming(config);\n // Drain all yielded steps, return the final result\n let result = await gen.next();\n while (!result.done) {\n result = await gen.next();\n }\n return result.value;\n}\n","// Helpers for parsing string-format tool arguments from OpenAI tool calls\n\nimport type { FinishFileSpec } from './types.js';\n\n/** Parse \"lines\" string from read tool (e.g. \"1-50\" or \"1-20,45-80\") into structured args */\nexport function parseReadLines(linesStr: string): { start?: number; end?: number; lines?: Array<[number, number]> } {\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of linesStr.split(',')) {\n const trimmed = rangeStr.trim();\n if (!trimmed) continue;\n const parts = trimmed.split('-').map(v => parseInt(v.trim(), 10));\n if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {\n ranges.push([parts[0], parts[1]]);\n } else if (Number.isFinite(parts[0])) {\n ranges.push([parts[0], parts[0]]);\n }\n }\n if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };\n if (ranges.length > 1) return { lines: ranges };\n return {};\n}\n\n/** Parse \"files\" string from finish tool (e.g. \"src/auth.py:1-50\\nsrc/user.py\" or space-separated) into FinishFileSpec[] */\nexport function parseFinishFiles(filesStr: string): FinishFileSpec[] {\n const files: FinishFileSpec[] = [];\n // Split on whitespace (training uses space-separated, SDK also supports newlines)\n for (const line of filesStr.trim().split(/\\s+/)) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n const colonIdx = trimmed.indexOf(':');\n if (colonIdx === -1) {\n files.push({ path: trimmed, lines: '*' });\n continue;\n }\n const filePath = trimmed.slice(0, colonIdx);\n const rangesPart = trimmed.slice(colonIdx + 1);\n if (!rangesPart.trim() || rangesPart.trim() === '*') {\n files.push({ path: filePath, lines: '*' });\n continue;\n }\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of rangesPart.split(',')) {\n const rt = rangeStr.trim();\n if (!rt) continue;\n const parts = rt.split('-').map(v => parseInt(v.trim(), 10));\n if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {\n ranges.push([parts[0], parts[1]]);\n } else if (Number.isFinite(parts[0])) {\n ranges.push([parts[0], parts[0]]);\n }\n }\n files.push({ path: filePath, lines: ranges.length > 0 ? ranges : '*' });\n }\n return files;\n}\n\n/** Extract directory path from a list_directory command string (e.g. \"ls -la src/\" → \"src/\") */\nexport function extractPathFromCommand(command: string): string {\n const tokens = command.trim().split(/\\s+/);\n const pathTokens = tokens.slice(1).filter(t => !t.startsWith('-') && !t.startsWith('|') && !t.startsWith('\\\\('));\n return pathTokens[0] || '.';\n}\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nexport async function toolGrep(\n provider: WarpGrepProvider,\n args: { pattern: string; path: string; glob?: string; context_lines?: number; case_sensitive?: boolean }\n): Promise<{ output: string }> {\n const res = await provider.grep(args);\n \n // Return errors as output - let the model see and handle them\n if (res.error) {\n return { output: res.error };\n }\n \n if (!res.lines.length) {\n return { output: 'no matches' };\n }\n \n return { output: res.lines.join('\\n') };\n}\n\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nfunction isValidRange(start: unknown, end: unknown): boolean {\n return (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Number.isFinite(start) &&\n Number.isFinite(end) &&\n start > 0 &&\n end >= start\n );\n}\n\nexport async function toolRead(\n provider: WarpGrepProvider,\n args: { path: string; start?: number; end?: number; lines?: Array<[number, number]> }\n): Promise<string> {\n if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {\n const validRanges: Array<[number, number]> = [];\n for (const range of args.lines) {\n if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {\n validRanges.push([range[0], range[1]]);\n }\n }\n \n if (validRanges.length === 0) {\n const res = await provider.read({ path: args.path });\n if (res.error) return res.error;\n if (!res.lines.length) return '(empty file)';\n return res.lines.join('\\n');\n }\n \n const chunks: string[] = [];\n for (const [start, end] of validRanges) {\n const res = await provider.read({ path: args.path, start, end });\n if (res.error) return res.error;\n chunks.push(res.lines.join('\\n'));\n }\n if (chunks.every(c => c === '')) return '(empty file)';\n return chunks.join('\\n...\\n');\n }\n\n const res = await provider.read({ path: args.path, start: args.start, end: args.end });\n if (res.error) {\n return res.error;\n }\n if (!res.lines.length) return '(empty file)';\n return res.lines.join('\\n');\n}\n\n","import type { WarpGrepProvider } from '../../providers/types.js';\nimport { AGENT_CONFIG } from '../config.js';\nimport path from 'path';\n\nexport async function toolListDirectory(\n provider: WarpGrepProvider,\n args: { path: string; pattern?: string | null; maxResults?: number; maxDepth?: number },\n repoRoot?: string,\n): Promise<string> {\n\n const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;\n const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n\n const entries = await provider.listDirectory({\n path: args.path,\n pattern: args.pattern ?? null,\n maxResults,\n maxDepth,\n });\n\n if (!entries.length) return 'empty';\n\n // Flat absolute paths (matches training format)\n // If repoRoot is available, convert relative paths to absolute\n if (repoRoot) {\n const absRoot = repoRoot;\n const lines = entries.map(e => path.join(absRoot, e.path));\n return lines.join('\\n');\n }\n\n // Fallback: return relative paths if repoRoot not available\n return entries.map(e => e.path).join('\\n');\n}\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nexport async function toolGlob(\n provider: WarpGrepProvider,\n args: { pattern: string; path?: string }\n): Promise<string> {\n const res = await provider.glob(args);\n\n if (res.error) {\n return res.error;\n }\n\n if (!res.files.length) {\n return 'no matches';\n }\n\n // Match training output format exactly\n const header = `Found ${res.totalFound} file(s) matching \"${args.pattern}\" within ${res.searchDir}, sorted by modification time (newest first):`;\n const body = res.files.join('\\n');\n const truncated = res.totalFound > res.files.length\n ? `\\n[${res.totalFound - res.files.length} files truncated]`\n : '';\n return `${header}\\n---\\n${body}\\n---${truncated}`;\n}\n","import type { FinishFileSpec } from '../types.js';\n\nfunction isValidRange(range: unknown): range is [number, number] {\n return (\n Array.isArray(range) &&\n range.length >= 2 &&\n typeof range[0] === 'number' &&\n typeof range[1] === 'number' &&\n Number.isFinite(range[0]) &&\n Number.isFinite(range[1]) &&\n range[0] > 0 &&\n range[1] >= range[0]\n );\n}\n\nfunction extractValidRanges(lines: unknown): Array<[number, number]> | null {\n if (!Array.isArray(lines)) return null;\n const valid: Array<[number, number]> = [];\n for (const range of lines) {\n if (isValidRange(range)) {\n valid.push([range[0], range[1]]);\n }\n }\n return valid.length > 0 ? valid : null;\n}\n\nexport function normalizeFinishFiles(files: FinishFileSpec[]): FinishFileSpec[] {\n return files.map((f) => {\n if (f.lines === '*') return { path: f.path, lines: '*' };\n const validRanges = extractValidRanges(f.lines);\n if (!validRanges) return { path: f.path, lines: '*' };\n return { path: f.path, lines: mergeRanges(validRanges) };\n });\n}\n\nexport async function readFinishFiles(\n repoRoot: string,\n files: FinishFileSpec[],\n reader: (path: string, start?: number, end?: number) => Promise<string[]>\n): Promise<{ path: string; ranges: '*' | Array<[number, number]>; content: string }[]> {\n const out: { path: string; ranges: '*' | Array<[number, number]>; content: string }[] = [];\n for (const f of files) {\n const validRanges = f.lines === '*' ? null : extractValidRanges(f.lines);\n if (f.lines === '*' || !validRanges) {\n const lines = await reader(f.path);\n out.push({ path: f.path, ranges: '*', content: lines.join('\\n') });\n } else {\n const ranges = mergeRanges(validRanges);\n const chunks: string[] = [];\n for (let i = 0; i < ranges.length; i++) {\n const [s, e] = ranges[i];\n if (i === 0 && s > 1) {\n chunks.push(`// ... existing code, block starting at line ${s} ...`);\n } else if (i > 0) {\n chunks.push(`// ... existing code, block starting at line ${s} ...`);\n }\n const lines = await reader(f.path, s, e);\n chunks.push(lines.join('\\n'));\n }\n out.push({ path: f.path, ranges, content: chunks.join('\\n') });\n }\n }\n return out;\n}\n\nfunction mergeRanges(ranges: Array<[number, number]>): Array<[number, number]> {\n if (!ranges.length) return [];\n const sorted = [...ranges].sort((a, b) => a[0] - b[0]);\n const merged: Array<[number, number]> = [];\n let [cs, ce] = sorted[0];\n for (let i = 1; i < sorted.length; i++) {\n const [s, e] = sorted[i];\n if (s <= ce + 1) {\n ce = Math.max(ce, e);\n } else {\n merged.push([cs, ce]);\n cs = s;\n ce = e;\n }\n }\n merged.push([cs, ce]);\n return merged;\n}\n\n","/**\n * Shared helper functions for warp-grep agent loop.\n * Used by both the internal runner and exported for harness users.\n */\n\nimport path from 'path';\nimport { AGENT_CONFIG } from './config.js';\nimport type { ChatMessage } from './types.js';\nimport type { WarpGrepProvider, ListDirectoryEntry } from '../providers/types.js';\n\nconst TRUNCATED_MARKER = '[truncated for context limit]';\n\n/**\n * Get the character size of a ChatMessage (handles all message types).\n */\nfunction getMessageSize(m: ChatMessage): number {\n if (m.role === 'tool') return m.content.length;\n if (m.role === 'assistant') {\n let size = typeof m.content === 'string' ? m.content.length : 0;\n if (m.tool_calls) {\n size += m.tool_calls.reduce((s, tc) => s + tc.function.name.length + tc.function.arguments.length, 0);\n }\n return size;\n }\n // system or user\n return (m as { content: string }).content.length;\n}\n\n/**\n * Format the turn counter message shown to the model.\n */\nexport function formatTurnMessage(turnsUsed: number, maxTurns: number): string {\n const turnsRemaining = maxTurns - turnsUsed;\n if (turnsRemaining === 1) {\n return `\\nYou have used ${turnsUsed} turns, you only have 1 turn remaining. You have run out of turns to explore the code base and MUST call the finish tool now`;\n }\n return `\\nYou have used ${turnsUsed} turn${turnsUsed === 1 ? '' : 's'} and have ${turnsRemaining} remaining`;\n}\n\n/**\n * Calculate and format the context budget indicator.\n */\nexport function calculateContextBudget(messages: ChatMessage[]): string {\n const totalChars = messages.reduce((sum, m) => sum + getMessageSize(m), 0);\n const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;\n const percent = Math.floor((totalChars / maxChars) * 100);\n const usedK = Math.floor(totalChars / 1000);\n const maxK = Math.floor(maxChars / 1000);\n return `<context_budget>${percent}% (${usedK}K/${maxK}K chars)</context_budget>`;\n}\n\n/**\n * Build the initial state message containing repo structure and search term.\n */\nexport async function buildInitialState(\n repoRoot: string,\n searchTerm: string,\n provider: WarpGrepProvider,\n options?: { search_type?: string },\n): Promise<string> {\n const budget = calculateContextBudget([]);\n const turnTag = `You have used 0 turns and have ${AGENT_CONFIG.MAX_TURNS} remaining`;\n const treeDepth = options?.search_type === 'node_modules' ? 1 : 2;\n\n const absRoot = repoRoot;\n\n try {\n const entries = await provider.listDirectory({\n path: '.',\n maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,\n maxDepth: treeDepth,\n });\n\n // Flat list of absolute paths (matches training format)\n // First line is the repo root, then one absolute path per entry\n const lines = [absRoot];\n for (const e of entries) {\n lines.push(path.join(absRoot, e.path));\n }\n\n return `<repo_structure>\\n${lines.join('\\n')}\\n</repo_structure>\\n\\n<search_string>\\n${searchTerm}\\n</search_string>\\n${budget}\\n${turnTag}`;\n } catch {\n return `<repo_structure>\\n${absRoot}\\n</repo_structure>\\n\\n<search_string>\\n${searchTerm}\\n</search_string>\\n${budget}\\n${turnTag}`;\n }\n}\n\n/**\n * Format directory entries as an indented tree string.\n */\nexport function formatListDirectoryTree(entries: ListDirectoryEntry[]): string {\n if (!entries.length) return 'empty';\n return entries\n .map((e) => {\n const indent = ' '.repeat(e.depth);\n const name = e.type === 'dir' ? `${e.name}/` : e.name;\n return `${indent}${name}`;\n })\n .join('\\n');\n}\n\n/**\n * Enforce hard context limit by truncating tool result messages.\n * Preserves the first user message (initial query) and all assistant messages.\n * Truncates tool/user messages from oldest to newest until under the threshold.\n *\n * @param messages - The conversation messages array (mutated in place)\n * @param maxChars - Maximum total character count (defaults to AGENT_CONFIG.MAX_CONTEXT_CHARS)\n * @returns The same messages array, truncated if necessary\n */\nexport function enforceContextLimit(\n messages: ChatMessage[],\n maxChars: number = AGENT_CONFIG.MAX_CONTEXT_CHARS\n): ChatMessage[] {\n const getTotalChars = () => messages.reduce((sum, m) => sum + getMessageSize(m), 0);\n\n if (getTotalChars() <= maxChars) {\n return messages;\n }\n\n // Find indices of truncatable messages (tool results and non-first user messages)\n const truncatableIndices: number[] = [];\n let firstUserSkipped = false;\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n if (m.role === 'tool') {\n truncatableIndices.push(i);\n } else if (m.role === 'user') {\n if (!firstUserSkipped) {\n firstUserSkipped = true;\n continue; // Skip first user message (contains the search query)\n }\n truncatableIndices.push(i);\n }\n }\n\n // Truncate from oldest to newest until under limit\n for (const idx of truncatableIndices) {\n if (getTotalChars() <= maxChars) {\n break;\n }\n const m = messages[idx];\n if (m.role === 'tool' && m.content !== TRUNCATED_MARKER) {\n messages[idx] = { role: 'tool', tool_call_id: m.tool_call_id, content: TRUNCATED_MARKER };\n } else if (m.role === 'user' && (m as { content: string }).content !== TRUNCATED_MARKER) {\n messages[idx] = { role: 'user', content: TRUNCATED_MARKER };\n }\n }\n\n return messages;\n}\n","/**\n * RemoteCommandsProvider - wraps simple RemoteCommands into WarpGrepProvider\n * \n * Handles parsing of raw stdout from grep/read/listDir commands.\n * Users just return stdout, SDK handles all format conversion.\n */\n\nimport type { WarpGrepProvider, GrepResult, ReadResult, GlobResult, ListDirectoryEntry } from './types.js';\nimport type { RemoteCommands } from '../types.js';\nimport { AGENT_CONFIG } from '../agent/config.js';\n\n/**\n * Directories/files to always skip (exact name match)\n */\nconst SKIP_NAMES = new Set([\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'Pods', '.bundle',\n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs',\n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n // Cache\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n // IDE\n '.idea', '.vscode', '.vs',\n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n // Temp\n 'tmp', 'temp', '.tmp', '.temp',\n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n]);\n\n/**\n * File extensions to skip\n */\nconst SKIP_EXTENSIONS = new Set([\n '.min.js', '.min.css', '.bundle.js',\n '.wasm', '.so', '.dll', '.pyc',\n '.map', '.js.map',\n]);\n\n/**\n * Check if a filename should be skipped\n */\nfunction shouldSkip(name: string): boolean {\n // Skip exact name matches\n if (SKIP_NAMES.has(name)) return true;\n \n // Skip hidden files/directories (start with .)\n if (name.startsWith('.')) return true;\n \n // Skip files with certain extensions\n for (const ext of SKIP_EXTENSIONS) {\n if (name.endsWith(ext)) return true;\n }\n \n return false;\n}\n\n/**\n * Wraps simple RemoteCommands functions into a full WarpGrepProvider.\n * \n * This allows users to provide three simple functions that return raw stdout,\n * and the SDK handles all parsing internally.\n * \n * @example\n * ```typescript\n * const provider = new RemoteCommandsProvider('/home/repo', {\n * grep: async (pattern, path) => {\n * const r = await sandbox.run(`rg '${pattern}' '${path}'`);\n * return r.stdout;\n * },\n * read: async (path, start, end) => {\n * const r = await sandbox.run(`sed -n '${start},${end}p' '${path}'`);\n * return r.stdout;\n * },\n * listDir: async (path, maxDepth) => {\n * const r = await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`);\n * return r.stdout;\n * },\n * });\n * ```\n */\nexport class RemoteCommandsProvider implements WarpGrepProvider {\n constructor(\n private readonly repoRoot: string,\n private readonly commands: RemoteCommands\n ) {}\n\n /**\n * Run grep command and parse ripgrep output\n */\n async grep(params: { pattern: string; path: string; glob?: string }): Promise<GrepResult> {\n try {\n const stdout = await this.commands.grep(params.pattern, params.path, params.glob);\n \n // Parse ripgrep output: each line is \"path:line:content\" or \"path-line-content\" for context\n const lines = (stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((l) => l.length > 0);\n \n // Truncate if too many lines (return partial results like training harness)\n if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {\n const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines };\n } catch (error) {\n return {\n lines: [],\n error: `[GREP ERROR] ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Read file and add line numbers\n */\n async read(params: { path: string; start?: number; end?: number }): Promise<ReadResult> {\n const rawStart = params.start;\n const rawEnd = params.end;\n \n const startValid = rawStart === undefined || (Number.isFinite(rawStart) && rawStart > 0);\n const endValid = rawEnd === undefined || (Number.isFinite(rawEnd) && rawEnd > 0);\n const rangeValid = startValid && endValid && \n (rawStart === undefined || rawEnd === undefined || rawStart <= rawEnd);\n \n const start = rangeValid && rawStart !== undefined ? rawStart : 1;\n const end = rangeValid && rawEnd !== undefined ? rawEnd : 1_000_000;\n \n try {\n const stdout = await this.commands.read(params.path, start, end);\n \n // Split content into lines and add line numbers\n const contentLines = (stdout || '').split('\\n');\n \n // Remove trailing empty line if present (common with sed output)\n if (contentLines.length > 0 && contentLines[contentLines.length - 1] === '') {\n contentLines.pop();\n }\n \n // Format as \"lineNumber|content\"\n const lines = contentLines.map((content, idx) => `${start + idx}|${content}`);\n \n // Check if output is too large\n if (lines.length > AGENT_CONFIG.MAX_READ_LINES) {\n const truncated = lines.slice(0, AGENT_CONFIG.MAX_READ_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${lines.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines };\n } catch (error) {\n return {\n lines: [],\n error: `[READ ERROR] ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * List directory and parse find output\n */\n async listDirectory(params: { \n path: string; \n pattern?: string | null; \n maxResults?: number; \n maxDepth?: number;\n }): Promise<ListDirectoryEntry[]> {\n const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;\n \n try {\n const stdout = await this.commands.listDir(params.path, maxDepth);\n \n // Parse find output: one path per line\n const paths = (stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((p) => p.length > 0);\n \n const regex = params.pattern ? new RegExp(params.pattern) : null;\n const entries: ListDirectoryEntry[] = [];\n \n for (const fullPath of paths) {\n // Skip the root path itself\n if (fullPath === params.path || fullPath === this.repoRoot) continue;\n \n const name = fullPath.split('/').pop() || '';\n \n // Simple name-based filtering - skip junk dirs/files\n if (shouldSkip(name)) continue;\n \n // Apply pattern filter if provided\n if (regex && !regex.test(name)) continue;\n \n // Determine relative path\n let relativePath = fullPath;\n if (fullPath.startsWith(this.repoRoot)) {\n relativePath = fullPath.slice(this.repoRoot.length).replace(/^\\//, '');\n }\n \n // Calculate depth based on path separators\n const depth = relativePath.split('/').filter(Boolean).length - 1;\n \n // Determine if it's a directory (ends with / or infer from path structure)\n // Note: Most sandbox find commands don't indicate type, so we guess based on extension\n const hasExtension = name.includes('.') && !name.startsWith('.');\n const type: 'file' | 'dir' = hasExtension ? 'file' : 'dir';\n \n entries.push({\n name,\n path: relativePath,\n type,\n depth: Math.max(0, depth),\n });\n \n if (entries.length >= maxResults) break;\n }\n \n return entries;\n } catch (error) {\n // Return empty array on error (consistent with LocalRipgrepProvider)\n return [];\n }\n }\n\n /**\n * Glob search - finds files matching a pattern.\n * Falls back to a grep --files approach via the listDir command.\n */\n async glob(params: { pattern: string; path?: string }): Promise<GlobResult> {\n const searchPath = params.path || this.repoRoot;\n try {\n // Use find with -name to simulate glob\n const stdout = await this.commands.listDir(searchPath, 10);\n const allPaths = (stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((p) => p.length > 0);\n\n // Simple glob matching: convert glob pattern to regex\n const globToRegex = (glob: string) => {\n const escaped = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.');\n return new RegExp(escaped);\n };\n const regex = globToRegex(params.pattern);\n\n const matched = allPaths\n .filter(p => {\n const name = p.split('/').pop() || '';\n return regex.test(name) && !shouldSkip(name);\n });\n\n const totalFound = matched.length;\n return { files: matched.slice(0, 100), searchDir: searchPath, totalFound };\n } catch (error) {\n return {\n files: [],\n searchDir: searchPath,\n totalFound: 0,\n error: `[GLOB ERROR] ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n}\n","/**\n * HTTP-based RemoteCommands for code search against the Morph landing API.\n *\n * Translates grep/read/listDir into POST requests to the code-search endpoints,\n * so the WarpGrep agent can search GitHub repositories that have been indexed\n * by the Morph code storage service.\n */\n\nimport type { RemoteCommands } from '../types.js';\n\nexport interface CodeStorageHttpConfig {\n /** Base URL for the code search API (e.g. \"https://morphllm.com\") */\n baseUrl: string;\n /** Repository ID returned by the get-or-create endpoint */\n repoId: string;\n /** Git branch to search */\n branch: string;\n}\n\nasync function post(url: string, body: Record<string, unknown>, op: string): Promise<string> {\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => res.statusText);\n // Return error as content instead of throwing so the agent can handle it gracefully\n try {\n const parsed = JSON.parse(text);\n if (parsed.error) return `Error: ${parsed.error}`;\n } catch { /* not JSON, fall through */ }\n return `Error: ${op} failed (${res.status}): ${text}`;\n }\n const data = await res.json();\n if (data.error) throw new Error(data.error);\n return data.stdout;\n}\n\nexport function createCodeStorageHttpCommands(config: CodeStorageHttpConfig): RemoteCommands {\n const { baseUrl, repoId, branch } = config;\n const encodedRepoId = encodeURIComponent(repoId);\n\n return {\n grep: (pattern: string, path: string, glob?: string) =>\n post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path, glob, branch }, 'grep'),\n\n read: (path: string, start: number, end: number) =>\n post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path, start, end, branch }, 'read'),\n\n listDir: (path: string, maxDepth: number) =>\n post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path, maxDepth, branch }, 'list'),\n };\n}\n","/**\n * GitHub URL parsing utilities\n */\n\n/**\n * Parse GitHub URL or \"owner/repo\" shorthand into owner and repo components.\n * Handles: \"owner/repo\", \"https://github.com/owner/repo\", \"github.com/owner/repo.git\"\n */\nexport function parseGitHubUrl(input: string): { owner: string; repo: string } {\n input = input.trim();\n\n // Try URL patterns first\n const urlPattern = /^(?:https?:\\/\\/)?github\\.com\\/([^\\/]+)\\/([^\\/\\?\\#]+)/;\n const match = input.match(urlPattern);\n if (match) {\n return { owner: match[1], repo: match[2].replace(/\\.git$/, '') };\n }\n\n // Try \"owner/repo\" shorthand (reject if owner contains '.', e.g. \"github.com/owner\")\n const shortPattern = /^([^\\/]+)\\/([^\\/]+)$/;\n const shortMatch = input.match(shortPattern);\n if (shortMatch && !shortMatch[1].includes('.')) {\n return { owner: shortMatch[1], repo: shortMatch[2].replace(/\\.git$/, '') };\n }\n\n throw new Error(\n `Invalid GitHub URL or shorthand: \"${input}\". Expected \"owner/repo\" or \"https://github.com/owner/repo\"`\n );\n}\n","/**\n * WarpGrep client for programmatic code search\n */\n\nimport { runWarpGrep, runWarpGrepStreaming } from './agent/runner.js';\nimport { RemoteCommandsProvider } from './providers/remote.js';\nimport type { WarpGrepProvider } from './providers/types.js';\nimport type { AgentRunResult, WarpGrepStep } from './agent/types.js';\nimport type {\n WarpGrepClientConfig,\n WarpGrepInput,\n WarpGrepResult,\n WarpGrepContext,\n WarpGrepToolConfig,\n GitHubSearchInput,\n GitHubReadFileInput,\n GitHubReadFileResult,\n RemoteCommands,\n} from './types.js';\nimport { createCodeStorageHttpCommands } from './providers/code_storage_http.js';\nimport { parseGitHubUrl } from './utils/github.js';\n\nconst DEFAULT_CODE_SEARCH_URL = 'https://morphllm.com';\n\n/**\n * Lazy-load LocalRipgrepProvider to avoid importing Node.js-specific\n * modules (child_process, fs) in edge environments like Cloudflare Workers.\n * Only loads when actually needed (i.e., when no remoteCommands or provider is specified).\n */\nasync function getLocalProvider(repoRoot: string, excludes?: string[], allowNames?: string[]): Promise<WarpGrepProvider> {\n const { LocalRipgrepProvider } = await import('./providers/local.js');\n const opts = allowNames?.length ? { allowNames } : undefined;\n return new LocalRipgrepProvider(repoRoot, excludes, opts);\n}\n\n/**\n * WarpGrep client for programmatic code search\n * \n * @example\n * ```typescript\n * import { WarpGrepClient } from '@morphllm/morphsdk';\n * \n * const client = new WarpGrepClient({ morphApiKey: process.env.MORPH_API_KEY });\n * \n * // Simple usage - defaults to LocalRipgrepProvider\n * const result = await client.execute({\n * searchTerm: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n *\n * // With custom excludes\n * const result = await client.execute({\n * searchTerm: 'Find database models',\n * repoRoot: '.',\n * excludes: ['node_modules', '.git', 'dist']\n * });\n * ```\n */\nexport class WarpGrepClient {\n private config: WarpGrepClientConfig;\n\n constructor(config: WarpGrepClientConfig = {}) {\n this.config = { ...config };\n }\n\n /**\n * Execute a code search\n *\n * @param input - Search parameters including searchTerm, repoRoot, and optional provider\n * @returns Search results with relevant code contexts, or an AsyncGenerator if streamSteps is true\n *\n * @example\n * ```typescript\n * // Standard execution\n * const result = await client.execute({\n * searchTerm: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n *\n * if (result.success) {\n * for (const ctx of result.contexts) {\n * console.log(`File: ${ctx.file}`);\n * console.log(ctx.content);\n * }\n * }\n *\n * // Streaming execution\n * const stream = client.execute({\n * searchTerm: 'Find auth middleware',\n * repoRoot: '.',\n * streamSteps: true\n * });\n *\n * for await (const step of stream) {\n * console.log(`Turn ${step.turn}:`, step.toolCalls);\n * }\n * ```\n */\n execute(input: WarpGrepInput & { streamSteps: true }): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined>;\n execute(input: WarpGrepInput & { streamSteps?: false | undefined }): Promise<WarpGrepResult>;\n execute(input: WarpGrepInput): Promise<WarpGrepResult> | AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n const toolConfig: WarpGrepToolConfig = {\n repoRoot: input.repoRoot,\n remoteCommands: input.remoteCommands,\n provider: input.provider,\n excludes: input.excludes,\n includes: input.includes,\n debug: input.debug ?? this.config.debug,\n morphApiKey: this.config.morphApiKey,\n morphApiUrl: this.config.morphApiUrl,\n retryConfig: this.config.retryConfig,\n timeout: this.config.timeout,\n search_type: input.search_type,\n };\n\n if (input.streamSteps) {\n return executeToolCallStreaming({ search_term: input.searchTerm }, toolConfig);\n }\n return executeToolCall({ search_term: input.searchTerm }, toolConfig);\n }\n\n /**\n * Search a public GitHub repository\n *\n * @example\n * ```typescript\n * // Simple usage\n * const result = await client.searchGitHub({\n * searchTerm: 'Find authentication middleware',\n * github: 'vercel/next.js',\n * });\n *\n * // With streaming\n * const stream = client.searchGitHub({\n * searchTerm: 'Find auth middleware',\n * github: 'https://github.com/vercel/next.js',\n * streamSteps: true,\n * });\n * for await (const step of stream) {\n * console.log(`Turn ${step.turn}:`, step.toolCalls);\n * }\n * ```\n */\n searchGitHub(input: GitHubSearchInput & { streamSteps: true }): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined>;\n searchGitHub(input: GitHubSearchInput & { streamSteps?: false | undefined }): Promise<WarpGrepResult>;\n searchGitHub(input: GitHubSearchInput): Promise<WarpGrepResult> | AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n if (input.streamSteps) {\n return this._searchGitHubStreaming(input);\n }\n return this._searchGitHubAsync(input);\n }\n\n /**\n * Read a single file from a public GitHub repository\n *\n * @example\n * ```typescript\n * const result = await client.readGitHubFile({\n * github: 'vercel/next.js',\n * path: 'src/server/app-render/index.tsx',\n * startLine: 1,\n * endLine: 50,\n * });\n * if (result.success) console.log(result.content);\n * ```\n */\n async readGitHubFile(input: GitHubReadFileInput): Promise<GitHubReadFileResult> {\n return executeGitHubReadFile(input, { timeout: this.config.timeout });\n }\n\n private async _resolveGitHubRepo(input: GitHubSearchInput): Promise<{ repo: string; remoteCommands: RemoteCommands }> {\n const { owner, repo } = parseGitHubUrl(input.github);\n const baseUrl = this.config.codeSearchUrl || DEFAULT_CODE_SEARCH_URL;\n const importRes = await fetch(`${baseUrl}/api/code-search/get-or-create?url=${encodeURIComponent(`${owner}/${repo}`)}`);\n if (!importRes.ok) {\n const text = await importRes.text().catch(() => importRes.statusText);\n throw new Error(`Failed to import repo ${owner}/${repo}: ${text}`);\n }\n const { repoId, defaultBranch } = await importRes.json();\n return {\n repo,\n remoteCommands: createCodeStorageHttpCommands({ baseUrl, repoId, branch: input.branch || defaultBranch }),\n };\n }\n\n private async _searchGitHubAsync(input: GitHubSearchInput): Promise<WarpGrepResult> {\n try {\n const { remoteCommands } = await this._resolveGitHubRepo(input);\n return this.execute({\n searchTerm: input.searchTerm,\n repoRoot: '.',\n remoteCommands,\n });\n } catch (error) {\n return { success: false, error: error instanceof Error ? error.message : String(error) };\n }\n }\n\n private async *_searchGitHubStreaming(input: GitHubSearchInput): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n let remoteCommands: RemoteCommands;\n try {\n ({ remoteCommands } = await this._resolveGitHubRepo(input));\n } catch (error) {\n return { success: false, error: error instanceof Error ? error.message : String(error) };\n }\n\n const generator = this.execute({\n searchTerm: input.searchTerm,\n repoRoot: '.',\n remoteCommands,\n streamSteps: true,\n });\n\n let result: WarpGrepResult;\n for (;;) {\n const { value, done } = await generator.next();\n if (done) {\n result = value;\n break;\n }\n yield value;\n }\n return result;\n }\n}\n\n/**\n * Execute a warp grep search directly\n *\n * @param input - Search parameters\n * @param config - Optional client configuration\n * @returns Search results, or an AsyncGenerator if streamSteps is true\n *\n * @example\n * ```typescript\n * import { executeWarpGrep } from '@morphllm/morphsdk/tools/warp-grep';\n *\n * const result = await executeWarpGrep({\n * searchTerm: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n *\n * // Streaming\n * const stream = executeWarpGrep({\n * searchTerm: 'Find auth',\n * repoRoot: '.',\n * streamSteps: true\n * });\n * for await (const step of stream) {\n * console.log(step.turn, step.toolCalls);\n * }\n * ```\n */\nexport function executeWarpGrep(\n input: WarpGrepInput & { streamSteps: true },\n config?: WarpGrepClientConfig\n): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined>;\nexport function executeWarpGrep(\n input: WarpGrepInput & { streamSteps?: false | undefined },\n config?: WarpGrepClientConfig\n): Promise<WarpGrepResult>;\nexport function executeWarpGrep(\n input: WarpGrepInput,\n config?: WarpGrepClientConfig\n): Promise<WarpGrepResult> | AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n const client = new WarpGrepClient(config);\n if (input.streamSteps) {\n return client.execute({ ...input, streamSteps: true });\n }\n return client.execute({ ...input, streamSteps: false });\n}\n\nexport async function executeToolCall(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n const parsed = typeof input === 'string' ? JSON.parse(input) : input;\n\n // Priority: remoteCommands > provider > LocalRipgrepProvider (lazy-loaded for edge compatibility)\n const allowNames = config.search_type === 'node_modules' ? ['node_modules'] : undefined;\n const provider = config.remoteCommands\n ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands)\n : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);\n\n const result = await runWarpGrep({\n searchTerm: parsed.search_term,\n repoRoot: config.repoRoot,\n provider,\n excludes: config.excludes,\n includes: config.includes,\n debug: config.debug ?? false,\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: config.timeout,\n search_type: config.search_type,\n });\n\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n const errorDetails = result.errors?.map(e => e.message).join('; ') || 'unknown reason';\n console.error(`[warp_grep] executeToolCall failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);\n return { success: false, error: `Search did not complete: ${errorDetails}` };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n lines: r.ranges,\n }));\n\n return { success: true, contexts, summary: finish.payload };\n}\n\n/**\n * Helper to process AgentRunResult into WarpGrepResult\n */\nfunction processAgentResult(result: AgentRunResult): WarpGrepResult {\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n const errorDetails = result.errors?.map(e => e.message).join('; ') || 'unknown reason';\n console.error(`[warp_grep] processAgentResult failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);\n return { success: false, error: `Search did not complete: ${errorDetails}` };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n lines: r.ranges,\n }));\n\n return { success: true, contexts, summary: finish.payload };\n}\n\n/**\n * Streaming version of executeToolCall that yields WarpGrepStep for each turn.\n */\nexport async function* executeToolCallStreaming(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n const parsed = typeof input === 'string' ? JSON.parse(input) : input;\n\n // Priority: remoteCommands > provider > LocalRipgrepProvider (lazy-loaded for edge compatibility)\n const allowNames = config.search_type === 'node_modules' ? ['node_modules'] : undefined;\n const provider = config.remoteCommands\n ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands)\n : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);\n\n const generator = runWarpGrepStreaming({\n searchTerm: parsed.search_term,\n repoRoot: config.repoRoot,\n provider,\n excludes: config.excludes,\n includes: config.includes,\n debug: config.debug ?? false,\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: config.timeout,\n search_type: config.search_type,\n });\n\n // Forward all yielded steps\n let agentResult: AgentRunResult;\n for (;;) {\n const { value, done } = await generator.next();\n if (done) {\n agentResult = value;\n break;\n }\n yield value;\n }\n\n return processAgentResult(agentResult);\n}\n\n/**\n * Fetch raw file content from a public GitHub repository.\n * Tries the given branch first, then falls back to main/master/develop.\n */\nasync function fetchRawGitHubFile(\n owner: string,\n repo: string,\n filePath: string,\n branch?: string,\n timeout?: number,\n): Promise<{ content: string; branch: string }> {\n const branches = branch ? [branch] : ['HEAD'];\n const fallbacks = ['main', 'master', 'develop'];\n\n const fetchWithTimeout = (url: string) =>\n timeout ? fetch(url, { signal: AbortSignal.timeout(timeout) }) : fetch(url);\n\n for (const b of branches) {\n const url = `https://raw.githubusercontent.com/${owner}/${repo}/${b}/${filePath}`;\n const res = await fetchWithTimeout(url);\n if (res.ok) return { content: await res.text(), branch: b };\n }\n\n for (const fb of fallbacks) {\n if (branch && fb === branch) continue;\n const url = `https://raw.githubusercontent.com/${owner}/${repo}/${fb}/${filePath}`;\n const res = await fetchWithTimeout(url);\n if (res.ok) return { content: await res.text(), branch: fb };\n }\n\n throw new Error(`File not found: ${owner}/${repo}/${filePath}`);\n}\n\n/**\n * Read a single file (or line range) from a public GitHub repository\n */\nexport async function executeGitHubReadFile(\n input: GitHubReadFileInput,\n config?: { timeout?: number },\n): Promise<GitHubReadFileResult> {\n try {\n const { owner, repo } = parseGitHubUrl(input.github);\n const { content: raw, branch } = await fetchRawGitHubFile(\n owner, repo, input.path, input.branch, config?.timeout,\n );\n\n const allLines = raw.split('\\n');\n const totalLines = allLines.length;\n const start = Math.max(1, input.startLine ?? 1);\n const end = Math.min(totalLines, input.endLine ?? totalLines);\n\n const selected = allLines.slice(start - 1, end);\n const padWidth = String(end).length;\n const numbered = selected\n .map((line, i) => `${String(start + i).padStart(padWidth)}|${line}`)\n .join('\\n');\n\n return {\n success: true,\n content: numbered,\n path: input.path,\n github: `${owner}/${repo}`,\n branch,\n lineRange: [start, end],\n totalLines,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Format a GitHub read file result for display or tool responses\n */\nexport function formatGitHubReadFileResult(result: GitHubReadFileResult): string {\n if (!result.success) {\n return `Failed to read file: ${result.error}`;\n }\n\n const rangeStr = result.lineRange\n ? ` (lines ${result.lineRange[0]}-${result.lineRange[1]} of ${result.totalLines})`\n : '';\n\n return `File: ${result.github}/${result.path}${rangeStr}\\n\\n${result.content}`;\n}\n\n/**\n * Format warp grep results for display or tool responses\n * \n * @param result - The search result\n * @returns Formatted string representation\n */\nexport function formatResult(result: WarpGrepResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (!result.contexts || result.contexts.length === 0) {\n return 'No relevant code found. Try rephrasing your search term.';\n }\n\n const parts: string[] = [];\n parts.push(`Morph Fast Context subagent performed search on repository:\\n`);\n parts.push('Relevant context found:');\n\n for (const ctx of result.contexts) {\n const rangeStr = !ctx.lines || ctx.lines === '*'\n ? '*'\n : ctx.lines.map(([s, e]) => `${s}-${e}`).join(',');\n parts.push(`- ${ctx.file}:${rangeStr}`);\n }\n\n parts.push('\\nHere is the content of files:\\n');\n\n for (const ctx of result.contexts) {\n const rangeStr = !ctx.lines || ctx.lines === '*'\n ? ''\n : ` lines=\"${ctx.lines.map(([s, e]) => `${s}-${e}`).join(',')}\"`;\n parts.push(`<file path=\"${ctx.file}\"${rangeStr}>`);\n parts.push(ctx.content);\n parts.push('</file>\\n');\n }\n\n return parts.join('\\n');\n}\n\n","/**\n * GitHub SDK Types\n *\n * Type definitions for the Morph GitHub integration.\n * Users connect GitHub in the Morph dashboard, then use these\n * types to interact with their GitHub repos through the SDK.\n */\n\n// =============================================================================\n// Configuration\n// =============================================================================\n\n/**\n * Configuration for the GitHub client\n */\nexport interface GitHubClientConfig {\n /** Morph API key (defaults to MORPH_API_KEY env var) */\n apiKey?: string;\n /** Default installation ID to use (optional, can be specified per-request) */\n installationId?: string;\n /** Base URL for the Morph API (defaults to https://api.morphllm.com) */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * A GitHub App installation (connected GitHub account)\n */\nexport interface Installation {\n /** Installation ID (use this for subsequent requests) */\n id: string;\n /** GitHub account login (username or org name) */\n accountLogin: string;\n /** Account type */\n accountType: \"User\" | \"Organization\";\n /** Custom display name (set in Morph dashboard) */\n displayName?: string;\n /** Whether check runs are disabled (only PR comments posted) */\n disableCheckRun: boolean;\n /** Whether to keep all previous PR comments (vs. replacing with latest) */\n keepCommentHistory: boolean;\n /** Browser automation model used for preview tests */\n model: string;\n}\n\n/**\n * Input for updating installation settings\n */\nexport interface UpdateInstallationInput {\n /** Installation ID to update */\n installationId: string;\n /** Custom display name */\n displayName?: string;\n /** Whether to disable check runs */\n disableCheckRun?: boolean;\n /** Whether to keep comment history */\n keepCommentHistory?: boolean;\n /** Browser automation model */\n model?: string;\n}\n\n/**\n * Site authentication credentials for a repo or project\n */\nexport interface SiteAuth {\n /** Login username or email */\n username: string | null;\n /** Login password */\n password: string | null;\n}\n\n/**\n * A repository with its Morph configuration\n */\nexport interface RepoConfig {\n /** Database UUID — use this for update/remove operations */\n id: string;\n /** GitHub's numeric repo ID */\n githubId: number;\n /** Full name including owner (e.g., \"acme/app\") */\n fullName: string;\n /** Repository name (e.g., \"app\") */\n name: string;\n /** Whether Morph tests are enabled */\n enabled: boolean;\n /** Whether to also test on mobile viewport */\n testMobile: boolean;\n /** Path filter — only trigger tests when files match this prefix */\n pathFilter: string | null;\n /** Custom instructions for the AI agent */\n customInstructions: string | null;\n /** Site authentication credentials */\n auth: SiteAuth | null;\n}\n\n/**\n * Input for updating a repo's configuration\n */\nexport interface UpdateRepoInput {\n /** Repo DB ID (from RepoConfig.id) */\n repoId: string;\n /** Whether Morph tests are enabled */\n enabled?: boolean;\n /** Whether to also test on mobile viewport */\n testMobile?: boolean;\n /** Path filter for conditional triggers */\n pathFilter?: string | null;\n /** Custom instructions for the AI agent */\n customInstructions?: string | null;\n /** Site auth credentials (null to clear) */\n auth?: { username?: string; password?: string; cookies?: unknown } | null;\n}\n\n/**\n * Input for syncing repos from GitHub\n */\nexport interface SyncReposInput {\n /** Installation ID to sync repos for */\n installationId: string;\n}\n\n/**\n * A monorepo sub-project scoped under a repo\n */\nexport interface Project {\n /** Project DB UUID */\n id: string;\n /** Parent repo DB UUID */\n repoId: string;\n /** Project name */\n name: string;\n /** Path filter within the repo */\n pathFilter: string | null;\n /** Whether tests are enabled */\n enabled: boolean;\n /** Whether to test on mobile viewport */\n testMobile: boolean;\n /** Custom instructions for the AI agent */\n customInstructions: string | null;\n /** Site authentication credentials */\n auth: SiteAuth | null;\n /** Creation timestamp (ISO 8601) */\n createdAt: string;\n}\n\n/**\n * Input for creating a project\n */\nexport interface CreateProjectInput {\n /** Parent repo DB ID */\n repoId: string;\n /** Project name (must be unique within the repo) */\n name: string;\n /** Path filter within the repo (e.g., \"packages/web/\") */\n pathFilter: string;\n /** Custom instructions for the AI agent */\n customInstructions?: string;\n}\n\n/**\n * Input for updating a project\n */\nexport interface UpdateProjectInput {\n /** Project DB ID */\n projectId: string;\n /** Whether tests are enabled */\n enabled?: boolean;\n /** Whether to test on mobile viewport */\n testMobile?: boolean;\n /** Path filter within the repo */\n pathFilter?: string | null;\n /** Custom instructions for the AI agent */\n customInstructions?: string | null;\n /** Site auth credentials (null to clear) */\n auth?: { username?: string; password?: string; cookies?: unknown } | null;\n}\n\n/**\n * Input for listing projects\n */\nexport interface ListProjectsInput {\n /** Parent repo DB ID */\n repoId: string;\n}\n\n/**\n * A GitHub repository\n */\nexport interface Repo {\n /** GitHub's numeric repo ID */\n id: number;\n /** Repository name (e.g., \"app\") */\n name: string;\n /** Full name including owner (e.g., \"acme/app\") */\n fullName: string;\n /** Whether the repo is private */\n private: boolean;\n /** Default branch name */\n defaultBranch?: string;\n}\n\n/**\n * A pull request (basic info)\n */\nexport interface PullRequest {\n /** PR number */\n number: number;\n /** PR title */\n title: string;\n /** PR description/body */\n body: string | null;\n /** PR state */\n state: \"open\" | \"closed\";\n /** Author's GitHub username */\n author: string;\n /** HEAD commit SHA */\n headSha: string;\n /** Base branch name */\n baseBranch: string;\n /** HEAD branch name */\n headBranch: string;\n /** Creation timestamp (ISO 8601) */\n createdAt: string;\n /** Last update timestamp (ISO 8601) */\n updatedAt: string;\n}\n\n/**\n * A pull request with full context (diff and files)\n */\nexport interface PullRequestWithContext extends PullRequest {\n /** Full unified diff */\n diff: string;\n /** List of changed files with patches */\n files: FileChange[];\n}\n\n/**\n * A file changed in a pull request\n */\nexport interface FileChange {\n /** File path */\n filename: string;\n /** Change status */\n status: \"added\" | \"removed\" | \"modified\" | \"renamed\";\n /** Number of lines added */\n additions: number;\n /** Number of lines deleted */\n deletions: number;\n /** Unified diff patch for this file */\n patch?: string;\n}\n\n/**\n * A deployment (e.g., Vercel preview)\n */\nexport interface Deployment {\n /** Deployment ID */\n id: number;\n /** Commit SHA this deployment is for */\n sha: string;\n /** Environment name (e.g., \"preview\", \"production\") */\n environment: string;\n /** Deployment state */\n state: \"pending\" | \"success\" | \"failure\" | \"error\" | \"inactive\" | \"in_progress\" | \"queued\";\n /** Preview/deployment URL (if available) */\n url: string | null;\n /** Creation timestamp (ISO 8601) */\n createdAt: string;\n}\n\n/**\n * A comment on a PR/issue\n */\nexport interface Comment {\n /** Comment ID */\n id: number;\n /** Comment body/content */\n body: string;\n /** Author's GitHub username */\n author: string;\n /** Creation timestamp (ISO 8601) */\n createdAt: string;\n /** Last update timestamp (ISO 8601) */\n updatedAt: string;\n}\n\n/**\n * A GitHub check run (CI status)\n */\nexport interface CheckRun {\n /** Check run ID */\n id: number;\n /** Check run name */\n name: string;\n /** Current status */\n status: \"queued\" | \"in_progress\" | \"completed\";\n /** Conclusion (only set when status is \"completed\") */\n conclusion?:\n | \"success\"\n | \"failure\"\n | \"neutral\"\n | \"cancelled\"\n | \"skipped\"\n | \"timed_out\"\n | \"action_required\";\n /** Start timestamp (ISO 8601) */\n startedAt?: string;\n /** Completion timestamp (ISO 8601) */\n completedAt?: string;\n}\n\n// =============================================================================\n// Input Types\n// =============================================================================\n\n/**\n * Input for listing repositories\n */\nexport interface ListReposInput {\n /** Installation ID to list repos for */\n installationId: string;\n}\n\n/**\n * Input for listing pull requests\n */\nexport interface ListPullRequestsInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Filter by PR state (default: \"open\") */\n state?: \"open\" | \"closed\" | \"all\";\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for getting a single pull request\n */\nexport interface GetPullRequestInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** PR number */\n number: number;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for listing deployments\n */\nexport interface ListDeploymentsInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Filter by commit SHA */\n sha?: string;\n /** Filter by environment name */\n environment?: string;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for listing comments on a PR\n */\nexport interface ListCommentsInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** PR number */\n pr: number;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for creating a comment\n */\nexport interface CreateCommentInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** PR number */\n pr: number;\n /** Comment body (Markdown supported) */\n body: string;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for updating a comment\n */\nexport interface UpdateCommentInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Comment ID to update */\n commentId: number;\n /** New comment body */\n body: string;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for deleting a comment\n */\nexport interface DeleteCommentInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Comment ID to delete */\n commentId: number;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for creating a check run\n */\nexport interface CreateCheckRunInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Commit SHA to create check run for */\n sha: string;\n /** Check run name (e.g., \"Preview Test\") */\n name: string;\n /** Initial status */\n status: \"queued\" | \"in_progress\";\n /** Output title */\n title?: string;\n /** Output summary (Markdown supported) */\n summary?: string;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for updating a check run\n */\nexport interface UpdateCheckRunInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Check run ID to update */\n checkRunId: number;\n /** New status */\n status?: \"queued\" | \"in_progress\" | \"completed\";\n /** Conclusion (required if status is \"completed\") */\n conclusion?: CheckRun[\"conclusion\"];\n /** Output title */\n title?: string;\n /** Output summary (Markdown supported) */\n summary?: string;\n /** Output text (detailed info, Markdown supported) */\n text?: string;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n// =============================================================================\n// Error Types\n// =============================================================================\n\n/**\n * Error thrown by GitHub operations\n */\nexport class GitHubError extends Error {\n /** HTTP status code */\n status: number;\n /** Error code from API */\n code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = \"GitHubError\";\n this.status = status;\n this.code = code;\n }\n}\n\n/**\n * Error thrown when no installation is found or specified\n */\nexport class NoInstallationError extends GitHubError {\n constructor(message = \"No GitHub installation found. Connect GitHub at morphllm.com/dashboard/integrations/github\") {\n super(message, 404, \"NO_INSTALLATION\");\n }\n}\n\n/**\n * Error thrown when resource is not found\n */\nexport class NotFoundError extends GitHubError {\n constructor(resource: string) {\n super(`${resource} not found`, 404, \"NOT_FOUND\");\n }\n}\n\n/**\n * Error thrown when user lacks permission\n */\nexport class PermissionError extends GitHubError {\n constructor(message = \"Insufficient permissions for this operation\") {\n super(message, 403, \"PERMISSION_DENIED\");\n }\n}\n","/**\n * GitHub SDK Client\n *\n * Provides access to GitHub repositories, pull requests, deployments,\n * comments, and check runs through the user's connected GitHub account.\n *\n * All operations are proxied through the Morph API - installation tokens\n * are never exposed to the client.\n */\n\nimport type {\n GitHubClientConfig,\n Installation,\n Repo,\n RepoConfig,\n PullRequest,\n PullRequestWithContext,\n Deployment,\n Comment,\n CheckRun,\n Project,\n ListReposInput,\n ListPullRequestsInput,\n GetPullRequestInput,\n ListDeploymentsInput,\n ListCommentsInput,\n CreateCommentInput,\n UpdateCommentInput,\n DeleteCommentInput,\n CreateCheckRunInput,\n UpdateCheckRunInput,\n UpdateInstallationInput,\n UpdateRepoInput,\n SyncReposInput,\n CreateProjectInput,\n UpdateProjectInput,\n ListProjectsInput,\n} from \"./types.js\";\n\nimport { GitHubError, NoInstallationError, NotFoundError, PermissionError } from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.morphllm.com\";\nconst DEFAULT_TIMEOUT = 30000;\n\n/**\n * GitHub SDK Client\n *\n * @example\n * ```typescript\n * import { MorphClient } from '@morphllm/morphsdk';\n *\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n *\n * // List installations\n * const installations = await morph.github.installations.list();\n *\n * // Get PR with context\n * const pr = await morph.github.pullRequests.get({\n * owner: \"acme\",\n * repo: \"app\",\n * number: 42\n * });\n * ```\n */\nexport class GitHubClient {\n private apiKey: string;\n private baseUrl: string;\n private timeout: number;\n private debug: boolean;\n private defaultInstallationId?: string;\n\n /** Installation operations */\n public installations: {\n list: () => Promise<Installation[]>;\n get: (installationId: string) => Promise<Installation>;\n update: (input: UpdateInstallationInput) => Promise<Installation>;\n disconnect: (installationId: string) => Promise<{ success: boolean; alreadyDeleted: boolean }>;\n };\n\n /** Repository operations */\n public repos: {\n list: (input: ListReposInput) => Promise<RepoConfig[]>;\n get: (repoId: string) => Promise<RepoConfig>;\n update: (input: UpdateRepoInput) => Promise<RepoConfig>;\n remove: (repoId: string) => Promise<{ success: boolean; alreadyRemoved: boolean }>;\n sync: (input: SyncReposInput) => Promise<{ count: number }>;\n };\n\n /** Project operations (monorepo sub-projects) */\n public projects: {\n list: (input: ListProjectsInput) => Promise<Project[]>;\n create: (input: CreateProjectInput) => Promise<Project>;\n update: (input: UpdateProjectInput) => Promise<Project>;\n delete: (projectId: string) => Promise<{ success: boolean }>;\n };\n\n /** Pull request operations */\n public pullRequests: {\n list: (input: ListPullRequestsInput) => Promise<PullRequest[]>;\n get: (input: GetPullRequestInput) => Promise<PullRequestWithContext>;\n };\n\n /** Deployment operations */\n public deployments: {\n list: (input: ListDeploymentsInput) => Promise<Deployment[]>;\n };\n\n /** Comment operations */\n public comments: {\n list: (input: ListCommentsInput) => Promise<Comment[]>;\n create: (input: CreateCommentInput) => Promise<Comment>;\n update: (input: UpdateCommentInput) => Promise<Comment>;\n delete: (input: DeleteCommentInput) => Promise<void>;\n };\n\n /** Check run operations */\n public checkRuns: {\n create: (input: CreateCheckRunInput) => Promise<CheckRun>;\n update: (input: UpdateCheckRunInput) => Promise<CheckRun>;\n };\n\n /**\n * Get the GitHub App installation URL.\n * Users visit this URL once to install the Morph GitHub App on their account/org.\n */\n public getInstallUrl(): string {\n return \"https://github.com/apps/morph-subagents/installations/new\";\n }\n\n constructor(config: GitHubClientConfig = {}) {\n this.apiKey = config.apiKey || process.env.MORPH_API_KEY || \"\";\n this.baseUrl = config.baseUrl || DEFAULT_BASE_URL;\n this.timeout = config.timeout || DEFAULT_TIMEOUT;\n this.debug = config.debug || false;\n this.defaultInstallationId = config.installationId;\n\n if (!this.apiKey) {\n throw new Error(\"API key required. Set MORPH_API_KEY or pass apiKey in config.\");\n }\n\n // Bind all methods\n this.installations = {\n list: this.listInstallations.bind(this),\n get: this.getInstallation.bind(this),\n update: this.updateInstallation.bind(this),\n disconnect: this.disconnectInstallation.bind(this),\n };\n\n this.repos = {\n list: this.listRepos.bind(this),\n get: this.getRepo.bind(this),\n update: this.updateRepo.bind(this),\n remove: this.removeRepo.bind(this),\n sync: this.syncRepos.bind(this),\n };\n\n this.projects = {\n list: this.listProjects.bind(this),\n create: this.createProject.bind(this),\n update: this.updateProject.bind(this),\n delete: this.deleteProject.bind(this),\n };\n\n this.pullRequests = {\n list: this.listPullRequests.bind(this),\n get: this.getPullRequest.bind(this),\n };\n\n this.deployments = {\n list: this.listDeployments.bind(this),\n };\n\n this.comments = {\n list: this.listComments.bind(this),\n create: this.createComment.bind(this),\n update: this.updateComment.bind(this),\n delete: this.deleteComment.bind(this),\n };\n\n this.checkRuns = {\n create: this.createCheckRun.bind(this),\n update: this.updateCheckRun.bind(this),\n };\n }\n\n /**\n * Make an authenticated API request\n */\n private async request<T>(\n method: string,\n path: string,\n body?: Record<string, unknown>\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`;\n\n if (this.debug) {\n console.log(`[GitHub SDK] ${method} ${path}`, body || \"\");\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n const message = errorData.error || errorData.detail || errorData.message || response.statusText;\n\n if (this.debug) {\n console.error(`[GitHub SDK] Error ${response.status}:`, message);\n }\n\n // Map to specific error types\n if (response.status === 404) {\n if (message.includes(\"installation\")) {\n throw new NoInstallationError(message);\n }\n throw new NotFoundError(message);\n }\n if (response.status === 403) {\n throw new PermissionError(message);\n }\n throw new GitHubError(message, response.status, errorData.code);\n }\n\n const data = await response.json();\n\n if (this.debug) {\n console.log(`[GitHub SDK] Response:`, JSON.stringify(data).slice(0, 200));\n }\n\n return data as T;\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof GitHubError) {\n throw error;\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new GitHubError(\"Request timeout\", 408, \"TIMEOUT\");\n }\n\n throw new GitHubError(\n error instanceof Error ? error.message : \"Unknown error\",\n 500,\n \"UNKNOWN\"\n );\n }\n }\n\n /**\n * Get the installation ID to use for a request\n */\n private getInstallationId(input?: { installationId?: string }): string | undefined {\n return input?.installationId || this.defaultInstallationId;\n }\n\n // ==========================================================================\n // Installations\n // ==========================================================================\n\n private async listInstallations(): Promise<Installation[]> {\n return this.request<Installation[]>(\"GET\", \"/api/v1/github/installations\");\n }\n\n private async getInstallation(installationId: string): Promise<Installation> {\n return this.request<Installation>(\"GET\", `/api/v1/github/installations/${installationId}`);\n }\n\n private async updateInstallation(input: UpdateInstallationInput): Promise<Installation> {\n if (this.debug) console.log(\"[GitHub SDK] updateInstallation\", input.installationId);\n const { installationId, ...body } = input;\n return this.request<Installation>(\"PATCH\", `/api/v1/github/installations/${installationId}`, body);\n }\n\n private async disconnectInstallation(installationId: string): Promise<{ success: boolean; alreadyDeleted: boolean }> {\n if (this.debug) console.log(\"[GitHub SDK] disconnectInstallation\", installationId);\n return this.request<{ success: boolean; alreadyDeleted: boolean }>(\"DELETE\", `/api/v1/github/installations/${installationId}`);\n }\n\n // ==========================================================================\n // Repositories\n // ==========================================================================\n\n private async listRepos(input: ListReposInput): Promise<RepoConfig[]> {\n const installationId = input.installationId || this.defaultInstallationId;\n if (!installationId) {\n throw new NoInstallationError(\"installationId required. Call installations.list() first.\");\n }\n return this.request<RepoConfig[]>(\"GET\", `/api/v1/github/installations/${installationId}/repos`);\n }\n\n private async getRepo(repoId: string): Promise<RepoConfig> {\n if (this.debug) console.log(\"[GitHub SDK] getRepo\", repoId);\n return this.request<RepoConfig>(\"GET\", `/api/v1/github/repos/${repoId}`);\n }\n\n private async updateRepo(input: UpdateRepoInput): Promise<RepoConfig> {\n if (this.debug) console.log(\"[GitHub SDK] updateRepo\", input.repoId);\n const { repoId, ...body } = input;\n return this.request<RepoConfig>(\"PATCH\", `/api/v1/github/repos/${repoId}`, body);\n }\n\n private async removeRepo(repoId: string): Promise<{ success: boolean; alreadyRemoved: boolean }> {\n if (this.debug) console.log(\"[GitHub SDK] removeRepo\", repoId);\n return this.request<{ success: boolean; alreadyRemoved: boolean }>(\"DELETE\", `/api/v1/github/repos/${repoId}`);\n }\n\n private async syncRepos(input: SyncReposInput): Promise<{ count: number }> {\n const installationId = input.installationId || this.defaultInstallationId;\n if (!installationId) {\n throw new NoInstallationError(\"installationId required. Call installations.list() first.\");\n }\n if (this.debug) console.log(\"[GitHub SDK] syncRepos\", installationId);\n return this.request<{ count: number }>(\"POST\", `/api/v1/github/installations/${installationId}/repos/sync`);\n }\n\n // ==========================================================================\n // Projects (monorepo sub-projects)\n // ==========================================================================\n\n private async listProjects(input: ListProjectsInput): Promise<Project[]> {\n if (this.debug) console.log(\"[GitHub SDK] listProjects\", input.repoId);\n return this.request<Project[]>(\"GET\", `/api/v1/github/repos/${input.repoId}/projects`);\n }\n\n private async createProject(input: CreateProjectInput): Promise<Project> {\n if (this.debug) console.log(\"[GitHub SDK] createProject\", input.repoId, input.name);\n const { repoId, ...body } = input;\n return this.request<Project>(\"POST\", `/api/v1/github/repos/${repoId}/projects`, body);\n }\n\n private async updateProject(input: UpdateProjectInput): Promise<Project> {\n if (this.debug) console.log(\"[GitHub SDK] updateProject\", input.projectId);\n const { projectId, ...body } = input;\n return this.request<Project>(\"PATCH\", `/api/v1/github/projects/${projectId}`, body);\n }\n\n private async deleteProject(projectId: string): Promise<{ success: boolean }> {\n if (this.debug) console.log(\"[GitHub SDK] deleteProject\", projectId);\n return this.request<{ success: boolean }>(\"DELETE\", `/api/v1/github/projects/${projectId}`);\n }\n\n // ==========================================================================\n // Pull Requests\n // ==========================================================================\n\n private async listPullRequests(input: ListPullRequestsInput): Promise<PullRequest[]> {\n const installationId = this.getInstallationId(input);\n const params = new URLSearchParams({\n owner: input.owner,\n repo: input.repo,\n ...(input.state && { state: input.state }),\n ...(installationId && { installationId }),\n });\n return this.request<PullRequest[]>(\"GET\", `/api/v1/github/pulls?${params}`);\n }\n\n private async getPullRequest(input: GetPullRequestInput): Promise<PullRequestWithContext> {\n const installationId = this.getInstallationId(input);\n const params = new URLSearchParams({\n owner: input.owner,\n repo: input.repo,\n ...(installationId && { installationId }),\n });\n return this.request<PullRequestWithContext>(\n \"GET\",\n `/api/v1/github/pulls/${input.number}?${params}`\n );\n }\n\n // ==========================================================================\n // Deployments\n // ==========================================================================\n\n private async listDeployments(input: ListDeploymentsInput): Promise<Deployment[]> {\n const installationId = this.getInstallationId(input);\n const params = new URLSearchParams({\n owner: input.owner,\n repo: input.repo,\n ...(input.sha && { sha: input.sha }),\n ...(input.environment && { environment: input.environment }),\n ...(installationId && { installationId }),\n });\n return this.request<Deployment[]>(\"GET\", `/api/v1/github/deployments?${params}`);\n }\n\n // ==========================================================================\n // Comments\n // ==========================================================================\n\n private async listComments(input: ListCommentsInput): Promise<Comment[]> {\n const installationId = this.getInstallationId(input);\n const params = new URLSearchParams({\n owner: input.owner,\n repo: input.repo,\n pr: String(input.pr),\n ...(installationId && { installationId }),\n });\n return this.request<Comment[]>(\"GET\", `/api/v1/github/comments?${params}`);\n }\n\n private async createComment(input: CreateCommentInput): Promise<Comment> {\n const installationId = this.getInstallationId(input);\n return this.request<Comment>(\"POST\", \"/api/v1/github/comments\", {\n owner: input.owner,\n repo: input.repo,\n pr: input.pr,\n body: input.body,\n ...(installationId && { installationId }),\n });\n }\n\n private async updateComment(input: UpdateCommentInput): Promise<Comment> {\n const installationId = this.getInstallationId(input);\n return this.request<Comment>(\"PATCH\", `/api/v1/github/comments/${input.commentId}`, {\n owner: input.owner,\n repo: input.repo,\n body: input.body,\n ...(installationId && { installationId }),\n });\n }\n\n private async deleteComment(input: DeleteCommentInput): Promise<void> {\n const installationId = this.getInstallationId(input);\n const params = new URLSearchParams({\n owner: input.owner,\n repo: input.repo,\n ...(installationId && { installationId }),\n });\n await this.request<void>(\"DELETE\", `/api/v1/github/comments/${input.commentId}?${params}`);\n }\n\n // ==========================================================================\n // Check Runs\n // ==========================================================================\n\n private async createCheckRun(input: CreateCheckRunInput): Promise<CheckRun> {\n const installationId = this.getInstallationId(input);\n return this.request<CheckRun>(\"POST\", \"/api/v1/github/check-runs\", {\n owner: input.owner,\n repo: input.repo,\n sha: input.sha,\n name: input.name,\n status: input.status,\n ...(input.title && { title: input.title }),\n ...(input.summary && { summary: input.summary }),\n ...(installationId && { installationId }),\n });\n }\n\n private async updateCheckRun(input: UpdateCheckRunInput): Promise<CheckRun> {\n const installationId = this.getInstallationId(input);\n return this.request<CheckRun>(\"PATCH\", `/api/v1/github/check-runs/${input.checkRunId}`, {\n owner: input.owner,\n repo: input.repo,\n ...(input.status && { status: input.status }),\n ...(input.conclusion && { conclusion: input.conclusion }),\n ...(input.title && { title: input.title }),\n ...(input.summary && { summary: input.summary }),\n ...(input.text && { text: input.text }),\n ...(installationId && { installationId }),\n });\n }\n}\n","/**\n * Morph Git Client - Simple, high-level Git operations\n * Built on isomorphic-git with explicit configuration\n */\n\n\nimport git from 'isomorphic-git';\nimport http from 'isomorphic-git/http/node';\nimport fs from 'fs';\nimport type {\n CloneOptions,\n PushOptions,\n PullOptions,\n AddOptions,\n CommitOptions,\n StatusOptions,\n LogOptions,\n CheckoutOptions,\n BranchOptions,\n DiffOptions,\n CommitObject,\n StatusResult,\n MorphGitConfig,\n MorphNotesSchema,\n WaitForEmbeddingsOptions,\n EmbeddingProgress,\n} from './types.js';\n\nconst DEFAULT_PROXY_URL = 'https://repos.morphllm.com';\n\n/**\n * MorphGit - Git operations for AI agents with Morph backend\n * \n * @example\n * ```typescript\n * import { MorphGit } from 'morphsdk/git';\n * \n * const morphGit = new MorphGit({\n * apiKey: process.env.MORPH_API_KEY!,\n * proxyUrl: 'https://repos.morphllm.com' // Optional\n * });\n * \n * await morphGit.init({ repoId: 'my-project', dir: './my-project' });\n * await morphGit.push({ dir: './my-project' });\n * ```\n */\nexport class MorphGit {\n private readonly apiKey: string;\n private readonly proxyUrl: string;\n\n constructor(config: MorphGitConfig) {\n // Validate API key\n if (!config.apiKey) {\n throw new Error('API key is required. Get one at https://morphllm.com/dashboard');\n }\n \n if (!config.apiKey.startsWith('sk-') && !config.apiKey.startsWith('morph-')) {\n throw new Error('Invalid API key format. Expected: sk-... or morph-...');\n }\n \n this.apiKey = config.apiKey;\n this.proxyUrl = config.proxyUrl || DEFAULT_PROXY_URL;\n }\n \n /**\n * Get auth callback for isomorphic-git operations\n * @private\n */\n private getAuthCallback() {\n return () => ({\n username: 'morph',\n password: this.apiKey,\n });\n }\n\n /**\n * Initialize a new repository\n * Creates the repo in the database and in the git provider\n * \n * @example\n * ```ts\n * await morphGit.init({\n * repoId: 'my-project',\n * dir: './my-project',\n * defaultBranch: 'main'\n * });\n * ```\n */\n async init(options: {\n repoId: string;\n dir: string;\n defaultBranch?: string;\n }): Promise<void> {\n const { repoId, dir, defaultBranch = 'main' } = options;\n\n // Call backend API to create repository\n const response = await fetch(`${this.proxyUrl}/v1/repos`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n repoId,\n name: repoId,\n defaultBranch,\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Failed to create repository: ${error}`);\n }\n\n // Initialize local git repository (industry standard: no clone needed)\n await git.init({\n fs,\n dir,\n defaultBranch,\n });\n\n // Add remote pointing to Morph git-proxy\n await git.addRemote({\n fs,\n dir,\n remote: 'origin',\n url: `${this.proxyUrl}/v1/repos/${repoId}`,\n });\n\n console.log(`✓ Repository '${repoId}' initialized`);\n }\n\n /**\n * Clone a repository from Morph repos\n * \n * @example\n * ```ts\n * await morphGit.clone({\n * repoId: 'my-project',\n * dir: './my-project'\n * });\n * ```\n */\n async clone(options: CloneOptions): Promise<void> {\n const { repoId, dir, branch = 'main', depth, singleBranch = true } = options;\n\n await git.clone({\n fs,\n http,\n dir,\n url: `${this.proxyUrl}/v1/repos/${repoId}`,\n ref: branch,\n singleBranch,\n depth,\n onAuth: this.getAuthCallback(),\n });\n }\n\n /**\n * Push changes to remote repository\n * \n * @example\n * ```ts\n * await morphGit.push({ \n * dir: './my-project',\n * branch: 'main', // Required: explicit branch name\n * index: true // Optional: generate embeddings for semantic search\n * });\n * ```\n */\n async push(options: PushOptions): Promise<void> {\n const { dir, remote = 'origin', branch, waitForEmbeddings, index = false } = options;\n\n if (!branch) {\n throw new Error(\n 'branch is required for push operations. ' +\n 'Specify the branch explicitly: { dir: \"./my-project\", branch: \"main\" }'\n );\n }\n\n // Get commit hash and repoId before pushing\n const commitHash = await git.resolveRef({ fs, dir, ref: 'HEAD' });\n \n // Get repoId from git remote URL\n let repoId: string | undefined;\n const remotes = await git.listRemotes({ fs, dir });\n const originRemote = remotes.find(r => r.remote === remote);\n if (originRemote) {\n // Extract repoId from URL: https://repos.morphllm.com/v1/repos/{repoId}\n const match = originRemote.url.match(/\\/repos\\/([^\\/]+)$/);\n if (match) {\n repoId = match[1];\n }\n }\n\n await git.push({\n fs,\n http,\n dir,\n remote,\n ref: branch,\n onAuth: this.getAuthCallback(),\n });\n \n // Configure commit after successful push (set index flag)\n if (repoId && commitHash) {\n await this.configureCommit({ repoId, commitHash, branch, index });\n }\n \n // Wait for embeddings if requested (and indexing is enabled)\n if (waitForEmbeddings && repoId && commitHash && index) {\n await this.waitForEmbeddings({ repoId, commitHash });\n }\n }\n\n /**\n * Configure commit settings on the backend after push.\n * Sets the index flag to control embedding generation.\n * @private\n */\n private async configureCommit(options: {\n repoId: string;\n commitHash: string;\n branch: string;\n index: boolean;\n }): Promise<void> {\n const { repoId, commitHash, branch, index } = options;\n \n const response = await fetch(\n `${this.proxyUrl}/v1/repos/${repoId}/commits/${commitHash}/config`,\n {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ index, branch }),\n }\n );\n\n if (!response.ok) {\n // Non-fatal: log warning but don't throw\n console.warn(`Failed to configure commit: ${response.status}`);\n }\n }\n\n /**\n * Pull changes from remote repository\n * \n * @example\n * ```ts\n * await morphGit.pull({ \n * dir: './my-project',\n * branch: 'main' // Required: explicit branch name\n * });\n * ```\n */\n async pull(options: PullOptions): Promise<void> {\n const { dir, remote = 'origin', branch } = options;\n\n if (!branch) {\n throw new Error(\n 'branch is required for pull operations. ' +\n 'Specify the branch explicitly: { dir: \"./my-project\", branch: \"main\" }'\n );\n }\n\n await git.pull({\n fs,\n http,\n dir,\n remote,\n ref: branch,\n onAuth: this.getAuthCallback(),\n author: {\n name: 'Morph Agent',\n email: 'agent@morph.com',\n },\n });\n }\n\n /**\n * Wait for embeddings to complete after push.\n * Polls status endpoint until embeddings are done.\n * \n * @example\n * ```ts\n * await morphGit.push({ dir: './my-project', branch: 'main' });\n * await morphGit.waitForEmbeddings({\n * repoId: 'my-project',\n * onProgress: (p) => console.log(`${p.filesProcessed}/${p.totalFiles}`)\n * });\n * ```\n */\n async waitForEmbeddings(options: WaitForEmbeddingsOptions): Promise<void> {\n const { repoId, commitHash, timeout = 120000, onProgress } = options;\n const startTime = Date.now();\n const pollInterval = 1000; // Poll every 1s\n \n while (Date.now() - startTime < timeout) {\n const statusUrl = `${this.proxyUrl}/v1/repos/${repoId}/embedding-status` +\n (commitHash ? `?commit_hash=${commitHash}` : '');\n \n const response = await fetch(statusUrl, {\n headers: { 'Authorization': `Bearer ${this.apiKey}` }\n });\n \n if (response.status === 404) {\n // No job found yet - might still be creating\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n continue;\n }\n \n if (!response.ok) {\n throw new Error(`Failed to get embedding status: ${response.status}`);\n }\n \n const status = await response.json();\n \n if (onProgress && status.progress) {\n onProgress(status.progress);\n }\n \n if (status.status === 'completed') {\n return; // Done!\n }\n \n if (status.status === 'failed') {\n throw new Error(`Embeddings failed: ${status.error || 'Unknown error'}`);\n }\n \n // Still processing (queued or processing), wait and poll again\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n \n throw new Error(`Embeddings timed out after ${timeout}ms`);\n }\n\n /**\n * Stage a file for commit\n * \n * @example\n * ```ts\n * await morphGit.add({\n * dir: './my-project',\n * filepath: 'src/app.ts'\n * });\n * ```\n */\n async add(options: AddOptions): Promise<void> {\n const { dir, filepath } = options;\n\n await git.add({\n fs,\n dir,\n filepath,\n });\n }\n\n /**\n * Remove a file from staging\n * \n * @example\n * ```ts\n * await morphGit.remove({\n * dir: './my-project',\n * filepath: 'src/old-file.ts'\n * });\n * ```\n */\n async remove(options: AddOptions): Promise<void> {\n const { dir, filepath } = options;\n\n await git.remove({\n fs,\n dir,\n filepath,\n });\n }\n\n /**\n * Commit staged changes\n * \n * @example\n * ```ts\n * await morphGit.commit({\n * dir: './my-project',\n * message: 'Add new feature',\n * author: {\n * name: 'AI Agent',\n * email: 'ai@example.com'\n * },\n * metadata: { issueId: 'PROJ-123', source: 'agent' },\n * chatHistory: [\n * { role: 'user', content: 'Please add a new feature' },\n * { role: 'assistant', content: 'I will add that feature' }\n * ],\n * recordingId: 'rec_123'\n * });\n * ```\n */\n async commit(options: CommitOptions): Promise<string> {\n const { dir, message, author, metadata, chatHistory, recordingId } = options;\n\n // Provide default author if not specified\n const commitAuthor = author || {\n name: 'Morph SDK',\n email: 'sdk@morphllm.com'\n };\n\n const sha = await git.commit({\n fs,\n dir,\n message,\n author: commitAuthor,\n });\n\n // Store notes if any note fields are provided\n if (metadata || chatHistory || recordingId) {\n const notes: MorphNotesSchema = {\n metadata,\n chatHistory,\n recordingId,\n _version: 1\n };\n \n await git.addNote({\n fs,\n dir,\n ref: 'refs/notes/morph-metadata',\n oid: sha,\n note: JSON.stringify(notes, null, 2),\n author: commitAuthor\n });\n }\n\n return sha;\n }\n\n /**\n * Get status of a file\n * \n * @example\n * ```ts\n * const status = await morphGit.status({\n * dir: './my-project',\n * filepath: 'src/app.ts'\n * });\n * console.log(status); // 'modified', '*added', etc.\n * ```\n */\n async status(options: StatusOptions): Promise<string> {\n const { dir, filepath } = options;\n\n if (!filepath) {\n throw new Error('filepath is required for status check');\n }\n\n const status = await git.status({\n fs,\n dir,\n filepath,\n });\n\n return status;\n }\n\n /**\n * Get commit history\n * \n * @example\n * ```ts\n * const commits = await morphGit.log({\n * dir: './my-project',\n * depth: 10\n * });\n * ```\n */\n async log(options: LogOptions): Promise<CommitObject[]> {\n const { dir, depth, ref } = options;\n\n const commits = await git.log({\n fs,\n dir,\n depth,\n ref,\n });\n\n return commits as CommitObject[];\n }\n\n /**\n * Checkout a branch or commit\n * \n * @example\n * ```ts\n * await morphGit.checkout({\n * dir: './my-project',\n * ref: 'feature-branch'\n * });\n * ```\n */\n async checkout(options: CheckoutOptions): Promise<void> {\n const { dir, ref } = options;\n\n await git.checkout({\n fs,\n dir,\n ref,\n });\n }\n\n /**\n * Create a new branch\n * \n * @example\n * ```ts\n * await morphGit.branch({\n * dir: './my-project',\n * name: 'feature-branch',\n * checkout: true\n * });\n * ```\n */\n async branch(options: BranchOptions): Promise<void> {\n const { dir, name, checkout = false } = options;\n\n await git.branch({\n fs,\n dir,\n ref: name,\n checkout,\n });\n }\n\n /**\n * List all branches\n * \n * @example\n * ```ts\n * const branches = await morphGit.listBranches({\n * dir: './my-project'\n * });\n * ```\n */\n async listBranches(options: { dir: string }): Promise<string[]> {\n const { dir } = options;\n\n const branches = await git.listBranches({\n fs,\n dir,\n });\n\n return branches;\n }\n\n /**\n * Get the current branch name\n * \n * @example\n * ```ts\n * const branch = await morphGit.currentBranch({\n * dir: './my-project'\n * });\n * ```\n */\n async currentBranch(options: { dir: string }): Promise<string | undefined> {\n const { dir } = options;\n\n const branch = await git.currentBranch({\n fs,\n dir,\n });\n\n return branch || undefined;\n }\n\n /**\n * Get list of changed files (similar to git diff --name-only)\n * \n * @example\n * ```ts\n * const changes = await morphGit.statusMatrix({\n * dir: './my-project'\n * });\n * ```\n */\n async statusMatrix(options: { dir: string }): Promise<StatusResult[]> {\n const { dir } = options;\n\n const matrix = await git.statusMatrix({\n fs,\n dir,\n });\n\n return matrix.map(([filepath, HEADStatus, workdirStatus, stageStatus]) => {\n let status: StatusResult['status'] = 'unmodified';\n\n // Determine status based on statusMatrix values\n if (HEADStatus === 1 && workdirStatus === 2 && stageStatus === 2) {\n status = 'modified';\n } else if (HEADStatus === 1 && workdirStatus === 2 && stageStatus === 1) {\n status = '*modified';\n } else if (HEADStatus === 0 && workdirStatus === 2 && stageStatus === 2) {\n status = 'added';\n } else if (HEADStatus === 0 && workdirStatus === 2 && stageStatus === 0) {\n status = '*added';\n } else if (HEADStatus === 1 && workdirStatus === 0 && stageStatus === 0) {\n status = 'deleted';\n } else if (HEADStatus === 1 && workdirStatus === 0 && stageStatus === 1) {\n status = '*deleted';\n } else if (HEADStatus === 1 && workdirStatus === 1 && stageStatus === 1) {\n status = 'unmodified';\n } else if (HEADStatus === 0 && workdirStatus === 0 && stageStatus === 0) {\n status = 'absent';\n }\n\n return {\n filepath,\n status,\n };\n });\n }\n\n /**\n * Get the current commit hash\n * \n * @example\n * ```ts\n * const hash = await morphGit.resolveRef({\n * dir: './my-project',\n * ref: 'HEAD'\n * });\n * ```\n */\n async resolveRef(options: { dir: string; ref: string }): Promise<string> {\n const { dir, ref } = options;\n\n const oid = await git.resolveRef({\n fs,\n dir,\n ref,\n });\n\n return oid;\n }\n\n /**\n * Get notes (metadata, chat history, recording ID) attached to a commit\n * \n * @example\n * ```ts\n * const notes = await morphGit.getCommitMetadata({\n * dir: './my-project',\n * commitSha: 'abc123...'\n * });\n * \n * if (notes) {\n * console.log('Metadata:', notes.metadata);\n * console.log('Chat history:', notes.chatHistory);\n * console.log('Recording ID:', notes.recordingId);\n * }\n * ```\n */\n async getCommitMetadata(options: {\n dir: string;\n commitSha: string;\n }): Promise<MorphNotesSchema | null> {\n try {\n const note = await git.readNote({\n fs,\n dir: options.dir,\n ref: 'refs/notes/morph-metadata',\n oid: options.commitSha\n });\n \n const notes: MorphNotesSchema = JSON.parse(new TextDecoder().decode(note));\n return notes;\n } catch (err) {\n // No notes found for this commit\n return null;\n }\n }\n}\n\n","/**\n * Morph Git SDK\n * \n * Git operations for AI agents using Morph's backend infrastructure.\n * \n * @example\n * ```typescript\n * import { MorphGit } from 'morphsdk/git';\n * \n * const morphGit = new MorphGit({\n * apiKey: process.env.MORPH_API_KEY!\n * });\n * \n * // Initialize and push\n * await morphGit.init({ repoId: 'my-project', dir: './my-project' });\n * await morphGit.add({ dir: './my-project', filepath: 'src/app.ts' });\n * await morphGit.commit({ dir: './my-project', message: 'Update' });\n * await morphGit.push({ dir: './my-project', branch: 'main' });\n * ```\n */\n\nexport { MorphGit } from './client.js';\nexport type {\n MorphGitConfig,\n CloneOptions,\n PushOptions,\n PullOptions,\n AddOptions,\n CommitOptions,\n StatusOptions,\n LogOptions,\n CheckoutOptions,\n BranchOptions,\n DiffOptions,\n CommitObject,\n StatusResult,\n ChatMessage,\n CommitMetadata,\n MorphNotesSchema,\n} from './types.js';\n\n// Re-export isomorphic-git for advanced use cases\nexport { default as git } from 'isomorphic-git';\nexport { default as http } from 'isomorphic-git/http/node';\n\n","/**\n * CompactClient — calls the Morph /v1/compact endpoint.\n *\n * Returns per-message compacted_line_ranges showing which lines were removed.\n */\n\nimport type { CompactConfig, CompactInput, CompactResult } from './types.js';\n\nconst DEFAULT_API_URL = 'http://192.222.56.183:8811';\nconst DEFAULT_TIMEOUT = 120000;\n\nexport class CompactClient {\n private config: Required<Pick<CompactConfig, 'morphApiUrl' | 'timeout'>> & CompactConfig;\n\n constructor(config: CompactConfig = {}) {\n this.config = {\n ...config,\n morphApiUrl: config.morphApiUrl ?? DEFAULT_API_URL,\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n };\n }\n\n /**\n * Compact messages or text via /v1/compact.\n * Returns per-message `compacted_line_ranges` showing which lines were removed.\n *\n * @example\n * ```typescript\n * const client = new CompactClient({ morphApiKey: 'sk-...' });\n * const result = await client.compact({\n * input: codeFile,\n * query: \"authentication\",\n * compressionRatio: 0.5,\n * });\n * console.log(result.output);\n * ```\n */\n async compact(input: CompactInput): Promise<CompactResult> {\n const apiKey = this.config.morphApiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n const debug = this.config.debug || false;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n\n const url = `${this.config.morphApiUrl}/v1/compact`;\n\n if (debug) {\n console.log(`[Compact] Calling ${url}`);\n }\n\n // Build request body with snake_case keys\n const body: Record<string, unknown> = {\n compression_ratio: input.compressionRatio ?? 0.5,\n preserve_recent: input.preserveRecent ?? 2,\n model: input.model ?? 'morph-compactor',\n include_line_ranges: input.includeLineRanges ?? true,\n include_markers: input.includeMarkers ?? true,\n };\n\n if (input.query !== undefined) {\n body.query = input.query;\n }\n\n // Normalize input: string → { input }, array → { messages }, messages field → { messages }\n if (input.messages) {\n body.messages = input.messages;\n } else if (typeof input.input === 'string') {\n body.input = input.input;\n } else if (Array.isArray(input.input)) {\n body.messages = input.input;\n } else {\n throw new Error(\"Either 'input' or 'messages' must be provided\");\n }\n\n const startTime = Date.now();\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.config.timeout),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`Compact API error ${response.status}: ${text}`);\n }\n\n const data = await response.json() as CompactResult;\n\n if (debug) {\n console.log(`[Compact] compact() done in ${Date.now() - startTime}ms`);\n }\n\n return data;\n }\n}\n","/**\n * Core implementation for intelligent model routing\n */\n\nimport { fetchWithRetry, withTimeout } from '../tools/utils/resilience.js';\nimport type {\n RouterConfig,\n RouterInput,\n RouterResult,\n RawRouterResult,\n ComplexityLevel,\n RouterMode,\n Provider,\n} from './types.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: 'https://api.morphllm.com',\n timeout: 5000, // 5 seconds (responses typically <500ms)\n debug: false,\n};\n\nabstract class BaseRouter {\n protected config: Required<Omit<RouterConfig, 'apiKey' | 'retryConfig'>> & Pick<RouterConfig, 'apiKey' | 'retryConfig'>;\n protected provider: Provider;\n\n constructor(provider: Provider, config: RouterConfig = {}) {\n this.provider = provider;\n this.config = {\n apiKey: config.apiKey,\n apiUrl: config.apiUrl || DEFAULT_CONFIG.apiUrl,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n debug: config.debug || DEFAULT_CONFIG.debug,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Select the optimal model for a given input and mode\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/${this.provider}`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Requesting ${this.provider} model selection:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model: string; confidence?: number } = await response.json();\n\n const result: RouterResult = {\n model: apiResult.model,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Selected model: ${apiResult.model}, Confidence: ${apiResult.confidence?.toFixed(3)}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[ModelRouter] Error selecting model:`, error);\n }\n throw error;\n }\n }\n}\n\n/**\n * OpenAI model router for GPT-5 series\n */\nexport class OpenAIRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('openai', config);\n }\n\n /**\n * Select optimal GPT-5 model\n * \n * @param input - User input and mode\n * @returns Selected model name (gpt-5-mini | gpt-5-low | gpt-5-medium | gpt-5-high)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Anthropic model router for Claude 4.5 series\n */\nexport class AnthropicRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('anthropic', config);\n }\n\n /**\n * Select optimal Claude model\n * \n * @param input - User input and mode\n * @returns Selected model name (claude-4.5-haiku | claude-4.5-sonnet)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Google Gemini model router\n */\nexport class GeminiRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('gemini', config);\n }\n\n /**\n * Select optimal Gemini model\n * \n * @param input - User input and mode\n * @returns Selected model name (gemini-2.5-flash | gemini-2.5-pro)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Raw difficulty classification router (no provider-specific mapping)\n */\nexport class RawRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('raw' as Provider, config);\n }\n\n /**\n * Get raw difficulty classification\n * \n * @param input - User input and mode\n * @returns Raw difficulty (easy | medium | hard | needs_info)\n */\n async classify(input: RouterInput): Promise<RawRouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/raw`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Requesting raw difficulty classification:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model?: string; difficulty?: string; confidence?: number } = await response.json();\n\n // Support both 'model' and 'difficulty' fields for compatibility\n // Empty string from API means \"medium\" difficulty (API bug workaround)\n let difficulty: ComplexityLevel;\n if (apiResult.difficulty === '') {\n difficulty = 'medium';\n } else {\n difficulty = (apiResult.difficulty || apiResult.model) as ComplexityLevel;\n }\n\n const result: RawRouterResult = {\n difficulty,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Classified as: ${difficulty}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[RawRouter] Error classifying:`, error);\n }\n throw error;\n }\n }\n}\n","/**\n * Prompts and descriptions for codebase_search\n */\n\n/**\n * Default tool name for the warp grep tool\n */\nexport const WARP_GREP_TOOL_NAME = 'codebase_search';\n\n/**\n * Default tool description for the warp grep tool\n */\nexport const WARP_GREP_DESCRIPTION = \n 'Very fast code search exploration subagent (not a grep tool) that runs parallel grep and file read calls over multiple turns to locate relevant files and line ranges. ' +\n 'The search term should be a targeted natural-language query describing what you are trying to find or accomplish, e.g. ' +\n '\"Find where authentication requests are handled in the Express routes\" or \"How do callers of processOrder handle the error case?\". ' +\n 'Fill in extra context you can infer to make the query specific. Do not pass bare keywords or symbol names — use grep directly for exact symbol lookups. ' +\n 'Use this tool first when exploring unfamiliar code. The results may be partial — follow up with classical search tools or direct file reads if needed.'\n 'When a task requires exploration beyond a single known file, ALWAYS default to warpgrep codebase search before other search mechanisms.'\n\nexport const GITHUB_WARP_GREP_SEARCH_TOOL_NAME = 'github_codebase_search';\n\nexport const GITHUB_WARP_GREP_SEARCH_DESCRIPTION =\n 'Use when you need to understand how a dependency or open-source project works by reading its actual source code on GitHub. ' +\n 'Code search exploration subagent for public GitHub repositories (not your local workspace — use codebase_search for that). ' +\n 'Runs parallel grep and file read calls to locate relevant files and line ranges in external github repositories without cloning the repository. ' +\n 'Pass a targeted natural-language query, not bare keywords. Useful for understanding how a library works or investigating upstream bugs. ' +\n 'You must provide either github_url or owner_repo (at least one required). '\n\nexport const GITHUB_WARP_GREP_SEARCH_INPUT_SCHEMA = {\n type: 'object' as const,\n properties: {\n search_term: { type: 'string' as const, description: 'A targeted natural-language query describing what to find (e.g. \"How does auth work for SSO users?\"). Not a keyword or symbol name.' },\n github_url: { type: 'string' as const, description: 'GitHub repository URL to search (e.g. \"https://github.com/vercel/next.js\"). You must provide either github_url or owner_repo.' },\n owner_repo: { type: 'string' as const, description: 'Repository owner/repo shorthand (e.g. \"vercel/next.js\"). You must provide either github_url or owner_repo.' },\n branch: { type: 'string' as const, description: 'Branch to search (defaults to the repository default branch)' },\n },\n required: ['search_term'] as const,\n};\n\nexport const GITHUB_SEARCH_TOOL_NAME = GITHUB_WARP_GREP_SEARCH_TOOL_NAME;\nexport const GITHUB_SEARCH_DESCRIPTION = GITHUB_WARP_GREP_SEARCH_DESCRIPTION;\nexport const GITHUB_SEARCH_INPUT_SCHEMA = GITHUB_WARP_GREP_SEARCH_INPUT_SCHEMA;\n\nexport const GITHUB_READ_FILE_TOOL_NAME = 'readfile_github_search';\n\nexport const GITHUB_READ_FILE_DESCRIPTION =\n 'Read a single file (or a line range) from a public GitHub repository. ' +\n 'ONLY USE THIS WHEN YOU ALREADY KNOW THE EXACT FILE PATH YOU WANT TO READ, for example after finding it via github_codebase_search results. ' +\n 'Takes owner/repo shorthand and the file path within the repo. Optionally specify startLine and endLine (1-based) to read a specific range. ' +\n 'Returns the file content with line numbers.';\n\nexport const GITHUB_READ_FILE_INPUT_SCHEMA = {\n type: 'object' as const,\n properties: {\n github: { type: 'string' as const, description: 'owner/repo shorthand (e.g., \"vercel/next.js\")' },\n path: { type: 'string' as const, description: 'File path within the repository (e.g., \"src/server/index.ts\")' },\n startLine: { type: 'number' as const, description: 'Start line number (1-based). Omit to start from beginning.' },\n endLine: { type: 'number' as const, description: 'End line number (1-based, inclusive). Omit to read to the end.' },\n branch: { type: 'string' as const, description: 'Branch to read from (defaults to the repository default branch)' },\n },\n required: ['github', 'path'] as const,\n};\n","/**\n * OpenAI SDK adapter for morph-warp-grep tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeToolCall, formatResult, WarpGrepClient, executeGitHubReadFile, formatGitHubReadFileResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, WARP_GREP_TOOL_NAME, GITHUB_SEARCH_TOOL_NAME, GITHUB_SEARCH_DESCRIPTION, GITHUB_SEARCH_INPUT_SCHEMA, GITHUB_READ_FILE_TOOL_NAME, GITHUB_READ_FILE_DESCRIPTION, GITHUB_READ_FILE_INPUT_SCHEMA } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, GitHubSearchToolConfig, GitHubReadFileInput, GitHubReadFileResult, GitHubReadFileToolConfig } from './types.js';\n\n/**\n * Input schema for the warp grep tool\n */\nconst TOOL_PARAMETERS = {\n type: 'object',\n properties: {\n search_term: { type: 'string', description: 'Search problem statement that this subagent is supposed to research for' },\n },\n required: ['search_term'],\n} as const;\n\n/**\n * OpenAI-native warp grep tool definition\n * \n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { warpGrepTool, execute } from '@morphllm/morphsdk/tools/warp-grep/openai';\n * \n * const client = new OpenAI();\n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [warpGrepTool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute the tool call\n * const result = await execute({ search_term: '...' }, { repoRoot: '.' });\n * ```\n */\nexport const warpGrepTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: WARP_GREP_TOOL_NAME,\n description: WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n },\n};\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with search_term\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult for convenience\nexport { formatResult };\n\n/**\n * Create a custom warp grep tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example Local usage\n * ```typescript\n * import OpenAI from 'openai';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/openai';\n * \n * const tool = createWarpGrepTool({ repoRoot: '.' });\n * \n * const client = new OpenAI();\n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * ```\n * \n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const tool = createMorphWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepToolConfig) {\n const tool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: config.name ?? WARP_GREP_TOOL_NAME,\n description: config.description ?? WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n },\n };\n\n return Object.assign(tool, {\n execute: async (input: unknown): Promise<WarpGrepResult> => {\n return executeToolCall(input as { search_term: string } | string, config);\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub search tool for OpenAI SDK\n *\n * @param config - Configuration options (morphApiKey, morphApiUrl, codeSearchUrl, timeout)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { createGitHubSearchTool } from '@morphllm/morphsdk/tools/warp-grep/openai';\n *\n * const tool = createGitHubSearchTool({ morphApiKey: process.env.MORPH_API_KEY });\n *\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'How does auth work in vercel/next.js?' }]\n * });\n *\n * // Execute\n * const result = await tool.execute({ search_term: 'auth middleware', github_url: 'https://github.com/vercel/next.js' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubSearchTool(config: GitHubSearchToolConfig) {\n const client = new WarpGrepClient(config);\n\n const tool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: GITHUB_SEARCH_TOOL_NAME,\n description: GITHUB_SEARCH_DESCRIPTION,\n parameters: GITHUB_SEARCH_INPUT_SCHEMA,\n },\n };\n\n return Object.assign(tool, {\n execute: async (input: { search_term: string; github_url?: string; owner_repo?: string; branch?: string }): Promise<WarpGrepResult> => {\n const github = input.github_url || input.owner_repo;\n if (!github) {\n throw new Error('Please provide github search url or owner/repo id');\n }\n return client.searchGitHub({ searchTerm: input.search_term, github, branch: input.branch });\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub read file tool for OpenAI SDK\n *\n * @param config - Optional configuration (timeout)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { createGitHubReadFileTool } from '@morphllm/morphsdk/tools/warp-grep/openai';\n *\n * const tool = createGitHubReadFileTool();\n *\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Read the package.json from vercel/next.js' }]\n * });\n *\n * const result = await tool.execute({ github: 'vercel/next.js', path: 'package.json' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubReadFileTool(config?: GitHubReadFileToolConfig) {\n const tool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: GITHUB_READ_FILE_TOOL_NAME,\n description: GITHUB_READ_FILE_DESCRIPTION,\n parameters: GITHUB_READ_FILE_INPUT_SCHEMA,\n },\n };\n\n return Object.assign(tool, {\n execute: async (input: GitHubReadFileInput): Promise<GitHubReadFileResult> => {\n return executeGitHubReadFile(input, config);\n },\n formatResult: (result: GitHubReadFileResult): string => {\n return formatGitHubReadFileResult(result);\n },\n });\n}\n\nexport default warpGrepTool;\n","/**\n * Tool descriptions and system prompts for codebase search\n */\n\nexport const CODEBASE_SEARCH_DESCRIPTION = `Semantic search that finds code by meaning, not exact text.\n\nUse this to explore unfamiliar codebases or ask \"how/where/what\" questions:\n- \"How does X work?\" - Find implementation details\n- \"Where is Y handled?\" - Locate specific functionality\n- \"What happens when Z?\" - Understand flow\n\nThe tool uses two-stage retrieval (embedding similarity + reranking) to find the most semantically relevant code chunks.\n\nReturns code chunks with file paths, line ranges, and full content ranked by relevance.`;\n\nexport const CODEBASE_SEARCH_SYSTEM_PROMPT = `You have access to the codebase_search tool that performs semantic code search.\n\nWhen searching:\n- Use natural language queries describing what you're looking for\n- Be specific about functionality, not variable names\n- Use target_directories to narrow search if you know the area\n- Results are ranked by relevance (rerank score is most important)\n\nThe tool returns:\n- File paths with symbol names (e.g. \"src/auth.ts::AuthService@L1-L17\")\n- Line ranges for precise navigation\n- Full code content for each match\n- Dual relevance scores: embedding similarity + rerank score\n\nUse results to understand code or answer questions. The content is provided in full - avoid re-reading unless you need more context.`;\n\n","/**\n * OpenAI SDK adapter for codebase_search tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION, CODEBASE_SEARCH_SYSTEM_PROMPT } from './prompts.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n/**\n * Direct codebase_search tool definition\n * Use this when you want to pass config at execute time\n */\nexport const codebaseSearchTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n },\n};\n\n/**\n * Create OpenAI-native codebase_search tool with execute and formatResult methods\n * \n * @param config - Configuration with repoId\n * @returns OpenAI ChatCompletionTool definition with methods\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/openai';\n * \n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\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: \"Find authentication code\" }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const toolDefinition: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n },\n };\n\n return Object.assign(toolDefinition, {\n execute: async (input: CodebaseSearchInput | string): Promise<CodebaseSearchResult> => {\n const parsedInput = typeof input === 'string' ? JSON.parse(input) : input;\n return executeCodebaseSearch(parsedInput, config);\n },\n formatResult: (result: CodebaseSearchResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Execute codebase_search tool call\n * \n * @param input - Tool input from GPT (parsed from tool_calls)\n * @param config - Configuration with repoId (REQUIRED)\n * @returns Search results\n * \n * @example\n * ```ts\n * // Handle tool calls from GPT:\n * if (response.choices[0].message.tool_calls) {\n * for (const toolCall of response.choices[0].message.tool_calls) {\n * const args = JSON.parse(toolCall.function.arguments);\n * const result = await execute(args, { repoId: 'my-project' });\n * console.log(`Found ${result.results.length} matches`);\n * }\n * }\n * ```\n */\nexport async function execute(\n input: CodebaseSearchInput,\n config: CodebaseSearchConfig\n): Promise<CodebaseSearchResult> {\n return executeCodebaseSearch(input, config);\n}\n\n/**\n * Format search results for GPT\n * \n * @param result - Search result from endpoint\n * @returns Formatted string for tool message\n */\nexport function formatResult(result: CodebaseSearchResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (result.results.length === 0) {\n return 'No matching code found. Try rephrasing your query or removing directory filters.';\n }\n\n const lines: string[] = [];\n \n lines.push(`Found ${result.results.length} relevant code sections (${result.stats.searchTimeMs}ms):\\n`);\n\n result.results.forEach((r, i) => {\n const relevance = (r.rerankScore * 100).toFixed(1);\n lines.push(`${i + 1}. ${r.filepath} (${relevance}% relevant)`);\n lines.push(` Symbol: ${r.symbolPath}`);\n lines.push(` Language: ${r.language}`);\n lines.push(` Lines: ${r.startLine}-${r.endLine}`);\n lines.push(` Code:`);\n \n // Show code content\n const codeLines = r.content.split('\\n');\n codeLines.slice(0, Math.min(codeLines.length, 20)).forEach(line => {\n lines.push(` ${line}`);\n });\n \n if (codeLines.length > 20) {\n lines.push(` ... (${codeLines.length - 20} more lines)`);\n }\n \n lines.push('');\n });\n\n return lines.join('\\n');\n}\n\n/**\n * Get the system prompt for codebase_search usage\n * \n * @returns System prompt to guide GPT\n */\nexport function getSystemPrompt(): string {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n}\n\n/**\n * Default export for convenience\n */\nexport default { createCodebaseSearchTool, execute, formatResult, getSystemPrompt };\n\n","/**\n * System prompts for edit_file tool\n */\n\nexport const EDIT_FILE_TOOL_DESCRIPTION = `Use this tool to make an edit to an existing file.\n\nThis will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.\n\nWhen writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.\n\nFor example:\n\n// ... existing code ...\nFIRST_EDIT\n// ... existing code ...\nSECOND_EDIT\n// ... existing code ...\nTHIRD_EDIT\n// ... existing code ...\n\nYou should still bias towards repeating as few lines of the original file as possible to convey the change.\nBut, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.\n\nDO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.\n\nIf you plan on deleting a section, you must provide context before and after to delete it.\n\nMake sure it is clear what the edit should be, and where it should be applied.\nMake edits to a file in a single edit_file call instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.`;\n\nexport const EDIT_FILE_SYSTEM_PROMPT = `When the user is asking for edits to their code, use the edit_file tool to highlight the changes necessary and add comments to indicate where unchanged code has been skipped. For example:\n\n// ... existing code ...\n{{ edit_1 }}\n// ... existing code ...\n{{ edit_2 }}\n// ... existing code ...\n\nOften this will mean that the start/end of the file will be skipped, but that's okay! Rewrite the entire file ONLY if specifically requested. Always provide a brief explanation of the updates, unless the user specifically requests only the code.\n\nThese edit codeblocks are also read by a less intelligent language model, colloquially called the apply model, to update the file. To help specify the edit to the apply model, you will be very careful when generating the codeblock to not introduce ambiguity. You will specify all unchanged regions (code and comments) of the file with \"// ... existing code ...\" comment markers. This will ensure the apply model will not delete existing unchanged code or comments when editing the file.`;\n\n","/**\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 return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;\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 * OpenAI Tool Factory for MorphClient\n * \n * Creates OpenAI-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool, createGitHubSearchTool } from '../tools/warp_grep/openai.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/openai.js';\nimport { createEditFileTool } from '../tools/fastapply/openai.js';\nimport type { WarpGrepToolConfig, GitHubSearchToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\n\n/**\n * Factory for creating OpenAI-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.openai.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.openai.createEditFileTool({ baseDir: './src' });\n * \n * // Use with OpenAI client\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [grepTool, searchTool, editTool],\n * messages: [{ role: 'user', content: 'Find and fix the bug' }]\n * });\n * ```\n */\nexport class OpenAIToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create an OpenAI-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible GitHub search tool\n *\n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createGitHubSearchTool(toolConfig?: Omit<GitHubSearchToolConfig, 'morphApiKey'>) {\n return createGitHubSearchTool({\n ...toolConfig,\n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Anthropic SDK adapter for morph-warp-grep tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeToolCall, formatResult, WarpGrepClient, executeGitHubReadFile, formatGitHubReadFileResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, WARP_GREP_TOOL_NAME, GITHUB_SEARCH_TOOL_NAME, GITHUB_SEARCH_DESCRIPTION, GITHUB_SEARCH_INPUT_SCHEMA, GITHUB_READ_FILE_TOOL_NAME, GITHUB_READ_FILE_DESCRIPTION, GITHUB_READ_FILE_INPUT_SCHEMA } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, GitHubSearchToolConfig, GitHubReadFileInput, GitHubReadFileResult, GitHubReadFileToolConfig } from './types.js';\n\n/**\n * Input schema for the warp grep tool\n */\nconst INPUT_SCHEMA = {\n type: 'object',\n properties: {\n search_term: { type: 'string', description: 'Search problem statement that this subagent is supposed to research for' },\n },\n required: ['search_term'],\n} as const;\n\n/**\n * Anthropic-native warp grep tool definition\n * \n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { warpGrepTool, execute } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const client = new Anthropic();\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [warpGrepTool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute the tool call\n * const result = await execute({ search_term: '...' }, { repoRoot: '.' });\n * ```\n */\nexport const warpGrepTool: Tool = {\n name: WARP_GREP_TOOL_NAME,\n description: WARP_GREP_DESCRIPTION,\n input_schema: INPUT_SCHEMA,\n};\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with search_term\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult for convenience\nexport { formatResult };\n\n/**\n * Create a custom warp grep tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example Local usage\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const tool = createWarpGrepTool({ repoRoot: '.' });\n * \n * const client = new Anthropic();\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * ```\n * \n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const tool = createMorphWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepToolConfig) {\n const tool: Tool = {\n name: config.name ?? WARP_GREP_TOOL_NAME,\n description: config.description ?? WARP_GREP_DESCRIPTION,\n input_schema: INPUT_SCHEMA,\n };\n\n return Object.assign(tool, {\n execute: async (input: unknown): Promise<WarpGrepResult> => {\n return executeToolCall(input as { search_term: string } | string, config);\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub search tool for Anthropic SDK\n *\n * @param config - Configuration options (morphApiKey, morphApiUrl, codeSearchUrl, timeout)\n * @returns Anthropic Tool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createGitHubSearchTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n *\n * const tool = createGitHubSearchTool({ morphApiKey: process.env.MORPH_API_KEY });\n *\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'How does auth work in vercel/next.js?' }]\n * });\n *\n * // Execute\n * const result = await tool.execute({ search_term: 'auth middleware', github_url: 'https://github.com/vercel/next.js' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubSearchTool(config: GitHubSearchToolConfig) {\n const client = new WarpGrepClient(config);\n\n const tool: Tool = {\n name: GITHUB_SEARCH_TOOL_NAME,\n description: GITHUB_SEARCH_DESCRIPTION,\n input_schema: GITHUB_SEARCH_INPUT_SCHEMA,\n };\n\n return Object.assign(tool, {\n execute: async (input: { search_term: string; github_url?: string; owner_repo?: string; branch?: string }): Promise<WarpGrepResult> => {\n const github = input.github_url || input.owner_repo;\n if (!github) {\n throw new Error('Please provide github search url or owner/repo id');\n }\n return client.searchGitHub({ searchTerm: input.search_term, github, branch: input.branch });\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub read file tool for Anthropic SDK\n *\n * @param config - Optional configuration (timeout)\n * @returns Anthropic Tool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createGitHubReadFileTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n *\n * const tool = createGitHubReadFileTool();\n *\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Read the package.json from vercel/next.js' }]\n * });\n *\n * const result = await tool.execute({ github: 'vercel/next.js', path: 'package.json' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubReadFileTool(config?: GitHubReadFileToolConfig) {\n const tool: Tool = {\n name: GITHUB_READ_FILE_TOOL_NAME,\n description: GITHUB_READ_FILE_DESCRIPTION,\n input_schema: GITHUB_READ_FILE_INPUT_SCHEMA,\n };\n\n return Object.assign(tool, {\n execute: async (input: GitHubReadFileInput): Promise<GitHubReadFileResult> => {\n return executeGitHubReadFile(input, config);\n },\n formatResult: (result: GitHubReadFileResult): string => {\n return formatGitHubReadFileResult(result);\n },\n });\n}\n","/**\n * Anthropic SDK adapter for codebase_search tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION, CODEBASE_SEARCH_SYSTEM_PROMPT } from './prompts.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n\n/**\n * Create Anthropic-native codebase_search tool with execute and formatResult methods\n * \n * @param config - Configuration with repoId\n * @returns Anthropic Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [tool], // tool itself is the Tool definition\n * messages: [{ role: \"user\", content: \"Find authentication code\" }]\n * });\n * \n * // Execute tool and format result\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const toolDefinition: Tool = {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n input_schema: {\n type: 'object',\n properties: {\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n query: {\n type: 'string',\n description: 'A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n cache_control: { type: 'ephemeral' } as any,\n } as any;\n\n return Object.assign(toolDefinition, {\n execute: async (input: CodebaseSearchInput): Promise<CodebaseSearchResult> => {\n return executeCodebaseSearch(input, config);\n },\n formatResult: (result: CodebaseSearchResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Format search results for Claude\n * \n * @param result - Search result from endpoint\n * @returns Formatted string for tool_result\n */\nfunction formatResult(result: CodebaseSearchResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (result.results.length === 0) {\n return 'No matching code found. Try rephrasing your query or broadening the search scope.';\n }\n\n const lines: string[] = [];\n \n lines.push(`Found ${result.results.length} relevant code sections (searched ${result.stats.candidatesRetrieved} candidates in ${result.stats.searchTimeMs}ms):\\n`);\n\n result.results.forEach((r, i) => {\n const relevance = (r.rerankScore * 100).toFixed(1);\n lines.push(`${i + 1}. ${r.filepath} (${relevance}% relevant)`);\n lines.push(` Symbol: ${r.symbolPath}`);\n lines.push(` Language: ${r.language}`);\n lines.push(` Lines: ${r.startLine}-${r.endLine}`);\n lines.push(` Code:`);\n \n // Show code content with indentation\n const codeLines = r.content.split('\\n');\n codeLines.slice(0, Math.min(codeLines.length, 20)).forEach(line => {\n lines.push(` ${line}`);\n });\n \n if (codeLines.length > 20) {\n lines.push(` ... (${codeLines.length - 20} more lines)`);\n }\n \n lines.push('');\n });\n\n return lines.join('\\n');\n}\n\n","/**\n * Anthropic SDK adapter for edit_file tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\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 * Anthropic-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { editFileTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: Tool = {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n input_schema: {\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 * Format the result for passing back to Claude\n * \n * @param result - The edit result\n * @returns Formatted string for tool_result\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 return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * morphApiKey: 'sk-...',\n * description: 'Custom tool description for your use case'\n * });\n * \n * // Use as Anthropic tool\n * const response = await client.messages.create({\n * tools: [tool], // tool itself is the Tool definition\n * ...\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: Tool = {\n ...editFileTool,\n ...(config.description && { description: config.description }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput): Promise<EditFileResult> => {\n return executeEditFile(input, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return EDIT_FILE_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Execute the edit_file tool with raw input\n * \n * @param input - Tool input from Claude's tool_use\n * @param config - Configuration for Fast Apply\n * @returns Tool result to send back to Claude\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 the edit_file tool\n * \n * @returns System prompt string\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n","/**\n * System prompts and tool descriptions for Explore subagent\n */\n\nimport type { ExploreThoroughness } from './types.js';\n\nconst THOROUGHNESS_INSTRUCTIONS: Record<ExploreThoroughness, string> = {\n quick: `Do 1-2 targeted searches. Find the most relevant file/function quickly and summarize. Don't go deep.`,\n medium: `Do 2-4 searches. Start broad, then follow up on the most promising leads. Cover the main aspects.`,\n thorough: `Do 4-8 searches. Explore systematically: start broad, then drill into each relevant area. Cover edge cases, related files, and the full call chain. Leave no stone unturned.`,\n};\n\nexport function getSystemPrompt(thoroughness: ExploreThoroughness = 'medium'): string {\n return `You are a codebase exploration specialist. Your job is to search a codebase and return a concise, accurate summary of what you find.\n\n## Mode\nREAD-ONLY. You cannot modify files. You can only search and read code.\n\n## Strategy\n${THOROUGHNESS_INSTRUCTIONS[thoroughness]}\n\n- Use multiple focused searches rather than one vague search\n- Follow imports, function calls, and type references to build complete understanding\n- If a search returns no results, try alternative terms (e.g., \"auth\" vs \"authentication\" vs \"login\")\n- Look at both implementation and tests when relevant\n\n## Communication\nYou have a \\`send_message\\` tool. Use it when:\n- You hit a fork in the road and need guidance (\"Found auth in both src/middleware/ and legacy/auth/. Which should I focus on?\")\n- You need clarification on ambiguous requests (\"There are 3 auth strategies: JWT, session, OAuth. Which one?\")\n- You want to share a key finding before continuing (\"The main auth handler is in src/auth/index.ts. It delegates to strategy-specific modules. Continuing to trace JWT flow.\")\n\nDo NOT use send_message for routine status updates. Only use it when you genuinely need input or have a significant finding worth sharing before you're done.\n\n## Output\nWhen you have enough information, output your final summary. Structure it as:\n1. Direct answer to the question\n2. Key files and their roles\n3. How the pieces connect\n\nBe concise. The summary should be useful to another AI model that will use your findings to complete a task.`;\n}\n\nexport const CODEBASE_SEARCH_TOOL = {\n name: 'codebase_search',\n description: 'Search the codebase for relevant code. Takes a natural language search request describing what you want to find. Returns matching file contents with line numbers.',\n input_schema: {\n type: 'object' as const,\n properties: {\n searchRequest: {\n type: 'string' as const,\n description: 'Natural language description of what to search for in the codebase',\n },\n },\n required: ['searchRequest'] as const,\n additionalProperties: false as const,\n },\n};\n\nexport const SEND_MESSAGE_TOOL = {\n name: 'send_message',\n description: 'Send a message to the orchestrating agent. Use this to ask questions, request clarification, or share important findings. The orchestrator may reply with additional context. Use sparingly — only when you genuinely need input or have a significant finding.',\n input_schema: {\n type: 'object' as const,\n properties: {\n message: {\n type: 'string' as const,\n description: 'The message to send to the orchestrator',\n },\n },\n required: ['message'] as const,\n additionalProperties: false as const,\n },\n};\n","/**\n * Anthropic SDK adapter for Explore subagent\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { WarpGrepClient } from '../tools/warp_grep/client.js';\nimport { formatResult } from '../tools/warp_grep/client.js';\nimport type { WarpGrepContext } from '../tools/warp_grep/types.js';\nimport { getSystemPrompt, CODEBASE_SEARCH_TOOL, SEND_MESSAGE_TOOL } from './prompts.js';\nimport type {\n ExploreSubagentConfig,\n ExploreResult,\n ExploreStep,\n ExploreSession,\n ExploreEvent,\n SubagentMessage,\n MessageHandler,\n StepHandler,\n} from './types.js';\n\n/** Config for Anthropic SDK Explore subagent */\nexport interface AnthropicExploreConfig extends ExploreSubagentConfig {\n /** Anthropic SDK client instance */\n client: AnthropicClient;\n /** Model name (e.g., 'claude-haiku-4-5-20251001') */\n model: string;\n}\n\n/** Minimal Anthropic client interface — avoids hard dependency on @anthropic-ai/sdk */\ninterface AnthropicClient {\n messages: {\n create(params: any): Promise<any>;\n };\n}\n\nconst DEFAULT_MAX_TURNS: Record<string, number> = {\n quick: 3,\n medium: 6,\n thorough: 12,\n};\n\nfunction getMaxTurns(config: ExploreSubagentConfig): number {\n return config.maxTurns ?? DEFAULT_MAX_TURNS[config.thoroughness ?? 'medium'] ?? 6;\n}\n\n/** Anthropic tool definitions */\nconst TOOLS: Tool[] = [\n {\n name: CODEBASE_SEARCH_TOOL.name,\n description: CODEBASE_SEARCH_TOOL.description,\n input_schema: CODEBASE_SEARCH_TOOL.input_schema,\n },\n {\n name: SEND_MESSAGE_TOOL.name,\n description: SEND_MESSAGE_TOOL.description,\n input_schema: SEND_MESSAGE_TOOL.input_schema,\n },\n];\n\n/**\n * Create an Explore subagent using the Anthropic SDK\n */\nexport function createExploreSubagent(config: AnthropicExploreConfig) {\n if (!config.repoRoot) {\n throw new Error('repoRoot is required for Explore subagent');\n }\n\n const warpGrep = new WarpGrepClient({\n morphApiKey: config.morphApiKey,\n });\n\n const thoroughness = config.thoroughness ?? 'medium';\n const maxTurns = getMaxTurns(config);\n const replyTimeout = config.replyTimeout ?? 30_000;\n\n /** Run the agent loop and collect results */\n async function runExplore(\n prompt: string,\n callbacks: {\n onStep?: StepHandler;\n onMessage?: MessageHandler;\n } = {},\n ): Promise<ExploreResult> {\n const startTime = Date.now();\n const allContexts: WarpGrepContext[] = [];\n let searchCount = 0;\n\n const timeoutMs = config.timeout;\n\n try {\n const messages: any[] = [{ role: 'user', content: prompt }];\n let turns = 0;\n\n while (turns < maxTurns) {\n // Check timeout\n if (timeoutMs && Date.now() - startTime > timeoutMs) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: `Exploration timed out after ${timeoutMs}ms`,\n };\n }\n\n const response = await config.client.messages.create({\n model: config.model,\n max_tokens: 4096,\n system: getSystemPrompt(thoroughness),\n tools: TOOLS,\n messages,\n });\n\n turns++;\n\n // Check if the model is done (no tool use)\n if (response.stop_reason === 'end_turn' || !response.content.some((b: any) => b.type === 'tool_use')) {\n const textBlock = response.content.find((b: any) => b.type === 'text');\n const summary = textBlock?.text || 'Exploration completed but no summary was generated.';\n\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: '',\n contextsFound: allContexts.length,\n isFinal: true,\n });\n\n return {\n success: true,\n summary,\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n };\n }\n\n // Process tool calls\n messages.push({ role: 'assistant', content: response.content });\n\n const toolResults: any[] = [];\n\n for (const block of response.content) {\n if (block.type !== 'tool_use') continue;\n\n if (block.name === 'codebase_search') {\n searchCount++;\n const input = block.input as { searchRequest: string };\n\n const warpResult = await warpGrep.execute({\n searchTerm: input.searchRequest,\n repoRoot: config.repoRoot,\n excludes: config.excludes,\n includes: config.includes,\n });\n\n if (warpResult.contexts) {\n allContexts.push(...warpResult.contexts);\n }\n\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: input.searchRequest,\n contextsFound: warpResult.contexts?.length ?? 0,\n isFinal: false,\n });\n\n toolResults.push({\n type: 'tool_result',\n tool_use_id: block.id,\n content: formatResult(warpResult),\n });\n } else if (block.name === 'send_message') {\n const input = block.input as { message: string };\n\n const subagentMsg: SubagentMessage = {\n from: 'explore',\n content: input.message,\n timestamp: Date.now(),\n };\n\n let replyText = '';\n\n if (callbacks.onMessage) {\n // Wait for reply with timeout\n replyText = await Promise.race([\n new Promise<string>((resolve) => {\n callbacks.onMessage!(subagentMsg, (text: string) => {\n resolve(text);\n });\n }),\n new Promise<string>((resolve) =>\n setTimeout(() => resolve(''), replyTimeout),\n ),\n ]);\n }\n\n const toolResponse = replyText\n ? `Response from orchestrator: ${replyText}`\n : 'No response. Continue with your best judgment.';\n\n toolResults.push({\n type: 'tool_result',\n tool_use_id: block.id,\n content: toolResponse,\n });\n }\n }\n\n messages.push({ role: 'user', content: toolResults });\n }\n\n // Ran out of turns — extract what we have\n return {\n success: true,\n summary: 'Exploration completed (max turns reached).',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n };\n } catch (error) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /** Anthropic Tool definition for use in parent agents */\n const exploreTool: Tool & {\n execute: (input: { searchRequest: string }) => Promise<ExploreResult>;\n formatResult: (result: ExploreResult) => string;\n } = Object.assign(\n {\n name: 'explore',\n description:\n 'Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings.',\n input_schema: {\n type: 'object' as const,\n properties: {\n searchRequest: {\n type: 'string' as const,\n description: 'What to explore in the codebase. Be specific about what you want to understand.',\n },\n },\n required: ['searchRequest'] as const,\n },\n },\n {\n execute: async (input: { searchRequest: string }): Promise<ExploreResult> => {\n return runExplore(input.searchRequest);\n },\n formatResult: (result: ExploreResult): string => {\n if (!result.success) {\n return `Exploration failed: ${result.error}`;\n }\n return result.summary;\n },\n },\n );\n\n return {\n /** Anthropic Tool definition for use in parent agents */\n tool: exploreTool,\n\n /** Run exploration with messaging support */\n run(prompt: string): ExploreSession {\n const messageHandlers: MessageHandler[] = [];\n const stepHandlers: StepHandler[] = [];\n\n let resultPromise: Promise<ExploreResult> | null = null;\n\n const session: ExploreSession = {\n on(event: string, handler: any) {\n if (event === 'message') messageHandlers.push(handler);\n if (event === 'step') stepHandlers.push(handler);\n return session;\n },\n send(_text: string) {\n // Convenience method — pause-and-ask flow uses the reply callback\n },\n get result() {\n if (!resultPromise) {\n resultPromise = runExplore(prompt, {\n onStep: (step) => {\n for (const handler of stepHandlers) handler(step);\n },\n onMessage: (msg, reply) => {\n if (messageHandlers.length > 0) {\n for (const handler of messageHandlers) handler(msg, reply);\n } else {\n reply('');\n }\n },\n });\n }\n return resultPromise;\n },\n };\n\n return session;\n },\n\n /** Stream exploration events as an async generator */\n async *stream(prompt: string): AsyncGenerator<ExploreEvent, ExploreResult, undefined> {\n const events: ExploreEvent[] = [];\n let resolveNext: (() => void) | null = null;\n let done = false;\n\n const resultPromise = runExplore(prompt, {\n onStep: (step) => {\n events.push({\n type: 'step',\n step: step.step,\n searchRequest: step.searchRequest,\n contextsFound: step.contextsFound,\n isFinal: step.isFinal,\n });\n resolveNext?.();\n },\n onMessage: (msg, reply) => {\n events.push({\n type: 'message',\n from: msg.from,\n content: msg.content,\n timestamp: msg.timestamp,\n });\n resolveNext?.();\n reply('Continue with your best judgment.');\n },\n });\n\n while (!done) {\n if (events.length > 0) {\n yield events.shift()!;\n } else {\n const raceResult = await Promise.race([\n resultPromise.then((r) => ({ type: 'done' as const, result: r })),\n new Promise<{ type: 'event' }>((resolve) => {\n resolveNext = () => resolve({ type: 'event' });\n }),\n ]);\n\n if (raceResult.type === 'done') {\n while (events.length > 0) {\n yield events.shift()!;\n }\n done = true;\n return raceResult.result;\n }\n }\n }\n\n return await resultPromise;\n },\n };\n}\n\n/** Deduplicate contexts, keeping the latest version of each file */\nfunction deduplicateContexts(contexts: WarpGrepContext[]): WarpGrepContext[] {\n const map = new Map<string, WarpGrepContext>();\n for (const ctx of contexts) {\n const existing = map.get(ctx.file);\n if (!existing || ctx.content.length > existing.content.length) {\n map.set(ctx.file, ctx);\n }\n }\n return Array.from(map.values());\n}\n","/**\n * Anthropic Tool Factory for MorphClient\n * \n * Creates Anthropic-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool, createGitHubSearchTool } from '../tools/warp_grep/anthropic.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/anthropic.js';\nimport { createEditFileTool } from '../tools/fastapply/anthropic.js';\nimport { createExploreSubagent } from '../subagents/anthropic.js';\nimport type { WarpGrepToolConfig, GitHubSearchToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\nimport type { ExploreSubagentConfig } from '../subagents/types.js';\n\n/**\n * Factory for creating Anthropic-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.anthropic.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.anthropic.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.anthropic.createEditFileTool({ baseDir: './src' });\n * \n * // Use with Anthropic client\n * const response = await anthropic.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [grepTool, searchTool, editTool],\n * messages: [{ role: 'user', content: 'Find and fix the bug' }]\n * });\n * ```\n */\nexport class AnthropicToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create an Anthropic-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n\n }\n\n /**\n * Create an Anthropic-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Anthropic-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Anthropic-compatible GitHub search tool\n *\n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createGitHubSearchTool(toolConfig?: Omit<GitHubSearchToolConfig, 'morphApiKey'>) {\n return createGitHubSearchTool({\n ...toolConfig,\n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Explore subagent that searches the codebase and returns summaries\n *\n * @param config - Subagent configuration including client and model (morphApiKey inherited from MorphClient)\n * @returns Explore subagent with .tool, .run(), and .stream() methods\n */\n createExploreSubagent(config: Omit<ExploreSubagentConfig, 'morphApiKey'> & { client: any; model: string }) {\n return createExploreSubagent({\n ...config,\n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Vercel AI SDK adapter for morph-warp-grep tool\n *\n * @example Using with your own Zod instance (recommended for avoiding version conflicts)\n * ```typescript\n * import { z } from 'zod'; // Your project's Zod\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const schema = z.object({\n * search_term: z.string().describe('Search problem statement'),\n * });\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: schema,\n * });\n * ```\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { jsonSchema } from 'ai';\nimport { executeToolCall, executeToolCallStreaming, formatResult, WarpGrepClient, executeGitHubReadFile, formatGitHubReadFileResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, GITHUB_SEARCH_DESCRIPTION, GITHUB_READ_FILE_DESCRIPTION } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, GitHubSearchToolConfig, GitHubReadFileInput, GitHubReadFileResult, GitHubReadFileToolConfig } from './types.js';\nimport type { WarpGrepStep } from './agent/types.js';\n\n/**\n * Raw JSON Schema for warp grep input (no Zod dependency).\n * Use this with jsonSchema() from 'ai' if you have Zod version conflicts.\n *\n * @example\n * ```typescript\n * import { jsonSchema } from 'ai';\n * import { warpGrepJsonSchema, createWarpGrepToolWithSchema } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepToolWithSchema({\n * repoRoot: '.',\n * inputSchema: jsonSchema(warpGrepJsonSchema),\n * });\n * ```\n */\nexport const warpGrepJsonSchema = {\n type: 'object' as const,\n properties: {\n search_term: {\n type: 'string' as const,\n description: 'Search problem statement that this subagent is supposed to research for',\n },\n },\n required: ['search_term'] as const,\n additionalProperties: false as const,\n};\n\n/** Type for the model-facing warp grep tool input (snake_case to match JSON schema) */\nexport type WarpGrepToolInput = { search_term: string };\n\n/**\n * Extended config that accepts a custom inputSchema\n */\nexport interface WarpGrepVercelConfig extends WarpGrepToolConfig {\n /**\n * Custom Zod schema or AI SDK schema. Use this to provide your own Zod instance\n * to avoid version conflicts between your project and the SDK.\n *\n * @example Using your own Zod\n * ```typescript\n * import { z } from 'zod'; // Your Zod version\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: z.object({\n * search_term: z.string().describe('Search problem statement'),\n * }),\n * });\n * ```\n *\n * @example Using jsonSchema (no Zod needed)\n * ```typescript\n * import { jsonSchema } from 'ai';\n * import { warpGrepJsonSchema } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: jsonSchema(warpGrepJsonSchema),\n * });\n * ```\n */\n inputSchema?: Parameters<typeof tool>[0]['inputSchema'];\n}\n\n/**\n * Execute warp grep search\n *\n * @param input - Tool input with search_term\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { search_term: string },\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult for convenience\nexport { formatResult };\n\n/**\n * Create Vercel AI SDK warp grep tool\n *\n * @param config - Configuration options\n * @returns Vercel AI SDK tool\n *\n * @example Local usage (uses SDK's Zod)\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({ repoRoot: '.' });\n *\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { grep: grepTool },\n * prompt: 'Find authentication middleware'\n * });\n * ```\n *\n * @example With your own Zod (avoids version conflicts)\n * ```typescript\n * import { z } from 'zod'; // Your project's Zod\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: z.object({\n * search_term: z.string().describe('Search problem statement'),\n * }),\n * });\n * ```\n *\n * @example Without Zod (using jsonSchema)\n * ```typescript\n * import { jsonSchema } from 'ai';\n * import { createWarpGrepTool, warpGrepJsonSchema } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: jsonSchema(warpGrepJsonSchema),\n * });\n * ```\n *\n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const grepTool = createWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepVercelConfig) {\n // Use provided schema or fall back to SDK's Zod schema\n const schema = config.inputSchema ?? z.object({\n search_term: z.string().describe('Search problem statement that this subagent is supposed to research for'),\n });\n\n return tool({\n description: config.description ?? WARP_GREP_DESCRIPTION,\n inputSchema: schema,\n execute: async (params: WarpGrepToolInput) => {\n // Use streaming execution to collect intermediate steps\n const steps: WarpGrepStep[] = [];\n const generator = executeToolCallStreaming(params, config);\n\n let result: WarpGrepResult;\n for (;;) {\n const { value, done } = await generator.next();\n if (done) {\n result = value;\n break;\n }\n steps.push(value);\n }\n\n if (!result!.success) {\n throw new Error(`Failed to search codebase: ${result!.error}`);\n }\n\n // Flatten all intermediate tool calls across turns for progress display\n const allToolCalls = steps.flatMap(s => s.toolCalls);\n return {\n success: true,\n contexts: result!.contexts,\n summary: result!.summary,\n progress: allToolCalls.length > 0 ? { turn: steps.length, toolCalls: allToolCalls } : undefined,\n };\n },\n });\n}\n\n/**\n * Create a GitHub search tool for Vercel AI SDK\n *\n * @param config - Configuration options (morphApiKey, morphApiUrl, codeSearchUrl, timeout)\n * @returns Vercel AI SDK tool\n *\n * @example\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createGitHubSearchTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const githubTool = createGitHubSearchTool({ morphApiKey: process.env.MORPH_API_KEY });\n *\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { githubSearch: githubTool },\n * prompt: 'How does auth work in vercel/next.js?'\n * });\n * ```\n */\nexport function createGitHubSearchTool(config: GitHubSearchToolConfig) {\n const client = new WarpGrepClient(config);\n\n return tool({\n description: GITHUB_SEARCH_DESCRIPTION,\n inputSchema: z.object({\n search_term: z.string().describe('Search problem statement that this subagent is supposed to research for'),\n github_url: z.string().optional().describe('GitHub repository URL to search (e.g. \"https://github.com/vercel/next.js\"). You must provide either github_url or owner_repo.'),\n owner_repo: z.string().optional().describe('Repository owner/repo shorthand (e.g. \"vercel/next.js\"). You must provide either github_url or owner_repo.'),\n branch: z.string().optional().describe('Branch to search (defaults to repo default branch)'),\n }),\n execute: async (params: { search_term: string; github_url?: string; owner_repo?: string; branch?: string }) => {\n const github = params.github_url || params.owner_repo;\n if (!github) {\n throw new Error('Please provide github search url or owner/repo id');\n }\n const result = await client.searchGitHub({ searchTerm: params.search_term, github, branch: params.branch });\n if (!result.success) {\n throw new Error(`GitHub search failed: ${result.error}`);\n }\n return {\n success: true,\n contexts: result.contexts,\n summary: result.summary,\n };\n },\n });\n}\n\n/**\n * Create a GitHub read file tool for Vercel AI SDK\n *\n * @param config - Optional configuration (timeout)\n * @returns Vercel AI SDK tool\n *\n * @example\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createGitHubReadFileTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const readFileTool = createGitHubReadFileTool();\n *\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { readFile: readFileTool },\n * prompt: 'Read the package.json from vercel/next.js'\n * });\n * ```\n */\nexport function createGitHubReadFileTool(config?: GitHubReadFileToolConfig) {\n return tool({\n description: GITHUB_READ_FILE_DESCRIPTION,\n inputSchema: z.object({\n github: z.string().describe('owner/repo shorthand (e.g., \"vercel/next.js\")'),\n path: z.string().describe('File path within the repository'),\n startLine: z.number().optional().describe('Start line number (1-based)'),\n endLine: z.number().optional().describe('End line number (1-based, inclusive)'),\n branch: z.string().optional().describe('Branch to read from (defaults to repo default branch)'),\n }),\n execute: async (params: GitHubReadFileInput) => {\n const result = await executeGitHubReadFile(params, config);\n if (!result.success) {\n throw new Error(`GitHub read file failed: ${result.error}`);\n }\n return result;\n },\n });\n}\n\n// Default export for convenience\nexport default createWarpGrepTool;\n","/**\n * Vercel AI SDK adapter for codebase_search tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION } from './prompts.js';\nimport type { CodebaseSearchConfig } from './types.js';\n\n/**\n * Create Vercel AI SDK codebase_search tool\n * \n * @param config - Configuration with repoId\n * @returns Vercel AI SDK tool definition (execution built-in)\n * \n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/codebase-search/vercel';\n * \n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\n * \n * const result = await generateText({\n * model: anthropic('claude-3-5-sonnet-20241022'),\n * tools: { codebaseSearch: tool },\n * prompt: \"Find authentication code\",\n * maxSteps: 5\n * });\n * \n * // Vercel AI SDK automatically executes and handles results\n * console.log(result.text);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const schema = z.object({\n query: z.string().describe('A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"'),\n target_directories: z.array(z.string()).describe('Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.'),\n explanation: z.string().describe('One sentence explanation as to why this tool is being used, and how it contributes to the goal.'),\n limit: z.number().optional().describe('Max results to return (default: 10)'),\n });\n\n return tool({\n description: CODEBASE_SEARCH_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const { query, target_directories, explanation, limit } = params;\n const result = await executeCodebaseSearch(\n { query, target_directories, explanation, limit },\n config\n );\n\n if (!result.success) {\n return {\n error: result.error,\n results: [],\n };\n }\n\n // Format results for Vercel AI SDK\n return {\n found: result.results.length,\n searchTime: `${result.stats.searchTimeMs}ms`,\n results: result.results.map(r => ({\n file: r.filepath,\n symbol: r.symbolPath,\n lines: `${r.startLine}-${r.endLine}`,\n language: r.language,\n relevance: `${(r.rerankScore * 100).toFixed(1)}%`,\n code: r.content,\n })),\n };\n },\n });\n}\n\n/**\n * Get system prompt for Vercel AI SDK\n */\nexport function getSystemPrompt(): string {\n return CODEBASE_SEARCH_DESCRIPTION;\n}\n\n/**\n * Default export\n */\nexport default { createCodebaseSearchTool, getSystemPrompt };\n\n","/**\n * Vercel AI SDK adapter for edit_file tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileConfig } from './types.js';\n\n/**\n * Vercel AI SDK tool for edit_file\n * \n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { editFileTool } from 'morphsdk/tools/vercel';\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix the bug in app.ts\"\n * });\n * ```\n */\nconst editFileSchema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n});\n\nexport const editFileTool = tool({\n description: EDIT_FILE_TOOL_DESCRIPTION,\n inputSchema: editFileSchema,\n execute: async (params) => {\n const result = await executeEditFile({\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n });\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n});\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide the model on using edit_file properly.\n * \n * @example\n * ```ts\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * system: getSystemPrompt(),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Vercel AI SDK tool with custom config\n * \n * @example\n * ```ts\n * const customEditTool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: customEditTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const schema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n });\n\n return tool({\n description: config.description || EDIT_FILE_TOOL_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const result = await executeEditFile(\n {\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n },\n config\n );\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n","/**\n * Vercel AI SDK adapter for Explore subagent\n */\n\nimport { tool, generateText, stepCountIs } from 'ai';\nimport type { LanguageModel } from 'ai';\nimport { z } from 'zod';\nimport { WarpGrepClient } from '../tools/warp_grep/client.js';\nimport { formatResult } from '../tools/warp_grep/client.js';\nimport type { WarpGrepContext } from '../tools/warp_grep/types.js';\nimport { getSystemPrompt, CODEBASE_SEARCH_TOOL, SEND_MESSAGE_TOOL } from './prompts.js';\nimport type {\n ExploreSubagentConfig,\n ExploreResult,\n ExploreStep,\n ExploreSession,\n ExploreEvent,\n SubagentMessage,\n MessageHandler,\n StepHandler,\n} from './types.js';\n\n/** Config for Vercel AI SDK Explore subagent */\nexport interface VercelExploreConfig extends ExploreSubagentConfig {\n /** Vercel AI SDK model instance */\n model: LanguageModel;\n}\n\nconst DEFAULT_MAX_TURNS: Record<string, number> = {\n quick: 3,\n medium: 6,\n thorough: 12,\n};\n\nfunction getMaxTurns(config: ExploreSubagentConfig): number {\n return config.maxTurns ?? DEFAULT_MAX_TURNS[config.thoroughness ?? 'medium'] ?? 6;\n}\n\n/**\n * Create an Explore subagent using Vercel AI SDK\n */\nexport function createExploreSubagent(config: VercelExploreConfig) {\n if (!config.repoRoot) {\n throw new Error('repoRoot is required for Explore subagent');\n }\n\n const warpGrep = new WarpGrepClient({\n morphApiKey: config.morphApiKey,\n });\n\n const thoroughness = config.thoroughness ?? 'medium';\n const replyTimeout = config.replyTimeout ?? 30_000;\n\n /** Run the agent loop and collect results */\n async function runExplore(\n prompt: string,\n callbacks: {\n onStep?: StepHandler;\n onMessage?: MessageHandler;\n } = {},\n ): Promise<ExploreResult> {\n const startTime = Date.now();\n const allContexts: WarpGrepContext[] = [];\n let searchCount = 0;\n\n const timeoutMs = config.timeout;\n const timeoutPromise = timeoutMs\n ? new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error(`Exploration timed out after ${timeoutMs}ms`)), timeoutMs),\n )\n : null;\n\n const runPromise = (async (): Promise<ExploreResult> => {\n try {\n const codebaseSearchSchema = z.object({\n searchRequest: z.string().describe('Natural language description of what to search for'),\n });\n\n const sendMessageSchema = z.object({\n message: z.string().describe('The message to send to the orchestrator'),\n });\n\n const result = await generateText({\n model: config.model,\n system: getSystemPrompt(thoroughness),\n prompt,\n tools: {\n codebase_search: tool({\n description: CODEBASE_SEARCH_TOOL.description,\n inputSchema: codebaseSearchSchema,\n execute: async (params: z.infer<typeof codebaseSearchSchema>) => {\n searchCount++;\n const warpResult = await warpGrep.execute({\n searchTerm: params.searchRequest,\n repoRoot: config.repoRoot,\n excludes: config.excludes,\n includes: config.includes,\n });\n\n if (warpResult.contexts) {\n allContexts.push(...warpResult.contexts);\n }\n\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: params.searchRequest,\n contextsFound: warpResult.contexts?.length ?? 0,\n isFinal: false,\n });\n\n return formatResult(warpResult);\n },\n }),\n send_message: tool({\n description: SEND_MESSAGE_TOOL.description,\n inputSchema: sendMessageSchema,\n execute: async (params: z.infer<typeof sendMessageSchema>) => {\n const subagentMsg: SubagentMessage = {\n from: 'explore',\n content: params.message,\n timestamp: Date.now(),\n };\n\n // Create a promise that waits for the host's reply\n const replyPromise = new Promise<string>((resolve) => {\n // Emit the message to the host via callback\n if (callbacks.onMessage) {\n callbacks.onMessage(subagentMsg, (replyText: string) => {\n resolve(replyText);\n });\n } else {\n // No handler registered, auto-resolve after timeout\n setTimeout(() => resolve(''), replyTimeout);\n }\n });\n\n // Wait for reply with timeout\n const reply = await Promise.race([\n replyPromise,\n new Promise<string>((resolve) =>\n setTimeout(() => resolve(''), replyTimeout),\n ),\n ]);\n\n if (reply) {\n return `Response from orchestrator: ${reply}`;\n }\n return 'No response. Continue with your best judgment.';\n },\n }),\n },\n stopWhen: stepCountIs(getMaxTurns(config)),\n });\n\n // Emit final step\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: '',\n contextsFound: allContexts.length,\n isFinal: true,\n });\n\n // Deduplicate contexts by file path\n const uniqueContexts = deduplicateContexts(allContexts);\n\n return {\n success: true,\n summary: result.text || 'Exploration completed but no summary was generated.',\n contexts: uniqueContexts,\n searchCount,\n durationMs: Date.now() - startTime,\n };\n } catch (error) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n })();\n\n if (timeoutPromise) {\n try {\n return await Promise.race([runPromise, timeoutPromise]);\n } catch (error) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n return runPromise;\n }\n\n const exploreToolSchema = z.object({\n searchRequest: z\n .string()\n .describe('What to explore in the codebase. Be specific about what you want to understand.'),\n });\n\n /** The Vercel AI tool for use in parent agents */\n const exploreTool = tool({\n description:\n 'Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings. Use this for broad exploration rather than pinpoint keyword searches.',\n inputSchema: exploreToolSchema,\n execute: async (params: z.infer<typeof exploreToolSchema>) => {\n const result = await runExplore(params.searchRequest);\n return {\n success: result.success,\n summary: result.summary,\n searchCount: result.searchCount,\n error: result.error,\n };\n },\n });\n\n return {\n /** Vercel AI SDK tool for use as a tool in parent agents */\n tool: exploreTool,\n\n /** Run exploration with messaging support */\n run(prompt: string): ExploreSession {\n const messageHandlers: MessageHandler[] = [];\n const stepHandlers: StepHandler[] = [];\n\n // Start the run lazily (after handlers are attached)\n let resultPromise: Promise<ExploreResult> | null = null;\n\n const session: ExploreSession = {\n on(event: string, handler: any) {\n if (event === 'message') messageHandlers.push(handler);\n if (event === 'step') stepHandlers.push(handler);\n return session;\n },\n send(_text: string) {\n // Convenience method — pause-and-ask flow uses the reply callback\n },\n get result() {\n if (!resultPromise) {\n resultPromise = runExplore(prompt, {\n onStep: (step) => {\n for (const handler of stepHandlers) handler(step);\n },\n onMessage: (msg, reply) => {\n if (messageHandlers.length > 0) {\n for (const handler of messageHandlers) handler(msg, reply);\n } else {\n // No handlers, auto-reply\n reply('');\n }\n },\n });\n }\n return resultPromise;\n },\n };\n\n return session;\n },\n\n /** Stream exploration events as an async generator */\n async *stream(prompt: string): AsyncGenerator<ExploreEvent, ExploreResult, undefined> {\n const events: ExploreEvent[] = [];\n let resolveNext: (() => void) | null = null;\n let done = false;\n\n const resultPromise = runExplore(prompt, {\n onStep: (step) => {\n events.push({\n type: 'step',\n step: step.step,\n searchRequest: step.searchRequest,\n contextsFound: step.contextsFound,\n isFinal: step.isFinal,\n });\n resolveNext?.();\n },\n onMessage: (msg, reply) => {\n events.push({\n type: 'message',\n from: msg.from,\n content: msg.content,\n timestamp: msg.timestamp,\n });\n resolveNext?.();\n // Auto-reply in streaming mode\n reply('Continue with your best judgment.');\n },\n });\n\n // Yield events as they come in\n while (!done) {\n if (events.length > 0) {\n yield events.shift()!;\n } else {\n // Check if the result is already done\n const raceResult = await Promise.race([\n resultPromise.then((r) => ({ type: 'done' as const, result: r })),\n new Promise<{ type: 'event' }>((resolve) => {\n resolveNext = () => resolve({ type: 'event' });\n }),\n ]);\n\n if (raceResult.type === 'done') {\n // Drain remaining events\n while (events.length > 0) {\n yield events.shift()!;\n }\n done = true;\n return raceResult.result;\n }\n }\n }\n\n return await resultPromise;\n },\n };\n}\n\n/** Deduplicate contexts, keeping the latest version of each file */\nfunction deduplicateContexts(contexts: WarpGrepContext[]): WarpGrepContext[] {\n const map = new Map<string, WarpGrepContext>();\n for (const ctx of contexts) {\n const existing = map.get(ctx.file);\n if (!existing || ctx.content.length > existing.content.length) {\n map.set(ctx.file, ctx);\n }\n }\n return Array.from(map.values());\n}\n","/**\n * Vercel AI SDK Tool Factory for MorphClient\n * \n * Creates Vercel AI SDK-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { LanguageModel } from 'ai';\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool, createGitHubSearchTool } from '../tools/warp_grep/vercel.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/vercel.js';\nimport { createEditFileTool } from '../tools/fastapply/vercel.js';\nimport { createExploreSubagent } from '../subagents/vercel.js';\nimport type { WarpGrepToolConfig, GitHubSearchToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\nimport type { ExploreSubagentConfig } from '../subagents/types.js';\n\n/**\n * Factory for creating Vercel AI SDK-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.vercel.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.vercel.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * \n * // Use with Vercel AI SDK\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { grep: grepTool, search: searchTool, edit: editTool },\n * prompt: 'Find and fix the bug'\n * });\n * ```\n */\nexport class VercelToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create a Vercel AI SDK-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible GitHub search tool\n *\n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createGitHubSearchTool(toolConfig?: Omit<GitHubSearchToolConfig, 'morphApiKey'>) {\n return createGitHubSearchTool({\n ...toolConfig,\n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Explore subagent that searches the codebase and returns summaries\n *\n * @param config - Subagent configuration including model (morphApiKey inherited from MorphClient)\n * @returns Explore subagent with .tool, .run(), and .stream() methods\n */\n createExploreSubagent(config: Omit<ExploreSubagentConfig, 'morphApiKey'> & { model: LanguageModel }) {\n return createExploreSubagent({\n ...config,\n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,MAAQ;AAAA,MACR,QAAU;AAAA,MACV,OAAS;AAAA,MACT,SAAW;AAAA,QACT,KAAK;AAAA,UACH,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,UAAU;AAAA,UACR,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,qBAAqB;AAAA,UACnB,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,4BAA4B;AAAA,UAC1B,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,+BAA+B;AAAA,UAC7B,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,4BAA4B;AAAA,UAC1B,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,4BAA4B;AAAA,UAC1B,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,4BAA4B;AAAA,UAC1B,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,6BAA6B;AAAA,UAC3B,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,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Q;AAAA,IACjC,CAAC;AAED,SAAK,MAAM,IAAI,SAAS;AAAA,MACtB,QAAQ,OAAO;AAAA,MACf,aAAa,OAAO;AAAA,IACtB,CAAC;AAED,SAAK,UAAU;AAAA,MACb,QAAQ,IAAI,aAAa;AAAA,QACvB,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,MACD,WAAW,IAAI,gBAAgB;AAAA,QAC7B,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,MACD,QAAQ,IAAI,aAAa;AAAA,QACvB,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,MACD,KAAK,IAAI,UAAU;AAAA,QACjB,QAAQ,OAAO;AAAA,QACf,OAAO,OAAO;AAAA,QACd,SAAS,OAAO;AAAA,QAChB,aAAa,OAAO;AAAA,MACtB,CAAC;AAAA,IACH;AAEA,UAAM,gBAAgB,IAAI,cAAc;AAAA,MACtC,aAAa,OAAO;AAAA,MACpB,SAAS,OAAO;AAAA,MAChB,aAAa,OAAO;AAAA,MACpB,OAAO,OAAO;AAAA,IAChB,CAAC;AACD,SAAK,UAAU,cAAc,QAAQ,KAAK,aAAa;AAGvD,SAAK,SAAS,IAAI,kBAAkB,MAAM;AAC1C,SAAK,YAAY,IAAI,qBAAqB,MAAM;AAChD,SAAK,SAAS,IAAI,kBAAkB,MAAM;AAAA,EAC5C;AACF;","names":["OpenAI","resolve","path","fs","import_path","fs","shouldSkip","SKIP_NAMES","SKIP_EXTENSIONS","import_promises","import_path","fs","path","applyEdit","callMorphAPI","generateUdiff","countChanges","resolve","DEFAULT_API_URL","DEFAULT_CONFIG","resolve","res","import_path","path","isValidRange","import_path","path","import_openai","import_path","DEFAULT_API_URL","OpenAI","resolve","payload","relative","path","path","LocalRipgrepProvider","DEFAULT_TIMEOUT","path","import_fs","git","fs","http","resolve","import_isomorphic_git","import_node","DEFAULT_API_URL","DEFAULT_TIMEOUT","DEFAULT_CONFIG","tool","formatResult","formatResult","formatResult","createWarpGrepTool","tool","createGitHubSearchTool","createCodebaseSearchTool","formatResult","editFileTool","formatResult","createEditFileTool","getSystemPrompt","getSystemPrompt","resolve","createWarpGrepTool","createCodebaseSearchTool","createEditFileTool","createGitHubSearchTool","createWarpGrepTool","createGitHubSearchTool","import_ai","import_zod","createCodebaseSearchTool","import_ai","import_zod","editFileTool","createEditFileTool","import_ai","import_zod","DEFAULT_MAX_TURNS","getMaxTurns","createExploreSubagent","getSystemPrompt","resolve","deduplicateContexts","createWarpGrepTool","createCodebaseSearchTool","createEditFileTool","createGitHubSearchTool","createExploreSubagent"]}
1
+ {"version":3,"sources":["../package.json","../version.ts","../tools/fastapply/apply.ts","../tools/warp_grep/agent/config.ts","../tools/warp_grep/utils/ripgrep.ts","../tools/warp_grep/utils/paths.ts","../tools/warp_grep/utils/files.ts","../tools/warp_grep/providers/local.ts","../client.ts","../tools/fastapply/core.ts","../tools/utils/resilience.ts","../tools/codebase_search/core.ts","../tools/browser/live.ts","../tools/browser/errors.ts","../tools/browser/profiles/types.ts","../tools/browser/profiles/core.ts","../tools/browser/core.ts","../tools/warp_grep/agent/runner.ts","../tools/warp_grep/agent/parser.ts","../tools/warp_grep/agent/tools/grep.ts","../tools/warp_grep/agent/tools/read.ts","../tools/warp_grep/agent/tools/list_directory.ts","../tools/warp_grep/agent/tools/glob.ts","../tools/warp_grep/agent/tools/finish.ts","../tools/warp_grep/agent/helpers.ts","../tools/warp_grep/providers/remote.ts","../tools/warp_grep/providers/code_storage_http.ts","../tools/warp_grep/utils/github.ts","../tools/warp_grep/client.ts","../tools/github/types.ts","../tools/github/core.ts","../git/client.ts","../git/index.ts","../tools/compact/core.ts","../modelrouter/core.ts","../tools/warp_grep/prompts.ts","../tools/warp_grep/openai.ts","../tools/codebase_search/prompts.ts","../tools/codebase_search/openai.ts","../tools/fastapply/prompts.ts","../tools/fastapply/openai.ts","../factories/openai.ts","../tools/warp_grep/anthropic.ts","../tools/codebase_search/anthropic.ts","../tools/fastapply/anthropic.ts","../subagents/prompts.ts","../subagents/anthropic.ts","../factories/anthropic.ts","../tools/warp_grep/vercel.ts","../tools/codebase_search/vercel.ts","../tools/fastapply/vercel.ts","../subagents/vercel.ts","../factories/vercel.ts"],"sourcesContent":["{\n \"name\": \"@morphllm/morphsdk\",\n \"version\": \"0.2.152\",\n \"description\": \"TypeScript SDK and CLI for Morph Fast Apply integration\",\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./edge\": {\n \"types\": \"./dist/edge.d.ts\",\n \"import\": \"./dist/edge.js\",\n \"require\": \"./dist/edge.cjs\"\n },\n \"./tools/warp-grep\": {\n \"types\": \"./dist/tools/warp_grep/index.d.ts\",\n \"import\": \"./dist/tools/warp_grep/index.js\",\n \"require\": \"./dist/tools/warp_grep/index.cjs\"\n },\n \"./tools/warp-grep/openai\": {\n \"types\": \"./dist/tools/warp_grep/openai.d.ts\",\n \"import\": \"./dist/tools/warp_grep/openai.js\",\n \"require\": \"./dist/tools/warp_grep/openai.cjs\"\n },\n \"./tools/warp-grep/anthropic\": {\n \"types\": \"./dist/tools/warp_grep/anthropic.d.ts\",\n \"import\": \"./dist/tools/warp_grep/anthropic.js\",\n \"require\": \"./dist/tools/warp_grep/anthropic.cjs\"\n },\n \"./tools/warp-grep/vercel\": {\n \"types\": \"./dist/tools/warp_grep/vercel.d.ts\",\n \"import\": \"./dist/tools/warp_grep/vercel.js\",\n \"require\": \"./dist/tools/warp_grep/vercel.cjs\"\n },\n \"./tools/warp-grep/client\": {\n \"types\": \"./dist/tools/warp_grep/client.d.ts\",\n \"import\": \"./dist/tools/warp_grep/client.js\",\n \"require\": \"./dist/tools/warp_grep/client.cjs\"\n },\n \"./tools/warp-grep/gemini\": {\n \"types\": \"./dist/tools/warp_grep/gemini.d.ts\",\n \"import\": \"./dist/tools/warp_grep/gemini.js\",\n \"require\": \"./dist/tools/warp_grep/gemini.cjs\"\n },\n \"./tools/warp-grep/harness\": {\n \"types\": \"./dist/tools/warp_grep/harness.d.ts\",\n \"import\": \"./dist/tools/warp_grep/harness.js\",\n \"require\": \"./dist/tools/warp_grep/harness.cjs\"\n },\n \"./tools/fastapply\": {\n \"types\": \"./dist/tools/fastapply/index.d.ts\",\n \"import\": \"./dist/tools/fastapply/index.js\",\n \"require\": \"./dist/tools/fastapply/index.cjs\"\n },\n \"./tools/fastapply/anthropic\": {\n \"types\": \"./dist/tools/fastapply/anthropic.d.ts\",\n \"import\": \"./dist/tools/fastapply/anthropic.js\",\n \"require\": \"./dist/tools/fastapply/anthropic.cjs\"\n },\n \"./tools/fastapply/openai\": {\n \"types\": \"./dist/tools/fastapply/openai.d.ts\",\n \"import\": \"./dist/tools/fastapply/openai.js\",\n \"require\": \"./dist/tools/fastapply/openai.cjs\"\n },\n \"./tools/fastapply/vercel\": {\n \"types\": \"./dist/tools/fastapply/vercel.d.ts\",\n \"import\": \"./dist/tools/fastapply/vercel.js\",\n \"require\": \"./dist/tools/fastapply/vercel.cjs\"\n },\n \"./tools/codebase-search\": {\n \"types\": \"./dist/tools/codebase_search/index.d.ts\",\n \"import\": \"./dist/tools/codebase_search/index.js\",\n \"require\": \"./dist/tools/codebase_search/index.cjs\"\n },\n \"./tools/codebase-search/anthropic\": {\n \"types\": \"./dist/tools/codebase_search/anthropic.d.ts\",\n \"import\": \"./dist/tools/codebase_search/anthropic.js\",\n \"require\": \"./dist/tools/codebase_search/anthropic.cjs\"\n },\n \"./tools/codebase-search/openai\": {\n \"types\": \"./dist/tools/codebase_search/openai.d.ts\",\n \"import\": \"./dist/tools/codebase_search/openai.js\",\n \"require\": \"./dist/tools/codebase_search/openai.cjs\"\n },\n \"./tools/codebase-search/vercel\": {\n \"types\": \"./dist/tools/codebase_search/vercel.d.ts\",\n \"import\": \"./dist/tools/codebase_search/vercel.js\",\n \"require\": \"./dist/tools/codebase_search/vercel.cjs\"\n },\n \"./tools/git\": {\n \"types\": \"./dist/git/index.d.ts\",\n \"import\": \"./dist/git/index.js\",\n \"require\": \"./dist/git/index.cjs\"\n },\n \"./tools/browser\": {\n \"types\": \"./dist/tools/browser/index.d.ts\",\n \"import\": \"./dist/tools/browser/index.js\",\n \"require\": \"./dist/tools/browser/index.cjs\"\n },\n \"./tools/browser/anthropic\": {\n \"types\": \"./dist/tools/browser/anthropic.d.ts\",\n \"import\": \"./dist/tools/browser/anthropic.js\",\n \"require\": \"./dist/tools/browser/anthropic.cjs\"\n },\n \"./tools/browser/openai\": {\n \"types\": \"./dist/tools/browser/openai.d.ts\",\n \"import\": \"./dist/tools/browser/openai.js\",\n \"require\": \"./dist/tools/browser/openai.cjs\"\n },\n \"./tools/browser/vercel\": {\n \"types\": \"./dist/tools/browser/vercel.d.ts\",\n \"import\": \"./dist/tools/browser/vercel.js\",\n \"require\": \"./dist/tools/browser/vercel.cjs\"\n },\n \"./tools/browser/profiles\": {\n \"types\": \"./dist/tools/browser/profiles/index.d.ts\",\n \"import\": \"./dist/tools/browser/profiles/index.js\",\n \"require\": \"./dist/tools/browser/profiles/index.cjs\"\n },\n \"./modelrouter\": {\n \"types\": \"./dist/modelrouter/index.d.ts\",\n \"import\": \"./dist/modelrouter/index.js\",\n \"require\": \"./dist/modelrouter/index.cjs\"\n },\n \"./tools/compact\": {\n \"types\": \"./dist/tools/compact/index.d.ts\",\n \"import\": \"./dist/tools/compact/index.js\",\n \"require\": \"./dist/tools/compact/index.cjs\"\n },\n \"./subagents\": {\n \"types\": \"./dist/subagents/index.d.ts\",\n \"import\": \"./dist/subagents/index.js\",\n \"require\": \"./dist/subagents/index.cjs\"\n },\n \"./subagents/vercel\": {\n \"types\": \"./dist/subagents/vercel.d.ts\",\n \"import\": \"./dist/subagents/vercel.js\",\n \"require\": \"./dist/subagents/vercel.cjs\"\n },\n \"./subagents/anthropic\": {\n \"types\": \"./dist/subagents/anthropic.d.ts\",\n \"import\": \"./dist/subagents/anthropic.js\",\n \"require\": \"./dist/subagents/anthropic.cjs\"\n }\n },\n \"files\": [\n \"dist/**/*.js\",\n \"dist/**/*.cjs\",\n \"dist/**/*.d.ts\",\n \"dist/**/*.map\",\n \"!dist/**/__tests__/**\",\n \"!dist/**/*.test.*\"\n ],\n \"scripts\": {\n \"build\": \"tsup version.ts index.ts edge.ts client.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 git/index.ts git/client.ts git/config.ts git/types.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 --format esm,cjs --sourcemap --clean --dts --dts-resolve\",\n \"prepare\": \"npm run build\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest watch\",\n \"test:anthropic\": \"vitest run anthropic\",\n \"test:openai\": \"vitest run openai\",\n \"test:vercel\": \"vitest run vercel\",\n \"test:git\": \"vitest run git\",\n \"test:browser\": \"vitest run browser\",\n \"test:agent\": \"npx tsx tests/fullAgentTest.ts\",\n \"test:integration\": \"npx tsx tests/fullIntegrationTest.ts\",\n \"release:patch\": \"npm version patch && npm publish\",\n \"release:minor\": \"npm version minor && npm publish\",\n \"release:major\": \"npm version major && npm publish\"\n },\n \"keywords\": [\n \"morph\",\n \"fast-apply\",\n \"cli\",\n \"sdk\",\n \"edit-file\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@vscode/ripgrep\": \"^1.17.0\",\n \"ai\": \">=5.0.0\",\n \"diff\": \"^7.0.0\",\n \"isomorphic-git\": \"^1.25.10\",\n \"openai\": \"^4.52.7\",\n \"zod\": \">=3.23.0\"\n },\n \"devDependencies\": {\n \"@ai-sdk/anthropic\": \"^2.0.70\",\n \"@ai-sdk/openai\": \"^2.0.35\",\n \"@anthropic-ai/sdk\": \"^0.30.1\",\n \"@google/generative-ai\": \"^0.24.1\",\n \"@types/diff\": \"^7.0.2\",\n \"@types/node\": \"^20.14.10\",\n \"@typescript-eslint/eslint-plugin\": \"^7.18.0\",\n \"@typescript-eslint/parser\": \"^7.18.0\",\n \"dotenv\": \"^16.4.5\",\n \"eslint\": \"^8.57.0\",\n \"shx\": \"^0.3.4\",\n \"tsup\": \"^8.5.0\",\n \"tsx\": \"^4.16.2\",\n \"typescript\": \"^5.5.4\",\n \"vitest\": \"^2.1.6\"\n },\n \"peerDependencies\": {\n \"@anthropic-ai/sdk\": \">=0.25.0\",\n \"@google/generative-ai\": \">=0.21.0\",\n \"ai\": \">=5.0.0\",\n \"zod\": \">=3.23.0\"\n },\n \"peerDependenciesMeta\": {\n \"@anthropic-ai/sdk\": {\n \"optional\": true\n },\n \"@google/generative-ai\": {\n \"optional\": true\n },\n \"ai\": {\n \"optional\": true\n },\n \"zod\": {\n \"optional\": true\n }\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","import pkg from './package.json' with { type: 'json' };\nexport const SDK_VERSION: string = pkg.version;\n","/**\n * Edge-compatible code application API\n *\n * This module works on:\n * - Node.js\n * - Cloudflare Workers\n * - Vercel Edge Functions\n * - Deno Deploy\n * - Browser environments\n *\n * For file-based operations, use executeEditFile from core.ts\n */\n\nimport { createTwoFilesPatch } from 'diff';\nimport OpenAI from 'openai';\nimport { SDK_VERSION } from '../../version.js';\nimport type {\n EditChanges,\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n} from './types.js';\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\nconst DEFAULT_TIMEOUT = 30000;\n\n/**\n * Generate a unified diff between two strings\n */\nexport function generateUdiff(\n original: string,\n modified: string,\n filepath: string\n): string {\n return createTwoFilesPatch(\n filepath,\n filepath,\n original,\n modified,\n 'Original',\n 'Modified'\n );\n}\n\n/**\n * Count changes from a unified diff\n */\nexport function countChanges(original: string, modified: string): EditChanges {\n const diff = generateUdiff(original, modified, 'file');\n const lines = diff.split('\\n');\n\n let linesAdded = 0;\n let linesRemoved = 0;\n\n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n linesAdded++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n linesRemoved++;\n }\n }\n\n const linesModified = Math.min(linesAdded, linesRemoved);\n\n return {\n linesAdded: linesAdded - linesModified,\n linesRemoved: linesRemoved - linesModified,\n linesModified,\n };\n}\n\n/**\n * Call Morph Apply API to merge code edits\n * Uses OpenAI SDK for reliable connection handling, retries, and timeouts\n */\nexport async function callMorphAPI(\n originalCode: string,\n codeEdit: string,\n instructions: string,\n filepath: string,\n config: ApplyEditConfig\n): Promise<{ content: string; completionId?: string }> {\n const apiKey = config.morphApiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n const apiUrl = config.morphApiUrl || DEFAULT_API_URL;\n const timeout = config.timeout || DEFAULT_TIMEOUT;\n const debug = config.debug || false;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n\n // Format message with XML tags as per Morph Fast Apply spec\n const message = `<instruction>${instructions}</instruction>\\n<code>${originalCode}</code>\\n<update>${codeEdit}</update>`;\n\n if (debug) {\n console.log(`[FastApply] Calling ${apiUrl}/v1/chat/completions`);\n console.log(`[FastApply] File: ${filepath}, Instructions: ${instructions.slice(0, 60)}...`);\n console.log(`[FastApply] Original: ${originalCode.length} chars, Edit: ${codeEdit.length} chars`);\n }\n\n const startTime = Date.now();\n\n const client = new OpenAI({\n apiKey,\n baseURL: `${apiUrl}/v1`,\n timeout,\n maxRetries: config.retryConfig?.maxRetries ?? 3,\n defaultHeaders: { 'X-Morph-SDK-Version': SDK_VERSION },\n });\n\n const completion = await client.chat.completions.create({\n model: 'morph-v3-fast',\n messages: [{ role: 'user', content: message }],\n });\n\n const content = completion.choices[0]?.message?.content;\n if (!content) {\n throw new Error('Morph API returned empty response');\n }\n\n const elapsed = Date.now() - startTime;\n\n if (debug) {\n console.log(`[FastApply] Success in ${elapsed}ms, merged: ${content.length} chars`);\n }\n\n return { content, completionId: completion.id };\n}\n\n/**\n * Apply an edit to code directly without file I/O\n *\n * This is the edge-compatible code-in/code-out API that accepts code content directly\n * and returns the merged result without reading or writing any files.\n *\n * Works on Cloudflare Workers, Vercel Edge Functions, Deno, and browsers.\n *\n * @param input - Code and edit parameters\n * @param config - Optional configuration\n * @returns Result with merged code\n *\n * @example\n * ```typescript\n * import { applyEdit } from '@morphllm/morphsdk';\n *\n * const result = await applyEdit({\n * originalCode: fs.readFileSync('file.ts', 'utf-8'),\n * codeEdit: '// ... existing code ...\\nconst newVar = 42;\\n// ... existing code ...',\n * instructions: 'Add a new variable',\n * filepath: 'file.ts' // optional, for udiff context\n * });\n *\n * if (result.success) {\n * fs.writeFileSync('file.ts', result.mergedCode);\n * }\n * ```\n */\nexport async function applyEdit(\n input: ApplyEditInput,\n config: ApplyEditConfig = {}\n): Promise<ApplyEditResult> {\n const debug = config.debug || false;\n const filepath = input.filepath || 'file';\n\n try {\n if (debug) {\n console.log(`[FastApply] Applying edit to code (${input.originalCode.length} chars)`);\n }\n\n const { content: mergedCode, completionId } = await callMorphAPI(\n input.originalCode,\n input.codeEdit,\n input.instructions,\n filepath,\n config\n );\n\n const udiff = config.generateUdiff !== false\n ? generateUdiff(input.originalCode, mergedCode, filepath)\n : undefined;\n\n const changes = countChanges(input.originalCode, mergedCode);\n\n return {\n success: true,\n mergedCode,\n udiff,\n changes,\n completionId,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n if (debug) console.error(`[FastApply] Error: ${errorMessage}`);\n\n return {\n success: false,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\n}\n","// Parse timeout from env, defaulting to 30 seconds\nconst parseEnvTimeout = (envValue: string | undefined, defaultMs: number): number => {\n if (!envValue) return defaultMs;\n const parsed = parseInt(envValue, 10);\n return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;\n};\n\nexport const AGENT_CONFIG = {\n MAX_TURNS: 6,\n /** Default timeout for model calls. Can be overridden via MORPH_WARP_GREP_TIMEOUT env var (in ms) */\n TIMEOUT_MS: parseEnvTimeout(process.env.MORPH_WARP_GREP_TIMEOUT, 30_000),\n MAX_CONTEXT_CHARS: 321_600,\n MAX_OUTPUT_LINES: 200,\n MAX_LIST_RESULTS: 500,\n MAX_READ_LINES: 800,\n MAX_LIST_DEPTH: 3,\n LIST_TIMEOUT_MS: 2_000,\n};\n\n/**\n * Comprehensive exclusion list for directories and files\n * These patterns are used with ripgrep's -g flag\n */\nconst BUILTIN_EXCLUDES = [\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n \n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'packages', 'Pods', '.bundle',\n \n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs', '*.egg-info',\n \n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n \n // Cache directories\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n \n // IDE/Editor\n '.idea', '.vscode', '.vs',\n \n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n \n // Temporary\n 'tmp', 'temp', '.tmp', '.temp',\n \n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n \n // Binary/minified\n '*.min.js', '*.min.css', '*.bundle.js',\n '*.wasm', '*.so', '*.dll', '*.pyc',\n '*.map', '*.js.map',\n \n // Hidden directories catch-all\n '.*',\n];\n\nexport const DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || '')\n .split(',')\n .map(s => s.trim())\n .filter(Boolean)\n .concat(BUILTIN_EXCLUDES);\n\nexport const DEFAULT_MODEL = 'morph-warp-grep-v2.1';\n","import { spawn } from 'child_process';\nimport { rgPath } from '@vscode/ripgrep';\n\nexport type ExecResult = { stdout: string; stderr: string; exitCode: number };\n\n// Cache the working ripgrep path to avoid repeated fallback checks\nlet resolvedRgPath: string | null = null;\nlet rgPathChecked = false;\n\nfunction spawnRg(rgBinary: string, args: string[], opts?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult> {\n return new Promise((resolve) => {\n const child = spawn(rgBinary, args, {\n cwd: opts?.cwd,\n env: { ...process.env, ...(opts?.env || {}) },\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (d) => (stdout += d.toString()));\n child.stderr.on('data', (d) => (stderr += d.toString()));\n child.on('close', (code) => {\n resolve({ stdout, stderr, exitCode: typeof code === 'number' ? code : -1 });\n });\n child.on('error', () => {\n resolve({ stdout: '', stderr: 'Failed to spawn ripgrep.', exitCode: -1 });\n });\n });\n}\n\n// Check if a result indicates a binary compatibility failure (not a normal rg error)\nfunction isBinaryFailure(result: ExecResult): boolean {\n // Spawn error\n if (result.exitCode === -1) return true;\n // jemalloc page size issue (common on ARM64 with non-standard page sizes)\n if (result.stderr.includes('jemalloc') || result.stderr.includes('Unsupported system page size')) return true;\n // SIGABRT (134 = 128 + 6)\n if (result.exitCode === 134) return true;\n return false;\n}\n\nexport async function runRipgrep(args: string[], opts?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult> {\n // If we've already determined the working path, use it\n if (rgPathChecked && resolvedRgPath) {\n return spawnRg(resolvedRgPath, args, opts);\n }\n\n // First attempt: bundled ripgrep\n if (!rgPathChecked) {\n const result = await spawnRg(rgPath, args, opts);\n \n if (!isBinaryFailure(result)) {\n // Bundled binary works, cache it\n resolvedRgPath = rgPath;\n rgPathChecked = true;\n return result;\n }\n\n // Bundled binary failed, try system rg\n const fallbackResult = await spawnRg('rg', args, opts);\n \n if (!isBinaryFailure(fallbackResult)) {\n // System rg works, cache it\n resolvedRgPath = 'rg';\n rgPathChecked = true;\n return fallbackResult;\n }\n\n // Neither works, mark as checked and return the original error\n rgPathChecked = true;\n return { \n stdout: '', \n stderr: 'Failed to spawn ripgrep. Neither bundled nor system rg is available.', \n exitCode: -1 \n };\n }\n\n // rgPathChecked is true but resolvedRgPath is null - no working rg found\n return { \n stdout: '', \n stderr: 'Failed to spawn ripgrep. Neither bundled nor system rg is available.', \n exitCode: -1 \n };\n}\n\n\n","import fs from 'fs';\nimport path from 'path';\n\nexport function resolveUnderRepo(repoRoot: string, targetPath: string): string {\n const absRoot = path.resolve(repoRoot);\n const resolved = path.resolve(absRoot, targetPath);\n ensureWithinRepo(absRoot, resolved);\n return resolved;\n}\n\nexport function ensureWithinRepo(repoRoot: string, absTarget: string): void {\n const rel = path.relative(path.resolve(repoRoot), path.resolve(absTarget));\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path outside repository root: ${absTarget}`);\n }\n}\n\nexport function toRepoRelative(repoRoot: string, absPath: string): string {\n return path.relative(path.resolve(repoRoot), path.resolve(absPath));\n}\n\nexport function isSymlink(p: string): boolean {\n try {\n const st = fs.lstatSync(p);\n return st.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\n/**\n * Detects and removes consecutive duplicate path segments.\n *\n * When the model predicts a path that includes the repo directory name,\n * joining with repoRoot creates duplication:\n * repoRoot=\"/Users/dhruv/repo\" + predicted=\"repo/src/file.ts\"\n * → \"/Users/dhruv/repo/repo/src/file.ts\"\n *\n * This function detects such patterns and returns the corrected path,\n * or null if no duplication is found.\n */\nexport function fixPathRepetition(fullPath: string): string | null {\n const segments = fullPath.split(path.sep).filter(Boolean);\n if (segments.length < 2) return null;\n\n for (let len = Math.floor(segments.length / 2); len >= 1; len--) {\n for (let i = 0; i <= segments.length - 2 * len; i++) {\n const first = segments.slice(i, i + len);\n const second = segments.slice(i + len, i + 2 * len);\n\n if (first.every((seg, idx) => seg === second[idx])) {\n const fixed = [...segments.slice(0, i), ...segments.slice(i + len)];\n return path.sep + fixed.join(path.sep);\n }\n }\n }\n\n return null;\n}\n\nexport function isTextualFile(filePath: string, maxBytes = 2_000_000): boolean {\n try {\n const st = fs.statSync(filePath);\n if (!st.isFile()) return false;\n if (st.size > maxBytes) return false;\n const fd = fs.openSync(filePath, 'r');\n const buf = Buffer.alloc(512);\n const read = fs.readSync(fd, buf, 0, buf.length, 0);\n fs.closeSync(fd);\n for (let i = 0; i < read; i++) {\n const c = buf[i];\n if (c === 0) return false; // binary heuristic\n }\n return true;\n } catch {\n return false;\n }\n}\n\n\n","import fs from 'fs/promises';\n\nexport async function readAllLines(filePath: string): Promise<string[]> {\n const content = await fs.readFile(filePath, 'utf8');\n // Preserve newlines; split keeping consistency\n return content.split(/\\r?\\n/);\n}\n\n\n","import fs from 'fs/promises';\nimport fssync from 'fs';\nimport path from 'path';\nimport { runRipgrep } from '../utils/ripgrep.js';\nimport { ensureWithinRepo, resolveUnderRepo, toRepoRelative, isSymlink, isTextualFile, fixPathRepetition } from '../utils/paths.js';\nimport type { WarpGrepProvider, GrepResult, ReadResult, GlobResult, ListDirectoryEntry } from './types.js';\nimport { readAllLines } from '../utils/files.js';\nimport { DEFAULT_EXCLUDES, AGENT_CONFIG } from '../agent/config.js';\n\n/**\n * Directories/files to always skip (exact name match)\n */\nconst SKIP_NAMES = new Set([\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'Pods', '.bundle',\n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs',\n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n // Cache\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n // IDE\n '.idea', '.vscode', '.vs',\n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n // Temp\n 'tmp', 'temp', '.tmp', '.temp',\n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n]);\n\n/**\n * File extensions to skip\n */\n\nconst SKIP_EXTENSIONS = new Set([\n '.min.js', '.min.css', '.bundle.js',\n '.wasm', '.so', '.dll', '.pyc',\n '.map', '.js.map',\n]);\n\n/**\n * Check if a filename should be skipped\n */\nfunction shouldSkip(name: string, allowNames?: Set<string>): boolean {\n // Allow explicitly permitted names through\n if (allowNames?.has(name)) return false;\n\n // Skip exact name matches\n if (SKIP_NAMES.has(name)) return true;\n\n // Skip hidden files/directories (start with .)\n if (name.startsWith('.')) return true;\n\n // Skip files with certain extensions\n for (const ext of SKIP_EXTENSIONS) {\n if (name.endsWith(ext)) return true;\n }\n\n return false;\n}\n\nexport class LocalRipgrepProvider implements WarpGrepProvider {\n private readonly allowNames?: Set<string>;\n\n constructor(\n private readonly repoRoot: string,\n private readonly excludes: string[] = DEFAULT_EXCLUDES,\n options?: { allowNames?: string[] },\n ) {\n if (options?.allowNames?.length) {\n this.allowNames = new Set(options.allowNames);\n }\n }\n\n async grep(params: { pattern: string; path: string; glob?: string; context_lines?: number; case_sensitive?: boolean }): Promise<GrepResult> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch (err) {\n return {\n lines: [],\n error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat) return { lines: [] };\n const targetArg = abs === path.resolve(this.repoRoot) ? '.' : toRepoRelative(this.repoRoot, abs);\n const contextLines = params.context_lines !== undefined ? String(params.context_lines) : '1';\n const args = [\n '--no-config',\n '--no-heading',\n '--with-filename',\n '--line-number',\n '--color=never',\n '--trim',\n '--max-columns=400',\n '-C', contextLines,\n ...(params.case_sensitive === false ? ['--ignore-case'] : []),\n ...(params.glob ? ['--glob', params.glob] : []),\n ...this.excludes.filter(e => !this.allowNames?.has(e)).flatMap((e) => ['-g', `!${e}`]),\n params.pattern,\n targetArg || '.',\n ];\n const res = await runRipgrep(args, { cwd: this.repoRoot });\n \n // Gracefully handle ripgrep not being available\n if (res.exitCode === -1) {\n return {\n lines: [],\n error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required but failed to execute. Please install it:\\n` +\n ` • macOS: brew install ripgrep\\n` +\n ` • Ubuntu/Debian: apt install ripgrep\\n` +\n ` • Windows: choco install ripgrep\\n` +\n ` • Or visit: https://github.com/BurntSushi/ripgrep#installation\\n` +\n `Exit code: ${res.exitCode}${res.stderr ? `\\nDetails: ${res.stderr}` : ''}`,\n };\n }\n \n // Handle other ripgrep errors gracefully\n if (res.exitCode !== 0 && res.exitCode !== 1) {\n return {\n lines: [],\n error: `[RIPGREP ERROR] grep failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ''}`,\n };\n }\n \n const lines = (res.stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((l) => l.length > 0);\n if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {\n const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines };\n }\n\n async read(params: { path: string; start?: number; end?: number }): Promise<ReadResult> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch (err) {\n return {\n lines: [],\n error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n let stat = await fs.stat(abs).catch(() => null);\n\n // Handle duplicate path segments from model predictions\n if (!stat || !stat.isFile()) {\n const fixedPath = fixPathRepetition(abs);\n if (fixedPath) {\n const fixedStat = await fs.stat(fixedPath).catch(() => null);\n if (fixedStat?.isFile()) {\n abs = fixedPath;\n stat = fixedStat;\n }\n }\n }\n\n // Gracefully handle file not found / not a file\n if (!stat || !stat.isFile()) {\n return {\n lines: [],\n error: `[FILE NOT FOUND] You tried to read \"${params.path}\" but there is no file at this path. ` +\n `Double-check the path exists and is spelled correctly.`,\n };\n }\n \n // Gracefully handle symlinks\n if (isSymlink(abs)) {\n return {\n lines: [],\n error: `[SYMLINK] You tried to read \"${params.path}\" but this is a symlink. ` +\n `Try reading the actual file it points to instead.`,\n };\n }\n \n // Gracefully handle non-text or too-large files\n if (!isTextualFile(abs)) {\n return {\n lines: [],\n error: `[UNREADABLE FILE] You tried to read \"${params.path}\" but this file is either too large ` +\n `or not a text file, so it cannot be read. Try a different file.`,\n };\n }\n \n let lines: string[];\n try {\n lines = await readAllLines(abs);\n } catch (err) {\n return {\n lines: [],\n error: `[READ ERROR] Failed to read \"${params.path}\": ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n const total = lines.length;\n const rawStart = params.start;\n const rawEnd = params.end;\n \n let s = 1;\n let e = total;\n \n const startValid = rawStart === undefined || (Number.isFinite(rawStart) && rawStart > 0);\n const endValid = rawEnd === undefined || (Number.isFinite(rawEnd) && rawEnd > 0);\n \n if (startValid && endValid) {\n s = rawStart ?? 1;\n e = Math.min(rawEnd ?? total, total);\n if ((s > total && total > 0) || (s > e)) {\n s = 1;\n e = total;\n }\n }\n const out: string[] = [];\n for (let i = s; i <= e; i += 1) {\n const content = lines[i - 1] ?? '';\n out.push(`${i}|${content}`);\n }\n if (out.length > AGENT_CONFIG.MAX_READ_LINES) {\n const truncated = out.slice(0, AGENT_CONFIG.MAX_READ_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${out.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines: out };\n }\n\n async listDirectory(params: { path: string; pattern?: string | null; maxResults?: number; maxDepth?: number }): Promise<ListDirectoryEntry[]> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch {\n // Path outside repo - return empty (graceful failure)\n return [];\n }\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat || !stat.isDirectory()) {\n return [];\n }\n const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;\n const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n const regex = params.pattern ? new RegExp(params.pattern) : null;\n const repoRoot = this.repoRoot;\n const allowNames = this.allowNames;\n\n const results: ListDirectoryEntry[] = [];\n let timedOut = false;\n const startTime = Date.now();\n\n async function walk(dir: string, depth: number) {\n if (Date.now() - startTime > AGENT_CONFIG.LIST_TIMEOUT_MS) {\n timedOut = true;\n return;\n }\n if (depth > maxDepth || results.length >= maxResults) return;\n let entries: import('fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return; // skip unreadable directories (ENOENT, EACCES, etc.)\n }\n for (const entry of entries) {\n if (timedOut || results.length >= maxResults) break;\n\n // Simple name-based filtering - skip junk dirs/files\n if (shouldSkip(entry.name, allowNames)) continue;\n \n // Apply user-provided pattern filter\n if (regex && !regex.test(entry.name)) continue;\n \n const full = path.join(dir, entry.name);\n const isDir = entry.isDirectory();\n \n results.push({\n name: entry.name,\n path: toRepoRelative(repoRoot, full),\n type: isDir ? 'dir' : 'file',\n depth,\n });\n if (isDir) {\n await walk(full, depth + 1);\n }\n }\n }\n await walk(abs, 0);\n return results;\n }\n\n async glob(params: { pattern: string; path?: string }): Promise<GlobResult> {\n let abs: string;\n try {\n abs = params.path ? resolveUnderRepo(this.repoRoot, params.path) : this.repoRoot;\n } catch (err) {\n return { files: [], searchDir: this.repoRoot, totalFound: 0, error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}` };\n }\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat || !stat.isDirectory()) {\n return { files: [], searchDir: abs, totalFound: 0, error: `[PATH ERROR] Directory not found: ${params.path || '.'}` };\n }\n\n const targetArg = abs === path.resolve(this.repoRoot) ? '.' : toRepoRelative(this.repoRoot, abs);\n const args = [\n '--no-config',\n '--files',\n '--color=never',\n '-g', params.pattern,\n ...this.excludes.filter(e => !this.allowNames?.has(e)).flatMap(e => ['-g', `!${e}`]),\n targetArg || '.',\n ];\n\n const res = await runRipgrep(args, { cwd: this.repoRoot });\n if (res.exitCode === -1) {\n return { files: [], searchDir: abs, totalFound: 0, error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required for glob search.` };\n }\n if (res.exitCode !== 0 && res.exitCode !== 1) {\n return { files: [], searchDir: abs, totalFound: 0, error: `[GLOB ERROR] glob failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ''}` };\n }\n\n // Convert to absolute paths\n const absRoot = path.resolve(this.repoRoot);\n const relFiles = (res.stdout || '').trim().split(/\\r?\\n/).filter(l => l.length > 0);\n const absFiles = relFiles.map(f => path.resolve(absRoot, f));\n\n // Sort by mtime descending (newest first), matching training format\n const withMtime: Array<{ file: string; mtime: number }> = [];\n for (const f of absFiles) {\n const s = await fs.stat(f).catch(() => null);\n withMtime.push({ file: f, mtime: s?.mtimeMs ?? 0 });\n }\n withMtime.sort((a, b) => b.mtime - a.mtime);\n\n const totalFound = withMtime.length;\n return { files: withMtime.slice(0, 100).map(f => f.file), searchDir: abs, totalFound };\n }\n}\n","/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface\n * \n * @example\n * ```typescript\n * import { MorphClient } from '@morphllm/morphsdk';\n * \n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * \n * // Direct execution\n * await morph.fastApply.execute({ target_filepath: 'src/index.ts', ... });\n * await morph.warpGrep.execute({ query: 'Find auth', repoRoot: '.' });\n * await morph.codebaseSearch.search({ query: 'auth logic', repoId: 'x' });\n * \n * // Tool creation for AI agents (API key inherited)\n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.anthropic.createCodebaseSearchTool({ repoId: 'x' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * \n * // Use tools with OpenAI\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [grepTool],\n * messages: [{ role: 'user', content: 'Find the bug' }]\n * });\n * ```\n */\n\nimport type { RetryConfig } from './tools/utils/resilience.js';\nimport { FastApplyClient } from './tools/fastapply/core.js';\nimport { CodebaseSearchClient } from './tools/codebase_search/core.js';\nimport { BrowserClient } from './tools/browser/core.js';\nimport { WarpGrepClient } from './tools/warp_grep/client.js';\nimport { GitHubClient } from './tools/github/core.js';\nimport { MorphGit } from './git/index.js';\nimport { CompactClient } from './tools/compact/core.js';\nimport { OpenAIRouter, AnthropicRouter, GeminiRouter, RawRouter } from './modelrouter/core.js';\nimport { OpenAIToolFactory, AnthropicToolFactory, VercelToolFactory } from './factories/index.js';\n\n/**\n * Configuration for the MorphClient\n */\nexport interface MorphClientConfig {\n /** Morph API key for authentication (defaults to MORPH_API_KEY env var) */\n apiKey?: string;\n /** Enable debug logging across all tools */\n debug?: boolean;\n /** Default timeout in milliseconds for API requests */\n timeout?: number;\n /** Retry configuration for failed requests */\n retryConfig?: RetryConfig;\n /** GitHub-specific configuration */\n github?: {\n /** Default installation ID for GitHub operations */\n installationId?: string;\n };\n}\n\n/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface:\n * - fastApply: AI-powered file editing with intelligent merging\n * - codebaseSearch: Semantic code search\n * - warpGrep: Fast code search with ripgrep\n * - browser: AI-powered browser automation\n * - git: Version control operations\n * - routers: Intelligent model selection (OpenAI, Anthropic, Gemini)\n * - openai/anthropic/vercel: Tool factories for agent frameworks\n */\nexport class MorphClient {\n /** Client configuration */\n public config: MorphClientConfig;\n\n /** FastApply tool for editing files with AI-powered merge */\n public fastApply: FastApplyClient;\n\n /** CodebaseSearch tool for semantic code search */\n public codebaseSearch: CodebaseSearchClient;\n\n /** WarpGrep tool for fast code search using ripgrep */\n public warpGrep: WarpGrepClient;\n\n /** Browser tool for AI-powered browser automation */\n public browser: BrowserClient;\n\n /** GitHub tool for PR context, comments, and check runs */\n public github: GitHubClient;\n\n /** Git tool for version control operations */\n public git: MorphGit;\n\n /** Model routers for intelligent model selection */\n public routers: {\n openai: OpenAIRouter;\n anthropic: AnthropicRouter;\n gemini: GeminiRouter;\n raw: RawRouter;\n };\n\n /** OpenAI-compatible tool factories */\n public openai: OpenAIToolFactory;\n\n /** Anthropic-compatible tool factories */\n public anthropic: AnthropicToolFactory;\n\n /** Vercel AI SDK tool factories */\n public vercel: VercelToolFactory;\n\n /** Compact context with line ranges */\n public compact: CompactClient['compact'];\n\n /**\n * Create a new Morph SDK client\n * \n * @param config - Client configuration (apiKey, debug, timeout, retryConfig)\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * ```\n */\n constructor(config: MorphClientConfig = {}) {\n this.config = config;\n\n // Initialize all sub-clients with shared config\n this.fastApply = new FastApplyClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.codebaseSearch = new CodebaseSearchClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.warpGrep = new WarpGrepClient({\n morphApiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.browser = new BrowserClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n });\n\n this.github = new GitHubClient({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n installationId: config.github?.installationId,\n });\n\n this.git = new MorphGit({\n apiKey: config.apiKey,\n retryConfig: config.retryConfig,\n });\n\n this.routers = {\n openai: new OpenAIRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n anthropic: new AnthropicRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n gemini: new GeminiRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n raw: new RawRouter({\n apiKey: config.apiKey,\n debug: config.debug,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n }),\n };\n\n const compactClient = new CompactClient({\n morphApiKey: config.apiKey,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n debug: config.debug,\n });\n this.compact = compactClient.compact.bind(compactClient);\n\n // Initialize tool factories\n this.openai = new OpenAIToolFactory(config);\n this.anthropic = new AnthropicToolFactory(config);\n this.vercel = new VercelToolFactory(config);\n }\n}\n","/**\n * Core implementation of Morph Fast Apply\n *\n * This module provides file-based operations that require Node.js.\n * For edge-compatible code-in/code-out operations, use applyEdit from ./apply.ts\n */\n\nimport { join, resolve, relative } from 'path';\nimport type {\n EditFileInput,\n EditFileResult,\n EditFileConfig,\n} from './types.js';\n\n// Re-export edge-compatible functions\nexport { applyEdit, generateUdiff, countChanges, callMorphAPI } from './apply.js';\n\nconst DEFAULT_CONFIG: Required<Omit<EditFileConfig, 'morphApiKey' | 'systemPrompt' | 'retryConfig' | 'description'>> = {\n morphApiUrl: 'https://api.morphllm.com',\n baseDir: process.cwd(),\n generateUdiff: true,\n autoWrite: true,\n timeout: 30000,\n debug: false,\n};\n\n/**\n * FastApply client for programmatic file editing\n * Note: This client requires Node.js for file operations\n */\nexport class FastApplyClient {\n private config: EditFileConfig;\n\n constructor(config: { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n this.config = {\n morphApiKey: config.apiKey,\n morphApiUrl: DEFAULT_CONFIG.morphApiUrl,\n debug: config.debug,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n retryConfig: config.retryConfig,\n generateUdiff: DEFAULT_CONFIG.generateUdiff,\n autoWrite: DEFAULT_CONFIG.autoWrite,\n };\n }\n\n /**\n * Execute a file edit operation\n *\n * @param input - Edit parameters including filepath, instructions, and code_edit\n * @param overrides - Optional config overrides for this operation\n * @returns Edit result with success status and changes\n */\n async execute(input: EditFileInput, overrides?: Partial<EditFileConfig>): Promise<EditFileResult> {\n return executeEditFile(input, { ...this.config, ...overrides });\n }\n\n /**\n * Apply an edit to code directly without file I/O\n *\n * Useful for sandbox environments or when you manage your own file system.\n * Compatible with the earlier OpenAI client API contract.\n *\n * @param input - Code and edit parameters\n * @param overrides - Optional config overrides for this operation\n * @returns Result with merged code\n *\n * @example\n * ```typescript\n * const result = await client.applyEdit({\n * originalCode: 'function hello() { return \"world\"; }',\n * codeEdit: 'function hello() { return \"universe\"; }',\n * instructions: 'Change return value'\n * });\n * console.log(result.mergedCode);\n * ```\n */\n async applyEdit(input: import('./types.js').ApplyEditInput, overrides?: Partial<import('./types.js').ApplyEditConfig>): Promise<import('./types.js').ApplyEditResult> {\n const { applyEdit } = await import('./apply.js');\n return applyEdit(input, { ...this.config, ...overrides });\n }\n}\n\n/**\n * Execute a file edit using Morph Fast Apply\n * Note: This function requires Node.js for file I/O\n */\nexport async function executeEditFile(\n input: EditFileInput,\n config: EditFileConfig = {}\n): Promise<EditFileResult> {\n const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;\n const fullPath = resolve(join(baseDir, input.target_filepath));\n const debug = config.debug || false;\n\n // Security: ensure file is within baseDir\n const relativePath = relative(baseDir, fullPath);\n if (relativePath.startsWith('..') || fullPath === baseDir) {\n return {\n success: false,\n filepath: input.target_filepath,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`,\n };\n }\n\n try {\n if (debug) console.log(`[FastApply] Reading file: ${input.target_filepath}`);\n\n // Dynamic import to avoid loading Node.js fs module at module evaluation time\n const { readFile, writeFile } = await import('fs/promises');\n const { callMorphAPI, generateUdiff, countChanges } = await import('./apply.js');\n\n // Handle both existing and non-existent files\n let originalCode = '';\n try {\n originalCode = await readFile(fullPath, 'utf-8');\n } catch (error: any) {\n if (error.code !== 'ENOENT') {\n throw error; // Re-throw if it's not a \"file not found\" error\n }\n // File doesn't exist, proceed with empty content (will create new file)\n if (debug) console.log(`[FastApply] File doesn't exist, will create new file`);\n }\n\n const { content: mergedCode, completionId } = await callMorphAPI(originalCode, input.code_edit, input.instructions, input.target_filepath, config);\n\n const udiff = config.generateUdiff !== false ? generateUdiff(originalCode, mergedCode, input.target_filepath) : undefined;\n\n if (config.autoWrite !== false) {\n await writeFile(fullPath, mergedCode, 'utf-8');\n if (debug) console.log(`[FastApply] Wrote ${mergedCode.length} chars to ${input.target_filepath}`);\n }\n\n const changes = countChanges(originalCode, mergedCode);\n\n return {\n success: true,\n filepath: input.target_filepath,\n udiff,\n changes,\n completionId,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n if (debug) console.error(`[FastApply] Error: ${errorMessage}`);\n\n return {\n success: false,\n filepath: input.target_filepath,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\n}\n","/**\n * Resilience utilities for retry logic and timeout handling\n */\n\nimport { SDK_VERSION } from '../../version.js';\n\nexport interface RetryConfig {\n maxRetries?: number; // Default: 3\n initialDelay?: number; // Default: 1000ms\n maxDelay?: number; // Default: 30000ms\n backoffMultiplier?: number; // Default: 2\n retryableErrors?: string[]; // Default: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND']\n onRetry?: (attempt: number, error: Error) => void;\n}\n\nconst DEFAULT_RETRY_CONFIG: Required<Omit<RetryConfig, 'onRetry'>> = {\n maxRetries: 3,\n initialDelay: 1000,\n maxDelay: 30000,\n backoffMultiplier: 2,\n retryableErrors: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'],\n};\n\n/**\n * Retry a fetch request with exponential backoff\n * \n * @param url - Request URL\n * @param options - Fetch options\n * @param retryConfig - Retry configuration\n * @returns Response from fetch\n * \n * @example\n * ```typescript\n * const response = await fetchWithRetry(\n * 'https://api.example.com/data',\n * { method: 'POST', body: JSON.stringify(data) },\n * { maxRetries: 5, initialDelay: 500 }\n * );\n * ```\n */\nexport async function fetchWithRetry(\n url: string,\n options: RequestInit,\n retryConfig: RetryConfig = {}\n): Promise<Response> {\n const {\n maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,\n initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,\n maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,\n backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,\n retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,\n onRetry,\n } = retryConfig;\n\n let lastError: Error | null = null;\n let delay = initialDelay;\n\n // Inject SDK version header (caller-provided headers can override)\n options = { ...options, headers: { 'X-Morph-SDK-Version': SDK_VERSION, ...options.headers } };\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n \n // Retry on 429 (rate limit) or 503 (service unavailable)\n if (response.status === 429 || response.status === 503) {\n if (attempt < maxRetries) {\n // Check for Retry-After header\n const retryAfter = response.headers.get('Retry-After');\n const waitTime = retryAfter \n ? parseInt(retryAfter) * 1000 \n : Math.min(delay, maxDelay);\n \n const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);\n if (onRetry) {\n onRetry(attempt + 1, error);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n continue;\n }\n }\n\n return response;\n } catch (error) {\n lastError = error as Error;\n \n // Check if error is retryable\n const isRetryable = retryableErrors.some(errType => \n lastError?.message?.includes(errType)\n );\n\n if (!isRetryable || attempt === maxRetries) {\n throw lastError;\n }\n\n // Exponential backoff\n const waitTime = Math.min(delay, maxDelay);\n if (onRetry) {\n onRetry(attempt + 1, lastError);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n }\n }\n\n throw lastError || new Error('Max retries exceeded');\n}\n\n/**\n * Add timeout to any promise\n * \n * @param promise - Promise to wrap with timeout\n * @param timeoutMs - Timeout in milliseconds\n * @param errorMessage - Optional custom error message\n * @returns Promise that rejects if timeout is reached\n * \n * @example\n * ```typescript\n * const result = await withTimeout(\n * fetchData(),\n * 5000,\n * 'Data fetch timed out'\n * );\n * ```\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n errorMessage?: string\n): Promise<T> {\n let timeoutId: NodeJS.Timeout | number;\n \n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n\n try {\n const result = await Promise.race([promise, timeoutPromise]);\n clearTimeout(timeoutId!);\n return result;\n } catch (error) {\n clearTimeout(timeoutId!);\n throw error;\n }\n}\n\n/**\n * Sleep for specified milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Unified error type for all tools\n */\nexport class MorphError extends Error {\n constructor(\n message: string,\n public code: string,\n public statusCode?: number,\n public retryable: boolean = false\n ) {\n super(message);\n this.name = 'MorphError';\n }\n}\n\n\n","/**\n * Core implementation for codebase search\n * Calls Morph rerank service for two-stage semantic search\n */\n\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n/**\n * CodebaseSearch client for programmatic semantic search\n */\nexport class CodebaseSearchClient {\n private config: { \n apiKey?: string; \n searchUrl?: string; \n debug?: boolean; \n timeout?: number; \n retryConfig?: any;\n };\n\n constructor(config: { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n this.config = {\n apiKey: config.apiKey,\n searchUrl: process.env.MORPH_SEARCH_URL || 'https://repos.morphllm.com',\n debug: config.debug,\n timeout: config.timeout || 30000,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Execute a semantic code search\n * \n * @param input - Search parameters including query, repoId, and target directories\n * @param overrides - Optional config overrides for this operation\n * @returns Search results with ranked code matches\n */\n async search(\n input: { query: string; repoId: string; target_directories?: string[]; explanation?: string; limit?: number },\n overrides?: any\n ): Promise<CodebaseSearchResult> {\n return executeCodebaseSearch(\n {\n query: input.query,\n target_directories: input.target_directories,\n explanation: input.explanation,\n limit: input.limit,\n },\n { ...this.config, repoId: input.repoId, ...overrides }\n );\n }\n}\n\n/**\n * Execute semantic code search\n */\nexport async function executeCodebaseSearch(\n input: CodebaseSearchInput,\n config: CodebaseSearchConfig\n): Promise<CodebaseSearchResult> {\n const apiKey = config.apiKey || process.env.MORPH_API_KEY;\n if (!apiKey) {\n throw new Error('MORPH_API_KEY not found. Set environment variable or pass in config');\n }\n\n const searchUrl = config.searchUrl || process.env.MORPH_SEARCH_URL || 'https://repos.morphllm.com';\n const timeout = config.timeout || 30000;\n const debug = config.debug || false;\n\n if (debug) {\n console.log(`[CodebaseSearch] Query: \"${input.query.slice(0, 60)}...\" repo=${config.repoId}`);\n console.log(`[CodebaseSearch] URL: ${searchUrl}/v1/codebase_search`);\n }\n\n const startTime = Date.now();\n\n try {\n const fetchPromise = fetchWithRetry(\n `${searchUrl}/v1/codebase_search`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n query: input.query,\n repoId: config.repoId,\n targetDirectories: input.target_directories || [],\n limit: input.limit || 10,\n candidateLimit: 50,\n }),\n },\n config.retryConfig\n );\n\n const response = await withTimeout(fetchPromise, timeout, `Codebase search timed out after ${timeout}ms`);\n\n if (!response.ok) {\n const errorText = await response.text();\n if (debug) console.error(`[CodebaseSearch] Error: ${response.status} - ${errorText}`);\n return {\n success: false,\n results: [],\n stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },\n error: `Search failed (${response.status}): ${errorText}`,\n };\n }\n\n const data = await response.json();\n const elapsed = Date.now() - startTime;\n\n if (debug) {\n console.log(`[CodebaseSearch] ✅ ${data.results?.length || 0} results in ${elapsed}ms`);\n }\n\n return {\n success: true,\n results: data.results || [],\n stats: data.stats || { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: elapsed },\n };\n\n } catch (error) {\n if (debug) console.error(`[CodebaseSearch] Exception: ${error instanceof Error ? error.message : error}`);\n return {\n success: false,\n results: [],\n stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n}\n\n","/**\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\n/**\n * Convert a CDP WebSocket scheme to HTTPS.\n *\n * Browser-use's live viewer expects `wss=https://UUID.cdpN.browser-use.com`\n * but CDP URLs use `wss://`. This swaps the scheme.\n */\nfunction cdpToHttps(wsUrl: string): string {\n return wsUrl.replace(/^wss:\\/\\//, 'https://').replace(/^ws:\\/\\//, 'http://');\n}\n\n/**\n * Normalize any debug URL into a valid browser-use live viewer URL.\n *\n * Handles three input formats:\n * 1. Already-correct `https://live.browser-use.com?wss=https://...` — pass through\n * 2. Already-correct but with wrong scheme `...?wss=wss://...` — fix the wss param\n * 3. Raw CDP URL `wss://UUID.cdpN.browser-use.com` — wrap into live viewer URL\n */\nfunction normalizeLiveUrl(debugUrl: string): string {\n const trimmed = debugUrl.trim();\n if (!trimmed) return trimmed;\n\n // Case 3: raw CDP WebSocket URL → wrap into live viewer\n if (trimmed.startsWith('wss://') || trimmed.startsWith('ws://')) {\n return `https://live.browser-use.com?wss=${encodeURIComponent(cdpToHttps(trimmed))}`;\n }\n\n let url: URL;\n try {\n url = new URL(trimmed);\n } catch {\n return trimmed;\n }\n\n // Case 2: live viewer URL with wrong scheme in wss param → fix it\n const wssParam = url.searchParams.get('wss');\n if (wssParam && (wssParam.startsWith('wss://') || wssParam.startsWith('ws://'))) {\n url.searchParams.set('wss', cdpToHttps(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: ${optionsOrPreset}. Available presets: ${Object.keys(LIVE_PRESETS).join(', ')}`\n );\n }\n return preset;\n }\n \n return optionsOrPreset;\n}\n","/**\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","/**\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","/**\n * ProfilesClient - Manage browser profiles for storing login state.\n *\n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: '...' });\n *\n * // Create a profile + live setup session\n * const setup = await morph.browser.profiles.createProfile({\n * name: 'LinkedIn',\n * repoId: 'owner/repo'\n * });\n *\n * console.log('Sign in at:', setup.session.debugUrl);\n * // User logs in, then explicitly save\n * await setup.save();\n *\n * // Use profile in browser tasks\n * await morph.browser.execute({\n * task: 'Check notifications',\n * url: 'https://linkedin.com',\n * profileId: profile.id\n * });\n * ```\n */\n\nimport { fetchWithRetry } from '../../utils/resilience.js';\nimport type { BrowserConfig } from '../types.js';\nimport {\n MorphValidationError,\n MorphAuthenticationError,\n parseAPIError,\n} from '../errors.js';\nimport type {\n Profile,\n ProfileSetup,\n ProfileWithMethods,\n CreateProfileInput,\n ProfileListResponse,\n ProfileSession,\n ProfileSessionInput,\n SaveProfileSessionInput,\n ProfileStateResponse,\n RepoSummary,\n RepoListResponse,\n APIProfile,\n APIProfileSession,\n APIProfileStateResponse,\n} from './types.js';\nimport {\n transformProfile,\n transformCreateInput,\n transformSession,\n transformSaveInput,\n transformStateResponse,\n} from './types.js';\n\nconst DEFAULT_API_URL = process.env.MORPH_ENVIRONMENT === 'DEV'\n ? 'http://localhost:8000'\n : 'https://browser.morphllm.com';\n\n/**\n * ProfilesClient class for managing browser profiles.\n *\n * Access via `morph.browser.profiles` on a MorphClient instance.\n */\nexport class ProfilesClient {\n private config: BrowserConfig;\n\n constructor(config: BrowserConfig) {\n this.config = config;\n }\n\n /**\n * Create a new browser profile and immediately start a live session.\n *\n * @param input - Profile creation parameters\n * @returns Profile setup handle with live URL + save()\n * @throws {MorphValidationError} If input validation fails\n * @throws {MorphProfileLimitError} If profile limit is exceeded\n * @throws {MorphAuthenticationError} If API key is missing or invalid\n *\n * @example\n * ```typescript\n * const setup = await morph.browser.profiles.createProfile({\n * name: 'LinkedIn Production',\n * repoId: 'owner/repo'\n * });\n * console.log(setup.session.debugUrl);\n * await setup.save();\n * ```\n */\n async createProfile(input: CreateProfileInput): Promise<ProfileSetup> {\n return createProfile(input, this.config);\n }\n\n /**\n * List all profiles for the authenticated user.\n *\n * @param repoId - Optional repository ID to filter by\n * @returns Array of profiles\n *\n * @example\n * ```typescript\n * // List all profiles\n * const allProfiles = await morph.browser.profiles.listProfiles();\n *\n * // List profiles for a specific repo\n * const repoProfiles = await morph.browser.profiles.listProfiles('owner/repo');\n * ```\n */\n async listProfiles(repoId?: string): Promise<Profile[]> {\n return listProfiles(this.config, repoId);\n }\n\n /**\n * Get a profile by ID with convenience methods.\n *\n * @param id - Profile ID\n * @returns Profile with attached methods\n * @throws {MorphNotFoundError} If profile is not found\n *\n * @example\n * ```typescript\n * const profile = await morph.browser.profiles.getProfile('profile-id');\n * const state = await profile.getState();\n * await profile.delete();\n * ```\n */\n async getProfile(id: string): Promise<ProfileWithMethods> {\n return getProfile(id, this.config);\n }\n\n /**\n * Update a profile by opening a live session (no rename).\n *\n * @param id - Profile ID\n * @returns Profile setup handle with live URL + save()\n */\n async updateProfile(id: string): Promise<ProfileSetup> {\n return updateProfile(id, this.config);\n }\n\n /**\n * Delete a profile.\n *\n * @param id - Profile ID\n * @throws {MorphNotFoundError} If profile is not found\n */\n async deleteProfile(id: string): Promise<void> {\n return deleteProfile(id, this.config);\n }\n\n /**\n * Start a browser session for profile setup.\n *\n * Returns a live URL where the user can sign into accounts.\n * After signing in, call `saveSession` to persist the state.\n *\n * @param input - Optional session parameters\n * @returns Session with debug URL\n *\n * @example\n * ```typescript\n * const session = await morph.browser.profiles.startSession();\n * console.log('Sign in at:', session.debugUrl);\n * // Open debugUrl in browser, user signs in...\n * await morph.browser.profiles.saveSession(session.sessionId, profile.id);\n * ```\n */\n async startSession(input?: ProfileSessionInput): Promise<ProfileSession> {\n return startProfileSession(this.config, input);\n }\n\n /**\n * Save browser state from a session to a profile.\n *\n * Call this after the user is done signing into accounts.\n * Extracts cookies, localStorage, and sessionStorage.\n *\n * @param sessionId - Browser session ID from startSession\n * @param profileId - Profile ID to save state to\n * @returns Updated profile with cookie domains\n */\n async saveSession(sessionId: string, profileId: string): Promise<Profile> {\n return saveProfileSession({ sessionId, profileId }, this.config);\n }\n\n /**\n * List available repo IDs (discovery).\n *\n * @returns Repo summaries with profile counts\n */\n async listRepos(): Promise<RepoSummary[]> {\n return listRepos(this.config);\n }\n\n /**\n * Get the presigned URL for a profile's state.\n *\n * Use this to download the raw state JSON for debugging\n * or to restore state manually.\n *\n * @param profileId - Profile ID\n * @returns State URL with expiry information\n */\n async getProfileState(profileId: string): Promise<ProfileStateResponse> {\n return getProfileState(profileId, this.config);\n }\n}\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\nfunction validateCreateInput(input: CreateProfileInput): void {\n if (!input.name || typeof input.name !== 'string') {\n throw new MorphValidationError('name is required', 'name');\n }\n\n const trimmedName = input.name.trim();\n if (trimmedName.length === 0) {\n throw new MorphValidationError('name cannot be empty', 'name');\n }\n\n if (trimmedName.length > 100) {\n throw new MorphValidationError('name must be 100 characters or less', 'name');\n }\n\n if (!input.repoId || typeof input.repoId !== 'string') {\n throw new MorphValidationError('repoId is required', 'repoId');\n }\n\n if (input.repoId.trim().length === 0) {\n throw new MorphValidationError('repoId cannot be empty', 'repoId');\n }\n}\n\nfunction validateId(id: string, fieldName: string): void {\n if (!id || typeof id !== 'string') {\n throw new MorphValidationError(`${fieldName} is required`, fieldName);\n }\n\n if (id.trim().length === 0) {\n throw new MorphValidationError(`${fieldName} cannot be empty`, fieldName);\n }\n}\n\n// ============================================================================\n// Standalone Functions\n// ============================================================================\n\n/**\n * Create a new browser profile.\n */\nexport async function createProfile(\n input: CreateProfileInput,\n config: BrowserConfig = {}\n): Promise<ProfileSetup> {\n validateCreateInput(input);\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(transformCreateInput(input)),\n },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiProfile: APIProfile = await response.json();\n const profile = transformProfile(apiProfile);\n const session = await startProfileSession(config, { profileId: profile.id });\n return buildProfileSetup(profile, session, config);\n}\n\n/**\n * List all profiles for the authenticated user.\n */\nexport async function listProfiles(\n config: BrowserConfig = {},\n repoId?: string\n): Promise<Profile[]> {\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const url = repoId\n ? `${apiUrl}/profiles?repo_id=${encodeURIComponent(repoId)}`\n : `${apiUrl}/profiles`;\n\n const response = await fetchWithRetry(\n url,\n { method: 'GET', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const data: { profiles: APIProfile[] } = await response.json();\n return data.profiles.map(transformProfile);\n}\n\n/**\n * Get a profile by ID with convenience methods.\n */\nexport async function getProfile(\n id: string,\n config: BrowserConfig = {}\n): Promise<ProfileWithMethods> {\n validateId(id, 'id');\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/${encodeURIComponent(id)}`,\n { method: 'GET', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiProfile: APIProfile = await response.json();\n const profile = transformProfile(apiProfile);\n\n // Attach convenience methods\n return {\n ...profile,\n getState: () => getProfileState(id, config),\n delete: () => deleteProfile(id, config),\n };\n}\n\n/**\n * Update a profile.\n */\nexport async function updateProfile(\n id: string,\n config: BrowserConfig = {}\n): Promise<ProfileSetup> {\n validateId(id, 'id');\n const profile = await fetchProfile(id, config);\n const session = await startProfileSession(config, { profileId: profile.id });\n return buildProfileSetup(profile, session, config);\n}\n\n/**\n * Delete a profile.\n */\nexport async function deleteProfile(\n id: string,\n config: BrowserConfig = {}\n): Promise<void> {\n validateId(id, 'id');\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/${encodeURIComponent(id)}`,\n { method: 'DELETE', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n}\n\n/**\n * Start a browser session for profile setup.\n */\nexport async function startProfileSession(\n config: BrowserConfig = {},\n input?: ProfileSessionInput\n): Promise<ProfileSession> {\n if (!config.apiKey) {\n throw new MorphAuthenticationError();\n }\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n // Transform input if provided\n const body = input?.profileId\n ? { profile_id: input.profileId }\n : {};\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/session/start`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiSession: APIProfileSession = await response.json();\n return transformSession(apiSession);\n}\n\n/**\n * Save browser state from a session to a profile.\n */\nexport async function saveProfileSession(\n input: SaveProfileSessionInput,\n config: BrowserConfig = {}\n): Promise<Profile> {\n validateId(input.sessionId, 'sessionId');\n validateId(input.profileId, 'profileId');\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/session/save`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify(transformSaveInput(input)),\n },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiProfile: APIProfile = await response.json();\n return transformProfile(apiProfile);\n}\n\n/**\n * List repo IDs available to the authenticated user/org.\n */\nexport async function listRepos(config: BrowserConfig = {}): Promise<RepoSummary[]> {\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/repos`,\n { method: 'GET', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const data = await response.json();\n const repos = Array.isArray(data?.repos) ? data.repos : [];\n\n return repos.map((repo: any) => ({\n repoId: repo.repo_id,\n repoFullName: repo.repo_full_name,\n profileCount: repo.profile_count ?? 0,\n })) satisfies RepoSummary[];\n}\n\n/**\n * Get the presigned URL for a profile's state.\n */\nexport async function getProfileState(\n profileId: string,\n config: BrowserConfig = {}\n): Promise<ProfileStateResponse> {\n validateId(profileId, 'profileId');\n\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/${encodeURIComponent(profileId)}/state`,\n { method: 'GET', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiState: APIProfileStateResponse = await response.json();\n return transformStateResponse(apiState);\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction buildHeaders(config: BrowserConfig): Record<string, string> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) {\n headers['Authorization'] = `Bearer ${config.apiKey}`;\n }\n return headers;\n}\n\nasync function fetchProfile(id: string, config: BrowserConfig): Promise<Profile> {\n const apiUrl = config.apiUrl || DEFAULT_API_URL;\n const headers = buildHeaders(config);\n\n const response = await fetchWithRetry(\n `${apiUrl}/profiles/${encodeURIComponent(id)}`,\n { method: 'GET', headers },\n config.retryConfig\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n const requestId = response.headers.get('x-request-id') || undefined;\n throw parseAPIError(response.status, errorText, requestId);\n }\n\n const apiProfile: APIProfile = await response.json();\n return transformProfile(apiProfile);\n}\n\nfunction buildProfileSetup(profile: Profile, session: ProfileSession, config: BrowserConfig): ProfileSetup {\n return {\n profile,\n session,\n save: () => saveProfileSession({ sessionId: session.sessionId, profileId: profile.id }, config),\n };\n}\n","/**\n * Core implementation for browser automation tasks\n */\n\nimport { fetchWithRetry, withTimeout } from '../utils/resilience.js';\nimport type {\n BrowserConfig,\n BrowserTaskInput,\n BrowserTaskInputWithSchema,\n BrowserTaskResult,\n BrowserTaskWithPromise,\n BrowserTaskWithPromiseAndSchema,\n RecordingStatus,\n RecordingWithMethods,\n ErrorsResponse,\n LiveSessionOptions,\n IframeOptions,\n WebpOptions,\n WebpResponse,\n} from './types.js';\nimport { buildLiveUrl, buildLiveIframe, buildEmbedCode, resolvePreset } from './live.js';\nimport { ProfilesClient } from './profiles/core.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: process.env.MORPH_ENVIRONMENT === 'DEV' \n ? 'http://localhost:8000'\n : 'https://browser.morphllm.com',\n timeout: 1000000, // 10 minutes for complex tasks\n debug: false,\n};\n\n/**\n * BrowserClient class for easier usage with instance configuration\n */\nexport class BrowserClient {\n private config: BrowserConfig;\n\n /**\n * Profile management - create and manage browser profiles for storing login state.\n */\n public profiles: ProfilesClient;\n\n constructor(config: BrowserConfig = {}) {\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n this.profiles = new ProfilesClient(this.config);\n }\n\n /**\n * Execute a browser automation task\n */\n async execute(input: BrowserTaskInput): Promise<BrowserTaskResult> {\n return executeBrowserTask(input, this.config);\n }\n\n async createTask(input: BrowserTaskInput): Promise<BrowserTaskWithPromise>;\n async createTask<T>(input: BrowserTaskInputWithSchema<T>): Promise<BrowserTaskWithPromiseAndSchema<T>>;\n async createTask<T>(\n input: BrowserTaskInput | BrowserTaskInputWithSchema<T>\n ): Promise<BrowserTaskWithPromise | BrowserTaskWithPromiseAndSchema<T>> {\n const apiUrl = this.config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = this.config.debug || false;\n \n const hasTask = typeof input.task === 'string' && input.task.trim().length > 0;\n const hasDiff = typeof (input as any).diff === 'string' && (input as any).diff.trim().length > 0;\n\n if (!hasTask && !hasDiff) {\n throw new Error('Browser task requires either \"task\" (natural language) or \"diff\" (PR-review planning)');\n }\n\n if (debug) {\n const preview = (input.task ?? '').slice(0, 60);\n console.log(`[Browser] createTask: \"${preview}...\" url=${input.url || 'none'}`);\n console.log(`[Browser] Calling async endpoint: ${apiUrl}/browser-task/async`);\n }\n \n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.config.apiKey) headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n \n // Call ASYNC endpoint for immediate return with live URL\n const response = await fetch(`${apiUrl}/browser-task/async`, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n task: input.task,\n diff: input.diff,\n url: input.url,\n max_steps: input.maxSteps ?? 10,\n model: input.model ?? 'morph-computer-use-v0',\n viewport_width: input.viewportWidth ?? 1280,\n viewport_height: input.viewportHeight ?? 720,\n external_id: input.externalId,\n repo_id: input.repoId,\n repo_full_name: input.repoFullName,\n commit_id: input.commitId,\n record_video: input.recordVideo ?? false,\n video_width: input.videoWidth ?? input.viewportWidth ?? 1280,\n video_height: input.videoHeight ?? input.viewportHeight ?? 720,\n allow_resizing: input.allowResizing ?? false,\n structured_output: 'schema' in input ? stringifyStructuredOutput(input.schema) : undefined,\n auth: input.auth,\n profile_id: input.profileId,\n force_query_params: input.forceQueryParams,\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] Error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n \n const result = mapTaskResult(await response.json());\n \n if (debug) {\n const debugUrl = result.debugUrl;\n console.log(`[Browser] ✅ Task created: recordingId=${result.recordingId ?? 'none'} debugUrl=${debugUrl ? 'available' : 'none'}`);\n }\n \n if ('schema' in input) {\n return wrapTaskResponseWithSchema(result, this.config, input.schema);\n } else {\n return wrapTaskResponse(result, this.config);\n }\n }\n\n /**\n * Execute task with recording and wait for video to be ready\n */\n async executeWithRecording(\n input: BrowserTaskInput & { recordVideo: true }\n ): Promise<BrowserTaskResult & { recording?: RecordingWithMethods }> {\n return executeWithRecording(input, this.config);\n }\n\n /**\n * Get recording status and URLs\n */\n async getRecording(recordingId: string): Promise<RecordingWithMethods> {\n return getRecording(recordingId, this.config);\n }\n\n /**\n * Wait for recording to complete with automatic polling\n */\n async waitForRecording(\n recordingId: string,\n options?: { timeout?: number; pollInterval?: number }\n ): Promise<RecordingWithMethods> {\n return waitForRecording(recordingId, this.config, options);\n }\n\n /**\n * Get errors from recording with screenshots\n */\n async getErrors(recordingId: string): Promise<ErrorsResponse> {\n return getErrors(recordingId, this.config);\n }\n\n /**\n * Get animated WebP preview of recording\n */\n async getWebp(\n recordingId: string,\n options?: WebpOptions\n ): Promise<WebpResponse> {\n return getWebp(recordingId, this.config, options);\n }\n\n /**\n * Check if browser worker service is healthy\n */\n async checkHealth(): Promise<{\n ok: boolean;\n google_configured: boolean;\n database_configured: boolean;\n s3_configured: boolean;\n error?: string;\n }> {\n return checkHealth(this.config);\n }\n}\n\n/**\n * Execute a natural language browser automation task\n * \n * Returns the full task result including rich agent history data (urls, errors, \n * action_history, judgement, etc.). When using this as an agent tool, use the\n * formatResult() functions from the SDK adapters to return a concise summary.\n * \n * @param input - Task parameters\n * @param config - Optional configuration (apiKey, apiUrl to override default)\n * @returns Task result with success status, findings, and comprehensive execution history\n * \n * @example\n * ```typescript\n * const result = await executeBrowserTask(\n * {\n * task: \"Test checkout flow for buying a pineapple\",\n * url: \"https://3000-abc.e2b.dev\",\n * maxSteps: 20,\n * repoId: \"my-project\",\n * commitId: \"uuid-here\"\n * },\n * {\n * apiKey: process.env.MORPH_API_KEY,\n * // apiUrl: 'http://localhost:8001' // Override for local testing\n * }\n * );\n * \n * if (result.success) {\n * console.log('Task completed:', result.result);\n * console.log('URLs visited:', result.urls);\n * console.log('Actions taken:', result.actionNames);\n * console.log('Has errors:', result.hasErrors);\n * console.log('Replay:', result.replayUrl);\n * }\n * ```\n */\nexport async function executeBrowserTask(\n input: BrowserTaskInput,\n config: BrowserConfig = {}\n): Promise<BrowserTaskResult> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const timeout = config.timeout || DEFAULT_CONFIG.timeout;\n const debug = config.debug || false;\n\n if (!input.task || input.task.trim().length === 0) {\n return { \n success: false, \n error: 'Task description is required. Example: \"Go to example.com and click the login button\"' \n };\n }\n\n if (input.maxSteps !== undefined && (input.maxSteps < 1 || input.maxSteps > 50)) {\n return { \n success: false, \n error: 'maxSteps must be between 1 and 50. Use more steps for complex multi-page flows.'\n };\n }\n\n if (debug) {\n console.log(`[Browser] Task: \"${input.task.slice(0, 60)}...\" url=${input.url || 'none'} maxSteps=${input.maxSteps ?? 10}`);\n console.log(`[Browser] Recording: ${input.recordVideo ? 'yes' : 'no'} | Calling ${apiUrl}/browser-task`);\n }\n\n const startTime = Date.now();\n\n try {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (config.apiKey) headers['Authorization'] = `Bearer ${config.apiKey}`;\n\n const fetchPromise = fetchWithRetry(\n `${apiUrl}/browser-task`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n task: input.task,\n url: input.url,\n max_steps: input.maxSteps ?? 10,\n model: input.model ?? 'morph-computer-use-v0',\n viewport_width: input.viewportWidth ?? 1280,\n viewport_height: input.viewportHeight ?? 720,\n external_id: input.externalId,\n repo_id: input.repoId,\n commit_id: input.commitId,\n record_video: input.recordVideo ?? false,\n video_width: input.videoWidth ?? input.viewportWidth ?? 1280,\n video_height: input.videoHeight ?? input.viewportHeight ?? 720,\n allow_resizing: input.allowResizing ?? false,\n structured_output: input.structuredOutput,\n auth: input.auth,\n profile_id: input.profileId,\n force_query_params: input.forceQueryParams,\n }),\n },\n config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n timeout,\n `Browser task timed out after ${timeout}ms. Consider increasing timeout or reducing maxSteps.`\n );\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] Error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result: BrowserTaskResult = mapTaskResult(await response.json());\n const elapsed = Date.now() - startTime;\n \n if (debug) {\n console.log(`[Browser] ✅ ${result.success ? 'Success' : 'Failed'} in ${elapsed}ms | steps=${result.stepsTaken ?? 0} recordingId=${result.recordingId ?? 'none'}`);\n }\n\n return result;\n\n } catch (error) {\n if (error instanceof Error) {\n // Handle network errors\n if (error.message.includes('ECONNREFUSED') || error.message.includes('fetch failed')) {\n return {\n success: false,\n error: `Cannot connect to browser worker at ${apiUrl}. Ensure the service is running and accessible. For local dev, set MORPH_ENVIRONMENT=DEV.`,\n };\n }\n\n return {\n success: false,\n error: error.message,\n };\n }\n\n return {\n success: false,\n error: String(error),\n };\n }\n}\n\n/**\n * Get recording status and video URL\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @returns Recording with convenience methods (.getWebp(), .getErrors())\n * \n * @example\n * ```typescript\n * const recording = await getRecording('uuid-here', { apiKey: 'key' });\n * \n * // Get animated WebP\n * const { webpUrl } = await recording.getWebp({ width: 780 });\n * \n * // Get errors with screenshots\n * const { errors } = await recording.getErrors();\n * ```\n */\nexport async function getRecording(\n recordingId: string,\n config: BrowserConfig = {}\n): Promise<RecordingWithMethods> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getRecording');\n }\n\n if (debug) console.log(`[Browser] getRecording: ${recordingId}`);\n\n const response = await fetch(`${apiUrl}/recordings/${recordingId}`, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getRecording error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const data: RecordingStatus = mapRecordingStatus(await response.json());\n if (debug) console.log(`[Browser] Recording status: ${data.status}`);\n\n // Return recording with convenience methods\n return {\n ...data,\n getWebp: (options?: WebpOptions) => getWebp(recordingId, config, options),\n getErrors: () => getErrors(recordingId, config),\n };\n}\n\n/**\n * Wait for recording to complete with automatic polling\n * \n * @param recordingId - Recording UUID\n * @param config - Configuration with apiKey\n * @param options - Polling options\n * @returns Recording status when completed or errored\n * \n * @example\n * ```typescript\n * const result = await executeBrowserTask({ task: '...', recordVideo: true }, config);\n * if (result.recordingId) {\n * const recording = await waitForRecording(result.recordingId, config, {\n * timeout: 60000, // 1 minute\n * pollInterval: 2000 // Check every 2 seconds\n * });\n * console.log('Video URL:', recording.videoUrl);\n * }\n * ```\n */\nexport async function waitForRecording(\n recordingId: string,\n config: BrowserConfig = {},\n options: { timeout?: number; pollInterval?: number } = {}\n): Promise<RecordingWithMethods> {\n const timeout = options.timeout ?? 60000; // Default 1 minute\n const pollInterval = options.pollInterval ?? 2000; // Default 2 seconds\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const status = await getRecording(recordingId, config);\n \n if (status.status === 'COMPLETED' || status.status === 'ERROR') {\n return status;\n }\n\n // Wait before next poll\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error(`Recording timeout after ${timeout}ms - status still pending`);\n}\n\n/**\n * Execute task with recording and wait for video to be ready\n * \n * @param input - Task parameters with recordVideo=true\n * @param config - Configuration with apiKey\n * @returns Task result with ready video URL\n * \n * @example\n * ```typescript\n * const result = await executeWithRecording(\n * {\n * task: \"Test checkout flow\",\n * url: \"https://example.com\",\n * recordVideo: true,\n * repoId: \"my-project\"\n * },\n * { apiKey: process.env.MORPH_API_KEY }\n * );\n * \n * console.log('Task result:', result.result);\n * console.log('Video URL:', result.recording?.videoUrl);\n * ```\n */\nexport async function executeWithRecording(\n input: BrowserTaskInput & { recordVideo: true },\n config: BrowserConfig = {}\n): Promise<BrowserTaskResult & { recording?: RecordingWithMethods }> {\n // Execute task with recording\n const taskResult = await executeBrowserTask(input, config);\n\n // If recording was created, wait for it to complete\n if (taskResult.recordingId) {\n try {\n const recording = await waitForRecording(\n taskResult.recordingId,\n config,\n { timeout: 60000, pollInterval: 2000 }\n );\n return {\n ...taskResult,\n recording,\n };\n } catch (error) {\n // Return task result even if recording fails\n // Still attach convenience methods for consistent API\n const errorRecording: RecordingWithMethods = {\n id: taskResult.recordingId,\n status: 'ERROR',\n error: error instanceof Error ? error.message : String(error),\n createdAt: new Date().toISOString(),\n getWebp: (options?: WebpOptions) => getWebp(taskResult.recordingId!, config, options),\n getErrors: () => getErrors(taskResult.recordingId!, config),\n };\n return {\n ...taskResult,\n recording: errorRecording,\n };\n }\n }\n\n return taskResult;\n}\n\n/**\n * Get errors from recording with screenshots\n * \n * Screenshots are captured in real-time (500ms after error occurs) during the browser session.\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @returns Errors with real-time screenshots\n * \n * @example\n * ```typescript\n * const { errors, totalErrors } = await getErrors('uuid-here', { apiKey: 'key' });\n * \n * console.log(`Found ${totalErrors} errors`);\n * \n * errors.forEach(err => {\n * console.log(`[${err.type}] ${err.message}`);\n * if (err.url) console.log(` URL: ${err.url}`);\n * if (err.screenshotUrl) console.log(` Screenshot: ${err.screenshotUrl}`);\n * \n * // Download screenshot\n * if (err.screenshotUrl) {\n * const response = await fetch(err.screenshotUrl);\n * const screenshot = await response.arrayBuffer();\n * // Save or process screenshot\n * }\n * });\n * ```\n */\nexport async function getErrors(\n recordingId: string,\n config: BrowserConfig = {}\n): Promise<ErrorsResponse> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getErrors');\n }\n\n if (debug) console.log(`[Browser] getErrors: ${recordingId}`);\n\n const response = await fetch(`${apiUrl}/recordings/${recordingId}/errors`, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getErrors error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const errors = mapErrorsResponse(await response.json());\n if (debug) console.log(`[Browser] Found ${errors.totalErrors} errors`);\n\n return errors;\n}\n\n/**\n * Helper to serialize Zod schema for API\n */\nfunction stringifyStructuredOutput(schema: any): string {\n try {\n return JSON.stringify({\n type: 'object',\n description: 'Zod schema definition (Zod v3)',\n zodDef: schema._def,\n });\n } catch (error) {\n console.warn('[Browser] Failed to serialize Zod schema:', error);\n return JSON.stringify({\n type: 'object',\n description: 'Schema serialization failed',\n });\n }\n}\n\n/**\n * Parse and validate structured task output\n */\nfunction parseStructuredTaskOutput<T>(\n result: BrowserTaskResult,\n schema: any\n): BrowserTaskResult & { parsed: T | null } {\n if (!result.output) {\n return { ...result, parsed: null };\n }\n\n try {\n const parsed = JSON.parse(result.output);\n const validated = schema.parse(parsed) as T;\n return { ...result, parsed: validated };\n } catch (error) {\n if (error instanceof SyntaxError) {\n return { ...result, parsed: null };\n }\n throw error;\n }\n}\n\nfunction mapTaskResult(api: any): BrowserTaskResult {\n if (!api || typeof api !== 'object') {\n return api as BrowserTaskResult;\n }\n\n return {\n success: api.success,\n result: api.result,\n error: api.error,\n stepsTaken: api.steps_taken,\n executionTimeMs: api.execution_time_ms,\n urls: api.urls,\n actionNames: api.action_names,\n errors: api.errors,\n modelActions: api.model_actions,\n isDone: api.is_done,\n actionHistory: api.action_history,\n actionResults: api.action_results,\n hasErrors: api.has_errors,\n numberOfSteps: api.number_of_steps,\n judgement: api.judgement,\n isValidated: api.is_validated,\n replayId: api.replay_id,\n replayUrl: api.replay_url,\n recordingId: api.recording_id,\n recordingStatus: api.recording_status,\n taskId: api.task_id,\n status: api.status,\n output: api.output,\n debugUrl: api.debug_url,\n };\n}\n\nfunction mapRecordingStatus(api: any): RecordingStatus {\n return {\n id: api.id,\n status: api.status,\n replayUrl: api.replay_url,\n networkUrl: api.network_url,\n consoleUrl: api.console_url,\n videoUrl: api.video_url,\n result: api.result,\n totalEvents: api.total_events,\n fileSize: api.file_size,\n duration: api.duration,\n error: api.error,\n createdAt: api.created_at,\n };\n}\n\nfunction mapBrowserError(api: any): ErrorsResponse['errors'][number] {\n return {\n type: api.type,\n message: api.message,\n url: api.url,\n timestamp: api.timestamp,\n screenshotUrl: api.screenshot_url,\n capturedAt: api.captured_at,\n status: api.status,\n };\n}\n\nfunction mapErrorsResponse(api: any): ErrorsResponse {\n return {\n recordingId: api.recording_id,\n totalErrors: api.total_errors,\n errors: Array.isArray(api.errors) ? api.errors.map(mapBrowserError) : [],\n };\n}\n\nfunction mapWebpResponse(api: any): WebpResponse {\n return {\n webpUrl: api.webp_url,\n cached: api.cached,\n width: api.width,\n fps: api.fps,\n maxDuration: api.max_duration,\n fileSize: api.file_size,\n maxSizeMb: api.max_size_mb,\n budgetMet: api.budget_met,\n qualityUsed: api.quality_used,\n attempts: api.attempts,\n };\n}\n\n/**\n * Get current task status\n */\nasync function getTaskStatus(\n taskId: string,\n config: BrowserConfig\n): Promise<BrowserTaskResult> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (debug) console.log(`[Browser] getTaskStatus: ${taskId}`);\n\n const headers: Record<string, string> = {};\n if (config.apiKey) headers['Authorization'] = `Bearer ${config.apiKey}`;\n\n const response = await fetch(`${apiUrl}/tasks/${taskId}`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getTaskStatus error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result: BrowserTaskResult = mapTaskResult(await response.json());\n if (debug) console.log(`[Browser] Task status: ${result.status}`);\n\n return result;\n}\n\n/**\n * Generate live URL for watching task execution in real-time\n */\nfunction generateLiveUrl(taskId: string, config: BrowserConfig): string {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const baseUrl = apiUrl.replace('/api', '');\n return `${baseUrl}/tasks/${taskId}/live`;\n}\n\n/**\n * Poll task until completion\n */\nasync function pollTaskUntilComplete(\n taskId: string,\n config: BrowserConfig,\n pollConfig: { interval?: number; timeout?: number } = {}\n): Promise<BrowserTaskResult> {\n const interval = pollConfig.interval ?? 2000; // 2 seconds\n const timeout = pollConfig.timeout ?? 300000; // 5 minutes\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n const status = await getTaskStatus(taskId, config);\n \n if (status.status === 'completed' || status.status === 'failed') {\n return status;\n }\n\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n\n throw new Error(`Task polling timeout after ${timeout}ms`);\n}\n\n/**\n * Wrap task response with convenience methods\n */\nfunction wrapTaskResponse(\n result: BrowserTaskResult,\n config: BrowserConfig\n): BrowserTaskWithPromise {\n const debugUrl = result.debugUrl ?? '';\n\n const wrapped: BrowserTaskWithPromise = {\n ...result,\n debugUrl,\n taskId: result.taskId || '',\n liveUrl: result.taskId\n ? generateLiveUrl(result.taskId, config)\n : debugUrl,\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n // If we have a taskId, poll task status endpoint\n if (result.taskId) {\n return pollTaskUntilComplete(result.taskId!, config, pollConfig);\n }\n // If we have a recordingId, poll recording status instead\n if (result.recordingId) {\n const recording = await waitForRecording(\n result.recordingId,\n config,\n pollConfig\n );\n // Return a result-like object (recording doesn't have full task result)\n return {\n ...result,\n recordingStatus: recording.status,\n } as BrowserTaskResult;\n }\n // No way to poll completion\n throw new Error('Cannot poll completion: no taskId or recordingId available');\n },\n // Add Steel live session helpers - either functional or error-throwing\n getLiveUrl: debugUrl\n ? (options?: LiveSessionOptions) => buildLiveUrl(debugUrl, options)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n getLiveIframe: debugUrl\n ? (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(debugUrl, options);\n }\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n getEmbedCode: debugUrl\n ? () => buildEmbedCode(debugUrl)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. Contact support@morphllm.com if you need help.'\n );\n },\n };\n\n return wrapped;\n}\n\n/**\n * Wrap task response with schema validation\n */\nfunction wrapTaskResponseWithSchema<T>(\n result: BrowserTaskResult,\n config: BrowserConfig,\n schema: any\n): BrowserTaskWithPromiseAndSchema<T> {\n const debugUrl = result.debugUrl ?? '';\n const parsed = result.output\n ? parseStructuredTaskOutput<T>(result, schema)\n : { ...result, parsed: null };\n\n const wrapped: BrowserTaskWithPromiseAndSchema<T> = {\n ...parsed,\n debugUrl,\n taskId: result.taskId || '',\n liveUrl: result.taskId\n ? generateLiveUrl(result.taskId, config)\n : debugUrl,\n complete: async (pollConfig?: { interval?: number; timeout?: number }) => {\n // If we have a taskId, poll task status endpoint\n if (result.taskId) {\n const finalResult = await pollTaskUntilComplete(result.taskId!, config, pollConfig);\n return parseStructuredTaskOutput<T>(finalResult, schema);\n }\n // If we have a recordingId, poll recording status instead\n if (result.recordingId) {\n const recording = await waitForRecording(\n result.recordingId,\n config,\n pollConfig\n );\n // Return parsed result (recording doesn't have task output)\n return {\n ...parsed,\n recordingStatus: recording.status,\n };\n }\n // No way to poll completion\n throw new Error('Cannot poll completion: no taskId or recordingId available');\n },\n // Add Steel live session helpers - either functional or error-throwing\n getLiveUrl: debugUrl\n ? (options?: LiveSessionOptions) => buildLiveUrl(debugUrl, options)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions. '\n );\n },\n getLiveIframe: debugUrl\n ? (optionsOrPreset?: string | IframeOptions) => {\n const options = resolvePreset(optionsOrPreset);\n return buildLiveIframe(debugUrl, options);\n }\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions.'\n );\n },\n getEmbedCode: debugUrl\n ? () => buildEmbedCode(debugUrl)\n : () => {\n throw new Error(\n 'Live sessions not available. Your backend must return a debugUrl in the response. ' +\n 'Contact support@morphllm.com if you need help enabling live sessions.'\n );\n },\n };\n\n return wrapped;\n}\n\n/**\n * Get animated WebP preview of recording\n * \n * Converts the native video recording to an animated WebP. Results are cached in S3.\n * \n * @param recordingId - Recording UUID from BrowserTaskResult\n * @param config - Configuration with apiKey\n * @param options - WebP generation options\n * @returns WebP URL and metadata\n * \n * @example\n * ```typescript\n * const webp = await getWebp('uuid-here', { apiKey: 'key' }, {\n * width: 780,\n * fps: 10,\n * quality: 65,\n * maxDuration: 15\n * });\n * console.log('WebP URL:', webp.webpUrl);\n * console.log('From cache:', webp.cached);\n * ```\n */\nexport async function getWebp(\n recordingId: string,\n config: BrowserConfig = {},\n options: WebpOptions = {}\n): Promise<WebpResponse> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n const debug = config.debug || false;\n\n if (!config.apiKey) {\n throw new Error('API key required for getWebp');\n }\n\n // Build query params\n const params = new URLSearchParams();\n if (options.maxDuration !== undefined) params.set('max_duration', String(options.maxDuration));\n if (options.fps !== undefined) params.set('fps', String(options.fps));\n if (options.width !== undefined) params.set('width', String(options.width));\n if (options.quality !== undefined) params.set('quality', String(options.quality));\n if (options.maxSizeMb !== undefined) params.set('max_size_mb', String(options.maxSizeMb));\n\n const url = `${apiUrl}/recordings/${recordingId}/webp${params.toString() ? '?' + params.toString() : ''}`;\n \n if (debug) console.log(`[Browser] getWebp: ${url}`);\n\n const response = await fetch(url, {\n method: 'GET',\n headers: { 'Authorization': `Bearer ${config.apiKey}` },\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n if (debug) console.error(`[Browser] getWebp error: ${response.status} - ${errorText}`);\n throw new Error(`HTTP ${response.status}: ${errorText}`);\n }\n\n const result = mapWebpResponse(await response.json());\n if (debug) console.log(`[Browser] WebP ready: ${result.webpUrl} (cached: ${result.cached})`);\n\n return result;\n}\n\n/**\n * Check if browser worker service is healthy\n * \n * @param config - Optional configuration\n * @returns Health status\n */\nexport async function checkHealth(config: BrowserConfig = {}): Promise<{\n ok: boolean;\n google_configured: boolean;\n database_configured: boolean;\n s3_configured: boolean;\n error?: string;\n}> {\n const apiUrl = config.apiUrl || DEFAULT_CONFIG.apiUrl;\n\n try {\n const response = await fetch(`${apiUrl}/health`, {\n method: 'GET',\n headers: config.apiKey\n ? { 'Authorization': `Bearer ${config.apiKey}` }\n : {},\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n\n const data = await response.json();\n return {\n ok: true,\n google_configured: data.google_configured ?? false,\n database_configured: data.database_configured ?? false,\n s3_configured: data.s3_configured ?? false,\n };\n } catch (error) {\n return {\n ok: false,\n google_configured: false,\n database_configured: false,\n s3_configured: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n","import { AGENT_CONFIG, DEFAULT_MODEL } from './config.js';\nimport type { AgentRunResult, ChatMessage, SessionConfig, AgentFinish, ToolCallRef, WarpGrepExecutionMetrics, WarpGrepTurnMetrics, WarpGrepStep } from './types.js';\nimport { parseFinishFiles, parseReadLines, extractPathFromCommand } 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 { toolGlob } from './tools/glob.js';\nimport { readFinishFiles } from './tools/finish.js';\nimport type { RetryConfig } from '../../utils/resilience.js';\nimport { formatTurnMessage, calculateContextBudget, buildInitialState, enforceContextLimit } from './helpers.js';\nimport OpenAI from 'openai';\nimport { SDK_VERSION } from '../../../version.js';\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 DEFAULT_API_URL = 'https://api.morphllm.com';\n\n// Tool definitions sent to the model (OpenAI function calling format)\nconst TOOL_SPECS: OpenAI.Chat.ChatCompletionTool[] = [\n {\n type: 'function',\n function: {\n name: 'list_directory',\n description: 'Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.',\n parameters: {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: \"Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */).\",\n },\n },\n required: ['command'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'grep_search',\n description: 'Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.',\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: \"Regex pattern to search for in file contents (e.g. 'class\\\\s+\\\\w+Error', 'import|require|from', 'def (get|set|update)_user').\",\n },\n path: {\n type: 'string',\n description: 'File or directory to search in. Defaults to current working directory.',\n },\n glob: {\n type: 'string',\n description: \"Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*').\",\n },\n limit: {\n type: 'integer',\n description: 'Limit output to first N matching lines. Shows all matches if not specified.',\n },\n },\n required: ['pattern'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'glob',\n description: 'Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.',\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: \"Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py').\",\n },\n path: {\n type: 'string',\n description: 'Directory to search in. Defaults to repository root.',\n },\n },\n required: ['pattern'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'read',\n description: 'Read entire files or specific line ranges using absolute paths.',\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: \"File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path).\",\n },\n lines: {\n type: 'string',\n description: \"Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file.\",\n },\n },\n required: ['path'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'finish',\n description: 'Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.',\n parameters: {\n type: 'object',\n properties: {\n files: {\n type: 'string',\n description: \"One file per line as path:lines (e.g. 'src/auth.py:1-15,25-50\\\\nsrc/user.py'). Omit line range to include entire file.\",\n },\n },\n required: ['files'],\n },\n },\n },\n];\n\ninterface CallModelOptions {\n morphApiKey?: string;\n morphApiUrl?: string;\n retryConfig?: RetryConfig;\n timeout?: number;\n search_type?: string;\n}\n\ntype ModelResponse = {\n content: string | null;\n tool_calls: ToolCallRef[];\n};\n\nasync function callModel(\n messages: ChatMessage[],\n model: string,\n options: CallModelOptions = {}\n): Promise<ModelResponse> {\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 parsedUrl = new URL(baseUrl);\n const baseURL = parsedUrl.pathname === '/' ? `${baseUrl}/v1` : baseUrl;\n\n const client = new OpenAI({\n apiKey,\n baseURL,\n maxRetries: options.retryConfig?.maxRetries,\n timeout: timeoutMs,\n defaultHeaders: { 'X-Morph-SDK-Version': SDK_VERSION },\n });\n\n const MAX_EMPTY_RETRIES = 1;\n\n for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {\n let data;\n try {\n data = await client.chat.completions.create({\n model,\n temperature: 0.0,\n max_tokens: 2048,\n messages: messages as OpenAI.Chat.ChatCompletionMessageParam[],\n tools: TOOL_SPECS,\n ...(options.search_type ? { search_type: options.search_type } as Record<string, unknown> : {}),\n });\n } catch (error) {\n if (error instanceof OpenAI.APIError && error.status === 404) {\n const defaultMsg =\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 const errorText = error.message?.trim();\n throw new Error(errorText || defaultMsg);\n }\n throw error;\n }\n\n const choice = data?.choices?.[0];\n const message = choice?.message;\n\n if (!message) {\n if (attempt === MAX_EMPTY_RETRIES) {\n throw new Error('Invalid response from model: no message in response');\n }\n await new Promise(resolve => setTimeout(resolve, 200));\n continue;\n }\n\n const toolCalls: ToolCallRef[] = (message.tool_calls || []).map(tc => ({\n id: tc.id,\n type: 'function' as const,\n function: { name: tc.function.name, arguments: tc.function.arguments },\n }));\n\n if (message.content || toolCalls.length > 0) {\n return { content: message.content ?? null, tool_calls: toolCalls };\n }\n\n if (attempt === MAX_EMPTY_RETRIES) {\n const finishReason = choice?.finish_reason ?? 'unknown';\n throw new Error(\n `Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`\n );\n }\n await new Promise(resolve => setTimeout(resolve, 200));\n }\n\n throw new Error('Invalid response from model');\n}\n\n/** Safely parse JSON, returning empty object on failure */\nfunction safeParseJSON(s: string): Record<string, unknown> {\n try {\n return JSON.parse(s);\n } catch {\n return {};\n }\n}\n\n/**\n * Execute a single tool call against the provider, returning the output string.\n */\nasync function executeTool(\n provider: WarpGrepProvider,\n name: string,\n args: Record<string, unknown>,\n repoRoot?: string,\n): Promise<string> {\n switch (name) {\n case 'grep_search': {\n const grepArgs: { pattern: string; path: string; glob?: string; case_sensitive?: boolean } = {\n pattern: args.pattern as string,\n path: (args.path as string) || '.',\n };\n if (args.glob) grepArgs.glob = args.glob as string;\n if (args.case_sensitive !== undefined) grepArgs.case_sensitive = args.case_sensitive as boolean;\n const result = await toolGrep(provider, grepArgs);\n let output = result.output;\n if (args.limit && typeof args.limit === 'number') {\n const lines = output.split('\\n');\n if (lines.length > args.limit) {\n output = lines.slice(0, args.limit).join('\\n') + `\\n... (truncated at ${args.limit} lines)`;\n }\n }\n return output;\n }\n case 'glob': {\n return toolGlob(provider, {\n pattern: args.pattern as string,\n path: args.path as string | undefined,\n });\n }\n case 'list_directory': {\n const dirPath = extractPathFromCommand((args.command as string) || '.');\n return toolListDirectory(provider, { path: dirPath }, repoRoot);\n }\n case 'read': {\n const readArgs: { path: string; start?: number; end?: number; lines?: Array<[number, number]> } = {\n path: args.path as string,\n };\n if (args.lines && typeof args.lines === 'string') {\n Object.assign(readArgs, parseReadLines(args.lines));\n }\n return toolRead(provider, readArgs);\n }\n default:\n return `Unknown tool: ${name}`;\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 = config.repoRoot || process.cwd();\n const model = config.model || DEFAULT_MODEL;\n const messages: ChatMessage[] = [];\n\n const maxTurns = AGENT_CONFIG.MAX_TURNS;\n\n const initialStateStart = Date.now();\n const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });\n timings.initial_state_ms = Date.now() - initialStateStart;\n\n messages.push({ role: 'user', content: initialState });\n\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 enforceContextLimit(messages);\n\n // Call model\n const modelCallStart = Date.now();\n const response = await callModel(messages, model, {\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: timeoutMs,\n search_type: config.search_type,\n }).catch((e: unknown) => {\n const errMsg = e instanceof Error ? e.message : String(e);\n console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);\n errors.push({ message: errMsg });\n return null;\n });\n turnMetrics.morph_api_ms = Date.now() - modelCallStart;\n\n if (!response) {\n timings.turns!.push(turnMetrics);\n break;\n }\n\n const toolCalls = response.tool_calls;\n\n // Add assistant message to history\n messages.push({\n role: 'assistant',\n content: response.content,\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n });\n\n if (toolCalls.length === 0) {\n console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || '').slice(0, 500)}`);\n errors.push({ message: 'No tool calls produced by the model.' });\n terminationReason = 'terminated';\n timings.turns!.push(turnMetrics);\n break;\n }\n\n // Yield step for streaming consumers\n yield {\n turn,\n toolCalls: toolCalls.map(tc => ({\n name: tc.function.name,\n arguments: safeParseJSON(tc.function.arguments),\n })),\n };\n\n // Check for finish call\n const finishCall = toolCalls.find(tc => tc.function.name === 'finish');\n if (finishCall) {\n const args = safeParseJSON(finishCall.function.arguments) as { files?: string };\n const filesStr = args.files || '';\n const files = parseFinishFiles(filesStr);\n finishMeta = { files };\n terminationReason = 'completed';\n\n if (files.length === 0) {\n const payload = filesStr || 'No relevant code found.';\n timings.turns!.push(turnMetrics);\n timings.total_ms = Date.now() - totalStart;\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: finishMeta },\n timings: timings as WarpGrepExecutionMetrics,\n };\n }\n\n timings.turns!.push(turnMetrics);\n break;\n }\n\n // Execute non-finish tool calls in parallel\n const toolExecStart = Date.now();\n const results = await Promise.all(\n toolCalls.map(async (tc) => {\n const args = safeParseJSON(tc.function.arguments);\n const output = await executeTool(provider, tc.function.name, args, repoRoot).catch(err => String(err));\n return { tool_call_id: tc.id, content: output };\n })\n );\n turnMetrics.local_tools_ms = Date.now() - toolExecStart;\n\n // Add tool result messages\n for (const result of results) {\n messages.push({ role: 'tool', tool_call_id: result.tool_call_id, content: result.content });\n }\n\n // Add turn counter hint\n const turnMsg = formatTurnMessage(turn, maxTurns);\n const budget = calculateContextBudget(messages);\n messages.push({ role: 'user', content: turnMsg + '\\n' + budget });\n\n timings.turns!.push(turnMetrics);\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 // If the model returned a path that doesn't start with repoRoot,\n // try resolving it against repoRoot (handles truncated absolute paths)\n let resolvedPath = p;\n if (!p.startsWith(repoRoot)) {\n // Strip leading slash for path.join, then try the resolved path\n const relative = p.startsWith('/') ? p.slice(1) : p;\n resolvedPath = path.join(repoRoot, relative);\n }\n try {\n const rr = await provider.read({ path: resolvedPath, 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: resolvedPath, error: errorMsg });\n console.error(`[warp_grep] Failed to read file: ${resolvedPath} - ${errorMsg}`);\n return [`[couldn't find: ${resolvedPath}]`];\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\n/**\n * Non-streaming version. Runs the agent loop and returns the final result.\n */\nexport async function runWarpGrep(config: SessionConfig & { provider: WarpGrepProvider }): Promise<AgentRunResult> {\n const gen = runWarpGrepStreaming(config);\n // Drain all yielded steps, return the final result\n let result = await gen.next();\n while (!result.done) {\n result = await gen.next();\n }\n return result.value;\n}\n","// Helpers for parsing string-format tool arguments from OpenAI tool calls\n\nimport type { FinishFileSpec } from './types.js';\n\n/** Parse \"lines\" string from read tool (e.g. \"1-50\" or \"1-20,45-80\") into structured args */\nexport function parseReadLines(linesStr: string): { start?: number; end?: number; lines?: Array<[number, number]> } {\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of linesStr.split(',')) {\n const trimmed = rangeStr.trim();\n if (!trimmed) continue;\n const parts = trimmed.split('-').map(v => parseInt(v.trim(), 10));\n if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {\n ranges.push([parts[0], parts[1]]);\n } else if (Number.isFinite(parts[0])) {\n ranges.push([parts[0], parts[0]]);\n }\n }\n if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };\n if (ranges.length > 1) return { lines: ranges };\n return {};\n}\n\n/** Parse \"files\" string from finish tool (e.g. \"src/auth.py:1-50\\nsrc/user.py\" or space-separated) into FinishFileSpec[] */\nexport function parseFinishFiles(filesStr: string): FinishFileSpec[] {\n const files: FinishFileSpec[] = [];\n // Split on whitespace (training uses space-separated, SDK also supports newlines)\n for (const line of filesStr.trim().split(/\\s+/)) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n const colonIdx = trimmed.indexOf(':');\n if (colonIdx === -1) {\n files.push({ path: trimmed, lines: '*' });\n continue;\n }\n const filePath = trimmed.slice(0, colonIdx);\n const rangesPart = trimmed.slice(colonIdx + 1);\n if (!rangesPart.trim() || rangesPart.trim() === '*') {\n files.push({ path: filePath, lines: '*' });\n continue;\n }\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of rangesPart.split(',')) {\n const rt = rangeStr.trim();\n if (!rt) continue;\n const parts = rt.split('-').map(v => parseInt(v.trim(), 10));\n if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {\n ranges.push([parts[0], parts[1]]);\n } else if (Number.isFinite(parts[0])) {\n ranges.push([parts[0], parts[0]]);\n }\n }\n files.push({ path: filePath, lines: ranges.length > 0 ? ranges : '*' });\n }\n return files;\n}\n\n/** Extract directory path from a list_directory command string (e.g. \"ls -la src/\" → \"src/\") */\nexport function extractPathFromCommand(command: string): string {\n const tokens = command.trim().split(/\\s+/);\n const pathTokens = tokens.slice(1).filter(t => !t.startsWith('-') && !t.startsWith('|') && !t.startsWith('\\\\('));\n return pathTokens[0] || '.';\n}\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nexport async function toolGrep(\n provider: WarpGrepProvider,\n args: { pattern: string; path: string; glob?: string; context_lines?: number; case_sensitive?: boolean }\n): Promise<{ output: string }> {\n const res = await provider.grep(args);\n \n // Return errors as output - let the model see and handle them\n if (res.error) {\n return { output: res.error };\n }\n \n if (!res.lines.length) {\n return { output: 'no matches' };\n }\n \n return { output: res.lines.join('\\n') };\n}\n\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nfunction isValidRange(start: unknown, end: unknown): boolean {\n return (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Number.isFinite(start) &&\n Number.isFinite(end) &&\n start > 0 &&\n end >= start\n );\n}\n\nexport async function toolRead(\n provider: WarpGrepProvider,\n args: { path: string; start?: number; end?: number; lines?: Array<[number, number]> }\n): Promise<string> {\n if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {\n const validRanges: Array<[number, number]> = [];\n for (const range of args.lines) {\n if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {\n validRanges.push([range[0], range[1]]);\n }\n }\n \n if (validRanges.length === 0) {\n const res = await provider.read({ path: args.path });\n if (res.error) return res.error;\n if (!res.lines.length) return '(empty file)';\n return res.lines.join('\\n');\n }\n \n const chunks: string[] = [];\n for (const [start, end] of validRanges) {\n const res = await provider.read({ path: args.path, start, end });\n if (res.error) return res.error;\n chunks.push(res.lines.join('\\n'));\n }\n if (chunks.every(c => c === '')) return '(empty file)';\n return chunks.join('\\n...\\n');\n }\n\n const res = await provider.read({ path: args.path, start: args.start, end: args.end });\n if (res.error) {\n return res.error;\n }\n if (!res.lines.length) return '(empty file)';\n return res.lines.join('\\n');\n}\n\n","import type { WarpGrepProvider } from '../../providers/types.js';\nimport { AGENT_CONFIG } from '../config.js';\nimport path from 'path';\n\nexport async function toolListDirectory(\n provider: WarpGrepProvider,\n args: { path: string; pattern?: string | null; maxResults?: number; maxDepth?: number },\n repoRoot?: string,\n): Promise<string> {\n\n const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;\n const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n\n const entries = await provider.listDirectory({\n path: args.path,\n pattern: args.pattern ?? null,\n maxResults,\n maxDepth,\n });\n\n if (!entries.length) return 'empty';\n\n // Flat absolute paths (matches training format)\n // If repoRoot is available, convert relative paths to absolute\n if (repoRoot) {\n const absRoot = repoRoot;\n const lines = entries.map(e => path.join(absRoot, e.path));\n return lines.join('\\n');\n }\n\n // Fallback: return relative paths if repoRoot not available\n return entries.map(e => e.path).join('\\n');\n}\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nexport async function toolGlob(\n provider: WarpGrepProvider,\n args: { pattern: string; path?: string }\n): Promise<string> {\n const res = await provider.glob(args);\n\n if (res.error) {\n return res.error;\n }\n\n if (!res.files.length) {\n return 'no matches';\n }\n\n // Match training output format exactly\n const header = `Found ${res.totalFound} file(s) matching \"${args.pattern}\" within ${res.searchDir}, sorted by modification time (newest first):`;\n const body = res.files.join('\\n');\n const truncated = res.totalFound > res.files.length\n ? `\\n[${res.totalFound - res.files.length} files truncated]`\n : '';\n return `${header}\\n---\\n${body}\\n---${truncated}`;\n}\n","import type { FinishFileSpec } from '../types.js';\n\nfunction isValidRange(range: unknown): range is [number, number] {\n return (\n Array.isArray(range) &&\n range.length >= 2 &&\n typeof range[0] === 'number' &&\n typeof range[1] === 'number' &&\n Number.isFinite(range[0]) &&\n Number.isFinite(range[1]) &&\n range[0] > 0 &&\n range[1] >= range[0]\n );\n}\n\nfunction extractValidRanges(lines: unknown): Array<[number, number]> | null {\n if (!Array.isArray(lines)) return null;\n const valid: Array<[number, number]> = [];\n for (const range of lines) {\n if (isValidRange(range)) {\n valid.push([range[0], range[1]]);\n }\n }\n return valid.length > 0 ? valid : null;\n}\n\nexport function normalizeFinishFiles(files: FinishFileSpec[]): FinishFileSpec[] {\n return files.map((f) => {\n if (f.lines === '*') return { path: f.path, lines: '*' };\n const validRanges = extractValidRanges(f.lines);\n if (!validRanges) return { path: f.path, lines: '*' };\n return { path: f.path, lines: mergeRanges(validRanges) };\n });\n}\n\nexport async function readFinishFiles(\n repoRoot: string,\n files: FinishFileSpec[],\n reader: (path: string, start?: number, end?: number) => Promise<string[]>\n): Promise<{ path: string; ranges: '*' | Array<[number, number]>; content: string }[]> {\n const out: { path: string; ranges: '*' | Array<[number, number]>; content: string }[] = [];\n for (const f of files) {\n const validRanges = f.lines === '*' ? null : extractValidRanges(f.lines);\n if (f.lines === '*' || !validRanges) {\n const lines = await reader(f.path);\n out.push({ path: f.path, ranges: '*', content: lines.join('\\n') });\n } else {\n const ranges = mergeRanges(validRanges);\n const chunks: string[] = [];\n for (let i = 0; i < ranges.length; i++) {\n const [s, e] = ranges[i];\n if (i === 0 && s > 1) {\n chunks.push(`// ... existing code, block starting at line ${s} ...`);\n } else if (i > 0) {\n chunks.push(`// ... existing code, block starting at line ${s} ...`);\n }\n const lines = await reader(f.path, s, e);\n chunks.push(lines.join('\\n'));\n }\n out.push({ path: f.path, ranges, content: chunks.join('\\n') });\n }\n }\n return out;\n}\n\nfunction mergeRanges(ranges: Array<[number, number]>): Array<[number, number]> {\n if (!ranges.length) return [];\n const sorted = [...ranges].sort((a, b) => a[0] - b[0]);\n const merged: Array<[number, number]> = [];\n let [cs, ce] = sorted[0];\n for (let i = 1; i < sorted.length; i++) {\n const [s, e] = sorted[i];\n if (s <= ce + 1) {\n ce = Math.max(ce, e);\n } else {\n merged.push([cs, ce]);\n cs = s;\n ce = e;\n }\n }\n merged.push([cs, ce]);\n return merged;\n}\n\n","/**\n * Shared helper functions for warp-grep agent loop.\n * Used by both the internal runner and exported for harness users.\n */\n\nimport path from 'path';\nimport { AGENT_CONFIG } from './config.js';\nimport type { ChatMessage } from './types.js';\nimport type { WarpGrepProvider, ListDirectoryEntry } from '../providers/types.js';\n\nconst TRUNCATED_MARKER = '[truncated for context limit]';\n\n/**\n * Get the character size of a ChatMessage (handles all message types).\n */\nfunction getMessageSize(m: ChatMessage): number {\n if (m.role === 'tool') return m.content.length;\n if (m.role === 'assistant') {\n let size = typeof m.content === 'string' ? m.content.length : 0;\n if (m.tool_calls) {\n size += m.tool_calls.reduce((s, tc) => s + tc.function.name.length + tc.function.arguments.length, 0);\n }\n return size;\n }\n // system or user\n return (m as { content: string }).content.length;\n}\n\n/**\n * Format the turn counter message shown to the model.\n */\nexport function formatTurnMessage(turnsUsed: number, maxTurns: number): string {\n const turnsRemaining = maxTurns - turnsUsed;\n if (turnsRemaining === 1) {\n return `\\nYou have used ${turnsUsed} turns, you only have 1 turn remaining. You have run out of turns to explore the code base and MUST call the finish tool now`;\n }\n return `\\nYou have used ${turnsUsed} turn${turnsUsed === 1 ? '' : 's'} and have ${turnsRemaining} remaining`;\n}\n\n/**\n * Calculate and format the context budget indicator.\n */\nexport function calculateContextBudget(messages: ChatMessage[]): string {\n const totalChars = messages.reduce((sum, m) => sum + getMessageSize(m), 0);\n const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;\n const percent = Math.floor((totalChars / maxChars) * 100);\n const usedK = Math.floor(totalChars / 1000);\n const maxK = Math.floor(maxChars / 1000);\n return `<context_budget>${percent}% (${usedK}K/${maxK}K chars)</context_budget>`;\n}\n\n/**\n * Build the initial state message containing repo structure and search term.\n */\nexport async function buildInitialState(\n repoRoot: string,\n searchTerm: string,\n provider: WarpGrepProvider,\n options?: { search_type?: string },\n): Promise<string> {\n const budget = calculateContextBudget([]);\n const turnTag = `You have used 0 turns and have ${AGENT_CONFIG.MAX_TURNS} remaining`;\n const treeDepth = options?.search_type === 'node_modules' ? 1 : 2;\n\n const absRoot = repoRoot;\n\n try {\n const entries = await provider.listDirectory({\n path: '.',\n maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,\n maxDepth: treeDepth,\n });\n\n // Flat list of absolute paths (matches training format)\n // First line is the repo root, then one absolute path per entry\n const lines = [absRoot];\n for (const e of entries) {\n lines.push(path.join(absRoot, e.path));\n }\n\n return `<repo_structure>\\n${lines.join('\\n')}\\n</repo_structure>\\n\\n<search_string>\\n${searchTerm}\\n</search_string>\\n${budget}\\n${turnTag}`;\n } catch {\n return `<repo_structure>\\n${absRoot}\\n</repo_structure>\\n\\n<search_string>\\n${searchTerm}\\n</search_string>\\n${budget}\\n${turnTag}`;\n }\n}\n\n/**\n * Format directory entries as an indented tree string.\n */\nexport function formatListDirectoryTree(entries: ListDirectoryEntry[]): string {\n if (!entries.length) return 'empty';\n return entries\n .map((e) => {\n const indent = ' '.repeat(e.depth);\n const name = e.type === 'dir' ? `${e.name}/` : e.name;\n return `${indent}${name}`;\n })\n .join('\\n');\n}\n\n/**\n * Enforce hard context limit by truncating tool result messages.\n * Preserves the first user message (initial query) and all assistant messages.\n * Truncates tool/user messages from oldest to newest until under the threshold.\n *\n * @param messages - The conversation messages array (mutated in place)\n * @param maxChars - Maximum total character count (defaults to AGENT_CONFIG.MAX_CONTEXT_CHARS)\n * @returns The same messages array, truncated if necessary\n */\nexport function enforceContextLimit(\n messages: ChatMessage[],\n maxChars: number = AGENT_CONFIG.MAX_CONTEXT_CHARS\n): ChatMessage[] {\n const getTotalChars = () => messages.reduce((sum, m) => sum + getMessageSize(m), 0);\n\n if (getTotalChars() <= maxChars) {\n return messages;\n }\n\n // Find indices of truncatable messages (tool results and non-first user messages)\n const truncatableIndices: number[] = [];\n let firstUserSkipped = false;\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n if (m.role === 'tool') {\n truncatableIndices.push(i);\n } else if (m.role === 'user') {\n if (!firstUserSkipped) {\n firstUserSkipped = true;\n continue; // Skip first user message (contains the search query)\n }\n truncatableIndices.push(i);\n }\n }\n\n // Truncate from oldest to newest until under limit\n for (const idx of truncatableIndices) {\n if (getTotalChars() <= maxChars) {\n break;\n }\n const m = messages[idx];\n if (m.role === 'tool' && m.content !== TRUNCATED_MARKER) {\n messages[idx] = { role: 'tool', tool_call_id: m.tool_call_id, content: TRUNCATED_MARKER };\n } else if (m.role === 'user' && (m as { content: string }).content !== TRUNCATED_MARKER) {\n messages[idx] = { role: 'user', content: TRUNCATED_MARKER };\n }\n }\n\n return messages;\n}\n","/**\n * RemoteCommandsProvider - wraps simple RemoteCommands into WarpGrepProvider\n * \n * Handles parsing of raw stdout from grep/read/listDir commands.\n * Users just return stdout, SDK handles all format conversion.\n */\n\nimport type { WarpGrepProvider, GrepResult, ReadResult, GlobResult, ListDirectoryEntry } from './types.js';\nimport type { RemoteCommands } from '../types.js';\nimport { AGENT_CONFIG } from '../agent/config.js';\n\n/**\n * Directories/files to always skip (exact name match)\n */\nconst SKIP_NAMES = new Set([\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'Pods', '.bundle',\n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs',\n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n // Cache\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n // IDE\n '.idea', '.vscode', '.vs',\n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n // Temp\n 'tmp', 'temp', '.tmp', '.temp',\n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n]);\n\n/**\n * File extensions to skip\n */\nconst SKIP_EXTENSIONS = new Set([\n '.min.js', '.min.css', '.bundle.js',\n '.wasm', '.so', '.dll', '.pyc',\n '.map', '.js.map',\n]);\n\n/**\n * Check if a filename should be skipped\n */\nfunction shouldSkip(name: string): boolean {\n // Skip exact name matches\n if (SKIP_NAMES.has(name)) return true;\n \n // Skip hidden files/directories (start with .)\n if (name.startsWith('.')) return true;\n \n // Skip files with certain extensions\n for (const ext of SKIP_EXTENSIONS) {\n if (name.endsWith(ext)) return true;\n }\n \n return false;\n}\n\n/**\n * Wraps simple RemoteCommands functions into a full WarpGrepProvider.\n * \n * This allows users to provide three simple functions that return raw stdout,\n * and the SDK handles all parsing internally.\n * \n * @example\n * ```typescript\n * const provider = new RemoteCommandsProvider('/home/repo', {\n * grep: async (pattern, path) => {\n * const r = await sandbox.run(`rg '${pattern}' '${path}'`);\n * return r.stdout;\n * },\n * read: async (path, start, end) => {\n * const r = await sandbox.run(`sed -n '${start},${end}p' '${path}'`);\n * return r.stdout;\n * },\n * listDir: async (path, maxDepth) => {\n * const r = await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`);\n * return r.stdout;\n * },\n * });\n * ```\n */\nexport class RemoteCommandsProvider implements WarpGrepProvider {\n constructor(\n private readonly repoRoot: string,\n private readonly commands: RemoteCommands\n ) {}\n\n /**\n * Run grep command and parse ripgrep output\n */\n async grep(params: { pattern: string; path: string; glob?: string }): Promise<GrepResult> {\n try {\n const stdout = await this.commands.grep(params.pattern, params.path, params.glob);\n \n // Parse ripgrep output: each line is \"path:line:content\" or \"path-line-content\" for context\n const lines = (stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((l) => l.length > 0);\n \n // Truncate if too many lines (return partial results like training harness)\n if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {\n const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines };\n } catch (error) {\n return {\n lines: [],\n error: `[GREP ERROR] ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Read file and add line numbers\n */\n async read(params: { path: string; start?: number; end?: number }): Promise<ReadResult> {\n const rawStart = params.start;\n const rawEnd = params.end;\n \n const startValid = rawStart === undefined || (Number.isFinite(rawStart) && rawStart > 0);\n const endValid = rawEnd === undefined || (Number.isFinite(rawEnd) && rawEnd > 0);\n const rangeValid = startValid && endValid && \n (rawStart === undefined || rawEnd === undefined || rawStart <= rawEnd);\n \n const start = rangeValid && rawStart !== undefined ? rawStart : 1;\n const end = rangeValid && rawEnd !== undefined ? rawEnd : 1_000_000;\n \n try {\n const stdout = await this.commands.read(params.path, start, end);\n \n // Split content into lines and add line numbers\n const contentLines = (stdout || '').split('\\n');\n \n // Remove trailing empty line if present (common with sed output)\n if (contentLines.length > 0 && contentLines[contentLines.length - 1] === '') {\n contentLines.pop();\n }\n \n // Format as \"lineNumber|content\"\n const lines = contentLines.map((content, idx) => `${start + idx}|${content}`);\n \n // Check if output is too large\n if (lines.length > AGENT_CONFIG.MAX_READ_LINES) {\n const truncated = lines.slice(0, AGENT_CONFIG.MAX_READ_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${lines.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines };\n } catch (error) {\n return {\n lines: [],\n error: `[READ ERROR] ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * List directory and parse find output\n */\n async listDirectory(params: { \n path: string; \n pattern?: string | null; \n maxResults?: number; \n maxDepth?: number;\n }): Promise<ListDirectoryEntry[]> {\n const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;\n \n try {\n const stdout = await this.commands.listDir(params.path, maxDepth);\n \n // Parse find output: one path per line\n const paths = (stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((p) => p.length > 0);\n \n const regex = params.pattern ? new RegExp(params.pattern) : null;\n const entries: ListDirectoryEntry[] = [];\n \n for (const fullPath of paths) {\n // Skip the root path itself\n if (fullPath === params.path || fullPath === this.repoRoot) continue;\n \n const name = fullPath.split('/').pop() || '';\n \n // Simple name-based filtering - skip junk dirs/files\n if (shouldSkip(name)) continue;\n \n // Apply pattern filter if provided\n if (regex && !regex.test(name)) continue;\n \n // Determine relative path\n let relativePath = fullPath;\n if (fullPath.startsWith(this.repoRoot)) {\n relativePath = fullPath.slice(this.repoRoot.length).replace(/^\\//, '');\n }\n \n // Calculate depth based on path separators\n const depth = relativePath.split('/').filter(Boolean).length - 1;\n \n // Determine if it's a directory (ends with / or infer from path structure)\n // Note: Most sandbox find commands don't indicate type, so we guess based on extension\n const hasExtension = name.includes('.') && !name.startsWith('.');\n const type: 'file' | 'dir' = hasExtension ? 'file' : 'dir';\n \n entries.push({\n name,\n path: relativePath,\n type,\n depth: Math.max(0, depth),\n });\n \n if (entries.length >= maxResults) break;\n }\n \n return entries;\n } catch (error) {\n // Return empty array on error (consistent with LocalRipgrepProvider)\n return [];\n }\n }\n\n /**\n * Glob search - finds files matching a pattern.\n * Falls back to a grep --files approach via the listDir command.\n */\n async glob(params: { pattern: string; path?: string }): Promise<GlobResult> {\n const searchPath = params.path || this.repoRoot;\n try {\n // Use find with -name to simulate glob\n const stdout = await this.commands.listDir(searchPath, 10);\n const allPaths = (stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((p) => p.length > 0);\n\n // Simple glob matching: convert glob pattern to regex\n const globToRegex = (glob: string) => {\n const escaped = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.');\n return new RegExp(escaped);\n };\n const regex = globToRegex(params.pattern);\n\n const matched = allPaths\n .filter(p => {\n const name = p.split('/').pop() || '';\n return regex.test(name) && !shouldSkip(name);\n });\n\n const totalFound = matched.length;\n return { files: matched.slice(0, 100), searchDir: searchPath, totalFound };\n } catch (error) {\n return {\n files: [],\n searchDir: searchPath,\n totalFound: 0,\n error: `[GLOB ERROR] ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n}\n","/**\n * HTTP-based RemoteCommands for code search against the Morph landing API.\n *\n * Translates grep/read/listDir into POST requests to the code-search endpoints,\n * so the WarpGrep agent can search GitHub repositories that have been indexed\n * by the Morph code storage service.\n */\n\nimport type { RemoteCommands } from '../types.js';\n\nexport interface CodeStorageHttpConfig {\n /** Base URL for the code search API (e.g. \"https://morphllm.com\") */\n baseUrl: string;\n /** Repository ID returned by the get-or-create endpoint */\n repoId: string;\n /** Git branch to search */\n branch: string;\n}\n\nasync function post(url: string, body: Record<string, unknown>, op: string): Promise<string> {\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => res.statusText);\n // Return error as content instead of throwing so the agent can handle it gracefully\n try {\n const parsed = JSON.parse(text);\n if (parsed.error) return `Error: ${parsed.error}`;\n } catch { /* not JSON, fall through */ }\n return `Error: ${op} failed (${res.status}): ${text}`;\n }\n const data = await res.json();\n if (data.error) throw new Error(data.error);\n return data.stdout;\n}\n\nexport function createCodeStorageHttpCommands(config: CodeStorageHttpConfig): RemoteCommands {\n const { baseUrl, repoId, branch } = config;\n const encodedRepoId = encodeURIComponent(repoId);\n\n return {\n grep: (pattern: string, path: string, glob?: string) =>\n post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path, glob, branch }, 'grep'),\n\n read: (path: string, start: number, end: number) =>\n post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path, start, end, branch }, 'read'),\n\n listDir: (path: string, maxDepth: number) =>\n post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path, maxDepth, branch }, 'list'),\n };\n}\n","/**\n * GitHub URL parsing utilities\n */\n\n/**\n * Parse GitHub URL or \"owner/repo\" shorthand into owner and repo components.\n * Handles: \"owner/repo\", \"https://github.com/owner/repo\", \"github.com/owner/repo.git\"\n */\nexport function parseGitHubUrl(input: string): { owner: string; repo: string } {\n input = input.trim();\n\n // Try URL patterns first\n const urlPattern = /^(?:https?:\\/\\/)?github\\.com\\/([^\\/]+)\\/([^\\/\\?\\#]+)/;\n const match = input.match(urlPattern);\n if (match) {\n return { owner: match[1], repo: match[2].replace(/\\.git$/, '') };\n }\n\n // Try \"owner/repo\" shorthand (reject if owner contains '.', e.g. \"github.com/owner\")\n const shortPattern = /^([^\\/]+)\\/([^\\/]+)$/;\n const shortMatch = input.match(shortPattern);\n if (shortMatch && !shortMatch[1].includes('.')) {\n return { owner: shortMatch[1], repo: shortMatch[2].replace(/\\.git$/, '') };\n }\n\n throw new Error(\n `Invalid GitHub URL or shorthand: \"${input}\". Expected \"owner/repo\" or \"https://github.com/owner/repo\"`\n );\n}\n","/**\n * WarpGrep client for programmatic code search\n */\n\nimport { runWarpGrep, runWarpGrepStreaming } from './agent/runner.js';\nimport { RemoteCommandsProvider } from './providers/remote.js';\nimport type { WarpGrepProvider } from './providers/types.js';\nimport type { AgentRunResult, WarpGrepStep } from './agent/types.js';\nimport type {\n WarpGrepClientConfig,\n WarpGrepInput,\n WarpGrepResult,\n WarpGrepContext,\n WarpGrepToolConfig,\n GitHubSearchInput,\n GitHubReadFileInput,\n GitHubReadFileResult,\n RemoteCommands,\n} from './types.js';\nimport { createCodeStorageHttpCommands } from './providers/code_storage_http.js';\nimport { parseGitHubUrl } from './utils/github.js';\n\nconst DEFAULT_CODE_SEARCH_URL = 'https://morphllm.com';\n\n/**\n * Lazy-load LocalRipgrepProvider to avoid importing Node.js-specific\n * modules (child_process, fs) in edge environments like Cloudflare Workers.\n * Only loads when actually needed (i.e., when no remoteCommands or provider is specified).\n */\nasync function getLocalProvider(repoRoot: string, excludes?: string[], allowNames?: string[]): Promise<WarpGrepProvider> {\n const { LocalRipgrepProvider } = await import('./providers/local.js');\n const opts = allowNames?.length ? { allowNames } : undefined;\n return new LocalRipgrepProvider(repoRoot, excludes, opts);\n}\n\n/**\n * WarpGrep client for programmatic code search\n * \n * @example\n * ```typescript\n * import { WarpGrepClient } from '@morphllm/morphsdk';\n * \n * const client = new WarpGrepClient({ morphApiKey: process.env.MORPH_API_KEY });\n * \n * // Simple usage - defaults to LocalRipgrepProvider\n * const result = await client.execute({\n * searchTerm: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n *\n * // With custom excludes\n * const result = await client.execute({\n * searchTerm: 'Find database models',\n * repoRoot: '.',\n * excludes: ['node_modules', '.git', 'dist']\n * });\n * ```\n */\nexport class WarpGrepClient {\n private config: WarpGrepClientConfig;\n\n constructor(config: WarpGrepClientConfig = {}) {\n this.config = { ...config };\n }\n\n /**\n * Execute a code search\n *\n * @param input - Search parameters including searchTerm, repoRoot, and optional provider\n * @returns Search results with relevant code contexts, or an AsyncGenerator if streamSteps is true\n *\n * @example\n * ```typescript\n * // Standard execution\n * const result = await client.execute({\n * searchTerm: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n *\n * if (result.success) {\n * for (const ctx of result.contexts) {\n * console.log(`File: ${ctx.file}`);\n * console.log(ctx.content);\n * }\n * }\n *\n * // Streaming execution\n * const stream = client.execute({\n * searchTerm: 'Find auth middleware',\n * repoRoot: '.',\n * streamSteps: true\n * });\n *\n * for await (const step of stream) {\n * console.log(`Turn ${step.turn}:`, step.toolCalls);\n * }\n * ```\n */\n execute(input: WarpGrepInput & { streamSteps: true }): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined>;\n execute(input: WarpGrepInput & { streamSteps?: false | undefined }): Promise<WarpGrepResult>;\n execute(input: WarpGrepInput): Promise<WarpGrepResult> | AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n const toolConfig: WarpGrepToolConfig = {\n repoRoot: input.repoRoot,\n remoteCommands: input.remoteCommands,\n provider: input.provider,\n excludes: input.excludes,\n includes: input.includes,\n debug: input.debug ?? this.config.debug,\n morphApiKey: this.config.morphApiKey,\n morphApiUrl: this.config.morphApiUrl,\n retryConfig: this.config.retryConfig,\n timeout: this.config.timeout,\n search_type: input.search_type,\n };\n\n if (input.streamSteps) {\n return executeToolCallStreaming({ search_term: input.searchTerm }, toolConfig);\n }\n return executeToolCall({ search_term: input.searchTerm }, toolConfig);\n }\n\n /**\n * Search a public GitHub repository\n *\n * @example\n * ```typescript\n * // Simple usage\n * const result = await client.searchGitHub({\n * searchTerm: 'Find authentication middleware',\n * github: 'vercel/next.js',\n * });\n *\n * // With streaming\n * const stream = client.searchGitHub({\n * searchTerm: 'Find auth middleware',\n * github: 'https://github.com/vercel/next.js',\n * streamSteps: true,\n * });\n * for await (const step of stream) {\n * console.log(`Turn ${step.turn}:`, step.toolCalls);\n * }\n * ```\n */\n searchGitHub(input: GitHubSearchInput & { streamSteps: true }): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined>;\n searchGitHub(input: GitHubSearchInput & { streamSteps?: false | undefined }): Promise<WarpGrepResult>;\n searchGitHub(input: GitHubSearchInput): Promise<WarpGrepResult> | AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n if (input.streamSteps) {\n return this._searchGitHubStreaming(input);\n }\n return this._searchGitHubAsync(input);\n }\n\n /**\n * Read a single file from a public GitHub repository\n *\n * @example\n * ```typescript\n * const result = await client.readGitHubFile({\n * github: 'vercel/next.js',\n * path: 'src/server/app-render/index.tsx',\n * startLine: 1,\n * endLine: 50,\n * });\n * if (result.success) console.log(result.content);\n * ```\n */\n async readGitHubFile(input: GitHubReadFileInput): Promise<GitHubReadFileResult> {\n return executeGitHubReadFile(input, { timeout: this.config.timeout });\n }\n\n private async _resolveGitHubRepo(input: GitHubSearchInput): Promise<{ repo: string; remoteCommands: RemoteCommands }> {\n const { owner, repo } = parseGitHubUrl(input.github);\n const baseUrl = this.config.codeSearchUrl || DEFAULT_CODE_SEARCH_URL;\n const importRes = await fetch(`${baseUrl}/api/code-search/get-or-create?url=${encodeURIComponent(`${owner}/${repo}`)}`);\n if (!importRes.ok) {\n const text = await importRes.text().catch(() => importRes.statusText);\n throw new Error(`Failed to import repo ${owner}/${repo}: ${text}`);\n }\n const { repoId, defaultBranch } = await importRes.json();\n return {\n repo,\n remoteCommands: createCodeStorageHttpCommands({ baseUrl, repoId, branch: input.branch || defaultBranch }),\n };\n }\n\n private async _searchGitHubAsync(input: GitHubSearchInput): Promise<WarpGrepResult> {\n try {\n const { remoteCommands } = await this._resolveGitHubRepo(input);\n return this.execute({\n searchTerm: input.searchTerm,\n repoRoot: '.',\n remoteCommands,\n });\n } catch (error) {\n return { success: false, error: error instanceof Error ? error.message : String(error) };\n }\n }\n\n private async *_searchGitHubStreaming(input: GitHubSearchInput): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n let remoteCommands: RemoteCommands;\n try {\n ({ remoteCommands } = await this._resolveGitHubRepo(input));\n } catch (error) {\n return { success: false, error: error instanceof Error ? error.message : String(error) };\n }\n\n const generator = this.execute({\n searchTerm: input.searchTerm,\n repoRoot: '.',\n remoteCommands,\n streamSteps: true,\n });\n\n let result: WarpGrepResult;\n for (;;) {\n const { value, done } = await generator.next();\n if (done) {\n result = value;\n break;\n }\n yield value;\n }\n return result;\n }\n}\n\n/**\n * Execute a warp grep search directly\n *\n * @param input - Search parameters\n * @param config - Optional client configuration\n * @returns Search results, or an AsyncGenerator if streamSteps is true\n *\n * @example\n * ```typescript\n * import { executeWarpGrep } from '@morphllm/morphsdk/tools/warp-grep';\n *\n * const result = await executeWarpGrep({\n * searchTerm: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n *\n * // Streaming\n * const stream = executeWarpGrep({\n * searchTerm: 'Find auth',\n * repoRoot: '.',\n * streamSteps: true\n * });\n * for await (const step of stream) {\n * console.log(step.turn, step.toolCalls);\n * }\n * ```\n */\nexport function executeWarpGrep(\n input: WarpGrepInput & { streamSteps: true },\n config?: WarpGrepClientConfig\n): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined>;\nexport function executeWarpGrep(\n input: WarpGrepInput & { streamSteps?: false | undefined },\n config?: WarpGrepClientConfig\n): Promise<WarpGrepResult>;\nexport function executeWarpGrep(\n input: WarpGrepInput,\n config?: WarpGrepClientConfig\n): Promise<WarpGrepResult> | AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n const client = new WarpGrepClient(config);\n if (input.streamSteps) {\n return client.execute({ ...input, streamSteps: true });\n }\n return client.execute({ ...input, streamSteps: false });\n}\n\nexport async function executeToolCall(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n const parsed = typeof input === 'string' ? JSON.parse(input) : input;\n\n // Priority: remoteCommands > provider > LocalRipgrepProvider (lazy-loaded for edge compatibility)\n const allowNames = config.search_type === 'node_modules' ? ['node_modules'] : undefined;\n const provider = config.remoteCommands\n ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands)\n : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);\n\n const result = await runWarpGrep({\n searchTerm: parsed.search_term,\n repoRoot: config.repoRoot,\n provider,\n excludes: config.excludes,\n includes: config.includes,\n debug: config.debug ?? false,\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: config.timeout,\n search_type: config.search_type,\n });\n\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n const errorDetails = result.errors?.map(e => e.message).join('; ') || 'unknown reason';\n console.error(`[warp_grep] executeToolCall failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);\n return { success: false, error: `Search did not complete: ${errorDetails}` };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n lines: r.ranges,\n }));\n\n return { success: true, contexts, summary: finish.payload };\n}\n\n/**\n * Helper to process AgentRunResult into WarpGrepResult\n */\nfunction processAgentResult(result: AgentRunResult): WarpGrepResult {\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n const errorDetails = result.errors?.map(e => e.message).join('; ') || 'unknown reason';\n console.error(`[warp_grep] processAgentResult failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);\n return { success: false, error: `Search did not complete: ${errorDetails}` };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n lines: r.ranges,\n }));\n\n return { success: true, contexts, summary: finish.payload };\n}\n\n/**\n * Streaming version of executeToolCall that yields WarpGrepStep for each turn.\n */\nexport async function* executeToolCallStreaming(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n const parsed = typeof input === 'string' ? JSON.parse(input) : input;\n\n // Priority: remoteCommands > provider > LocalRipgrepProvider (lazy-loaded for edge compatibility)\n const allowNames = config.search_type === 'node_modules' ? ['node_modules'] : undefined;\n const provider = config.remoteCommands\n ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands)\n : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);\n\n const generator = runWarpGrepStreaming({\n searchTerm: parsed.search_term,\n repoRoot: config.repoRoot,\n provider,\n excludes: config.excludes,\n includes: config.includes,\n debug: config.debug ?? false,\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: config.timeout,\n search_type: config.search_type,\n });\n\n // Forward all yielded steps\n let agentResult: AgentRunResult;\n for (;;) {\n const { value, done } = await generator.next();\n if (done) {\n agentResult = value;\n break;\n }\n yield value;\n }\n\n return processAgentResult(agentResult);\n}\n\n/**\n * Fetch raw file content from a public GitHub repository.\n * Tries the given branch first, then falls back to main/master/develop.\n */\nasync function fetchRawGitHubFile(\n owner: string,\n repo: string,\n filePath: string,\n branch?: string,\n timeout?: number,\n): Promise<{ content: string; branch: string }> {\n const branches = branch ? [branch] : ['HEAD'];\n const fallbacks = ['main', 'master', 'develop'];\n\n const fetchWithTimeout = (url: string) =>\n timeout ? fetch(url, { signal: AbortSignal.timeout(timeout) }) : fetch(url);\n\n for (const b of branches) {\n const url = `https://raw.githubusercontent.com/${owner}/${repo}/${b}/${filePath}`;\n const res = await fetchWithTimeout(url);\n if (res.ok) return { content: await res.text(), branch: b };\n }\n\n for (const fb of fallbacks) {\n if (branch && fb === branch) continue;\n const url = `https://raw.githubusercontent.com/${owner}/${repo}/${fb}/${filePath}`;\n const res = await fetchWithTimeout(url);\n if (res.ok) return { content: await res.text(), branch: fb };\n }\n\n throw new Error(`File not found: ${owner}/${repo}/${filePath}`);\n}\n\n/**\n * Read a single file (or line range) from a public GitHub repository\n */\nexport async function executeGitHubReadFile(\n input: GitHubReadFileInput,\n config?: { timeout?: number },\n): Promise<GitHubReadFileResult> {\n try {\n const { owner, repo } = parseGitHubUrl(input.github);\n const { content: raw, branch } = await fetchRawGitHubFile(\n owner, repo, input.path, input.branch, config?.timeout,\n );\n\n const allLines = raw.split('\\n');\n const totalLines = allLines.length;\n const start = Math.max(1, input.startLine ?? 1);\n const end = Math.min(totalLines, input.endLine ?? totalLines);\n\n const selected = allLines.slice(start - 1, end);\n const padWidth = String(end).length;\n const numbered = selected\n .map((line, i) => `${String(start + i).padStart(padWidth)}|${line}`)\n .join('\\n');\n\n return {\n success: true,\n content: numbered,\n path: input.path,\n github: `${owner}/${repo}`,\n branch,\n lineRange: [start, end],\n totalLines,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Format a GitHub read file result for display or tool responses\n */\nexport function formatGitHubReadFileResult(result: GitHubReadFileResult): string {\n if (!result.success) {\n return `Failed to read file: ${result.error}`;\n }\n\n const rangeStr = result.lineRange\n ? ` (lines ${result.lineRange[0]}-${result.lineRange[1]} of ${result.totalLines})`\n : '';\n\n return `File: ${result.github}/${result.path}${rangeStr}\\n\\n${result.content}`;\n}\n\n/**\n * Format warp grep results for display or tool responses\n * \n * @param result - The search result\n * @returns Formatted string representation\n */\nexport function formatResult(result: WarpGrepResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (!result.contexts || result.contexts.length === 0) {\n return 'No relevant code found. Try rephrasing your search term.';\n }\n\n const parts: string[] = [];\n parts.push(`Morph Fast Context subagent performed search on repository:\\n`);\n parts.push('Relevant context found:');\n\n for (const ctx of result.contexts) {\n const rangeStr = !ctx.lines || ctx.lines === '*'\n ? '*'\n : ctx.lines.map(([s, e]) => `${s}-${e}`).join(',');\n parts.push(`- ${ctx.file}:${rangeStr}`);\n }\n\n parts.push('\\nHere is the content of files:\\n');\n\n for (const ctx of result.contexts) {\n const rangeStr = !ctx.lines || ctx.lines === '*'\n ? ''\n : ` lines=\"${ctx.lines.map(([s, e]) => `${s}-${e}`).join(',')}\"`;\n parts.push(`<file path=\"${ctx.file}\"${rangeStr}>`);\n parts.push(ctx.content);\n parts.push('</file>\\n');\n }\n\n return parts.join('\\n');\n}\n\n","/**\n * GitHub SDK Types\n *\n * Type definitions for the Morph GitHub integration.\n * Users connect GitHub in the Morph dashboard, then use these\n * types to interact with their GitHub repos through the SDK.\n */\n\n// =============================================================================\n// Configuration\n// =============================================================================\n\n/**\n * Configuration for the GitHub client\n */\nexport interface GitHubClientConfig {\n /** Morph API key (defaults to MORPH_API_KEY env var) */\n apiKey?: string;\n /** Default installation ID to use (optional, can be specified per-request) */\n installationId?: string;\n /** Base URL for the Morph API (defaults to https://api.morphllm.com) */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n// =============================================================================\n// Core Types\n// =============================================================================\n\n/**\n * A GitHub App installation (connected GitHub account)\n */\nexport interface Installation {\n /** Installation ID (use this for subsequent requests) */\n id: string;\n /** GitHub account login (username or org name) */\n accountLogin: string;\n /** Account type */\n accountType: \"User\" | \"Organization\";\n /** Custom display name (set in Morph dashboard) */\n displayName?: string;\n /** Whether check runs are disabled (only PR comments posted) */\n disableCheckRun: boolean;\n /** Whether to keep all previous PR comments (vs. replacing with latest) */\n keepCommentHistory: boolean;\n /** Browser automation model used for preview tests */\n model: string;\n}\n\n/**\n * Input for updating installation settings\n */\nexport interface UpdateInstallationInput {\n /** Installation ID to update */\n installationId: string;\n /** Custom display name */\n displayName?: string;\n /** Whether to disable check runs */\n disableCheckRun?: boolean;\n /** Whether to keep comment history */\n keepCommentHistory?: boolean;\n /** Browser automation model */\n model?: string;\n}\n\n/**\n * Site authentication credentials for a repo or project\n */\nexport interface SiteAuth {\n /** Login username or email */\n username: string | null;\n /** Login password */\n password: string | null;\n}\n\n/**\n * A repository with its Morph configuration\n */\nexport interface RepoConfig {\n /** Database UUID — use this for update/remove operations */\n id: string;\n /** GitHub's numeric repo ID */\n githubId: number;\n /** Full name including owner (e.g., \"acme/app\") */\n fullName: string;\n /** Repository name (e.g., \"app\") */\n name: string;\n /** Whether Morph tests are enabled */\n enabled: boolean;\n /** Whether to also test on mobile viewport */\n testMobile: boolean;\n /** Path filter — only trigger tests when files match this prefix */\n pathFilter: string | null;\n /** Custom instructions for the AI agent */\n customInstructions: string | null;\n /** Site authentication credentials */\n auth: SiteAuth | null;\n}\n\n/**\n * Input for updating a repo's configuration\n */\nexport interface UpdateRepoInput {\n /** Repo DB ID (from RepoConfig.id) */\n repoId: string;\n /** Whether Morph tests are enabled */\n enabled?: boolean;\n /** Whether to also test on mobile viewport */\n testMobile?: boolean;\n /** Path filter for conditional triggers */\n pathFilter?: string | null;\n /** Custom instructions for the AI agent */\n customInstructions?: string | null;\n /** Site auth credentials (null to clear) */\n auth?: { username?: string; password?: string; cookies?: unknown } | null;\n}\n\n/**\n * Input for syncing repos from GitHub\n */\nexport interface SyncReposInput {\n /** Installation ID to sync repos for */\n installationId: string;\n}\n\n/**\n * A monorepo sub-project scoped under a repo\n */\nexport interface Project {\n /** Project DB UUID */\n id: string;\n /** Parent repo DB UUID */\n repoId: string;\n /** Project name */\n name: string;\n /** Path filter within the repo */\n pathFilter: string | null;\n /** Whether tests are enabled */\n enabled: boolean;\n /** Whether to test on mobile viewport */\n testMobile: boolean;\n /** Custom instructions for the AI agent */\n customInstructions: string | null;\n /** Site authentication credentials */\n auth: SiteAuth | null;\n /** Creation timestamp (ISO 8601) */\n createdAt: string;\n}\n\n/**\n * Input for creating a project\n */\nexport interface CreateProjectInput {\n /** Parent repo DB ID */\n repoId: string;\n /** Project name (must be unique within the repo) */\n name: string;\n /** Path filter within the repo (e.g., \"packages/web/\") */\n pathFilter: string;\n /** Custom instructions for the AI agent */\n customInstructions?: string;\n}\n\n/**\n * Input for updating a project\n */\nexport interface UpdateProjectInput {\n /** Project DB ID */\n projectId: string;\n /** Whether tests are enabled */\n enabled?: boolean;\n /** Whether to test on mobile viewport */\n testMobile?: boolean;\n /** Path filter within the repo */\n pathFilter?: string | null;\n /** Custom instructions for the AI agent */\n customInstructions?: string | null;\n /** Site auth credentials (null to clear) */\n auth?: { username?: string; password?: string; cookies?: unknown } | null;\n}\n\n/**\n * Input for listing projects\n */\nexport interface ListProjectsInput {\n /** Parent repo DB ID */\n repoId: string;\n}\n\n/**\n * A GitHub repository\n */\nexport interface Repo {\n /** GitHub's numeric repo ID */\n id: number;\n /** Repository name (e.g., \"app\") */\n name: string;\n /** Full name including owner (e.g., \"acme/app\") */\n fullName: string;\n /** Whether the repo is private */\n private: boolean;\n /** Default branch name */\n defaultBranch?: string;\n}\n\n/**\n * A pull request (basic info)\n */\nexport interface PullRequest {\n /** PR number */\n number: number;\n /** PR title */\n title: string;\n /** PR description/body */\n body: string | null;\n /** PR state */\n state: \"open\" | \"closed\";\n /** Author's GitHub username */\n author: string;\n /** HEAD commit SHA */\n headSha: string;\n /** Base branch name */\n baseBranch: string;\n /** HEAD branch name */\n headBranch: string;\n /** Creation timestamp (ISO 8601) */\n createdAt: string;\n /** Last update timestamp (ISO 8601) */\n updatedAt: string;\n}\n\n/**\n * A pull request with full context (diff and files)\n */\nexport interface PullRequestWithContext extends PullRequest {\n /** Full unified diff */\n diff: string;\n /** List of changed files with patches */\n files: FileChange[];\n}\n\n/**\n * A file changed in a pull request\n */\nexport interface FileChange {\n /** File path */\n filename: string;\n /** Change status */\n status: \"added\" | \"removed\" | \"modified\" | \"renamed\";\n /** Number of lines added */\n additions: number;\n /** Number of lines deleted */\n deletions: number;\n /** Unified diff patch for this file */\n patch?: string;\n}\n\n/**\n * A deployment (e.g., Vercel preview)\n */\nexport interface Deployment {\n /** Deployment ID */\n id: number;\n /** Commit SHA this deployment is for */\n sha: string;\n /** Environment name (e.g., \"preview\", \"production\") */\n environment: string;\n /** Deployment state */\n state: \"pending\" | \"success\" | \"failure\" | \"error\" | \"inactive\" | \"in_progress\" | \"queued\";\n /** Preview/deployment URL (if available) */\n url: string | null;\n /** Creation timestamp (ISO 8601) */\n createdAt: string;\n}\n\n/**\n * A comment on a PR/issue\n */\nexport interface Comment {\n /** Comment ID */\n id: number;\n /** Comment body/content */\n body: string;\n /** Author's GitHub username */\n author: string;\n /** Creation timestamp (ISO 8601) */\n createdAt: string;\n /** Last update timestamp (ISO 8601) */\n updatedAt: string;\n}\n\n/**\n * A GitHub check run (CI status)\n */\nexport interface CheckRun {\n /** Check run ID */\n id: number;\n /** Check run name */\n name: string;\n /** Current status */\n status: \"queued\" | \"in_progress\" | \"completed\";\n /** Conclusion (only set when status is \"completed\") */\n conclusion?:\n | \"success\"\n | \"failure\"\n | \"neutral\"\n | \"cancelled\"\n | \"skipped\"\n | \"timed_out\"\n | \"action_required\";\n /** Start timestamp (ISO 8601) */\n startedAt?: string;\n /** Completion timestamp (ISO 8601) */\n completedAt?: string;\n}\n\n// =============================================================================\n// Input Types\n// =============================================================================\n\n/**\n * Input for listing repositories\n */\nexport interface ListReposInput {\n /** Installation ID to list repos for */\n installationId: string;\n}\n\n/**\n * Input for listing pull requests\n */\nexport interface ListPullRequestsInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Filter by PR state (default: \"open\") */\n state?: \"open\" | \"closed\" | \"all\";\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for getting a single pull request\n */\nexport interface GetPullRequestInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** PR number */\n number: number;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for listing deployments\n */\nexport interface ListDeploymentsInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Filter by commit SHA */\n sha?: string;\n /** Filter by environment name */\n environment?: string;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for listing comments on a PR\n */\nexport interface ListCommentsInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** PR number */\n pr: number;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for creating a comment\n */\nexport interface CreateCommentInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** PR number */\n pr: number;\n /** Comment body (Markdown supported) */\n body: string;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for updating a comment\n */\nexport interface UpdateCommentInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Comment ID to update */\n commentId: number;\n /** New comment body */\n body: string;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for deleting a comment\n */\nexport interface DeleteCommentInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Comment ID to delete */\n commentId: number;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for creating a check run\n */\nexport interface CreateCheckRunInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Commit SHA to create check run for */\n sha: string;\n /** Check run name (e.g., \"Preview Test\") */\n name: string;\n /** Initial status */\n status: \"queued\" | \"in_progress\";\n /** Output title */\n title?: string;\n /** Output summary (Markdown supported) */\n summary?: string;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n/**\n * Input for updating a check run\n */\nexport interface UpdateCheckRunInput {\n /** Repository owner */\n owner: string;\n /** Repository name */\n repo: string;\n /** Check run ID to update */\n checkRunId: number;\n /** New status */\n status?: \"queued\" | \"in_progress\" | \"completed\";\n /** Conclusion (required if status is \"completed\") */\n conclusion?: CheckRun[\"conclusion\"];\n /** Output title */\n title?: string;\n /** Output summary (Markdown supported) */\n summary?: string;\n /** Output text (detailed info, Markdown supported) */\n text?: string;\n /** Installation ID (uses default if not specified) */\n installationId?: string;\n}\n\n// =============================================================================\n// Error Types\n// =============================================================================\n\n/**\n * Error thrown by GitHub operations\n */\nexport class GitHubError extends Error {\n /** HTTP status code */\n status: number;\n /** Error code from API */\n code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = \"GitHubError\";\n this.status = status;\n this.code = code;\n }\n}\n\n/**\n * Error thrown when no installation is found or specified\n */\nexport class NoInstallationError extends GitHubError {\n constructor(message = \"No GitHub installation found. Connect GitHub at morphllm.com/dashboard/integrations/github\") {\n super(message, 404, \"NO_INSTALLATION\");\n }\n}\n\n/**\n * Error thrown when resource is not found\n */\nexport class NotFoundError extends GitHubError {\n constructor(resource: string) {\n super(`${resource} not found`, 404, \"NOT_FOUND\");\n }\n}\n\n/**\n * Error thrown when user lacks permission\n */\nexport class PermissionError extends GitHubError {\n constructor(message = \"Insufficient permissions for this operation\") {\n super(message, 403, \"PERMISSION_DENIED\");\n }\n}\n","/**\n * GitHub SDK Client\n *\n * Provides access to GitHub repositories, pull requests, deployments,\n * comments, and check runs through the user's connected GitHub account.\n *\n * All operations are proxied through the Morph API - installation tokens\n * are never exposed to the client.\n */\n\nimport type {\n GitHubClientConfig,\n Installation,\n Repo,\n RepoConfig,\n PullRequest,\n PullRequestWithContext,\n Deployment,\n Comment,\n CheckRun,\n Project,\n ListReposInput,\n ListPullRequestsInput,\n GetPullRequestInput,\n ListDeploymentsInput,\n ListCommentsInput,\n CreateCommentInput,\n UpdateCommentInput,\n DeleteCommentInput,\n CreateCheckRunInput,\n UpdateCheckRunInput,\n UpdateInstallationInput,\n UpdateRepoInput,\n SyncReposInput,\n CreateProjectInput,\n UpdateProjectInput,\n ListProjectsInput,\n} from \"./types.js\";\n\nimport { GitHubError, NoInstallationError, NotFoundError, PermissionError } from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.morphllm.com\";\nconst DEFAULT_TIMEOUT = 30000;\n\n/**\n * GitHub SDK Client\n *\n * @example\n * ```typescript\n * import { MorphClient } from '@morphllm/morphsdk';\n *\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n *\n * // List installations\n * const installations = await morph.github.installations.list();\n *\n * // Get PR with context\n * const pr = await morph.github.pullRequests.get({\n * owner: \"acme\",\n * repo: \"app\",\n * number: 42\n * });\n * ```\n */\nexport class GitHubClient {\n private apiKey: string;\n private baseUrl: string;\n private timeout: number;\n private debug: boolean;\n private defaultInstallationId?: string;\n\n /** Installation operations */\n public installations: {\n list: () => Promise<Installation[]>;\n get: (installationId: string) => Promise<Installation>;\n update: (input: UpdateInstallationInput) => Promise<Installation>;\n disconnect: (installationId: string) => Promise<{ success: boolean; alreadyDeleted: boolean }>;\n };\n\n /** Repository operations */\n public repos: {\n list: (input: ListReposInput) => Promise<RepoConfig[]>;\n get: (repoId: string) => Promise<RepoConfig>;\n update: (input: UpdateRepoInput) => Promise<RepoConfig>;\n remove: (repoId: string) => Promise<{ success: boolean; alreadyRemoved: boolean }>;\n sync: (input: SyncReposInput) => Promise<{ count: number }>;\n };\n\n /** Project operations (monorepo sub-projects) */\n public projects: {\n list: (input: ListProjectsInput) => Promise<Project[]>;\n create: (input: CreateProjectInput) => Promise<Project>;\n update: (input: UpdateProjectInput) => Promise<Project>;\n delete: (projectId: string) => Promise<{ success: boolean }>;\n };\n\n /** Pull request operations */\n public pullRequests: {\n list: (input: ListPullRequestsInput) => Promise<PullRequest[]>;\n get: (input: GetPullRequestInput) => Promise<PullRequestWithContext>;\n };\n\n /** Deployment operations */\n public deployments: {\n list: (input: ListDeploymentsInput) => Promise<Deployment[]>;\n };\n\n /** Comment operations */\n public comments: {\n list: (input: ListCommentsInput) => Promise<Comment[]>;\n create: (input: CreateCommentInput) => Promise<Comment>;\n update: (input: UpdateCommentInput) => Promise<Comment>;\n delete: (input: DeleteCommentInput) => Promise<void>;\n };\n\n /** Check run operations */\n public checkRuns: {\n create: (input: CreateCheckRunInput) => Promise<CheckRun>;\n update: (input: UpdateCheckRunInput) => Promise<CheckRun>;\n };\n\n /**\n * Get the GitHub App installation URL.\n * Users visit this URL once to install the Morph GitHub App on their account/org.\n */\n public getInstallUrl(): string {\n return \"https://github.com/apps/morph-subagents/installations/new\";\n }\n\n constructor(config: GitHubClientConfig = {}) {\n this.apiKey = config.apiKey || process.env.MORPH_API_KEY || \"\";\n this.baseUrl = config.baseUrl || DEFAULT_BASE_URL;\n this.timeout = config.timeout || DEFAULT_TIMEOUT;\n this.debug = config.debug || false;\n this.defaultInstallationId = config.installationId;\n\n if (!this.apiKey) {\n throw new Error(\"API key required. Set MORPH_API_KEY or pass apiKey in config.\");\n }\n\n // Bind all methods\n this.installations = {\n list: this.listInstallations.bind(this),\n get: this.getInstallation.bind(this),\n update: this.updateInstallation.bind(this),\n disconnect: this.disconnectInstallation.bind(this),\n };\n\n this.repos = {\n list: this.listRepos.bind(this),\n get: this.getRepo.bind(this),\n update: this.updateRepo.bind(this),\n remove: this.removeRepo.bind(this),\n sync: this.syncRepos.bind(this),\n };\n\n this.projects = {\n list: this.listProjects.bind(this),\n create: this.createProject.bind(this),\n update: this.updateProject.bind(this),\n delete: this.deleteProject.bind(this),\n };\n\n this.pullRequests = {\n list: this.listPullRequests.bind(this),\n get: this.getPullRequest.bind(this),\n };\n\n this.deployments = {\n list: this.listDeployments.bind(this),\n };\n\n this.comments = {\n list: this.listComments.bind(this),\n create: this.createComment.bind(this),\n update: this.updateComment.bind(this),\n delete: this.deleteComment.bind(this),\n };\n\n this.checkRuns = {\n create: this.createCheckRun.bind(this),\n update: this.updateCheckRun.bind(this),\n };\n }\n\n /**\n * Make an authenticated API request\n */\n private async request<T>(\n method: string,\n path: string,\n body?: Record<string, unknown>\n ): Promise<T> {\n const url = `${this.baseUrl}${path}`;\n\n if (this.debug) {\n console.log(`[GitHub SDK] ${method} ${path}`, body || \"\");\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n const message = errorData.error || errorData.detail || errorData.message || response.statusText;\n\n if (this.debug) {\n console.error(`[GitHub SDK] Error ${response.status}:`, message);\n }\n\n // Map to specific error types\n if (response.status === 404) {\n if (message.includes(\"installation\")) {\n throw new NoInstallationError(message);\n }\n throw new NotFoundError(message);\n }\n if (response.status === 403) {\n throw new PermissionError(message);\n }\n throw new GitHubError(message, response.status, errorData.code);\n }\n\n const data = await response.json();\n\n if (this.debug) {\n console.log(`[GitHub SDK] Response:`, JSON.stringify(data).slice(0, 200));\n }\n\n return data as T;\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof GitHubError) {\n throw error;\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new GitHubError(\"Request timeout\", 408, \"TIMEOUT\");\n }\n\n throw new GitHubError(\n error instanceof Error ? error.message : \"Unknown error\",\n 500,\n \"UNKNOWN\"\n );\n }\n }\n\n /**\n * Get the installation ID to use for a request\n */\n private getInstallationId(input?: { installationId?: string }): string | undefined {\n return input?.installationId || this.defaultInstallationId;\n }\n\n // ==========================================================================\n // Installations\n // ==========================================================================\n\n private async listInstallations(): Promise<Installation[]> {\n return this.request<Installation[]>(\"GET\", \"/api/v1/github/installations\");\n }\n\n private async getInstallation(installationId: string): Promise<Installation> {\n return this.request<Installation>(\"GET\", `/api/v1/github/installations/${installationId}`);\n }\n\n private async updateInstallation(input: UpdateInstallationInput): Promise<Installation> {\n if (this.debug) console.log(\"[GitHub SDK] updateInstallation\", input.installationId);\n const { installationId, ...body } = input;\n return this.request<Installation>(\"PATCH\", `/api/v1/github/installations/${installationId}`, body);\n }\n\n private async disconnectInstallation(installationId: string): Promise<{ success: boolean; alreadyDeleted: boolean }> {\n if (this.debug) console.log(\"[GitHub SDK] disconnectInstallation\", installationId);\n return this.request<{ success: boolean; alreadyDeleted: boolean }>(\"DELETE\", `/api/v1/github/installations/${installationId}`);\n }\n\n // ==========================================================================\n // Repositories\n // ==========================================================================\n\n private async listRepos(input: ListReposInput): Promise<RepoConfig[]> {\n const installationId = input.installationId || this.defaultInstallationId;\n if (!installationId) {\n throw new NoInstallationError(\"installationId required. Call installations.list() first.\");\n }\n return this.request<RepoConfig[]>(\"GET\", `/api/v1/github/installations/${installationId}/repos`);\n }\n\n private async getRepo(repoId: string): Promise<RepoConfig> {\n if (this.debug) console.log(\"[GitHub SDK] getRepo\", repoId);\n return this.request<RepoConfig>(\"GET\", `/api/v1/github/repos/${repoId}`);\n }\n\n private async updateRepo(input: UpdateRepoInput): Promise<RepoConfig> {\n if (this.debug) console.log(\"[GitHub SDK] updateRepo\", input.repoId);\n const { repoId, ...body } = input;\n return this.request<RepoConfig>(\"PATCH\", `/api/v1/github/repos/${repoId}`, body);\n }\n\n private async removeRepo(repoId: string): Promise<{ success: boolean; alreadyRemoved: boolean }> {\n if (this.debug) console.log(\"[GitHub SDK] removeRepo\", repoId);\n return this.request<{ success: boolean; alreadyRemoved: boolean }>(\"DELETE\", `/api/v1/github/repos/${repoId}`);\n }\n\n private async syncRepos(input: SyncReposInput): Promise<{ count: number }> {\n const installationId = input.installationId || this.defaultInstallationId;\n if (!installationId) {\n throw new NoInstallationError(\"installationId required. Call installations.list() first.\");\n }\n if (this.debug) console.log(\"[GitHub SDK] syncRepos\", installationId);\n return this.request<{ count: number }>(\"POST\", `/api/v1/github/installations/${installationId}/repos/sync`);\n }\n\n // ==========================================================================\n // Projects (monorepo sub-projects)\n // ==========================================================================\n\n private async listProjects(input: ListProjectsInput): Promise<Project[]> {\n if (this.debug) console.log(\"[GitHub SDK] listProjects\", input.repoId);\n return this.request<Project[]>(\"GET\", `/api/v1/github/repos/${input.repoId}/projects`);\n }\n\n private async createProject(input: CreateProjectInput): Promise<Project> {\n if (this.debug) console.log(\"[GitHub SDK] createProject\", input.repoId, input.name);\n const { repoId, ...body } = input;\n return this.request<Project>(\"POST\", `/api/v1/github/repos/${repoId}/projects`, body);\n }\n\n private async updateProject(input: UpdateProjectInput): Promise<Project> {\n if (this.debug) console.log(\"[GitHub SDK] updateProject\", input.projectId);\n const { projectId, ...body } = input;\n return this.request<Project>(\"PATCH\", `/api/v1/github/projects/${projectId}`, body);\n }\n\n private async deleteProject(projectId: string): Promise<{ success: boolean }> {\n if (this.debug) console.log(\"[GitHub SDK] deleteProject\", projectId);\n return this.request<{ success: boolean }>(\"DELETE\", `/api/v1/github/projects/${projectId}`);\n }\n\n // ==========================================================================\n // Pull Requests\n // ==========================================================================\n\n private async listPullRequests(input: ListPullRequestsInput): Promise<PullRequest[]> {\n const installationId = this.getInstallationId(input);\n const params = new URLSearchParams({\n owner: input.owner,\n repo: input.repo,\n ...(input.state && { state: input.state }),\n ...(installationId && { installationId }),\n });\n return this.request<PullRequest[]>(\"GET\", `/api/v1/github/pulls?${params}`);\n }\n\n private async getPullRequest(input: GetPullRequestInput): Promise<PullRequestWithContext> {\n const installationId = this.getInstallationId(input);\n const params = new URLSearchParams({\n owner: input.owner,\n repo: input.repo,\n ...(installationId && { installationId }),\n });\n return this.request<PullRequestWithContext>(\n \"GET\",\n `/api/v1/github/pulls/${input.number}?${params}`\n );\n }\n\n // ==========================================================================\n // Deployments\n // ==========================================================================\n\n private async listDeployments(input: ListDeploymentsInput): Promise<Deployment[]> {\n const installationId = this.getInstallationId(input);\n const params = new URLSearchParams({\n owner: input.owner,\n repo: input.repo,\n ...(input.sha && { sha: input.sha }),\n ...(input.environment && { environment: input.environment }),\n ...(installationId && { installationId }),\n });\n return this.request<Deployment[]>(\"GET\", `/api/v1/github/deployments?${params}`);\n }\n\n // ==========================================================================\n // Comments\n // ==========================================================================\n\n private async listComments(input: ListCommentsInput): Promise<Comment[]> {\n const installationId = this.getInstallationId(input);\n const params = new URLSearchParams({\n owner: input.owner,\n repo: input.repo,\n pr: String(input.pr),\n ...(installationId && { installationId }),\n });\n return this.request<Comment[]>(\"GET\", `/api/v1/github/comments?${params}`);\n }\n\n private async createComment(input: CreateCommentInput): Promise<Comment> {\n const installationId = this.getInstallationId(input);\n return this.request<Comment>(\"POST\", \"/api/v1/github/comments\", {\n owner: input.owner,\n repo: input.repo,\n pr: input.pr,\n body: input.body,\n ...(installationId && { installationId }),\n });\n }\n\n private async updateComment(input: UpdateCommentInput): Promise<Comment> {\n const installationId = this.getInstallationId(input);\n return this.request<Comment>(\"PATCH\", `/api/v1/github/comments/${input.commentId}`, {\n owner: input.owner,\n repo: input.repo,\n body: input.body,\n ...(installationId && { installationId }),\n });\n }\n\n private async deleteComment(input: DeleteCommentInput): Promise<void> {\n const installationId = this.getInstallationId(input);\n const params = new URLSearchParams({\n owner: input.owner,\n repo: input.repo,\n ...(installationId && { installationId }),\n });\n await this.request<void>(\"DELETE\", `/api/v1/github/comments/${input.commentId}?${params}`);\n }\n\n // ==========================================================================\n // Check Runs\n // ==========================================================================\n\n private async createCheckRun(input: CreateCheckRunInput): Promise<CheckRun> {\n const installationId = this.getInstallationId(input);\n return this.request<CheckRun>(\"POST\", \"/api/v1/github/check-runs\", {\n owner: input.owner,\n repo: input.repo,\n sha: input.sha,\n name: input.name,\n status: input.status,\n ...(input.title && { title: input.title }),\n ...(input.summary && { summary: input.summary }),\n ...(installationId && { installationId }),\n });\n }\n\n private async updateCheckRun(input: UpdateCheckRunInput): Promise<CheckRun> {\n const installationId = this.getInstallationId(input);\n return this.request<CheckRun>(\"PATCH\", `/api/v1/github/check-runs/${input.checkRunId}`, {\n owner: input.owner,\n repo: input.repo,\n ...(input.status && { status: input.status }),\n ...(input.conclusion && { conclusion: input.conclusion }),\n ...(input.title && { title: input.title }),\n ...(input.summary && { summary: input.summary }),\n ...(input.text && { text: input.text }),\n ...(installationId && { installationId }),\n });\n }\n}\n","/**\n * Morph Git Client - Simple, high-level Git operations\n * Built on isomorphic-git with explicit configuration\n */\n\n\nimport git from 'isomorphic-git';\nimport http from 'isomorphic-git/http/node';\nimport fs from 'fs';\nimport type {\n CloneOptions,\n PushOptions,\n PullOptions,\n AddOptions,\n CommitOptions,\n StatusOptions,\n LogOptions,\n CheckoutOptions,\n BranchOptions,\n DiffOptions,\n CommitObject,\n StatusResult,\n MorphGitConfig,\n MorphNotesSchema,\n WaitForEmbeddingsOptions,\n EmbeddingProgress,\n} from './types.js';\n\nconst DEFAULT_PROXY_URL = 'https://repos.morphllm.com';\n\n/**\n * MorphGit - Git operations for AI agents with Morph backend\n * \n * @example\n * ```typescript\n * import { MorphGit } from 'morphsdk/git';\n * \n * const morphGit = new MorphGit({\n * apiKey: process.env.MORPH_API_KEY!,\n * proxyUrl: 'https://repos.morphllm.com' // Optional\n * });\n * \n * await morphGit.init({ repoId: 'my-project', dir: './my-project' });\n * await morphGit.push({ dir: './my-project' });\n * ```\n */\nexport class MorphGit {\n private readonly apiKey: string;\n private readonly proxyUrl: string;\n\n constructor(config: MorphGitConfig) {\n // Validate API key\n if (!config.apiKey) {\n throw new Error('API key is required. Get one at https://morphllm.com/dashboard');\n }\n \n if (!config.apiKey.startsWith('sk-') && !config.apiKey.startsWith('morph-')) {\n throw new Error('Invalid API key format. Expected: sk-... or morph-...');\n }\n \n this.apiKey = config.apiKey;\n this.proxyUrl = config.proxyUrl || DEFAULT_PROXY_URL;\n }\n \n /**\n * Get auth callback for isomorphic-git operations\n * @private\n */\n private getAuthCallback() {\n return () => ({\n username: 'morph',\n password: this.apiKey,\n });\n }\n\n /**\n * Initialize a new repository\n * Creates the repo in the database and in the git provider\n * \n * @example\n * ```ts\n * await morphGit.init({\n * repoId: 'my-project',\n * dir: './my-project',\n * defaultBranch: 'main'\n * });\n * ```\n */\n async init(options: {\n repoId: string;\n dir: string;\n defaultBranch?: string;\n }): Promise<void> {\n const { repoId, dir, defaultBranch = 'main' } = options;\n\n // Call backend API to create repository\n const response = await fetch(`${this.proxyUrl}/v1/repos`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n repoId,\n name: repoId,\n defaultBranch,\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Failed to create repository: ${error}`);\n }\n\n // Initialize local git repository (industry standard: no clone needed)\n await git.init({\n fs,\n dir,\n defaultBranch,\n });\n\n // Add remote pointing to Morph git-proxy\n await git.addRemote({\n fs,\n dir,\n remote: 'origin',\n url: `${this.proxyUrl}/v1/repos/${repoId}`,\n });\n\n console.log(`✓ Repository '${repoId}' initialized`);\n }\n\n /**\n * Clone a repository from Morph repos\n * \n * @example\n * ```ts\n * await morphGit.clone({\n * repoId: 'my-project',\n * dir: './my-project'\n * });\n * ```\n */\n async clone(options: CloneOptions): Promise<void> {\n const { repoId, dir, branch = 'main', depth, singleBranch = true } = options;\n\n await git.clone({\n fs,\n http,\n dir,\n url: `${this.proxyUrl}/v1/repos/${repoId}`,\n ref: branch,\n singleBranch,\n depth,\n onAuth: this.getAuthCallback(),\n });\n }\n\n /**\n * Push changes to remote repository\n * \n * @example\n * ```ts\n * await morphGit.push({ \n * dir: './my-project',\n * branch: 'main', // Required: explicit branch name\n * index: true // Optional: generate embeddings for semantic search\n * });\n * ```\n */\n async push(options: PushOptions): Promise<void> {\n const { dir, remote = 'origin', branch, waitForEmbeddings, index = false } = options;\n\n if (!branch) {\n throw new Error(\n 'branch is required for push operations. ' +\n 'Specify the branch explicitly: { dir: \"./my-project\", branch: \"main\" }'\n );\n }\n\n // Get commit hash and repoId before pushing\n const commitHash = await git.resolveRef({ fs, dir, ref: 'HEAD' });\n \n // Get repoId from git remote URL\n let repoId: string | undefined;\n const remotes = await git.listRemotes({ fs, dir });\n const originRemote = remotes.find(r => r.remote === remote);\n if (originRemote) {\n // Extract repoId from URL: https://repos.morphllm.com/v1/repos/{repoId}\n const match = originRemote.url.match(/\\/repos\\/([^\\/]+)$/);\n if (match) {\n repoId = match[1];\n }\n }\n\n await git.push({\n fs,\n http,\n dir,\n remote,\n ref: branch,\n onAuth: this.getAuthCallback(),\n });\n \n // Configure commit after successful push (set index flag)\n if (repoId && commitHash) {\n await this.configureCommit({ repoId, commitHash, branch, index });\n }\n \n // Wait for embeddings if requested (and indexing is enabled)\n if (waitForEmbeddings && repoId && commitHash && index) {\n await this.waitForEmbeddings({ repoId, commitHash });\n }\n }\n\n /**\n * Configure commit settings on the backend after push.\n * Sets the index flag to control embedding generation.\n * @private\n */\n private async configureCommit(options: {\n repoId: string;\n commitHash: string;\n branch: string;\n index: boolean;\n }): Promise<void> {\n const { repoId, commitHash, branch, index } = options;\n \n const response = await fetch(\n `${this.proxyUrl}/v1/repos/${repoId}/commits/${commitHash}/config`,\n {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ index, branch }),\n }\n );\n\n if (!response.ok) {\n // Non-fatal: log warning but don't throw\n console.warn(`Failed to configure commit: ${response.status}`);\n }\n }\n\n /**\n * Pull changes from remote repository\n * \n * @example\n * ```ts\n * await morphGit.pull({ \n * dir: './my-project',\n * branch: 'main' // Required: explicit branch name\n * });\n * ```\n */\n async pull(options: PullOptions): Promise<void> {\n const { dir, remote = 'origin', branch } = options;\n\n if (!branch) {\n throw new Error(\n 'branch is required for pull operations. ' +\n 'Specify the branch explicitly: { dir: \"./my-project\", branch: \"main\" }'\n );\n }\n\n await git.pull({\n fs,\n http,\n dir,\n remote,\n ref: branch,\n onAuth: this.getAuthCallback(),\n author: {\n name: 'Morph Agent',\n email: 'agent@morph.com',\n },\n });\n }\n\n /**\n * Wait for embeddings to complete after push.\n * Polls status endpoint until embeddings are done.\n * \n * @example\n * ```ts\n * await morphGit.push({ dir: './my-project', branch: 'main' });\n * await morphGit.waitForEmbeddings({\n * repoId: 'my-project',\n * onProgress: (p) => console.log(`${p.filesProcessed}/${p.totalFiles}`)\n * });\n * ```\n */\n async waitForEmbeddings(options: WaitForEmbeddingsOptions): Promise<void> {\n const { repoId, commitHash, timeout = 120000, onProgress } = options;\n const startTime = Date.now();\n const pollInterval = 1000; // Poll every 1s\n \n while (Date.now() - startTime < timeout) {\n const statusUrl = `${this.proxyUrl}/v1/repos/${repoId}/embedding-status` +\n (commitHash ? `?commit_hash=${commitHash}` : '');\n \n const response = await fetch(statusUrl, {\n headers: { 'Authorization': `Bearer ${this.apiKey}` }\n });\n \n if (response.status === 404) {\n // No job found yet - might still be creating\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n continue;\n }\n \n if (!response.ok) {\n throw new Error(`Failed to get embedding status: ${response.status}`);\n }\n \n const status = await response.json();\n \n if (onProgress && status.progress) {\n onProgress(status.progress);\n }\n \n if (status.status === 'completed') {\n return; // Done!\n }\n \n if (status.status === 'failed') {\n throw new Error(`Embeddings failed: ${status.error || 'Unknown error'}`);\n }\n \n // Still processing (queued or processing), wait and poll again\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n \n throw new Error(`Embeddings timed out after ${timeout}ms`);\n }\n\n /**\n * Stage a file for commit\n * \n * @example\n * ```ts\n * await morphGit.add({\n * dir: './my-project',\n * filepath: 'src/app.ts'\n * });\n * ```\n */\n async add(options: AddOptions): Promise<void> {\n const { dir, filepath } = options;\n\n await git.add({\n fs,\n dir,\n filepath,\n });\n }\n\n /**\n * Remove a file from staging\n * \n * @example\n * ```ts\n * await morphGit.remove({\n * dir: './my-project',\n * filepath: 'src/old-file.ts'\n * });\n * ```\n */\n async remove(options: AddOptions): Promise<void> {\n const { dir, filepath } = options;\n\n await git.remove({\n fs,\n dir,\n filepath,\n });\n }\n\n /**\n * Commit staged changes\n * \n * @example\n * ```ts\n * await morphGit.commit({\n * dir: './my-project',\n * message: 'Add new feature',\n * author: {\n * name: 'AI Agent',\n * email: 'ai@example.com'\n * },\n * metadata: { issueId: 'PROJ-123', source: 'agent' },\n * chatHistory: [\n * { role: 'user', content: 'Please add a new feature' },\n * { role: 'assistant', content: 'I will add that feature' }\n * ],\n * recordingId: 'rec_123'\n * });\n * ```\n */\n async commit(options: CommitOptions): Promise<string> {\n const { dir, message, author, metadata, chatHistory, recordingId } = options;\n\n // Provide default author if not specified\n const commitAuthor = author || {\n name: 'Morph SDK',\n email: 'sdk@morphllm.com'\n };\n\n const sha = await git.commit({\n fs,\n dir,\n message,\n author: commitAuthor,\n });\n\n // Store notes if any note fields are provided\n if (metadata || chatHistory || recordingId) {\n const notes: MorphNotesSchema = {\n metadata,\n chatHistory,\n recordingId,\n _version: 1\n };\n \n await git.addNote({\n fs,\n dir,\n ref: 'refs/notes/morph-metadata',\n oid: sha,\n note: JSON.stringify(notes, null, 2),\n author: commitAuthor\n });\n }\n\n return sha;\n }\n\n /**\n * Get status of a file\n * \n * @example\n * ```ts\n * const status = await morphGit.status({\n * dir: './my-project',\n * filepath: 'src/app.ts'\n * });\n * console.log(status); // 'modified', '*added', etc.\n * ```\n */\n async status(options: StatusOptions): Promise<string> {\n const { dir, filepath } = options;\n\n if (!filepath) {\n throw new Error('filepath is required for status check');\n }\n\n const status = await git.status({\n fs,\n dir,\n filepath,\n });\n\n return status;\n }\n\n /**\n * Get commit history\n * \n * @example\n * ```ts\n * const commits = await morphGit.log({\n * dir: './my-project',\n * depth: 10\n * });\n * ```\n */\n async log(options: LogOptions): Promise<CommitObject[]> {\n const { dir, depth, ref } = options;\n\n const commits = await git.log({\n fs,\n dir,\n depth,\n ref,\n });\n\n return commits as CommitObject[];\n }\n\n /**\n * Checkout a branch or commit\n * \n * @example\n * ```ts\n * await morphGit.checkout({\n * dir: './my-project',\n * ref: 'feature-branch'\n * });\n * ```\n */\n async checkout(options: CheckoutOptions): Promise<void> {\n const { dir, ref } = options;\n\n await git.checkout({\n fs,\n dir,\n ref,\n });\n }\n\n /**\n * Create a new branch\n * \n * @example\n * ```ts\n * await morphGit.branch({\n * dir: './my-project',\n * name: 'feature-branch',\n * checkout: true\n * });\n * ```\n */\n async branch(options: BranchOptions): Promise<void> {\n const { dir, name, checkout = false } = options;\n\n await git.branch({\n fs,\n dir,\n ref: name,\n checkout,\n });\n }\n\n /**\n * List all branches\n * \n * @example\n * ```ts\n * const branches = await morphGit.listBranches({\n * dir: './my-project'\n * });\n * ```\n */\n async listBranches(options: { dir: string }): Promise<string[]> {\n const { dir } = options;\n\n const branches = await git.listBranches({\n fs,\n dir,\n });\n\n return branches;\n }\n\n /**\n * Get the current branch name\n * \n * @example\n * ```ts\n * const branch = await morphGit.currentBranch({\n * dir: './my-project'\n * });\n * ```\n */\n async currentBranch(options: { dir: string }): Promise<string | undefined> {\n const { dir } = options;\n\n const branch = await git.currentBranch({\n fs,\n dir,\n });\n\n return branch || undefined;\n }\n\n /**\n * Get list of changed files (similar to git diff --name-only)\n * \n * @example\n * ```ts\n * const changes = await morphGit.statusMatrix({\n * dir: './my-project'\n * });\n * ```\n */\n async statusMatrix(options: { dir: string }): Promise<StatusResult[]> {\n const { dir } = options;\n\n const matrix = await git.statusMatrix({\n fs,\n dir,\n });\n\n return matrix.map(([filepath, HEADStatus, workdirStatus, stageStatus]) => {\n let status: StatusResult['status'] = 'unmodified';\n\n // Determine status based on statusMatrix values\n if (HEADStatus === 1 && workdirStatus === 2 && stageStatus === 2) {\n status = 'modified';\n } else if (HEADStatus === 1 && workdirStatus === 2 && stageStatus === 1) {\n status = '*modified';\n } else if (HEADStatus === 0 && workdirStatus === 2 && stageStatus === 2) {\n status = 'added';\n } else if (HEADStatus === 0 && workdirStatus === 2 && stageStatus === 0) {\n status = '*added';\n } else if (HEADStatus === 1 && workdirStatus === 0 && stageStatus === 0) {\n status = 'deleted';\n } else if (HEADStatus === 1 && workdirStatus === 0 && stageStatus === 1) {\n status = '*deleted';\n } else if (HEADStatus === 1 && workdirStatus === 1 && stageStatus === 1) {\n status = 'unmodified';\n } else if (HEADStatus === 0 && workdirStatus === 0 && stageStatus === 0) {\n status = 'absent';\n }\n\n return {\n filepath,\n status,\n };\n });\n }\n\n /**\n * Get the current commit hash\n * \n * @example\n * ```ts\n * const hash = await morphGit.resolveRef({\n * dir: './my-project',\n * ref: 'HEAD'\n * });\n * ```\n */\n async resolveRef(options: { dir: string; ref: string }): Promise<string> {\n const { dir, ref } = options;\n\n const oid = await git.resolveRef({\n fs,\n dir,\n ref,\n });\n\n return oid;\n }\n\n /**\n * Get notes (metadata, chat history, recording ID) attached to a commit\n * \n * @example\n * ```ts\n * const notes = await morphGit.getCommitMetadata({\n * dir: './my-project',\n * commitSha: 'abc123...'\n * });\n * \n * if (notes) {\n * console.log('Metadata:', notes.metadata);\n * console.log('Chat history:', notes.chatHistory);\n * console.log('Recording ID:', notes.recordingId);\n * }\n * ```\n */\n async getCommitMetadata(options: {\n dir: string;\n commitSha: string;\n }): Promise<MorphNotesSchema | null> {\n try {\n const note = await git.readNote({\n fs,\n dir: options.dir,\n ref: 'refs/notes/morph-metadata',\n oid: options.commitSha\n });\n \n const notes: MorphNotesSchema = JSON.parse(new TextDecoder().decode(note));\n return notes;\n } catch (err) {\n // No notes found for this commit\n return null;\n }\n }\n}\n\n","/**\n * Morph Git SDK\n * \n * Git operations for AI agents using Morph's backend infrastructure.\n * \n * @example\n * ```typescript\n * import { MorphGit } from 'morphsdk/git';\n * \n * const morphGit = new MorphGit({\n * apiKey: process.env.MORPH_API_KEY!\n * });\n * \n * // Initialize and push\n * await morphGit.init({ repoId: 'my-project', dir: './my-project' });\n * await morphGit.add({ dir: './my-project', filepath: 'src/app.ts' });\n * await morphGit.commit({ dir: './my-project', message: 'Update' });\n * await morphGit.push({ dir: './my-project', branch: 'main' });\n * ```\n */\n\nexport { MorphGit } from './client.js';\nexport type {\n MorphGitConfig,\n CloneOptions,\n PushOptions,\n PullOptions,\n AddOptions,\n CommitOptions,\n StatusOptions,\n LogOptions,\n CheckoutOptions,\n BranchOptions,\n DiffOptions,\n CommitObject,\n StatusResult,\n ChatMessage,\n CommitMetadata,\n MorphNotesSchema,\n} from './types.js';\n\n// Re-export isomorphic-git for advanced use cases\nexport { default as git } from 'isomorphic-git';\nexport { default as http } from 'isomorphic-git/http/node';\n\n","/**\n * CompactClient — calls the Morph /v1/compact endpoint.\n *\n * Returns per-message compacted_line_ranges showing which lines were removed.\n */\n\nimport type { CompactConfig, CompactInput, CompactResult } from './types.js';\n\nconst DEFAULT_API_URL = 'http://192.222.56.183:8811';\nconst DEFAULT_TIMEOUT = 120000;\n\nexport class CompactClient {\n private config: Required<Pick<CompactConfig, 'morphApiUrl' | 'timeout'>> & CompactConfig;\n\n constructor(config: CompactConfig = {}) {\n this.config = {\n ...config,\n morphApiUrl: config.morphApiUrl ?? DEFAULT_API_URL,\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n };\n }\n\n /**\n * Compact messages or text via /v1/compact.\n * Returns per-message `compacted_line_ranges` showing which lines were removed.\n *\n * @example\n * ```typescript\n * const client = new CompactClient({ morphApiKey: 'sk-...' });\n * const result = await client.compact({\n * input: codeFile,\n * query: \"authentication\",\n * compressionRatio: 0.5,\n * });\n * console.log(result.output);\n * ```\n */\n async compact(input: CompactInput): Promise<CompactResult> {\n const apiKey = this.config.morphApiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n const debug = this.config.debug || false;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n\n const url = `${this.config.morphApiUrl}/v1/compact`;\n\n if (debug) {\n console.log(`[Compact] Calling ${url}`);\n }\n\n // Build request body with snake_case keys\n const body: Record<string, unknown> = {\n compression_ratio: input.compressionRatio ?? 0.5,\n preserve_recent: input.preserveRecent ?? 2,\n model: input.model ?? 'morph-compactor',\n include_line_ranges: input.includeLineRanges ?? true,\n include_markers: input.includeMarkers ?? true,\n };\n\n if (input.query !== undefined) {\n body.query = input.query;\n }\n\n // Normalize input: string → { input }, array → { messages }, messages field → { messages }\n if (input.messages) {\n body.messages = input.messages;\n } else if (typeof input.input === 'string') {\n body.input = input.input;\n } else if (Array.isArray(input.input)) {\n body.messages = input.input;\n } else {\n throw new Error(\"Either 'input' or 'messages' must be provided\");\n }\n\n const startTime = Date.now();\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.config.timeout),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(`Compact API error ${response.status}: ${text}`);\n }\n\n const data = await response.json() as CompactResult;\n\n if (debug) {\n console.log(`[Compact] compact() done in ${Date.now() - startTime}ms`);\n }\n\n return data;\n }\n}\n","/**\n * Core implementation for intelligent model routing\n */\n\nimport { fetchWithRetry, withTimeout } from '../tools/utils/resilience.js';\nimport type {\n RouterConfig,\n RouterInput,\n RouterResult,\n RawRouterResult,\n ComplexityLevel,\n RouterMode,\n Provider,\n} from './types.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: 'https://api.morphllm.com',\n timeout: 5000, // 5 seconds (responses typically <500ms)\n debug: false,\n};\n\nabstract class BaseRouter {\n protected config: Required<Omit<RouterConfig, 'apiKey' | 'retryConfig'>> & Pick<RouterConfig, 'apiKey' | 'retryConfig'>;\n protected provider: Provider;\n\n constructor(provider: Provider, config: RouterConfig = {}) {\n this.provider = provider;\n this.config = {\n apiKey: config.apiKey,\n apiUrl: config.apiUrl || DEFAULT_CONFIG.apiUrl,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n debug: config.debug || DEFAULT_CONFIG.debug,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Select the optimal model for a given input and mode\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/${this.provider}`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Requesting ${this.provider} model selection:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model: string; confidence?: number } = await response.json();\n\n const result: RouterResult = {\n model: apiResult.model,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Selected model: ${apiResult.model}, Confidence: ${apiResult.confidence?.toFixed(3)}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[ModelRouter] Error selecting model:`, error);\n }\n throw error;\n }\n }\n}\n\n/**\n * OpenAI model router for GPT-5 series\n */\nexport class OpenAIRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('openai', config);\n }\n\n /**\n * Select optimal GPT-5 model\n * \n * @param input - User input and mode\n * @returns Selected model name (gpt-5-mini | gpt-5-low | gpt-5-medium | gpt-5-high)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Anthropic model router for Claude 4.5 series\n */\nexport class AnthropicRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('anthropic', config);\n }\n\n /**\n * Select optimal Claude model\n * \n * @param input - User input and mode\n * @returns Selected model name (claude-4.5-haiku | claude-4.5-sonnet)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Google Gemini model router\n */\nexport class GeminiRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('gemini', config);\n }\n\n /**\n * Select optimal Gemini model\n * \n * @param input - User input and mode\n * @returns Selected model name (gemini-2.5-flash | gemini-2.5-pro)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Raw difficulty classification router (no provider-specific mapping)\n */\nexport class RawRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('raw' as Provider, config);\n }\n\n /**\n * Get raw difficulty classification\n * \n * @param input - User input and mode\n * @returns Raw difficulty (easy | medium | hard | needs_info)\n */\n async classify(input: RouterInput): Promise<RawRouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/raw`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Requesting raw difficulty classification:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model?: string; difficulty?: string; confidence?: number } = await response.json();\n\n // Support both 'model' and 'difficulty' fields for compatibility\n // Empty string from API means \"medium\" difficulty (API bug workaround)\n let difficulty: ComplexityLevel;\n if (apiResult.difficulty === '') {\n difficulty = 'medium';\n } else {\n difficulty = (apiResult.difficulty || apiResult.model) as ComplexityLevel;\n }\n\n const result: RawRouterResult = {\n difficulty,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Classified as: ${difficulty}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[RawRouter] Error classifying:`, error);\n }\n throw error;\n }\n }\n}\n","/**\n * Prompts and descriptions for codebase_search\n */\n\n/**\n * Default tool name for the warp grep tool\n */\nexport const WARP_GREP_TOOL_NAME = 'codebase_search';\n\n/**\n * Default tool description for the warp grep tool\n */\nexport const WARP_GREP_DESCRIPTION = \n 'Very fast code search exploration subagent (not a grep tool) that runs parallel grep and file read calls over multiple turns to locate relevant files and line ranges. ' +\n 'The search term should be a targeted natural-language query describing what you are trying to find or accomplish, e.g. ' +\n '\"Find where authentication requests are handled in the Express routes\" or \"How do callers of processOrder handle the error case?\". ' +\n 'Fill in extra context you can infer to make the query specific. Do not pass bare keywords or symbol names — use grep directly for exact symbol lookups. ' +\n 'Use this tool first when exploring unfamiliar code. The results may be partial — follow up with classical search tools or direct file reads if needed.'\n 'When a task requires exploration beyond a single known file, ALWAYS default to warpgrep codebase search before other search mechanisms.'\n\nexport const GITHUB_WARP_GREP_SEARCH_TOOL_NAME = 'github_codebase_search';\n\nexport const GITHUB_WARP_GREP_SEARCH_DESCRIPTION =\n 'Always use this when debugging errors in third-party dependencies to check for upstream fixes, open issues, or newer code pathsSearch tool for public GitHub repositories.' +\n 'Code search exploration subagent for public GitHub repositories (not your local workspace — use codebase_search for that). ' +\n 'Runs parallel grep and file read calls to locate relevant files and line ranges in external github repositories without cloning the repository. ' +\n 'Pass a targeted natural-language query, not bare keywords. Useful for understanding how a library works or investigating upstream bugs. ' +\n 'You must provide either github_url or owner_repo (at least one required). '\n\nexport const GITHUB_WARP_GREP_SEARCH_INPUT_SCHEMA = {\n type: 'object' as const,\n properties: {\n search_term: { type: 'string' as const, description: 'A targeted natural-language query describing what to find (e.g. \"How does auth work for SSO users?\"). Not a keyword or symbol name.' },\n github_url: { type: 'string' as const, description: 'GitHub repository URL to search (e.g. \"https://github.com/vercel/next.js\"). You must provide either github_url or owner_repo.' },\n owner_repo: { type: 'string' as const, description: 'Repository owner/repo shorthand (e.g. \"vercel/next.js\"). You must provide either github_url or owner_repo.' },\n branch: { type: 'string' as const, description: 'Branch to search (defaults to the repository default branch)' },\n },\n required: ['search_term'] as const,\n};\n\nexport const GITHUB_SEARCH_TOOL_NAME = GITHUB_WARP_GREP_SEARCH_TOOL_NAME;\nexport const GITHUB_SEARCH_DESCRIPTION = GITHUB_WARP_GREP_SEARCH_DESCRIPTION;\nexport const GITHUB_SEARCH_INPUT_SCHEMA = GITHUB_WARP_GREP_SEARCH_INPUT_SCHEMA;\n\nexport const GITHUB_READ_FILE_TOOL_NAME = 'readfile_github_search';\n\nexport const GITHUB_READ_FILE_DESCRIPTION =\n 'Read a single file (or a line range) from a public GitHub repository. ' +\n 'ONLY USE THIS WHEN YOU ALREADY KNOW THE EXACT FILE PATH YOU WANT TO READ, for example after finding it via github_codebase_search results. ' +\n 'Takes owner/repo shorthand and the file path within the repo. Optionally specify startLine and endLine (1-based) to read a specific range. ' +\n 'Returns the file content with line numbers.';\n\nexport const GITHUB_READ_FILE_INPUT_SCHEMA = {\n type: 'object' as const,\n properties: {\n github: { type: 'string' as const, description: 'owner/repo shorthand (e.g., \"vercel/next.js\")' },\n path: { type: 'string' as const, description: 'File path within the repository (e.g., \"src/server/index.ts\")' },\n startLine: { type: 'number' as const, description: 'Start line number (1-based). Omit to start from beginning.' },\n endLine: { type: 'number' as const, description: 'End line number (1-based, inclusive). Omit to read to the end.' },\n branch: { type: 'string' as const, description: 'Branch to read from (defaults to the repository default branch)' },\n },\n required: ['github', 'path'] as const,\n};\n","/**\n * OpenAI SDK adapter for morph-warp-grep tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeToolCall, formatResult, WarpGrepClient, executeGitHubReadFile, formatGitHubReadFileResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, WARP_GREP_TOOL_NAME, GITHUB_SEARCH_TOOL_NAME, GITHUB_SEARCH_DESCRIPTION, GITHUB_SEARCH_INPUT_SCHEMA, GITHUB_READ_FILE_TOOL_NAME, GITHUB_READ_FILE_DESCRIPTION, GITHUB_READ_FILE_INPUT_SCHEMA } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, GitHubSearchToolConfig, GitHubReadFileInput, GitHubReadFileResult, GitHubReadFileToolConfig } from './types.js';\n\n/**\n * Input schema for the warp grep tool\n */\nconst TOOL_PARAMETERS = {\n type: 'object',\n properties: {\n search_term: { type: 'string', description: 'Search problem statement that this subagent is supposed to research for' },\n },\n required: ['search_term'],\n} as const;\n\n/**\n * OpenAI-native warp grep tool definition\n * \n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { warpGrepTool, execute } from '@morphllm/morphsdk/tools/warp-grep/openai';\n * \n * const client = new OpenAI();\n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [warpGrepTool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute the tool call\n * const result = await execute({ search_term: '...' }, { repoRoot: '.' });\n * ```\n */\nexport const warpGrepTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: WARP_GREP_TOOL_NAME,\n description: WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n },\n};\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with search_term\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult for convenience\nexport { formatResult };\n\n/**\n * Create a custom warp grep tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example Local usage\n * ```typescript\n * import OpenAI from 'openai';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/openai';\n * \n * const tool = createWarpGrepTool({ repoRoot: '.' });\n * \n * const client = new OpenAI();\n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * ```\n * \n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const tool = createMorphWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepToolConfig) {\n const tool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: config.name ?? WARP_GREP_TOOL_NAME,\n description: config.description ?? WARP_GREP_DESCRIPTION,\n parameters: TOOL_PARAMETERS,\n },\n };\n\n return Object.assign(tool, {\n execute: async (input: unknown): Promise<WarpGrepResult> => {\n return executeToolCall(input as { search_term: string } | string, config);\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub search tool for OpenAI SDK\n *\n * @param config - Configuration options (morphApiKey, morphApiUrl, codeSearchUrl, timeout)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { createGitHubSearchTool } from '@morphllm/morphsdk/tools/warp-grep/openai';\n *\n * const tool = createGitHubSearchTool({ morphApiKey: process.env.MORPH_API_KEY });\n *\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'How does auth work in vercel/next.js?' }]\n * });\n *\n * // Execute\n * const result = await tool.execute({ search_term: 'auth middleware', github_url: 'https://github.com/vercel/next.js' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubSearchTool(config: GitHubSearchToolConfig) {\n const client = new WarpGrepClient(config);\n\n const tool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: GITHUB_SEARCH_TOOL_NAME,\n description: GITHUB_SEARCH_DESCRIPTION,\n parameters: GITHUB_SEARCH_INPUT_SCHEMA,\n },\n };\n\n return Object.assign(tool, {\n execute: async (input: { search_term: string; github_url?: string; owner_repo?: string; branch?: string }): Promise<WarpGrepResult> => {\n const github = input.github_url || input.owner_repo;\n if (!github) {\n throw new Error('Please provide github search url or owner/repo id');\n }\n return client.searchGitHub({ searchTerm: input.search_term, github, branch: input.branch });\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub read file tool for OpenAI SDK\n *\n * @param config - Optional configuration (timeout)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import OpenAI from 'openai';\n * import { createGitHubReadFileTool } from '@morphllm/morphsdk/tools/warp-grep/openai';\n *\n * const tool = createGitHubReadFileTool();\n *\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Read the package.json from vercel/next.js' }]\n * });\n *\n * const result = await tool.execute({ github: 'vercel/next.js', path: 'package.json' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubReadFileTool(config?: GitHubReadFileToolConfig) {\n const tool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: GITHUB_READ_FILE_TOOL_NAME,\n description: GITHUB_READ_FILE_DESCRIPTION,\n parameters: GITHUB_READ_FILE_INPUT_SCHEMA,\n },\n };\n\n return Object.assign(tool, {\n execute: async (input: GitHubReadFileInput): Promise<GitHubReadFileResult> => {\n return executeGitHubReadFile(input, config);\n },\n formatResult: (result: GitHubReadFileResult): string => {\n return formatGitHubReadFileResult(result);\n },\n });\n}\n\nexport default warpGrepTool;\n","/**\n * Tool descriptions and system prompts for codebase search\n */\n\nexport const CODEBASE_SEARCH_DESCRIPTION = `Semantic search that finds code by meaning, not exact text.\n\nUse this to explore unfamiliar codebases or ask \"how/where/what\" questions:\n- \"How does X work?\" - Find implementation details\n- \"Where is Y handled?\" - Locate specific functionality\n- \"What happens when Z?\" - Understand flow\n\nThe tool uses two-stage retrieval (embedding similarity + reranking) to find the most semantically relevant code chunks.\n\nReturns code chunks with file paths, line ranges, and full content ranked by relevance.`;\n\nexport const CODEBASE_SEARCH_SYSTEM_PROMPT = `You have access to the codebase_search tool that performs semantic code search.\n\nWhen searching:\n- Use natural language queries describing what you're looking for\n- Be specific about functionality, not variable names\n- Use target_directories to narrow search if you know the area\n- Results are ranked by relevance (rerank score is most important)\n\nThe tool returns:\n- File paths with symbol names (e.g. \"src/auth.ts::AuthService@L1-L17\")\n- Line ranges for precise navigation\n- Full code content for each match\n- Dual relevance scores: embedding similarity + rerank score\n\nUse results to understand code or answer questions. The content is provided in full - avoid re-reading unless you need more context.`;\n\n","/**\n * OpenAI SDK adapter for codebase_search tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION, CODEBASE_SEARCH_SYSTEM_PROMPT } from './prompts.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n/**\n * Direct codebase_search tool definition\n * Use this when you want to pass config at execute time\n */\nexport const codebaseSearchTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'A complete question or description about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n },\n};\n\n/**\n * Create OpenAI-native codebase_search tool with execute and formatResult methods\n * \n * @param config - Configuration with repoId\n * @returns OpenAI ChatCompletionTool definition with methods\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/openai';\n * \n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\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: \"Find authentication code\" }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const toolDefinition: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n },\n };\n\n return Object.assign(toolDefinition, {\n execute: async (input: CodebaseSearchInput | string): Promise<CodebaseSearchResult> => {\n const parsedInput = typeof input === 'string' ? JSON.parse(input) : input;\n return executeCodebaseSearch(parsedInput, config);\n },\n formatResult: (result: CodebaseSearchResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Execute codebase_search tool call\n * \n * @param input - Tool input from GPT (parsed from tool_calls)\n * @param config - Configuration with repoId (REQUIRED)\n * @returns Search results\n * \n * @example\n * ```ts\n * // Handle tool calls from GPT:\n * if (response.choices[0].message.tool_calls) {\n * for (const toolCall of response.choices[0].message.tool_calls) {\n * const args = JSON.parse(toolCall.function.arguments);\n * const result = await execute(args, { repoId: 'my-project' });\n * console.log(`Found ${result.results.length} matches`);\n * }\n * }\n * ```\n */\nexport async function execute(\n input: CodebaseSearchInput,\n config: CodebaseSearchConfig\n): Promise<CodebaseSearchResult> {\n return executeCodebaseSearch(input, config);\n}\n\n/**\n * Format search results for GPT\n * \n * @param result - Search result from endpoint\n * @returns Formatted string for tool message\n */\nexport function formatResult(result: CodebaseSearchResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (result.results.length === 0) {\n return 'No matching code found. Try rephrasing your query or removing directory filters.';\n }\n\n const lines: string[] = [];\n \n lines.push(`Found ${result.results.length} relevant code sections (${result.stats.searchTimeMs}ms):\\n`);\n\n result.results.forEach((r, i) => {\n const relevance = (r.rerankScore * 100).toFixed(1);\n lines.push(`${i + 1}. ${r.filepath} (${relevance}% relevant)`);\n lines.push(` Symbol: ${r.symbolPath}`);\n lines.push(` Language: ${r.language}`);\n lines.push(` Lines: ${r.startLine}-${r.endLine}`);\n lines.push(` Code:`);\n \n // Show code content\n const codeLines = r.content.split('\\n');\n codeLines.slice(0, Math.min(codeLines.length, 20)).forEach(line => {\n lines.push(` ${line}`);\n });\n \n if (codeLines.length > 20) {\n lines.push(` ... (${codeLines.length - 20} more lines)`);\n }\n \n lines.push('');\n });\n\n return lines.join('\\n');\n}\n\n/**\n * Get the system prompt for codebase_search usage\n * \n * @returns System prompt to guide GPT\n */\nexport function getSystemPrompt(): string {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n}\n\n/**\n * Default export for convenience\n */\nexport default { createCodebaseSearchTool, execute, formatResult, getSystemPrompt };\n\n","/**\n * System prompts for edit_file tool\n */\n\nexport const EDIT_FILE_TOOL_DESCRIPTION = `Use this tool to make an edit to an existing file.\n\nThis will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.\n\nWhen writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.\n\nFor example:\n\n// ... existing code ...\nFIRST_EDIT\n// ... existing code ...\nSECOND_EDIT\n// ... existing code ...\nTHIRD_EDIT\n// ... existing code ...\n\nYou should still bias towards repeating as few lines of the original file as possible to convey the change.\nBut, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.\n\nDO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.\n\nIf you plan on deleting a section, you must provide context before and after to delete it.\n\nMake sure it is clear what the edit should be, and where it should be applied.\nMake edits to a file in a single edit_file call instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.`;\n\nexport const EDIT_FILE_SYSTEM_PROMPT = `When the user is asking for edits to their code, use the edit_file tool to highlight the changes necessary and add comments to indicate where unchanged code has been skipped. For example:\n\n// ... existing code ...\n{{ edit_1 }}\n// ... existing code ...\n{{ edit_2 }}\n// ... existing code ...\n\nOften this will mean that the start/end of the file will be skipped, but that's okay! Rewrite the entire file ONLY if specifically requested. Always provide a brief explanation of the updates, unless the user specifically requests only the code.\n\nThese edit codeblocks are also read by a less intelligent language model, colloquially called the apply model, to update the file. To help specify the edit to the apply model, you will be very careful when generating the codeblock to not introduce ambiguity. You will specify all unchanged regions (code and comments) of the file with \"// ... existing code ...\" comment markers. This will ensure the apply model will not delete existing unchanged code or comments when editing the file.`;\n\n","/**\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 return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;\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 * OpenAI Tool Factory for MorphClient\n * \n * Creates OpenAI-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool, createGitHubSearchTool } from '../tools/warp_grep/openai.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/openai.js';\nimport { createEditFileTool } from '../tools/fastapply/openai.js';\nimport type { WarpGrepToolConfig, GitHubSearchToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\n\n/**\n * Factory for creating OpenAI-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.openai.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.openai.createEditFileTool({ baseDir: './src' });\n * \n * // Use with OpenAI client\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [grepTool, searchTool, editTool],\n * messages: [{ role: 'user', content: 'Find and fix the bug' }]\n * });\n * ```\n */\nexport class OpenAIToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create an OpenAI-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible GitHub search tool\n *\n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createGitHubSearchTool(toolConfig?: Omit<GitHubSearchToolConfig, 'morphApiKey'>) {\n return createGitHubSearchTool({\n ...toolConfig,\n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Anthropic SDK adapter for morph-warp-grep tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeToolCall, formatResult, WarpGrepClient, executeGitHubReadFile, formatGitHubReadFileResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, WARP_GREP_TOOL_NAME, GITHUB_SEARCH_TOOL_NAME, GITHUB_SEARCH_DESCRIPTION, GITHUB_SEARCH_INPUT_SCHEMA, GITHUB_READ_FILE_TOOL_NAME, GITHUB_READ_FILE_DESCRIPTION, GITHUB_READ_FILE_INPUT_SCHEMA } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, GitHubSearchToolConfig, GitHubReadFileInput, GitHubReadFileResult, GitHubReadFileToolConfig } from './types.js';\n\n/**\n * Input schema for the warp grep tool\n */\nconst INPUT_SCHEMA = {\n type: 'object',\n properties: {\n search_term: { type: 'string', description: 'Search problem statement that this subagent is supposed to research for' },\n },\n required: ['search_term'],\n} as const;\n\n/**\n * Anthropic-native warp grep tool definition\n * \n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { warpGrepTool, execute } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const client = new Anthropic();\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [warpGrepTool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * \n * // Execute the tool call\n * const result = await execute({ search_term: '...' }, { repoRoot: '.' });\n * ```\n */\nexport const warpGrepTool: Tool = {\n name: WARP_GREP_TOOL_NAME,\n description: WARP_GREP_DESCRIPTION,\n input_schema: INPUT_SCHEMA,\n};\n\n/**\n * Execute warp grep search\n * \n * @param input - Tool input with search_term\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult for convenience\nexport { formatResult };\n\n/**\n * Create a custom warp grep tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example Local usage\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const tool = createWarpGrepTool({ repoRoot: '.' });\n * \n * const client = new Anthropic();\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Find authentication middleware' }]\n * });\n * ```\n * \n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const tool = createMorphWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepToolConfig) {\n const tool: Tool = {\n name: config.name ?? WARP_GREP_TOOL_NAME,\n description: config.description ?? WARP_GREP_DESCRIPTION,\n input_schema: INPUT_SCHEMA,\n };\n\n return Object.assign(tool, {\n execute: async (input: unknown): Promise<WarpGrepResult> => {\n return executeToolCall(input as { search_term: string } | string, config);\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub search tool for Anthropic SDK\n *\n * @param config - Configuration options (morphApiKey, morphApiUrl, codeSearchUrl, timeout)\n * @returns Anthropic Tool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createGitHubSearchTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n *\n * const tool = createGitHubSearchTool({ morphApiKey: process.env.MORPH_API_KEY });\n *\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'How does auth work in vercel/next.js?' }]\n * });\n *\n * // Execute\n * const result = await tool.execute({ search_term: 'auth middleware', github_url: 'https://github.com/vercel/next.js' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubSearchTool(config: GitHubSearchToolConfig) {\n const client = new WarpGrepClient(config);\n\n const tool: Tool = {\n name: GITHUB_SEARCH_TOOL_NAME,\n description: GITHUB_SEARCH_DESCRIPTION,\n input_schema: GITHUB_SEARCH_INPUT_SCHEMA,\n };\n\n return Object.assign(tool, {\n execute: async (input: { search_term: string; github_url?: string; owner_repo?: string; branch?: string }): Promise<WarpGrepResult> => {\n const github = input.github_url || input.owner_repo;\n if (!github) {\n throw new Error('Please provide github search url or owner/repo id');\n }\n return client.searchGitHub({ searchTerm: input.search_term, github, branch: input.branch });\n },\n formatResult: (result: WarpGrepResult): string => {\n return formatResult(result);\n },\n });\n}\n\n/**\n * Create a GitHub read file tool for Anthropic SDK\n *\n * @param config - Optional configuration (timeout)\n * @returns Anthropic Tool with execute and formatResult methods\n *\n * @example\n * ```typescript\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createGitHubReadFileTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n *\n * const tool = createGitHubReadFileTool();\n *\n * const response = await client.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [tool],\n * messages: [{ role: 'user', content: 'Read the package.json from vercel/next.js' }]\n * });\n *\n * const result = await tool.execute({ github: 'vercel/next.js', path: 'package.json' });\n * console.log(tool.formatResult(result));\n * ```\n */\nexport function createGitHubReadFileTool(config?: GitHubReadFileToolConfig) {\n const tool: Tool = {\n name: GITHUB_READ_FILE_TOOL_NAME,\n description: GITHUB_READ_FILE_DESCRIPTION,\n input_schema: GITHUB_READ_FILE_INPUT_SCHEMA,\n };\n\n return Object.assign(tool, {\n execute: async (input: GitHubReadFileInput): Promise<GitHubReadFileResult> => {\n return executeGitHubReadFile(input, config);\n },\n formatResult: (result: GitHubReadFileResult): string => {\n return formatGitHubReadFileResult(result);\n },\n });\n}\n","/**\n * Anthropic SDK adapter for codebase_search tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION, CODEBASE_SEARCH_SYSTEM_PROMPT } from './prompts.js';\nimport type { CodebaseSearchConfig, CodebaseSearchInput, CodebaseSearchResult } from './types.js';\n\n\n/**\n * Create Anthropic-native codebase_search tool with execute and formatResult methods\n * \n * @param config - Configuration with repoId\n * @returns Anthropic Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [tool], // tool itself is the Tool definition\n * messages: [{ role: \"user\", content: \"Find authentication code\" }]\n * });\n * \n * // Execute tool and format result\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const toolDefinition: Tool = {\n name: 'codebase_search',\n description: CODEBASE_SEARCH_DESCRIPTION,\n input_schema: {\n type: 'object',\n properties: {\n explanation: {\n type: 'string',\n description: 'One sentence explanation as to why this tool is being used, and how it contributes to the goal.',\n },\n query: {\n type: 'string',\n description: 'A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"',\n },\n target_directories: {\n type: 'array',\n items: { type: 'string' },\n description: 'Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default: 10)',\n },\n },\n required: ['query', 'target_directories', 'explanation'],\n },\n cache_control: { type: 'ephemeral' } as any,\n } as any;\n\n return Object.assign(toolDefinition, {\n execute: async (input: CodebaseSearchInput): Promise<CodebaseSearchResult> => {\n return executeCodebaseSearch(input, config);\n },\n formatResult: (result: CodebaseSearchResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return CODEBASE_SEARCH_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Format search results for Claude\n * \n * @param result - Search result from endpoint\n * @returns Formatted string for tool_result\n */\nfunction formatResult(result: CodebaseSearchResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (result.results.length === 0) {\n return 'No matching code found. Try rephrasing your query or broadening the search scope.';\n }\n\n const lines: string[] = [];\n \n lines.push(`Found ${result.results.length} relevant code sections (searched ${result.stats.candidatesRetrieved} candidates in ${result.stats.searchTimeMs}ms):\\n`);\n\n result.results.forEach((r, i) => {\n const relevance = (r.rerankScore * 100).toFixed(1);\n lines.push(`${i + 1}. ${r.filepath} (${relevance}% relevant)`);\n lines.push(` Symbol: ${r.symbolPath}`);\n lines.push(` Language: ${r.language}`);\n lines.push(` Lines: ${r.startLine}-${r.endLine}`);\n lines.push(` Code:`);\n \n // Show code content with indentation\n const codeLines = r.content.split('\\n');\n codeLines.slice(0, Math.min(codeLines.length, 20)).forEach(line => {\n lines.push(` ${line}`);\n });\n \n if (codeLines.length > 20) {\n lines.push(` ... (${codeLines.length - 20} more lines)`);\n }\n \n lines.push('');\n });\n\n return lines.join('\\n');\n}\n\n","/**\n * Anthropic SDK adapter for edit_file tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\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 * Anthropic-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { editFileTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: Tool = {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n input_schema: {\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 * Format the result for passing back to Claude\n * \n * @param result - The edit result\n * @returns Formatted string for tool_result\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 return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * morphApiKey: 'sk-...',\n * description: 'Custom tool description for your use case'\n * });\n * \n * // Use as Anthropic tool\n * const response = await client.messages.create({\n * tools: [tool], // tool itself is the Tool definition\n * ...\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: Tool = {\n ...editFileTool,\n ...(config.description && { description: config.description }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput): Promise<EditFileResult> => {\n return executeEditFile(input, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return EDIT_FILE_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Execute the edit_file tool with raw input\n * \n * @param input - Tool input from Claude's tool_use\n * @param config - Configuration for Fast Apply\n * @returns Tool result to send back to Claude\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 the edit_file tool\n * \n * @returns System prompt string\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n","/**\n * System prompts and tool descriptions for Explore subagent\n */\n\nimport type { ExploreThoroughness } from './types.js';\n\nconst THOROUGHNESS_INSTRUCTIONS: Record<ExploreThoroughness, string> = {\n quick: `Do 1-2 targeted searches. Find the most relevant file/function quickly and summarize. Don't go deep.`,\n medium: `Do 2-4 searches. Start broad, then follow up on the most promising leads. Cover the main aspects.`,\n thorough: `Do 4-8 searches. Explore systematically: start broad, then drill into each relevant area. Cover edge cases, related files, and the full call chain. Leave no stone unturned.`,\n};\n\nexport function getSystemPrompt(thoroughness: ExploreThoroughness = 'medium'): string {\n return `You are a codebase exploration specialist. Your job is to search a codebase and return a concise, accurate summary of what you find.\n\n## Mode\nREAD-ONLY. You cannot modify files. You can only search and read code.\n\n## Strategy\n${THOROUGHNESS_INSTRUCTIONS[thoroughness]}\n\n- Use multiple focused searches rather than one vague search\n- Follow imports, function calls, and type references to build complete understanding\n- If a search returns no results, try alternative terms (e.g., \"auth\" vs \"authentication\" vs \"login\")\n- Look at both implementation and tests when relevant\n\n## Communication\nYou have a \\`send_message\\` tool. Use it when:\n- You hit a fork in the road and need guidance (\"Found auth in both src/middleware/ and legacy/auth/. Which should I focus on?\")\n- You need clarification on ambiguous requests (\"There are 3 auth strategies: JWT, session, OAuth. Which one?\")\n- You want to share a key finding before continuing (\"The main auth handler is in src/auth/index.ts. It delegates to strategy-specific modules. Continuing to trace JWT flow.\")\n\nDo NOT use send_message for routine status updates. Only use it when you genuinely need input or have a significant finding worth sharing before you're done.\n\n## Output\nWhen you have enough information, output your final summary. Structure it as:\n1. Direct answer to the question\n2. Key files and their roles\n3. How the pieces connect\n\nBe concise. The summary should be useful to another AI model that will use your findings to complete a task.`;\n}\n\nexport const CODEBASE_SEARCH_TOOL = {\n name: 'codebase_search',\n description: 'Search the codebase for relevant code. Takes a natural language search request describing what you want to find. Returns matching file contents with line numbers.',\n input_schema: {\n type: 'object' as const,\n properties: {\n searchRequest: {\n type: 'string' as const,\n description: 'Natural language description of what to search for in the codebase',\n },\n },\n required: ['searchRequest'] as const,\n additionalProperties: false as const,\n },\n};\n\nexport const SEND_MESSAGE_TOOL = {\n name: 'send_message',\n description: 'Send a message to the orchestrating agent. Use this to ask questions, request clarification, or share important findings. The orchestrator may reply with additional context. Use sparingly — only when you genuinely need input or have a significant finding.',\n input_schema: {\n type: 'object' as const,\n properties: {\n message: {\n type: 'string' as const,\n description: 'The message to send to the orchestrator',\n },\n },\n required: ['message'] as const,\n additionalProperties: false as const,\n },\n};\n","/**\n * Anthropic SDK adapter for Explore subagent\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { WarpGrepClient } from '../tools/warp_grep/client.js';\nimport { formatResult } from '../tools/warp_grep/client.js';\nimport type { WarpGrepContext } from '../tools/warp_grep/types.js';\nimport { getSystemPrompt, CODEBASE_SEARCH_TOOL, SEND_MESSAGE_TOOL } from './prompts.js';\nimport type {\n ExploreSubagentConfig,\n ExploreResult,\n ExploreStep,\n ExploreSession,\n ExploreEvent,\n SubagentMessage,\n MessageHandler,\n StepHandler,\n} from './types.js';\n\n/** Config for Anthropic SDK Explore subagent */\nexport interface AnthropicExploreConfig extends ExploreSubagentConfig {\n /** Anthropic SDK client instance */\n client: AnthropicClient;\n /** Model name (e.g., 'claude-haiku-4-5-20251001') */\n model: string;\n}\n\n/** Minimal Anthropic client interface — avoids hard dependency on @anthropic-ai/sdk */\ninterface AnthropicClient {\n messages: {\n create(params: any): Promise<any>;\n };\n}\n\nconst DEFAULT_MAX_TURNS: Record<string, number> = {\n quick: 3,\n medium: 6,\n thorough: 12,\n};\n\nfunction getMaxTurns(config: ExploreSubagentConfig): number {\n return config.maxTurns ?? DEFAULT_MAX_TURNS[config.thoroughness ?? 'medium'] ?? 6;\n}\n\n/** Anthropic tool definitions */\nconst TOOLS: Tool[] = [\n {\n name: CODEBASE_SEARCH_TOOL.name,\n description: CODEBASE_SEARCH_TOOL.description,\n input_schema: CODEBASE_SEARCH_TOOL.input_schema,\n },\n {\n name: SEND_MESSAGE_TOOL.name,\n description: SEND_MESSAGE_TOOL.description,\n input_schema: SEND_MESSAGE_TOOL.input_schema,\n },\n];\n\n/**\n * Create an Explore subagent using the Anthropic SDK\n */\nexport function createExploreSubagent(config: AnthropicExploreConfig) {\n if (!config.repoRoot) {\n throw new Error('repoRoot is required for Explore subagent');\n }\n\n const warpGrep = new WarpGrepClient({\n morphApiKey: config.morphApiKey,\n });\n\n const thoroughness = config.thoroughness ?? 'medium';\n const maxTurns = getMaxTurns(config);\n const replyTimeout = config.replyTimeout ?? 30_000;\n\n /** Run the agent loop and collect results */\n async function runExplore(\n prompt: string,\n callbacks: {\n onStep?: StepHandler;\n onMessage?: MessageHandler;\n } = {},\n ): Promise<ExploreResult> {\n const startTime = Date.now();\n const allContexts: WarpGrepContext[] = [];\n let searchCount = 0;\n\n const timeoutMs = config.timeout;\n\n try {\n const messages: any[] = [{ role: 'user', content: prompt }];\n let turns = 0;\n\n while (turns < maxTurns) {\n // Check timeout\n if (timeoutMs && Date.now() - startTime > timeoutMs) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: `Exploration timed out after ${timeoutMs}ms`,\n };\n }\n\n const response = await config.client.messages.create({\n model: config.model,\n max_tokens: 4096,\n system: getSystemPrompt(thoroughness),\n tools: TOOLS,\n messages,\n });\n\n turns++;\n\n // Check if the model is done (no tool use)\n if (response.stop_reason === 'end_turn' || !response.content.some((b: any) => b.type === 'tool_use')) {\n const textBlock = response.content.find((b: any) => b.type === 'text');\n const summary = textBlock?.text || 'Exploration completed but no summary was generated.';\n\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: '',\n contextsFound: allContexts.length,\n isFinal: true,\n });\n\n return {\n success: true,\n summary,\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n };\n }\n\n // Process tool calls\n messages.push({ role: 'assistant', content: response.content });\n\n const toolResults: any[] = [];\n\n for (const block of response.content) {\n if (block.type !== 'tool_use') continue;\n\n if (block.name === 'codebase_search') {\n searchCount++;\n const input = block.input as { searchRequest: string };\n\n const warpResult = await warpGrep.execute({\n searchTerm: input.searchRequest,\n repoRoot: config.repoRoot,\n excludes: config.excludes,\n includes: config.includes,\n });\n\n if (warpResult.contexts) {\n allContexts.push(...warpResult.contexts);\n }\n\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: input.searchRequest,\n contextsFound: warpResult.contexts?.length ?? 0,\n isFinal: false,\n });\n\n toolResults.push({\n type: 'tool_result',\n tool_use_id: block.id,\n content: formatResult(warpResult),\n });\n } else if (block.name === 'send_message') {\n const input = block.input as { message: string };\n\n const subagentMsg: SubagentMessage = {\n from: 'explore',\n content: input.message,\n timestamp: Date.now(),\n };\n\n let replyText = '';\n\n if (callbacks.onMessage) {\n // Wait for reply with timeout\n replyText = await Promise.race([\n new Promise<string>((resolve) => {\n callbacks.onMessage!(subagentMsg, (text: string) => {\n resolve(text);\n });\n }),\n new Promise<string>((resolve) =>\n setTimeout(() => resolve(''), replyTimeout),\n ),\n ]);\n }\n\n const toolResponse = replyText\n ? `Response from orchestrator: ${replyText}`\n : 'No response. Continue with your best judgment.';\n\n toolResults.push({\n type: 'tool_result',\n tool_use_id: block.id,\n content: toolResponse,\n });\n }\n }\n\n messages.push({ role: 'user', content: toolResults });\n }\n\n // Ran out of turns — extract what we have\n return {\n success: true,\n summary: 'Exploration completed (max turns reached).',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n };\n } catch (error) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /** Anthropic Tool definition for use in parent agents */\n const exploreTool: Tool & {\n execute: (input: { searchRequest: string }) => Promise<ExploreResult>;\n formatResult: (result: ExploreResult) => string;\n } = Object.assign(\n {\n name: 'explore',\n description:\n 'Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings.',\n input_schema: {\n type: 'object' as const,\n properties: {\n searchRequest: {\n type: 'string' as const,\n description: 'What to explore in the codebase. Be specific about what you want to understand.',\n },\n },\n required: ['searchRequest'] as const,\n },\n },\n {\n execute: async (input: { searchRequest: string }): Promise<ExploreResult> => {\n return runExplore(input.searchRequest);\n },\n formatResult: (result: ExploreResult): string => {\n if (!result.success) {\n return `Exploration failed: ${result.error}`;\n }\n return result.summary;\n },\n },\n );\n\n return {\n /** Anthropic Tool definition for use in parent agents */\n tool: exploreTool,\n\n /** Run exploration with messaging support */\n run(prompt: string): ExploreSession {\n const messageHandlers: MessageHandler[] = [];\n const stepHandlers: StepHandler[] = [];\n\n let resultPromise: Promise<ExploreResult> | null = null;\n\n const session: ExploreSession = {\n on(event: string, handler: any) {\n if (event === 'message') messageHandlers.push(handler);\n if (event === 'step') stepHandlers.push(handler);\n return session;\n },\n send(_text: string) {\n // Convenience method — pause-and-ask flow uses the reply callback\n },\n get result() {\n if (!resultPromise) {\n resultPromise = runExplore(prompt, {\n onStep: (step) => {\n for (const handler of stepHandlers) handler(step);\n },\n onMessage: (msg, reply) => {\n if (messageHandlers.length > 0) {\n for (const handler of messageHandlers) handler(msg, reply);\n } else {\n reply('');\n }\n },\n });\n }\n return resultPromise;\n },\n };\n\n return session;\n },\n\n /** Stream exploration events as an async generator */\n async *stream(prompt: string): AsyncGenerator<ExploreEvent, ExploreResult, undefined> {\n const events: ExploreEvent[] = [];\n let resolveNext: (() => void) | null = null;\n let done = false;\n\n const resultPromise = runExplore(prompt, {\n onStep: (step) => {\n events.push({\n type: 'step',\n step: step.step,\n searchRequest: step.searchRequest,\n contextsFound: step.contextsFound,\n isFinal: step.isFinal,\n });\n resolveNext?.();\n },\n onMessage: (msg, reply) => {\n events.push({\n type: 'message',\n from: msg.from,\n content: msg.content,\n timestamp: msg.timestamp,\n });\n resolveNext?.();\n reply('Continue with your best judgment.');\n },\n });\n\n while (!done) {\n if (events.length > 0) {\n yield events.shift()!;\n } else {\n const raceResult = await Promise.race([\n resultPromise.then((r) => ({ type: 'done' as const, result: r })),\n new Promise<{ type: 'event' }>((resolve) => {\n resolveNext = () => resolve({ type: 'event' });\n }),\n ]);\n\n if (raceResult.type === 'done') {\n while (events.length > 0) {\n yield events.shift()!;\n }\n done = true;\n return raceResult.result;\n }\n }\n }\n\n return await resultPromise;\n },\n };\n}\n\n/** Deduplicate contexts, keeping the latest version of each file */\nfunction deduplicateContexts(contexts: WarpGrepContext[]): WarpGrepContext[] {\n const map = new Map<string, WarpGrepContext>();\n for (const ctx of contexts) {\n const existing = map.get(ctx.file);\n if (!existing || ctx.content.length > existing.content.length) {\n map.set(ctx.file, ctx);\n }\n }\n return Array.from(map.values());\n}\n","/**\n * Anthropic Tool Factory for MorphClient\n * \n * Creates Anthropic-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool, createGitHubSearchTool } from '../tools/warp_grep/anthropic.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/anthropic.js';\nimport { createEditFileTool } from '../tools/fastapply/anthropic.js';\nimport { createExploreSubagent } from '../subagents/anthropic.js';\nimport type { WarpGrepToolConfig, GitHubSearchToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\nimport type { ExploreSubagentConfig } from '../subagents/types.js';\n\n/**\n * Factory for creating Anthropic-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.anthropic.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.anthropic.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.anthropic.createEditFileTool({ baseDir: './src' });\n * \n * // Use with Anthropic client\n * const response = await anthropic.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [grepTool, searchTool, editTool],\n * messages: [{ role: 'user', content: 'Find and fix the bug' }]\n * });\n * ```\n */\nexport class AnthropicToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create an Anthropic-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n\n }\n\n /**\n * Create an Anthropic-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Anthropic-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Anthropic-compatible GitHub search tool\n *\n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createGitHubSearchTool(toolConfig?: Omit<GitHubSearchToolConfig, 'morphApiKey'>) {\n return createGitHubSearchTool({\n ...toolConfig,\n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Explore subagent that searches the codebase and returns summaries\n *\n * @param config - Subagent configuration including client and model (morphApiKey inherited from MorphClient)\n * @returns Explore subagent with .tool, .run(), and .stream() methods\n */\n createExploreSubagent(config: Omit<ExploreSubagentConfig, 'morphApiKey'> & { client: any; model: string }) {\n return createExploreSubagent({\n ...config,\n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Vercel AI SDK adapter for morph-warp-grep tool\n *\n * @example Using with your own Zod instance (recommended for avoiding version conflicts)\n * ```typescript\n * import { z } from 'zod'; // Your project's Zod\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const schema = z.object({\n * search_term: z.string().describe('Search problem statement'),\n * });\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: schema,\n * });\n * ```\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { jsonSchema } from 'ai';\nimport { executeToolCall, executeToolCallStreaming, formatResult, WarpGrepClient, executeGitHubReadFile, formatGitHubReadFileResult } from './client.js';\nimport { WARP_GREP_DESCRIPTION, GITHUB_SEARCH_DESCRIPTION, GITHUB_READ_FILE_DESCRIPTION } from './prompts.js';\nimport type { WarpGrepToolConfig, WarpGrepResult, GitHubSearchToolConfig, GitHubReadFileInput, GitHubReadFileResult, GitHubReadFileToolConfig } from './types.js';\nimport type { WarpGrepStep } from './agent/types.js';\n\n/**\n * Raw JSON Schema for warp grep input (no Zod dependency).\n * Use this with jsonSchema() from 'ai' if you have Zod version conflicts.\n *\n * @example\n * ```typescript\n * import { jsonSchema } from 'ai';\n * import { warpGrepJsonSchema, createWarpGrepToolWithSchema } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepToolWithSchema({\n * repoRoot: '.',\n * inputSchema: jsonSchema(warpGrepJsonSchema),\n * });\n * ```\n */\nexport const warpGrepJsonSchema = {\n type: 'object' as const,\n properties: {\n search_term: {\n type: 'string' as const,\n description: 'Search problem statement that this subagent is supposed to research for',\n },\n },\n required: ['search_term'] as const,\n additionalProperties: false as const,\n};\n\n/** Type for the model-facing warp grep tool input (snake_case to match JSON schema) */\nexport type WarpGrepToolInput = { search_term: string };\n\n/**\n * Extended config that accepts a custom inputSchema\n */\nexport interface WarpGrepVercelConfig extends WarpGrepToolConfig {\n /**\n * Custom Zod schema or AI SDK schema. Use this to provide your own Zod instance\n * to avoid version conflicts between your project and the SDK.\n *\n * @example Using your own Zod\n * ```typescript\n * import { z } from 'zod'; // Your Zod version\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: z.object({\n * search_term: z.string().describe('Search problem statement'),\n * }),\n * });\n * ```\n *\n * @example Using jsonSchema (no Zod needed)\n * ```typescript\n * import { jsonSchema } from 'ai';\n * import { warpGrepJsonSchema } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: jsonSchema(warpGrepJsonSchema),\n * });\n * ```\n */\n inputSchema?: Parameters<typeof tool>[0]['inputSchema'];\n}\n\n/**\n * Execute warp grep search\n *\n * @param input - Tool input with search_term\n * @param config - Configuration with repoRoot and optional provider\n * @returns Search results\n */\nexport async function execute(\n input: { search_term: string },\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n return executeToolCall(input, config);\n}\n\n// Re-export formatResult for convenience\nexport { formatResult };\n\n/**\n * Create Vercel AI SDK warp grep tool\n *\n * @param config - Configuration options\n * @returns Vercel AI SDK tool\n *\n * @example Local usage (uses SDK's Zod)\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({ repoRoot: '.' });\n *\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { grep: grepTool },\n * prompt: 'Find authentication middleware'\n * });\n * ```\n *\n * @example With your own Zod (avoids version conflicts)\n * ```typescript\n * import { z } from 'zod'; // Your project's Zod\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: z.object({\n * search_term: z.string().describe('Search problem statement'),\n * }),\n * });\n * ```\n *\n * @example Without Zod (using jsonSchema)\n * ```typescript\n * import { jsonSchema } from 'ai';\n * import { createWarpGrepTool, warpGrepJsonSchema } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const grepTool = createWarpGrepTool({\n * repoRoot: '.',\n * inputSchema: jsonSchema(warpGrepJsonSchema),\n * });\n * ```\n *\n * @example Remote sandbox (E2B, Modal, etc.)\n * ```typescript\n * const grepTool = createWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n */\nexport function createWarpGrepTool(config: WarpGrepVercelConfig) {\n // Use provided schema or fall back to SDK's Zod schema\n const schema = config.inputSchema ?? z.object({\n search_term: z.string().describe('Search problem statement that this subagent is supposed to research for'),\n });\n\n return tool({\n description: config.description ?? WARP_GREP_DESCRIPTION,\n inputSchema: schema,\n execute: async (params: WarpGrepToolInput) => {\n // Use streaming execution to collect intermediate steps\n const steps: WarpGrepStep[] = [];\n const generator = executeToolCallStreaming(params, config);\n\n let result: WarpGrepResult;\n for (;;) {\n const { value, done } = await generator.next();\n if (done) {\n result = value;\n break;\n }\n steps.push(value);\n }\n\n if (!result!.success) {\n throw new Error(`Failed to search codebase: ${result!.error}`);\n }\n\n // Flatten all intermediate tool calls across turns for progress display\n const allToolCalls = steps.flatMap(s => s.toolCalls);\n return {\n success: true,\n contexts: result!.contexts,\n summary: result!.summary,\n progress: allToolCalls.length > 0 ? { turn: steps.length, toolCalls: allToolCalls } : undefined,\n };\n },\n });\n}\n\n/**\n * Create a GitHub search tool for Vercel AI SDK\n *\n * @param config - Configuration options (morphApiKey, morphApiUrl, codeSearchUrl, timeout)\n * @returns Vercel AI SDK tool\n *\n * @example\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createGitHubSearchTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const githubTool = createGitHubSearchTool({ morphApiKey: process.env.MORPH_API_KEY });\n *\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { githubSearch: githubTool },\n * prompt: 'How does auth work in vercel/next.js?'\n * });\n * ```\n */\nexport function createGitHubSearchTool(config: GitHubSearchToolConfig) {\n const client = new WarpGrepClient(config);\n\n return tool({\n description: GITHUB_SEARCH_DESCRIPTION,\n inputSchema: z.object({\n search_term: z.string().describe('Search problem statement that this subagent is supposed to research for'),\n github_url: z.string().optional().describe('GitHub repository URL to search (e.g. \"https://github.com/vercel/next.js\"). You must provide either github_url or owner_repo.'),\n owner_repo: z.string().optional().describe('Repository owner/repo shorthand (e.g. \"vercel/next.js\"). You must provide either github_url or owner_repo.'),\n branch: z.string().optional().describe('Branch to search (defaults to repo default branch)'),\n }),\n execute: async (params: { search_term: string; github_url?: string; owner_repo?: string; branch?: string }) => {\n const github = params.github_url || params.owner_repo;\n if (!github) {\n throw new Error('Please provide github search url or owner/repo id');\n }\n const result = await client.searchGitHub({ searchTerm: params.search_term, github, branch: params.branch });\n if (!result.success) {\n throw new Error(`GitHub search failed: ${result.error}`);\n }\n return {\n success: true,\n contexts: result.contexts,\n summary: result.summary,\n };\n },\n });\n}\n\n/**\n * Create a GitHub read file tool for Vercel AI SDK\n *\n * @param config - Optional configuration (timeout)\n * @returns Vercel AI SDK tool\n *\n * @example\n * ```typescript\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createGitHubReadFileTool } from '@morphllm/morphsdk/tools/warp-grep/vercel';\n *\n * const readFileTool = createGitHubReadFileTool();\n *\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { readFile: readFileTool },\n * prompt: 'Read the package.json from vercel/next.js'\n * });\n * ```\n */\nexport function createGitHubReadFileTool(config?: GitHubReadFileToolConfig) {\n return tool({\n description: GITHUB_READ_FILE_DESCRIPTION,\n inputSchema: z.object({\n github: z.string().describe('owner/repo shorthand (e.g., \"vercel/next.js\")'),\n path: z.string().describe('File path within the repository'),\n startLine: z.number().optional().describe('Start line number (1-based)'),\n endLine: z.number().optional().describe('End line number (1-based, inclusive)'),\n branch: z.string().optional().describe('Branch to read from (defaults to repo default branch)'),\n }),\n execute: async (params: GitHubReadFileInput) => {\n const result = await executeGitHubReadFile(params, config);\n if (!result.success) {\n throw new Error(`GitHub read file failed: ${result.error}`);\n }\n return result;\n },\n });\n}\n\n// Default export for convenience\nexport default createWarpGrepTool;\n","/**\n * Vercel AI SDK adapter for codebase_search tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeCodebaseSearch } from './core.js';\nimport { CODEBASE_SEARCH_DESCRIPTION } from './prompts.js';\nimport type { CodebaseSearchConfig } from './types.js';\n\n/**\n * Create Vercel AI SDK codebase_search tool\n * \n * @param config - Configuration with repoId\n * @returns Vercel AI SDK tool definition (execution built-in)\n * \n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { createCodebaseSearchTool } from 'morphsdk/tools/codebase-search/vercel';\n * \n * const tool = createCodebaseSearchTool({ repoId: 'my-project' });\n * \n * const result = await generateText({\n * model: anthropic('claude-3-5-sonnet-20241022'),\n * tools: { codebaseSearch: tool },\n * prompt: \"Find authentication code\",\n * maxSteps: 5\n * });\n * \n * // Vercel AI SDK automatically executes and handles results\n * console.log(result.text);\n * ```\n */\nexport function createCodebaseSearchTool(config: CodebaseSearchConfig) {\n const schema = z.object({\n query: z.string().describe('A complete question about what you want to understand. Ask as if talking to a colleague: \"How does X work?\", \"What happens when Y?\", \"Where is Z handled?\"'),\n target_directories: z.array(z.string()).describe('Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo.'),\n explanation: z.string().describe('One sentence explanation as to why this tool is being used, and how it contributes to the goal.'),\n limit: z.number().optional().describe('Max results to return (default: 10)'),\n });\n\n return tool({\n description: CODEBASE_SEARCH_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const { query, target_directories, explanation, limit } = params;\n const result = await executeCodebaseSearch(\n { query, target_directories, explanation, limit },\n config\n );\n\n if (!result.success) {\n return {\n error: result.error,\n results: [],\n };\n }\n\n // Format results for Vercel AI SDK\n return {\n found: result.results.length,\n searchTime: `${result.stats.searchTimeMs}ms`,\n results: result.results.map(r => ({\n file: r.filepath,\n symbol: r.symbolPath,\n lines: `${r.startLine}-${r.endLine}`,\n language: r.language,\n relevance: `${(r.rerankScore * 100).toFixed(1)}%`,\n code: r.content,\n })),\n };\n },\n });\n}\n\n/**\n * Get system prompt for Vercel AI SDK\n */\nexport function getSystemPrompt(): string {\n return CODEBASE_SEARCH_DESCRIPTION;\n}\n\n/**\n * Default export\n */\nexport default { createCodebaseSearchTool, getSystemPrompt };\n\n","/**\n * Vercel AI SDK adapter for edit_file tool\n */\n\nimport { tool } from 'ai';\nimport { z } from 'zod';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileConfig } from './types.js';\n\n/**\n * Vercel AI SDK tool for edit_file\n * \n * @example\n * ```ts\n * import { generateText } from 'ai';\n * import { anthropic } from '@ai-sdk/anthropic';\n * import { editFileTool } from 'morphsdk/tools/vercel';\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix the bug in app.ts\"\n * });\n * ```\n */\nconst editFileSchema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n});\n\nexport const editFileTool = tool({\n description: EDIT_FILE_TOOL_DESCRIPTION,\n inputSchema: editFileSchema,\n execute: async (params) => {\n const result = await executeEditFile({\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n });\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n});\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide the model on using edit_file properly.\n * \n * @example\n * ```ts\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * system: getSystemPrompt(),\n * tools: { editFile: editFileTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Vercel AI SDK tool with custom config\n * \n * @example\n * ```ts\n * const customEditTool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { editFile: customEditTool },\n * prompt: \"Fix bugs\"\n * });\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const schema = z.object({\n target_filepath: z.string().describe('The path of the target file to modify'),\n instructions: z\n .string()\n .describe('A single sentence describing what you are changing (first person)'),\n code_edit: z\n .string()\n .describe('The lazy edit with // ... existing code ... markers'),\n });\n\n return tool({\n description: config.description || EDIT_FILE_TOOL_DESCRIPTION,\n inputSchema: schema,\n execute: async (params) => {\n const result = await executeEditFile(\n {\n target_filepath: params.target_filepath,\n instructions: params.instructions,\n code_edit: params.code_edit,\n },\n config\n );\n \n if (!result.success) {\n throw new Error(`Failed to edit file: ${result.error}`);\n }\n \n return {\n success: true,\n filepath: result.filepath,\n changes: result.changes,\n udiff: result.udiff,\n };\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n","/**\n * Vercel AI SDK adapter for Explore subagent\n */\n\nimport { tool, generateText, stepCountIs } from 'ai';\nimport type { LanguageModel } from 'ai';\nimport { z } from 'zod';\nimport { WarpGrepClient } from '../tools/warp_grep/client.js';\nimport { formatResult } from '../tools/warp_grep/client.js';\nimport type { WarpGrepContext } from '../tools/warp_grep/types.js';\nimport { getSystemPrompt, CODEBASE_SEARCH_TOOL, SEND_MESSAGE_TOOL } from './prompts.js';\nimport type {\n ExploreSubagentConfig,\n ExploreResult,\n ExploreStep,\n ExploreSession,\n ExploreEvent,\n SubagentMessage,\n MessageHandler,\n StepHandler,\n} from './types.js';\n\n/** Config for Vercel AI SDK Explore subagent */\nexport interface VercelExploreConfig extends ExploreSubagentConfig {\n /** Vercel AI SDK model instance */\n model: LanguageModel;\n}\n\nconst DEFAULT_MAX_TURNS: Record<string, number> = {\n quick: 3,\n medium: 6,\n thorough: 12,\n};\n\nfunction getMaxTurns(config: ExploreSubagentConfig): number {\n return config.maxTurns ?? DEFAULT_MAX_TURNS[config.thoroughness ?? 'medium'] ?? 6;\n}\n\n/**\n * Create an Explore subagent using Vercel AI SDK\n */\nexport function createExploreSubagent(config: VercelExploreConfig) {\n if (!config.repoRoot) {\n throw new Error('repoRoot is required for Explore subagent');\n }\n\n const warpGrep = new WarpGrepClient({\n morphApiKey: config.morphApiKey,\n });\n\n const thoroughness = config.thoroughness ?? 'medium';\n const replyTimeout = config.replyTimeout ?? 30_000;\n\n /** Run the agent loop and collect results */\n async function runExplore(\n prompt: string,\n callbacks: {\n onStep?: StepHandler;\n onMessage?: MessageHandler;\n } = {},\n ): Promise<ExploreResult> {\n const startTime = Date.now();\n const allContexts: WarpGrepContext[] = [];\n let searchCount = 0;\n\n const timeoutMs = config.timeout;\n const timeoutPromise = timeoutMs\n ? new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error(`Exploration timed out after ${timeoutMs}ms`)), timeoutMs),\n )\n : null;\n\n const runPromise = (async (): Promise<ExploreResult> => {\n try {\n const codebaseSearchSchema = z.object({\n searchRequest: z.string().describe('Natural language description of what to search for'),\n });\n\n const sendMessageSchema = z.object({\n message: z.string().describe('The message to send to the orchestrator'),\n });\n\n const result = await generateText({\n model: config.model,\n system: getSystemPrompt(thoroughness),\n prompt,\n tools: {\n codebase_search: tool({\n description: CODEBASE_SEARCH_TOOL.description,\n inputSchema: codebaseSearchSchema,\n execute: async (params: z.infer<typeof codebaseSearchSchema>) => {\n searchCount++;\n const warpResult = await warpGrep.execute({\n searchTerm: params.searchRequest,\n repoRoot: config.repoRoot,\n excludes: config.excludes,\n includes: config.includes,\n });\n\n if (warpResult.contexts) {\n allContexts.push(...warpResult.contexts);\n }\n\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: params.searchRequest,\n contextsFound: warpResult.contexts?.length ?? 0,\n isFinal: false,\n });\n\n return formatResult(warpResult);\n },\n }),\n send_message: tool({\n description: SEND_MESSAGE_TOOL.description,\n inputSchema: sendMessageSchema,\n execute: async (params: z.infer<typeof sendMessageSchema>) => {\n const subagentMsg: SubagentMessage = {\n from: 'explore',\n content: params.message,\n timestamp: Date.now(),\n };\n\n // Create a promise that waits for the host's reply\n const replyPromise = new Promise<string>((resolve) => {\n // Emit the message to the host via callback\n if (callbacks.onMessage) {\n callbacks.onMessage(subagentMsg, (replyText: string) => {\n resolve(replyText);\n });\n } else {\n // No handler registered, auto-resolve after timeout\n setTimeout(() => resolve(''), replyTimeout);\n }\n });\n\n // Wait for reply with timeout\n const reply = await Promise.race([\n replyPromise,\n new Promise<string>((resolve) =>\n setTimeout(() => resolve(''), replyTimeout),\n ),\n ]);\n\n if (reply) {\n return `Response from orchestrator: ${reply}`;\n }\n return 'No response. Continue with your best judgment.';\n },\n }),\n },\n stopWhen: stepCountIs(getMaxTurns(config)),\n });\n\n // Emit final step\n callbacks.onStep?.({\n step: searchCount,\n searchRequest: '',\n contextsFound: allContexts.length,\n isFinal: true,\n });\n\n // Deduplicate contexts by file path\n const uniqueContexts = deduplicateContexts(allContexts);\n\n return {\n success: true,\n summary: result.text || 'Exploration completed but no summary was generated.',\n contexts: uniqueContexts,\n searchCount,\n durationMs: Date.now() - startTime,\n };\n } catch (error) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n })();\n\n if (timeoutPromise) {\n try {\n return await Promise.race([runPromise, timeoutPromise]);\n } catch (error) {\n return {\n success: false,\n summary: '',\n contexts: deduplicateContexts(allContexts),\n searchCount,\n durationMs: Date.now() - startTime,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n return runPromise;\n }\n\n const exploreToolSchema = z.object({\n searchRequest: z\n .string()\n .describe('What to explore in the codebase. Be specific about what you want to understand.'),\n });\n\n /** The Vercel AI tool for use in parent agents */\n const exploreTool = tool({\n description:\n 'Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings. Use this for broad exploration rather than pinpoint keyword searches.',\n inputSchema: exploreToolSchema,\n execute: async (params: z.infer<typeof exploreToolSchema>) => {\n const result = await runExplore(params.searchRequest);\n return {\n success: result.success,\n summary: result.summary,\n searchCount: result.searchCount,\n error: result.error,\n };\n },\n });\n\n return {\n /** Vercel AI SDK tool for use as a tool in parent agents */\n tool: exploreTool,\n\n /** Run exploration with messaging support */\n run(prompt: string): ExploreSession {\n const messageHandlers: MessageHandler[] = [];\n const stepHandlers: StepHandler[] = [];\n\n // Start the run lazily (after handlers are attached)\n let resultPromise: Promise<ExploreResult> | null = null;\n\n const session: ExploreSession = {\n on(event: string, handler: any) {\n if (event === 'message') messageHandlers.push(handler);\n if (event === 'step') stepHandlers.push(handler);\n return session;\n },\n send(_text: string) {\n // Convenience method — pause-and-ask flow uses the reply callback\n },\n get result() {\n if (!resultPromise) {\n resultPromise = runExplore(prompt, {\n onStep: (step) => {\n for (const handler of stepHandlers) handler(step);\n },\n onMessage: (msg, reply) => {\n if (messageHandlers.length > 0) {\n for (const handler of messageHandlers) handler(msg, reply);\n } else {\n // No handlers, auto-reply\n reply('');\n }\n },\n });\n }\n return resultPromise;\n },\n };\n\n return session;\n },\n\n /** Stream exploration events as an async generator */\n async *stream(prompt: string): AsyncGenerator<ExploreEvent, ExploreResult, undefined> {\n const events: ExploreEvent[] = [];\n let resolveNext: (() => void) | null = null;\n let done = false;\n\n const resultPromise = runExplore(prompt, {\n onStep: (step) => {\n events.push({\n type: 'step',\n step: step.step,\n searchRequest: step.searchRequest,\n contextsFound: step.contextsFound,\n isFinal: step.isFinal,\n });\n resolveNext?.();\n },\n onMessage: (msg, reply) => {\n events.push({\n type: 'message',\n from: msg.from,\n content: msg.content,\n timestamp: msg.timestamp,\n });\n resolveNext?.();\n // Auto-reply in streaming mode\n reply('Continue with your best judgment.');\n },\n });\n\n // Yield events as they come in\n while (!done) {\n if (events.length > 0) {\n yield events.shift()!;\n } else {\n // Check if the result is already done\n const raceResult = await Promise.race([\n resultPromise.then((r) => ({ type: 'done' as const, result: r })),\n new Promise<{ type: 'event' }>((resolve) => {\n resolveNext = () => resolve({ type: 'event' });\n }),\n ]);\n\n if (raceResult.type === 'done') {\n // Drain remaining events\n while (events.length > 0) {\n yield events.shift()!;\n }\n done = true;\n return raceResult.result;\n }\n }\n }\n\n return await resultPromise;\n },\n };\n}\n\n/** Deduplicate contexts, keeping the latest version of each file */\nfunction deduplicateContexts(contexts: WarpGrepContext[]): WarpGrepContext[] {\n const map = new Map<string, WarpGrepContext>();\n for (const ctx of contexts) {\n const existing = map.get(ctx.file);\n if (!existing || ctx.content.length > existing.content.length) {\n map.set(ctx.file, ctx);\n }\n }\n return Array.from(map.values());\n}\n","/**\n * Vercel AI SDK Tool Factory for MorphClient\n * \n * Creates Vercel AI SDK-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { LanguageModel } from 'ai';\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool, createGitHubSearchTool } from '../tools/warp_grep/vercel.js';\nimport { createCodebaseSearchTool } from '../tools/codebase_search/vercel.js';\nimport { createEditFileTool } from '../tools/fastapply/vercel.js';\nimport { createExploreSubagent } from '../subagents/vercel.js';\nimport type { WarpGrepToolConfig, GitHubSearchToolConfig } from '../tools/warp_grep/types.js';\nimport type { CodebaseSearchConfig } from '../tools/codebase_search/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\nimport type { ExploreSubagentConfig } from '../subagents/types.js';\n\n/**\n * Factory for creating Vercel AI SDK-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.vercel.createWarpGrepTool({ repoRoot: '.' });\n * const searchTool = morph.vercel.createCodebaseSearchTool({ repoId: 'my-project' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * \n * // Use with Vercel AI SDK\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { grep: grepTool, search: searchTool, edit: editTool },\n * prompt: 'Find and fix the bug'\n * });\n * ```\n */\nexport class VercelToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create a Vercel AI SDK-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible codebase search tool\n * \n * @param toolConfig - Tool configuration with repoId (apiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createCodebaseSearchTool(toolConfig: Omit<CodebaseSearchConfig, 'apiKey'>) {\n return createCodebaseSearchTool({ \n ...toolConfig, \n apiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible GitHub search tool\n *\n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createGitHubSearchTool(toolConfig?: Omit<GitHubSearchToolConfig, 'morphApiKey'>) {\n return createGitHubSearchTool({\n ...toolConfig,\n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Explore subagent that searches the codebase and returns summaries\n *\n * @param config - Subagent configuration including model (morphApiKey inherited from MorphClient)\n * @returns Explore subagent with .tool, .run(), and .stream() methods\n */\n createExploreSubagent(config: Omit<ExploreSubagentConfig, 'morphApiKey'> & { model: LanguageModel }) {\n return createExploreSubagent({\n ...config,\n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,MAAQ;AAAA,MACR,QAAU;AAAA,MACV,OAAS;AAAA,MACT,SAAW;AAAA,QACT,KAAK;AAAA,UACH,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,UAAU;AAAA,UACR,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,qBAAqB;AAAA,UACnB,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,4BAA4B;AAAA,UAC1B,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,+BAA+B;AAAA,UAC7B,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,4BAA4B;AAAA,UAC1B,OAAS;AAAA,UACT,QAAU;AAAA,UACV,SAAW;AAAA,QACb;AAAA,QACA,4BAA4B;AAAA,UAC1B,OAAS;AAAA,UACT,QAAU;AA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,EAC5C;AACF;","names":["OpenAI","resolve","path","fs","import_path","fs","shouldSkip","SKIP_NAMES","SKIP_EXTENSIONS","import_promises","import_path","fs","path","applyEdit","callMorphAPI","generateUdiff","countChanges","resolve","DEFAULT_API_URL","DEFAULT_CONFIG","resolve","res","import_path","path","isValidRange","import_path","path","import_openai","import_path","DEFAULT_API_URL","OpenAI","resolve","payload","relative","path","path","LocalRipgrepProvider","DEFAULT_TIMEOUT","path","import_fs","git","fs","http","resolve","import_isomorphic_git","import_node","DEFAULT_API_URL","DEFAULT_TIMEOUT","DEFAULT_CONFIG","tool","formatResult","formatResult","formatResult","createWarpGrepTool","tool","createGitHubSearchTool","createCodebaseSearchTool","formatResult","editFileTool","formatResult","createEditFileTool","getSystemPrompt","getSystemPrompt","resolve","createWarpGrepTool","createCodebaseSearchTool","createEditFileTool","createGitHubSearchTool","createWarpGrepTool","createGitHubSearchTool","import_ai","import_zod","createCodebaseSearchTool","import_ai","import_zod","editFileTool","createEditFileTool","import_ai","import_zod","DEFAULT_MAX_TURNS","getMaxTurns","createExploreSubagent","getSystemPrompt","resolve","deduplicateContexts","createWarpGrepTool","createCodebaseSearchTool","createEditFileTool","createGitHubSearchTool","createExploreSubagent"]}