@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,408 @@
1
+ 'use strict';
2
+
3
+ var chunkVL4QNALG_cjs = require('./chunk-VL4QNALG.cjs');
4
+ var chunkKF6S3EPJ_cjs = require('./chunk-KF6S3EPJ.cjs');
5
+ var chunkQT5LGZG3_cjs = require('./chunk-QT5LGZG3.cjs');
6
+ var diff = require('diff');
7
+ var OpenAI = require('openai');
8
+
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ var OpenAI__default = /*#__PURE__*/_interopDefault(OpenAI);
12
+
13
+ // tools/fastapply/anchors.ts
14
+ var DEFAULT_MIN_ANCHOR_LINE_LENGTH = 24;
15
+ var DEFAULT_ANCHOR_COMPACTION_THRESHOLD = 128 * 1024;
16
+ var FastApplyAnchorIntegrityError = class extends Error {
17
+ code = "anchor_integrity_failed";
18
+ completionId;
19
+ constructor(completionId) {
20
+ super(
21
+ "Fast Apply failed large-file anchor integrity checks. The partial result was discarded safely."
22
+ );
23
+ this.name = "FastApplyAnchorIntegrityError";
24
+ this.completionId = completionId;
25
+ }
26
+ };
27
+ function escapeRegExp(value) {
28
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
29
+ }
30
+ function findNamespace(values) {
31
+ for (let namespace = 0; namespace < Number.MAX_SAFE_INTEGER; namespace++) {
32
+ const prefix = `\u27EAM${namespace}:`;
33
+ if (values.every((value) => !value.includes(prefix))) {
34
+ return namespace;
35
+ }
36
+ }
37
+ throw new Error("Unable to allocate a Fast Apply anchor namespace");
38
+ }
39
+ function htmlLabel(token) {
40
+ if (!token.startsWith("<")) return "text";
41
+ const match = token.match(/^<\s*(!doctype|\/?[a-zA-Z][\w:-]*)/);
42
+ return (match?.[1] ?? "tag").toLowerCase();
43
+ }
44
+ function htmlTokenUnits(value, visibleTags = /* @__PURE__ */ new Set()) {
45
+ return (value.match(/<[^>]*>|[^<]+/g) ?? [value]).map((token) => ({
46
+ value: token,
47
+ label: htmlLabel(token),
48
+ anchorable: token.length >= DEFAULT_MIN_ANCHOR_LINE_LENGTH && !visibleTags.has(htmlLabel(token).replace(/^\//, ""))
49
+ }));
50
+ }
51
+ function sourceUnits(originalCode, editContext) {
52
+ const trimmed = originalCode.trimStart().toLowerCase();
53
+ const looksLikeHtml = (trimmed.startsWith("<!doctype") || trimmed.startsWith("<html")) && /<\/html\s*>/i.test(originalCode);
54
+ if (looksLikeHtml) {
55
+ const contextWords = new Set(
56
+ editContext.join(" ").toLowerCase().match(/[a-z][\w:-]*/g) ?? []
57
+ );
58
+ return htmlTokenUnits(originalCode, contextWords);
59
+ }
60
+ const parts = originalCode.split(/(\r\n|\n|\r)/);
61
+ const units = [];
62
+ for (let index = 0; index < parts.length; index += 2) {
63
+ const line = parts[index] ?? "";
64
+ const lineEnding = parts[index + 1] ?? "";
65
+ units.push({
66
+ value: line,
67
+ label: "line",
68
+ anchorable: line.length >= DEFAULT_MIN_ANCHOR_LINE_LENGTH
69
+ });
70
+ if (lineEnding) {
71
+ units.push({ value: lineEnding, anchorable: false });
72
+ }
73
+ }
74
+ return units;
75
+ }
76
+ function copyCount(value) {
77
+ const words = {
78
+ one: 1,
79
+ two: 2,
80
+ three: 3,
81
+ four: 4,
82
+ five: 5,
83
+ six: 6,
84
+ seven: 7,
85
+ eight: 8,
86
+ nine: 9,
87
+ ten: 10
88
+ };
89
+ return /^\d+$/.test(value) ? Number(value) : words[value.toLowerCase()];
90
+ }
91
+ function structuralExpectation(originalCode, editContext) {
92
+ const context = editContext.join(" ");
93
+ const match = context.match(
94
+ /(?: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
95
+ );
96
+ if (!match) return void 0;
97
+ const tag = match[1].toLowerCase();
98
+ const addedCopies = copyCount(match[2]);
99
+ if (addedCopies === void 0) return void 0;
100
+ const tagPattern = new RegExp(`<${escapeRegExp(tag)}(?:\\s|>)`, "gi");
101
+ const originalCount = originalCode.match(tagPattern)?.length ?? 0;
102
+ if (originalCount === 0) return void 0;
103
+ return { tag, expectedCount: originalCount * (addedCopies + 1) };
104
+ }
105
+ function createAnchorCompactionPlan(originalCode, collisionValues = []) {
106
+ const namespace = findNamespace([originalCode, ...collisionValues]);
107
+ const expectation = structuralExpectation(originalCode, collisionValues);
108
+ const markerPrefix = `\u27EAM${namespace}:`;
109
+ const definitions = /* @__PURE__ */ new Map();
110
+ const values = [];
111
+ const markers = [];
112
+ let anchorCount = 0;
113
+ let skeleton = "";
114
+ for (const unit of sourceUnits(originalCode, collisionValues)) {
115
+ if (!unit.anchorable) {
116
+ skeleton += unit.value;
117
+ continue;
118
+ }
119
+ let id = definitions.get(unit.value);
120
+ if (id === void 0) {
121
+ id = values.length;
122
+ definitions.set(unit.value, id);
123
+ values.push(unit.value);
124
+ markers.push(`${markerPrefix}${id}:${unit.label ?? "unit"}\u27EB`);
125
+ }
126
+ skeleton += markers[id];
127
+ anchorCount++;
128
+ }
129
+ if (anchorCount === 0 || skeleton.length >= originalCode.length) {
130
+ return void 0;
131
+ }
132
+ const definitionsBegin = `\u27EAMORPH_DEFINITIONS_BEGIN_${namespace}\u27EB`;
133
+ const definitionsEnd = `\u27EAMORPH_DEFINITIONS_END_${namespace}\u27EB`;
134
+ const codeBegin = `\u27EAMORPH_CODE_BEGIN_${namespace}\u27EB`;
135
+ const serializedDefinitions = values.map((value, id) => `${markers[id]}=${JSON.stringify(value)}`).join("\n");
136
+ const code = [
137
+ definitionsBegin,
138
+ serializedDefinitions,
139
+ definitionsEnd,
140
+ codeBegin,
141
+ skeleton
142
+ ].join("\n");
143
+ const instructionSuffix = `
144
+
145
+ LARGE-FILE ANCHOR PROTOCOL:
146
+ The <code> block starts with an exact anchor definition table, then ${codeBegin}, then the source skeleton.
147
+ Each ${markerPrefix}N:kind\u27EB placeholder represents the exact source fragment in its matching JSON-string definition. The kind suffix describes its HTML tag, text, or source line.
148
+ Return only the updated source skeleton after ${codeBegin}; never return the definition table or protocol delimiters.
149
+ Copy a placeholder exactly when its source fragment is unchanged. You may repeat, reorder, or remove placeholders when the requested edit requires it.
150
+ To modify an anchored fragment, output the modified source instead of its placeholder.
151
+ Do not invent or alter placeholder IDs.`;
152
+ const markerPattern = new RegExp(`${escapeRegExp(markerPrefix)}(\\d+):[^\u27EB]+\u27EB`, "g");
153
+ return {
154
+ code,
155
+ instructionSuffix,
156
+ anchorCount,
157
+ uniqueAnchorCount: values.length,
158
+ hasStructuralValidation: expectation !== void 0,
159
+ expand(content) {
160
+ const codeBeginIndex = content.lastIndexOf(codeBegin);
161
+ const skeletonContent = codeBeginIndex >= 0 ? content.slice(codeBeginIndex + codeBegin.length).replace(/^\r?\n/, "") : content;
162
+ const expanded = skeletonContent.replace(markerPattern, (marker, idText) => {
163
+ const id = Number(idText);
164
+ const value = values[id];
165
+ return value === void 0 || markers[id] !== marker ? marker : value;
166
+ });
167
+ if (expanded.includes(markerPrefix)) {
168
+ throw new FastApplyAnchorIntegrityError();
169
+ }
170
+ if (expectation) {
171
+ const tagPattern = new RegExp(`<${escapeRegExp(expectation.tag)}(?:\\s|>)`, "gi");
172
+ const actualCount = expanded.match(tagPattern)?.length ?? 0;
173
+ if (actualCount !== expectation.expectedCount) {
174
+ throw new FastApplyAnchorIntegrityError();
175
+ }
176
+ }
177
+ return expanded;
178
+ }
179
+ };
180
+ }
181
+
182
+ // tools/fastapply/apply.ts
183
+ var DEFAULT_API_URL = "https://api.morphllm.com";
184
+ var DEFAULT_TIMEOUT = 6e5;
185
+ var FastApplyContextLengthError = class extends Error {
186
+ code = "context_length_exceeded";
187
+ completionId;
188
+ constructor(completionId) {
189
+ super(
190
+ "Fast Apply exhausted its context window before producing the complete file. Retry with a smaller input/update or use sparse anchors for unchanged code."
191
+ );
192
+ this.name = "FastApplyContextLengthError";
193
+ this.completionId = completionId;
194
+ }
195
+ };
196
+ function isAsyncIterable(value) {
197
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
198
+ }
199
+ async function collectCompletion(response) {
200
+ if (!isAsyncIterable(response)) {
201
+ const completion = response;
202
+ return {
203
+ content: completion.choices?.[0]?.message?.content ?? "",
204
+ completionId: completion.id,
205
+ finishReason: completion.choices?.[0]?.finish_reason
206
+ };
207
+ }
208
+ const content = [];
209
+ let completionId;
210
+ let finishReason;
211
+ for await (const chunk of response) {
212
+ completionId = chunk.id ?? completionId;
213
+ for (const choice of chunk.choices ?? []) {
214
+ if (choice.delta?.content) {
215
+ content.push(choice.delta.content);
216
+ }
217
+ if (choice.finish_reason !== void 0 && choice.finish_reason !== null) {
218
+ finishReason = choice.finish_reason;
219
+ }
220
+ }
221
+ }
222
+ return { content: content.join(""), completionId, finishReason };
223
+ }
224
+ function generateUdiff(original, modified, filepath) {
225
+ return diff.createTwoFilesPatch(
226
+ filepath,
227
+ filepath,
228
+ original,
229
+ modified,
230
+ "Original",
231
+ "Modified"
232
+ );
233
+ }
234
+ function countChanges(original, modified) {
235
+ const diff = generateUdiff(original, modified, "file");
236
+ const lines = diff.split("\n");
237
+ let linesAdded = 0;
238
+ let linesRemoved = 0;
239
+ for (const line of lines) {
240
+ if (line.startsWith("+") && !line.startsWith("+++")) {
241
+ linesAdded++;
242
+ } else if (line.startsWith("-") && !line.startsWith("---")) {
243
+ linesRemoved++;
244
+ }
245
+ }
246
+ const linesModified = Math.min(linesAdded, linesRemoved);
247
+ return {
248
+ linesAdded: linesAdded - linesModified,
249
+ linesRemoved: linesRemoved - linesModified,
250
+ linesModified
251
+ };
252
+ }
253
+ async function callMorphAPI(originalCode, codeEdit, instructions, filepath, config) {
254
+ const pii = chunkKF6S3EPJ_cjs.resolvePIIGuard(config.redactPII)?.session();
255
+ if (pii) {
256
+ const [code, edit, instr] = await Promise.all([
257
+ pii.redact(originalCode),
258
+ pii.redact(codeEdit),
259
+ pii.redact(instructions)
260
+ ]);
261
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "pii_redacted", { values: pii.size });
262
+ const merged = await callMorphAPI(code, edit, instr, filepath, { ...config, redactPII: void 0 });
263
+ return { ...merged, content: pii.restoreStrict(merged.content) };
264
+ }
265
+ const apiKey = config.morphApiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
266
+ const apiUrl = config.morphApiUrl || DEFAULT_API_URL;
267
+ const useLarge = config.large ?? (typeof process !== "undefined" ? process.env?.MORPH_LARGE_APPLY !== "false" : true);
268
+ const model = useLarge ? "morph-v3-large" : "morph-v3-fast";
269
+ const timeout = config.timeout ?? DEFAULT_TIMEOUT;
270
+ config.debug || false;
271
+ if (!apiKey) {
272
+ throw new Error(
273
+ "Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config."
274
+ );
275
+ }
276
+ const anchorThreshold = config.anchorCompactionThreshold ?? DEFAULT_ANCHOR_COMPACTION_THRESHOLD;
277
+ const anchorPlan = config.anchorCompaction !== false && originalCode.length >= anchorThreshold ? createAnchorCompactionPlan(originalCode, [codeEdit, instructions]) : void 0;
278
+ const requestCode = anchorPlan?.code ?? originalCode;
279
+ const requestInstructions = anchorPlan ? instructions + anchorPlan.instructionSuffix : instructions;
280
+ const message = `<instruction>${requestInstructions}</instruction>
281
+ <code>${requestCode}</code>
282
+ <update>${codeEdit}</update>`;
283
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "http_request", {
284
+ url: `${apiUrl}/v1/chat/completions`,
285
+ model,
286
+ filepath,
287
+ instruction_len: instructions.length,
288
+ original_len: originalCode.length,
289
+ request_code_len: requestCode.length,
290
+ code_edit_len: codeEdit.length,
291
+ anchor_count: anchorPlan?.anchorCount ?? 0,
292
+ unique_anchor_count: anchorPlan?.uniqueAnchorCount ?? 0
293
+ });
294
+ const startTime = Date.now();
295
+ const client = new OpenAI__default.default({
296
+ apiKey,
297
+ baseURL: `${apiUrl}/v1`,
298
+ timeout,
299
+ maxRetries: config.retryConfig?.maxRetries ?? 3,
300
+ defaultHeaders: {
301
+ "X-Morph-SDK-Version": chunkQT5LGZG3_cjs.SDK_VERSION,
302
+ ...anchorPlan ? { "X-Morph-Apply-Context": "extralong" } : {}
303
+ }
304
+ });
305
+ try {
306
+ const maxAttempts = anchorPlan?.hasStructuralValidation ? 2 : 1;
307
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
308
+ const response = await client.chat.completions.create({
309
+ model,
310
+ messages: [{ role: "user", content: message }],
311
+ stream: true
312
+ });
313
+ const completion = await collectCompletion(response);
314
+ if (completion.finishReason === "length") {
315
+ throw new FastApplyContextLengthError(completion.completionId);
316
+ }
317
+ let content = completion.content;
318
+ if (!content) {
319
+ throw new Error("Morph API returned empty response");
320
+ }
321
+ if (anchorPlan) {
322
+ try {
323
+ content = anchorPlan.expand(content);
324
+ } catch (error) {
325
+ if (error instanceof FastApplyAnchorIntegrityError) {
326
+ if (attempt < maxAttempts) {
327
+ chunkVL4QNALG_cjs.logger.warn("FastApply", "anchor_validation_retry", {
328
+ attempt,
329
+ completion_id: completion.completionId
330
+ });
331
+ continue;
332
+ }
333
+ throw new FastApplyAnchorIntegrityError(completion.completionId);
334
+ }
335
+ throw error;
336
+ }
337
+ }
338
+ const elapsed = Date.now() - startTime;
339
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "http_response", { status: 200, completion_id: completion.completionId, content_len: content.length, latency_ms: elapsed });
340
+ return { content, completionId: completion.completionId };
341
+ }
342
+ throw new FastApplyAnchorIntegrityError();
343
+ } catch (error) {
344
+ const elapsed = Date.now() - startTime;
345
+ const status = error?.status || error?.response?.status;
346
+ chunkVL4QNALG_cjs.logger.error("FastApply", "http_error", {
347
+ status,
348
+ error: error?.message,
349
+ latency_ms: elapsed
350
+ });
351
+ if (status === 401) {
352
+ const err = new Error(
353
+ "Authentication failed: Your Morph API key is invalid or has been revoked. Please visit https://morphllm.com to get a valid API key, then update your MCP configuration."
354
+ );
355
+ err.status = 401;
356
+ throw err;
357
+ }
358
+ if (status === 429) {
359
+ const err = new Error(
360
+ "Rate limited: You've exceeded your Morph API usage limits. Please visit https://morphllm.com to check your plan and purchase additional credits."
361
+ );
362
+ err.status = 429;
363
+ throw err;
364
+ }
365
+ throw error;
366
+ }
367
+ }
368
+ async function applyEdit(input, config = {}) {
369
+ const filepath = input.filepath || "file";
370
+ try {
371
+ chunkVL4QNALG_cjs.logger.debug("FastApply", "apply_edit_start", { original_len: input.originalCode.length, code_edit_len: input.codeEdit.length });
372
+ const instruction = input.instruction ?? input.instructions ?? "";
373
+ const { content: mergedCode, completionId } = await callMorphAPI(
374
+ input.originalCode,
375
+ input.codeEdit,
376
+ instruction,
377
+ filepath,
378
+ config
379
+ );
380
+ const udiff = config.generateUdiff !== false ? generateUdiff(input.originalCode, mergedCode, filepath) : void 0;
381
+ const changes = countChanges(input.originalCode, mergedCode);
382
+ return {
383
+ success: true,
384
+ mergedCode,
385
+ udiff,
386
+ changes,
387
+ completionId
388
+ };
389
+ } catch (error) {
390
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
391
+ chunkVL4QNALG_cjs.logger.error("FastApply", "apply_edit_error", { error: errorMessage });
392
+ const structuredError = error instanceof FastApplyContextLengthError || error instanceof FastApplyAnchorIntegrityError ? error : void 0;
393
+ return {
394
+ success: false,
395
+ changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
396
+ error: errorMessage,
397
+ errorCode: structuredError?.code,
398
+ completionId: structuredError?.completionId
399
+ };
400
+ }
401
+ }
402
+
403
+ exports.FastApplyAnchorIntegrityError = FastApplyAnchorIntegrityError;
404
+ exports.FastApplyContextLengthError = FastApplyContextLengthError;
405
+ exports.applyEdit = applyEdit;
406
+ exports.callMorphAPI = callMorphAPI;
407
+ exports.countChanges = countChanges;
408
+ exports.generateUdiff = generateUdiff;
@@ -0,0 +1,280 @@
1
+ 'use strict';
2
+
3
+ var chunkJHC2R3HU_cjs = require('./chunk-JHC2R3HU.cjs');
4
+ var chunkTPZHMD7J_cjs = require('./chunk-TPZHMD7J.cjs');
5
+
6
+ // subagents/anthropic.ts
7
+ var DEFAULT_MAX_TURNS = {
8
+ quick: 3,
9
+ medium: 6,
10
+ thorough: 12
11
+ };
12
+ function getMaxTurns(config) {
13
+ return config.maxTurns ?? DEFAULT_MAX_TURNS[config.thoroughness ?? "medium"] ?? 6;
14
+ }
15
+ var TOOLS = [
16
+ {
17
+ name: chunkTPZHMD7J_cjs.CODEBASE_SEARCH_TOOL.name,
18
+ description: chunkTPZHMD7J_cjs.CODEBASE_SEARCH_TOOL.description,
19
+ input_schema: chunkTPZHMD7J_cjs.CODEBASE_SEARCH_TOOL.input_schema
20
+ },
21
+ {
22
+ name: chunkTPZHMD7J_cjs.SEND_MESSAGE_TOOL.name,
23
+ description: chunkTPZHMD7J_cjs.SEND_MESSAGE_TOOL.description,
24
+ input_schema: chunkTPZHMD7J_cjs.SEND_MESSAGE_TOOL.input_schema
25
+ }
26
+ ];
27
+ function createExploreSubagent(config) {
28
+ if (!config.repoRoot) {
29
+ throw new Error("repoRoot is required for Explore subagent");
30
+ }
31
+ const warpGrep = new chunkJHC2R3HU_cjs.WarpGrepClient({
32
+ morphApiKey: config.morphApiKey
33
+ });
34
+ const thoroughness = config.thoroughness ?? "medium";
35
+ const maxTurns = getMaxTurns(config);
36
+ const replyTimeout = config.replyTimeout ?? 3e4;
37
+ async function runExplore(prompt, callbacks = {}) {
38
+ const startTime = Date.now();
39
+ const allContexts = [];
40
+ let searchCount = 0;
41
+ const timeoutMs = config.timeout;
42
+ try {
43
+ const messages = [{ role: "user", content: prompt }];
44
+ let turns = 0;
45
+ while (turns < maxTurns) {
46
+ if (timeoutMs && Date.now() - startTime > timeoutMs) {
47
+ return {
48
+ success: false,
49
+ summary: "",
50
+ contexts: deduplicateContexts(allContexts),
51
+ searchCount,
52
+ durationMs: Date.now() - startTime,
53
+ error: `Exploration timed out after ${timeoutMs}ms`
54
+ };
55
+ }
56
+ const response = await config.client.messages.create({
57
+ model: config.model,
58
+ max_tokens: 4096,
59
+ system: chunkTPZHMD7J_cjs.getSystemPrompt(thoroughness),
60
+ tools: TOOLS,
61
+ messages
62
+ });
63
+ turns++;
64
+ if (response.stop_reason === "end_turn" || !response.content.some((b) => b.type === "tool_use")) {
65
+ const textBlock = response.content.find((b) => b.type === "text");
66
+ const summary = textBlock?.text || "Exploration completed but no summary was generated.";
67
+ callbacks.onStep?.({
68
+ step: searchCount,
69
+ searchRequest: "",
70
+ contextsFound: allContexts.length,
71
+ isFinal: true
72
+ });
73
+ return {
74
+ success: true,
75
+ summary,
76
+ contexts: deduplicateContexts(allContexts),
77
+ searchCount,
78
+ durationMs: Date.now() - startTime
79
+ };
80
+ }
81
+ messages.push({ role: "assistant", content: response.content });
82
+ const toolResults = [];
83
+ for (const block of response.content) {
84
+ if (block.type !== "tool_use") continue;
85
+ if (block.name === "codebase_search") {
86
+ searchCount++;
87
+ const input = block.input;
88
+ const warpResult = await warpGrep.execute({
89
+ searchTerm: input.searchRequest,
90
+ repoRoot: config.repoRoot,
91
+ excludes: config.excludes,
92
+ includes: config.includes
93
+ });
94
+ if (warpResult.contexts) {
95
+ allContexts.push(...warpResult.contexts);
96
+ }
97
+ callbacks.onStep?.({
98
+ step: searchCount,
99
+ searchRequest: input.searchRequest,
100
+ contextsFound: warpResult.contexts?.length ?? 0,
101
+ isFinal: false
102
+ });
103
+ toolResults.push({
104
+ type: "tool_result",
105
+ tool_use_id: block.id,
106
+ content: chunkJHC2R3HU_cjs.formatResult(warpResult)
107
+ });
108
+ } else if (block.name === "send_message") {
109
+ const input = block.input;
110
+ const subagentMsg = {
111
+ from: "explore",
112
+ content: input.message,
113
+ timestamp: Date.now()
114
+ };
115
+ let replyText = "";
116
+ if (callbacks.onMessage) {
117
+ replyText = await Promise.race([
118
+ new Promise((resolve) => {
119
+ callbacks.onMessage(subagentMsg, (text) => {
120
+ resolve(text);
121
+ });
122
+ }),
123
+ new Promise(
124
+ (resolve) => setTimeout(() => resolve(""), replyTimeout)
125
+ )
126
+ ]);
127
+ }
128
+ const toolResponse = replyText ? `Response from orchestrator: ${replyText}` : "No response. Continue with your best judgment.";
129
+ toolResults.push({
130
+ type: "tool_result",
131
+ tool_use_id: block.id,
132
+ content: toolResponse
133
+ });
134
+ }
135
+ }
136
+ messages.push({ role: "user", content: toolResults });
137
+ }
138
+ return {
139
+ success: true,
140
+ summary: "Exploration completed (max turns reached).",
141
+ contexts: deduplicateContexts(allContexts),
142
+ searchCount,
143
+ durationMs: Date.now() - startTime
144
+ };
145
+ } catch (error) {
146
+ return {
147
+ success: false,
148
+ summary: "",
149
+ contexts: deduplicateContexts(allContexts),
150
+ searchCount,
151
+ durationMs: Date.now() - startTime,
152
+ error: error instanceof Error ? error.message : String(error)
153
+ };
154
+ }
155
+ }
156
+ const exploreTool = Object.assign(
157
+ {
158
+ name: "explore",
159
+ description: "Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings.",
160
+ input_schema: {
161
+ type: "object",
162
+ properties: {
163
+ searchRequest: {
164
+ type: "string",
165
+ description: "What to explore in the codebase. Be specific about what you want to understand."
166
+ }
167
+ },
168
+ required: ["searchRequest"]
169
+ }
170
+ },
171
+ {
172
+ execute: async (input) => {
173
+ return runExplore(input.searchRequest);
174
+ },
175
+ formatResult: (result) => {
176
+ if (!result.success) {
177
+ return `Exploration failed: ${result.error}`;
178
+ }
179
+ return result.summary;
180
+ }
181
+ }
182
+ );
183
+ return {
184
+ /** Anthropic Tool definition for use in parent agents */
185
+ tool: exploreTool,
186
+ /** Run exploration with messaging support */
187
+ run(prompt) {
188
+ const messageHandlers = [];
189
+ const stepHandlers = [];
190
+ let resultPromise = null;
191
+ const session = {
192
+ on(event, handler) {
193
+ if (event === "message") messageHandlers.push(handler);
194
+ if (event === "step") stepHandlers.push(handler);
195
+ return session;
196
+ },
197
+ send(_text) {
198
+ },
199
+ get result() {
200
+ if (!resultPromise) {
201
+ resultPromise = runExplore(prompt, {
202
+ onStep: (step) => {
203
+ for (const handler of stepHandlers) handler(step);
204
+ },
205
+ onMessage: (msg, reply) => {
206
+ if (messageHandlers.length > 0) {
207
+ for (const handler of messageHandlers) handler(msg, reply);
208
+ } else {
209
+ reply("");
210
+ }
211
+ }
212
+ });
213
+ }
214
+ return resultPromise;
215
+ }
216
+ };
217
+ return session;
218
+ },
219
+ /** Stream exploration events as an async generator */
220
+ async *stream(prompt) {
221
+ const events = [];
222
+ let resolveNext = null;
223
+ let done = false;
224
+ const resultPromise = runExplore(prompt, {
225
+ onStep: (step) => {
226
+ events.push({
227
+ type: "step",
228
+ step: step.step,
229
+ searchRequest: step.searchRequest,
230
+ contextsFound: step.contextsFound,
231
+ isFinal: step.isFinal
232
+ });
233
+ resolveNext?.();
234
+ },
235
+ onMessage: (msg, reply) => {
236
+ events.push({
237
+ type: "message",
238
+ from: msg.from,
239
+ content: msg.content,
240
+ timestamp: msg.timestamp
241
+ });
242
+ resolveNext?.();
243
+ reply("Continue with your best judgment.");
244
+ }
245
+ });
246
+ while (!done) {
247
+ if (events.length > 0) {
248
+ yield events.shift();
249
+ } else {
250
+ const raceResult = await Promise.race([
251
+ resultPromise.then((r) => ({ type: "done", result: r })),
252
+ new Promise((resolve) => {
253
+ resolveNext = () => resolve({ type: "event" });
254
+ })
255
+ ]);
256
+ if (raceResult.type === "done") {
257
+ while (events.length > 0) {
258
+ yield events.shift();
259
+ }
260
+ done = true;
261
+ return raceResult.result;
262
+ }
263
+ }
264
+ }
265
+ return await resultPromise;
266
+ }
267
+ };
268
+ }
269
+ function deduplicateContexts(contexts) {
270
+ const map = /* @__PURE__ */ new Map();
271
+ for (const ctx of contexts) {
272
+ const existing = map.get(ctx.file);
273
+ if (!existing || ctx.content.length > existing.content.length) {
274
+ map.set(ctx.file, ctx);
275
+ }
276
+ }
277
+ return Array.from(map.values());
278
+ }
279
+
280
+ exports.createExploreSubagent = createExploreSubagent;