@morphllm/morphsdk 0.2.128 → 0.2.130
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.
- package/dist/{chunk-QADEVECV.js → chunk-23GFM2S4.js} +2 -2
- package/dist/chunk-2YDR2TVC.js +146 -0
- package/dist/chunk-2YDR2TVC.js.map +1 -0
- package/dist/{chunk-KJ2LHKMG.js → chunk-44LNZESZ.js} +2 -2
- package/dist/{chunk-2QEBF4AZ.js → chunk-455KLJVM.js} +2 -2
- package/dist/{chunk-2VG5U65J.js → chunk-4NB7BURA.js} +2 -2
- package/dist/{chunk-E3OFQTVC.js → chunk-5QADKWS4.js} +3 -3
- package/dist/{chunk-XILGON6V.js → chunk-6WIJVB3U.js} +2 -2
- package/dist/{chunk-V57QVD3A.js → chunk-7GDUMJCC.js} +2 -2
- package/dist/{chunk-GXSAAPHL.js → chunk-7RNI2GUH.js} +2 -2
- package/dist/{chunk-TI7HMM55.js → chunk-ED7GLEP4.js} +2 -2
- package/dist/{chunk-TI7HMM55.js.map → chunk-ED7GLEP4.js.map} +1 -1
- package/dist/{chunk-TWF4NJLY.js → chunk-FU67WHCZ.js} +2 -2
- package/dist/{chunk-EYNEGN53.js → chunk-GTNE5WGY.js} +2 -2
- package/dist/{chunk-Z4BQLSRH.js → chunk-H4T4M64U.js} +2 -2
- package/dist/{chunk-2WSTJZ44.js → chunk-JVAEGZYR.js} +2 -2
- package/dist/{chunk-E2ZUOZXR.js → chunk-KQ4ZPKAO.js} +2 -2
- package/dist/{chunk-UTEC7ALJ.js → chunk-L4SVHM57.js} +2 -2
- package/dist/{chunk-PMNJ36FT.js → chunk-OGTOHKOF.js} +2 -2
- package/dist/{chunk-TUJEEBG6.js → chunk-PRTGXOHT.js} +2 -2
- package/dist/{chunk-5K6NULTA.js → chunk-PXNTBHUV.js} +1 -1
- package/dist/{chunk-4TIWAMKP.js → chunk-Q77MJHR7.js} +2 -2
- package/dist/{chunk-UWIR6MF5.js → chunk-SDTV6S54.js} +2 -2
- package/dist/{chunk-BTOLMQSL.js → chunk-UWCEDILY.js} +18 -17
- package/dist/{chunk-BTOLMQSL.js.map → chunk-UWCEDILY.js.map} +1 -1
- package/dist/{chunk-S6PJ5HUJ.js → chunk-V7A2T34J.js} +2 -2
- package/dist/{chunk-RAHZBCQA.js → chunk-XIDCJI2A.js} +2 -2
- package/dist/{client-CNYzlN_6.d.ts → client-Cv2iwTZi.d.ts} +2 -1
- package/dist/client.cjs +83 -12
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.ts +2 -2
- package/dist/client.js +21 -21
- package/dist/edge.cjs +81 -11
- package/dist/edge.cjs.map +1 -1
- package/dist/edge.d.ts +2 -2
- package/dist/edge.js +5 -5
- package/dist/index.cjs +83 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +21 -21
- package/dist/modelrouter/core.cjs +1 -1
- package/dist/modelrouter/core.cjs.map +1 -1
- package/dist/modelrouter/core.js +3 -3
- package/dist/modelrouter/index.cjs +1 -1
- package/dist/modelrouter/index.cjs.map +1 -1
- package/dist/modelrouter/index.js +3 -3
- package/dist/tools/browser/anthropic.cjs +1 -1
- package/dist/tools/browser/anthropic.cjs.map +1 -1
- package/dist/tools/browser/anthropic.js +5 -5
- package/dist/tools/browser/core.cjs +1 -1
- package/dist/tools/browser/core.cjs.map +1 -1
- package/dist/tools/browser/core.js +4 -4
- package/dist/tools/browser/index.cjs +1 -1
- package/dist/tools/browser/index.cjs.map +1 -1
- package/dist/tools/browser/index.js +7 -7
- package/dist/tools/browser/openai.cjs +1 -1
- package/dist/tools/browser/openai.cjs.map +1 -1
- package/dist/tools/browser/openai.js +5 -5
- package/dist/tools/browser/profiles/core.cjs +1 -1
- package/dist/tools/browser/profiles/core.cjs.map +1 -1
- package/dist/tools/browser/profiles/core.js +3 -3
- package/dist/tools/browser/profiles/index.cjs +1 -1
- package/dist/tools/browser/profiles/index.cjs.map +1 -1
- package/dist/tools/browser/profiles/index.js +3 -3
- package/dist/tools/browser/vercel.cjs +1 -1
- package/dist/tools/browser/vercel.cjs.map +1 -1
- package/dist/tools/browser/vercel.js +5 -5
- package/dist/tools/codebase_search/anthropic.cjs +1 -1
- package/dist/tools/codebase_search/anthropic.cjs.map +1 -1
- package/dist/tools/codebase_search/anthropic.js +4 -4
- package/dist/tools/codebase_search/core.cjs +1 -1
- package/dist/tools/codebase_search/core.cjs.map +1 -1
- package/dist/tools/codebase_search/core.js +3 -3
- package/dist/tools/codebase_search/index.cjs +1 -1
- package/dist/tools/codebase_search/index.cjs.map +1 -1
- package/dist/tools/codebase_search/index.js +6 -6
- package/dist/tools/codebase_search/openai.cjs +1 -1
- package/dist/tools/codebase_search/openai.cjs.map +1 -1
- package/dist/tools/codebase_search/openai.js +4 -4
- package/dist/tools/codebase_search/vercel.cjs +1 -1
- package/dist/tools/codebase_search/vercel.cjs.map +1 -1
- package/dist/tools/codebase_search/vercel.js +4 -4
- package/dist/tools/compact/core.cjs +80 -10
- package/dist/tools/compact/core.cjs.map +1 -1
- package/dist/tools/compact/core.d.ts +23 -3
- package/dist/tools/compact/core.js +1 -1
- package/dist/tools/compact/index.cjs +80 -10
- package/dist/tools/compact/index.cjs.map +1 -1
- package/dist/tools/compact/index.d.ts +2 -2
- package/dist/tools/compact/index.js +1 -1
- package/dist/tools/compact/types.cjs.map +1 -1
- package/dist/tools/compact/types.d.ts +59 -8
- package/dist/tools/fastapply/anthropic.cjs +1 -1
- package/dist/tools/fastapply/anthropic.cjs.map +1 -1
- package/dist/tools/fastapply/anthropic.js +4 -4
- package/dist/tools/fastapply/apply.cjs +1 -1
- package/dist/tools/fastapply/apply.cjs.map +1 -1
- package/dist/tools/fastapply/apply.js +2 -2
- package/dist/tools/fastapply/core.cjs +1 -1
- package/dist/tools/fastapply/core.cjs.map +1 -1
- package/dist/tools/fastapply/core.js +3 -3
- package/dist/tools/fastapply/index.cjs +1 -1
- package/dist/tools/fastapply/index.cjs.map +1 -1
- package/dist/tools/fastapply/index.d.ts +1 -1
- package/dist/tools/fastapply/index.js +6 -6
- package/dist/tools/fastapply/openai.cjs +1 -1
- package/dist/tools/fastapply/openai.cjs.map +1 -1
- package/dist/tools/fastapply/openai.js +4 -4
- package/dist/tools/fastapply/vercel.cjs +1 -1
- package/dist/tools/fastapply/vercel.cjs.map +1 -1
- package/dist/tools/fastapply/vercel.d.ts +1 -1
- package/dist/tools/fastapply/vercel.js +4 -4
- package/dist/tools/index.cjs +1 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js +6 -6
- package/dist/tools/utils/resilience.cjs +1 -1
- package/dist/tools/utils/resilience.cjs.map +1 -1
- package/dist/tools/utils/resilience.js +2 -2
- package/dist/tools/warp_grep/agent/runner.cjs +1 -1
- package/dist/tools/warp_grep/agent/runner.cjs.map +1 -1
- package/dist/tools/warp_grep/agent/runner.js +2 -2
- package/dist/tools/warp_grep/anthropic.cjs +1 -1
- package/dist/tools/warp_grep/anthropic.cjs.map +1 -1
- package/dist/tools/warp_grep/anthropic.js +4 -4
- package/dist/tools/warp_grep/client.cjs +1 -1
- package/dist/tools/warp_grep/client.cjs.map +1 -1
- package/dist/tools/warp_grep/client.js +3 -3
- package/dist/tools/warp_grep/gemini.cjs +1 -1
- package/dist/tools/warp_grep/gemini.cjs.map +1 -1
- package/dist/tools/warp_grep/gemini.js +3 -3
- package/dist/tools/warp_grep/index.cjs +1 -1
- package/dist/tools/warp_grep/index.cjs.map +1 -1
- package/dist/tools/warp_grep/index.js +3 -3
- package/dist/tools/warp_grep/openai.cjs +1 -1
- package/dist/tools/warp_grep/openai.cjs.map +1 -1
- package/dist/tools/warp_grep/openai.js +4 -4
- package/dist/tools/warp_grep/vercel.cjs +1 -1
- package/dist/tools/warp_grep/vercel.cjs.map +1 -1
- package/dist/tools/warp_grep/vercel.js +4 -4
- package/dist/version.cjs +1 -1
- package/dist/version.cjs.map +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-J267T54M.js +0 -76
- package/dist/chunk-J267T54M.js.map +0 -1
- package/dist/{chunk-QADEVECV.js.map → chunk-23GFM2S4.js.map} +0 -0
- package/dist/{chunk-KJ2LHKMG.js.map → chunk-44LNZESZ.js.map} +0 -0
- package/dist/{chunk-2QEBF4AZ.js.map → chunk-455KLJVM.js.map} +0 -0
- package/dist/{chunk-2VG5U65J.js.map → chunk-4NB7BURA.js.map} +0 -0
- package/dist/{chunk-E3OFQTVC.js.map → chunk-5QADKWS4.js.map} +0 -0
- package/dist/{chunk-XILGON6V.js.map → chunk-6WIJVB3U.js.map} +0 -0
- package/dist/{chunk-V57QVD3A.js.map → chunk-7GDUMJCC.js.map} +0 -0
- package/dist/{chunk-GXSAAPHL.js.map → chunk-7RNI2GUH.js.map} +0 -0
- package/dist/{chunk-TWF4NJLY.js.map → chunk-FU67WHCZ.js.map} +0 -0
- package/dist/{chunk-EYNEGN53.js.map → chunk-GTNE5WGY.js.map} +0 -0
- package/dist/{chunk-Z4BQLSRH.js.map → chunk-H4T4M64U.js.map} +0 -0
- package/dist/{chunk-2WSTJZ44.js.map → chunk-JVAEGZYR.js.map} +0 -0
- package/dist/{chunk-E2ZUOZXR.js.map → chunk-KQ4ZPKAO.js.map} +0 -0
- package/dist/{chunk-UTEC7ALJ.js.map → chunk-L4SVHM57.js.map} +0 -0
- package/dist/{chunk-PMNJ36FT.js.map → chunk-OGTOHKOF.js.map} +0 -0
- package/dist/{chunk-TUJEEBG6.js.map → chunk-PRTGXOHT.js.map} +0 -0
- package/dist/{chunk-5K6NULTA.js.map → chunk-PXNTBHUV.js.map} +0 -0
- package/dist/{chunk-4TIWAMKP.js.map → chunk-Q77MJHR7.js.map} +0 -0
- package/dist/{chunk-UWIR6MF5.js.map → chunk-SDTV6S54.js.map} +0 -0
- package/dist/{chunk-S6PJ5HUJ.js.map → chunk-V7A2T34J.js.map} +0 -0
- package/dist/{chunk-RAHZBCQA.js.map → chunk-XIDCJI2A.js.map} +0 -0
- package/dist/{vercel-BTSPdTA-.d.ts → vercel-B1GZ_g9N.d.ts} +2 -2
package/dist/client.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import './tools/fastapply/core.js';
|
|
|
3
3
|
import './tools/codebase_search/core.js';
|
|
4
4
|
import './tools/browser/core.js';
|
|
5
5
|
import './tools/warp_grep/client.js';
|
|
6
|
-
export { M as MorphClient, a as MorphClientConfig } from './client-
|
|
6
|
+
export { M as MorphClient, a as MorphClientConfig } from './client-Cv2iwTZi.js';
|
|
7
7
|
import './git/client.js';
|
|
8
8
|
import './tools/compact/core.js';
|
|
9
9
|
import './modelrouter/core.js';
|
|
@@ -24,5 +24,5 @@ import './git/types.js';
|
|
|
24
24
|
import 'isomorphic-git';
|
|
25
25
|
import 'isomorphic-git/http/node';
|
|
26
26
|
import './tools/compact/types.js';
|
|
27
|
-
import 'openai/resources/
|
|
27
|
+
import 'openai/resources/chat/completions';
|
|
28
28
|
import './modelrouter/types.js';
|
package/dist/client.js
CHANGED
|
@@ -1,39 +1,39 @@
|
|
|
1
1
|
import {
|
|
2
2
|
MorphClient
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import "./chunk-
|
|
5
|
-
import "./chunk-
|
|
6
|
-
import "./chunk-
|
|
3
|
+
} from "./chunk-UWCEDILY.js";
|
|
4
|
+
import "./chunk-FU67WHCZ.js";
|
|
5
|
+
import "./chunk-Q77MJHR7.js";
|
|
6
|
+
import "./chunk-7RNI2GUH.js";
|
|
7
7
|
import "./chunk-6DRIR7AI.js";
|
|
8
|
-
import "./chunk-
|
|
8
|
+
import "./chunk-PRTGXOHT.js";
|
|
9
9
|
import "./chunk-NF2QWJDY.js";
|
|
10
10
|
import "./chunk-63VHBANJ.js";
|
|
11
|
-
import "./chunk-
|
|
11
|
+
import "./chunk-23GFM2S4.js";
|
|
12
12
|
import "./chunk-GVGJIXV2.js";
|
|
13
13
|
import "./chunk-2U3RMBXT.js";
|
|
14
14
|
import "./chunk-DKODF3YG.js";
|
|
15
15
|
import "./chunk-QRXG5CAZ.js";
|
|
16
16
|
import "./chunk-VCKJ22DX.js";
|
|
17
|
-
import "./chunk-
|
|
18
|
-
import "./chunk-
|
|
19
|
-
import "./chunk-
|
|
17
|
+
import "./chunk-4NB7BURA.js";
|
|
18
|
+
import "./chunk-XIDCJI2A.js";
|
|
19
|
+
import "./chunk-L4SVHM57.js";
|
|
20
20
|
import "./chunk-YQMPVJ2L.js";
|
|
21
|
-
import "./chunk-
|
|
22
|
-
import "./chunk-
|
|
23
|
-
import "./chunk-
|
|
24
|
-
import "./chunk-
|
|
25
|
-
import "./chunk-
|
|
21
|
+
import "./chunk-455KLJVM.js";
|
|
22
|
+
import "./chunk-V7A2T34J.js";
|
|
23
|
+
import "./chunk-JVAEGZYR.js";
|
|
24
|
+
import "./chunk-OGTOHKOF.js";
|
|
25
|
+
import "./chunk-PXNTBHUV.js";
|
|
26
26
|
import "./chunk-63WE2C5R.js";
|
|
27
|
-
import "./chunk-
|
|
28
|
-
import "./chunk-
|
|
27
|
+
import "./chunk-5QADKWS4.js";
|
|
28
|
+
import "./chunk-44LNZESZ.js";
|
|
29
29
|
import "./chunk-2AMEQAO2.js";
|
|
30
30
|
import "./chunk-YTYCHRQ2.js";
|
|
31
31
|
import "./chunk-2VERUKO2.js";
|
|
32
|
-
import "./chunk-
|
|
33
|
-
import "./chunk-
|
|
34
|
-
import "./chunk-
|
|
35
|
-
import "./chunk-
|
|
36
|
-
import "./chunk-
|
|
32
|
+
import "./chunk-2YDR2TVC.js";
|
|
33
|
+
import "./chunk-GTNE5WGY.js";
|
|
34
|
+
import "./chunk-6WIJVB3U.js";
|
|
35
|
+
import "./chunk-7GDUMJCC.js";
|
|
36
|
+
import "./chunk-ED7GLEP4.js";
|
|
37
37
|
import "./chunk-GZMUGMOZ.js";
|
|
38
38
|
import "./chunk-LE66XCOI.js";
|
|
39
39
|
import "./chunk-PZ5AY32C.js";
|
package/dist/edge.cjs
CHANGED
|
@@ -46,7 +46,7 @@ module.exports = __toCommonJS(edge_exports);
|
|
|
46
46
|
// package.json
|
|
47
47
|
var package_default = {
|
|
48
48
|
name: "@morphllm/morphsdk",
|
|
49
|
-
version: "0.2.
|
|
49
|
+
version: "0.2.130",
|
|
50
50
|
description: "TypeScript SDK and CLI for Morph Fast Apply integration",
|
|
51
51
|
type: "module",
|
|
52
52
|
main: "./dist/index.cjs",
|
|
@@ -695,19 +695,29 @@ var CompactClient = class {
|
|
|
695
695
|
timeout: this.config.timeout,
|
|
696
696
|
maxRetries: this.config.retryConfig?.maxRetries ?? 3
|
|
697
697
|
});
|
|
698
|
-
const
|
|
699
|
-
|
|
698
|
+
const messages = [];
|
|
699
|
+
if (input.prompt) {
|
|
700
|
+
messages.push({
|
|
701
|
+
role: "system",
|
|
702
|
+
content: `The user's next message will be: "${input.prompt}"
|
|
703
|
+
Prioritize keeping context relevant to this query.`
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
if (typeof input.input === "string") {
|
|
707
|
+
messages.push({ role: "user", content: input.input });
|
|
708
|
+
} else {
|
|
709
|
+
messages.push(...input.input);
|
|
710
|
+
}
|
|
700
711
|
if (debug) {
|
|
701
|
-
console.log(`[Compact] Calling ${this.config.morphApiUrl}/v1/
|
|
712
|
+
console.log(`[Compact] Calling ${this.config.morphApiUrl}/v1/chat/completions`);
|
|
702
713
|
console.log(`[Compact] Model: ${input.model || "morph-compactor"}`);
|
|
703
714
|
}
|
|
704
715
|
const startTime = Date.now();
|
|
705
|
-
const response = await client.
|
|
716
|
+
const response = await client.chat.completions.create({
|
|
706
717
|
model: input.model || "morph-compactor",
|
|
707
|
-
|
|
708
|
-
...instructions && { instructions },
|
|
718
|
+
messages,
|
|
709
719
|
...input.temperature != null && { temperature: input.temperature },
|
|
710
|
-
...input.max_output_tokens != null && {
|
|
720
|
+
...input.max_output_tokens != null && { max_tokens: input.max_output_tokens },
|
|
711
721
|
stream: false
|
|
712
722
|
});
|
|
713
723
|
const elapsed = Date.now() - startTime;
|
|
@@ -716,12 +726,72 @@ Prioritize keeping context relevant to this query.` : void 0;
|
|
|
716
726
|
}
|
|
717
727
|
return {
|
|
718
728
|
id: response.id,
|
|
719
|
-
output: response.
|
|
720
|
-
usage: response.usage
|
|
721
|
-
|
|
729
|
+
output: response.choices[0]?.message?.content || "",
|
|
730
|
+
usage: response.usage ? {
|
|
731
|
+
input_tokens: response.usage.prompt_tokens,
|
|
732
|
+
output_tokens: response.usage.completion_tokens,
|
|
733
|
+
total_tokens: response.usage.total_tokens
|
|
734
|
+
} : void 0,
|
|
722
735
|
model: response.model
|
|
723
736
|
};
|
|
724
737
|
}
|
|
738
|
+
/**
|
|
739
|
+
* Compress messages using the direct /v1/compress endpoint.
|
|
740
|
+
* Returns per-message `compacted_line_ranges` showing which lines were removed.
|
|
741
|
+
*
|
|
742
|
+
* @example
|
|
743
|
+
* ```typescript
|
|
744
|
+
* const client = new CompactClient({ morphApiKey: 'sk-...' });
|
|
745
|
+
* const result = await client.compress({
|
|
746
|
+
* messages: [{ role: "user", content: codeFile }],
|
|
747
|
+
* compression_ratio: 0.5,
|
|
748
|
+
* query: "authentication",
|
|
749
|
+
* });
|
|
750
|
+
* for (const msg of result.messages) {
|
|
751
|
+
* for (const r of msg.compacted_line_ranges) {
|
|
752
|
+
* console.log(`Lines ${r.start}-${r.end} removed`);
|
|
753
|
+
* }
|
|
754
|
+
* }
|
|
755
|
+
* ```
|
|
756
|
+
*/
|
|
757
|
+
async compress(input) {
|
|
758
|
+
const apiKey = this.config.morphApiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
|
|
759
|
+
const debug = this.config.debug || false;
|
|
760
|
+
if (!apiKey) {
|
|
761
|
+
throw new Error(
|
|
762
|
+
"Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config."
|
|
763
|
+
);
|
|
764
|
+
}
|
|
765
|
+
const url = `${this.config.morphApiUrl}/v1/compress`;
|
|
766
|
+
if (debug) {
|
|
767
|
+
console.log(`[Compact] Calling ${url}`);
|
|
768
|
+
}
|
|
769
|
+
const startTime = Date.now();
|
|
770
|
+
const response = await fetch(url, {
|
|
771
|
+
method: "POST",
|
|
772
|
+
headers: {
|
|
773
|
+
"Authorization": `Bearer ${apiKey}`,
|
|
774
|
+
"Content-Type": "application/json"
|
|
775
|
+
},
|
|
776
|
+
body: JSON.stringify({
|
|
777
|
+
messages: input.messages,
|
|
778
|
+
compression_ratio: input.compression_ratio ?? 0.5,
|
|
779
|
+
preserve_recent: input.preserve_recent ?? 2,
|
|
780
|
+
query: input.query,
|
|
781
|
+
model: input.model ?? "swe-pruner-0.6b"
|
|
782
|
+
}),
|
|
783
|
+
signal: AbortSignal.timeout(this.config.timeout)
|
|
784
|
+
});
|
|
785
|
+
if (!response.ok) {
|
|
786
|
+
const body = await response.text();
|
|
787
|
+
throw new Error(`Compress API error ${response.status}: ${body}`);
|
|
788
|
+
}
|
|
789
|
+
const data = await response.json();
|
|
790
|
+
if (debug) {
|
|
791
|
+
console.log(`[Compact] compress() done in ${Date.now() - startTime}ms`);
|
|
792
|
+
}
|
|
793
|
+
return data;
|
|
794
|
+
}
|
|
725
795
|
};
|
|
726
796
|
// Annotate the CommonJS export names for ESM import in node:
|
|
727
797
|
0 && (module.exports = {
|
package/dist/edge.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../edge.ts","../package.json","../version.ts","../tools/fastapply/apply.ts","../tools/utils/resilience.ts","../modelrouter/core.ts","../tools/compact/core.ts"],"sourcesContent":["/**\n * Morph SDK - Edge-Compatible Entry Point\n *\n * This module has zero Node.js dependencies and works on:\n * - Cloudflare Workers\n * - Vercel Edge Functions\n * - Deno Deploy\n * - Browser environments\n *\n * For full functionality including file operations, use the main entry point:\n * import { MorphClient } from '@morphllm/morphsdk';\n *\n * @example\n * ```typescript\n * // Edge-compatible usage (Cloudflare Workers, Vercel Edge, etc.)\n * import { applyEdit, OpenAIRouter } from '@morphllm/morphsdk/edge';\n *\n * // Fast Apply\n * const result = await applyEdit({\n * originalCode: 'function hello() { return \"world\"; }',\n * codeEdit: 'function hello() { return \"universe\"; }',\n * instructions: 'Change return value'\n * }, {\n * morphApiKey: env.MORPH_API_KEY\n * });\n *\n * // Model Router\n * const router = new OpenAIRouter({ apiKey: env.MORPH_API_KEY });\n * const { model } = await router.selectModel({ input: 'Write a hello world' });\n * ```\n */\n\n// Export SDK version\nexport { SDK_VERSION } from './version.js';\n\n// Edge-compatible FastApply functions\nexport {\n applyEdit,\n generateUdiff,\n countChanges,\n callMorphAPI,\n} from './tools/fastapply/apply.js';\n\n// Edge-compatible Model Routers\nexport {\n OpenAIRouter,\n AnthropicRouter,\n GeminiRouter,\n RawRouter,\n} from './modelrouter/core.js';\n\n// Export FastApply types\nexport type {\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n EditChanges,\n} from './tools/fastapply/types.js';\n\n// Export Model Router types\nexport type {\n RouterConfig,\n RouterInput,\n RouterResult,\n RawRouterResult,\n ComplexityLevel,\n RouterMode,\n Provider,\n} from './modelrouter/types.js';\n\nexport type {\n RetryConfig,\n} from './tools/utils/resilience.js';\n\n// Edge-compatible Compact tool\nexport { CompactClient } from './tools/compact/core.js';\nexport type { CompactInput, CompactResult, CompactConfig } from './tools/compact/types.js';\n","{\n \"name\": \"@morphllm/morphsdk\",\n \"version\": \"0.2.128\",\n \"description\": \"TypeScript SDK and CLI for Morph Fast Apply integration\",\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./edge\": {\n \"types\": \"./dist/edge.d.ts\",\n \"import\": \"./dist/edge.js\",\n \"require\": \"./dist/edge.cjs\"\n },\n \"./tools/warp-grep\": {\n \"types\": \"./dist/tools/warp_grep/index.d.ts\",\n \"import\": \"./dist/tools/warp_grep/index.js\",\n \"require\": \"./dist/tools/warp_grep/index.cjs\"\n },\n \"./tools/warp-grep/openai\": {\n \"types\": \"./dist/tools/warp_grep/openai.d.ts\",\n \"import\": \"./dist/tools/warp_grep/openai.js\",\n \"require\": \"./dist/tools/warp_grep/openai.cjs\"\n },\n \"./tools/warp-grep/anthropic\": {\n \"types\": \"./dist/tools/warp_grep/anthropic.d.ts\",\n \"import\": \"./dist/tools/warp_grep/anthropic.js\",\n \"require\": \"./dist/tools/warp_grep/anthropic.cjs\"\n },\n \"./tools/warp-grep/vercel\": {\n \"types\": \"./dist/tools/warp_grep/vercel.d.ts\",\n \"import\": \"./dist/tools/warp_grep/vercel.js\",\n \"require\": \"./dist/tools/warp_grep/vercel.cjs\"\n },\n \"./tools/warp-grep/client\": {\n \"types\": \"./dist/tools/warp_grep/client.d.ts\",\n \"import\": \"./dist/tools/warp_grep/client.js\",\n \"require\": \"./dist/tools/warp_grep/client.cjs\"\n },\n \"./tools/warp-grep/gemini\": {\n \"types\": \"./dist/tools/warp_grep/gemini.d.ts\",\n \"import\": \"./dist/tools/warp_grep/gemini.js\",\n \"require\": \"./dist/tools/warp_grep/gemini.cjs\"\n },\n \"./tools/warp-grep/harness\": {\n \"types\": \"./dist/tools/warp_grep/harness.d.ts\",\n \"import\": \"./dist/tools/warp_grep/harness.js\",\n \"require\": \"./dist/tools/warp_grep/harness.cjs\"\n },\n \"./tools/fastapply\": {\n \"types\": \"./dist/tools/fastapply/index.d.ts\",\n \"import\": \"./dist/tools/fastapply/index.js\",\n \"require\": \"./dist/tools/fastapply/index.cjs\"\n },\n \"./tools/fastapply/anthropic\": {\n \"types\": \"./dist/tools/fastapply/anthropic.d.ts\",\n \"import\": \"./dist/tools/fastapply/anthropic.js\",\n \"require\": \"./dist/tools/fastapply/anthropic.cjs\"\n },\n \"./tools/fastapply/openai\": {\n \"types\": \"./dist/tools/fastapply/openai.d.ts\",\n \"import\": \"./dist/tools/fastapply/openai.js\",\n \"require\": \"./dist/tools/fastapply/openai.cjs\"\n },\n \"./tools/fastapply/vercel\": {\n \"types\": \"./dist/tools/fastapply/vercel.d.ts\",\n \"import\": \"./dist/tools/fastapply/vercel.js\",\n \"require\": \"./dist/tools/fastapply/vercel.cjs\"\n },\n \"./tools/codebase-search\": {\n \"types\": \"./dist/tools/codebase_search/index.d.ts\",\n \"import\": \"./dist/tools/codebase_search/index.js\",\n \"require\": \"./dist/tools/codebase_search/index.cjs\"\n },\n \"./tools/codebase-search/anthropic\": {\n \"types\": \"./dist/tools/codebase_search/anthropic.d.ts\",\n \"import\": \"./dist/tools/codebase_search/anthropic.js\",\n \"require\": \"./dist/tools/codebase_search/anthropic.cjs\"\n },\n \"./tools/codebase-search/openai\": {\n \"types\": \"./dist/tools/codebase_search/openai.d.ts\",\n \"import\": \"./dist/tools/codebase_search/openai.js\",\n \"require\": \"./dist/tools/codebase_search/openai.cjs\"\n },\n \"./tools/codebase-search/vercel\": {\n \"types\": \"./dist/tools/codebase_search/vercel.d.ts\",\n \"import\": \"./dist/tools/codebase_search/vercel.js\",\n \"require\": \"./dist/tools/codebase_search/vercel.cjs\"\n },\n \"./tools/git\": {\n \"types\": \"./dist/git/index.d.ts\",\n \"import\": \"./dist/git/index.js\",\n \"require\": \"./dist/git/index.cjs\"\n },\n \"./tools/browser\": {\n \"types\": \"./dist/tools/browser/index.d.ts\",\n \"import\": \"./dist/tools/browser/index.js\",\n \"require\": \"./dist/tools/browser/index.cjs\"\n },\n \"./tools/browser/anthropic\": {\n \"types\": \"./dist/tools/browser/anthropic.d.ts\",\n \"import\": \"./dist/tools/browser/anthropic.js\",\n \"require\": \"./dist/tools/browser/anthropic.cjs\"\n },\n \"./tools/browser/openai\": {\n \"types\": \"./dist/tools/browser/openai.d.ts\",\n \"import\": \"./dist/tools/browser/openai.js\",\n \"require\": \"./dist/tools/browser/openai.cjs\"\n },\n \"./tools/browser/vercel\": {\n \"types\": \"./dist/tools/browser/vercel.d.ts\",\n \"import\": \"./dist/tools/browser/vercel.js\",\n \"require\": \"./dist/tools/browser/vercel.cjs\"\n },\n \"./tools/browser/profiles\": {\n \"types\": \"./dist/tools/browser/profiles/index.d.ts\",\n \"import\": \"./dist/tools/browser/profiles/index.js\",\n \"require\": \"./dist/tools/browser/profiles/index.cjs\"\n },\n \"./modelrouter\": {\n \"types\": \"./dist/modelrouter/index.d.ts\",\n \"import\": \"./dist/modelrouter/index.js\",\n \"require\": \"./dist/modelrouter/index.cjs\"\n },\n \"./tools/compact\": {\n \"types\": \"./dist/tools/compact/index.d.ts\",\n \"import\": \"./dist/tools/compact/index.js\",\n \"require\": \"./dist/tools/compact/index.cjs\"\n }\n },\n \"files\": [\n \"dist/**/*.js\",\n \"dist/**/*.cjs\",\n \"dist/**/*.d.ts\",\n \"dist/**/*.map\",\n \"!dist/**/__tests__/**\",\n \"!dist/**/*.test.*\"\n ],\n \"scripts\": {\n \"build\": \"tsup version.ts index.ts edge.ts client.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/codebase_search/index.ts tools/codebase_search/core.ts tools/codebase_search/types.ts tools/codebase_search/prompts.ts tools/codebase_search/anthropic.ts tools/codebase_search/openai.ts tools/codebase_search/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts git/index.ts git/client.ts git/config.ts git/types.ts tools/browser/index.ts tools/browser/core.ts tools/browser/types.ts tools/browser/prompts.ts tools/browser/anthropic.ts tools/browser/openai.ts tools/browser/vercel.ts tools/browser/live.ts tools/browser/errors.ts tools/browser/profiles/index.ts tools/browser/profiles/core.ts tools/browser/profiles/types.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve\",\n \"prepare\": \"npm run build\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest watch\",\n \"test:anthropic\": \"vitest run anthropic\",\n \"test:openai\": \"vitest run openai\",\n \"test:vercel\": \"vitest run vercel\",\n \"test:git\": \"vitest run git\",\n \"test:browser\": \"vitest run browser\",\n \"test:agent\": \"npx tsx tests/fullAgentTest.ts\",\n \"test:integration\": \"npx tsx tests/fullIntegrationTest.ts\",\n \"release:patch\": \"npm version patch && npm publish\",\n \"release:minor\": \"npm version minor && npm publish\",\n \"release:major\": \"npm version major && npm publish\"\n },\n \"keywords\": [\n \"morph\",\n \"fast-apply\",\n \"cli\",\n \"sdk\",\n \"edit-file\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@vscode/ripgrep\": \"^1.17.0\",\n \"ai\": \"^5.0.0\",\n \"diff\": \"^7.0.0\",\n \"isomorphic-git\": \"^1.25.10\",\n \"openai\": \"^4.52.7\",\n \"zod\": \"^3.23.8\"\n },\n \"devDependencies\": {\n \"@ai-sdk/anthropic\": \"^1.0.9\",\n \"@ai-sdk/openai\": \"^2.0.35\",\n \"@anthropic-ai/sdk\": \"^0.30.1\",\n \"@google/generative-ai\": \"^0.24.1\",\n \"@types/diff\": \"^7.0.2\",\n \"@types/node\": \"^20.14.10\",\n \"@typescript-eslint/eslint-plugin\": \"^7.18.0\",\n \"@typescript-eslint/parser\": \"^7.18.0\",\n \"dotenv\": \"^16.4.5\",\n \"eslint\": \"^8.57.0\",\n \"shx\": \"^0.3.4\",\n \"tsup\": \"^8.5.0\",\n \"tsx\": \"^4.16.2\",\n \"typescript\": \"^5.5.4\",\n \"vitest\": \"^2.1.6\"\n },\n \"peerDependencies\": {\n \"@anthropic-ai/sdk\": \">=0.25.0\",\n \"@google/generative-ai\": \">=0.21.0\",\n \"ai\": \">=5.0.0\",\n \"zod\": \">=3.23.0\"\n },\n \"peerDependenciesMeta\": {\n \"@anthropic-ai/sdk\": {\n \"optional\": true\n },\n \"@google/generative-ai\": {\n \"optional\": true\n },\n \"ai\": {\n \"optional\": true\n },\n \"zod\": {\n \"optional\": true\n }\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","import pkg from './package.json' with { type: 'json' };\nexport const SDK_VERSION: string = pkg.version;\n","/**\n * Edge-compatible code application API\n *\n * This module works on:\n * - Node.js\n * - Cloudflare Workers\n * - Vercel Edge Functions\n * - Deno Deploy\n * - Browser environments\n *\n * For file-based operations, use executeEditFile from core.ts\n */\n\nimport { createTwoFilesPatch } from 'diff';\nimport OpenAI from 'openai';\nimport { SDK_VERSION } from '../../version.js';\nimport type {\n EditChanges,\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n} from './types.js';\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\nconst DEFAULT_TIMEOUT = 30000;\n\n/**\n * Generate a unified diff between two strings\n */\nexport function generateUdiff(\n original: string,\n modified: string,\n filepath: string\n): string {\n return createTwoFilesPatch(\n filepath,\n filepath,\n original,\n modified,\n 'Original',\n 'Modified'\n );\n}\n\n/**\n * Count changes from a unified diff\n */\nexport function countChanges(original: string, modified: string): EditChanges {\n const diff = generateUdiff(original, modified, 'file');\n const lines = diff.split('\\n');\n\n let linesAdded = 0;\n let linesRemoved = 0;\n\n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n linesAdded++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n linesRemoved++;\n }\n }\n\n const linesModified = Math.min(linesAdded, linesRemoved);\n\n return {\n linesAdded: linesAdded - linesModified,\n linesRemoved: linesRemoved - linesModified,\n linesModified,\n };\n}\n\n/**\n * Call Morph Apply API to merge code edits\n * Uses OpenAI SDK for reliable connection handling, retries, and timeouts\n */\nexport async function callMorphAPI(\n originalCode: string,\n codeEdit: string,\n instructions: string,\n filepath: string,\n config: ApplyEditConfig\n): Promise<{ content: string; completionId?: string }> {\n const apiKey = config.morphApiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n const apiUrl = config.morphApiUrl || DEFAULT_API_URL;\n const timeout = config.timeout || DEFAULT_TIMEOUT;\n const debug = config.debug || false;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n\n // Format message with XML tags as per Morph Fast Apply spec\n const message = `<instruction>${instructions}</instruction>\\n<code>${originalCode}</code>\\n<update>${codeEdit}</update>`;\n\n if (debug) {\n console.log(`[FastApply] Calling ${apiUrl}/v1/chat/completions`);\n console.log(`[FastApply] File: ${filepath}, Instructions: ${instructions.slice(0, 60)}...`);\n console.log(`[FastApply] Original: ${originalCode.length} chars, Edit: ${codeEdit.length} chars`);\n }\n\n const startTime = Date.now();\n\n const client = new OpenAI({\n apiKey,\n baseURL: `${apiUrl}/v1`,\n timeout,\n maxRetries: config.retryConfig?.maxRetries ?? 3,\n defaultHeaders: { 'X-Morph-SDK-Version': SDK_VERSION },\n });\n\n const completion = await client.chat.completions.create({\n model: 'morph-v3-fast',\n messages: [{ role: 'user', content: message }],\n });\n\n const content = completion.choices[0]?.message?.content;\n if (!content) {\n throw new Error('Morph API returned empty response');\n }\n\n const elapsed = Date.now() - startTime;\n\n if (debug) {\n console.log(`[FastApply] Success in ${elapsed}ms, merged: ${content.length} chars`);\n }\n\n return { content, completionId: completion.id };\n}\n\n/**\n * Apply an edit to code directly without file I/O\n *\n * This is the edge-compatible code-in/code-out API that accepts code content directly\n * and returns the merged result without reading or writing any files.\n *\n * Works on Cloudflare Workers, Vercel Edge Functions, Deno, and browsers.\n *\n * @param input - Code and edit parameters\n * @param config - Optional configuration\n * @returns Result with merged code\n *\n * @example\n * ```typescript\n * import { applyEdit } from '@morphllm/morphsdk';\n *\n * const result = await applyEdit({\n * originalCode: fs.readFileSync('file.ts', 'utf-8'),\n * codeEdit: '// ... existing code ...\\nconst newVar = 42;\\n// ... existing code ...',\n * instructions: 'Add a new variable',\n * filepath: 'file.ts' // optional, for udiff context\n * });\n *\n * if (result.success) {\n * fs.writeFileSync('file.ts', result.mergedCode);\n * }\n * ```\n */\nexport async function applyEdit(\n input: ApplyEditInput,\n config: ApplyEditConfig = {}\n): Promise<ApplyEditResult> {\n const debug = config.debug || false;\n const filepath = input.filepath || 'file';\n\n try {\n if (debug) {\n console.log(`[FastApply] Applying edit to code (${input.originalCode.length} chars)`);\n }\n\n const { content: mergedCode, completionId } = await callMorphAPI(\n input.originalCode,\n input.codeEdit,\n input.instructions,\n filepath,\n config\n );\n\n const udiff = config.generateUdiff !== false\n ? generateUdiff(input.originalCode, mergedCode, filepath)\n : undefined;\n\n const changes = countChanges(input.originalCode, mergedCode);\n\n return {\n success: true,\n mergedCode,\n udiff,\n changes,\n completionId,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n if (debug) console.error(`[FastApply] Error: ${errorMessage}`);\n\n return {\n success: false,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\n}\n","/**\n * Resilience utilities for retry logic and timeout handling\n */\n\nimport { SDK_VERSION } from '../../version.js';\n\nexport interface RetryConfig {\n maxRetries?: number; // Default: 3\n initialDelay?: number; // Default: 1000ms\n maxDelay?: number; // Default: 30000ms\n backoffMultiplier?: number; // Default: 2\n retryableErrors?: string[]; // Default: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND']\n onRetry?: (attempt: number, error: Error) => void;\n}\n\nconst DEFAULT_RETRY_CONFIG: Required<Omit<RetryConfig, 'onRetry'>> = {\n maxRetries: 3,\n initialDelay: 1000,\n maxDelay: 30000,\n backoffMultiplier: 2,\n retryableErrors: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'],\n};\n\n/**\n * Retry a fetch request with exponential backoff\n * \n * @param url - Request URL\n * @param options - Fetch options\n * @param retryConfig - Retry configuration\n * @returns Response from fetch\n * \n * @example\n * ```typescript\n * const response = await fetchWithRetry(\n * 'https://api.example.com/data',\n * { method: 'POST', body: JSON.stringify(data) },\n * { maxRetries: 5, initialDelay: 500 }\n * );\n * ```\n */\nexport async function fetchWithRetry(\n url: string,\n options: RequestInit,\n retryConfig: RetryConfig = {}\n): Promise<Response> {\n const {\n maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,\n initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,\n maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,\n backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,\n retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,\n onRetry,\n } = retryConfig;\n\n let lastError: Error | null = null;\n let delay = initialDelay;\n\n // Inject SDK version header (caller-provided headers can override)\n options = { ...options, headers: { 'X-Morph-SDK-Version': SDK_VERSION, ...options.headers } };\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n \n // Retry on 429 (rate limit) or 503 (service unavailable)\n if (response.status === 429 || response.status === 503) {\n if (attempt < maxRetries) {\n // Check for Retry-After header\n const retryAfter = response.headers.get('Retry-After');\n const waitTime = retryAfter \n ? parseInt(retryAfter) * 1000 \n : Math.min(delay, maxDelay);\n \n const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);\n if (onRetry) {\n onRetry(attempt + 1, error);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n continue;\n }\n }\n\n return response;\n } catch (error) {\n lastError = error as Error;\n \n // Check if error is retryable\n const isRetryable = retryableErrors.some(errType => \n lastError?.message?.includes(errType)\n );\n\n if (!isRetryable || attempt === maxRetries) {\n throw lastError;\n }\n\n // Exponential backoff\n const waitTime = Math.min(delay, maxDelay);\n if (onRetry) {\n onRetry(attempt + 1, lastError);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n }\n }\n\n throw lastError || new Error('Max retries exceeded');\n}\n\n/**\n * Add timeout to any promise\n * \n * @param promise - Promise to wrap with timeout\n * @param timeoutMs - Timeout in milliseconds\n * @param errorMessage - Optional custom error message\n * @returns Promise that rejects if timeout is reached\n * \n * @example\n * ```typescript\n * const result = await withTimeout(\n * fetchData(),\n * 5000,\n * 'Data fetch timed out'\n * );\n * ```\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n errorMessage?: string\n): Promise<T> {\n let timeoutId: NodeJS.Timeout | number;\n \n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n\n try {\n const result = await Promise.race([promise, timeoutPromise]);\n clearTimeout(timeoutId!);\n return result;\n } catch (error) {\n clearTimeout(timeoutId!);\n throw error;\n }\n}\n\n/**\n * Sleep for specified milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Unified error type for all tools\n */\nexport class MorphError extends Error {\n constructor(\n message: string,\n public code: string,\n public statusCode?: number,\n public retryable: boolean = false\n ) {\n super(message);\n this.name = 'MorphError';\n }\n}\n\n\n","/**\n * Core implementation for intelligent model routing\n */\n\nimport { fetchWithRetry, withTimeout } from '../tools/utils/resilience.js';\nimport type {\n RouterConfig,\n RouterInput,\n RouterResult,\n RawRouterResult,\n ComplexityLevel,\n RouterMode,\n Provider,\n} from './types.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: 'https://api.morphllm.com',\n timeout: 5000, // 5 seconds (responses typically <500ms)\n debug: false,\n};\n\nabstract class BaseRouter {\n protected config: Required<Omit<RouterConfig, 'apiKey' | 'retryConfig'>> & Pick<RouterConfig, 'apiKey' | 'retryConfig'>;\n protected provider: Provider;\n\n constructor(provider: Provider, config: RouterConfig = {}) {\n this.provider = provider;\n this.config = {\n apiKey: config.apiKey,\n apiUrl: config.apiUrl || DEFAULT_CONFIG.apiUrl,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n debug: config.debug || DEFAULT_CONFIG.debug,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Select the optimal model for a given input and mode\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/${this.provider}`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Requesting ${this.provider} model selection:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model: string; confidence?: number } = await response.json();\n\n const result: RouterResult = {\n model: apiResult.model,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Selected model: ${apiResult.model}, Confidence: ${apiResult.confidence?.toFixed(3)}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[ModelRouter] Error selecting model:`, error);\n }\n throw error;\n }\n }\n}\n\n/**\n * OpenAI model router for GPT-5 series\n */\nexport class OpenAIRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('openai', config);\n }\n\n /**\n * Select optimal GPT-5 model\n * \n * @param input - User input and mode\n * @returns Selected model name (gpt-5-mini | gpt-5-low | gpt-5-medium | gpt-5-high)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Anthropic model router for Claude 4.5 series\n */\nexport class AnthropicRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('anthropic', config);\n }\n\n /**\n * Select optimal Claude model\n * \n * @param input - User input and mode\n * @returns Selected model name (claude-4.5-haiku | claude-4.5-sonnet)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Google Gemini model router\n */\nexport class GeminiRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('gemini', config);\n }\n\n /**\n * Select optimal Gemini model\n * \n * @param input - User input and mode\n * @returns Selected model name (gemini-2.5-flash | gemini-2.5-pro)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Raw difficulty classification router (no provider-specific mapping)\n */\nexport class RawRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('raw' as Provider, config);\n }\n\n /**\n * Get raw difficulty classification\n * \n * @param input - User input and mode\n * @returns Raw difficulty (easy | medium | hard | needs_info)\n */\n async classify(input: RouterInput): Promise<RawRouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/raw`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Requesting raw difficulty classification:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model?: string; difficulty?: string; confidence?: number } = await response.json();\n\n // Support both 'model' and 'difficulty' fields for compatibility\n // Empty string from API means \"medium\" difficulty (API bug workaround)\n let difficulty: ComplexityLevel;\n if (apiResult.difficulty === '') {\n difficulty = 'medium';\n } else {\n difficulty = (apiResult.difficulty || apiResult.model) as ComplexityLevel;\n }\n\n const result: RawRouterResult = {\n difficulty,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Classified as: ${difficulty}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[RawRouter] Error classifying:`, error);\n }\n throw error;\n }\n }\n}\n","/**\n * Core implementation of Morph Compact\n *\n * Uses the OpenAI Responses API to compact conversation context\n * via the Morph compactor model.\n */\n\nimport OpenAI from 'openai';\nimport type { CompactConfig, CompactInput, CompactResult } from './types.js';\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\nconst DEFAULT_TIMEOUT = 120000;\n\n/**\n * CompactClient for programmatic context compaction\n */\nexport class CompactClient {\n private config: Required<Pick<CompactConfig, 'morphApiUrl' | 'timeout'>> & CompactConfig;\n\n constructor(config: CompactConfig = {}) {\n this.config = {\n morphApiUrl: DEFAULT_API_URL,\n timeout: DEFAULT_TIMEOUT,\n ...config,\n };\n }\n\n /**\n * Compact conversation context using Morph compactor\n *\n * @param input - Compact parameters including input content and optional prompt\n * @returns Compact result with compacted output and usage stats\n *\n * @example\n * ```typescript\n * const client = new CompactClient({ morphApiKey: 'sk-...' });\n * const result = await client.compact({\n * input: 'Long conversation context to compact...',\n * prompt: 'Focus on the code review feedback',\n * });\n * console.log(result.output);\n * ```\n */\n async compact(input: CompactInput): Promise<CompactResult> {\n const apiKey = this.config.morphApiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n const debug = this.config.debug || false;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n\n const client = new OpenAI({\n apiKey,\n baseURL: `${this.config.morphApiUrl}/v1`,\n timeout: this.config.timeout,\n maxRetries: this.config.retryConfig?.maxRetries ?? 3,\n });\n\n const instructions = input.prompt\n ? `The user's next message will be: \"${input.prompt}\"\\nPrioritize keeping context relevant to this query.`\n : undefined;\n\n if (debug) {\n console.log(`[Compact] Calling ${this.config.morphApiUrl}/v1/responses`);\n console.log(`[Compact] Model: ${input.model || 'morph-compactor'}`);\n }\n\n const startTime = Date.now();\n\n const response = await client.responses.create({\n model: input.model || 'morph-compactor',\n input: input.input as any,\n ...(instructions && { instructions }),\n ...(input.temperature != null && { temperature: input.temperature }),\n ...(input.max_output_tokens != null && { max_output_tokens: input.max_output_tokens }),\n stream: false,\n });\n\n const elapsed = Date.now() - startTime;\n\n if (debug) {\n console.log(`[Compact] Success in ${elapsed}ms`);\n }\n\n return {\n id: response.id,\n output: response.output as any,\n usage: response.usage as any,\n status: response.status ?? 'completed',\n model: response.model,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAA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,MACjB,OAAO,SAAS;AAAA,MAChB,QAAQ,SAAS,UAAU;AAAA,MAC3B,OAAO,SAAS;AAAA,IAClB;AAAA,EACF;AACF;","names":["OpenAI","import_openai","DEFAULT_API_URL","DEFAULT_TIMEOUT","OpenAI"]}
|
|
1
|
+
{"version":3,"sources":["../edge.ts","../package.json","../version.ts","../tools/fastapply/apply.ts","../tools/utils/resilience.ts","../modelrouter/core.ts","../tools/compact/core.ts"],"sourcesContent":["/**\n * Morph SDK - Edge-Compatible Entry Point\n *\n * This module has zero Node.js dependencies and works on:\n * - Cloudflare Workers\n * - Vercel Edge Functions\n * - Deno Deploy\n * - Browser environments\n *\n * For full functionality including file operations, use the main entry point:\n * import { MorphClient } from '@morphllm/morphsdk';\n *\n * @example\n * ```typescript\n * // Edge-compatible usage (Cloudflare Workers, Vercel Edge, etc.)\n * import { applyEdit, OpenAIRouter } from '@morphllm/morphsdk/edge';\n *\n * // Fast Apply\n * const result = await applyEdit({\n * originalCode: 'function hello() { return \"world\"; }',\n * codeEdit: 'function hello() { return \"universe\"; }',\n * instructions: 'Change return value'\n * }, {\n * morphApiKey: env.MORPH_API_KEY\n * });\n *\n * // Model Router\n * const router = new OpenAIRouter({ apiKey: env.MORPH_API_KEY });\n * const { model } = await router.selectModel({ input: 'Write a hello world' });\n * ```\n */\n\n// Export SDK version\nexport { SDK_VERSION } from './version.js';\n\n// Edge-compatible FastApply functions\nexport {\n applyEdit,\n generateUdiff,\n countChanges,\n callMorphAPI,\n} from './tools/fastapply/apply.js';\n\n// Edge-compatible Model Routers\nexport {\n OpenAIRouter,\n AnthropicRouter,\n GeminiRouter,\n RawRouter,\n} from './modelrouter/core.js';\n\n// Export FastApply types\nexport type {\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n EditChanges,\n} from './tools/fastapply/types.js';\n\n// Export Model Router types\nexport type {\n RouterConfig,\n RouterInput,\n RouterResult,\n RawRouterResult,\n ComplexityLevel,\n RouterMode,\n Provider,\n} from './modelrouter/types.js';\n\nexport type {\n RetryConfig,\n} from './tools/utils/resilience.js';\n\n// Edge-compatible Compact tool\nexport { CompactClient } from './tools/compact/core.js';\nexport type {\n CompactInput, CompactResult, CompactConfig,\n CompressInput, CompressResult, CompressMessage, CompactedRange,\n} from './tools/compact/types.js';\n","{\n \"name\": \"@morphllm/morphsdk\",\n \"version\": \"0.2.130\",\n \"description\": \"TypeScript SDK and CLI for Morph Fast Apply integration\",\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./edge\": {\n \"types\": \"./dist/edge.d.ts\",\n \"import\": \"./dist/edge.js\",\n \"require\": \"./dist/edge.cjs\"\n },\n \"./tools/warp-grep\": {\n \"types\": \"./dist/tools/warp_grep/index.d.ts\",\n \"import\": \"./dist/tools/warp_grep/index.js\",\n \"require\": \"./dist/tools/warp_grep/index.cjs\"\n },\n \"./tools/warp-grep/openai\": {\n \"types\": \"./dist/tools/warp_grep/openai.d.ts\",\n \"import\": \"./dist/tools/warp_grep/openai.js\",\n \"require\": \"./dist/tools/warp_grep/openai.cjs\"\n },\n \"./tools/warp-grep/anthropic\": {\n \"types\": \"./dist/tools/warp_grep/anthropic.d.ts\",\n \"import\": \"./dist/tools/warp_grep/anthropic.js\",\n \"require\": \"./dist/tools/warp_grep/anthropic.cjs\"\n },\n \"./tools/warp-grep/vercel\": {\n \"types\": \"./dist/tools/warp_grep/vercel.d.ts\",\n \"import\": \"./dist/tools/warp_grep/vercel.js\",\n \"require\": \"./dist/tools/warp_grep/vercel.cjs\"\n },\n \"./tools/warp-grep/client\": {\n \"types\": \"./dist/tools/warp_grep/client.d.ts\",\n \"import\": \"./dist/tools/warp_grep/client.js\",\n \"require\": \"./dist/tools/warp_grep/client.cjs\"\n },\n \"./tools/warp-grep/gemini\": {\n \"types\": \"./dist/tools/warp_grep/gemini.d.ts\",\n \"import\": \"./dist/tools/warp_grep/gemini.js\",\n \"require\": \"./dist/tools/warp_grep/gemini.cjs\"\n },\n \"./tools/warp-grep/harness\": {\n \"types\": \"./dist/tools/warp_grep/harness.d.ts\",\n \"import\": \"./dist/tools/warp_grep/harness.js\",\n \"require\": \"./dist/tools/warp_grep/harness.cjs\"\n },\n \"./tools/fastapply\": {\n \"types\": \"./dist/tools/fastapply/index.d.ts\",\n \"import\": \"./dist/tools/fastapply/index.js\",\n \"require\": \"./dist/tools/fastapply/index.cjs\"\n },\n \"./tools/fastapply/anthropic\": {\n \"types\": \"./dist/tools/fastapply/anthropic.d.ts\",\n \"import\": \"./dist/tools/fastapply/anthropic.js\",\n \"require\": \"./dist/tools/fastapply/anthropic.cjs\"\n },\n \"./tools/fastapply/openai\": {\n \"types\": \"./dist/tools/fastapply/openai.d.ts\",\n \"import\": \"./dist/tools/fastapply/openai.js\",\n \"require\": \"./dist/tools/fastapply/openai.cjs\"\n },\n \"./tools/fastapply/vercel\": {\n \"types\": \"./dist/tools/fastapply/vercel.d.ts\",\n \"import\": \"./dist/tools/fastapply/vercel.js\",\n \"require\": \"./dist/tools/fastapply/vercel.cjs\"\n },\n \"./tools/codebase-search\": {\n \"types\": \"./dist/tools/codebase_search/index.d.ts\",\n \"import\": \"./dist/tools/codebase_search/index.js\",\n \"require\": \"./dist/tools/codebase_search/index.cjs\"\n },\n \"./tools/codebase-search/anthropic\": {\n \"types\": \"./dist/tools/codebase_search/anthropic.d.ts\",\n \"import\": \"./dist/tools/codebase_search/anthropic.js\",\n \"require\": \"./dist/tools/codebase_search/anthropic.cjs\"\n },\n \"./tools/codebase-search/openai\": {\n \"types\": \"./dist/tools/codebase_search/openai.d.ts\",\n \"import\": \"./dist/tools/codebase_search/openai.js\",\n \"require\": \"./dist/tools/codebase_search/openai.cjs\"\n },\n \"./tools/codebase-search/vercel\": {\n \"types\": \"./dist/tools/codebase_search/vercel.d.ts\",\n \"import\": \"./dist/tools/codebase_search/vercel.js\",\n \"require\": \"./dist/tools/codebase_search/vercel.cjs\"\n },\n \"./tools/git\": {\n \"types\": \"./dist/git/index.d.ts\",\n \"import\": \"./dist/git/index.js\",\n \"require\": \"./dist/git/index.cjs\"\n },\n \"./tools/browser\": {\n \"types\": \"./dist/tools/browser/index.d.ts\",\n \"import\": \"./dist/tools/browser/index.js\",\n \"require\": \"./dist/tools/browser/index.cjs\"\n },\n \"./tools/browser/anthropic\": {\n \"types\": \"./dist/tools/browser/anthropic.d.ts\",\n \"import\": \"./dist/tools/browser/anthropic.js\",\n \"require\": \"./dist/tools/browser/anthropic.cjs\"\n },\n \"./tools/browser/openai\": {\n \"types\": \"./dist/tools/browser/openai.d.ts\",\n \"import\": \"./dist/tools/browser/openai.js\",\n \"require\": \"./dist/tools/browser/openai.cjs\"\n },\n \"./tools/browser/vercel\": {\n \"types\": \"./dist/tools/browser/vercel.d.ts\",\n \"import\": \"./dist/tools/browser/vercel.js\",\n \"require\": \"./dist/tools/browser/vercel.cjs\"\n },\n \"./tools/browser/profiles\": {\n \"types\": \"./dist/tools/browser/profiles/index.d.ts\",\n \"import\": \"./dist/tools/browser/profiles/index.js\",\n \"require\": \"./dist/tools/browser/profiles/index.cjs\"\n },\n \"./modelrouter\": {\n \"types\": \"./dist/modelrouter/index.d.ts\",\n \"import\": \"./dist/modelrouter/index.js\",\n \"require\": \"./dist/modelrouter/index.cjs\"\n },\n \"./tools/compact\": {\n \"types\": \"./dist/tools/compact/index.d.ts\",\n \"import\": \"./dist/tools/compact/index.js\",\n \"require\": \"./dist/tools/compact/index.cjs\"\n }\n },\n \"files\": [\n \"dist/**/*.js\",\n \"dist/**/*.cjs\",\n \"dist/**/*.d.ts\",\n \"dist/**/*.map\",\n \"!dist/**/__tests__/**\",\n \"!dist/**/*.test.*\"\n ],\n \"scripts\": {\n \"build\": \"tsup version.ts index.ts edge.ts client.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/codebase_search/index.ts tools/codebase_search/core.ts tools/codebase_search/types.ts tools/codebase_search/prompts.ts tools/codebase_search/anthropic.ts tools/codebase_search/openai.ts tools/codebase_search/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts git/index.ts git/client.ts git/config.ts git/types.ts tools/browser/index.ts tools/browser/core.ts tools/browser/types.ts tools/browser/prompts.ts tools/browser/anthropic.ts tools/browser/openai.ts tools/browser/vercel.ts tools/browser/live.ts tools/browser/errors.ts tools/browser/profiles/index.ts tools/browser/profiles/core.ts tools/browser/profiles/types.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve\",\n \"prepare\": \"npm run build\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest watch\",\n \"test:anthropic\": \"vitest run anthropic\",\n \"test:openai\": \"vitest run openai\",\n \"test:vercel\": \"vitest run vercel\",\n \"test:git\": \"vitest run git\",\n \"test:browser\": \"vitest run browser\",\n \"test:agent\": \"npx tsx tests/fullAgentTest.ts\",\n \"test:integration\": \"npx tsx tests/fullIntegrationTest.ts\",\n \"release:patch\": \"npm version patch && npm publish\",\n \"release:minor\": \"npm version minor && npm publish\",\n \"release:major\": \"npm version major && npm publish\"\n },\n \"keywords\": [\n \"morph\",\n \"fast-apply\",\n \"cli\",\n \"sdk\",\n \"edit-file\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@vscode/ripgrep\": \"^1.17.0\",\n \"ai\": \"^5.0.0\",\n \"diff\": \"^7.0.0\",\n \"isomorphic-git\": \"^1.25.10\",\n \"openai\": \"^4.52.7\",\n \"zod\": \"^3.23.8\"\n },\n \"devDependencies\": {\n \"@ai-sdk/anthropic\": \"^1.0.9\",\n \"@ai-sdk/openai\": \"^2.0.35\",\n \"@anthropic-ai/sdk\": \"^0.30.1\",\n \"@google/generative-ai\": \"^0.24.1\",\n \"@types/diff\": \"^7.0.2\",\n \"@types/node\": \"^20.14.10\",\n \"@typescript-eslint/eslint-plugin\": \"^7.18.0\",\n \"@typescript-eslint/parser\": \"^7.18.0\",\n \"dotenv\": \"^16.4.5\",\n \"eslint\": \"^8.57.0\",\n \"shx\": \"^0.3.4\",\n \"tsup\": \"^8.5.0\",\n \"tsx\": \"^4.16.2\",\n \"typescript\": \"^5.5.4\",\n \"vitest\": \"^2.1.6\"\n },\n \"peerDependencies\": {\n \"@anthropic-ai/sdk\": \">=0.25.0\",\n \"@google/generative-ai\": \">=0.21.0\",\n \"ai\": \">=5.0.0\",\n \"zod\": \">=3.23.0\"\n },\n \"peerDependenciesMeta\": {\n \"@anthropic-ai/sdk\": {\n \"optional\": true\n },\n \"@google/generative-ai\": {\n \"optional\": true\n },\n \"ai\": {\n \"optional\": true\n },\n \"zod\": {\n \"optional\": true\n }\n },\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","import pkg from './package.json' with { type: 'json' };\nexport const SDK_VERSION: string = pkg.version;\n","/**\n * Edge-compatible code application API\n *\n * This module works on:\n * - Node.js\n * - Cloudflare Workers\n * - Vercel Edge Functions\n * - Deno Deploy\n * - Browser environments\n *\n * For file-based operations, use executeEditFile from core.ts\n */\n\nimport { createTwoFilesPatch } from 'diff';\nimport OpenAI from 'openai';\nimport { SDK_VERSION } from '../../version.js';\nimport type {\n EditChanges,\n ApplyEditInput,\n ApplyEditResult,\n ApplyEditConfig,\n} from './types.js';\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\nconst DEFAULT_TIMEOUT = 30000;\n\n/**\n * Generate a unified diff between two strings\n */\nexport function generateUdiff(\n original: string,\n modified: string,\n filepath: string\n): string {\n return createTwoFilesPatch(\n filepath,\n filepath,\n original,\n modified,\n 'Original',\n 'Modified'\n );\n}\n\n/**\n * Count changes from a unified diff\n */\nexport function countChanges(original: string, modified: string): EditChanges {\n const diff = generateUdiff(original, modified, 'file');\n const lines = diff.split('\\n');\n\n let linesAdded = 0;\n let linesRemoved = 0;\n\n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n linesAdded++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n linesRemoved++;\n }\n }\n\n const linesModified = Math.min(linesAdded, linesRemoved);\n\n return {\n linesAdded: linesAdded - linesModified,\n linesRemoved: linesRemoved - linesModified,\n linesModified,\n };\n}\n\n/**\n * Call Morph Apply API to merge code edits\n * Uses OpenAI SDK for reliable connection handling, retries, and timeouts\n */\nexport async function callMorphAPI(\n originalCode: string,\n codeEdit: string,\n instructions: string,\n filepath: string,\n config: ApplyEditConfig\n): Promise<{ content: string; completionId?: string }> {\n const apiKey = config.morphApiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n const apiUrl = config.morphApiUrl || DEFAULT_API_URL;\n const timeout = config.timeout || DEFAULT_TIMEOUT;\n const debug = config.debug || false;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n\n // Format message with XML tags as per Morph Fast Apply spec\n const message = `<instruction>${instructions}</instruction>\\n<code>${originalCode}</code>\\n<update>${codeEdit}</update>`;\n\n if (debug) {\n console.log(`[FastApply] Calling ${apiUrl}/v1/chat/completions`);\n console.log(`[FastApply] File: ${filepath}, Instructions: ${instructions.slice(0, 60)}...`);\n console.log(`[FastApply] Original: ${originalCode.length} chars, Edit: ${codeEdit.length} chars`);\n }\n\n const startTime = Date.now();\n\n const client = new OpenAI({\n apiKey,\n baseURL: `${apiUrl}/v1`,\n timeout,\n maxRetries: config.retryConfig?.maxRetries ?? 3,\n defaultHeaders: { 'X-Morph-SDK-Version': SDK_VERSION },\n });\n\n const completion = await client.chat.completions.create({\n model: 'morph-v3-fast',\n messages: [{ role: 'user', content: message }],\n });\n\n const content = completion.choices[0]?.message?.content;\n if (!content) {\n throw new Error('Morph API returned empty response');\n }\n\n const elapsed = Date.now() - startTime;\n\n if (debug) {\n console.log(`[FastApply] Success in ${elapsed}ms, merged: ${content.length} chars`);\n }\n\n return { content, completionId: completion.id };\n}\n\n/**\n * Apply an edit to code directly without file I/O\n *\n * This is the edge-compatible code-in/code-out API that accepts code content directly\n * and returns the merged result without reading or writing any files.\n *\n * Works on Cloudflare Workers, Vercel Edge Functions, Deno, and browsers.\n *\n * @param input - Code and edit parameters\n * @param config - Optional configuration\n * @returns Result with merged code\n *\n * @example\n * ```typescript\n * import { applyEdit } from '@morphllm/morphsdk';\n *\n * const result = await applyEdit({\n * originalCode: fs.readFileSync('file.ts', 'utf-8'),\n * codeEdit: '// ... existing code ...\\nconst newVar = 42;\\n// ... existing code ...',\n * instructions: 'Add a new variable',\n * filepath: 'file.ts' // optional, for udiff context\n * });\n *\n * if (result.success) {\n * fs.writeFileSync('file.ts', result.mergedCode);\n * }\n * ```\n */\nexport async function applyEdit(\n input: ApplyEditInput,\n config: ApplyEditConfig = {}\n): Promise<ApplyEditResult> {\n const debug = config.debug || false;\n const filepath = input.filepath || 'file';\n\n try {\n if (debug) {\n console.log(`[FastApply] Applying edit to code (${input.originalCode.length} chars)`);\n }\n\n const { content: mergedCode, completionId } = await callMorphAPI(\n input.originalCode,\n input.codeEdit,\n input.instructions,\n filepath,\n config\n );\n\n const udiff = config.generateUdiff !== false\n ? generateUdiff(input.originalCode, mergedCode, filepath)\n : undefined;\n\n const changes = countChanges(input.originalCode, mergedCode);\n\n return {\n success: true,\n mergedCode,\n udiff,\n changes,\n completionId,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n if (debug) console.error(`[FastApply] Error: ${errorMessage}`);\n\n return {\n success: false,\n changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },\n error: errorMessage,\n };\n }\n}\n","/**\n * Resilience utilities for retry logic and timeout handling\n */\n\nimport { SDK_VERSION } from '../../version.js';\n\nexport interface RetryConfig {\n maxRetries?: number; // Default: 3\n initialDelay?: number; // Default: 1000ms\n maxDelay?: number; // Default: 30000ms\n backoffMultiplier?: number; // Default: 2\n retryableErrors?: string[]; // Default: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND']\n onRetry?: (attempt: number, error: Error) => void;\n}\n\nconst DEFAULT_RETRY_CONFIG: Required<Omit<RetryConfig, 'onRetry'>> = {\n maxRetries: 3,\n initialDelay: 1000,\n maxDelay: 30000,\n backoffMultiplier: 2,\n retryableErrors: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'],\n};\n\n/**\n * Retry a fetch request with exponential backoff\n * \n * @param url - Request URL\n * @param options - Fetch options\n * @param retryConfig - Retry configuration\n * @returns Response from fetch\n * \n * @example\n * ```typescript\n * const response = await fetchWithRetry(\n * 'https://api.example.com/data',\n * { method: 'POST', body: JSON.stringify(data) },\n * { maxRetries: 5, initialDelay: 500 }\n * );\n * ```\n */\nexport async function fetchWithRetry(\n url: string,\n options: RequestInit,\n retryConfig: RetryConfig = {}\n): Promise<Response> {\n const {\n maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,\n initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,\n maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,\n backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,\n retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,\n onRetry,\n } = retryConfig;\n\n let lastError: Error | null = null;\n let delay = initialDelay;\n\n // Inject SDK version header (caller-provided headers can override)\n options = { ...options, headers: { 'X-Morph-SDK-Version': SDK_VERSION, ...options.headers } };\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n \n // Retry on 429 (rate limit) or 503 (service unavailable)\n if (response.status === 429 || response.status === 503) {\n if (attempt < maxRetries) {\n // Check for Retry-After header\n const retryAfter = response.headers.get('Retry-After');\n const waitTime = retryAfter \n ? parseInt(retryAfter) * 1000 \n : Math.min(delay, maxDelay);\n \n const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);\n if (onRetry) {\n onRetry(attempt + 1, error);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n continue;\n }\n }\n\n return response;\n } catch (error) {\n lastError = error as Error;\n \n // Check if error is retryable\n const isRetryable = retryableErrors.some(errType => \n lastError?.message?.includes(errType)\n );\n\n if (!isRetryable || attempt === maxRetries) {\n throw lastError;\n }\n\n // Exponential backoff\n const waitTime = Math.min(delay, maxDelay);\n if (onRetry) {\n onRetry(attempt + 1, lastError);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n }\n }\n\n throw lastError || new Error('Max retries exceeded');\n}\n\n/**\n * Add timeout to any promise\n * \n * @param promise - Promise to wrap with timeout\n * @param timeoutMs - Timeout in milliseconds\n * @param errorMessage - Optional custom error message\n * @returns Promise that rejects if timeout is reached\n * \n * @example\n * ```typescript\n * const result = await withTimeout(\n * fetchData(),\n * 5000,\n * 'Data fetch timed out'\n * );\n * ```\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n errorMessage?: string\n): Promise<T> {\n let timeoutId: NodeJS.Timeout | number;\n \n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n\n try {\n const result = await Promise.race([promise, timeoutPromise]);\n clearTimeout(timeoutId!);\n return result;\n } catch (error) {\n clearTimeout(timeoutId!);\n throw error;\n }\n}\n\n/**\n * Sleep for specified milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Unified error type for all tools\n */\nexport class MorphError extends Error {\n constructor(\n message: string,\n public code: string,\n public statusCode?: number,\n public retryable: boolean = false\n ) {\n super(message);\n this.name = 'MorphError';\n }\n}\n\n\n","/**\n * Core implementation for intelligent model routing\n */\n\nimport { fetchWithRetry, withTimeout } from '../tools/utils/resilience.js';\nimport type {\n RouterConfig,\n RouterInput,\n RouterResult,\n RawRouterResult,\n ComplexityLevel,\n RouterMode,\n Provider,\n} from './types.js';\n\nconst DEFAULT_CONFIG = {\n apiUrl: 'https://api.morphllm.com',\n timeout: 5000, // 5 seconds (responses typically <500ms)\n debug: false,\n};\n\nabstract class BaseRouter {\n protected config: Required<Omit<RouterConfig, 'apiKey' | 'retryConfig'>> & Pick<RouterConfig, 'apiKey' | 'retryConfig'>;\n protected provider: Provider;\n\n constructor(provider: Provider, config: RouterConfig = {}) {\n this.provider = provider;\n this.config = {\n apiKey: config.apiKey,\n apiUrl: config.apiUrl || DEFAULT_CONFIG.apiUrl,\n timeout: config.timeout || DEFAULT_CONFIG.timeout,\n debug: config.debug || DEFAULT_CONFIG.debug,\n retryConfig: config.retryConfig,\n };\n }\n\n /**\n * Select the optimal model for a given input and mode\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/${this.provider}`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Requesting ${this.provider} model selection:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model: string; confidence?: number } = await response.json();\n\n const result: RouterResult = {\n model: apiResult.model,\n };\n\n if (this.config.debug) {\n console.log(`[ModelRouter] Selected model: ${apiResult.model}, Confidence: ${apiResult.confidence?.toFixed(3)}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[ModelRouter] Error selecting model:`, error);\n }\n throw error;\n }\n }\n}\n\n/**\n * OpenAI model router for GPT-5 series\n */\nexport class OpenAIRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('openai', config);\n }\n\n /**\n * Select optimal GPT-5 model\n * \n * @param input - User input and mode\n * @returns Selected model name (gpt-5-mini | gpt-5-low | gpt-5-medium | gpt-5-high)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Anthropic model router for Claude 4.5 series\n */\nexport class AnthropicRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('anthropic', config);\n }\n\n /**\n * Select optimal Claude model\n * \n * @param input - User input and mode\n * @returns Selected model name (claude-4.5-haiku | claude-4.5-sonnet)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Google Gemini model router\n */\nexport class GeminiRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('gemini', config);\n }\n\n /**\n * Select optimal Gemini model\n * \n * @param input - User input and mode\n * @returns Selected model name (gemini-2.5-flash | gemini-2.5-pro)\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n return super.selectModel(input);\n }\n}\n\n/**\n * Raw difficulty classification router (no provider-specific mapping)\n */\nexport class RawRouter extends BaseRouter {\n constructor(config: RouterConfig = {}) {\n super('raw' as Provider, config);\n }\n\n /**\n * Get raw difficulty classification\n * \n * @param input - User input and mode\n * @returns Raw difficulty (easy | medium | hard | needs_info)\n */\n async classify(input: RouterInput): Promise<RawRouterResult> {\n const mode = input.mode || 'balanced';\n const apiKey = this.config.apiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n const url = `${this.config.apiUrl}/v1/router/raw`;\n const payload = {\n input: input.input,\n mode,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Requesting raw difficulty classification:`, {\n mode,\n inputLength: input.input.length,\n });\n }\n\n try {\n const fetchPromise = fetchWithRetry(\n url,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n },\n this.config.retryConfig\n );\n\n const response = await withTimeout(\n fetchPromise,\n this.config.timeout,\n `Router API request timed out after ${this.config.timeout}ms`\n );\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Router API error (${response.status}): ${errorText || response.statusText}`\n );\n }\n\n const apiResult: { model?: string; difficulty?: string; confidence?: number } = await response.json();\n\n // Support both 'model' and 'difficulty' fields for compatibility\n // Empty string from API means \"medium\" difficulty (API bug workaround)\n let difficulty: ComplexityLevel;\n if (apiResult.difficulty === '') {\n difficulty = 'medium';\n } else {\n difficulty = (apiResult.difficulty || apiResult.model) as ComplexityLevel;\n }\n\n const result: RawRouterResult = {\n difficulty,\n };\n\n if (this.config.debug) {\n console.log(`[RawRouter] Classified as: ${difficulty}`);\n }\n\n return result;\n } catch (error) {\n if (this.config.debug) {\n console.error(`[RawRouter] Error classifying:`, error);\n }\n throw error;\n }\n }\n}\n","/**\n * Core implementation of Morph Compact\n *\n * Uses the OpenAI Chat Completions API to compact conversation context\n * via the Morph compactor model.\n */\n\nimport OpenAI from 'openai';\nimport type { ChatCompletionMessageParam } from 'openai/resources/chat/completions';\nimport type { CompactConfig, CompactInput, CompactResult, CompressInput, CompressResult } from './types.js';\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\nconst DEFAULT_TIMEOUT = 120000;\n\n/**\n * CompactClient for programmatic context compaction\n */\nexport class CompactClient {\n private config: Required<Pick<CompactConfig, 'morphApiUrl' | 'timeout'>> & CompactConfig;\n\n constructor(config: CompactConfig = {}) {\n this.config = {\n morphApiUrl: DEFAULT_API_URL,\n timeout: DEFAULT_TIMEOUT,\n ...config,\n };\n }\n\n /**\n * Compact conversation context using Morph compactor\n *\n * @param input - Compact parameters including input content and optional prompt\n * @returns Compact result with compacted output and usage stats\n *\n * @example\n * ```typescript\n * const client = new CompactClient({ morphApiKey: 'sk-...' });\n * const result = await client.compact({\n * input: 'Long conversation context to compact...',\n * prompt: 'Focus on the code review feedback',\n * });\n * console.log(result.output);\n * ```\n */\n async compact(input: CompactInput): Promise<CompactResult> {\n const apiKey = this.config.morphApiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n const debug = this.config.debug || false;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n\n const client = new OpenAI({\n apiKey,\n baseURL: `${this.config.morphApiUrl}/v1`,\n timeout: this.config.timeout,\n maxRetries: this.config.retryConfig?.maxRetries ?? 3,\n });\n\n // Build messages array from input\n const messages: ChatCompletionMessageParam[] = [];\n\n if (input.prompt) {\n messages.push({\n role: 'system',\n content: `The user's next message will be: \"${input.prompt}\"\\nPrioritize keeping context relevant to this query.`,\n });\n }\n\n if (typeof input.input === 'string') {\n messages.push({ role: 'user', content: input.input });\n } else {\n // input is ChatCompletionMessageParam[]\n messages.push(...input.input);\n }\n\n if (debug) {\n console.log(`[Compact] Calling ${this.config.morphApiUrl}/v1/chat/completions`);\n console.log(`[Compact] Model: ${input.model || 'morph-compactor'}`);\n }\n\n const startTime = Date.now();\n\n const response = await client.chat.completions.create({\n model: input.model || 'morph-compactor',\n messages,\n ...(input.temperature != null && { temperature: input.temperature }),\n ...(input.max_output_tokens != null && { max_tokens: input.max_output_tokens }),\n stream: false,\n });\n\n const elapsed = Date.now() - startTime;\n\n if (debug) {\n console.log(`[Compact] Success in ${elapsed}ms`);\n }\n\n return {\n id: response.id,\n output: response.choices[0]?.message?.content || '',\n usage: response.usage ? {\n input_tokens: response.usage.prompt_tokens,\n output_tokens: response.usage.completion_tokens,\n total_tokens: response.usage.total_tokens,\n } : undefined,\n model: response.model,\n };\n }\n\n /**\n * Compress messages using the direct /v1/compress endpoint.\n * Returns per-message `compacted_line_ranges` showing which lines were removed.\n *\n * @example\n * ```typescript\n * const client = new CompactClient({ morphApiKey: 'sk-...' });\n * const result = await client.compress({\n * messages: [{ role: \"user\", content: codeFile }],\n * compression_ratio: 0.5,\n * query: \"authentication\",\n * });\n * for (const msg of result.messages) {\n * for (const r of msg.compacted_line_ranges) {\n * console.log(`Lines ${r.start}-${r.end} removed`);\n * }\n * }\n * ```\n */\n async compress(input: CompressInput): Promise<CompressResult> {\n const apiKey = this.config.morphApiKey || (typeof process !== 'undefined' ? process.env?.MORPH_API_KEY : undefined);\n const debug = this.config.debug || false;\n\n if (!apiKey) {\n throw new Error(\n 'Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config.'\n );\n }\n\n const url = `${this.config.morphApiUrl}/v1/compress`;\n\n if (debug) {\n console.log(`[Compact] Calling ${url}`);\n }\n\n const startTime = Date.now();\n\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n messages: input.messages,\n compression_ratio: input.compression_ratio ?? 0.5,\n preserve_recent: input.preserve_recent ?? 2,\n query: input.query,\n model: input.model ?? 'swe-pruner-0.6b',\n }),\n signal: AbortSignal.timeout(this.config.timeout),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(`Compress API error ${response.status}: ${body}`);\n }\n\n const data = await response.json() as CompressResult;\n\n if (debug) {\n console.log(`[Compact] compress() done in ${Date.now() - startTime}ms`);\n }\n\n return data;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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,UAAU;AAAA,MACR,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SAAW;AAAA,IACb;AAAA,IACA,qBAAqB;AAAA,MACnB,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SAAW;AAAA,IACb;AAAA,IACA,4BAA4B;AAAA,MAC1B,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SAAW;AAAA,IACb;AAAA,IACA,+BAA+B;AAAA,MAC7B,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SAAW;AAAA,IACb;AAAA,IACA,4BAA4B;AAAA,MAC1B,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SAAW;AAAA,IACb;AAAA,IACA,4BAA4B;AAAA,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AAK,OAAO,gBAAgB,OAAO,YAAY,cAAc,QAAQ,KAAK,gBAAgB;AACzG,UAAM,QAAQ,KAAK,OAAO,SAAS;AAEnC,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,MAAM,GAAG,KAAK,OAAO,WAAW;AAEtC,QAAI,OAAO;AACT,cAAQ,IAAI,qBAAqB,GAAG,EAAE;AAAA,IACxC;AAEA,UAAM,YAAY,KAAK,IAAI;AAE3B,UAAM,WAAW,MAAM,MAAM,KAAK;AAAA,MAChC,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,iBAAiB,UAAU,MAAM;AAAA,QACjC,gBAAgB;AAAA,MAClB;AAAA,MACA,MAAM,KAAK,UAAU;AAAA,QACnB,UAAU,MAAM;AAAA,QAChB,mBAAmB,MAAM,qBAAqB;AAAA,QAC9C,iBAAiB,MAAM,mBAAmB;AAAA,QAC1C,OAAO,MAAM;AAAA,QACb,OAAO,MAAM,SAAS;AAAA,MACxB,CAAC;AAAA,MACD,QAAQ,YAAY,QAAQ,KAAK,OAAO,OAAO;AAAA,IACjD,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,OAAO,MAAM,SAAS,KAAK;AACjC,YAAM,IAAI,MAAM,sBAAsB,SAAS,MAAM,KAAK,IAAI,EAAE;AAAA,IAClE;AAEA,UAAM,OAAO,MAAM,SAAS,KAAK;AAEjC,QAAI,OAAO;AACT,cAAQ,IAAI,gCAAgC,KAAK,IAAI,IAAI,SAAS,IAAI;AAAA,IACxE;AAEA,WAAO;AAAA,EACT;AACF;","names":["OpenAI","import_openai","DEFAULT_API_URL","DEFAULT_TIMEOUT","OpenAI"]}
|
package/dist/edge.d.ts
CHANGED
|
@@ -5,5 +5,5 @@ export { ApplyEditConfig, ApplyEditInput, ApplyEditResult, EditChanges } from '.
|
|
|
5
5
|
export { ComplexityLevel, Provider, RawRouterResult, RouterConfig, RouterInput, RouterMode, RouterResult } from './modelrouter/types.js';
|
|
6
6
|
export { RetryConfig } from './tools/utils/resilience.js';
|
|
7
7
|
export { CompactClient } from './tools/compact/core.js';
|
|
8
|
-
export { CompactConfig, CompactInput, CompactResult } from './tools/compact/types.js';
|
|
9
|
-
import 'openai/resources/
|
|
8
|
+
export { CompactConfig, CompactInput, CompactResult, CompactedRange, CompressInput, CompressMessage, CompressResult } from './tools/compact/types.js';
|
|
9
|
+
import 'openai/resources/chat/completions';
|
package/dist/edge.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CompactClient
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-2YDR2TVC.js";
|
|
4
4
|
import {
|
|
5
5
|
AnthropicRouter,
|
|
6
6
|
GeminiRouter,
|
|
7
7
|
OpenAIRouter,
|
|
8
8
|
RawRouter
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-GTNE5WGY.js";
|
|
10
10
|
import {
|
|
11
11
|
applyEdit,
|
|
12
12
|
callMorphAPI,
|
|
13
13
|
countChanges,
|
|
14
14
|
generateUdiff
|
|
15
|
-
} from "./chunk-
|
|
16
|
-
import "./chunk-
|
|
15
|
+
} from "./chunk-6WIJVB3U.js";
|
|
16
|
+
import "./chunk-7GDUMJCC.js";
|
|
17
17
|
import {
|
|
18
18
|
SDK_VERSION
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-ED7GLEP4.js";
|
|
20
20
|
import "./chunk-PZ5AY32C.js";
|
|
21
21
|
export {
|
|
22
22
|
AnthropicRouter,
|
package/dist/index.cjs
CHANGED
|
@@ -36,7 +36,7 @@ var init_package = __esm({
|
|
|
36
36
|
"package.json"() {
|
|
37
37
|
package_default = {
|
|
38
38
|
name: "@morphllm/morphsdk",
|
|
39
|
-
version: "0.2.
|
|
39
|
+
version: "0.2.130",
|
|
40
40
|
description: "TypeScript SDK and CLI for Morph Fast Apply integration",
|
|
41
41
|
type: "module",
|
|
42
42
|
main: "./dist/index.cjs",
|
|
@@ -4656,19 +4656,29 @@ var CompactClient = class {
|
|
|
4656
4656
|
timeout: this.config.timeout,
|
|
4657
4657
|
maxRetries: this.config.retryConfig?.maxRetries ?? 3
|
|
4658
4658
|
});
|
|
4659
|
-
const
|
|
4660
|
-
|
|
4659
|
+
const messages = [];
|
|
4660
|
+
if (input.prompt) {
|
|
4661
|
+
messages.push({
|
|
4662
|
+
role: "system",
|
|
4663
|
+
content: `The user's next message will be: "${input.prompt}"
|
|
4664
|
+
Prioritize keeping context relevant to this query.`
|
|
4665
|
+
});
|
|
4666
|
+
}
|
|
4667
|
+
if (typeof input.input === "string") {
|
|
4668
|
+
messages.push({ role: "user", content: input.input });
|
|
4669
|
+
} else {
|
|
4670
|
+
messages.push(...input.input);
|
|
4671
|
+
}
|
|
4661
4672
|
if (debug) {
|
|
4662
|
-
console.log(`[Compact] Calling ${this.config.morphApiUrl}/v1/
|
|
4673
|
+
console.log(`[Compact] Calling ${this.config.morphApiUrl}/v1/chat/completions`);
|
|
4663
4674
|
console.log(`[Compact] Model: ${input.model || "morph-compactor"}`);
|
|
4664
4675
|
}
|
|
4665
4676
|
const startTime = Date.now();
|
|
4666
|
-
const response = await client.
|
|
4677
|
+
const response = await client.chat.completions.create({
|
|
4667
4678
|
model: input.model || "morph-compactor",
|
|
4668
|
-
|
|
4669
|
-
...instructions && { instructions },
|
|
4679
|
+
messages,
|
|
4670
4680
|
...input.temperature != null && { temperature: input.temperature },
|
|
4671
|
-
...input.max_output_tokens != null && {
|
|
4681
|
+
...input.max_output_tokens != null && { max_tokens: input.max_output_tokens },
|
|
4672
4682
|
stream: false
|
|
4673
4683
|
});
|
|
4674
4684
|
const elapsed = Date.now() - startTime;
|
|
@@ -4677,12 +4687,72 @@ Prioritize keeping context relevant to this query.` : void 0;
|
|
|
4677
4687
|
}
|
|
4678
4688
|
return {
|
|
4679
4689
|
id: response.id,
|
|
4680
|
-
output: response.
|
|
4681
|
-
usage: response.usage
|
|
4682
|
-
|
|
4690
|
+
output: response.choices[0]?.message?.content || "",
|
|
4691
|
+
usage: response.usage ? {
|
|
4692
|
+
input_tokens: response.usage.prompt_tokens,
|
|
4693
|
+
output_tokens: response.usage.completion_tokens,
|
|
4694
|
+
total_tokens: response.usage.total_tokens
|
|
4695
|
+
} : void 0,
|
|
4683
4696
|
model: response.model
|
|
4684
4697
|
};
|
|
4685
4698
|
}
|
|
4699
|
+
/**
|
|
4700
|
+
* Compress messages using the direct /v1/compress endpoint.
|
|
4701
|
+
* Returns per-message `compacted_line_ranges` showing which lines were removed.
|
|
4702
|
+
*
|
|
4703
|
+
* @example
|
|
4704
|
+
* ```typescript
|
|
4705
|
+
* const client = new CompactClient({ morphApiKey: 'sk-...' });
|
|
4706
|
+
* const result = await client.compress({
|
|
4707
|
+
* messages: [{ role: "user", content: codeFile }],
|
|
4708
|
+
* compression_ratio: 0.5,
|
|
4709
|
+
* query: "authentication",
|
|
4710
|
+
* });
|
|
4711
|
+
* for (const msg of result.messages) {
|
|
4712
|
+
* for (const r of msg.compacted_line_ranges) {
|
|
4713
|
+
* console.log(`Lines ${r.start}-${r.end} removed`);
|
|
4714
|
+
* }
|
|
4715
|
+
* }
|
|
4716
|
+
* ```
|
|
4717
|
+
*/
|
|
4718
|
+
async compress(input) {
|
|
4719
|
+
const apiKey = this.config.morphApiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
|
|
4720
|
+
const debug = this.config.debug || false;
|
|
4721
|
+
if (!apiKey) {
|
|
4722
|
+
throw new Error(
|
|
4723
|
+
"Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config."
|
|
4724
|
+
);
|
|
4725
|
+
}
|
|
4726
|
+
const url = `${this.config.morphApiUrl}/v1/compress`;
|
|
4727
|
+
if (debug) {
|
|
4728
|
+
console.log(`[Compact] Calling ${url}`);
|
|
4729
|
+
}
|
|
4730
|
+
const startTime = Date.now();
|
|
4731
|
+
const response = await fetch(url, {
|
|
4732
|
+
method: "POST",
|
|
4733
|
+
headers: {
|
|
4734
|
+
"Authorization": `Bearer ${apiKey}`,
|
|
4735
|
+
"Content-Type": "application/json"
|
|
4736
|
+
},
|
|
4737
|
+
body: JSON.stringify({
|
|
4738
|
+
messages: input.messages,
|
|
4739
|
+
compression_ratio: input.compression_ratio ?? 0.5,
|
|
4740
|
+
preserve_recent: input.preserve_recent ?? 2,
|
|
4741
|
+
query: input.query,
|
|
4742
|
+
model: input.model ?? "swe-pruner-0.6b"
|
|
4743
|
+
}),
|
|
4744
|
+
signal: AbortSignal.timeout(this.config.timeout)
|
|
4745
|
+
});
|
|
4746
|
+
if (!response.ok) {
|
|
4747
|
+
const body = await response.text();
|
|
4748
|
+
throw new Error(`Compress API error ${response.status}: ${body}`);
|
|
4749
|
+
}
|
|
4750
|
+
const data = await response.json();
|
|
4751
|
+
if (debug) {
|
|
4752
|
+
console.log(`[Compact] compress() done in ${Date.now() - startTime}ms`);
|
|
4753
|
+
}
|
|
4754
|
+
return data;
|
|
4755
|
+
}
|
|
4686
4756
|
};
|
|
4687
4757
|
|
|
4688
4758
|
// modelrouter/core.ts
|
|
@@ -5756,7 +5826,8 @@ var MorphClient = class {
|
|
|
5756
5826
|
debug: config.debug
|
|
5757
5827
|
});
|
|
5758
5828
|
this.responses = {
|
|
5759
|
-
compact: compactClient.compact.bind(compactClient)
|
|
5829
|
+
compact: compactClient.compact.bind(compactClient),
|
|
5830
|
+
compress: compactClient.compress.bind(compactClient)
|
|
5760
5831
|
};
|
|
5761
5832
|
this.openai = new OpenAIToolFactory(config);
|
|
5762
5833
|
this.anthropic = new AnthropicToolFactory(config);
|