@morphllm/morphsdk 0.2.200 → 0.2.201

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 (283) hide show
  1. package/dist/ai-sdk/index.cjs +0 -1
  2. package/dist/ai-sdk/index.js +0 -1
  3. package/dist/{chunk-HYRHI2UL.js → chunk-2PPYWRMZ.js} +0 -1
  4. package/dist/{chunk-IA5K2HTC.js → chunk-44OIEPIO.js} +1 -2
  5. package/dist/{chunk-FBRNUWEB.js → chunk-4OUGA3KS.js} +0 -1
  6. package/dist/{chunk-AKSXZBPT.js → chunk-5NSYDT36.js} +3 -4
  7. package/dist/{chunk-G2RSY56Q.js → chunk-6TZCVTW5.js} +0 -1
  8. package/dist/{chunk-F3NCFNUX.js → chunk-6WP7EA4F.js} +0 -1
  9. package/dist/{chunk-PJNL35DC.js → chunk-B376VMIH.js} +2 -3
  10. package/dist/{chunk-LN7GNFET.js → chunk-BZXOAC2R.js} +4 -5
  11. package/dist/{chunk-WTENYKJP.js → chunk-DBNSOYQ3.js} +2 -3
  12. package/dist/{chunk-MPL6BDR6.js → chunk-EQAWWVKV.js} +1 -2
  13. package/dist/{chunk-ZZ25FZG2.js → chunk-ETBRAKVV.js} +0 -1
  14. package/dist/chunk-FBOZIVVQ.js +0 -0
  15. package/dist/{chunk-B4X5RWLR.js → chunk-FVT4PU4I.js} +14 -15
  16. package/dist/{chunk-MRMBFJR2.js → chunk-HDP4QAZL.js} +0 -1
  17. package/dist/{chunk-TPP2UGQP.js → chunk-I26FQELI.js} +0 -1
  18. package/dist/{chunk-XTLPA7ZP.js → chunk-ILY5N5NJ.js} +2 -3
  19. package/dist/{chunk-UKAAT6KT.js → chunk-JBAY3PRV.js} +4 -5
  20. package/dist/chunk-LDM7RNNN.js +0 -0
  21. package/dist/{chunk-PD3EDFQD.js → chunk-LISSWRUD.js} +5 -6
  22. package/dist/{chunk-CCJK3HTG.js → chunk-M34E2AMK.js} +0 -1
  23. package/dist/{chunk-ZE64EWUV.js → chunk-M6AVXUM4.js} +2 -3
  24. package/dist/{chunk-QRXG5CAZ.js → chunk-MF56KEI4.js} +0 -1
  25. package/dist/{chunk-PZ5AY32C.js → chunk-MLKGABMK.js} +0 -1
  26. package/dist/{chunk-5TOJD2C5.js → chunk-NRG6QX3L.js} +0 -1
  27. package/dist/{chunk-3CCWSLQW.js → chunk-NWGRW4V7.js} +1 -2
  28. package/dist/{chunk-63VHBANJ.js → chunk-OPDWMD4Q.js} +0 -1
  29. package/dist/{chunk-TIMDDHYB.js → chunk-OVLUL5AC.js} +3 -4
  30. package/dist/{chunk-QTBFL4DG.js → chunk-P2KW2O5R.js} +2 -3
  31. package/dist/{chunk-63WE2C5R.js → chunk-PA3UTI4A.js} +0 -1
  32. package/dist/{chunk-UHIANNKC.js → chunk-RJXAXR7Q.js} +3 -4
  33. package/dist/{chunk-A4D2CIIT.js → chunk-RYVW7RUM.js} +1 -2
  34. package/dist/{chunk-Z57GJLCG.js → chunk-RZOJ4GSY.js} +4 -5
  35. package/dist/{chunk-Q65LL6UM.js → chunk-SU7AAS3O.js} +2 -3
  36. package/dist/{chunk-7I2A7GGJ.js → chunk-TS3OJ4LA.js} +1 -2
  37. package/dist/{chunk-SNYHVDE4.js → chunk-TZC3EOZS.js} +3 -4
  38. package/dist/{chunk-Q6QCHAMD.js → chunk-UAPK3AIJ.js} +0 -1
  39. package/dist/{chunk-UZ42MHTR.js → chunk-UZCXOOZO.js} +2 -4
  40. package/dist/{chunk-L6YOMTFU.js → chunk-VOXUA5ZH.js} +4 -5
  41. package/dist/{chunk-MLROWLS6.js → chunk-WBTXEJOC.js} +8 -9
  42. package/dist/{chunk-YPKNMYD4.js → chunk-ZSHVXDA2.js} +0 -1
  43. package/dist/client.cjs +2 -4
  44. package/dist/client.js +32 -33
  45. package/dist/core/client.cjs +2 -4
  46. package/dist/core/client.js +6 -7
  47. package/dist/core/error.cjs +2 -4
  48. package/dist/core/error.js +4 -5
  49. package/dist/core/index.cjs +2 -4
  50. package/dist/core/index.js +8 -9
  51. package/dist/core/resource.cjs +0 -1
  52. package/dist/core/resource.js +2 -3
  53. package/dist/edge.cjs +2 -4
  54. package/dist/edge.js +10 -11
  55. package/dist/index.cjs +2 -4
  56. package/dist/index.js +39 -40
  57. package/dist/modelrouter/core.cjs +2 -4
  58. package/dist/modelrouter/core.js +8 -9
  59. package/dist/modelrouter/index.cjs +2 -4
  60. package/dist/modelrouter/index.js +8 -9
  61. package/dist/modelrouter/types.cjs +0 -1
  62. package/dist/modelrouter/types.js +0 -1
  63. package/dist/subagents/anthropic.cjs +2 -4
  64. package/dist/subagents/anthropic.js +19 -20
  65. package/dist/subagents/index.cjs +0 -1
  66. package/dist/subagents/index.js +2 -3
  67. package/dist/subagents/prompts.cjs +0 -1
  68. package/dist/subagents/prompts.js +2 -3
  69. package/dist/subagents/types.cjs +0 -1
  70. package/dist/subagents/types.js +0 -1
  71. package/dist/subagents/vercel.cjs +2 -4
  72. package/dist/subagents/vercel.js +19 -20
  73. package/dist/tools/compact/core.cjs +2 -4
  74. package/dist/tools/compact/core.js +8 -9
  75. package/dist/tools/compact/index.cjs +2 -4
  76. package/dist/tools/compact/index.js +9 -10
  77. package/dist/tools/compact/types.cjs +0 -1
  78. package/dist/tools/compact/types.js +0 -1
  79. package/dist/tools/fastapply/anthropic.cjs +2 -4
  80. package/dist/tools/fastapply/anthropic.js +11 -12
  81. package/dist/tools/fastapply/apply.cjs +2 -4
  82. package/dist/tools/fastapply/apply.js +4 -5
  83. package/dist/tools/fastapply/core.cjs +2 -4
  84. package/dist/tools/fastapply/core.js +9 -10
  85. package/dist/tools/fastapply/index.cjs +2 -4
  86. package/dist/tools/fastapply/index.js +14 -15
  87. package/dist/tools/fastapply/openai.cjs +2 -4
  88. package/dist/tools/fastapply/openai.js +11 -12
  89. package/dist/tools/fastapply/prompts.cjs +0 -1
  90. package/dist/tools/fastapply/prompts.js +2 -3
  91. package/dist/tools/fastapply/types.cjs +0 -1
  92. package/dist/tools/fastapply/types.js +0 -1
  93. package/dist/tools/fastapply/vercel.cjs +2 -4
  94. package/dist/tools/fastapply/vercel.js +11 -12
  95. package/dist/tools/index.cjs +2 -4
  96. package/dist/tools/index.js +14 -15
  97. package/dist/tools/utils/resilience.cjs +2 -4
  98. package/dist/tools/utils/resilience.js +3 -4
  99. package/dist/tools/warp_grep/agent/config.cjs +0 -1
  100. package/dist/tools/warp_grep/agent/config.js +2 -3
  101. package/dist/tools/warp_grep/agent/formatter.cjs +0 -1
  102. package/dist/tools/warp_grep/agent/formatter.js +2 -3
  103. package/dist/tools/warp_grep/agent/parser.cjs +0 -1
  104. package/dist/tools/warp_grep/agent/parser.js +2 -3
  105. package/dist/tools/warp_grep/agent/runner.cjs +2 -4
  106. package/dist/tools/warp_grep/agent/runner.js +7 -8
  107. package/dist/tools/warp_grep/agent/types.cjs +0 -1
  108. package/dist/tools/warp_grep/agent/types.js +0 -1
  109. package/dist/tools/warp_grep/anthropic.cjs +2 -4
  110. package/dist/tools/warp_grep/anthropic.js +19 -20
  111. package/dist/tools/warp_grep/client.cjs +2 -4
  112. package/dist/tools/warp_grep/client.js +17 -18
  113. package/dist/tools/warp_grep/gemini.cjs +2 -4
  114. package/dist/tools/warp_grep/gemini.js +18 -19
  115. package/dist/tools/warp_grep/harness.cjs +0 -1
  116. package/dist/tools/warp_grep/harness.js +9 -10
  117. package/dist/tools/warp_grep/index.cjs +2 -4
  118. package/dist/tools/warp_grep/index.js +24 -25
  119. package/dist/tools/warp_grep/openai.cjs +2 -4
  120. package/dist/tools/warp_grep/openai.js +19 -20
  121. package/dist/tools/warp_grep/providers/code_storage_http.cjs +0 -1
  122. package/dist/tools/warp_grep/providers/code_storage_http.js +2 -3
  123. package/dist/tools/warp_grep/providers/local.cjs +0 -1
  124. package/dist/tools/warp_grep/providers/local.js +6 -7
  125. package/dist/tools/warp_grep/providers/remote.cjs +0 -1
  126. package/dist/tools/warp_grep/providers/remote.js +3 -4
  127. package/dist/tools/warp_grep/providers/types.cjs +0 -1
  128. package/dist/tools/warp_grep/providers/types.js +0 -1
  129. package/dist/tools/warp_grep/utils/files.cjs +0 -1
  130. package/dist/tools/warp_grep/utils/files.js +2 -3
  131. package/dist/tools/warp_grep/utils/github.cjs +0 -1
  132. package/dist/tools/warp_grep/utils/github.js +2 -3
  133. package/dist/tools/warp_grep/utils/paths.cjs +0 -1
  134. package/dist/tools/warp_grep/utils/paths.js +2 -3
  135. package/dist/tools/warp_grep/utils/ripgrep.cjs +0 -1
  136. package/dist/tools/warp_grep/utils/ripgrep.js +2 -3
  137. package/dist/tools/warp_grep/vercel.cjs +2 -4
  138. package/dist/tools/warp_grep/vercel.js +19 -20
  139. package/dist/version.cjs +2 -4
  140. package/dist/version.js +2 -3
  141. package/package.json +2 -3
  142. package/dist/ai-sdk/index.cjs.map +0 -1
  143. package/dist/ai-sdk/index.js.map +0 -1
  144. package/dist/chunk-3CCWSLQW.js.map +0 -1
  145. package/dist/chunk-5TOJD2C5.js.map +0 -1
  146. package/dist/chunk-63VHBANJ.js.map +0 -1
  147. package/dist/chunk-63WE2C5R.js.map +0 -1
  148. package/dist/chunk-7I2A7GGJ.js.map +0 -1
  149. package/dist/chunk-A4D2CIIT.js.map +0 -1
  150. package/dist/chunk-AKSXZBPT.js.map +0 -1
  151. package/dist/chunk-B4X5RWLR.js.map +0 -1
  152. package/dist/chunk-CCJK3HTG.js.map +0 -1
  153. package/dist/chunk-F3NCFNUX.js.map +0 -1
  154. package/dist/chunk-FBRNUWEB.js.map +0 -1
  155. package/dist/chunk-G2RSY56Q.js.map +0 -1
  156. package/dist/chunk-HYRHI2UL.js.map +0 -1
  157. package/dist/chunk-IA5K2HTC.js.map +0 -1
  158. package/dist/chunk-L6YOMTFU.js.map +0 -1
  159. package/dist/chunk-LN7GNFET.js.map +0 -1
  160. package/dist/chunk-MLROWLS6.js.map +0 -1
  161. package/dist/chunk-MPL6BDR6.js.map +0 -1
  162. package/dist/chunk-MRMBFJR2.js.map +0 -1
  163. package/dist/chunk-PD3EDFQD.js.map +0 -1
  164. package/dist/chunk-PJNL35DC.js.map +0 -1
  165. package/dist/chunk-PZ5AY32C.js.map +0 -1
  166. package/dist/chunk-Q65LL6UM.js.map +0 -1
  167. package/dist/chunk-Q6QCHAMD.js.map +0 -1
  168. package/dist/chunk-QRXG5CAZ.js.map +0 -1
  169. package/dist/chunk-QTBFL4DG.js.map +0 -1
  170. package/dist/chunk-SNYHVDE4.js.map +0 -1
  171. package/dist/chunk-TIMDDHYB.js.map +0 -1
  172. package/dist/chunk-TPP2UGQP.js.map +0 -1
  173. package/dist/chunk-UHIANNKC.js.map +0 -1
  174. package/dist/chunk-UKAAT6KT.js.map +0 -1
  175. package/dist/chunk-UZ42MHTR.js.map +0 -1
  176. package/dist/chunk-VZ7BOH2K.js +0 -1
  177. package/dist/chunk-VZ7BOH2K.js.map +0 -1
  178. package/dist/chunk-WTENYKJP.js.map +0 -1
  179. package/dist/chunk-X2K57BH6.js +0 -1
  180. package/dist/chunk-X2K57BH6.js.map +0 -1
  181. package/dist/chunk-XTLPA7ZP.js.map +0 -1
  182. package/dist/chunk-YPKNMYD4.js.map +0 -1
  183. package/dist/chunk-Z57GJLCG.js.map +0 -1
  184. package/dist/chunk-ZE64EWUV.js.map +0 -1
  185. package/dist/chunk-ZZ25FZG2.js.map +0 -1
  186. package/dist/client.cjs.map +0 -1
  187. package/dist/client.js.map +0 -1
  188. package/dist/core/client.cjs.map +0 -1
  189. package/dist/core/client.js.map +0 -1
  190. package/dist/core/error.cjs.map +0 -1
  191. package/dist/core/error.js.map +0 -1
  192. package/dist/core/index.cjs.map +0 -1
  193. package/dist/core/index.js.map +0 -1
  194. package/dist/core/resource.cjs.map +0 -1
  195. package/dist/core/resource.js.map +0 -1
  196. package/dist/edge.cjs.map +0 -1
  197. package/dist/edge.js.map +0 -1
  198. package/dist/index.cjs.map +0 -1
  199. package/dist/index.js.map +0 -1
  200. package/dist/modelrouter/core.cjs.map +0 -1
  201. package/dist/modelrouter/core.js.map +0 -1
  202. package/dist/modelrouter/index.cjs.map +0 -1
  203. package/dist/modelrouter/index.js.map +0 -1
  204. package/dist/modelrouter/types.cjs.map +0 -1
  205. package/dist/modelrouter/types.js.map +0 -1
  206. package/dist/subagents/anthropic.cjs.map +0 -1
  207. package/dist/subagents/anthropic.js.map +0 -1
  208. package/dist/subagents/index.cjs.map +0 -1
  209. package/dist/subagents/index.js.map +0 -1
  210. package/dist/subagents/prompts.cjs.map +0 -1
  211. package/dist/subagents/prompts.js.map +0 -1
  212. package/dist/subagents/types.cjs.map +0 -1
  213. package/dist/subagents/types.js.map +0 -1
  214. package/dist/subagents/vercel.cjs.map +0 -1
  215. package/dist/subagents/vercel.js.map +0 -1
  216. package/dist/tools/compact/core.cjs.map +0 -1
  217. package/dist/tools/compact/core.js.map +0 -1
  218. package/dist/tools/compact/index.cjs.map +0 -1
  219. package/dist/tools/compact/index.js.map +0 -1
  220. package/dist/tools/compact/types.cjs.map +0 -1
  221. package/dist/tools/compact/types.js.map +0 -1
  222. package/dist/tools/fastapply/anthropic.cjs.map +0 -1
  223. package/dist/tools/fastapply/anthropic.js.map +0 -1
  224. package/dist/tools/fastapply/apply.cjs.map +0 -1
  225. package/dist/tools/fastapply/apply.js.map +0 -1
  226. package/dist/tools/fastapply/core.cjs.map +0 -1
  227. package/dist/tools/fastapply/core.js.map +0 -1
  228. package/dist/tools/fastapply/index.cjs.map +0 -1
  229. package/dist/tools/fastapply/index.js.map +0 -1
  230. package/dist/tools/fastapply/openai.cjs.map +0 -1
  231. package/dist/tools/fastapply/openai.js.map +0 -1
  232. package/dist/tools/fastapply/prompts.cjs.map +0 -1
  233. package/dist/tools/fastapply/prompts.js.map +0 -1
  234. package/dist/tools/fastapply/types.cjs.map +0 -1
  235. package/dist/tools/fastapply/types.js.map +0 -1
  236. package/dist/tools/fastapply/vercel.cjs.map +0 -1
  237. package/dist/tools/fastapply/vercel.js.map +0 -1
  238. package/dist/tools/index.cjs.map +0 -1
  239. package/dist/tools/index.js.map +0 -1
  240. package/dist/tools/utils/resilience.cjs.map +0 -1
  241. package/dist/tools/utils/resilience.js.map +0 -1
  242. package/dist/tools/warp_grep/agent/config.cjs.map +0 -1
  243. package/dist/tools/warp_grep/agent/config.js.map +0 -1
  244. package/dist/tools/warp_grep/agent/formatter.cjs.map +0 -1
  245. package/dist/tools/warp_grep/agent/formatter.js.map +0 -1
  246. package/dist/tools/warp_grep/agent/parser.cjs.map +0 -1
  247. package/dist/tools/warp_grep/agent/parser.js.map +0 -1
  248. package/dist/tools/warp_grep/agent/runner.cjs.map +0 -1
  249. package/dist/tools/warp_grep/agent/runner.js.map +0 -1
  250. package/dist/tools/warp_grep/agent/types.cjs.map +0 -1
  251. package/dist/tools/warp_grep/agent/types.js.map +0 -1
  252. package/dist/tools/warp_grep/anthropic.cjs.map +0 -1
  253. package/dist/tools/warp_grep/anthropic.js.map +0 -1
  254. package/dist/tools/warp_grep/client.cjs.map +0 -1
  255. package/dist/tools/warp_grep/client.js.map +0 -1
  256. package/dist/tools/warp_grep/gemini.cjs.map +0 -1
  257. package/dist/tools/warp_grep/gemini.js.map +0 -1
  258. package/dist/tools/warp_grep/harness.cjs.map +0 -1
  259. package/dist/tools/warp_grep/harness.js.map +0 -1
  260. package/dist/tools/warp_grep/index.cjs.map +0 -1
  261. package/dist/tools/warp_grep/index.js.map +0 -1
  262. package/dist/tools/warp_grep/openai.cjs.map +0 -1
  263. package/dist/tools/warp_grep/openai.js.map +0 -1
  264. package/dist/tools/warp_grep/providers/code_storage_http.cjs.map +0 -1
  265. package/dist/tools/warp_grep/providers/code_storage_http.js.map +0 -1
  266. package/dist/tools/warp_grep/providers/local.cjs.map +0 -1
  267. package/dist/tools/warp_grep/providers/local.js.map +0 -1
  268. package/dist/tools/warp_grep/providers/remote.cjs.map +0 -1
  269. package/dist/tools/warp_grep/providers/remote.js.map +0 -1
  270. package/dist/tools/warp_grep/providers/types.cjs.map +0 -1
  271. package/dist/tools/warp_grep/providers/types.js.map +0 -1
  272. package/dist/tools/warp_grep/utils/files.cjs.map +0 -1
  273. package/dist/tools/warp_grep/utils/files.js.map +0 -1
  274. package/dist/tools/warp_grep/utils/github.cjs.map +0 -1
  275. package/dist/tools/warp_grep/utils/github.js.map +0 -1
  276. package/dist/tools/warp_grep/utils/paths.cjs.map +0 -1
  277. package/dist/tools/warp_grep/utils/paths.js.map +0 -1
  278. package/dist/tools/warp_grep/utils/ripgrep.cjs.map +0 -1
  279. package/dist/tools/warp_grep/utils/ripgrep.js.map +0 -1
  280. package/dist/tools/warp_grep/vercel.cjs.map +0 -1
  281. package/dist/tools/warp_grep/vercel.js.map +0 -1
  282. package/dist/version.cjs.map +0 -1
  283. package/dist/version.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../logger.ts","../../package.json","../../version.ts","../../tools/fastapply/anchors.ts","../../tools/fastapply/apply.ts","../../tools/index.ts","../../tools/fastapply/core.ts","../../tools/utils/resilience.ts","../../core/client.ts","../../tools/fastapply/prompts.ts","../../tools/fastapply/anthropic.ts","../../tools/fastapply/openai.ts","../../tools/fastapply/vercel.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.200\",\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 \"./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 \"./modelrouter\": {\n \"types\": \"./dist/modelrouter/index.d.ts\",\n \"import\": \"./dist/modelrouter/index.js\",\n \"require\": \"./dist/modelrouter/index.cjs\"\n },\n \"./tools/compact\": {\n \"types\": \"./dist/tools/compact/index.d.ts\",\n \"import\": \"./dist/tools/compact/index.js\",\n \"require\": \"./dist/tools/compact/index.cjs\"\n },\n \"./subagents\": {\n \"types\": \"./dist/subagents/index.d.ts\",\n \"import\": \"./dist/subagents/index.js\",\n \"require\": \"./dist/subagents/index.cjs\"\n },\n \"./subagents/vercel\": {\n \"types\": \"./dist/subagents/vercel.d.ts\",\n \"import\": \"./dist/subagents/vercel.js\",\n \"require\": \"./dist/subagents/vercel.cjs\"\n },\n \"./subagents/anthropic\": {\n \"types\": \"./dist/subagents/anthropic.d.ts\",\n \"import\": \"./dist/subagents/anthropic.js\",\n \"require\": \"./dist/subagents/anthropic.cjs\"\n },\n \"./ai-sdk\": {\n \"types\": \"./dist/ai-sdk/index.d.ts\",\n \"import\": \"./dist/ai-sdk/index.js\",\n \"require\": \"./dist/ai-sdk/index.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/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve && tsup ai-sdk/index.ts --format esm,cjs --sourcemap --dts --no-clean --out-dir dist/ai-sdk\",\n \"prepare\": \"npm run build\",\n \"typecheck\": \"tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json\",\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: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 \"@vscode/ripgrep\": \"^1.17.0\",\n \"ai\": \">=5.0.0\",\n \"diff\": \"^7.0.0\",\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 \"@ai-sdk/openai-compatible\": \">=2.0.74 <4\",\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","const DEFAULT_MIN_ANCHOR_LINE_LENGTH = 24;\n\nexport const DEFAULT_ANCHOR_COMPACTION_THRESHOLD = 128 * 1024;\n\nexport interface AnchorCompactionPlan {\n code: string;\n instructionSuffix: string;\n anchorCount: number;\n uniqueAnchorCount: number;\n hasStructuralValidation: boolean;\n expand: (content: string) => string;\n}\n\nexport class FastApplyAnchorIntegrityError extends Error {\n readonly code = 'anchor_integrity_failed';\n readonly completionId?: string;\n\n constructor(completionId?: string) {\n super(\n 'Fast Apply failed large-file anchor integrity checks. The partial result was discarded safely.'\n );\n this.name = 'FastApplyAnchorIntegrityError';\n this.completionId = completionId;\n }\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction findNamespace(values: string[]): number {\n for (let namespace = 0; namespace < Number.MAX_SAFE_INTEGER; namespace++) {\n const prefix = `⟪M${namespace}:`;\n if (values.every((value) => !value.includes(prefix))) {\n return namespace;\n }\n }\n\n throw new Error('Unable to allocate a Fast Apply anchor namespace');\n}\n\ninterface SourceUnit {\n value: string;\n label?: string;\n anchorable: boolean;\n}\n\nfunction htmlLabel(token: string): string {\n if (!token.startsWith('<')) return 'text';\n const match = token.match(/^<\\s*(!doctype|\\/?[a-zA-Z][\\w:-]*)/);\n return (match?.[1] ?? 'tag').toLowerCase();\n}\n\nfunction htmlTokenUnits(value: string, visibleTags = new Set<string>()): SourceUnit[] {\n return (value.match(/<[^>]*>|[^<]+/g) ?? [value]).map((token) => ({\n value: token,\n label: htmlLabel(token),\n anchorable: token.length >= DEFAULT_MIN_ANCHOR_LINE_LENGTH\n && !visibleTags.has(htmlLabel(token).replace(/^\\//, '')),\n }));\n}\n\nfunction sourceUnits(originalCode: string, editContext: string[]): SourceUnit[] {\n const trimmed = originalCode.trimStart().toLowerCase();\n const looksLikeHtml = (trimmed.startsWith('<!doctype') || trimmed.startsWith('<html'))\n && /<\\/html\\s*>/i.test(originalCode);\n\n if (looksLikeHtml) {\n const contextWords = new Set(\n editContext.join(' ').toLowerCase().match(/[a-z][\\w:-]*/g) ?? []\n );\n return htmlTokenUnits(originalCode, contextWords);\n }\n\n const parts = originalCode.split(/(\\r\\n|\\n|\\r)/);\n const units: SourceUnit[] = [];\n for (let index = 0; index < parts.length; index += 2) {\n const line = parts[index] ?? '';\n const lineEnding = parts[index + 1] ?? '';\n units.push({\n value: line,\n label: 'line',\n anchorable: line.length >= DEFAULT_MIN_ANCHOR_LINE_LENGTH,\n });\n if (lineEnding) {\n units.push({ value: lineEnding, anchorable: false });\n }\n }\n return units;\n}\n\nfunction copyCount(value: string): number | undefined {\n const words: Record<string, number> = {\n one: 1,\n two: 2,\n three: 3,\n four: 4,\n five: 5,\n six: 6,\n seven: 7,\n eight: 8,\n nine: 9,\n ten: 10,\n };\n return /^\\d+$/.test(value) ? Number(value) : words[value.toLowerCase()];\n}\n\nfunction structuralExpectation(originalCode: string, editContext: string[]) {\n const context = editContext.join(' ');\n const match = context.match(\n /(?:for every|for each|each)\\s+([a-z][\\w:-]*)[\\s\\S]{0,120}?add\\s+(one|two|three|four|five|six|seven|eight|nine|ten|\\d+)\\s+identical cop(?:y|ies)/i\n );\n if (!match) return undefined;\n\n const tag = match[1]!.toLowerCase();\n const addedCopies = copyCount(match[2]!);\n if (addedCopies === undefined) return undefined;\n\n const tagPattern = new RegExp(`<${escapeRegExp(tag)}(?:\\\\s|>)`, 'gi');\n const originalCount = originalCode.match(tagPattern)?.length ?? 0;\n if (originalCount === 0) return undefined;\n\n return { tag, expectedCount: originalCount * (addedCopies + 1) };\n}\n\n/**\n * Replace long source fragments with lossless placeholders. Definitions are sent once,\n * while the model can emit a small skeleton containing repeated/moved placeholders.\n */\nexport function createAnchorCompactionPlan(\n originalCode: string,\n collisionValues: string[] = []\n): AnchorCompactionPlan | undefined {\n const namespace = findNamespace([originalCode, ...collisionValues]);\n const expectation = structuralExpectation(originalCode, collisionValues);\n const markerPrefix = `⟪M${namespace}:`;\n const definitions = new Map<string, number>();\n const values: string[] = [];\n const markers: string[] = [];\n let anchorCount = 0;\n let skeleton = '';\n\n for (const unit of sourceUnits(originalCode, collisionValues)) {\n if (!unit.anchorable) {\n skeleton += unit.value;\n continue;\n }\n\n let id = definitions.get(unit.value);\n if (id === undefined) {\n id = values.length;\n definitions.set(unit.value, id);\n values.push(unit.value);\n markers.push(`${markerPrefix}${id}:${unit.label ?? 'unit'}⟫`);\n }\n\n skeleton += markers[id];\n anchorCount++;\n }\n\n if (anchorCount === 0 || skeleton.length >= originalCode.length) {\n return undefined;\n }\n\n const definitionsBegin = `⟪MORPH_DEFINITIONS_BEGIN_${namespace}⟫`;\n const definitionsEnd = `⟪MORPH_DEFINITIONS_END_${namespace}⟫`;\n const codeBegin = `⟪MORPH_CODE_BEGIN_${namespace}⟫`;\n const serializedDefinitions = values\n .map((value, id) => `${markers[id]}=${JSON.stringify(value)}`)\n .join('\\n');\n\n const code = [\n definitionsBegin,\n serializedDefinitions,\n definitionsEnd,\n codeBegin,\n skeleton,\n ].join('\\n');\n\n const instructionSuffix = `\n\nLARGE-FILE ANCHOR PROTOCOL:\nThe <code> block starts with an exact anchor definition table, then ${codeBegin}, then the source skeleton.\nEach ${markerPrefix}N:kind⟫ placeholder represents the exact source fragment in its matching JSON-string definition. The kind suffix describes its HTML tag, text, or source line.\nReturn only the updated source skeleton after ${codeBegin}; never return the definition table or protocol delimiters.\nCopy a placeholder exactly when its source fragment is unchanged. You may repeat, reorder, or remove placeholders when the requested edit requires it.\nTo modify an anchored fragment, output the modified source instead of its placeholder.\nDo not invent or alter placeholder IDs.`;\n\n const markerPattern = new RegExp(`${escapeRegExp(markerPrefix)}(\\\\d+):[^⟫]+⟫`, 'g');\n\n return {\n code,\n instructionSuffix,\n anchorCount,\n uniqueAnchorCount: values.length,\n hasStructuralValidation: expectation !== undefined,\n expand(content: string): string {\n const codeBeginIndex = content.lastIndexOf(codeBegin);\n const skeletonContent = codeBeginIndex >= 0\n ? content.slice(codeBeginIndex + codeBegin.length).replace(/^\\r?\\n/, '')\n : content;\n\n const expanded = skeletonContent.replace(markerPattern, (marker, idText: string) => {\n const id = Number(idText);\n const value = values[id];\n return value === undefined || markers[id] !== marker ? marker : value;\n });\n\n if (expanded.includes(markerPrefix)) {\n throw new FastApplyAnchorIntegrityError();\n }\n\n if (expectation) {\n const tagPattern = new RegExp(`<${escapeRegExp(expectation.tag)}(?:\\\\s|>)`, 'gi');\n const actualCount = expanded.match(tagPattern)?.length ?? 0;\n if (actualCount !== expectation.expectedCount) {\n throw new FastApplyAnchorIntegrityError();\n }\n }\n\n return expanded;\n },\n };\n}\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 {\n createAnchorCompactionPlan,\n DEFAULT_ANCHOR_COMPACTION_THRESHOLD,\n FastApplyAnchorIntegrityError,\n} from './anchors.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\nexport { FastApplyAnchorIntegrityError } from './anchors.js';\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 const anchorThreshold = config.anchorCompactionThreshold\n ?? DEFAULT_ANCHOR_COMPACTION_THRESHOLD;\n const anchorPlan = config.anchorCompaction !== false\n && originalCode.length >= anchorThreshold\n ? createAnchorCompactionPlan(originalCode, [codeEdit, instructions])\n : undefined;\n const requestCode = anchorPlan?.code ?? originalCode;\n const requestInstructions = anchorPlan\n ? instructions + anchorPlan.instructionSuffix\n : instructions;\n\n // Format message with XML tags as per Morph Fast Apply spec\n const message = `<instruction>${requestInstructions}</instruction>\\n<code>${requestCode}</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 request_code_len: requestCode.length,\n code_edit_len: codeEdit.length,\n anchor_count: anchorPlan?.anchorCount ?? 0,\n unique_anchor_count: anchorPlan?.uniqueAnchorCount ?? 0,\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: {\n 'X-Morph-SDK-Version': SDK_VERSION,\n ...(anchorPlan ? { 'X-Morph-Apply-Context': 'extralong' } : {}),\n },\n });\n\n try {\n const maxAttempts = anchorPlan?.hasStructuralValidation ? 2 : 1;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\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 let content = completion.content;\n if (!content) {\n throw new Error('Morph API returned empty response');\n }\n\n if (anchorPlan) {\n try {\n content = anchorPlan.expand(content);\n } catch (error) {\n if (error instanceof FastApplyAnchorIntegrityError) {\n if (attempt < maxAttempts) {\n logger.warn('FastApply', 'anchor_validation_retry', {\n attempt,\n completion_id: completion.completionId,\n });\n continue;\n }\n throw new FastApplyAnchorIntegrityError(completion.completionId);\n }\n throw error;\n }\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 }\n\n throw new FastApplyAnchorIntegrityError();\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 structuredError = error instanceof FastApplyContextLengthError\n || error instanceof FastApplyAnchorIntegrityError\n ? error\n : undefined;\n\n return {\n success: false,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n errorCode: structuredError?.code,\n completionId: structuredError?.completionId,\n };\n }\n}\n","/**\n * Morph SDK Tools\n * \n * @example\n * ```ts\n * // Import framework-specific tools\n * import { editFileTool } from 'morphsdk/tools/anthropic';\n * import { editFileTool } from 'morphsdk/tools/openai';\n * import { editFileTool } from 'morphsdk/tools/vercel';\n * ```\n */\n\n// Re-export fastapply tools\nexport * from './fastapply/index.js';\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 {\n FastApplyAnchorIntegrityError,\n FastApplyContextLengthError,\n} from './apply.js';\n\n// Re-export edge-compatible functions\nexport { applyEdit, generateUdiff, countChanges, callMorphAPI } from './apply.js';\nexport { FastApplyAnchorIntegrityError, 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 anchorCompaction: true,\n anchorCompactionThreshold: 128 * 1024,\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 structuredError = error instanceof FastApplyContextLengthError\n || error instanceof FastApplyAnchorIntegrityError\n ? error\n : 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: structuredError?.code,\n completionId: structuredError?.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 * 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_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 /** 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 /** 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 /** 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.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 (!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","/**\n * Anthropic SDK adapter for edit_file tool\n */\n\nimport type { Tool } from '@anthropic-ai/sdk/resources/messages';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * Anthropic-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import Anthropic from '@anthropic-ai/sdk';\n * import { editFileTool } from 'morphsdk/tools/anthropic';\n * \n * const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n * \n * const response = await client.messages.create({\n * model: \"claude-sonnet-4-5-20250929\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: Tool = {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n input_schema: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instruction: {\n type: 'string',\n description: 'A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit.',\n },\n code_edit: {\n type: 'string',\n description: 'Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.',\n },\n },\n required: ['target_filepath', 'instruction', 'code_edit'],\n },\n};\n\n/**\n * Format the result for passing back to Claude\n * \n * @param result - The edit result\n * @returns Formatted string for tool_result\n */\nexport function formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;\n}\n\n/**\n * Create a custom edit_file tool with configuration\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * morphApiKey: 'sk-...',\n * description: 'Custom tool description for your use case'\n * });\n * \n * // Use as Anthropic tool\n * const response = await client.messages.create({\n * tools: [tool], // tool itself is the Tool definition\n * ...\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolUseBlock.input);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: Tool = {\n ...editFileTool,\n ...(config.description && { description: config.description }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput): Promise<EditFileResult> => {\n return executeEditFile(input, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return EDIT_FILE_SYSTEM_PROMPT;\n },\n });\n}\n\n/**\n * Execute the edit_file tool with raw input\n * \n * @param input - Tool input from Claude's tool_use\n * @param config - Configuration for Fast Apply\n * @returns Tool result to send back to Claude\n */\nexport async function execute(\n input: EditFileInput,\n config?: EditFileConfig\n): Promise<EditFileResult> {\n return executeEditFile(input, config);\n}\n\n/**\n * Get the system prompt for the edit_file tool\n * \n * @returns System prompt string\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n","/**\n * OpenAI SDK adapter for edit_file tool\n */\n\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions';\nimport { executeEditFile } from './core.js';\nimport { EDIT_FILE_TOOL_DESCRIPTION, EDIT_FILE_SYSTEM_PROMPT } from './prompts.js';\nimport type { EditFileInput, EditFileResult, EditFileConfig } from './types.js';\n\n/**\n * OpenAI-native tool definition for edit_file\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { editFileTool } from 'morphsdk/tools/openai';\n * \n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * \n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * tools: [editFileTool],\n * messages: [{ role: \"user\", content: \"Fix the bug in app.ts\" }]\n * });\n * ```\n */\nexport const editFileTool: ChatCompletionTool = {\n type: 'function',\n function: {\n name: 'edit_file',\n description: EDIT_FILE_TOOL_DESCRIPTION,\n parameters: {\n type: 'object',\n properties: {\n target_filepath: {\n type: 'string',\n description: 'The path of the target file to modify',\n },\n instruction: {\n type: 'string',\n description: 'A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit.',\n },\n code_edit: {\n type: 'string',\n description: 'Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.',\n },\n },\n required: ['target_filepath', 'instruction', 'code_edit'],\n },\n },\n};\n\n/**\n * Execute an edit_file tool call\n * \n * @param input - The tool input from GPT (parsed from tool_calls)\n * @param config - Optional configuration\n * @returns The result of the edit operation\n * \n * @example\n * ```ts\n * const args = JSON.parse(toolCall.function.arguments);\n * const result = await execute(args);\n * console.log('Changes applied:', result.udiff);\n * ```\n */\nexport async function execute(\n input: EditFileInput,\n config?: EditFileConfig\n): Promise<EditFileResult> {\n return executeEditFile(input, config);\n}\n\n/**\n * Get the system prompt for edit_file usage\n * \n * Add this to your system message to guide GPT on using edit_file properly.\n * \n * @example\n * ```ts\n * const response = await client.chat.completions.create({\n * model: \"gpt-4o\",\n * messages: [\n * { role: \"system\", content: getSystemPrompt() },\n * { role: \"user\", content: \"Fix bugs\" }\n * ],\n * tools: [editFileTool]\n * });\n * ```\n */\nexport function getSystemPrompt(): string {\n return EDIT_FILE_SYSTEM_PROMPT;\n}\n\n/**\n * Format the result for passing back to GPT\n * \n * @param result - The edit result\n * @returns Formatted string for tool message\n */\nexport function formatResult(result: EditFileResult): string {\n if (!result.success) {\n return `Error editing file: ${result.error}`;\n }\n \n const { changes } = result;\n return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;\n}\n\n/**\n * Create a custom edit_file tool with configuration and methods\n * \n * @param config - Configuration options\n * @returns Tool definition with execute and formatResult methods\n * \n * @example\n * ```ts\n * import OpenAI from 'openai';\n * import { createEditFileTool } from 'morphsdk/tools/fastapply/openai';\n * \n * const tool = createEditFileTool({\n * baseDir: './src',\n * generateUdiff: true,\n * description: 'Custom tool description for your use case'\n * });\n * \n * const client = new OpenAI();\n * \n * const response = await client.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [tool], // tool itself is the ChatCompletionTool\n * messages: [{ role: 'user', content: 'Fix bug in app.ts' }]\n * });\n * \n * // Execute and format\n * const result = await tool.execute(toolCallArgs);\n * const formatted = tool.formatResult(result);\n * ```\n */\nexport function createEditFileTool(config: EditFileConfig = {}) {\n const toolDef: ChatCompletionTool = {\n ...editFileTool,\n ...(config.description && {\n function: {\n ...editFileTool.function,\n description: config.description,\n },\n }),\n };\n \n return Object.assign({}, toolDef, {\n execute: async (input: EditFileInput | string): Promise<EditFileResult> => {\n const parsedInput = typeof input === 'string' ? JSON.parse(input) : input;\n return execute(parsedInput, config);\n },\n formatResult: (result: EditFileResult): string => {\n return formatResult(result);\n },\n getSystemPrompt: (): string => {\n return getSystemPrompt();\n },\n });\n}\n\n// Default export for convenience\nexport default editFileTool;\n\n","/**\n * 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"],"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,iBAAiB;AACxE,YAAI,GAAG;AAGL,eAAK,QAAQ,OAAO,IAAI,EACrB,KAAK,CAAC,OAAO;AACZ,iBAAK,aAAa,GAAG,kBAAkB,GAAG,EAAE,OAAO,IAAI,CAAC;AAAA,UAC1D,CAAC,EACA,MAAM,MAAM;AAAA,UAEb,CAAC;AAAA,QACL,OAAO;AACL,eAAK,QAAQ,QAAQ,QAAQ;AAAA,QAC/B;AAAA,MACF;AAAA,MAEA,MAAM,WAAmB,KAAa,MAAgC;AAAE,aAAK,KAAK,SAAS,WAAW,KAAK,IAAI;AAAA,MAAG;AAAA,MAClH,KAAK,WAAmB,KAAa,MAAgC;AAAE,aAAK,KAAK,QAAQ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AAa,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,iBAAQF;","names":["OpenAI","callMorphAPI","generateUdiff","countChanges","createEditFileTool","editFileTool","execute","formatResult","getSystemPrompt","editFileTool","execute","getSystemPrompt","formatResult","createEditFileTool","createEditFileTool","editFileTool","getSystemPrompt","editFileTool","getSystemPrompt","createEditFileTool"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../tools/utils/resilience.ts","../../../package.json","../../../version.ts"],"sourcesContent":["/**\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 \"name\": \"@morphllm/morphsdk\",\n \"version\": \"0.2.200\",\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 \"./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 \"./modelrouter\": {\n \"types\": \"./dist/modelrouter/index.d.ts\",\n \"import\": \"./dist/modelrouter/index.js\",\n \"require\": \"./dist/modelrouter/index.cjs\"\n },\n \"./tools/compact\": {\n \"types\": \"./dist/tools/compact/index.d.ts\",\n \"import\": \"./dist/tools/compact/index.js\",\n \"require\": \"./dist/tools/compact/index.cjs\"\n },\n \"./subagents\": {\n \"types\": \"./dist/subagents/index.d.ts\",\n \"import\": \"./dist/subagents/index.js\",\n \"require\": \"./dist/subagents/index.cjs\"\n },\n \"./subagents/vercel\": {\n \"types\": \"./dist/subagents/vercel.d.ts\",\n \"import\": \"./dist/subagents/vercel.js\",\n \"require\": \"./dist/subagents/vercel.cjs\"\n },\n \"./subagents/anthropic\": {\n \"types\": \"./dist/subagents/anthropic.d.ts\",\n \"import\": \"./dist/subagents/anthropic.js\",\n \"require\": \"./dist/subagents/anthropic.cjs\"\n },\n \"./ai-sdk\": {\n \"types\": \"./dist/ai-sdk/index.d.ts\",\n \"import\": \"./dist/ai-sdk/index.js\",\n \"require\": \"./dist/ai-sdk/index.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/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve && tsup ai-sdk/index.ts --format esm,cjs --sourcemap --dts --no-clean --out-dir dist/ai-sdk\",\n \"prepare\": \"npm run build\",\n \"typecheck\": \"tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json\",\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: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 \"@vscode/ripgrep\": \"^1.17.0\",\n \"ai\": \">=5.0.0\",\n \"diff\": \"^7.0.0\",\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 \"@ai-sdk/openai-compatible\": \">=2.0.74 <4\",\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,MAAQ;AAAA,EACR,MAAQ;AAAA,EACR,QAAU;AAAA,EACV,OAAS;AAAA,EACT,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SAAW;AAAA,IACb;AAAA,IACA,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;AAJN;AACA;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../tools/warp_grep/agent/config.ts"],"sourcesContent":["// Parse timeout from env, defaulting to 30 seconds\nconst parseEnvTimeout = (envValue: string | undefined, defaultMs: number): number => {\n if (!envValue) return defaultMs;\n const parsed = parseInt(envValue, 10);\n return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;\n};\n\nexport const AGENT_CONFIG = {\n MAX_TURNS: 6,\n /** Default timeout for model calls. Can be overridden via MORPH_WARP_GREP_TIMEOUT env var (in ms) */\n TIMEOUT_MS: parseEnvTimeout(process.env.MORPH_WARP_GREP_TIMEOUT, 60_000),\n MAX_CONTEXT_CHARS: 321_600,\n MAX_OUTPUT_LINES: 200,\n MAX_LIST_RESULTS: 500,\n MAX_READ_LINES: 800,\n MAX_LIST_DEPTH: 3,\n LIST_TIMEOUT_MS: 2_000,\n};\n\n/**\n * Comprehensive exclusion list for directories and files\n * These patterns are used with ripgrep's -g flag\n */\nconst BUILTIN_EXCLUDES = [\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n \n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'packages', 'Pods', '.bundle',\n \n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs', '*.egg-info',\n \n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n \n // Cache directories\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n \n // IDE/Editor\n '.idea', '.vscode', '.vs',\n \n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n \n // Temporary\n 'tmp', 'temp', '.tmp', '.temp',\n \n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n \n // Binary/minified\n '*.min.js', '*.min.css', '*.bundle.js',\n '*.wasm', '*.so', '*.dll', '*.pyc',\n '*.map', '*.js.map',\n \n // Hidden directories catch-all\n '.*',\n];\n\nexport const DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || '')\n .split(',')\n .map(s => s.trim())\n .filter(Boolean)\n .concat(BUILTIN_EXCLUDES);\n\nexport const DEFAULT_MODEL = 'morph-warp-grep-v2.1';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,IAAM,kBAAkB,CAAC,UAA8B,cAA8B;AACnF,MAAI,CAAC,SAAU,QAAO;AACtB,QAAM,SAAS,SAAS,UAAU,EAAE;AACpC,SAAO,MAAM,MAAM,KAAK,UAAU,IAAI,YAAY;AACpD;AAEO,IAAM,eAAe;AAAA,EAC1B,WAAW;AAAA;AAAA,EAEX,YAAY,gBAAgB,QAAQ,IAAI,yBAAyB,GAAM;AAAA,EACvE,mBAAmB;AAAA,EACnB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,iBAAiB;AACnB;AAMA,IAAM,mBAAmB;AAAA;AAAA,EAEvB;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAO;AAAA;AAAA,EAGvB;AAAA,EAAgB;AAAA,EAAoB;AAAA,EAAS;AAAA,EAC7C;AAAA,EAAU;AAAA,EAAY;AAAA,EAAQ;AAAA;AAAA,EAG9B;AAAA,EAAe;AAAA,EAAiB;AAAA,EAAe;AAAA,EAC/C;AAAA,EAAS;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAS;AAAA;AAAA,EAG1C;AAAA,EAAQ;AAAA,EAAS;AAAA,EAAO;AAAA,EAAU;AAAA,EAAU;AAAA,EAC5C;AAAA,EAAS;AAAA,EAAS;AAAA,EAAW;AAAA,EAAW;AAAA;AAAA,EAGxC;AAAA,EAAU;AAAA,EAAiB;AAAA,EAAU;AAAA,EAAO;AAAA;AAAA,EAG5C;AAAA,EAAS;AAAA,EAAW;AAAA;AAAA,EAGpB;AAAA,EAAY;AAAA,EAAa;AAAA,EAAW;AAAA;AAAA,EAGpC;AAAA,EAAO;AAAA,EAAQ;AAAA,EAAQ;AAAA;AAAA,EAGvB;AAAA,EAAqB;AAAA,EAAa;AAAA,EAAkB;AAAA,EACpD;AAAA,EAAc;AAAA,EAAgB;AAAA;AAAA,EAG9B;AAAA,EAAY;AAAA,EAAa;AAAA,EACzB;AAAA,EAAU;AAAA,EAAQ;AAAA,EAAS;AAAA,EAC3B;AAAA,EAAS;AAAA;AAAA,EAGT;AACF;AAEO,IAAM,oBAAoB,QAAQ,IAAI,2BAA2B,IACrE,MAAM,GAAG,EACT,IAAI,OAAK,EAAE,KAAK,CAAC,EACjB,OAAO,OAAO,EACd,OAAO,gBAAgB;AAEnB,IAAM,gBAAgB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../tools/warp_grep/agent/formatter.ts"],"sourcesContent":["export class ToolOutputFormatter {\n\tformat(\n\t\ttoolName: string,\n\t\t_args: Record<string, unknown> | null | undefined,\n\t\toutput: string,\n\t\toptions: { isError?: boolean } = {}\n\t): string {\n\t\tconst name = (toolName ?? \"\").trim();\n\t\tif (!name) {\n\t\t\treturn \"\";\n\t\t}\n\t\tconst payload = (output as any)?.toString?.()?.trim?.() ?? \"\";\n\t\tconst isError = Boolean(options.isError);\n\n\t\tif (!payload && !isError) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\treturn `<tool_response>\\n${payload}\\n</tool_response>`;\n\t}\n}\n\nconst sharedFormatter = new ToolOutputFormatter();\n\nexport function formatAgentToolOutput(\n\ttoolName: string,\n\targs: Record<string, unknown> | null | undefined,\n\toutput: string,\n\toptions: { isError?: boolean } = {}\n): string {\n\treturn sharedFormatter.format(toolName, args, output, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,IAAM,sBAAN,MAA0B;AAAA,EAChC,OACC,UACA,OACA,QACA,UAAiC,CAAC,GACzB;AACT,UAAM,QAAQ,YAAY,IAAI,KAAK;AACnC,QAAI,CAAC,MAAM;AACV,aAAO;AAAA,IACR;AACA,UAAM,UAAW,QAAgB,WAAW,GAAG,OAAO,KAAK;AAC3D,UAAM,UAAU,QAAQ,QAAQ,OAAO;AAEvC,QAAI,CAAC,WAAW,CAAC,SAAS;AACzB,aAAO;AAAA,IACR;AAEA,WAAO;AAAA,EAAoB,OAAO;AAAA;AAAA,EACnC;AACD;AAEA,IAAM,kBAAkB,IAAI,oBAAoB;AAEzC,SAAS,sBACf,UACA,MACA,QACA,UAAiC,CAAC,GACzB;AACT,SAAO,gBAAgB,OAAO,UAAU,MAAM,QAAQ,OAAO;AAC9D;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../tools/warp_grep/agent/parser.ts"],"sourcesContent":["// Helpers for parsing string-format tool arguments from OpenAI tool calls\n\nimport type { FinishFileSpec } from './types.js';\n\n/** Parse \"lines\" string from read tool (e.g. \"1-50\" or \"1-20,45-80\") into structured args */\nexport function parseReadLines(linesStr: string): { start?: number; end?: number; lines?: Array<[number, number]> } {\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of linesStr.split(',')) {\n const trimmed = rangeStr.trim();\n if (!trimmed) continue;\n const parts = trimmed.split('-').map(v => parseInt(v.trim(), 10));\n if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {\n ranges.push([parts[0], parts[1]]);\n } else if (Number.isFinite(parts[0])) {\n ranges.push([parts[0], parts[0]]);\n }\n }\n if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };\n if (ranges.length > 1) return { lines: ranges };\n return {};\n}\n\n/** Parse \"files\" string from finish tool (e.g. \"src/auth.py:1-50\\nsrc/user.py\" or space-separated) into FinishFileSpec[] */\nexport function parseFinishFiles(filesStr: string): FinishFileSpec[] {\n const files: FinishFileSpec[] = [];\n // Split on whitespace (training uses space-separated, SDK also supports newlines)\n for (const line of filesStr.trim().split(/\\s+/)) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n // Skip Windows drive letter prefix (e.g. \"C:\") to avoid splitting on it\n const searchFrom = /^[A-Za-z]:/.test(trimmed) ? 2 : 0;\n const colonIdx = trimmed.indexOf(':', searchFrom);\n if (colonIdx === -1) {\n files.push({ path: trimmed, lines: '*' });\n continue;\n }\n const filePath = trimmed.slice(0, colonIdx);\n const rangesPart = trimmed.slice(colonIdx + 1);\n if (!rangesPart.trim() || rangesPart.trim() === '*') {\n files.push({ path: filePath, lines: '*' });\n continue;\n }\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of rangesPart.split(',')) {\n const rt = rangeStr.trim();\n if (!rt) continue;\n const parts = rt.split('-').map(v => parseInt(v.trim(), 10));\n if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {\n ranges.push([parts[0], parts[1]]);\n } else if (Number.isFinite(parts[0])) {\n ranges.push([parts[0], parts[0]]);\n }\n }\n files.push({ path: filePath, lines: ranges.length > 0 ? ranges : '*' });\n }\n return files;\n}\n\n/** Extract directory path from a list_directory command string (e.g. \"ls -la src/\" → \"src/\") */\nexport function extractPathFromCommand(command: string): string {\n const tokens = command.trim().split(/\\s+/);\n const pathTokens = tokens.slice(1).filter(t => !t.startsWith('-') && !t.startsWith('|') && !t.startsWith('\\\\('));\n return pathTokens[0] || '.';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKO,SAAS,eAAe,U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D,YAAM,KAAK,EAAE,MAAM,UAAU,OAAO,IAAI,CAAC;AACzC;AAAA,IACF;AACA,UAAM,SAAkC,CAAC;AACzC,eAAW,YAAY,WAAW,MAAM,GAAG,GAAG;AAC5C,YAAM,KAAK,SAAS,KAAK;AACzB,UAAI,CAAC,GAAI;AACT,YAAM,QAAQ,GAAG,MAAM,GAAG,EAAE,IAAI,OAAK,SAAS,EAAE,KAAK,GAAG,EAAE,CAAC;AAC3D,UAAI,MAAM,UAAU,KAAK,OAAO,SAAS,MAAM,CAAC,CAAC,KAAK,OAAO,SAAS,MAAM,CAAC,CAAC,GAAG;AAC/E,eAAO,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;AAAA,MAClC,WAAW,OAAO,SAAS,MAAM,CAAC,CAAC,GAAG;AACpC,eAAO,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;AAAA,MAClC;AAAA,IACF;AACA,UAAM,KAAK,EAAE,MAAM,UAAU,OAAO,OAAO,SAAS,IAAI,SAAS,IAAI,CAAC;AAAA,EACxE;AACA,SAAO;AACT;AAGO,SAAS,uBAAuB,SAAyB;AAC9D,QAAM,SAAS,QAAQ,KAAK,EAAE,MAAM,KAAK;AACzC,QAAM,aAAa,OAAO,MAAM,CAAC,EAAE,OAAO,OAAK,CAAC,EAAE,WAAW,GAAG,KAAK,CAAC,EAAE,WAAW,GAAG,KAAK,CAAC,EAAE,WAAW,KAAK,CAAC;AAC/G,SAAO,WAAW,CAAC,KAAK;AAC1B;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../tools/warp_grep/agent/runner.ts","../../../../tools/warp_grep/agent/config.ts","../../../../tools/warp_grep/agent/parser.ts","../../../../tools/warp_grep/agent/tools/grep.ts","../../../../tools/warp_grep/agent/tools/read.ts","../../../../tools/warp_grep/agent/tools/list_directory.ts","../../../../tools/warp_grep/agent/tools/glob.ts","../../../../tools/warp_grep/agent/tools/finish.ts","../../../../tools/warp_grep/agent/helpers.ts","../../../../package.json","../../../../version.ts","../../../../logger.ts"],"sourcesContent":["import { AGENT_CONFIG, DEFAULT_MODEL } from './config.js';\nimport type { AgentRunResult, ChatMessage, SessionConfig, AgentFinish, ToolCallRef, WarpGrepExecutionMetrics, WarpGrepTurnMetrics, WarpGrepStep } from './types.js';\nimport { parseFinishFiles, parseReadLines, extractPathFromCommand } from './parser.js';\nimport type { WarpGrepProvider } from '../providers/types.js';\nimport { toolGrep } from './tools/grep.js';\nimport { toolRead } from './tools/read.js';\nimport { toolListDirectory } from './tools/list_directory.js';\nimport { toolGlob } from './tools/glob.js';\nimport { readFinishFiles } from './tools/finish.js';\nimport type { RetryConfig } from '../../utils/resilience.js';\nimport { formatTurnMessage, calculateContextBudget, buildInitialState, enforceContextLimit } from './helpers.js';\nimport OpenAI from 'openai';\nimport { SDK_VERSION } from '../../../version.js';\nimport path from 'path';\nimport { logger } from '../../../logger.js';\n\ntype EventName =\n | 'initial_state'\n | 'round_start'\n | 'round_end'\n | 'finish'\n | 'error';\n\nexport type EventCallback = (name: EventName, payload: Record<string, unknown>) => void;\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\n\n// Tool definitions sent to the model (OpenAI function calling format)\nconst TOOL_SPECS: OpenAI.Chat.ChatCompletionTool[] = [\n {\n type: 'function',\n function: {\n name: 'list_directory',\n description: 'Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.',\n parameters: {\n type: 'object',\n properties: {\n command: {\n type: 'string',\n description: \"Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */).\",\n },\n },\n required: ['command'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'grep_search',\n description: 'Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.',\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: \"Regex pattern to search for in file contents (e.g. 'class\\\\s+\\\\w+Error', 'import|require|from', 'def (get|set|update)_user').\",\n },\n path: {\n type: 'string',\n description: 'File or directory to search in. Defaults to current working directory.',\n },\n glob: {\n type: 'string',\n description: \"Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*').\",\n },\n limit: {\n type: 'integer',\n description: 'Limit output to first N matching lines. Shows all matches if not specified.',\n },\n },\n required: ['pattern'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'glob',\n description: 'Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.',\n parameters: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: \"Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py').\",\n },\n path: {\n type: 'string',\n description: 'Directory to search in. Defaults to repository root.',\n },\n },\n required: ['pattern'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'read',\n description: 'Read entire files or specific line ranges using absolute paths.',\n parameters: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: \"File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path).\",\n },\n lines: {\n type: 'string',\n description: \"Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file.\",\n },\n },\n required: ['path'],\n },\n },\n },\n {\n type: 'function',\n function: {\n name: 'finish',\n description: 'Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.',\n parameters: {\n type: 'object',\n properties: {\n files: {\n type: 'string',\n description: \"One file per line as path:lines (e.g. 'src/auth.py:1-15,25-50\\\\nsrc/user.py'). Omit line range to include entire file.\",\n },\n },\n required: ['files'],\n },\n },\n },\n];\n\ninterface CallModelOptions {\n morphApiKey?: string;\n morphApiUrl?: string;\n retryConfig?: RetryConfig;\n timeout?: number;\n search_type?: string;\n}\n\ntype ModelResponse = {\n content: string | null;\n tool_calls: ToolCallRef[];\n};\n\nasync function callModel(\n messages: ChatMessage[],\n model: string,\n options: CallModelOptions = {}\n): Promise<ModelResponse> {\n const baseUrl = options.morphApiUrl || DEFAULT_API_URL;\n const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || '';\n const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;\n\n const parsedUrl = new URL(baseUrl);\n const baseURL = parsedUrl.pathname === '/' ? `${baseUrl}/v1` : baseUrl;\n\n const client = new OpenAI({\n apiKey,\n baseURL,\n maxRetries: 0,\n timeout: timeoutMs,\n defaultHeaders: { 'X-Morph-SDK-Version': SDK_VERSION },\n });\n\n const MAX_EMPTY_RETRIES = 1;\n\n logger.debug('WarpGrep', 'model_call', { url: baseURL, model, message_count: messages.length });\n const callStartTime = Date.now();\n\n for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {\n let data;\n try {\n data = await client.chat.completions.create({\n model,\n temperature: 0.0,\n max_tokens: 2048,\n messages: messages as OpenAI.Chat.ChatCompletionMessageParam[],\n tools: TOOL_SPECS,\n ...(options.search_type ? { search_type: options.search_type } as Record<string, unknown> : {}),\n });\n } catch (error) {\n const callLatencyMs = Date.now() - callStartTime;\n if (error instanceof OpenAI.APIError) {\n logger.error('WarpGrep', 'model_call_error', { status: error.status, error: error.message, latency_ms: callLatencyMs });\n if (error.status === 404) {\n const defaultMsg =\n 'The endpoint you are trying to call is likely deprecated. Please update with: npm cache clean --force && npx -y @morphllm/morphmcp@latest or visit: https://morphllm.com/mcp';\n const errorText = error.message?.trim();\n throw new Error(errorText || defaultMsg);\n }\n } else {\n logger.error('WarpGrep', 'model_call_error', { status: undefined, error: error instanceof Error ? error.message : String(error), latency_ms: callLatencyMs });\n }\n throw error;\n }\n\n const choice = data?.choices?.[0];\n const message = choice?.message;\n\n if (!message) {\n if (attempt === MAX_EMPTY_RETRIES) {\n throw new Error('Invalid response from model: no message in response');\n }\n await new Promise(resolve => setTimeout(resolve, 200));\n continue;\n }\n\n const toolCalls: ToolCallRef[] = (message.tool_calls || []).map(tc => ({\n id: tc.id,\n type: 'function' as const,\n function: { name: tc.function.name, arguments: tc.function.arguments },\n }));\n\n if (message.content || toolCalls.length > 0) {\n logger.debug('WarpGrep', 'model_call_complete', { latency_ms: Date.now() - callStartTime, tool_calls_count: toolCalls.length, finish_reason: choice?.finish_reason ?? 'unknown' });\n return { content: message.content ?? null, tool_calls: toolCalls };\n }\n\n if (attempt === MAX_EMPTY_RETRIES) {\n const finishReason = choice?.finish_reason ?? 'unknown';\n throw new Error(\n `Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`\n );\n }\n await new Promise(resolve => setTimeout(resolve, 200));\n }\n\n throw new Error('Invalid response from model');\n}\n\n/** Safely parse JSON, returning empty object on failure */\nfunction safeParseJSON(s: string): Record<string, unknown> {\n try {\n return JSON.parse(s);\n } catch {\n return {};\n }\n}\n\n/**\n * Execute a single tool call against the provider, returning the output string.\n */\nasync function executeTool(\n provider: WarpGrepProvider,\n name: string,\n args: Record<string, unknown>,\n repoRoot?: string,\n): Promise<string> {\n switch (name) {\n case 'grep_search': {\n const grepArgs: { pattern: string; path: string; glob?: string; case_sensitive?: boolean } = {\n pattern: args.pattern as string,\n path: (args.path as string) || '.',\n };\n if (args.glob) grepArgs.glob = args.glob as string;\n if (args.case_sensitive !== undefined) grepArgs.case_sensitive = args.case_sensitive as boolean;\n const result = await toolGrep(provider, grepArgs);\n let output = result.output;\n if (args.limit && typeof args.limit === 'number') {\n const lines = output.split('\\n');\n if (lines.length > args.limit) {\n output = lines.slice(0, args.limit).join('\\n') + `\\n... (truncated at ${args.limit} lines)`;\n }\n }\n return output;\n }\n case 'glob': {\n return toolGlob(provider, {\n pattern: args.pattern as string,\n path: args.path as string | undefined,\n });\n }\n case 'list_directory': {\n const dirPath = extractPathFromCommand((args.command as string) || '.');\n return toolListDirectory(provider, { path: dirPath }, repoRoot);\n }\n case 'read': {\n const readArgs: { path: string; start?: number; end?: number; lines?: Array<[number, number]> } = {\n path: args.path as string,\n };\n if (args.lines && typeof args.lines === 'string') {\n Object.assign(readArgs, parseReadLines(args.lines));\n }\n return toolRead(provider, readArgs);\n }\n default:\n return `Unknown tool: ${name}`;\n }\n}\n\n/**\n * Streaming version of runWarpGrep that yields step information after each turn.\n * Yields WarpGrepStep with tool calls for each turn, then returns the final AgentRunResult.\n */\nexport async function* runWarpGrepStreaming(\n config: SessionConfig & { provider: WarpGrepProvider }\n): AsyncGenerator<WarpGrepStep, AgentRunResult, undefined> {\n const totalStart = Date.now();\n const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;\n const timings: Partial<WarpGrepExecutionMetrics> = { turns: [], timeout_ms: timeoutMs };\n\n const repoRoot = config.repoRoot || process.cwd();\n const model = config.model || DEFAULT_MODEL;\n const messages: ChatMessage[] = [];\n\n const maxTurns = AGENT_CONFIG.MAX_TURNS;\n\n logger.debug('WarpGrep', 'session_start', { search_term: config.searchTerm, model, max_turns: maxTurns });\n\n const initialStateStart = Date.now();\n const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });\n timings.initial_state_ms = Date.now() - initialStateStart;\n\n logger.debug('WarpGrep', 'initial_state', { system_prompt_len: initialState.length, user_message_len: initialState.length });\n\n messages.push({ role: 'user', content: initialState });\n\n const provider = config.provider;\n const errors: Array<{ message: string }> = [];\n\n let finishMeta: AgentFinish | undefined;\n let terminationReason: AgentRunResult['terminationReason'] = 'terminated';\n\n for (let turn = 1; turn <= maxTurns; turn += 1) {\n const turnMetrics: WarpGrepTurnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };\n\n logger.debug('WarpGrep', 'turn_start', { turn, message_count: messages.length });\n\n const beforeChars = messages.reduce((sum, m) => sum + (typeof m.content === 'string' ? m.content.length : 0), 0);\n enforceContextLimit(messages);\n const afterChars = messages.reduce((sum, m) => sum + (typeof m.content === 'string' ? m.content.length : 0), 0);\n if (afterChars < beforeChars) {\n logger.debug('WarpGrep', 'context_truncated', { before_chars: beforeChars, after_chars: afterChars });\n }\n\n // Call model\n const modelCallStart = Date.now();\n const response = await callModel(messages, model, {\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: timeoutMs,\n search_type: config.search_type,\n }).catch((e: unknown) => {\n const errMsg = e instanceof Error ? e.message : String(e);\n console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);\n logger.error('WarpGrep', 'error', { turn, error: errMsg, phase: 'model_call' });\n errors.push({ message: errMsg });\n return null;\n });\n turnMetrics.morph_api_ms = Date.now() - modelCallStart;\n\n if (!response) {\n timings.turns!.push(turnMetrics);\n break;\n }\n\n const toolCalls = response.tool_calls;\n logger.debug('WarpGrep', 'model_response', { turn, tool_calls: toolCalls.map(tc => tc.function.name), latency_ms: turnMetrics.morph_api_ms });\n\n // Add assistant message to history\n messages.push({\n role: 'assistant',\n content: response.content,\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n });\n\n if (toolCalls.length === 0) {\n console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || '').slice(0, 500)}`);\n errors.push({ message: 'No tool calls produced by the model.' });\n terminationReason = 'terminated';\n timings.turns!.push(turnMetrics);\n break;\n }\n\n // Yield step for streaming consumers\n yield {\n turn,\n toolCalls: toolCalls.map(tc => ({\n name: tc.function.name,\n arguments: safeParseJSON(tc.function.arguments),\n })),\n };\n\n // Check for finish call\n const finishCall = toolCalls.find(tc => tc.function.name === 'finish');\n if (finishCall) {\n const args = safeParseJSON(finishCall.function.arguments) as { files?: string };\n const filesStr = args.files || '';\n const files = parseFinishFiles(filesStr);\n finishMeta = { files };\n terminationReason = 'completed';\n logger.debug('WarpGrep', 'finish', { turns: turn, files: files.map(f => f.path) });\n\n if (files.length === 0) {\n const payload = filesStr || 'No relevant code found.';\n timings.turns!.push(turnMetrics);\n timings.total_ms = Date.now() - totalStart;\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: finishMeta },\n timings: timings as WarpGrepExecutionMetrics,\n };\n }\n\n timings.turns!.push(turnMetrics);\n break;\n }\n\n // Execute non-finish tool calls in parallel\n const toolExecStart = Date.now();\n const results = await Promise.all(\n toolCalls.map(async (tc) => {\n const args = safeParseJSON(tc.function.arguments);\n const argsSummary = Object.fromEntries(Object.entries(args).map(([k, v]) => [k, typeof v === 'string' && v.length > 100 ? v.slice(0, 100) + '...' : v]));\n logger.debug('WarpGrep', 'tool_exec', { turn, tool: tc.function.name, args_summary: argsSummary });\n const toolStart = Date.now();\n const output = await executeTool(provider, tc.function.name, args, repoRoot).catch(err => String(err));\n logger.debug('WarpGrep', 'tool_result', { turn, tool: tc.function.name, result_len: output.length, latency_ms: Date.now() - toolStart });\n return { tool_call_id: tc.id, content: output };\n })\n );\n turnMetrics.local_tools_ms = Date.now() - toolExecStart;\n\n // Add tool result messages\n for (const result of results) {\n messages.push({ role: 'tool', tool_call_id: result.tool_call_id, content: result.content });\n }\n\n // Add turn counter hint\n const turnMsg = formatTurnMessage(turn, maxTurns);\n const budget = calculateContextBudget(messages);\n messages.push({ role: 'user', content: turnMsg + '\\n' + budget });\n\n timings.turns!.push(turnMetrics);\n }\n\n if (terminationReason !== 'completed' || !finishMeta) {\n timings.total_ms = Date.now() - totalStart;\n return { terminationReason, messages, errors, timings: timings as WarpGrepExecutionMetrics };\n }\n\n // Build finish payload\n const parts: string[] = ['Relevant context found:'];\n for (const f of finishMeta.files) {\n const ranges = f.lines === '*' ? '*'\n : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(', ')\n : '*';\n parts.push(`- ${f.path}: ${ranges}`);\n }\n const payload = parts.join('\\n');\n\n // Resolve file contents for returned ranges\n const finishResolutionStart = Date.now();\n const fileReadErrors: Array<{ path: string; error: string }> = [];\n const resolved = await readFinishFiles(\n repoRoot,\n finishMeta.files,\n async (p: string, s?: number, e?: number) => {\n // If the model returned a path that doesn't start with repoRoot,\n // try resolving it against repoRoot (handles truncated absolute paths)\n let resolvedPath = p;\n if (!p.startsWith(repoRoot)) {\n // Strip leading slash for path.join, then try the resolved path\n const relative = p.startsWith('/') ? p.slice(1) : p;\n resolvedPath = path.join(repoRoot, relative);\n }\n try {\n const rr = await provider.read({ path: resolvedPath, start: s, end: e });\n return rr.lines.map(l => {\n const idx = l.indexOf('|');\n return idx >= 0 ? l.slice(idx + 1) : l;\n });\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n fileReadErrors.push({ path: resolvedPath, error: errorMsg });\n console.error(`[warp_grep] Failed to read file: ${resolvedPath} - ${errorMsg}`);\n return [`[couldn't find: ${resolvedPath}]`];\n }\n }\n );\n\n timings.finish_resolution_ms = Date.now() - finishResolutionStart;\n\n if (fileReadErrors.length > 0) {\n errors.push(...fileReadErrors.map(e => ({ message: `File read error: ${e.path} - ${e.error}` })));\n }\n\n timings.total_ms = Date.now() - totalStart;\n return {\n terminationReason: 'completed',\n messages,\n finish: { payload, metadata: finishMeta, resolved },\n timings: timings as WarpGrepExecutionMetrics,\n };\n}\n\n/**\n * Non-streaming version. Runs the agent loop and returns the final result.\n */\nexport async function runWarpGrep(config: SessionConfig & { provider: WarpGrepProvider }): Promise<AgentRunResult> {\n const gen = runWarpGrepStreaming(config);\n // Drain all yielded steps, return the final result\n let result = await gen.next();\n while (!result.done) {\n result = await gen.next();\n }\n return result.value;\n}\n","// Parse timeout from env, defaulting to 30 seconds\nconst parseEnvTimeout = (envValue: string | undefined, defaultMs: number): number => {\n if (!envValue) return defaultMs;\n const parsed = parseInt(envValue, 10);\n return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;\n};\n\nexport const AGENT_CONFIG = {\n MAX_TURNS: 6,\n /** Default timeout for model calls. Can be overridden via MORPH_WARP_GREP_TIMEOUT env var (in ms) */\n TIMEOUT_MS: parseEnvTimeout(process.env.MORPH_WARP_GREP_TIMEOUT, 60_000),\n MAX_CONTEXT_CHARS: 321_600,\n MAX_OUTPUT_LINES: 200,\n MAX_LIST_RESULTS: 500,\n MAX_READ_LINES: 800,\n MAX_LIST_DEPTH: 3,\n LIST_TIMEOUT_MS: 2_000,\n};\n\n/**\n * Comprehensive exclusion list for directories and files\n * These patterns are used with ripgrep's -g flag\n */\nconst BUILTIN_EXCLUDES = [\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n \n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'packages', 'Pods', '.bundle',\n \n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs', '*.egg-info',\n \n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n \n // Cache directories\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n \n // IDE/Editor\n '.idea', '.vscode', '.vs',\n \n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n \n // Temporary\n 'tmp', 'temp', '.tmp', '.temp',\n \n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n \n // Binary/minified\n '*.min.js', '*.min.css', '*.bundle.js',\n '*.wasm', '*.so', '*.dll', '*.pyc',\n '*.map', '*.js.map',\n \n // Hidden directories catch-all\n '.*',\n];\n\nexport const DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || '')\n .split(',')\n .map(s => s.trim())\n .filter(Boolean)\n .concat(BUILTIN_EXCLUDES);\n\nexport const DEFAULT_MODEL = 'morph-warp-grep-v2.1';\n","// Helpers for parsing string-format tool arguments from OpenAI tool calls\n\nimport type { FinishFileSpec } from './types.js';\n\n/** Parse \"lines\" string from read tool (e.g. \"1-50\" or \"1-20,45-80\") into structured args */\nexport function parseReadLines(linesStr: string): { start?: number; end?: number; lines?: Array<[number, number]> } {\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of linesStr.split(',')) {\n const trimmed = rangeStr.trim();\n if (!trimmed) continue;\n const parts = trimmed.split('-').map(v => parseInt(v.trim(), 10));\n if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {\n ranges.push([parts[0], parts[1]]);\n } else if (Number.isFinite(parts[0])) {\n ranges.push([parts[0], parts[0]]);\n }\n }\n if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };\n if (ranges.length > 1) return { lines: ranges };\n return {};\n}\n\n/** Parse \"files\" string from finish tool (e.g. \"src/auth.py:1-50\\nsrc/user.py\" or space-separated) into FinishFileSpec[] */\nexport function parseFinishFiles(filesStr: string): FinishFileSpec[] {\n const files: FinishFileSpec[] = [];\n // Split on whitespace (training uses space-separated, SDK also supports newlines)\n for (const line of filesStr.trim().split(/\\s+/)) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n // Skip Windows drive letter prefix (e.g. \"C:\") to avoid splitting on it\n const searchFrom = /^[A-Za-z]:/.test(trimmed) ? 2 : 0;\n const colonIdx = trimmed.indexOf(':', searchFrom);\n if (colonIdx === -1) {\n files.push({ path: trimmed, lines: '*' });\n continue;\n }\n const filePath = trimmed.slice(0, colonIdx);\n const rangesPart = trimmed.slice(colonIdx + 1);\n if (!rangesPart.trim() || rangesPart.trim() === '*') {\n files.push({ path: filePath, lines: '*' });\n continue;\n }\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of rangesPart.split(',')) {\n const rt = rangeStr.trim();\n if (!rt) continue;\n const parts = rt.split('-').map(v => parseInt(v.trim(), 10));\n if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {\n ranges.push([parts[0], parts[1]]);\n } else if (Number.isFinite(parts[0])) {\n ranges.push([parts[0], parts[0]]);\n }\n }\n files.push({ path: filePath, lines: ranges.length > 0 ? ranges : '*' });\n }\n return files;\n}\n\n/** Extract directory path from a list_directory command string (e.g. \"ls -la src/\" → \"src/\") */\nexport function extractPathFromCommand(command: string): string {\n const tokens = command.trim().split(/\\s+/);\n const pathTokens = tokens.slice(1).filter(t => !t.startsWith('-') && !t.startsWith('|') && !t.startsWith('\\\\('));\n return pathTokens[0] || '.';\n}\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nexport async function toolGrep(\n provider: WarpGrepProvider,\n args: { pattern: string; path: string; glob?: string; context_lines?: number; case_sensitive?: boolean }\n): Promise<{ output: string }> {\n const res = await provider.grep(args);\n \n // Return errors as output - let the model see and handle them\n if (res.error) {\n return { output: res.error };\n }\n \n if (!res.lines.length) {\n return { output: 'no matches' };\n }\n \n return { output: res.lines.join('\\n') };\n}\n\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nfunction isValidRange(start: unknown, end: unknown): boolean {\n return (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Number.isFinite(start) &&\n Number.isFinite(end) &&\n start > 0 &&\n end >= start\n );\n}\n\nexport async function toolRead(\n provider: WarpGrepProvider,\n args: { path: string; start?: number; end?: number; lines?: Array<[number, number]> }\n): Promise<string> {\n if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {\n const validRanges: Array<[number, number]> = [];\n for (const range of args.lines) {\n if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {\n validRanges.push([range[0], range[1]]);\n }\n }\n \n if (validRanges.length === 0) {\n const res = await provider.read({ path: args.path });\n if (res.error) return res.error;\n if (!res.lines.length) return '(empty file)';\n return res.lines.join('\\n');\n }\n \n const chunks: string[] = [];\n for (const [start, end] of validRanges) {\n const res = await provider.read({ path: args.path, start, end });\n if (res.error) return res.error;\n chunks.push(res.lines.join('\\n'));\n }\n if (chunks.every(c => c === '')) return '(empty file)';\n return chunks.join('\\n...\\n');\n }\n\n const res = await provider.read({ path: args.path, start: args.start, end: args.end });\n if (res.error) {\n return res.error;\n }\n if (!res.lines.length) return '(empty file)';\n return res.lines.join('\\n');\n}\n\n","import type { WarpGrepProvider } from '../../providers/types.js';\nimport { AGENT_CONFIG } from '../config.js';\nimport path from 'path';\n\nexport async function toolListDirectory(\n provider: WarpGrepProvider,\n args: { path: string; pattern?: string | null; maxResults?: number; maxDepth?: number },\n repoRoot?: string,\n): Promise<string> {\n\n const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;\n const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n\n const entries = await provider.listDirectory({\n path: args.path,\n pattern: args.pattern ?? null,\n maxResults,\n maxDepth,\n });\n\n if (!entries.length) return 'empty';\n\n // Flat absolute paths (matches training format)\n // If repoRoot is available, convert relative paths to absolute\n if (repoRoot) {\n const absRoot = repoRoot;\n const lines = entries.map(e => path.join(absRoot, e.path));\n return lines.join('\\n');\n }\n\n // Fallback: return relative paths if repoRoot not available\n return entries.map(e => e.path).join('\\n');\n}\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nexport async function toolGlob(\n provider: WarpGrepProvider,\n args: { pattern: string; path?: string }\n): Promise<string> {\n const res = await provider.glob(args);\n\n if (res.error) {\n return res.error;\n }\n\n if (!res.files.length) {\n return 'no matches';\n }\n\n // Match training output format exactly\n const header = `Found ${res.totalFound} file(s) matching \"${args.pattern}\" within ${res.searchDir}, sorted by modification time (newest first):`;\n const body = res.files.join('\\n');\n const truncated = res.totalFound > res.files.length\n ? `\\n[${res.totalFound - res.files.length} files truncated]`\n : '';\n return `${header}\\n---\\n${body}\\n---${truncated}`;\n}\n","import type { FinishFileSpec } from '../types.js';\n\nfunction isValidRange(range: unknown): range is [number, number] {\n return (\n Array.isArray(range) &&\n range.length >= 2 &&\n typeof range[0] === 'number' &&\n typeof range[1] === 'number' &&\n Number.isFinite(range[0]) &&\n Number.isFinite(range[1]) &&\n range[0] > 0 &&\n range[1] >= range[0]\n );\n}\n\nfunction extractValidRanges(lines: unknown): Array<[number, number]> | null {\n if (!Array.isArray(lines)) return null;\n const valid: Array<[number, number]> = [];\n for (const range of lines) {\n if (isValidRange(range)) {\n valid.push([range[0], range[1]]);\n }\n }\n return valid.length > 0 ? valid : null;\n}\n\nexport function normalizeFinishFiles(files: FinishFileSpec[]): FinishFileSpec[] {\n return files.map((f) => {\n if (f.lines === '*') return { path: f.path, lines: '*' };\n const validRanges = extractValidRanges(f.lines);\n if (!validRanges) return { path: f.path, lines: '*' };\n return { path: f.path, lines: mergeRanges(validRanges) };\n });\n}\n\nexport async function readFinishFiles(\n repoRoot: string,\n files: FinishFileSpec[],\n reader: (path: string, start?: number, end?: number) => Promise<string[]>\n): Promise<{ path: string; ranges: '*' | Array<[number, number]>; content: string }[]> {\n const out: { path: string; ranges: '*' | Array<[number, number]>; content: string }[] = [];\n for (const f of files) {\n const validRanges = f.lines === '*' ? null : extractValidRanges(f.lines);\n if (f.lines === '*' || !validRanges) {\n const lines = await reader(f.path);\n out.push({ path: f.path, ranges: '*', content: lines.join('\\n') });\n } else {\n const ranges = mergeRanges(validRanges);\n const chunks: string[] = [];\n for (let i = 0; i < ranges.length; i++) {\n const [s, e] = ranges[i];\n if (i === 0 && s > 1) {\n chunks.push(`// ... existing code, block starting at line ${s} ...`);\n } else if (i > 0) {\n chunks.push(`// ... existing code, block starting at line ${s} ...`);\n }\n const lines = await reader(f.path, s, e);\n chunks.push(lines.join('\\n'));\n }\n out.push({ path: f.path, ranges, content: chunks.join('\\n') });\n }\n }\n return out;\n}\n\nfunction mergeRanges(ranges: Array<[number, number]>): Array<[number, number]> {\n if (!ranges.length) return [];\n const sorted = [...ranges].sort((a, b) => a[0] - b[0]);\n const merged: Array<[number, number]> = [];\n let [cs, ce] = sorted[0];\n for (let i = 1; i < sorted.length; i++) {\n const [s, e] = sorted[i];\n if (s <= ce + 1) {\n ce = Math.max(ce, e);\n } else {\n merged.push([cs, ce]);\n cs = s;\n ce = e;\n }\n }\n merged.push([cs, ce]);\n return merged;\n}\n\n","/**\n * Shared helper functions for warp-grep agent loop.\n * Used by both the internal runner and exported for harness users.\n */\n\nimport path from 'path';\nimport { AGENT_CONFIG } from './config.js';\nimport type { ChatMessage } from './types.js';\nimport type { WarpGrepProvider, ListDirectoryEntry } from '../providers/types.js';\n\nconst TRUNCATED_MARKER = '[truncated for context limit]';\n\n/**\n * Get the character size of a ChatMessage (handles all message types).\n */\nfunction getMessageSize(m: ChatMessage): number {\n if (m.role === 'tool') return m.content.length;\n if (m.role === 'assistant') {\n let size = typeof m.content === 'string' ? m.content.length : 0;\n if (m.tool_calls) {\n size += m.tool_calls.reduce((s, tc) => s + tc.function.name.length + tc.function.arguments.length, 0);\n }\n return size;\n }\n // system or user\n return (m as { content: string }).content.length;\n}\n\n/**\n * Format the turn counter message shown to the model.\n */\nexport function formatTurnMessage(turnsUsed: number, maxTurns: number): string {\n const turnsRemaining = maxTurns - turnsUsed;\n if (turnsRemaining === 1) {\n return `\\nYou have used ${turnsUsed} turns, you only have 1 turn remaining. You have run out of turns to explore the code base and MUST call the finish tool now`;\n }\n return `\\nYou have used ${turnsUsed} turn${turnsUsed === 1 ? '' : 's'} and have ${turnsRemaining} remaining`;\n}\n\n/**\n * Calculate and format the context budget indicator.\n */\nexport function calculateContextBudget(messages: ChatMessage[]): string {\n const totalChars = messages.reduce((sum, m) => sum + getMessageSize(m), 0);\n const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;\n const percent = Math.floor((totalChars / maxChars) * 100);\n const usedK = Math.floor(totalChars / 1000);\n const maxK = Math.floor(maxChars / 1000);\n return `<context_budget>${percent}% (${usedK}K/${maxK}K chars)</context_budget>`;\n}\n\n/**\n * Build the initial state message containing repo structure and search term.\n */\nexport async function buildInitialState(\n repoRoot: string,\n searchTerm: string,\n provider: WarpGrepProvider,\n options?: { search_type?: string },\n): Promise<string> {\n const budget = calculateContextBudget([]);\n const turnTag = `You have used 0 turns and have ${AGENT_CONFIG.MAX_TURNS} remaining`;\n const treeDepth = options?.search_type === 'node_modules' ? 1 : 2;\n\n const absRoot = repoRoot;\n\n try {\n const entries = await provider.listDirectory({\n path: '.',\n maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,\n maxDepth: treeDepth,\n });\n\n // Flat list of absolute paths (matches training format)\n // First line is the repo root, then one absolute path per entry\n const lines = [absRoot];\n for (const e of entries) {\n lines.push(path.join(absRoot, e.path));\n }\n\n return `<repo_structure>\\n${lines.join('\\n')}\\n</repo_structure>\\n\\n<search_string>\\n${searchTerm}\\n</search_string>\\n${budget}\\n${turnTag}`;\n } catch {\n return `<repo_structure>\\n${absRoot}\\n</repo_structure>\\n\\n<search_string>\\n${searchTerm}\\n</search_string>\\n${budget}\\n${turnTag}`;\n }\n}\n\n/**\n * Format directory entries as an indented tree string.\n */\nexport function formatListDirectoryTree(entries: ListDirectoryEntry[]): string {\n if (!entries.length) return 'empty';\n return entries\n .map((e) => {\n const indent = ' '.repeat(e.depth);\n const name = e.type === 'dir' ? `${e.name}/` : e.name;\n return `${indent}${name}`;\n })\n .join('\\n');\n}\n\n/**\n * Enforce hard context limit by truncating tool result messages.\n * Preserves the first user message (initial query) and all assistant messages.\n * Truncates tool/user messages from oldest to newest until under the threshold.\n *\n * @param messages - The conversation messages array (mutated in place)\n * @param maxChars - Maximum total character count (defaults to AGENT_CONFIG.MAX_CONTEXT_CHARS)\n * @returns The same messages array, truncated if necessary\n */\nexport function enforceContextLimit(\n messages: ChatMessage[],\n maxChars: number = AGENT_CONFIG.MAX_CONTEXT_CHARS\n): ChatMessage[] {\n const getTotalChars = () => messages.reduce((sum, m) => sum + getMessageSize(m), 0);\n\n if (getTotalChars() <= maxChars) {\n return messages;\n }\n\n // Find indices of truncatable messages (tool results and non-first user messages)\n const truncatableIndices: number[] = [];\n let firstUserSkipped = false;\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n if (m.role === 'tool') {\n truncatableIndices.push(i);\n } else if (m.role === 'user') {\n if (!firstUserSkipped) {\n firstUserSkipped = true;\n continue; // Skip first user message (contains the search query)\n }\n truncatableIndices.push(i);\n }\n }\n\n // Truncate from oldest to newest until under limit\n for (const idx of truncatableIndices) {\n if (getTotalChars() <= maxChars) {\n break;\n }\n const m = messages[idx];\n if (m.role === 'tool' && m.content !== TRUNCATED_MARKER) {\n messages[idx] = { role: 'tool', tool_call_id: m.tool_call_id, content: TRUNCATED_MARKER };\n } else if (m.role === 'user' && (m as { content: string }).content !== TRUNCATED_MARKER) {\n messages[idx] = { role: 'user', content: TRUNCATED_MARKER };\n }\n }\n\n return messages;\n}\n","{\n \"name\": \"@morphllm/morphsdk\",\n \"version\": \"0.2.200\",\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 \"./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 \"./modelrouter\": {\n \"types\": \"./dist/modelrouter/index.d.ts\",\n \"import\": \"./dist/modelrouter/index.js\",\n \"require\": \"./dist/modelrouter/index.cjs\"\n },\n \"./tools/compact\": {\n \"types\": \"./dist/tools/compact/index.d.ts\",\n \"import\": \"./dist/tools/compact/index.js\",\n \"require\": \"./dist/tools/compact/index.cjs\"\n },\n \"./subagents\": {\n \"types\": \"./dist/subagents/index.d.ts\",\n \"import\": \"./dist/subagents/index.js\",\n \"require\": \"./dist/subagents/index.cjs\"\n },\n \"./subagents/vercel\": {\n \"types\": \"./dist/subagents/vercel.d.ts\",\n \"import\": \"./dist/subagents/vercel.js\",\n \"require\": \"./dist/subagents/vercel.cjs\"\n },\n \"./subagents/anthropic\": {\n \"types\": \"./dist/subagents/anthropic.d.ts\",\n \"import\": \"./dist/subagents/anthropic.js\",\n \"require\": \"./dist/subagents/anthropic.cjs\"\n },\n \"./ai-sdk\": {\n \"types\": \"./dist/ai-sdk/index.d.ts\",\n \"import\": \"./dist/ai-sdk/index.js\",\n \"require\": \"./dist/ai-sdk/index.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/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve && tsup ai-sdk/index.ts --format esm,cjs --sourcemap --dts --no-clean --out-dir dist/ai-sdk\",\n \"prepare\": \"npm run build\",\n \"typecheck\": \"tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json\",\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: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 \"@vscode/ripgrep\": \"^1.17.0\",\n \"ai\": \">=5.0.0\",\n \"diff\": \"^7.0.0\",\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 \"@ai-sdk/openai-compatible\": \">=2.0.74 <4\",\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-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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,IAAM,kBAAkB,CAAC,UAA8B,cAA8B;AACnF,MAAI,CAAC,SAAU,QAAO;AACtB,QAAM,SAAS,SAAS,UAAU,EAAE;AACpC,SAAO,MAAM,MAAM,KAAK,UAAU,IAAI,YAAY;AACpD;AAEO,IAAM,eAAe;AAAA,EAC1B,WAAW;AAAA;AAAA,EAEX,YAAY,gBAAgB,QAAQ,IAAI,yBAAyB,GAAM;AAAA,EACvE,mBAAmB;AAAA,EACnB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,iBAAiB;AACnB;AAMA,IAAM,mBAAmB;AAAA;AAAA,EAEvB;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAO;AAAA;AAAA,EAGvB;AAAA,EAAgB;AAAA,EAAoB;AAAA,EAAS;AAAA,EAC7C;AAA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eAAe,SAAS,GAAG;AAC7B,WAAO,KAAK,GAAG,eAAe,IAAI,QAAM,EAAE,SAAS,oBAAoB,EAAE,IAAI,MAAM,EAAE,KAAK,GAAG,EAAE,CAAC;AAAA,EAClG;AAEA,UAAQ,WAAW,KAAK,IAAI,IAAI;AAChC,SAAO;AAAA,IACL,mBAAmB;AAAA,IACnB;AAAA,IACA,QAAQ,EAAE,SAAS,UAAU,YAAY,SAAS;AAAA,IAClD;AAAA,EACF;AACF;AAKA,eAAsB,YAAY,QAAiF;AACjH,QAAM,MAAM,qBAAqB,MAAM;AAEvC,MAAI,SAAS,MAAM,IAAI,KAAK;AAC5B,SAAO,CAAC,OAAO,MAAM;AACnB,aAAS,MAAM,IAAI,KAAK;AAAA,EAC1B;AACA,SAAO,OAAO;AAChB;","names":["res","path","isValidRange","import_path","path","import_path","OpenAI","payload","path"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../tools/warp_grep/agent/types.ts"],"sourcesContent":["// Core types for morph-warp-grep agent\n\nexport type ToolCallRef = {\n id: string;\n type: 'function';\n function: { name: string; arguments: string };\n};\n\nexport type ChatMessage =\n | { role: 'system'; content: string }\n | { role: 'user'; content: string }\n | { role: 'assistant'; content: string | null; tool_calls?: ToolCallRef[] }\n | { role: 'tool'; tool_call_id: string; content: string };\n\nexport type ToolName = 'list_directory' | 'grep_search' | 'glob' | 'read' | 'finish';\n\nexport type ToolCall = {\n name: ToolName;\n arguments?: Record<string, unknown>;\n};\n\nexport type FinishFileSpec = {\n path: string;\n lines: '*' | Array<[number, number]>;\n};\n\nexport type ResolvedContext = {\n path: string;\n ranges: '*' | Array<[number, number]>;\n content: string;\n};\n\nexport type AgentFinish = {\n files: FinishFileSpec[];\n};\n\nexport type ResolvedFile = {\n path: string;\n content: string;\n};\n\nexport type WarpGrepTurnMetrics = {\n turn: number;\n morph_api_ms: number;\n local_tools_ms: number;\n};\n\nexport type WarpGrepExecutionMetrics = {\n total_ms: number;\n timeout_ms: number;\n initial_state_ms: number;\n turns: WarpGrepTurnMetrics[];\n finish_resolution_ms?: number;\n};\n\nexport type AgentRunResult = {\n terminationReason: 'completed' | 'terminated' | 'error';\n messages: ChatMessage[];\n finish?: {\n payload: string;\n metadata?: AgentFinish;\n resolved?: ResolvedContext[];\n };\n errors?: Array<{ message: string }>;\n timings?: WarpGrepExecutionMetrics;\n};\n\nexport type SessionConfig = {\n searchTerm: string;\n model?: string;\n repoRoot: string;\n excludes?: string[];\n includes?: string[];\n debug?: boolean;\n provider?: unknown; // late-bound to provider interface to avoid cycles\n /** Morph API key (defaults to MORPH_API_KEY env var) */\n morphApiKey?: string;\n /** Morph API base URL */\n morphApiUrl?: string;\n /** Retry configuration */\n retryConfig?: import('../../utils/resilience.js').RetryConfig;\n /** Timeout for model calls in ms (defaults to MORPH_WARP_GREP_TIMEOUT env var, then 30000) */\n timeout?: number;\n /** Search type hint. When 'node_modules', uses shallower initial tree and includes node_modules in search. */\n search_type?: string;\n};\n\n/**\n * A single step yielded during streaming execution.\n * Contains the turn number and tool calls made during that turn.\n */\nexport type WarpGrepStep = {\n turn: number;\n toolCalls: Array<{\n name: string;\n arguments: Record<string, unknown>;\n }>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}