@morphllm/morphsdk 0.2.202 → 0.2.204

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 (246) hide show
  1. package/README.md +101 -0
  2. package/dist/chunk-2GMG5XKU.js +100 -0
  3. package/dist/chunk-2PPYWRMZ.js +3 -4
  4. package/dist/chunk-3HAHJYZQ.cjs +74 -0
  5. package/dist/{chunk-2XU3XXUE.js → chunk-3JROKKS4.js} +3 -25
  6. package/dist/{chunk-26K5EJD3.js → chunk-43JBUEIX.js} +4 -18
  7. package/dist/chunk-44OIEPIO.js +4 -23
  8. package/dist/chunk-4EQQGUZ7.cjs +104 -0
  9. package/dist/chunk-4OUGA3KS.js +1 -5
  10. package/dist/{chunk-VQDDL3UH.js → chunk-4TZBUFVP.js} +2 -8
  11. package/dist/{chunk-YAM6P5OQ.js → chunk-564XJOQP.js} +2 -6
  12. package/dist/chunk-5H3FKFOI.cjs +77 -0
  13. package/dist/chunk-5TTZQF4X.cjs +110 -0
  14. package/dist/chunk-6HAYJA6M.cjs +317 -0
  15. package/dist/chunk-6TZCVTW5.js +3 -4
  16. package/dist/chunk-6WP7EA4F.js +2 -4
  17. package/dist/chunk-74A4HLIO.cjs +42 -0
  18. package/dist/chunk-75ZPJI57.cjs +9 -0
  19. package/dist/chunk-7PJYY46L.cjs +2 -0
  20. package/dist/chunk-AWFZKS27.cjs +11 -0
  21. package/dist/chunk-BJBWWIZV.cjs +2 -0
  22. package/dist/chunk-DLYDIYDK.cjs +305 -0
  23. package/dist/{chunk-65TUD7JV.js → chunk-DYCMPDPV.js} +13 -29
  24. package/dist/{chunk-3CPI6ZIC.js → chunk-DZP7BR66.js} +22 -43
  25. package/dist/chunk-E63OPKP7.js +96 -0
  26. package/dist/chunk-E6V75LI6.cjs +334 -0
  27. package/dist/{chunk-XPHNS7NW.js → chunk-EJ6ID24K.js} +3 -12
  28. package/dist/chunk-EJTL2BOZ.cjs +42 -0
  29. package/dist/chunk-ETBRAKVV.js +1 -5
  30. package/dist/chunk-F633IVQA.cjs +91 -0
  31. package/dist/chunk-FBOZIVVQ.js +1 -0
  32. package/dist/{chunk-UKXCGQPS.js → chunk-FGA6EYC2.js} +35 -37
  33. package/dist/{chunk-CAWQEHKP.js → chunk-G4RODMXA.js} +4 -19
  34. package/dist/chunk-GUNGJC6X.cjs +256 -0
  35. package/dist/chunk-GYE3FY6Z.js +8 -0
  36. package/dist/chunk-HDP4QAZL.js +1 -4
  37. package/dist/chunk-HNMEBYIS.cjs +86 -0
  38. package/dist/chunk-HP3PCOTW.cjs +81 -0
  39. package/dist/{chunk-ICCGLO6V.js → chunk-IGXNLXPN.js} +12 -17
  40. package/dist/chunk-IPJA3ZS6.cjs +10 -0
  41. package/dist/chunk-JHC2R3HU.cjs +317 -0
  42. package/dist/{chunk-IBRBSDLT.js → chunk-JVMIFGZY.js} +5 -8
  43. package/dist/chunk-KF6S3EPJ.cjs +100 -0
  44. package/dist/chunk-KVGZ2TSG.cjs +274 -0
  45. package/dist/{chunk-6OYJC4TZ.js → chunk-L5SCKZVK.js} +13 -22
  46. package/dist/chunk-LDM7RNNN.js +1 -0
  47. package/dist/{chunk-UAZKHSEU.js → chunk-LQST3NW2.js} +5 -15
  48. package/dist/chunk-M34E2AMK.js +1 -5
  49. package/dist/chunk-MF56KEI4.js +1 -4
  50. package/dist/chunk-MLKGABMK.js +1 -3
  51. package/dist/chunk-MLPZKUCO.js +4 -5
  52. package/dist/chunk-MMX5PUGC.cjs +242 -0
  53. package/dist/chunk-MWXJ6DZ2.cjs +21 -0
  54. package/dist/chunk-NJWOWXUR.cjs +137 -0
  55. package/dist/chunk-NNKBKENK.cjs +15 -0
  56. package/dist/chunk-NRG6QX3L.js +1 -3
  57. package/dist/chunk-OCKEEEYE.cjs +433 -0
  58. package/dist/chunk-OENJO7YW.js +306 -0
  59. package/dist/chunk-OKLAYEBC.cjs +2 -0
  60. package/dist/chunk-OPDWMD4Q.js +1 -3
  61. package/dist/{chunk-D6YJ5X3C.js → chunk-OX5GN2KB.js} +26 -14
  62. package/dist/{chunk-JEVLCA5C.js → chunk-OYBOP47A.js} +18 -19
  63. package/dist/chunk-OZHCHPIE.js +1 -0
  64. package/dist/chunk-PA3UTI4A.js +1 -4
  65. package/dist/chunk-QEEAIXL5.cjs +74 -0
  66. package/dist/chunk-QT5LGZG3.cjs +10 -0
  67. package/dist/chunk-R3TUE7O2.cjs +107 -0
  68. package/dist/chunk-RYVW7RUM.js +2 -6
  69. package/dist/{chunk-LVKKICOB.js → chunk-SOQYE5A4.js} +36 -69
  70. package/dist/chunk-ST2OXLT5.cjs +91 -0
  71. package/dist/{chunk-SIFDK4AA.js → chunk-TH4MG73B.js} +3 -24
  72. package/dist/{chunk-OSL4CNSO.js → chunk-TLMAMVAW.js} +7 -23
  73. package/dist/chunk-TPZHMD7J.cjs +72 -0
  74. package/dist/{chunk-PDSIWL7I.js → chunk-U4PYAGNR.js} +6 -19
  75. package/dist/chunk-UAPK3AIJ.js +1 -10
  76. package/dist/chunk-UF5IKELS.cjs +26 -0
  77. package/dist/chunk-UHFVWYSP.cjs +408 -0
  78. package/dist/chunk-UKBSXYKE.cjs +280 -0
  79. package/dist/chunk-UNX7V6P6.cjs +60 -0
  80. package/dist/chunk-UZMMJ47A.cjs +107 -0
  81. package/dist/chunk-VHD7CW5O.cjs +43 -0
  82. package/dist/chunk-VL4QNALG.cjs +50 -0
  83. package/dist/chunk-VYE7O4FM.cjs +51 -0
  84. package/dist/chunk-WIYVT4UO.cjs +173 -0
  85. package/dist/chunk-WJHHO24M.cjs +91 -0
  86. package/dist/chunk-WR7LSUIR.cjs +213 -0
  87. package/dist/chunk-XE6D4J63.cjs +72 -0
  88. package/dist/chunk-YAUXTFIN.cjs +21 -0
  89. package/dist/{chunk-NFPRKZQ5.js → chunk-YJUCGZNN.js} +5 -22
  90. package/dist/chunk-ZSHVXDA2.js +4 -10
  91. package/dist/chunk-ZX6T3LNG.js +302 -0
  92. package/dist/{client-BWhi-vSj.d.ts → client-DSXbcxII.d.ts} +10 -1
  93. package/dist/client.cjs +44 -4360
  94. package/dist/client.d.ts +4 -2
  95. package/dist/client.js +36 -37
  96. package/dist/core/client.cjs +14 -476
  97. package/dist/core/client.d.ts +8 -0
  98. package/dist/core/client.js +10 -11
  99. package/dist/core/error.cjs +8 -251
  100. package/dist/core/error.js +4 -9
  101. package/dist/core/index.cjs +27 -491
  102. package/dist/core/index.d.ts +2 -0
  103. package/dist/core/index.js +12 -19
  104. package/dist/core/resource.cjs +9 -33
  105. package/dist/core/resource.d.ts +2 -0
  106. package/dist/core/resource.js +2 -7
  107. package/dist/edge.cjs +74 -1111
  108. package/dist/edge.d.ts +3 -0
  109. package/dist/edge.js +14 -42
  110. package/dist/guard-CvW03v4u.d.ts +59 -0
  111. package/dist/index.cjs +140 -4431
  112. package/dist/index.d.ts +6 -2
  113. package/dist/index.js +44 -87
  114. package/dist/modelrouter/core.cjs +35 -651
  115. package/dist/modelrouter/core.d.ts +2 -0
  116. package/dist/modelrouter/core.js +12 -21
  117. package/dist/modelrouter/index.cjs +35 -651
  118. package/dist/modelrouter/index.d.ts +2 -0
  119. package/dist/modelrouter/index.js +12 -21
  120. package/dist/modelrouter/types.cjs +1 -17
  121. package/dist/modelrouter/types.d.ts +5 -0
  122. package/dist/modelrouter/types.js +1 -0
  123. package/dist/subagents/anthropic.cjs +31 -2784
  124. package/dist/subagents/anthropic.d.ts +3 -1
  125. package/dist/subagents/anthropic.js +23 -24
  126. package/dist/subagents/index.cjs +14 -95
  127. package/dist/subagents/index.d.ts +3 -1
  128. package/dist/subagents/index.js +2 -11
  129. package/dist/subagents/prompts.cjs +14 -93
  130. package/dist/subagents/prompts.d.ts +3 -1
  131. package/dist/subagents/prompts.js +2 -11
  132. package/dist/subagents/types.cjs +1 -17
  133. package/dist/subagents/types.d.ts +3 -1
  134. package/dist/subagents/types.js +1 -0
  135. package/dist/subagents/vercel.cjs +31 -2761
  136. package/dist/subagents/vercel.d.ts +3 -1
  137. package/dist/subagents/vercel.js +23 -24
  138. package/dist/tools/compact/core.cjs +20 -552
  139. package/dist/tools/compact/core.d.ts +2 -0
  140. package/dist/tools/compact/core.js +12 -13
  141. package/dist/tools/compact/index.cjs +24 -598
  142. package/dist/tools/compact/index.d.ts +3 -1
  143. package/dist/tools/compact/index.js +13 -17
  144. package/dist/tools/compact/types.cjs +1 -17
  145. package/dist/tools/compact/types.d.ts +4 -4
  146. package/dist/tools/compact/types.js +1 -0
  147. package/dist/tools/fastapply/anthropic.cjs +39 -899
  148. package/dist/tools/fastapply/anthropic.d.ts +2 -0
  149. package/dist/tools/fastapply/anthropic.js +15 -24
  150. package/dist/tools/fastapply/apply.cjs +32 -672
  151. package/dist/tools/fastapply/apply.d.ts +2 -0
  152. package/dist/tools/fastapply/apply.js +8 -19
  153. package/dist/tools/fastapply/core.cjs +49 -1069
  154. package/dist/tools/fastapply/core.d.ts +3 -0
  155. package/dist/tools/fastapply/core.js +13 -29
  156. package/dist/tools/fastapply/index.cjs +56 -1052
  157. package/dist/tools/fastapply/index.d.ts +2 -0
  158. package/dist/tools/fastapply/index.js +18 -44
  159. package/dist/tools/fastapply/openai.cjs +45 -910
  160. package/dist/tools/fastapply/openai.d.ts +2 -0
  161. package/dist/tools/fastapply/openai.js +15 -26
  162. package/dist/tools/fastapply/prompts.cjs +10 -62
  163. package/dist/tools/fastapply/prompts.js +2 -9
  164. package/dist/tools/fastapply/types.cjs +1 -17
  165. package/dist/tools/fastapply/types.d.ts +9 -4
  166. package/dist/tools/fastapply/types.js +1 -0
  167. package/dist/tools/fastapply/vercel.cjs +37 -905
  168. package/dist/tools/fastapply/vercel.d.ts +2 -0
  169. package/dist/tools/fastapply/vercel.js +15 -22
  170. package/dist/tools/index.cjs +56 -1052
  171. package/dist/tools/index.d.ts +2 -0
  172. package/dist/tools/index.js +18 -44
  173. package/dist/tools/pii/index.cjs +47 -0
  174. package/dist/tools/pii/index.d.ts +4 -0
  175. package/dist/tools/pii/index.js +6 -0
  176. package/dist/tools/pii/model.cjs +45 -0
  177. package/dist/tools/pii/model.d.ts +83 -0
  178. package/dist/tools/pii/model.js +4 -0
  179. package/dist/tools/pii/patterns.cjs +15 -0
  180. package/dist/tools/pii/patterns.d.ts +31 -0
  181. package/dist/tools/pii/patterns.js +2 -0
  182. package/dist/tools/pii/regex.cjs +32 -0
  183. package/dist/tools/pii/regex.d.ts +48 -0
  184. package/dist/tools/pii/regex.js +3 -0
  185. package/dist/tools/pii/types.cjs +2 -0
  186. package/dist/tools/pii/types.d.ts +108 -0
  187. package/dist/tools/pii/types.js +1 -0
  188. package/dist/tools/utils/resilience.cjs +15 -312
  189. package/dist/tools/utils/resilience.js +3 -12
  190. package/dist/tools/warp_grep/agent/config.cjs +16 -127
  191. package/dist/tools/warp_grep/agent/config.js +2 -11
  192. package/dist/tools/warp_grep/agent/formatter.cjs +12 -48
  193. package/dist/tools/warp_grep/agent/formatter.js +2 -9
  194. package/dist/tools/warp_grep/agent/parser.cjs +16 -83
  195. package/dist/tools/warp_grep/agent/parser.d.ts +2 -0
  196. package/dist/tools/warp_grep/agent/parser.js +2 -11
  197. package/dist/tools/warp_grep/agent/runner.cjs +19 -1081
  198. package/dist/tools/warp_grep/agent/runner.d.ts +2 -0
  199. package/dist/tools/warp_grep/agent/runner.js +11 -14
  200. package/dist/tools/warp_grep/agent/types.cjs +1 -17
  201. package/dist/tools/warp_grep/agent/types.d.ts +4 -0
  202. package/dist/tools/warp_grep/agent/types.js +1 -0
  203. package/dist/tools/warp_grep/anthropic.cjs +51 -2561
  204. package/dist/tools/warp_grep/anthropic.d.ts +3 -1
  205. package/dist/tools/warp_grep/anthropic.js +23 -35
  206. package/dist/tools/warp_grep/client.cjs +53 -2471
  207. package/dist/tools/warp_grep/client.d.ts +3 -1
  208. package/dist/tools/warp_grep/client.js +21 -34
  209. package/dist/tools/warp_grep/gemini.cjs +52 -2490
  210. package/dist/tools/warp_grep/gemini.d.ts +3 -1
  211. package/dist/tools/warp_grep/gemini.js +25 -41
  212. package/dist/tools/warp_grep/harness.cjs +81 -936
  213. package/dist/tools/warp_grep/harness.d.ts +2 -0
  214. package/dist/tools/warp_grep/harness.js +12 -51
  215. package/dist/tools/warp_grep/index.cjs +128 -2575
  216. package/dist/tools/warp_grep/index.d.ts +3 -1
  217. package/dist/tools/warp_grep/index.js +28 -87
  218. package/dist/tools/warp_grep/openai.cjs +57 -2575
  219. package/dist/tools/warp_grep/openai.d.ts +3 -1
  220. package/dist/tools/warp_grep/openai.js +23 -37
  221. package/dist/tools/warp_grep/providers/code_storage_http.cjs +12 -65
  222. package/dist/tools/warp_grep/providers/code_storage_http.d.ts +3 -1
  223. package/dist/tools/warp_grep/providers/code_storage_http.js +2 -9
  224. package/dist/tools/warp_grep/providers/local.cjs +10 -589
  225. package/dist/tools/warp_grep/providers/local.js +6 -11
  226. package/dist/tools/warp_grep/providers/remote.cjs +8 -331
  227. package/dist/tools/warp_grep/providers/remote.d.ts +3 -1
  228. package/dist/tools/warp_grep/providers/remote.js +3 -8
  229. package/dist/tools/warp_grep/providers/types.cjs +1 -17
  230. package/dist/tools/warp_grep/providers/types.js +1 -0
  231. package/dist/tools/warp_grep/utils/files.cjs +9 -42
  232. package/dist/tools/warp_grep/utils/files.js +2 -7
  233. package/dist/tools/warp_grep/utils/github.cjs +9 -43
  234. package/dist/tools/warp_grep/utils/github.js +2 -7
  235. package/dist/tools/warp_grep/utils/paths.cjs +28 -104
  236. package/dist/tools/warp_grep/utils/paths.js +2 -17
  237. package/dist/tools/warp_grep/utils/ripgrep.cjs +9 -103
  238. package/dist/tools/warp_grep/utils/ripgrep.js +2 -7
  239. package/dist/tools/warp_grep/vercel.cjs +57 -2557
  240. package/dist/tools/warp_grep/vercel.d.ts +3 -1
  241. package/dist/tools/warp_grep/vercel.js +23 -37
  242. package/dist/{types-DxZLPogx.d.ts → types-BKhXjDCB.d.ts} +6 -1
  243. package/dist/version.cjs +7 -225
  244. package/dist/version.js +2 -7
  245. package/package.json +11 -2
  246. package/dist/chunk-E6TL6MIH.js +0 -203
@@ -0,0 +1,137 @@
1
+ 'use strict';
2
+
3
+ var chunkUHFVWYSP_cjs = require('./chunk-UHFVWYSP.cjs');
4
+ var chunk5TTZQF4X_cjs = require('./chunk-5TTZQF4X.cjs');
5
+ var chunkVL4QNALG_cjs = require('./chunk-VL4QNALG.cjs');
6
+ var chunkAWFZKS27_cjs = require('./chunk-AWFZKS27.cjs');
7
+ var path = require('path');
8
+
9
+ var DEFAULT_CONFIG = {
10
+ baseDir: process.cwd(),
11
+ generateUdiff: true,
12
+ autoWrite: true,
13
+ timeout: 6e5};
14
+ var FastApplyClient = class extends chunkAWFZKS27_cjs.APIResource {
15
+ config;
16
+ constructor(clientOrConfig = {}) {
17
+ const isClient = clientOrConfig instanceof chunk5TTZQF4X_cjs.MorphAPIClient;
18
+ super(
19
+ isClient ? clientOrConfig : new chunk5TTZQF4X_cjs.MorphAPIClient({
20
+ apiKey: clientOrConfig.apiKey,
21
+ timeout: clientOrConfig.timeout ?? DEFAULT_CONFIG.timeout,
22
+ retryConfig: clientOrConfig.retryConfig,
23
+ debug: clientOrConfig.debug,
24
+ redactPII: clientOrConfig.redactPII
25
+ })
26
+ );
27
+ this.config = {
28
+ morphApiKey: this._client.resolveApiKey(),
29
+ morphApiUrl: this._client.baseURL,
30
+ debug: this._client.debug,
31
+ timeout: (isClient ? void 0 : clientOrConfig.timeout) ?? DEFAULT_CONFIG.timeout,
32
+ retryConfig: this._client.retryConfig,
33
+ redactPII: this._client.redactPII,
34
+ generateUdiff: DEFAULT_CONFIG.generateUdiff,
35
+ autoWrite: DEFAULT_CONFIG.autoWrite
36
+ };
37
+ }
38
+ /**
39
+ * Execute a file edit operation
40
+ *
41
+ * @param input - Edit parameters including filepath, instructions, and code_edit
42
+ * @param overrides - Optional config overrides for this operation
43
+ * @returns Edit result with success status and changes
44
+ */
45
+ async execute(input, overrides) {
46
+ return executeEditFile(input, { ...this.config, ...overrides });
47
+ }
48
+ /**
49
+ * Apply an edit to code directly without file I/O
50
+ *
51
+ * Useful for sandbox environments or when you manage your own file system.
52
+ * Compatible with the earlier OpenAI client API contract.
53
+ *
54
+ * @param input - Code and edit parameters
55
+ * @param overrides - Optional config overrides for this operation
56
+ * @returns Result with merged code
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * const result = await client.applyEdit({
61
+ * originalCode: 'function hello() { return "world"; }',
62
+ * codeEdit: 'function hello() { return "universe"; }',
63
+ * instructions: 'Change return value'
64
+ * });
65
+ * console.log(result.mergedCode);
66
+ * ```
67
+ */
68
+ async applyEdit(input, overrides) {
69
+ const { applyEdit: applyEdit2 } = await import('./tools/fastapply/apply.cjs');
70
+ return applyEdit2(input, { ...this.config, ...overrides });
71
+ }
72
+ };
73
+ async function executeEditFile(input, config = {}) {
74
+ const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;
75
+ const fullPath = path.resolve(path.join(baseDir, input.target_filepath));
76
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "execute_start", { target_filepath: input.target_filepath, baseDir, autoWrite: config.autoWrite !== false });
77
+ const relativePath = path.relative(baseDir, fullPath);
78
+ if (relativePath.startsWith("..") || fullPath === baseDir) {
79
+ chunkVL4QNALG_cjs.logger.warn("FastApply", "security_check_failed", { target_filepath: input.target_filepath, relative: relativePath });
80
+ return {
81
+ success: false,
82
+ filepath: input.target_filepath,
83
+ changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
84
+ error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`
85
+ };
86
+ }
87
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "security_check", { resolved: fullPath, relative: relativePath });
88
+ try {
89
+ const { readFile, writeFile } = await import('fs/promises');
90
+ const { callMorphAPI: callMorphAPI2, generateUdiff: generateUdiff2, countChanges: countChanges2 } = await import('./tools/fastapply/apply.cjs');
91
+ let originalCode = "";
92
+ let fileExists = true;
93
+ try {
94
+ originalCode = await readFile(fullPath, "utf-8");
95
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "file_read", { path: fullPath, exists: true, size_bytes: originalCode.length });
96
+ } catch (error) {
97
+ if (error.code !== "ENOENT") {
98
+ throw error;
99
+ }
100
+ fileExists = false;
101
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "file_read", { path: fullPath, exists: false });
102
+ }
103
+ const instruction = input.instruction ?? input.instructions ?? "";
104
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "api_call", { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });
105
+ const { content: mergedCode, completionId } = await callMorphAPI2(originalCode, input.code_edit, instruction, input.target_filepath, config);
106
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "api_response", { completion_id: completionId, merged_len: mergedCode.length });
107
+ const udiff = config.generateUdiff !== false ? generateUdiff2(originalCode, mergedCode, input.target_filepath) : void 0;
108
+ if (config.autoWrite !== false) {
109
+ await writeFile(fullPath, mergedCode, "utf-8");
110
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "file_write", { path: fullPath, size_bytes: mergedCode.length });
111
+ }
112
+ const changes = countChanges2(originalCode, mergedCode);
113
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "changes", { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });
114
+ return {
115
+ success: true,
116
+ filepath: input.target_filepath,
117
+ udiff,
118
+ changes,
119
+ completionId
120
+ };
121
+ } catch (error) {
122
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
123
+ const structuredError = error instanceof chunkUHFVWYSP_cjs.FastApplyContextLengthError || error instanceof chunkUHFVWYSP_cjs.FastApplyAnchorIntegrityError ? error : void 0;
124
+ chunkVL4QNALG_cjs.logger.error("FastApply", "execute_error", { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : void 0 });
125
+ return {
126
+ success: false,
127
+ filepath: input.target_filepath,
128
+ changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
129
+ error: errorMessage,
130
+ errorCode: structuredError?.code,
131
+ completionId: structuredError?.completionId
132
+ };
133
+ }
134
+ }
135
+
136
+ exports.FastApplyClient = FastApplyClient;
137
+ exports.executeEditFile = executeEditFile;
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ var fs = require('fs/promises');
4
+
5
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
+
7
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
8
+
9
+ // tools/warp_grep/utils/files.ts
10
+ async function readAllLines(filePath) {
11
+ const content = await fs__default.default.readFile(filePath, "utf8");
12
+ return content.split(/\r?\n/);
13
+ }
14
+
15
+ exports.readAllLines = readAllLines;
@@ -6,6 +6,4 @@ var APIResource = class {
6
6
  }
7
7
  };
8
8
 
9
- export {
10
- APIResource
11
- };
9
+ export { APIResource };
@@ -0,0 +1,433 @@
1
+ 'use strict';
2
+
3
+ var chunkKVGZ2TSG_cjs = require('./chunk-KVGZ2TSG.cjs');
4
+ var chunkUNX7V6P6_cjs = require('./chunk-UNX7V6P6.cjs');
5
+ var chunk4EQQGUZ7_cjs = require('./chunk-4EQQGUZ7.cjs');
6
+ var chunkVL4QNALG_cjs = require('./chunk-VL4QNALG.cjs');
7
+ var chunkKF6S3EPJ_cjs = require('./chunk-KF6S3EPJ.cjs');
8
+ var chunkQT5LGZG3_cjs = require('./chunk-QT5LGZG3.cjs');
9
+ var OpenAI = require('openai');
10
+ var path = require('path');
11
+
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
+
14
+ var OpenAI__default = /*#__PURE__*/_interopDefault(OpenAI);
15
+ var path__default = /*#__PURE__*/_interopDefault(path);
16
+
17
+ var DEFAULT_API_URL = "https://api.morphllm.com";
18
+ var TOOL_SPECS = [
19
+ {
20
+ type: "function",
21
+ function: {
22
+ name: "list_directory",
23
+ description: "Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.",
24
+ parameters: {
25
+ type: "object",
26
+ properties: {
27
+ command: {
28
+ type: "string",
29
+ description: "Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */)."
30
+ }
31
+ },
32
+ required: ["command"]
33
+ }
34
+ }
35
+ },
36
+ {
37
+ type: "function",
38
+ function: {
39
+ name: "grep_search",
40
+ description: "Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.",
41
+ parameters: {
42
+ type: "object",
43
+ properties: {
44
+ pattern: {
45
+ type: "string",
46
+ description: "Regex pattern to search for in file contents (e.g. 'class\\s+\\w+Error', 'import|require|from', 'def (get|set|update)_user')."
47
+ },
48
+ path: {
49
+ type: "string",
50
+ description: "File or directory to search in. Defaults to current working directory."
51
+ },
52
+ glob: {
53
+ type: "string",
54
+ description: "Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*')."
55
+ },
56
+ limit: {
57
+ type: "integer",
58
+ description: "Limit output to first N matching lines. Shows all matches if not specified."
59
+ }
60
+ },
61
+ required: ["pattern"]
62
+ }
63
+ }
64
+ },
65
+ {
66
+ type: "function",
67
+ function: {
68
+ name: "glob",
69
+ description: "Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.",
70
+ parameters: {
71
+ type: "object",
72
+ properties: {
73
+ pattern: {
74
+ type: "string",
75
+ description: "Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py')."
76
+ },
77
+ path: {
78
+ type: "string",
79
+ description: "Directory to search in. Defaults to repository root."
80
+ }
81
+ },
82
+ required: ["pattern"]
83
+ }
84
+ }
85
+ },
86
+ {
87
+ type: "function",
88
+ function: {
89
+ name: "read",
90
+ description: "Read entire files or specific line ranges using absolute paths.",
91
+ parameters: {
92
+ type: "object",
93
+ properties: {
94
+ path: {
95
+ type: "string",
96
+ description: "File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path)."
97
+ },
98
+ lines: {
99
+ type: "string",
100
+ description: "Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file."
101
+ }
102
+ },
103
+ required: ["path"]
104
+ }
105
+ }
106
+ },
107
+ {
108
+ type: "function",
109
+ function: {
110
+ name: "finish",
111
+ description: "Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.",
112
+ parameters: {
113
+ type: "object",
114
+ properties: {
115
+ files: {
116
+ type: "string",
117
+ 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."
118
+ }
119
+ },
120
+ required: ["files"]
121
+ }
122
+ }
123
+ }
124
+ ];
125
+ async function redactMessages(messages, pii) {
126
+ return Promise.all(
127
+ messages.map(async (message) => {
128
+ const out = { ...message };
129
+ if (typeof message.content === "string") out.content = await pii.redact(message.content);
130
+ if (message.role === "assistant" && out.role === "assistant" && message.tool_calls) {
131
+ out.tool_calls = await Promise.all(
132
+ message.tool_calls.map(async (tc) => ({
133
+ ...tc,
134
+ function: { ...tc.function, arguments: await pii.redact(tc.function.arguments) }
135
+ }))
136
+ );
137
+ }
138
+ return out;
139
+ })
140
+ );
141
+ }
142
+ async function callModel(messages, model, options = {}) {
143
+ const baseUrl = options.morphApiUrl || DEFAULT_API_URL;
144
+ const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
145
+ const timeoutMs = options.timeout ?? chunk4EQQGUZ7_cjs.AGENT_CONFIG.TIMEOUT_MS;
146
+ const parsedUrl = new URL(baseUrl);
147
+ const baseURL = parsedUrl.pathname === "/" ? `${baseUrl}/v1` : baseUrl;
148
+ const client = new OpenAI__default.default({
149
+ apiKey,
150
+ baseURL,
151
+ maxRetries: 0,
152
+ timeout: timeoutMs,
153
+ defaultHeaders: { "X-Morph-SDK-Version": chunkQT5LGZG3_cjs.SDK_VERSION }
154
+ });
155
+ const MAX_EMPTY_RETRIES = 1;
156
+ const pii = options.pii;
157
+ const outgoing = pii ? await redactMessages(messages, pii) : messages;
158
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "model_call", { url: baseURL, model, message_count: messages.length });
159
+ const callStartTime = Date.now();
160
+ for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {
161
+ let data;
162
+ try {
163
+ data = await client.chat.completions.create({
164
+ model,
165
+ temperature: 0,
166
+ max_tokens: 2048,
167
+ messages: outgoing,
168
+ tools: TOOL_SPECS,
169
+ ...options.search_type ? { search_type: options.search_type } : {}
170
+ });
171
+ } catch (error) {
172
+ const callLatencyMs = Date.now() - callStartTime;
173
+ if (error instanceof OpenAI__default.default.APIError) {
174
+ chunkVL4QNALG_cjs.logger.error("WarpGrep", "model_call_error", { status: error.status, error: error.message, latency_ms: callLatencyMs });
175
+ if (error.status === 404) {
176
+ const defaultMsg = "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";
177
+ const errorText = error.message?.trim();
178
+ throw new Error(errorText || defaultMsg);
179
+ }
180
+ } else {
181
+ chunkVL4QNALG_cjs.logger.error("WarpGrep", "model_call_error", { status: void 0, error: error instanceof Error ? error.message : String(error), latency_ms: callLatencyMs });
182
+ }
183
+ throw error;
184
+ }
185
+ const choice = data?.choices?.[0];
186
+ const message = choice?.message;
187
+ if (!message) {
188
+ if (attempt === MAX_EMPTY_RETRIES) {
189
+ throw new Error("Invalid response from model: no message in response");
190
+ }
191
+ await new Promise((resolve) => setTimeout(resolve, 200));
192
+ continue;
193
+ }
194
+ const toolCalls = (message.tool_calls || []).map((tc) => ({
195
+ id: tc.id,
196
+ type: "function",
197
+ // Restore real values so grep patterns and file paths work against the local repo.
198
+ function: { name: tc.function.name, arguments: pii ? pii.restore(tc.function.arguments) : tc.function.arguments }
199
+ }));
200
+ if (message.content || toolCalls.length > 0) {
201
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "model_call_complete", { latency_ms: Date.now() - callStartTime, tool_calls_count: toolCalls.length, finish_reason: choice?.finish_reason ?? "unknown" });
202
+ return { content: pii ? pii.restore(message.content ?? null) ?? null : message.content ?? null, tool_calls: toolCalls };
203
+ }
204
+ if (attempt === MAX_EMPTY_RETRIES) {
205
+ const finishReason = choice?.finish_reason ?? "unknown";
206
+ throw new Error(
207
+ `Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`
208
+ );
209
+ }
210
+ await new Promise((resolve) => setTimeout(resolve, 200));
211
+ }
212
+ throw new Error("Invalid response from model");
213
+ }
214
+ function safeParseJSON(s) {
215
+ try {
216
+ return JSON.parse(s);
217
+ } catch {
218
+ return {};
219
+ }
220
+ }
221
+ async function executeTool(provider, name, args, repoRoot) {
222
+ switch (name) {
223
+ case "grep_search": {
224
+ const grepArgs = {
225
+ pattern: args.pattern,
226
+ path: args.path || "."
227
+ };
228
+ if (args.glob) grepArgs.glob = args.glob;
229
+ if (args.case_sensitive !== void 0) grepArgs.case_sensitive = args.case_sensitive;
230
+ const result = await chunkKVGZ2TSG_cjs.toolGrep(provider, grepArgs);
231
+ let output = result.output;
232
+ if (args.limit && typeof args.limit === "number") {
233
+ const lines = output.split("\n");
234
+ if (lines.length > args.limit) {
235
+ output = lines.slice(0, args.limit).join("\n") + `
236
+ ... (truncated at ${args.limit} lines)`;
237
+ }
238
+ }
239
+ return output;
240
+ }
241
+ case "glob": {
242
+ return chunkKVGZ2TSG_cjs.toolGlob(provider, {
243
+ pattern: args.pattern,
244
+ path: args.path
245
+ });
246
+ }
247
+ case "list_directory": {
248
+ const dirPath = chunkUNX7V6P6_cjs.extractPathFromCommand(args.command || ".");
249
+ return chunkKVGZ2TSG_cjs.toolListDirectory(provider, { path: dirPath }, repoRoot);
250
+ }
251
+ case "read": {
252
+ const readArgs = {
253
+ path: args.path
254
+ };
255
+ if (args.lines && typeof args.lines === "string") {
256
+ Object.assign(readArgs, chunkUNX7V6P6_cjs.parseReadLines(args.lines));
257
+ }
258
+ return chunkKVGZ2TSG_cjs.toolRead(provider, readArgs);
259
+ }
260
+ default:
261
+ return `Unknown tool: ${name}`;
262
+ }
263
+ }
264
+ async function* runWarpGrepStreaming(config) {
265
+ const totalStart = Date.now();
266
+ const timeoutMs = config.timeout ?? chunk4EQQGUZ7_cjs.AGENT_CONFIG.TIMEOUT_MS;
267
+ const timings = { turns: [], timeout_ms: timeoutMs };
268
+ const repoRoot = config.repoRoot || process.cwd();
269
+ const model = config.model || chunk4EQQGUZ7_cjs.DEFAULT_MODEL;
270
+ const messages = [];
271
+ const pii = chunkKF6S3EPJ_cjs.resolvePIIGuard(config.redactPII)?.session();
272
+ const maxTurns = chunk4EQQGUZ7_cjs.AGENT_CONFIG.MAX_TURNS;
273
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "session_start", { search_term: config.searchTerm, model, max_turns: maxTurns });
274
+ const initialStateStart = Date.now();
275
+ const initialState = await chunkKVGZ2TSG_cjs.buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });
276
+ timings.initial_state_ms = Date.now() - initialStateStart;
277
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "initial_state", { system_prompt_len: initialState.length, user_message_len: initialState.length });
278
+ messages.push({ role: "user", content: initialState });
279
+ const provider = config.provider;
280
+ const errors = [];
281
+ let finishMeta;
282
+ let terminationReason = "terminated";
283
+ for (let turn = 1; turn <= maxTurns; turn += 1) {
284
+ const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
285
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "turn_start", { turn, message_count: messages.length });
286
+ const beforeChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
287
+ chunkKVGZ2TSG_cjs.enforceContextLimit(messages);
288
+ const afterChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
289
+ if (afterChars < beforeChars) {
290
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "context_truncated", { before_chars: beforeChars, after_chars: afterChars });
291
+ }
292
+ const modelCallStart = Date.now();
293
+ const response = await callModel(messages, model, {
294
+ morphApiKey: config.morphApiKey,
295
+ morphApiUrl: config.morphApiUrl,
296
+ retryConfig: config.retryConfig,
297
+ timeout: timeoutMs,
298
+ search_type: config.search_type,
299
+ pii
300
+ }).catch((e) => {
301
+ const errMsg = e instanceof Error ? e.message : String(e);
302
+ console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
303
+ chunkVL4QNALG_cjs.logger.error("WarpGrep", "error", { turn, error: errMsg, phase: "model_call" });
304
+ errors.push({ message: errMsg });
305
+ return null;
306
+ });
307
+ turnMetrics.morph_api_ms = Date.now() - modelCallStart;
308
+ if (!response) {
309
+ timings.turns.push(turnMetrics);
310
+ break;
311
+ }
312
+ const toolCalls = response.tool_calls;
313
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "model_response", { turn, tool_calls: toolCalls.map((tc) => tc.function.name), latency_ms: turnMetrics.morph_api_ms });
314
+ messages.push({
315
+ role: "assistant",
316
+ content: response.content,
317
+ ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
318
+ });
319
+ if (toolCalls.length === 0) {
320
+ console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || "").slice(0, 500)}`);
321
+ errors.push({ message: "No tool calls produced by the model." });
322
+ terminationReason = "terminated";
323
+ timings.turns.push(turnMetrics);
324
+ break;
325
+ }
326
+ yield {
327
+ turn,
328
+ toolCalls: toolCalls.map((tc) => ({
329
+ name: tc.function.name,
330
+ arguments: safeParseJSON(tc.function.arguments)
331
+ }))
332
+ };
333
+ const finishCall = toolCalls.find((tc) => tc.function.name === "finish");
334
+ if (finishCall) {
335
+ const args = safeParseJSON(finishCall.function.arguments);
336
+ const filesStr = args.files || "";
337
+ const files = chunkUNX7V6P6_cjs.parseFinishFiles(filesStr);
338
+ finishMeta = { files };
339
+ terminationReason = "completed";
340
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "finish", { turns: turn, files: files.map((f) => f.path) });
341
+ if (files.length === 0) {
342
+ const payload2 = filesStr || "No relevant code found.";
343
+ timings.turns.push(turnMetrics);
344
+ timings.total_ms = Date.now() - totalStart;
345
+ return {
346
+ terminationReason: "completed",
347
+ messages,
348
+ finish: { payload: payload2, metadata: finishMeta },
349
+ timings
350
+ };
351
+ }
352
+ timings.turns.push(turnMetrics);
353
+ break;
354
+ }
355
+ const toolExecStart = Date.now();
356
+ const results = await Promise.all(
357
+ toolCalls.map(async (tc) => {
358
+ const args = safeParseJSON(tc.function.arguments);
359
+ const argsSummary = Object.fromEntries(Object.entries(args).map(([k, v]) => [k, typeof v === "string" && v.length > 100 ? v.slice(0, 100) + "..." : v]));
360
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "tool_exec", { turn, tool: tc.function.name, args_summary: argsSummary });
361
+ const toolStart = Date.now();
362
+ const output = await executeTool(provider, tc.function.name, args, repoRoot).catch((err) => String(err));
363
+ chunkVL4QNALG_cjs.logger.debug("WarpGrep", "tool_result", { turn, tool: tc.function.name, result_len: output.length, latency_ms: Date.now() - toolStart });
364
+ return { tool_call_id: tc.id, content: output };
365
+ })
366
+ );
367
+ turnMetrics.local_tools_ms = Date.now() - toolExecStart;
368
+ for (const result of results) {
369
+ messages.push({ role: "tool", tool_call_id: result.tool_call_id, content: result.content });
370
+ }
371
+ const turnMsg = chunkKVGZ2TSG_cjs.formatTurnMessage(turn, maxTurns);
372
+ const budget = chunkKVGZ2TSG_cjs.calculateContextBudget(messages);
373
+ messages.push({ role: "user", content: turnMsg + "\n" + budget });
374
+ timings.turns.push(turnMetrics);
375
+ }
376
+ if (terminationReason !== "completed" || !finishMeta) {
377
+ timings.total_ms = Date.now() - totalStart;
378
+ return { terminationReason, messages, errors, timings };
379
+ }
380
+ const parts = ["Relevant context found:"];
381
+ for (const f of finishMeta.files) {
382
+ const ranges = f.lines === "*" ? "*" : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(", ") : "*";
383
+ parts.push(`- ${f.path}: ${ranges}`);
384
+ }
385
+ const payload = parts.join("\n");
386
+ const finishResolutionStart = Date.now();
387
+ const fileReadErrors = [];
388
+ const resolved = await chunkKVGZ2TSG_cjs.readFinishFiles(
389
+ repoRoot,
390
+ finishMeta.files,
391
+ async (p, s, e) => {
392
+ let resolvedPath = p;
393
+ if (!p.startsWith(repoRoot)) {
394
+ const relative = p.startsWith("/") ? p.slice(1) : p;
395
+ resolvedPath = path__default.default.join(repoRoot, relative);
396
+ }
397
+ try {
398
+ const rr = await provider.read({ path: resolvedPath, start: s, end: e });
399
+ return rr.lines.map((l) => {
400
+ const idx = l.indexOf("|");
401
+ return idx >= 0 ? l.slice(idx + 1) : l;
402
+ });
403
+ } catch (err) {
404
+ const errorMsg = err instanceof Error ? err.message : String(err);
405
+ fileReadErrors.push({ path: resolvedPath, error: errorMsg });
406
+ console.error(`[warp_grep] Failed to read file: ${resolvedPath} - ${errorMsg}`);
407
+ return [`[couldn't find: ${resolvedPath}]`];
408
+ }
409
+ }
410
+ );
411
+ timings.finish_resolution_ms = Date.now() - finishResolutionStart;
412
+ if (fileReadErrors.length > 0) {
413
+ errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
414
+ }
415
+ timings.total_ms = Date.now() - totalStart;
416
+ return {
417
+ terminationReason: "completed",
418
+ messages,
419
+ finish: { payload, metadata: finishMeta, resolved },
420
+ timings
421
+ };
422
+ }
423
+ async function runWarpGrep(config) {
424
+ const gen = runWarpGrepStreaming(config);
425
+ let result = await gen.next();
426
+ while (!result.done) {
427
+ result = await gen.next();
428
+ }
429
+ return result.value;
430
+ }
431
+
432
+ exports.runWarpGrep = runWarpGrep;
433
+ exports.runWarpGrepStreaming = runWarpGrepStreaming;