@morphllm/morphsdk 0.2.192 → 0.2.193

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 (205) hide show
  1. package/dist/{chunk-OZDNWR3I.js → chunk-23KRET2F.js} +3 -3
  2. package/dist/{chunk-DDM6B66N.js → chunk-2BFAHP3U.js} +3 -3
  3. package/dist/{chunk-4BALDMIZ.js → chunk-362NSH77.js} +2 -2
  4. package/dist/{chunk-EUZCZNK4.js → chunk-3EVXYGJU.js} +2 -2
  5. package/dist/{chunk-QJQORGE3.js → chunk-3GYCTQ3B.js} +2 -2
  6. package/dist/{chunk-RAWFZX7R.js → chunk-5JZHQGFA.js} +2 -2
  7. package/dist/{chunk-HHSBWOAP.js → chunk-6HVOMKED.js} +2 -2
  8. package/dist/{chunk-IY5WUAFH.js → chunk-A7T7RKSW.js} +2 -2
  9. package/dist/{chunk-XT75CKB2.js → chunk-BMO22JIM.js} +21 -21
  10. package/dist/{chunk-AKPE7Z23.js → chunk-EQI6CRLJ.js} +2 -2
  11. package/dist/{chunk-45HXBGGH.js → chunk-F3FIVK6A.js} +2 -2
  12. package/dist/{chunk-3RIS4CS2.js → chunk-FLWWY5IP.js} +2 -2
  13. package/dist/{chunk-3RIS4CS2.js.map → chunk-FLWWY5IP.js.map} +1 -1
  14. package/dist/{chunk-24ID7P4E.js → chunk-GXQXQMVG.js} +4 -4
  15. package/dist/{chunk-CKN2RJPD.js → chunk-HQ3N3YAO.js} +2 -2
  16. package/dist/{chunk-TP625ZYJ.js → chunk-KGA3RGUQ.js} +2 -2
  17. package/dist/{chunk-UCDN6SER.js → chunk-LATNDSMS.js} +2 -2
  18. package/dist/{chunk-2W54UBCR.js → chunk-MHWNJR5B.js} +4 -4
  19. package/dist/{chunk-NDUHOFAN.js → chunk-N4LGEYGW.js} +2 -2
  20. package/dist/{chunk-F4L7PCXV.js → chunk-ONP3JVU3.js} +2 -2
  21. package/dist/{chunk-DRM3ETEL.js → chunk-OQZOP2PQ.js} +2 -2
  22. package/dist/{chunk-OXVH7KJ7.js → chunk-PI5TUSCU.js} +2 -2
  23. package/dist/{chunk-X57U7AHA.js → chunk-PPABZ2FR.js} +2 -2
  24. package/dist/{chunk-4EZ7L6FJ.js → chunk-SOZM3BG3.js} +3 -3
  25. package/dist/{chunk-FL4XLVK2.js → chunk-TW3IQ357.js} +2 -2
  26. package/dist/{chunk-G5J5ZHCG.js → chunk-UEHQJLKC.js} +2 -2
  27. package/dist/{chunk-A777CPSD.js → chunk-UXSK2O6V.js} +2 -2
  28. package/dist/{chunk-SM27L5SF.js → chunk-VPDOBYJE.js} +58 -10
  29. package/dist/chunk-VPDOBYJE.js.map +1 -0
  30. package/dist/{chunk-GS4QVZ75.js → chunk-WLTBLDXJ.js} +4 -4
  31. package/dist/{chunk-EABWHIAS.js → chunk-YTQSM7JP.js} +10 -4
  32. package/dist/chunk-YTQSM7JP.js.map +1 -0
  33. package/dist/{chunk-4E2HKWUQ.js → chunk-Z5Y5WBGI.js} +2 -2
  34. package/dist/{chunk-KKVV5RQZ.js → chunk-ZWJUC7YK.js} +3 -3
  35. package/dist/client.cjs +64 -12
  36. package/dist/client.cjs.map +1 -1
  37. package/dist/client.js +28 -28
  38. package/dist/core/client.cjs +1 -1
  39. package/dist/core/client.cjs.map +1 -1
  40. package/dist/core/client.js +4 -4
  41. package/dist/core/error.cjs +1 -1
  42. package/dist/core/error.cjs.map +1 -1
  43. package/dist/core/error.js +3 -3
  44. package/dist/core/index.cjs +1 -1
  45. package/dist/core/index.cjs.map +1 -1
  46. package/dist/core/index.js +4 -4
  47. package/dist/edge.cjs +58 -9
  48. package/dist/edge.cjs.map +1 -1
  49. package/dist/edge.d.ts +1 -1
  50. package/dist/edge.js +9 -7
  51. package/dist/git/client.cjs +1 -1
  52. package/dist/git/client.cjs.map +1 -1
  53. package/dist/git/client.js +5 -5
  54. package/dist/git/index.cjs +1 -1
  55. package/dist/git/index.cjs.map +1 -1
  56. package/dist/git/index.js +5 -5
  57. package/dist/index.cjs +66 -12
  58. package/dist/index.cjs.map +1 -1
  59. package/dist/index.d.ts +1 -1
  60. package/dist/index.js +30 -28
  61. package/dist/modelrouter/core.cjs +1 -1
  62. package/dist/modelrouter/core.cjs.map +1 -1
  63. package/dist/modelrouter/core.js +5 -5
  64. package/dist/modelrouter/index.cjs +1 -1
  65. package/dist/modelrouter/index.cjs.map +1 -1
  66. package/dist/modelrouter/index.js +5 -5
  67. package/dist/subagents/anthropic.cjs +1 -1
  68. package/dist/subagents/anthropic.cjs.map +1 -1
  69. package/dist/subagents/anthropic.js +9 -9
  70. package/dist/subagents/vercel.cjs +1 -1
  71. package/dist/subagents/vercel.cjs.map +1 -1
  72. package/dist/subagents/vercel.js +9 -9
  73. package/dist/tools/browser/anthropic.cjs +1 -1
  74. package/dist/tools/browser/anthropic.cjs.map +1 -1
  75. package/dist/tools/browser/anthropic.js +7 -7
  76. package/dist/tools/browser/core.cjs +1 -1
  77. package/dist/tools/browser/core.cjs.map +1 -1
  78. package/dist/tools/browser/core.js +6 -6
  79. package/dist/tools/browser/index.cjs +1 -1
  80. package/dist/tools/browser/index.cjs.map +1 -1
  81. package/dist/tools/browser/index.js +9 -9
  82. package/dist/tools/browser/openai.cjs +1 -1
  83. package/dist/tools/browser/openai.cjs.map +1 -1
  84. package/dist/tools/browser/openai.js +7 -7
  85. package/dist/tools/browser/profiles/core.cjs +1 -1
  86. package/dist/tools/browser/profiles/core.cjs.map +1 -1
  87. package/dist/tools/browser/profiles/core.js +3 -3
  88. package/dist/tools/browser/profiles/index.cjs +1 -1
  89. package/dist/tools/browser/profiles/index.cjs.map +1 -1
  90. package/dist/tools/browser/profiles/index.js +3 -3
  91. package/dist/tools/browser/vercel.cjs +1 -1
  92. package/dist/tools/browser/vercel.cjs.map +1 -1
  93. package/dist/tools/browser/vercel.js +7 -7
  94. package/dist/tools/codebase_search/anthropic.cjs +1 -1
  95. package/dist/tools/codebase_search/anthropic.cjs.map +1 -1
  96. package/dist/tools/codebase_search/anthropic.js +6 -6
  97. package/dist/tools/codebase_search/core.cjs +1 -1
  98. package/dist/tools/codebase_search/core.cjs.map +1 -1
  99. package/dist/tools/codebase_search/core.js +5 -5
  100. package/dist/tools/codebase_search/index.cjs +1 -1
  101. package/dist/tools/codebase_search/index.cjs.map +1 -1
  102. package/dist/tools/codebase_search/index.js +8 -8
  103. package/dist/tools/codebase_search/openai.cjs +1 -1
  104. package/dist/tools/codebase_search/openai.cjs.map +1 -1
  105. package/dist/tools/codebase_search/openai.js +6 -6
  106. package/dist/tools/codebase_search/vercel.cjs +1 -1
  107. package/dist/tools/codebase_search/vercel.cjs.map +1 -1
  108. package/dist/tools/codebase_search/vercel.js +6 -6
  109. package/dist/tools/compact/core.cjs +1 -1
  110. package/dist/tools/compact/core.cjs.map +1 -1
  111. package/dist/tools/compact/core.js +5 -5
  112. package/dist/tools/compact/index.cjs +1 -1
  113. package/dist/tools/compact/index.cjs.map +1 -1
  114. package/dist/tools/compact/index.js +6 -6
  115. package/dist/tools/fastapply/anthropic.cjs +64 -12
  116. package/dist/tools/fastapply/anthropic.cjs.map +1 -1
  117. package/dist/tools/fastapply/anthropic.js +7 -7
  118. package/dist/tools/fastapply/apply.cjs +58 -9
  119. package/dist/tools/fastapply/apply.cjs.map +1 -1
  120. package/dist/tools/fastapply/apply.d.ts +6 -1
  121. package/dist/tools/fastapply/apply.js +4 -2
  122. package/dist/tools/fastapply/core.cjs +66 -12
  123. package/dist/tools/fastapply/core.cjs.map +1 -1
  124. package/dist/tools/fastapply/core.d.ts +1 -1
  125. package/dist/tools/fastapply/core.js +8 -6
  126. package/dist/tools/fastapply/index.cjs +66 -12
  127. package/dist/tools/fastapply/index.cjs.map +1 -1
  128. package/dist/tools/fastapply/index.d.ts +1 -1
  129. package/dist/tools/fastapply/index.js +11 -9
  130. package/dist/tools/fastapply/openai.cjs +64 -12
  131. package/dist/tools/fastapply/openai.cjs.map +1 -1
  132. package/dist/tools/fastapply/openai.js +7 -7
  133. package/dist/tools/fastapply/types.cjs.map +1 -1
  134. package/dist/tools/fastapply/types.d.ts +6 -2
  135. package/dist/tools/fastapply/vercel.cjs +64 -12
  136. package/dist/tools/fastapply/vercel.cjs.map +1 -1
  137. package/dist/tools/fastapply/vercel.js +7 -7
  138. package/dist/tools/index.cjs +66 -12
  139. package/dist/tools/index.cjs.map +1 -1
  140. package/dist/tools/index.d.ts +1 -1
  141. package/dist/tools/index.js +11 -9
  142. package/dist/tools/reflex/core.cjs +1 -1
  143. package/dist/tools/reflex/core.cjs.map +1 -1
  144. package/dist/tools/reflex/core.js +5 -5
  145. package/dist/tools/reflex/index.cjs +1 -1
  146. package/dist/tools/reflex/index.cjs.map +1 -1
  147. package/dist/tools/reflex/index.js +5 -5
  148. package/dist/tools/utils/resilience.cjs +1 -1
  149. package/dist/tools/utils/resilience.cjs.map +1 -1
  150. package/dist/tools/utils/resilience.js +2 -2
  151. package/dist/tools/warp_grep/agent/runner.cjs +1 -1
  152. package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
  153. package/dist/tools/warp_grep/agent/runner.js +2 -2
  154. package/dist/tools/warp_grep/anthropic.cjs +1 -1
  155. package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
  156. package/dist/tools/warp_grep/anthropic.js +9 -9
  157. package/dist/tools/warp_grep/client.cjs +1 -1
  158. package/dist/tools/warp_grep/client.cjs.map +1 -1
  159. package/dist/tools/warp_grep/client.js +8 -8
  160. package/dist/tools/warp_grep/gemini.cjs +1 -1
  161. package/dist/tools/warp_grep/gemini.cjs.map +1 -1
  162. package/dist/tools/warp_grep/gemini.js +8 -8
  163. package/dist/tools/warp_grep/index.cjs +1 -1
  164. package/dist/tools/warp_grep/index.cjs.map +1 -1
  165. package/dist/tools/warp_grep/index.js +8 -8
  166. package/dist/tools/warp_grep/openai.cjs +1 -1
  167. package/dist/tools/warp_grep/openai.cjs.map +1 -1
  168. package/dist/tools/warp_grep/openai.js +9 -9
  169. package/dist/tools/warp_grep/vercel.cjs +1 -1
  170. package/dist/tools/warp_grep/vercel.cjs.map +1 -1
  171. package/dist/tools/warp_grep/vercel.js +9 -9
  172. package/dist/version.cjs +1 -1
  173. package/dist/version.cjs.map +1 -1
  174. package/dist/version.js +1 -1
  175. package/package.json +1 -1
  176. package/dist/chunk-EABWHIAS.js.map +0 -1
  177. package/dist/chunk-SM27L5SF.js.map +0 -1
  178. /package/dist/{chunk-OZDNWR3I.js.map → chunk-23KRET2F.js.map} +0 -0
  179. /package/dist/{chunk-DDM6B66N.js.map → chunk-2BFAHP3U.js.map} +0 -0
  180. /package/dist/{chunk-4BALDMIZ.js.map → chunk-362NSH77.js.map} +0 -0
  181. /package/dist/{chunk-EUZCZNK4.js.map → chunk-3EVXYGJU.js.map} +0 -0
  182. /package/dist/{chunk-QJQORGE3.js.map → chunk-3GYCTQ3B.js.map} +0 -0
  183. /package/dist/{chunk-RAWFZX7R.js.map → chunk-5JZHQGFA.js.map} +0 -0
  184. /package/dist/{chunk-HHSBWOAP.js.map → chunk-6HVOMKED.js.map} +0 -0
  185. /package/dist/{chunk-IY5WUAFH.js.map → chunk-A7T7RKSW.js.map} +0 -0
  186. /package/dist/{chunk-XT75CKB2.js.map → chunk-BMO22JIM.js.map} +0 -0
  187. /package/dist/{chunk-AKPE7Z23.js.map → chunk-EQI6CRLJ.js.map} +0 -0
  188. /package/dist/{chunk-45HXBGGH.js.map → chunk-F3FIVK6A.js.map} +0 -0
  189. /package/dist/{chunk-24ID7P4E.js.map → chunk-GXQXQMVG.js.map} +0 -0
  190. /package/dist/{chunk-CKN2RJPD.js.map → chunk-HQ3N3YAO.js.map} +0 -0
  191. /package/dist/{chunk-TP625ZYJ.js.map → chunk-KGA3RGUQ.js.map} +0 -0
  192. /package/dist/{chunk-UCDN6SER.js.map → chunk-LATNDSMS.js.map} +0 -0
  193. /package/dist/{chunk-2W54UBCR.js.map → chunk-MHWNJR5B.js.map} +0 -0
  194. /package/dist/{chunk-NDUHOFAN.js.map → chunk-N4LGEYGW.js.map} +0 -0
  195. /package/dist/{chunk-F4L7PCXV.js.map → chunk-ONP3JVU3.js.map} +0 -0
  196. /package/dist/{chunk-DRM3ETEL.js.map → chunk-OQZOP2PQ.js.map} +0 -0
  197. /package/dist/{chunk-OXVH7KJ7.js.map → chunk-PI5TUSCU.js.map} +0 -0
  198. /package/dist/{chunk-X57U7AHA.js.map → chunk-PPABZ2FR.js.map} +0 -0
  199. /package/dist/{chunk-4EZ7L6FJ.js.map → chunk-SOZM3BG3.js.map} +0 -0
  200. /package/dist/{chunk-FL4XLVK2.js.map → chunk-TW3IQ357.js.map} +0 -0
  201. /package/dist/{chunk-G5J5ZHCG.js.map → chunk-UEHQJLKC.js.map} +0 -0
  202. /package/dist/{chunk-A777CPSD.js.map → chunk-UXSK2O6V.js.map} +0 -0
  203. /package/dist/{chunk-GS4QVZ75.js.map → chunk-WLTBLDXJ.js.map} +0 -0
  204. /package/dist/{chunk-4E2HKWUQ.js.map → chunk-Z5Y5WBGI.js.map} +0 -0
  205. /package/dist/{chunk-KKVV5RQZ.js.map → chunk-ZWJUC7YK.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../logger.ts","../../../package.json","../../../version.ts","../../../tools/fastapply/apply.ts","../../../tools/fastapply/vercel.ts","../../../tools/fastapply/core.ts","../../../tools/utils/resilience.ts","../../../core/client.ts","../../../tools/fastapply/prompts.ts"],"sourcesContent":["/**\n * Edge-safe logger.\n *\n * This module is imported transitively by the edge entrypoint\n * (`@morphllm/morphsdk/edge`) via fastapply, modelrouter, etc.\n * Edge runtimes (Vercel Edge Functions, Cloudflare Workers, Deno Deploy)\n * run on V8 isolates — not Node.js — so Node built-ins like fs don't\n * exist. A top-level static import of fs would crash at module-load time,\n * even if createWriteStream is only called conditionally.\n *\n * Fix: we use a dynamic import() behind a runtime check. In Node the\n * import resolves and file logging works normally. In edge runtimes the\n * import rejects and we silently fall back to console-only logging.\n */\n\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\ninterface WriteStream {\n write(chunk: string): boolean;\n}\n\nclass MorphLogger {\n private enabled: boolean;\n private fileStream: WriteStream | null;\n /** Resolves once the file stream is initialized (or immediately if no file logging). */\n readonly ready: Promise<void>;\n\n constructor() {\n this.enabled = typeof process !== 'undefined' &&\n (process.env.MORPH_DEBUG === '1' || !!process.env.MORPH_LOG_FILE);\n this.fileStream = null;\n\n const f = typeof process !== 'undefined' ? process.env.MORPH_LOG_FILE : undefined;\n if (f) {\n // Dynamic import — never evaluated at parse time, so edge runtimes\n // don't blow up with \"Module 'fs' not found\".\n this.ready = import('fs')\n .then((fs) => {\n this.fileStream = fs.createWriteStream(f, { flags: 'a' });\n })\n .catch(() => {\n // Edge runtime — fs unavailable, silently skip file logging\n });\n } else {\n this.ready = Promise.resolve();\n }\n }\n\n debug(component: string, msg: string, data?: Record<string, unknown>) { this._log('debug', component, msg, data); }\n info(component: string, msg: string, data?: Record<string, unknown>) { this._log('info', component, msg, data); }\n warn(component: string, msg: string, data?: Record<string, unknown>) { this._log('warn', component, msg, data); }\n error(component: string, msg: string, data?: Record<string, unknown>) { this._log('error', component, msg, data); }\n\n enable() { this.enabled = true; }\n get isEnabled() { return this.enabled; }\n\n private _log(level: LogLevel, component: string, msg: string, data?: Record<string, unknown>) {\n if (level !== 'error' && !this.enabled) return;\n const ts = new Date().toISOString();\n const prefix = `[${ts}] [${level.toUpperCase()}] [${component}]`;\n console.error(data ? `${prefix} ${msg} ${JSON.stringify(data)}` : `${prefix} ${msg}`);\n this.fileStream?.write(JSON.stringify({ ts, level, component, msg, ...(data && { data }) }) + '\\n');\n }\n}\n\nexport const logger = new MorphLogger();\n","{\n \"name\": \"@morphllm/morphsdk\",\n \"version\": \"0.2.192\",\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 \"./logger\": {\n \"types\": \"./dist/logger.d.ts\",\n \"import\": \"./dist/logger.js\",\n \"require\": \"./dist/logger.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 \"./tracing\": {\n \"types\": \"./dist/tracing/index.d.ts\",\n \"import\": \"./dist/tracing/index.js\",\n \"require\": \"./dist/tracing/index.cjs\"\n },\n \"./tracing/otel\": {\n \"types\": \"./dist/tracing/otel.d.ts\",\n \"import\": \"./dist/tracing/otel.js\",\n \"require\": \"./dist/tracing/otel.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 \"./tools/reflex\": {\n \"types\": \"./dist/tools/reflex/index.d.ts\",\n \"import\": \"./dist/tools/reflex/index.js\",\n \"require\": \"./dist/tools/reflex/index.cjs\"\n },\n \"./tools/traces\": {\n \"types\": \"./dist/tools/traces/index.d.ts\",\n \"import\": \"./dist/tools/traces/index.js\",\n \"require\": \"./dist/tools/traces/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 core/index.ts core/client.ts core/resource.ts core/error.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/codebase_search/index.ts tools/codebase_search/core.ts tools/codebase_search/types.ts tools/codebase_search/prompts.ts tools/codebase_search/anthropic.ts tools/codebase_search/openai.ts tools/codebase_search/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts 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/reflex/index.ts tools/reflex/core.ts tools/reflex/types.ts tools/traces/index.ts tools/traces/core.ts tools/traces/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts tracing/index.ts tracing/core.ts tracing/interaction.ts tracing/otel.ts tracing/types.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve\",\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 \"test:e2e\": \"vitest run --config vitest.e2e.config.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 \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"^0.203.0\",\n \"@opentelemetry/sdk-trace-base\": \"^2.7.1\",\n \"@traceloop/node-server-sdk\": \"^0.27.0\",\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 { logger } from '../../logger.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 = 90000;\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 useLarge = config.large ?? (typeof process !== 'undefined' ? process.env?.MORPH_LARGE_APPLY !== 'false' : true);\n const model = useLarge ? 'morph-v3-large' : 'morph-v3-fast';\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 logger.debug('FastApply', 'http_request', {\n url: `${apiUrl}/v1/chat/completions`,\n model,\n filepath,\n instruction_len: instructions.length,\n original_len: originalCode.length,\n code_edit_len: codeEdit.length,\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 try {\n const completion = await client.chat.completions.create({\n model,\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 logger.debug('FastApply', 'http_response', { status: 200, completion_id: completion.id, content_len: content.length, latency_ms: elapsed });\n\n return { content, completionId: completion.id };\n } catch (error: any) {\n const elapsed = Date.now() - startTime;\n const status = error?.status || error?.response?.status;\n logger.error('FastApply', 'http_error', {\n status,\n error: error?.message,\n latency_ms: elapsed,\n });\n\n if (status === 401) {\n const err = new Error(\n 'Authentication failed: Your Morph API key is invalid or has been revoked. ' +\n 'Please visit https://morphllm.com to get a valid API key, then update your MCP configuration.'\n );\n (err as any).status = 401;\n throw err;\n }\n\n if (status === 429) {\n const err = new Error(\n 'Rate limited: You\\'ve exceeded your Morph API usage limits. ' +\n 'Please visit https://morphllm.com to check your plan and purchase additional credits.'\n );\n (err as any).status = 429;\n throw err;\n }\n\n throw error;\n }\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 is accepted but does nothing\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 filepath = input.filepath || 'file';\n\n try {\n logger.debug('FastApply', 'apply_edit_start', { original_len: input.originalCode.length, code_edit_len: input.codeEdit.length });\n\n const instruction = input.instruction ?? input.instructions ?? '';\n const { content: mergedCode, completionId } = await callMorphAPI(\n input.originalCode,\n input.codeEdit,\n instruction,\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 logger.error('FastApply', 'apply_edit_error', { error: errorMessage });\n\n return {\n success: false,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\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 instruction: z\n .string()\n .describe('A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit.'),\n code_edit: z\n .string()\n .describe('Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.'),\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 instruction: params.instruction,\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 instruction: z\n .string()\n .describe('A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit.'),\n code_edit: z\n .string()\n .describe('Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.'),\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 instruction: params.instruction,\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 * 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';\nimport { logger } from '../../logger.js';\nimport { MorphAPIClient } from '../../core/client.js';\nimport { APIResource } from '../../core/resource.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' | 'large'>> = {\n morphApiUrl: 'https://api.morphllm.com',\n baseDir: process.cwd(),\n generateUdiff: true,\n autoWrite: true,\n timeout: 90000,\n debug: false,\n};\n\n/**\n * FastApply client for programmatic file editing\n * Note: This client requires Node.js for file operations\n *\n * @deprecated Prefer the unified `MorphClient` (`new MorphClient({ apiKey }).fastApply`).\n * Standalone clients remain only for backwards compatibility and may be removed in a future\n * major version — do not use them in new code.\n */\nexport class FastApplyClient extends APIResource {\n private config: EditFileConfig;\n\n constructor(clientOrConfig: MorphAPIClient | { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n const isClient = clientOrConfig instanceof MorphAPIClient;\n super(\n isClient\n ? clientOrConfig\n : new MorphAPIClient({\n apiKey: clientOrConfig.apiKey,\n timeout: clientOrConfig.timeout ?? DEFAULT_CONFIG.timeout,\n retryConfig: clientOrConfig.retryConfig,\n debug: clientOrConfig.debug,\n }),\n );\n // FastApply talks to /v1/chat/completions through the `openai` package, but\n // sources its credentials and host from the shared transport.\n this.config = {\n morphApiKey: this._client.resolveApiKey(),\n morphApiUrl: this._client.baseURL,\n debug: this._client.debug,\n timeout: (isClient ? undefined : clientOrConfig.timeout) ?? DEFAULT_CONFIG.timeout,\n retryConfig: this._client.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\n logger.debug('FastApply', 'execute_start', { target_filepath: input.target_filepath, baseDir, autoWrite: config.autoWrite !== false });\n\n // Security: ensure file is within baseDir\n const relativePath = relative(baseDir, fullPath);\n if (relativePath.startsWith('..') || fullPath === baseDir) {\n logger.warn('FastApply', 'security_check_failed', { target_filepath: input.target_filepath, relative: relativePath });\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 logger.debug('FastApply', 'security_check', { resolved: fullPath, relative: relativePath });\n\n try {\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 let fileExists = true;\n try {\n originalCode = await readFile(fullPath, 'utf-8');\n logger.debug('FastApply', 'file_read', { path: fullPath, exists: true, size_bytes: originalCode.length });\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 fileExists = false;\n logger.debug('FastApply', 'file_read', { path: fullPath, exists: false });\n }\n\n const instruction = input.instruction ?? input.instructions ?? '';\n logger.debug('FastApply', 'api_call', { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });\n\n const { content: mergedCode, completionId } = await callMorphAPI(originalCode, input.code_edit, instruction, input.target_filepath, config);\n\n logger.debug('FastApply', 'api_response', { completion_id: completionId, merged_len: mergedCode.length });\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 logger.debug('FastApply', 'file_write', { path: fullPath, size_bytes: mergedCode.length });\n }\n\n const changes = countChanges(originalCode, mergedCode);\n logger.debug('FastApply', 'changes', { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });\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 logger.error('FastApply', 'execute_error', { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : undefined });\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 * MorphAPIClient — the SDK transport.\n *\n * One place owns authentication, the Morph service hosts, default headers,\n * retries, timeouts, and error mapping. Every resource (FastApply, Compact,\n * Reflex, …) holds a reference to this client and delegates HTTP to it via\n * `get`/`post`/`delete`/`request`, exactly like the OpenAI SDK.\n *\n * This module is intentionally free of tool imports and Node built-ins so it\n * stays edge-safe (it is reachable from `@morphllm/morphsdk/edge` through the\n * Compact and model-router resources).\n */\nimport { fetchWithRetry, withTimeout, MorphError, type RetryConfig } from '../tools/utils/resilience.js';\nimport { logger } from '../logger.js';\nimport { SDK_VERSION } from '../version.js';\nimport { toMorphError } from './error.js';\n\n/** The Morph services the SDK talks to. */\nconst DEFAULT_BASE_URL = 'https://api.morphllm.com';\nconst DEFAULT_REPOS_URL = 'https://repos.morphllm.com';\nconst DEFAULT_BROWSER_URL = 'https://browser.morphllm.com';\nconst DEFAULT_TIMEOUT = 60_000;\n\nconst env = (name: string): string | undefined =>\n typeof process !== 'undefined' ? process.env?.[name] : undefined;\n\nconst stripTrailingSlash = (url: string): string => url.replace(/\\/+$/, '');\n\nexport interface MorphAPIClientOptions {\n /** Morph API key. Resolved against `MORPH_API_KEY` at request time if omitted. */\n apiKey?: string;\n /** Primary API host (default `https://api.morphllm.com`). */\n baseURL?: string;\n /** Code-storage host for codebase search and git (default `https://repos.morphllm.com`). */\n reposURL?: string;\n /** Browser-automation host (default `https://browser.morphllm.com`). */\n browserURL?: string;\n /** Default per-request timeout in ms (default 60s). Resources may override per call. */\n timeout?: number;\n /** Retry policy for transient failures. */\n retryConfig?: RetryConfig;\n /** Enable debug logging. */\n debug?: boolean;\n}\n\n/** Per-request options accepted by `request`/`get`/`post`/`delete`. */\nexport interface RequestOptions {\n /** JSON body; serialized with `JSON.stringify`. */\n body?: unknown;\n /** Query parameters; `undefined`/`null` values are dropped. */\n query?: Record<string, string | number | boolean | undefined | null>;\n /** Extra headers, merged over (and able to override) the defaults. */\n headers?: Record<string, string>;\n /** Override the timeout for this call. */\n timeout?: number;\n /** Hit a different host than the default (e.g. `this._client.reposURL`). */\n baseURL?: string;\n /** Return the raw `Response` of a successful (2xx) request instead of parsed JSON (for streaming). */\n stream?: boolean;\n /**\n * Return the raw `Response` without throwing on non-2xx and without parsing.\n * For resources that map errors into their own taxonomy (e.g. GitHub).\n */\n raw?: boolean;\n /** Caller-supplied abort signal. */\n signal?: AbortSignal;\n}\n\nexport class MorphAPIClient {\n /** Explicit key as provided; resolved against env at request time. */\n apiKey?: string;\n baseURL: string;\n reposURL: string;\n browserURL: string;\n /** Explicit default timeout (ms), if set. The request default is applied lazily so\n * resources can read an undefined value and supply their own fallback. */\n timeout?: number;\n retryConfig?: RetryConfig;\n debug: boolean;\n\n constructor(options: MorphAPIClientOptions = {}) {\n this.apiKey = options.apiKey;\n this.baseURL = stripTrailingSlash(options.baseURL ?? DEFAULT_BASE_URL);\n this.reposURL = stripTrailingSlash(options.reposURL ?? env('MORPH_SEARCH_URL') ?? DEFAULT_REPOS_URL);\n this.browserURL = stripTrailingSlash(\n options.browserURL ?? (env('MORPH_ENVIRONMENT') === 'DEV' ? 'http://localhost:8000' : DEFAULT_BROWSER_URL),\n );\n this.timeout = options.timeout;\n this.retryConfig = options.retryConfig;\n this.debug = options.debug ?? false;\n if (this.debug) logger.enable();\n }\n\n /** The key actually used for requests: explicit, else `MORPH_API_KEY`. */\n resolveApiKey(): string | undefined {\n return this.apiKey ?? env('MORPH_API_KEY');\n }\n\n /** Headers shared with tools that bring their own HTTP client (FastApply/WarpGrep via the `openai` package). */\n defaultHeaders(): Record<string, string> {\n return { 'X-Morph-SDK-Version': SDK_VERSION };\n }\n\n buildURL(path: string, baseURL?: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n const base = stripTrailingSlash(baseURL ?? this.baseURL);\n return `${base}${path.startsWith('/') ? '' : '/'}${path}`;\n }\n\n private buildHeaders(apiKey: string, extra?: Record<string, string>): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n 'X-Morph-SDK-Version': SDK_VERSION,\n Authorization: `Bearer ${apiKey}`,\n ...extra,\n };\n }\n\n private applyQuery(url: string, query?: RequestOptions['query']): string {\n if (!query) return url;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== null) params.set(key, String(value));\n }\n const qs = params.toString();\n return qs ? `${url}${url.includes('?') ? '&' : '?'}${qs}` : url;\n }\n\n async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const apiKey = this.resolveApiKey();\n if (!apiKey) {\n throw new MorphError(\n 'Morph API key not found. Set the MORPH_API_KEY environment variable or pass apiKey in config.',\n 'missing_api_key',\n 401,\n );\n }\n\n const url = this.applyQuery(this.buildURL(path, opts.baseURL), opts.query);\n const timeout = opts.timeout ?? this.timeout ?? DEFAULT_TIMEOUT;\n\n const init: RequestInit = {\n method,\n headers: this.buildHeaders(apiKey, opts.headers),\n ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n };\n\n logger.debug('MorphAPIClient', 'request', { method, url });\n\n const response = await withTimeout(\n fetchWithRetry(url, init, this.retryConfig ?? {}),\n timeout,\n `Morph request to ${url} timed out after ${timeout}ms`,\n );\n\n if (opts.raw) return response as unknown as T;\n if (!response.ok) throw await toMorphError(response);\n if (opts.stream) return response as unknown as T;\n if (response.status === 204) return undefined as T;\n\n const text = await response.text();\n return (text ? JSON.parse(text) : undefined) as T;\n }\n\n get<T>(path: string, opts?: RequestOptions): Promise<T> {\n return this.request<T>('GET', path, opts);\n }\n\n post<T>(path: string, opts?: RequestOptions): Promise<T> {\n return this.request<T>('POST', path, opts);\n }\n\n delete<T>(path: string, opts?: RequestOptions): Promise<T> {\n return this.request<T>('DELETE', path, opts);\n }\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAqBM,aA4CO;AAjEb;AAAA;AAAA;AAqBA,IAAM,cAAN,MAAkB;AAAA,MACR;AAAA,MACA;AAAA;AAAA,MAEC;AAAA,MAET,cAAc;AACZ,aAAK,UAAU,OAAO,YAAY,gBAC/B,QAAQ,IAAI,gBAAgB,OAAO,CAAC,CAAC,QAAQ,IAAI;AACpD,aAAK,aAAa;AAElB,cAAM,IAAI,OAAO,YAAY,cAAc,QAAQ,IAAI,i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CAAC,OAAO,SAAS;AACnB,YAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,IACxD;AAEA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,UAAU,OAAO;AAAA,MACjB,SAAS,OAAO;AAAA,MAChB,OAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF,CAAC;AAiBM,SAAS,kBAA0B;AACxC,SAAO;AACT;AAuBO,SAAS,mBAAmB,SAAyB,CAAC,GAAG;AAC9D,QAAM,SAAS,aAAE,OAAO;AAAA,IACtB,iBAAiB,aAAE,OAAO,EAAE,SAAS,uCAAuC;AAAA,IAC5E,aAAa,aACV,OAAO,EACP,SAAS,yIAAyI;AAAA,IACrJ,WAAW,aACR,OAAO,EACP,SAAS,sHAAsH;AAAA,EACpI,CAAC;AAED,aAAO,gBAAK;AAAA,IACV,aAAa,OAAO,eAAe;AAAA,IACnC,aAAa;AAAA,IACb,SAAS,OAAO,WAAW;AACzB,YAAM,SAAS,MAAM;AAAA,QACnB;AAAA,UACE,iBAAiB,OAAO;AAAA,UACxB,aAAa,OAAO;AAAA,UACpB,WAAW,OAAO;AAAA,QACpB;AAAA,QACA;AAAA,MACF;AAEA,UAAI,CAAC,OAAO,SAAS;AACnB,cAAM,IAAI,MAAM,wBAAwB,OAAO,KAAK,EAAE;AAAA,MACxD;AAEA,aAAO;AAAA,QACL,SAAS;AAAA,QACT,UAAU,OAAO;AAAA,QACjB,SAAS,OAAO;AAAA,QAChB,OAAO,OAAO;AAAA,MAChB;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAGA,IAAO,iBAAQ;","names":["OpenAI","callMorphAPI","generateUdiff","countChanges"]}
1
+ {"version":3,"sources":["../../../logger.ts","../../../package.json","../../../version.ts","../../../tools/fastapply/apply.ts","../../../tools/fastapply/vercel.ts","../../../tools/fastapply/core.ts","../../../tools/utils/resilience.ts","../../../core/client.ts","../../../tools/fastapply/prompts.ts"],"sourcesContent":["/**\n * Edge-safe logger.\n *\n * This module is imported transitively by the edge entrypoint\n * (`@morphllm/morphsdk/edge`) via fastapply, modelrouter, etc.\n * Edge runtimes (Vercel Edge Functions, Cloudflare Workers, Deno Deploy)\n * run on V8 isolates — not Node.js — so Node built-ins like fs don't\n * exist. A top-level static import of fs would crash at module-load time,\n * even if createWriteStream is only called conditionally.\n *\n * Fix: we use a dynamic import() behind a runtime check. In Node the\n * import resolves and file logging works normally. In edge runtimes the\n * import rejects and we silently fall back to console-only logging.\n */\n\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\ninterface WriteStream {\n write(chunk: string): boolean;\n}\n\nclass MorphLogger {\n private enabled: boolean;\n private fileStream: WriteStream | null;\n /** Resolves once the file stream is initialized (or immediately if no file logging). */\n readonly ready: Promise<void>;\n\n constructor() {\n this.enabled = typeof process !== 'undefined' &&\n (process.env.MORPH_DEBUG === '1' || !!process.env.MORPH_LOG_FILE);\n this.fileStream = null;\n\n const f = typeof process !== 'undefined' ? process.env.MORPH_LOG_FILE : undefined;\n if (f) {\n // Dynamic import — never evaluated at parse time, so edge runtimes\n // don't blow up with \"Module 'fs' not found\".\n this.ready = import('fs')\n .then((fs) => {\n this.fileStream = fs.createWriteStream(f, { flags: 'a' });\n })\n .catch(() => {\n // Edge runtime — fs unavailable, silently skip file logging\n });\n } else {\n this.ready = Promise.resolve();\n }\n }\n\n debug(component: string, msg: string, data?: Record<string, unknown>) { this._log('debug', component, msg, data); }\n info(component: string, msg: string, data?: Record<string, unknown>) { this._log('info', component, msg, data); }\n warn(component: string, msg: string, data?: Record<string, unknown>) { this._log('warn', component, msg, data); }\n error(component: string, msg: string, data?: Record<string, unknown>) { this._log('error', component, msg, data); }\n\n enable() { this.enabled = true; }\n get isEnabled() { return this.enabled; }\n\n private _log(level: LogLevel, component: string, msg: string, data?: Record<string, unknown>) {\n if (level !== 'error' && !this.enabled) return;\n const ts = new Date().toISOString();\n const prefix = `[${ts}] [${level.toUpperCase()}] [${component}]`;\n console.error(data ? `${prefix} ${msg} ${JSON.stringify(data)}` : `${prefix} ${msg}`);\n this.fileStream?.write(JSON.stringify({ ts, level, component, msg, ...(data && { data }) }) + '\\n');\n }\n}\n\nexport const logger = new MorphLogger();\n","{\n \"name\": \"@morphllm/morphsdk\",\n \"version\": \"0.2.193\",\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 \"./logger\": {\n \"types\": \"./dist/logger.d.ts\",\n \"import\": \"./dist/logger.js\",\n \"require\": \"./dist/logger.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 \"./tracing\": {\n \"types\": \"./dist/tracing/index.d.ts\",\n \"import\": \"./dist/tracing/index.js\",\n \"require\": \"./dist/tracing/index.cjs\"\n },\n \"./tracing/otel\": {\n \"types\": \"./dist/tracing/otel.d.ts\",\n \"import\": \"./dist/tracing/otel.js\",\n \"require\": \"./dist/tracing/otel.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 \"./tools/reflex\": {\n \"types\": \"./dist/tools/reflex/index.d.ts\",\n \"import\": \"./dist/tools/reflex/index.js\",\n \"require\": \"./dist/tools/reflex/index.cjs\"\n },\n \"./tools/traces\": {\n \"types\": \"./dist/tools/traces/index.d.ts\",\n \"import\": \"./dist/tools/traces/index.js\",\n \"require\": \"./dist/tools/traces/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 core/index.ts core/client.ts core/resource.ts core/error.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/codebase_search/index.ts tools/codebase_search/core.ts tools/codebase_search/types.ts tools/codebase_search/prompts.ts tools/codebase_search/anthropic.ts tools/codebase_search/openai.ts tools/codebase_search/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts 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/reflex/index.ts tools/reflex/core.ts tools/reflex/types.ts tools/traces/index.ts tools/traces/core.ts tools/traces/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts tracing/index.ts tracing/core.ts tracing/interaction.ts tracing/otel.ts tracing/types.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve\",\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 \"test:e2e\": \"vitest run --config vitest.e2e.config.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 \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"^0.203.0\",\n \"@opentelemetry/sdk-trace-base\": \"^2.7.1\",\n \"@traceloop/node-server-sdk\": \"^0.27.0\",\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 { logger } from '../../logger.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 = 600000;\n\ntype CompletionChunk = {\n id?: string;\n choices?: Array<{\n delta?: { content?: string | null };\n finish_reason?: string | null;\n }>;\n};\n\ntype CompletionResponse = {\n id?: string;\n choices?: Array<{\n message?: { content?: string | null };\n finish_reason?: string | null;\n }>;\n};\n\nexport class FastApplyContextLengthError extends Error {\n readonly code = 'context_length_exceeded';\n readonly completionId?: string;\n\n constructor(completionId?: string) {\n super(\n 'Fast Apply exhausted its context window before producing the complete file. ' +\n 'Retry with a smaller input/update or use sparse anchors for unchanged code.'\n );\n this.name = 'FastApplyContextLengthError';\n this.completionId = completionId;\n }\n}\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<CompletionChunk> {\n return typeof value === 'object' && value !== null && Symbol.asyncIterator in value;\n}\n\nasync function collectCompletion(\n response: unknown\n): Promise<{ content: string; completionId?: string; finishReason?: string | null }> {\n if (!isAsyncIterable(response)) {\n const completion = response as CompletionResponse;\n return {\n content: completion.choices?.[0]?.message?.content ?? '',\n completionId: completion.id,\n finishReason: completion.choices?.[0]?.finish_reason,\n };\n }\n\n const content: string[] = [];\n let completionId: string | undefined;\n let finishReason: string | null | undefined;\n\n for await (const chunk of response) {\n completionId = chunk.id ?? completionId;\n for (const choice of chunk.choices ?? []) {\n if (choice.delta?.content) {\n content.push(choice.delta.content);\n }\n if (choice.finish_reason !== undefined && choice.finish_reason !== null) {\n finishReason = choice.finish_reason;\n }\n }\n }\n\n return { content: content.join(''), completionId, finishReason };\n}\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 useLarge = config.large ?? (typeof process !== 'undefined' ? process.env?.MORPH_LARGE_APPLY !== 'false' : true);\n const model = useLarge ? 'morph-v3-large' : 'morph-v3-fast';\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 logger.debug('FastApply', 'http_request', {\n url: `${apiUrl}/v1/chat/completions`,\n model,\n filepath,\n instruction_len: instructions.length,\n original_len: originalCode.length,\n code_edit_len: codeEdit.length,\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 try {\n const response = await client.chat.completions.create({\n model,\n messages: [{ role: 'user', content: message }],\n stream: true,\n });\n const completion = await collectCompletion(response);\n\n if (completion.finishReason === 'length') {\n throw new FastApplyContextLengthError(completion.completionId);\n }\n\n const content = completion.content;\n if (!content) {\n throw new Error('Morph API returned empty response');\n }\n\n const elapsed = Date.now() - startTime;\n logger.debug('FastApply', 'http_response', { status: 200, completion_id: completion.completionId, content_len: content.length, latency_ms: elapsed });\n\n return { content, completionId: completion.completionId };\n } catch (error: any) {\n const elapsed = Date.now() - startTime;\n const status = error?.status || error?.response?.status;\n logger.error('FastApply', 'http_error', {\n status,\n error: error?.message,\n latency_ms: elapsed,\n });\n\n if (status === 401) {\n const err = new Error(\n 'Authentication failed: Your Morph API key is invalid or has been revoked. ' +\n 'Please visit https://morphllm.com to get a valid API key, then update your MCP configuration.'\n );\n (err as any).status = 401;\n throw err;\n }\n\n if (status === 429) {\n const err = new Error(\n 'Rate limited: You\\'ve exceeded your Morph API usage limits. ' +\n 'Please visit https://morphllm.com to check your plan and purchase additional credits.'\n );\n (err as any).status = 429;\n throw err;\n }\n\n throw error;\n }\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 is accepted but does nothing\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 filepath = input.filepath || 'file';\n\n try {\n logger.debug('FastApply', 'apply_edit_start', { original_len: input.originalCode.length, code_edit_len: input.codeEdit.length });\n\n const instruction = input.instruction ?? input.instructions ?? '';\n const { content: mergedCode, completionId } = await callMorphAPI(\n input.originalCode,\n input.codeEdit,\n instruction,\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 logger.error('FastApply', 'apply_edit_error', { error: errorMessage });\n const contextError = error instanceof FastApplyContextLengthError ? error : undefined;\n\n return {\n success: false,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n errorCode: contextError?.code,\n completionId: contextError?.completionId,\n };\n }\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 instruction: z\n .string()\n .describe('A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit.'),\n code_edit: z\n .string()\n .describe('Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.'),\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 instruction: params.instruction,\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 instruction: z\n .string()\n .describe('A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit.'),\n code_edit: z\n .string()\n .describe('Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.'),\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 instruction: params.instruction,\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 * 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';\nimport { logger } from '../../logger.js';\nimport { MorphAPIClient } from '../../core/client.js';\nimport { APIResource } from '../../core/resource.js';\nimport { FastApplyContextLengthError } from './apply.js';\n\n// Re-export edge-compatible functions\nexport { applyEdit, generateUdiff, countChanges, callMorphAPI } from './apply.js';\nexport { FastApplyContextLengthError };\n\nconst DEFAULT_CONFIG: Required<Omit<EditFileConfig, 'morphApiKey' | 'systemPrompt' | 'retryConfig' | 'description' | 'large'>> = {\n morphApiUrl: 'https://api.morphllm.com',\n baseDir: process.cwd(),\n generateUdiff: true,\n autoWrite: true,\n timeout: 600000,\n debug: false,\n};\n\n/**\n * FastApply client for programmatic file editing\n * Note: This client requires Node.js for file operations\n *\n * @deprecated Prefer the unified `MorphClient` (`new MorphClient({ apiKey }).fastApply`).\n * Standalone clients remain only for backwards compatibility and may be removed in a future\n * major version — do not use them in new code.\n */\nexport class FastApplyClient extends APIResource {\n private config: EditFileConfig;\n\n constructor(clientOrConfig: MorphAPIClient | { apiKey?: string; debug?: boolean; timeout?: number; retryConfig?: any } = {}) {\n const isClient = clientOrConfig instanceof MorphAPIClient;\n super(\n isClient\n ? clientOrConfig\n : new MorphAPIClient({\n apiKey: clientOrConfig.apiKey,\n timeout: clientOrConfig.timeout ?? DEFAULT_CONFIG.timeout,\n retryConfig: clientOrConfig.retryConfig,\n debug: clientOrConfig.debug,\n }),\n );\n // FastApply talks to /v1/chat/completions through the `openai` package, but\n // sources its credentials and host from the shared transport.\n this.config = {\n morphApiKey: this._client.resolveApiKey(),\n morphApiUrl: this._client.baseURL,\n debug: this._client.debug,\n timeout: (isClient ? undefined : clientOrConfig.timeout) ?? DEFAULT_CONFIG.timeout,\n retryConfig: this._client.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\n logger.debug('FastApply', 'execute_start', { target_filepath: input.target_filepath, baseDir, autoWrite: config.autoWrite !== false });\n\n // Security: ensure file is within baseDir\n const relativePath = relative(baseDir, fullPath);\n if (relativePath.startsWith('..') || fullPath === baseDir) {\n logger.warn('FastApply', 'security_check_failed', { target_filepath: input.target_filepath, relative: relativePath });\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 logger.debug('FastApply', 'security_check', { resolved: fullPath, relative: relativePath });\n\n try {\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 let fileExists = true;\n try {\n originalCode = await readFile(fullPath, 'utf-8');\n logger.debug('FastApply', 'file_read', { path: fullPath, exists: true, size_bytes: originalCode.length });\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 fileExists = false;\n logger.debug('FastApply', 'file_read', { path: fullPath, exists: false });\n }\n\n const instruction = input.instruction ?? input.instructions ?? '';\n logger.debug('FastApply', 'api_call', { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });\n\n const { content: mergedCode, completionId } = await callMorphAPI(originalCode, input.code_edit, instruction, input.target_filepath, config);\n\n logger.debug('FastApply', 'api_response', { completion_id: completionId, merged_len: mergedCode.length });\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 logger.debug('FastApply', 'file_write', { path: fullPath, size_bytes: mergedCode.length });\n }\n\n const changes = countChanges(originalCode, mergedCode);\n logger.debug('FastApply', 'changes', { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });\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 const contextError = error instanceof FastApplyContextLengthError ? error : undefined;\n logger.error('FastApply', 'execute_error', { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : undefined });\n\n return {\n success: false,\n filepath: input.target_filepath,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n errorCode: contextError?.code,\n completionId: contextError?.completionId,\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 * MorphAPIClient — the SDK transport.\n *\n * One place owns authentication, the Morph service hosts, default headers,\n * retries, timeouts, and error mapping. Every resource (FastApply, Compact,\n * Reflex, …) holds a reference to this client and delegates HTTP to it via\n * `get`/`post`/`delete`/`request`, exactly like the OpenAI SDK.\n *\n * This module is intentionally free of tool imports and Node built-ins so it\n * stays edge-safe (it is reachable from `@morphllm/morphsdk/edge` through the\n * Compact and model-router resources).\n */\nimport { fetchWithRetry, withTimeout, MorphError, type RetryConfig } from '../tools/utils/resilience.js';\nimport { logger } from '../logger.js';\nimport { SDK_VERSION } from '../version.js';\nimport { toMorphError } from './error.js';\n\n/** The Morph services the SDK talks to. */\nconst DEFAULT_BASE_URL = 'https://api.morphllm.com';\nconst DEFAULT_REPOS_URL = 'https://repos.morphllm.com';\nconst DEFAULT_BROWSER_URL = 'https://browser.morphllm.com';\nconst DEFAULT_TIMEOUT = 60_000;\n\nconst env = (name: string): string | undefined =>\n typeof process !== 'undefined' ? process.env?.[name] : undefined;\n\nconst stripTrailingSlash = (url: string): string => url.replace(/\\/+$/, '');\n\nexport interface MorphAPIClientOptions {\n /** Morph API key. Resolved against `MORPH_API_KEY` at request time if omitted. */\n apiKey?: string;\n /** Primary API host (default `https://api.morphllm.com`). */\n baseURL?: string;\n /** Code-storage host for codebase search and git (default `https://repos.morphllm.com`). */\n reposURL?: string;\n /** Browser-automation host (default `https://browser.morphllm.com`). */\n browserURL?: string;\n /** Default per-request timeout in ms (default 60s). Resources may override per call. */\n timeout?: number;\n /** Retry policy for transient failures. */\n retryConfig?: RetryConfig;\n /** Enable debug logging. */\n debug?: boolean;\n}\n\n/** Per-request options accepted by `request`/`get`/`post`/`delete`. */\nexport interface RequestOptions {\n /** JSON body; serialized with `JSON.stringify`. */\n body?: unknown;\n /** Query parameters; `undefined`/`null` values are dropped. */\n query?: Record<string, string | number | boolean | undefined | null>;\n /** Extra headers, merged over (and able to override) the defaults. */\n headers?: Record<string, string>;\n /** Override the timeout for this call. */\n timeout?: number;\n /** Hit a different host than the default (e.g. `this._client.reposURL`). */\n baseURL?: string;\n /** Return the raw `Response` of a successful (2xx) request instead of parsed JSON (for streaming). */\n stream?: boolean;\n /**\n * Return the raw `Response` without throwing on non-2xx and without parsing.\n * For resources that map errors into their own taxonomy (e.g. GitHub).\n */\n raw?: boolean;\n /** Caller-supplied abort signal. */\n signal?: AbortSignal;\n}\n\nexport class MorphAPIClient {\n /** Explicit key as provided; resolved against env at request time. */\n apiKey?: string;\n baseURL: string;\n reposURL: string;\n browserURL: string;\n /** Explicit default timeout (ms), if set. The request default is applied lazily so\n * resources can read an undefined value and supply their own fallback. */\n timeout?: number;\n retryConfig?: RetryConfig;\n debug: boolean;\n\n constructor(options: MorphAPIClientOptions = {}) {\n this.apiKey = options.apiKey;\n this.baseURL = stripTrailingSlash(options.baseURL ?? DEFAULT_BASE_URL);\n this.reposURL = stripTrailingSlash(options.reposURL ?? env('MORPH_SEARCH_URL') ?? DEFAULT_REPOS_URL);\n this.browserURL = stripTrailingSlash(\n options.browserURL ?? (env('MORPH_ENVIRONMENT') === 'DEV' ? 'http://localhost:8000' : DEFAULT_BROWSER_URL),\n );\n this.timeout = options.timeout;\n this.retryConfig = options.retryConfig;\n this.debug = options.debug ?? false;\n if (this.debug) logger.enable();\n }\n\n /** The key actually used for requests: explicit, else `MORPH_API_KEY`. */\n resolveApiKey(): string | undefined {\n return this.apiKey ?? env('MORPH_API_KEY');\n }\n\n /** Headers shared with tools that bring their own HTTP client (FastApply/WarpGrep via the `openai` package). */\n defaultHeaders(): Record<string, string> {\n return { 'X-Morph-SDK-Version': SDK_VERSION };\n }\n\n buildURL(path: string, baseURL?: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n const base = stripTrailingSlash(baseURL ?? this.baseURL);\n return `${base}${path.startsWith('/') ? '' : '/'}${path}`;\n }\n\n private buildHeaders(apiKey: string, extra?: Record<string, string>): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n 'X-Morph-SDK-Version': SDK_VERSION,\n Authorization: `Bearer ${apiKey}`,\n ...extra,\n };\n }\n\n private applyQuery(url: string, query?: RequestOptions['query']): string {\n if (!query) return url;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== null) params.set(key, String(value));\n }\n const qs = params.toString();\n return qs ? `${url}${url.includes('?') ? '&' : '?'}${qs}` : url;\n }\n\n async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const apiKey = this.resolveApiKey();\n if (!apiKey) {\n throw new MorphError(\n 'Morph API key not found. Set the MORPH_API_KEY environment variable or pass apiKey in config.',\n 'missing_api_key',\n 401,\n );\n }\n\n const url = this.applyQuery(this.buildURL(path, opts.baseURL), opts.query);\n const timeout = opts.timeout ?? this.timeout ?? DEFAULT_TIMEOUT;\n\n const init: RequestInit = {\n method,\n headers: this.buildHeaders(apiKey, opts.headers),\n ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n };\n\n logger.debug('MorphAPIClient', 'request', { method, url });\n\n const response = await withTimeout(\n fetchWithRetry(url, init, this.retryConfig ?? {}),\n timeout,\n `Morph request to ${url} timed out after ${timeout}ms`,\n );\n\n if (opts.raw) return response as unknown as T;\n if (!response.ok) throw await toMorphError(response);\n if (opts.stream) return response as unknown as T;\n if (response.status === 204) return undefined as T;\n\n const text = await response.text();\n return (text ? JSON.parse(text) : undefined) as T;\n }\n\n get<T>(path: string, opts?: RequestOptions): Promise<T> {\n return this.request<T>('GET', path, opts);\n }\n\n post<T>(path: string, opts?: RequestOptions): Promise<T> {\n return this.request<T>('POST', path, opts);\n }\n\n delete<T>(path: string, opts?: RequestOptions): Promise<T> {\n return this.request<T>('DELETE', path, opts);\n }\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAqBM,aA4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;AAGA,IAAO,iBAAQ;","names":["OpenAI","callMorphAPI","generateUdiff","countChanges"]}
@@ -3,15 +3,15 @@ import {
3
3
  editFileTool,
4
4
  getSystemPrompt,
5
5
  vercel_default
6
- } from "../../chunk-4BALDMIZ.js";
6
+ } from "../../chunk-362NSH77.js";
7
7
  import "../../chunk-63WE2C5R.js";
8
- import "../../chunk-EABWHIAS.js";
9
- import "../../chunk-SM27L5SF.js";
10
- import "../../chunk-2W54UBCR.js";
8
+ import "../../chunk-YTQSM7JP.js";
9
+ import "../../chunk-VPDOBYJE.js";
10
+ import "../../chunk-MHWNJR5B.js";
11
11
  import "../../chunk-F3NCFNUX.js";
12
- import "../../chunk-4E2HKWUQ.js";
13
- import "../../chunk-EUZCZNK4.js";
14
- import "../../chunk-3RIS4CS2.js";
12
+ import "../../chunk-Z5Y5WBGI.js";
13
+ import "../../chunk-3EVXYGJU.js";
14
+ import "../../chunk-FLWWY5IP.js";
15
15
  import "../../chunk-LKFZBBTD.js";
16
16
  import "../../chunk-PZ5AY32C.js";
17
17
  export {
@@ -89,7 +89,7 @@ var init_package = __esm({
89
89
  "package.json"() {
90
90
  package_default = {
91
91
  name: "@morphllm/morphsdk",
92
- version: "0.2.192",
92
+ version: "0.2.193",
93
93
  description: "TypeScript SDK and CLI for Morph Fast Apply integration",
94
94
  type: "module",
95
95
  main: "./dist/index.cjs",
@@ -369,11 +369,40 @@ var init_version = __esm({
369
369
  // tools/fastapply/apply.ts
370
370
  var apply_exports = {};
371
371
  __export(apply_exports, {
372
+ FastApplyContextLengthError: () => FastApplyContextLengthError,
372
373
  applyEdit: () => applyEdit,
373
374
  callMorphAPI: () => callMorphAPI,
374
375
  countChanges: () => countChanges,
375
376
  generateUdiff: () => generateUdiff
376
377
  });
378
+ function isAsyncIterable(value) {
379
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
380
+ }
381
+ async function collectCompletion(response) {
382
+ if (!isAsyncIterable(response)) {
383
+ const completion = response;
384
+ return {
385
+ content: completion.choices?.[0]?.message?.content ?? "",
386
+ completionId: completion.id,
387
+ finishReason: completion.choices?.[0]?.finish_reason
388
+ };
389
+ }
390
+ const content = [];
391
+ let completionId;
392
+ let finishReason;
393
+ for await (const chunk of response) {
394
+ completionId = chunk.id ?? completionId;
395
+ for (const choice of chunk.choices ?? []) {
396
+ if (choice.delta?.content) {
397
+ content.push(choice.delta.content);
398
+ }
399
+ if (choice.finish_reason !== void 0 && choice.finish_reason !== null) {
400
+ finishReason = choice.finish_reason;
401
+ }
402
+ }
403
+ }
404
+ return { content: content.join(""), completionId, finishReason };
405
+ }
377
406
  function generateUdiff(original, modified, filepath) {
378
407
  return (0, import_diff.createTwoFilesPatch)(
379
408
  filepath,
@@ -408,7 +437,7 @@ async function callMorphAPI(originalCode, codeEdit, instructions, filepath, conf
408
437
  const apiUrl = config.morphApiUrl || DEFAULT_API_URL;
409
438
  const useLarge = config.large ?? (typeof process !== "undefined" ? process.env?.MORPH_LARGE_APPLY !== "false" : true);
410
439
  const model = useLarge ? "morph-v3-large" : "morph-v3-fast";
411
- const timeout = config.timeout || DEFAULT_TIMEOUT;
440
+ const timeout = config.timeout ?? DEFAULT_TIMEOUT;
412
441
  const debug = config.debug || false;
413
442
  if (!apiKey) {
414
443
  throw new Error(
@@ -435,17 +464,22 @@ async function callMorphAPI(originalCode, codeEdit, instructions, filepath, conf
435
464
  defaultHeaders: { "X-Morph-SDK-Version": SDK_VERSION }
436
465
  });
437
466
  try {
438
- const completion = await client.chat.completions.create({
467
+ const response = await client.chat.completions.create({
439
468
  model,
440
- messages: [{ role: "user", content: message }]
469
+ messages: [{ role: "user", content: message }],
470
+ stream: true
441
471
  });
442
- const content = completion.choices[0]?.message?.content;
472
+ const completion = await collectCompletion(response);
473
+ if (completion.finishReason === "length") {
474
+ throw new FastApplyContextLengthError(completion.completionId);
475
+ }
476
+ const content = completion.content;
443
477
  if (!content) {
444
478
  throw new Error("Morph API returned empty response");
445
479
  }
446
480
  const elapsed = Date.now() - startTime;
447
- logger.debug("FastApply", "http_response", { status: 200, completion_id: completion.id, content_len: content.length, latency_ms: elapsed });
448
- return { content, completionId: completion.id };
481
+ logger.debug("FastApply", "http_response", { status: 200, completion_id: completion.completionId, content_len: content.length, latency_ms: elapsed });
482
+ return { content, completionId: completion.completionId };
449
483
  } catch (error) {
450
484
  const elapsed = Date.now() - startTime;
451
485
  const status = error?.status || error?.response?.status;
@@ -495,14 +529,17 @@ async function applyEdit(input, config = {}) {
495
529
  } catch (error) {
496
530
  const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
497
531
  logger.error("FastApply", "apply_edit_error", { error: errorMessage });
532
+ const contextError = error instanceof FastApplyContextLengthError ? error : void 0;
498
533
  return {
499
534
  success: false,
500
535
  changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
501
- error: errorMessage
536
+ error: errorMessage,
537
+ errorCode: contextError?.code,
538
+ completionId: contextError?.completionId
502
539
  };
503
540
  }
504
541
  }
505
- var import_diff, import_openai, DEFAULT_API_URL, DEFAULT_TIMEOUT;
542
+ var import_diff, import_openai, DEFAULT_API_URL, DEFAULT_TIMEOUT, FastApplyContextLengthError;
506
543
  var init_apply = __esm({
507
544
  "tools/fastapply/apply.ts"() {
508
545
  "use strict";
@@ -511,7 +548,18 @@ var init_apply = __esm({
511
548
  init_version();
512
549
  init_logger();
513
550
  DEFAULT_API_URL = "https://api.morphllm.com";
514
- DEFAULT_TIMEOUT = 9e4;
551
+ DEFAULT_TIMEOUT = 6e5;
552
+ FastApplyContextLengthError = class extends Error {
553
+ code = "context_length_exceeded";
554
+ completionId;
555
+ constructor(completionId) {
556
+ super(
557
+ "Fast Apply exhausted its context window before producing the complete file. Retry with a smaller input/update or use sparse anchors for unchanged code."
558
+ );
559
+ this.name = "FastApplyContextLengthError";
560
+ this.completionId = completionId;
561
+ }
562
+ };
515
563
  }
516
564
  });
517
565
 
@@ -520,6 +568,7 @@ var tools_exports = {};
520
568
  __export(tools_exports, {
521
569
  EDIT_FILE_SYSTEM_PROMPT: () => EDIT_FILE_SYSTEM_PROMPT,
522
570
  EDIT_FILE_TOOL_DESCRIPTION: () => EDIT_FILE_TOOL_DESCRIPTION,
571
+ FastApplyContextLengthError: () => FastApplyContextLengthError,
523
572
  anthropic: () => anthropic_exports,
524
573
  applyEdit: () => applyEdit,
525
574
  countChanges: () => countChanges,
@@ -543,12 +592,13 @@ init_version();
543
592
 
544
593
  // tools/fastapply/core.ts
545
594
  init_apply();
595
+ init_apply();
546
596
  var DEFAULT_CONFIG = {
547
597
  morphApiUrl: "https://api.morphllm.com",
548
598
  baseDir: process.cwd(),
549
599
  generateUdiff: true,
550
600
  autoWrite: true,
551
- timeout: 9e4,
601
+ timeout: 6e5,
552
602
  debug: false
553
603
  };
554
604
  async function executeEditFile(input, config = {}) {
@@ -601,12 +651,15 @@ async function executeEditFile(input, config = {}) {
601
651
  };
602
652
  } catch (error) {
603
653
  const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
654
+ const contextError = error instanceof FastApplyContextLengthError ? error : void 0;
604
655
  logger.error("FastApply", "execute_error", { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : void 0 });
605
656
  return {
606
657
  success: false,
607
658
  filepath: input.target_filepath,
608
659
  changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
609
- error: errorMessage
660
+ error: errorMessage,
661
+ errorCode: contextError?.code,
662
+ completionId: contextError?.completionId
610
663
  };
611
664
  }
612
665
  }
@@ -857,6 +910,7 @@ var vercel_default = editFileTool3;
857
910
  0 && (module.exports = {
858
911
  EDIT_FILE_SYSTEM_PROMPT,
859
912
  EDIT_FILE_TOOL_DESCRIPTION,
913
+ FastApplyContextLengthError,
860
914
  anthropic,
861
915
  applyEdit,
862
916
  countChanges,