@morphllm/morphsdk 0.2.200 → 0.2.201
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-sdk/index.cjs +0 -1
- package/dist/ai-sdk/index.js +0 -1
- package/dist/{chunk-HYRHI2UL.js → chunk-2PPYWRMZ.js} +0 -1
- package/dist/{chunk-IA5K2HTC.js → chunk-44OIEPIO.js} +1 -2
- package/dist/{chunk-FBRNUWEB.js → chunk-4OUGA3KS.js} +0 -1
- package/dist/{chunk-AKSXZBPT.js → chunk-5NSYDT36.js} +3 -4
- package/dist/{chunk-G2RSY56Q.js → chunk-6TZCVTW5.js} +0 -1
- package/dist/{chunk-F3NCFNUX.js → chunk-6WP7EA4F.js} +0 -1
- package/dist/{chunk-PJNL35DC.js → chunk-B376VMIH.js} +2 -3
- package/dist/{chunk-LN7GNFET.js → chunk-BZXOAC2R.js} +4 -5
- package/dist/{chunk-WTENYKJP.js → chunk-DBNSOYQ3.js} +2 -3
- package/dist/{chunk-MPL6BDR6.js → chunk-EQAWWVKV.js} +1 -2
- package/dist/{chunk-ZZ25FZG2.js → chunk-ETBRAKVV.js} +0 -1
- package/dist/chunk-FBOZIVVQ.js +0 -0
- package/dist/{chunk-B4X5RWLR.js → chunk-FVT4PU4I.js} +14 -15
- package/dist/{chunk-MRMBFJR2.js → chunk-HDP4QAZL.js} +0 -1
- package/dist/{chunk-TPP2UGQP.js → chunk-I26FQELI.js} +0 -1
- package/dist/{chunk-XTLPA7ZP.js → chunk-ILY5N5NJ.js} +2 -3
- package/dist/{chunk-UKAAT6KT.js → chunk-JBAY3PRV.js} +4 -5
- package/dist/chunk-LDM7RNNN.js +0 -0
- package/dist/{chunk-PD3EDFQD.js → chunk-LISSWRUD.js} +5 -6
- package/dist/{chunk-CCJK3HTG.js → chunk-M34E2AMK.js} +0 -1
- package/dist/{chunk-ZE64EWUV.js → chunk-M6AVXUM4.js} +2 -3
- package/dist/{chunk-QRXG5CAZ.js → chunk-MF56KEI4.js} +0 -1
- package/dist/{chunk-PZ5AY32C.js → chunk-MLKGABMK.js} +0 -1
- package/dist/{chunk-5TOJD2C5.js → chunk-NRG6QX3L.js} +0 -1
- package/dist/{chunk-3CCWSLQW.js → chunk-NWGRW4V7.js} +1 -2
- package/dist/{chunk-63VHBANJ.js → chunk-OPDWMD4Q.js} +0 -1
- package/dist/{chunk-TIMDDHYB.js → chunk-OVLUL5AC.js} +3 -4
- package/dist/{chunk-QTBFL4DG.js → chunk-P2KW2O5R.js} +2 -3
- package/dist/{chunk-63WE2C5R.js → chunk-PA3UTI4A.js} +0 -1
- package/dist/{chunk-UHIANNKC.js → chunk-RJXAXR7Q.js} +3 -4
- package/dist/{chunk-A4D2CIIT.js → chunk-RYVW7RUM.js} +1 -2
- package/dist/{chunk-Z57GJLCG.js → chunk-RZOJ4GSY.js} +4 -5
- package/dist/{chunk-Q65LL6UM.js → chunk-SU7AAS3O.js} +2 -3
- package/dist/{chunk-7I2A7GGJ.js → chunk-TS3OJ4LA.js} +1 -2
- package/dist/{chunk-SNYHVDE4.js → chunk-TZC3EOZS.js} +3 -4
- package/dist/{chunk-Q6QCHAMD.js → chunk-UAPK3AIJ.js} +0 -1
- package/dist/{chunk-UZ42MHTR.js → chunk-UZCXOOZO.js} +2 -4
- package/dist/{chunk-L6YOMTFU.js → chunk-VOXUA5ZH.js} +4 -5
- package/dist/{chunk-MLROWLS6.js → chunk-WBTXEJOC.js} +8 -9
- package/dist/{chunk-YPKNMYD4.js → chunk-ZSHVXDA2.js} +0 -1
- package/dist/client.cjs +2 -4
- package/dist/client.js +32 -33
- package/dist/core/client.cjs +2 -4
- package/dist/core/client.js +6 -7
- package/dist/core/error.cjs +2 -4
- package/dist/core/error.js +4 -5
- package/dist/core/index.cjs +2 -4
- package/dist/core/index.js +8 -9
- package/dist/core/resource.cjs +0 -1
- package/dist/core/resource.js +2 -3
- package/dist/edge.cjs +2 -4
- package/dist/edge.js +10 -11
- package/dist/index.cjs +2 -4
- package/dist/index.js +39 -40
- package/dist/modelrouter/core.cjs +2 -4
- package/dist/modelrouter/core.js +8 -9
- package/dist/modelrouter/index.cjs +2 -4
- package/dist/modelrouter/index.js +8 -9
- package/dist/modelrouter/types.cjs +0 -1
- package/dist/modelrouter/types.js +0 -1
- package/dist/subagents/anthropic.cjs +2 -4
- package/dist/subagents/anthropic.js +19 -20
- package/dist/subagents/index.cjs +0 -1
- package/dist/subagents/index.js +2 -3
- package/dist/subagents/prompts.cjs +0 -1
- package/dist/subagents/prompts.js +2 -3
- package/dist/subagents/types.cjs +0 -1
- package/dist/subagents/types.js +0 -1
- package/dist/subagents/vercel.cjs +2 -4
- package/dist/subagents/vercel.js +19 -20
- package/dist/tools/compact/core.cjs +2 -4
- package/dist/tools/compact/core.js +8 -9
- package/dist/tools/compact/index.cjs +2 -4
- package/dist/tools/compact/index.js +9 -10
- package/dist/tools/compact/types.cjs +0 -1
- package/dist/tools/compact/types.js +0 -1
- package/dist/tools/fastapply/anthropic.cjs +2 -4
- package/dist/tools/fastapply/anthropic.js +11 -12
- package/dist/tools/fastapply/apply.cjs +2 -4
- package/dist/tools/fastapply/apply.js +4 -5
- package/dist/tools/fastapply/core.cjs +2 -4
- package/dist/tools/fastapply/core.js +9 -10
- package/dist/tools/fastapply/index.cjs +2 -4
- package/dist/tools/fastapply/index.js +14 -15
- package/dist/tools/fastapply/openai.cjs +2 -4
- package/dist/tools/fastapply/openai.js +11 -12
- package/dist/tools/fastapply/prompts.cjs +0 -1
- package/dist/tools/fastapply/prompts.js +2 -3
- package/dist/tools/fastapply/types.cjs +0 -1
- package/dist/tools/fastapply/types.js +0 -1
- package/dist/tools/fastapply/vercel.cjs +2 -4
- package/dist/tools/fastapply/vercel.js +11 -12
- package/dist/tools/index.cjs +2 -4
- package/dist/tools/index.js +14 -15
- package/dist/tools/utils/resilience.cjs +2 -4
- package/dist/tools/utils/resilience.js +3 -4
- package/dist/tools/warp_grep/agent/config.cjs +0 -1
- package/dist/tools/warp_grep/agent/config.js +2 -3
- package/dist/tools/warp_grep/agent/formatter.cjs +0 -1
- package/dist/tools/warp_grep/agent/formatter.js +2 -3
- package/dist/tools/warp_grep/agent/parser.cjs +0 -1
- package/dist/tools/warp_grep/agent/parser.js +2 -3
- package/dist/tools/warp_grep/agent/runner.cjs +2 -4
- package/dist/tools/warp_grep/agent/runner.js +7 -8
- package/dist/tools/warp_grep/agent/types.cjs +0 -1
- package/dist/tools/warp_grep/agent/types.js +0 -1
- package/dist/tools/warp_grep/anthropic.cjs +2 -4
- package/dist/tools/warp_grep/anthropic.js +19 -20
- package/dist/tools/warp_grep/client.cjs +2 -4
- package/dist/tools/warp_grep/client.js +17 -18
- package/dist/tools/warp_grep/gemini.cjs +2 -4
- package/dist/tools/warp_grep/gemini.js +18 -19
- package/dist/tools/warp_grep/harness.cjs +0 -1
- package/dist/tools/warp_grep/harness.js +9 -10
- package/dist/tools/warp_grep/index.cjs +2 -4
- package/dist/tools/warp_grep/index.js +24 -25
- package/dist/tools/warp_grep/openai.cjs +2 -4
- package/dist/tools/warp_grep/openai.js +19 -20
- package/dist/tools/warp_grep/providers/code_storage_http.cjs +0 -1
- package/dist/tools/warp_grep/providers/code_storage_http.js +2 -3
- package/dist/tools/warp_grep/providers/local.cjs +0 -1
- package/dist/tools/warp_grep/providers/local.js +6 -7
- package/dist/tools/warp_grep/providers/remote.cjs +0 -1
- package/dist/tools/warp_grep/providers/remote.js +3 -4
- package/dist/tools/warp_grep/providers/types.cjs +0 -1
- package/dist/tools/warp_grep/providers/types.js +0 -1
- package/dist/tools/warp_grep/utils/files.cjs +0 -1
- package/dist/tools/warp_grep/utils/files.js +2 -3
- package/dist/tools/warp_grep/utils/github.cjs +0 -1
- package/dist/tools/warp_grep/utils/github.js +2 -3
- package/dist/tools/warp_grep/utils/paths.cjs +0 -1
- package/dist/tools/warp_grep/utils/paths.js +2 -3
- package/dist/tools/warp_grep/utils/ripgrep.cjs +0 -1
- package/dist/tools/warp_grep/utils/ripgrep.js +2 -3
- package/dist/tools/warp_grep/vercel.cjs +2 -4
- package/dist/tools/warp_grep/vercel.js +19 -20
- package/dist/version.cjs +2 -4
- package/dist/version.js +2 -3
- package/package.json +2 -3
- package/dist/ai-sdk/index.cjs.map +0 -1
- package/dist/ai-sdk/index.js.map +0 -1
- package/dist/chunk-3CCWSLQW.js.map +0 -1
- package/dist/chunk-5TOJD2C5.js.map +0 -1
- package/dist/chunk-63VHBANJ.js.map +0 -1
- package/dist/chunk-63WE2C5R.js.map +0 -1
- package/dist/chunk-7I2A7GGJ.js.map +0 -1
- package/dist/chunk-A4D2CIIT.js.map +0 -1
- package/dist/chunk-AKSXZBPT.js.map +0 -1
- package/dist/chunk-B4X5RWLR.js.map +0 -1
- package/dist/chunk-CCJK3HTG.js.map +0 -1
- package/dist/chunk-F3NCFNUX.js.map +0 -1
- package/dist/chunk-FBRNUWEB.js.map +0 -1
- package/dist/chunk-G2RSY56Q.js.map +0 -1
- package/dist/chunk-HYRHI2UL.js.map +0 -1
- package/dist/chunk-IA5K2HTC.js.map +0 -1
- package/dist/chunk-L6YOMTFU.js.map +0 -1
- package/dist/chunk-LN7GNFET.js.map +0 -1
- package/dist/chunk-MLROWLS6.js.map +0 -1
- package/dist/chunk-MPL6BDR6.js.map +0 -1
- package/dist/chunk-MRMBFJR2.js.map +0 -1
- package/dist/chunk-PD3EDFQD.js.map +0 -1
- package/dist/chunk-PJNL35DC.js.map +0 -1
- package/dist/chunk-PZ5AY32C.js.map +0 -1
- package/dist/chunk-Q65LL6UM.js.map +0 -1
- package/dist/chunk-Q6QCHAMD.js.map +0 -1
- package/dist/chunk-QRXG5CAZ.js.map +0 -1
- package/dist/chunk-QTBFL4DG.js.map +0 -1
- package/dist/chunk-SNYHVDE4.js.map +0 -1
- package/dist/chunk-TIMDDHYB.js.map +0 -1
- package/dist/chunk-TPP2UGQP.js.map +0 -1
- package/dist/chunk-UHIANNKC.js.map +0 -1
- package/dist/chunk-UKAAT6KT.js.map +0 -1
- package/dist/chunk-UZ42MHTR.js.map +0 -1
- package/dist/chunk-VZ7BOH2K.js +0 -1
- package/dist/chunk-VZ7BOH2K.js.map +0 -1
- package/dist/chunk-WTENYKJP.js.map +0 -1
- package/dist/chunk-X2K57BH6.js +0 -1
- package/dist/chunk-X2K57BH6.js.map +0 -1
- package/dist/chunk-XTLPA7ZP.js.map +0 -1
- package/dist/chunk-YPKNMYD4.js.map +0 -1
- package/dist/chunk-Z57GJLCG.js.map +0 -1
- package/dist/chunk-ZE64EWUV.js.map +0 -1
- package/dist/chunk-ZZ25FZG2.js.map +0 -1
- package/dist/client.cjs.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/core/client.cjs.map +0 -1
- package/dist/core/client.js.map +0 -1
- package/dist/core/error.cjs.map +0 -1
- package/dist/core/error.js.map +0 -1
- package/dist/core/index.cjs.map +0 -1
- package/dist/core/index.js.map +0 -1
- package/dist/core/resource.cjs.map +0 -1
- package/dist/core/resource.js.map +0 -1
- package/dist/edge.cjs.map +0 -1
- package/dist/edge.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/modelrouter/core.cjs.map +0 -1
- package/dist/modelrouter/core.js.map +0 -1
- package/dist/modelrouter/index.cjs.map +0 -1
- package/dist/modelrouter/index.js.map +0 -1
- package/dist/modelrouter/types.cjs.map +0 -1
- package/dist/modelrouter/types.js.map +0 -1
- package/dist/subagents/anthropic.cjs.map +0 -1
- package/dist/subagents/anthropic.js.map +0 -1
- package/dist/subagents/index.cjs.map +0 -1
- package/dist/subagents/index.js.map +0 -1
- package/dist/subagents/prompts.cjs.map +0 -1
- package/dist/subagents/prompts.js.map +0 -1
- package/dist/subagents/types.cjs.map +0 -1
- package/dist/subagents/types.js.map +0 -1
- package/dist/subagents/vercel.cjs.map +0 -1
- package/dist/subagents/vercel.js.map +0 -1
- package/dist/tools/compact/core.cjs.map +0 -1
- package/dist/tools/compact/core.js.map +0 -1
- package/dist/tools/compact/index.cjs.map +0 -1
- package/dist/tools/compact/index.js.map +0 -1
- package/dist/tools/compact/types.cjs.map +0 -1
- package/dist/tools/compact/types.js.map +0 -1
- package/dist/tools/fastapply/anthropic.cjs.map +0 -1
- package/dist/tools/fastapply/anthropic.js.map +0 -1
- package/dist/tools/fastapply/apply.cjs.map +0 -1
- package/dist/tools/fastapply/apply.js.map +0 -1
- package/dist/tools/fastapply/core.cjs.map +0 -1
- package/dist/tools/fastapply/core.js.map +0 -1
- package/dist/tools/fastapply/index.cjs.map +0 -1
- package/dist/tools/fastapply/index.js.map +0 -1
- package/dist/tools/fastapply/openai.cjs.map +0 -1
- package/dist/tools/fastapply/openai.js.map +0 -1
- package/dist/tools/fastapply/prompts.cjs.map +0 -1
- package/dist/tools/fastapply/prompts.js.map +0 -1
- package/dist/tools/fastapply/types.cjs.map +0 -1
- package/dist/tools/fastapply/types.js.map +0 -1
- package/dist/tools/fastapply/vercel.cjs.map +0 -1
- package/dist/tools/fastapply/vercel.js.map +0 -1
- package/dist/tools/index.cjs.map +0 -1
- package/dist/tools/index.js.map +0 -1
- package/dist/tools/utils/resilience.cjs.map +0 -1
- package/dist/tools/utils/resilience.js.map +0 -1
- package/dist/tools/warp_grep/agent/config.cjs.map +0 -1
- package/dist/tools/warp_grep/agent/config.js.map +0 -1
- package/dist/tools/warp_grep/agent/formatter.cjs.map +0 -1
- package/dist/tools/warp_grep/agent/formatter.js.map +0 -1
- package/dist/tools/warp_grep/agent/parser.cjs.map +0 -1
- package/dist/tools/warp_grep/agent/parser.js.map +0 -1
- package/dist/tools/warp_grep/agent/runner.cjs.map +0 -1
- package/dist/tools/warp_grep/agent/runner.js.map +0 -1
- package/dist/tools/warp_grep/agent/types.cjs.map +0 -1
- package/dist/tools/warp_grep/agent/types.js.map +0 -1
- package/dist/tools/warp_grep/anthropic.cjs.map +0 -1
- package/dist/tools/warp_grep/anthropic.js.map +0 -1
- package/dist/tools/warp_grep/client.cjs.map +0 -1
- package/dist/tools/warp_grep/client.js.map +0 -1
- package/dist/tools/warp_grep/gemini.cjs.map +0 -1
- package/dist/tools/warp_grep/gemini.js.map +0 -1
- package/dist/tools/warp_grep/harness.cjs.map +0 -1
- package/dist/tools/warp_grep/harness.js.map +0 -1
- package/dist/tools/warp_grep/index.cjs.map +0 -1
- package/dist/tools/warp_grep/index.js.map +0 -1
- package/dist/tools/warp_grep/openai.cjs.map +0 -1
- package/dist/tools/warp_grep/openai.js.map +0 -1
- package/dist/tools/warp_grep/providers/code_storage_http.cjs.map +0 -1
- package/dist/tools/warp_grep/providers/code_storage_http.js.map +0 -1
- package/dist/tools/warp_grep/providers/local.cjs.map +0 -1
- package/dist/tools/warp_grep/providers/local.js.map +0 -1
- package/dist/tools/warp_grep/providers/remote.cjs.map +0 -1
- package/dist/tools/warp_grep/providers/remote.js.map +0 -1
- package/dist/tools/warp_grep/providers/types.cjs.map +0 -1
- package/dist/tools/warp_grep/providers/types.js.map +0 -1
- package/dist/tools/warp_grep/utils/files.cjs.map +0 -1
- package/dist/tools/warp_grep/utils/files.js.map +0 -1
- package/dist/tools/warp_grep/utils/github.cjs.map +0 -1
- package/dist/tools/warp_grep/utils/github.js.map +0 -1
- package/dist/tools/warp_grep/utils/paths.cjs.map +0 -1
- package/dist/tools/warp_grep/utils/paths.js.map +0 -1
- package/dist/tools/warp_grep/utils/ripgrep.cjs.map +0 -1
- package/dist/tools/warp_grep/utils/ripgrep.js.map +0 -1
- package/dist/tools/warp_grep/vercel.cjs.map +0 -1
- package/dist/tools/warp_grep/vercel.js.map +0 -1
- package/dist/version.cjs.map +0 -1
- package/dist/version.js.map +0 -1
|
@@ -5,27 +5,27 @@ import {
|
|
|
5
5
|
execute,
|
|
6
6
|
vercel_default,
|
|
7
7
|
warpGrepJsonSchema
|
|
8
|
-
} from "../../chunk-
|
|
9
|
-
import "../../chunk-
|
|
8
|
+
} from "../../chunk-SU7AAS3O.js";
|
|
9
|
+
import "../../chunk-UAPK3AIJ.js";
|
|
10
10
|
import {
|
|
11
11
|
formatResult
|
|
12
|
-
} from "../../chunk-
|
|
13
|
-
import "../../chunk-
|
|
14
|
-
import "../../chunk-
|
|
15
|
-
import "../../chunk-
|
|
16
|
-
import "../../chunk-
|
|
17
|
-
import "../../chunk-
|
|
18
|
-
import "../../chunk-
|
|
19
|
-
import "../../chunk-
|
|
20
|
-
import "../../chunk-
|
|
21
|
-
import "../../chunk-
|
|
22
|
-
import "../../chunk-
|
|
23
|
-
import "../../chunk-
|
|
24
|
-
import "../../chunk-
|
|
25
|
-
import "../../chunk-
|
|
26
|
-
import "../../chunk-
|
|
27
|
-
import "../../chunk-
|
|
28
|
-
import "../../chunk-
|
|
12
|
+
} from "../../chunk-WBTXEJOC.js";
|
|
13
|
+
import "../../chunk-HDP4QAZL.js";
|
|
14
|
+
import "../../chunk-RYVW7RUM.js";
|
|
15
|
+
import "../../chunk-OPDWMD4Q.js";
|
|
16
|
+
import "../../chunk-LISSWRUD.js";
|
|
17
|
+
import "../../chunk-44OIEPIO.js";
|
|
18
|
+
import "../../chunk-M34E2AMK.js";
|
|
19
|
+
import "../../chunk-4OUGA3KS.js";
|
|
20
|
+
import "../../chunk-NWGRW4V7.js";
|
|
21
|
+
import "../../chunk-5NSYDT36.js";
|
|
22
|
+
import "../../chunk-JBAY3PRV.js";
|
|
23
|
+
import "../../chunk-6WP7EA4F.js";
|
|
24
|
+
import "../../chunk-EQAWWVKV.js";
|
|
25
|
+
import "../../chunk-TS3OJ4LA.js";
|
|
26
|
+
import "../../chunk-UZCXOOZO.js";
|
|
27
|
+
import "../../chunk-NRG6QX3L.js";
|
|
28
|
+
import "../../chunk-MLKGABMK.js";
|
|
29
29
|
export {
|
|
30
30
|
createGitHubReadFileTool,
|
|
31
31
|
createGitHubSearchTool,
|
|
@@ -35,4 +35,3 @@ export {
|
|
|
35
35
|
formatResult,
|
|
36
36
|
warpGrepJsonSchema
|
|
37
37
|
};
|
|
38
|
-
//# sourceMappingURL=vercel.js.map
|
package/dist/version.cjs
CHANGED
|
@@ -27,7 +27,7 @@ module.exports = __toCommonJS(version_exports);
|
|
|
27
27
|
// package.json
|
|
28
28
|
var package_default = {
|
|
29
29
|
name: "@morphllm/morphsdk",
|
|
30
|
-
version: "0.2.
|
|
30
|
+
version: "0.2.201",
|
|
31
31
|
description: "TypeScript SDK and CLI for Morph Fast Apply integration",
|
|
32
32
|
type: "module",
|
|
33
33
|
main: "./dist/index.cjs",
|
|
@@ -139,12 +139,11 @@ var package_default = {
|
|
|
139
139
|
"dist/**/*.js",
|
|
140
140
|
"dist/**/*.cjs",
|
|
141
141
|
"dist/**/*.d.ts",
|
|
142
|
-
"dist/**/*.map",
|
|
143
142
|
"!dist/**/__tests__/**",
|
|
144
143
|
"!dist/**/*.test.*"
|
|
145
144
|
],
|
|
146
145
|
scripts: {
|
|
147
|
-
build: "tsup version.ts index.ts edge.ts client.ts core/index.ts core/client.ts core/resource.ts core/error.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts --format esm,cjs --
|
|
146
|
+
build: "tsup version.ts index.ts edge.ts client.ts core/index.ts core/client.ts core/resource.ts core/error.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts --format esm,cjs --clean --dts --dts-resolve && tsup ai-sdk/index.ts --format esm,cjs --dts --no-clean --out-dir dist/ai-sdk",
|
|
148
147
|
prepare: "npm run build",
|
|
149
148
|
typecheck: "tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json",
|
|
150
149
|
lint: "eslint .",
|
|
@@ -228,4 +227,3 @@ var SDK_VERSION = package_default.version;
|
|
|
228
227
|
0 && (module.exports = {
|
|
229
228
|
SDK_VERSION
|
|
230
229
|
});
|
|
231
|
-
//# sourceMappingURL=version.cjs.map
|
package/dist/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@morphllm/morphsdk",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.201",
|
|
4
4
|
"description": "TypeScript SDK and CLI for Morph Fast Apply integration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -112,12 +112,11 @@
|
|
|
112
112
|
"dist/**/*.js",
|
|
113
113
|
"dist/**/*.cjs",
|
|
114
114
|
"dist/**/*.d.ts",
|
|
115
|
-
"dist/**/*.map",
|
|
116
115
|
"!dist/**/__tests__/**",
|
|
117
116
|
"!dist/**/*.test.*"
|
|
118
117
|
],
|
|
119
118
|
"scripts": {
|
|
120
|
-
"build": "tsup version.ts index.ts edge.ts client.ts core/index.ts core/client.ts core/resource.ts core/error.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts --format esm,cjs --
|
|
119
|
+
"build": "tsup version.ts index.ts edge.ts client.ts core/index.ts core/client.ts core/resource.ts core/error.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.ts --format esm,cjs --clean --dts --dts-resolve && tsup ai-sdk/index.ts --format esm,cjs --dts --no-clean --out-dir dist/ai-sdk",
|
|
121
120
|
"prepare": "npm run build",
|
|
122
121
|
"typecheck": "tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json",
|
|
123
122
|
"lint": "eslint .",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../ai-sdk/index.ts"],"sourcesContent":["import {\n createOpenAICompatible,\n type OpenAICompatibleProvider,\n type OpenAICompatibleProviderSettings,\n} from '@ai-sdk/openai-compatible'\n\nexport const MORPH_API_BASE_URL = 'https://api.morphllm.com/v1'\n\n/** Public model identifiers served by Morph's shared API. */\nexport type MorphChatModelId =\n | 'morph-kimik3'\n | 'morph-glm53-744b'\n | 'morph-glm53flash'\n | 'morph-dsv41flash'\n | 'morph-dsv4flash'\n | (string & {})\n\nexport interface MorphProviderSettings {\n /**\n * Morph API key. Defaults to the `MORPH_API_KEY` environment variable.\n */\n apiKey?: string\n\n /**\n * Base URL for API calls. Set this to the URL of a dedicated Morph endpoint\n * when using reserved capacity.\n */\n baseURL?: string\n\n /** Custom headers to include with every request. */\n headers?: Record<string, string>\n\n /** Custom fetch implementation, useful for middleware and tests. */\n fetch?: OpenAICompatibleProviderSettings['fetch']\n}\n\nexport type MorphProvider = OpenAICompatibleProvider<\n MorphChatModelId,\n string,\n string,\n string\n>\n\n/**\n * Creates a Morph provider for the Vercel AI SDK.\n */\nexport function createMorph(options: MorphProviderSettings = {}): MorphProvider {\n return createOpenAICompatible<\n MorphChatModelId,\n string,\n string,\n string\n >({\n name: 'morph',\n baseURL: options.baseURL ?? MORPH_API_BASE_URL,\n apiKey: options.apiKey ?? process.env.MORPH_API_KEY,\n headers: options.headers,\n fetch: options.fetch,\n includeUsage: true,\n supportsStructuredOutputs: true,\n })\n}\n\n/** Default Morph provider using `MORPH_API_KEY`. */\nexport const morph = createMorph()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,+BAIO;AAEA,IAAM,qBAAqB;AAwC3B,SAAS,YAAY,UAAiC,CAAC,GAAkB;AAC9E,aAAO,iDAKL;AAAA,IACA,MAAM;AAAA,IACN,SAAS,QAAQ,WAAW;AAAA,IAC5B,QAAQ,QAAQ,UAAU,QAAQ,IAAI;AAAA,IACtC,SAAS,QAAQ;AAAA,IACjB,OAAO,QAAQ;AAAA,IACf,cAAc;AAAA,IACd,2BAA2B;AAAA,EAC7B,CAAC;AACH;AAGO,IAAM,QAAQ,YAAY;","names":[]}
|
package/dist/ai-sdk/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../ai-sdk/index.ts"],"sourcesContent":["import {\n createOpenAICompatible,\n type OpenAICompatibleProvider,\n type OpenAICompatibleProviderSettings,\n} from '@ai-sdk/openai-compatible'\n\nexport const MORPH_API_BASE_URL = 'https://api.morphllm.com/v1'\n\n/** Public model identifiers served by Morph's shared API. */\nexport type MorphChatModelId =\n | 'morph-kimik3'\n | 'morph-glm53-744b'\n | 'morph-glm53flash'\n | 'morph-dsv41flash'\n | 'morph-dsv4flash'\n | (string & {})\n\nexport interface MorphProviderSettings {\n /**\n * Morph API key. Defaults to the `MORPH_API_KEY` environment variable.\n */\n apiKey?: string\n\n /**\n * Base URL for API calls. Set this to the URL of a dedicated Morph endpoint\n * when using reserved capacity.\n */\n baseURL?: string\n\n /** Custom headers to include with every request. */\n headers?: Record<string, string>\n\n /** Custom fetch implementation, useful for middleware and tests. */\n fetch?: OpenAICompatibleProviderSettings['fetch']\n}\n\nexport type MorphProvider = OpenAICompatibleProvider<\n MorphChatModelId,\n string,\n string,\n string\n>\n\n/**\n * Creates a Morph provider for the Vercel AI SDK.\n */\nexport function createMorph(options: MorphProviderSettings = {}): MorphProvider {\n return createOpenAICompatible<\n MorphChatModelId,\n string,\n string,\n string\n >({\n name: 'morph',\n baseURL: options.baseURL ?? MORPH_API_BASE_URL,\n apiKey: options.apiKey ?? process.env.MORPH_API_KEY,\n headers: options.headers,\n fetch: options.fetch,\n includeUsage: true,\n supportsStructuredOutputs: true,\n })\n}\n\n/** Default Morph provider using `MORPH_API_KEY`. */\nexport const morph = createMorph()\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAGK;AAEA,IAAM,qBAAqB;AAwC3B,SAAS,YAAY,UAAiC,CAAC,GAAkB;AAC9E,SAAO,uBAKL;AAAA,IACA,MAAM;AAAA,IACN,SAAS,QAAQ,WAAW;AAAA,IAC5B,QAAQ,QAAQ,UAAU,QAAQ,IAAI;AAAA,IACtC,SAAS,QAAQ;AAAA,IACjB,OAAO,QAAQ;AAAA,IACf,cAAc;AAAA,IACd,2BAA2B;AAAA,EAC7B,CAAC;AACH;AAGO,IAAM,QAAQ,YAAY;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/compact/utils.ts"],"sourcesContent":["import { CompactClient } from './core.js';\n\nexport async function compactFileContexts(\n files: { path: string; content: string }[],\n query: string,\n apiKey?: string,\n apiUrl?: string,\n maxTokens: number = 10000,\n maxConcurrency: number = 3\n): Promise<{ path: string; content: string }[]> {\n const totalLength = files.reduce((sum, file) => sum + file.content.length, 0);\n const estimatedTokens = totalLength / 3;\n\n if (estimatedTokens <= maxTokens) {\n return files;\n }\n\n let compressionRatio = maxTokens / estimatedTokens;\n compressionRatio = Math.max(0.3, Math.min(0.99, compressionRatio));\n\n const client = new CompactClient({\n morphApiKey: apiKey,\n morphApiUrl: apiUrl,\n });\n\n const results: { path: string; content: string }[] = [];\n const inProgress = new Set<Promise<void>>();\n\n for (const file of files) {\n if (file.content.length < 500) {\n results.push({ path: file.path, content: file.content });\n continue;\n }\n\n const task = async () => {\n try {\n const result = await client.compact({\n input: file.content,\n query,\n compressionRatio,\n preserveRecent: 0,\n });\n results.push({ path: file.path, content: result.output });\n } catch (error) {\n console.error(`[compactFileContexts] Failed to compact file ${file.path}:`, error);\n results.push({ path: file.path, content: file.content });\n }\n };\n\n const promise = task().finally(() => inProgress.delete(promise));\n inProgress.add(promise);\n\n if (inProgress.size >= maxConcurrency) {\n await Promise.race(inProgress);\n }\n }\n\n await Promise.all(inProgress);\n\n const orderMap = new Map(files.map((f, i) => [f.path, i]));\n return results.sort((a, b) => (orderMap.get(a.path) ?? 0) - (orderMap.get(b.path) ?? 0));\n}\n"],"m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B,QAAM,WAAW,IAAI,IAAI,MAAM,IAAI,CAAC,GAAG,MAAM,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;AACzD,SAAO,QAAQ,KAAK,CAAC,GAAG,OAAO,SAAS,IAAI,EAAE,IAAI,KAAK,MAAM,SAAS,IAAI,EAAE,IAAI,KAAK,EAAE;AACzF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../core/resource.ts"],"sourcesContent":["/**\n * Base class for every API resource (FastApply, Compact, …).\n *\n * Mirrors the OpenAI SDK's `APIResource`: a resource holds nothing but a\n * reference to the transport (`MorphAPIClient`) and delegates all HTTP to it.\n * Sub-resources receive the same client by reference, so configuration and the\n * fetch/retry/auth machinery live in exactly one place.\n */\nimport type { MorphAPIClient } from './client.js';\n\nexport abstract class APIResource {\n protected _client: MorphAPIClient;\n\n constructor(client: MorphAPIClient) {\n this._client = client;\n }\n}\n"],"mappings":";AAUO,IAAe,cAAf,MAA2B;AAAA,EACtB;AAAA,EAEV,YAAY,QAAwB;AAClC,SAAK,UAAU;AAAA,EACjB;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/utils/github.ts"],"sourcesContent":["/**\n * GitHub URL parsing utilities\n */\n\n/**\n * Parse GitHub URL or \"owner/repo\" shorthand into owner and repo components.\n * Handles: \"owner/repo\", \"https://github.com/owner/repo\", \"github.com/owner/repo.git\"\n */\nexport function parseGitHubUrl(input: string): { owner: string; repo: string } {\n input = input.trim();\n\n // Try URL patterns first\n const urlPattern = /^(?:https?:\\/\\/)?github\\.com\\/([^\\/]+)\\/([^\\/\\?\\#]+)/;\n const match = input.match(urlPattern);\n if (match) {\n return { owner: match[1], repo: match[2].replace(/\\.git$/, '') };\n }\n\n // Try \"owner/repo\" shorthand (reject if owner contains '.', e.g. \"github.com/owner\")\n const shortPattern = /^([^\\/]+)\\/([^\\/]+)$/;\n const shortMatch = input.match(shortPattern);\n if (shortMatch && !shortMatch[1].includes('.')) {\n return { owner: shortMatch[1], repo: shortMatch[2].replace(/\\.git$/, '') };\n }\n\n throw new Error(\n `Invalid GitHub URL or shorthand: \"${input}\". Expected \"owner/repo\" or \"https://github.com/owner/repo\"`\n );\n}\n"],"mappings":";AAQO,SAAS,eAAe,OAAgD;AAC7E,UAAQ,MAAM,KAAK;AAGnB,QAAM,aAAa;AACnB,QAAM,QAAQ,MAAM,MAAM,UAAU;AACpC,MAAI,OAAO;AACT,WAAO,EAAE,OAAO,MAAM,CAAC,GAAG,MAAM,MAAM,CAAC,EAAE,QAAQ,UAAU,EAAE,EAAE;AAAA,EACjE;AAGA,QAAM,eAAe;AACrB,QAAM,aAAa,MAAM,MAAM,YAAY;AAC3C,MAAI,cAAc,CAAC,WAAW,CAAC,EAAE,SAAS,GAAG,GAAG;AAC9C,WAAO,EAAE,OAAO,WAAW,CAAC,GAAG,MAAM,WAAW,CAAC,EAAE,QAAQ,UAAU,EAAE,EAAE;AAAA,EAC3E;AAEA,QAAM,IAAI;AAAA,IACR,qCAAqC,KAAK;AAAA,EAC5C;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/fastapply/prompts.ts"],"sourcesContent":["/**\n * System prompts for edit_file tool\n */\n\nexport const EDIT_FILE_TOOL_DESCRIPTION = `Use this tool to make an edit to an existing file.\n\nThis will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.\n\nWhen writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.\n\nFor example:\n\n// ... existing code ...\nFIRST_EDIT\n// ... existing code ...\nSECOND_EDIT\n// ... existing code ...\nTHIRD_EDIT\n// ... existing code ...\n\nYou should still bias towards repeating as few lines of the original file as possible to convey the change.\nBut, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.\n\nDO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.\n\nIf you plan on deleting a section, you must provide context before and after to delete it.\n\nMake sure it is clear what the edit should be, and where it should be applied.\nMake edits to a file in a single edit_file call instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.`;\n\nexport const EDIT_FILE_SYSTEM_PROMPT = `When the user is asking for edits to their code, use the edit_file tool to highlight the changes necessary and add comments to indicate where unchanged code has been skipped. For example:\n\n// ... existing code ...\n{{ edit_1 }}\n// ... existing code ...\n{{ edit_2 }}\n// ... existing code ...\n\nOften this will mean that the start/end of the file will be skipped, but that's okay! Rewrite the entire file ONLY if specifically requested. Always provide a brief explanation of the updates, unless the user specifically requests only the code.\n\nThese edit codeblocks are also read by a less intelligent language model, colloquially called the apply model, to update the file. To help specify the edit to the apply model, you will be very careful when generating the codeblock to not introduce ambiguity. You will specify all unchanged regions (code and comments) of the file with \"// ... existing code ...\" comment markers. This will ensure the apply model will not delete existing unchanged code or comments when editing the file.`;\n\n"],"mappings":";AAIO,IAAM,6BAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0BnC,IAAM,0BAA0B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/utils/resilience.ts"],"sourcesContent":["/**\n * Resilience utilities for retry logic and timeout handling\n */\n\nimport { SDK_VERSION } from '../../version.js';\n\nexport interface RetryConfig {\n maxRetries?: number; // Default: 3\n initialDelay?: number; // Default: 1000ms\n maxDelay?: number; // Default: 30000ms\n backoffMultiplier?: number; // Default: 2\n retryableErrors?: string[]; // Default: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND']\n onRetry?: (attempt: number, error: Error) => void;\n}\n\nconst DEFAULT_RETRY_CONFIG: Required<Omit<RetryConfig, 'onRetry'>> = {\n maxRetries: 3,\n initialDelay: 1000,\n maxDelay: 30000,\n backoffMultiplier: 2,\n retryableErrors: ['ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'],\n};\n\n/**\n * Retry a fetch request with exponential backoff\n * \n * @param url - Request URL\n * @param options - Fetch options\n * @param retryConfig - Retry configuration\n * @returns Response from fetch\n * \n * @example\n * ```typescript\n * const response = await fetchWithRetry(\n * 'https://api.example.com/data',\n * { method: 'POST', body: JSON.stringify(data) },\n * { maxRetries: 5, initialDelay: 500 }\n * );\n * ```\n */\nexport async function fetchWithRetry(\n url: string,\n options: RequestInit,\n retryConfig: RetryConfig = {}\n): Promise<Response> {\n const {\n maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,\n initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,\n maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,\n backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,\n retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,\n onRetry,\n } = retryConfig;\n\n let lastError: Error | null = null;\n let delay = initialDelay;\n\n // Inject SDK version header (caller-provided headers can override)\n options = { ...options, headers: { 'X-Morph-SDK-Version': SDK_VERSION, ...options.headers } };\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const response = await fetch(url, options);\n \n // Retry on 429 (rate limit) or 503 (service unavailable)\n if (response.status === 429 || response.status === 503) {\n if (attempt < maxRetries) {\n // Check for Retry-After header\n const retryAfter = response.headers.get('Retry-After');\n const waitTime = retryAfter \n ? parseInt(retryAfter) * 1000 \n : Math.min(delay, maxDelay);\n \n const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);\n if (onRetry) {\n onRetry(attempt + 1, error);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n continue;\n }\n }\n\n return response;\n } catch (error) {\n lastError = error as Error;\n \n // Check if error is retryable\n const isRetryable = retryableErrors.some(errType => \n lastError?.message?.includes(errType)\n );\n\n if (!isRetryable || attempt === maxRetries) {\n throw lastError;\n }\n\n // Exponential backoff\n const waitTime = Math.min(delay, maxDelay);\n if (onRetry) {\n onRetry(attempt + 1, lastError);\n }\n \n await sleep(waitTime);\n delay *= backoffMultiplier;\n }\n }\n\n throw lastError || new Error('Max retries exceeded');\n}\n\n/**\n * Add timeout to any promise\n * \n * @param promise - Promise to wrap with timeout\n * @param timeoutMs - Timeout in milliseconds\n * @param errorMessage - Optional custom error message\n * @returns Promise that rejects if timeout is reached\n * \n * @example\n * ```typescript\n * const result = await withTimeout(\n * fetchData(),\n * 5000,\n * 'Data fetch timed out'\n * );\n * ```\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n errorMessage?: string\n): Promise<T> {\n let timeoutId: NodeJS.Timeout | number;\n \n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n\n try {\n const result = await Promise.race([promise, timeoutPromise]);\n clearTimeout(timeoutId!);\n return result;\n } catch (error) {\n clearTimeout(timeoutId!);\n throw error;\n }\n}\n\n/**\n * Sleep for specified milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Unified error type for all tools\n */\nexport class MorphError extends Error {\n constructor(\n message: string,\n public code: string,\n public statusCode?: number,\n public retryable: boolean = false\n ) {\n super(message);\n this.name = 'MorphError';\n }\n}\n\n\n"],"mappings":";;;;;AAeA,IAAM,uBAA+D;AAAA,EACnE,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,iBAAiB,CAAC,gBAAgB,aAAa,WAAW;AAC5D;AAmBA,eAAsB,eACpB,KACA,SACA,cAA2B,CAAC,GACT;AACnB,QAAM;AAAA,IACJ,aAAa,qBAAqB;AAAA,IAClC,eAA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AAW;AACvD,gBAAY,WAAW,MAAM;AAC3B,aAAO,IAAI,MAAM,gBAAgB,6BAA6B,SAAS,IAAI,CAAC;AAAA,IAC9E,GAAG,SAAS;AAAA,EACd,CAAC;AAED,MAAI;AACF,UAAM,SAAS,MAAM,QAAQ,KAAK,CAAC,SAAS,cAAc,CAAC;AAC3D,iBAAa,SAAU;AACvB,WAAO;AAAA,EACT,SAAS,OAAO;AACd,iBAAa,SAAU;AACvB,UAAM;AAAA,EACR;AACF;AAKA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,aAAW,WAAW,SAAS,EAAE,CAAC;AACvD;AAKO,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YACE,SACO,MACA,YACA,YAAqB,OAC5B;AACA,UAAM,OAAO;AAJN;AACA;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/providers/remote.ts"],"sourcesContent":["/**\n * RemoteCommandsProvider - wraps simple RemoteCommands into WarpGrepProvider\n * \n * Handles parsing of raw stdout from grep/read/listDir commands.\n * Users just return stdout, SDK handles all format conversion.\n */\n\nimport type { WarpGrepProvider, GrepResult, ReadResult, GlobResult, ListDirectoryEntry } from './types.js';\nimport type { RemoteCommands } from '../types.js';\nimport { AGENT_CONFIG } from '../agent/config.js';\n\n/**\n * Directories/files to always skip (exact name match)\n */\nconst SKIP_NAMES = new Set([\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'Pods', '.bundle',\n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs',\n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n // Cache\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n // IDE\n '.idea', '.vscode', '.vs',\n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n // Temp\n 'tmp', 'temp', '.tmp', '.temp',\n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n]);\n\n/**\n * File extensions to skip\n */\nconst SKIP_EXTENSIONS = new Set([\n '.min.js', '.min.css', '.bundle.js',\n '.wasm', '.so', '.dll', '.pyc',\n '.map', '.js.map',\n]);\n\n/**\n * Check if a filename should be skipped\n */\nfunction shouldSkip(name: string): boolean {\n // Skip exact name matches\n if (SKIP_NAMES.has(name)) return true;\n \n // Skip hidden files/directories (start with .)\n if (name.startsWith('.')) return true;\n \n // Skip files with certain extensions\n for (const ext of SKIP_EXTENSIONS) {\n if (name.endsWith(ext)) return true;\n }\n \n return false;\n}\n\n/**\n * Wraps simple RemoteCommands functions into a full WarpGrepProvider.\n * \n * This allows users to provide three simple functions that return raw stdout,\n * and the SDK handles all parsing internally.\n * \n * @example\n * ```typescript\n * const provider = new RemoteCommandsProvider('/home/repo', {\n * grep: async (pattern, path) => {\n * const r = await sandbox.run(`rg '${pattern}' '${path}'`);\n * return r.stdout;\n * },\n * read: async (path, start, end) => {\n * const r = await sandbox.run(`sed -n '${start},${end}p' '${path}'`);\n * return r.stdout;\n * },\n * listDir: async (path, maxDepth) => {\n * const r = await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`);\n * return r.stdout;\n * },\n * });\n * ```\n */\nexport class RemoteCommandsProvider implements WarpGrepProvider {\n constructor(\n private readonly repoRoot: string,\n private readonly commands: RemoteCommands\n ) {}\n\n /**\n * Run grep command and parse ripgrep output\n */\n async grep(params: { pattern: string; path: string; glob?: string }): Promise<GrepResult> {\n try {\n const stdout = await this.commands.grep(params.pattern, params.path, params.glob);\n \n // Parse ripgrep output: each line is \"path:line:content\" or \"path-line-content\" for context\n const lines = (stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((l) => l.length > 0);\n \n // Truncate if too many lines (return partial results like training harness)\n if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {\n const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines };\n } catch (error) {\n return {\n lines: [],\n error: `[GREP ERROR] ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Read file and add line numbers\n */\n async read(params: { path: string; start?: number; end?: number }): Promise<ReadResult> {\n const rawStart = params.start;\n const rawEnd = params.end;\n \n const startValid = rawStart === undefined || (Number.isFinite(rawStart) && rawStart > 0);\n const endValid = rawEnd === undefined || (Number.isFinite(rawEnd) && rawEnd > 0);\n const rangeValid = startValid && endValid && \n (rawStart === undefined || rawEnd === undefined || rawStart <= rawEnd);\n \n const start = rangeValid && rawStart !== undefined ? rawStart : 1;\n const end = rangeValid && rawEnd !== undefined ? rawEnd : 1_000_000;\n \n try {\n const stdout = await this.commands.read(params.path, start, end);\n \n // Split content into lines and add line numbers\n const contentLines = (stdout || '').split('\\n');\n \n // Remove trailing empty line if present (common with sed output)\n if (contentLines.length > 0 && contentLines[contentLines.length - 1] === '') {\n contentLines.pop();\n }\n \n // Format as \"lineNumber|content\"\n const lines = contentLines.map((content, idx) => `${start + idx}|${content}`);\n \n // Check if output is too large\n if (lines.length > AGENT_CONFIG.MAX_READ_LINES) {\n const truncated = lines.slice(0, AGENT_CONFIG.MAX_READ_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${lines.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines };\n } catch (error) {\n return {\n lines: [],\n error: `[READ ERROR] ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * List directory and parse find output\n */\n async listDirectory(params: { \n path: string; \n pattern?: string | null; \n maxResults?: number; \n maxDepth?: number;\n }): Promise<ListDirectoryEntry[]> {\n const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;\n \n try {\n const stdout = await this.commands.listDir(params.path, maxDepth);\n \n // Parse find output: one path per line\n const paths = (stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((p) => p.length > 0);\n \n const regex = params.pattern ? new RegExp(params.pattern) : null;\n const entries: ListDirectoryEntry[] = [];\n \n for (const fullPath of paths) {\n // Skip the root path itself\n if (fullPath === params.path || fullPath === this.repoRoot) continue;\n \n const name = fullPath.split('/').pop() || '';\n \n // Simple name-based filtering - skip junk dirs/files\n if (shouldSkip(name)) continue;\n \n // Apply pattern filter if provided\n if (regex && !regex.test(name)) continue;\n \n // Determine relative path\n let relativePath = fullPath;\n if (fullPath.startsWith(this.repoRoot)) {\n relativePath = fullPath.slice(this.repoRoot.length).replace(/^\\//, '');\n }\n \n // Calculate depth based on path separators\n const depth = relativePath.split('/').filter(Boolean).length - 1;\n \n // Determine if it's a directory (ends with / or infer from path structure)\n // Note: Most sandbox find commands don't indicate type, so we guess based on extension\n const hasExtension = name.includes('.') && !name.startsWith('.');\n const type: 'file' | 'dir' = hasExtension ? 'file' : 'dir';\n \n entries.push({\n name,\n path: relativePath,\n type,\n depth: Math.max(0, depth),\n });\n \n if (entries.length >= maxResults) break;\n }\n \n return entries;\n } catch (error) {\n // Return empty array on error (consistent with LocalRipgrepProvider)\n return [];\n }\n }\n\n /**\n * Glob search - finds files matching a pattern.\n * Falls back to a grep --files approach via the listDir command.\n */\n async glob(params: { pattern: string; path?: string }): Promise<GlobResult> {\n const searchPath = params.path || this.repoRoot;\n try {\n // Use find with -name to simulate glob\n const stdout = await this.commands.listDir(searchPath, 10);\n const allPaths = (stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((p) => p.length > 0);\n\n // Simple glob matching: convert glob pattern to regex\n const globToRegex = (glob: string) => {\n const escaped = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.');\n return new RegExp(escaped);\n };\n const regex = globToRegex(params.pattern);\n\n const matched = allPaths\n .filter(p => {\n const name = p.split('/').pop() || '';\n return regex.test(name) && !shouldSkip(name);\n });\n\n const totalFound = matched.length;\n return { files: matched.slice(0, 100), searchDir: searchPath, totalFound };\n } catch (error) {\n return {\n files: [],\n searchDir: searchPath,\n totalFound: 0,\n error: `[GLOB ERROR] ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n}\n"],"mappings":";;;;;AAcA,IAAM,aAAa,oBAAI,IAAI;AAAA;AAAA,EAEzB;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAO;AAAA;AAAA,EAEvB;AAAA,EAAgB;AAAA,EAAoB;AAAA,EAAS;AAAA,EAC7C;AAAA,EAAU;AAAA,EAAQ;AAAA;AAAA,EAElB;AAAA,EAAe;AAAA,EAAiB;AAAA,EAAe;AAAA,EAC/C;AAAA,EAAS;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAQ;AAAA;AAAA,EAEjC;AAAA,EAAQ;AAAA,EAAS;AAAA,EAAO;AAAA,EAAU;AAAA,EAAU;AAAA,EAC5C;AAAA,EAAS;AAAA,EAAS;AAAA,EAAW;AAAA,EAAW;AAAA;AAAA,EAExC;AAAA,EAAU;AAAA,EAAiB;AAAA,EAAU;AAAA,EAAO;AAAA;AAAA,EAE5C;AAAA,EAAS;AAAA,EAAW;AAAA;AAAA,EAEpB;AAAA,EAAY;AAAA,EAAa;AAAA,EAAW;AAAA;AAAA,EAEpC;AAAA,EAAO;AAAA,EAAQ;AAAA,EAAQ;AAAA;AAAA,EAEvB;AAAA,EAAqB;AAAA,EAAa;AAAA,EAAkB;AAAA,EACpD;AAAA,EAAc;AAAA,EAAgB;AAChC,CAAC;AAKD,IAAM,kBAAkB,oBAAI,IAAI;AAAA,EAC9B;AAAA,EAAW;AAAA,EAAY;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AK;AACX,cAAM,OAAO,EAAE,MAAM,GAAG,EAAE,IAAI,KAAK;AACnC,eAAO,MAAM,KAAK,IAAI,KAAK,CAAC,WAAW,IAAI;AAAA,MAC7C,CAAC;AAEH,YAAM,aAAa,QAAQ;AAC3B,aAAO,EAAE,OAAO,QAAQ,MAAM,GAAG,GAAG,GAAG,WAAW,YAAY,WAAW;AAAA,IAC3E,SAAS,OAAO;AACd,aAAO;AAAA,QACL,OAAO,CAAC;AAAA,QACR,WAAW;AAAA,QACX,YAAY;AAAA,QACZ,OAAO,gBAAgB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,MAC/E;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/compact/core.ts"],"sourcesContent":["/**\n * CompactClient — calls the Morph /v1/compact endpoint.\n *\n * Returns per-message compacted_line_ranges showing which lines were removed.\n * HTTP goes through the shared `MorphAPIClient` transport.\n */\nimport { MorphAPIClient } from '../../core/client.js';\nimport { APIResource } from '../../core/resource.js';\nimport { MorphError } from '../utils/resilience.js';\nimport type { CompactConfig, CompactInput, CompactResult } from './types.js';\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\nconst DEFAULT_TIMEOUT = 120000;\n\nfunction resolveClient(clientOrConfig: MorphAPIClient | CompactConfig): MorphAPIClient {\n if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;\n return new MorphAPIClient({\n apiKey: clientOrConfig.morphApiKey,\n baseURL: clientOrConfig.morphApiUrl ?? DEFAULT_API_URL,\n timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT,\n retryConfig: clientOrConfig.retryConfig,\n debug: clientOrConfig.debug,\n });\n}\n\n/**\n * @deprecated Prefer the unified `MorphClient` (`new MorphClient({ apiKey }).compact`).\n * In edge runtimes where `MorphClient` is unavailable, pass a shared transport:\n * `new CompactClient(new MorphAPIClient({ apiKey }))`. Kept only for backwards compatibility.\n */\nexport class CompactClient extends APIResource {\n /** Resolved URL/timeout, exposed for backwards-compatible introspection. */\n readonly config: { morphApiUrl: string; timeout: number; debug: boolean };\n\n constructor(clientOrConfig: MorphAPIClient | CompactConfig = {}) {\n super(resolveClient(clientOrConfig));\n const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;\n this.config = {\n morphApiUrl: this._client.baseURL,\n timeout: cfg.timeout ?? DEFAULT_TIMEOUT,\n debug: cfg.debug ?? false,\n };\n }\n\n /**\n * Compact messages or text via /v1/compact.\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.compact({\n * input: codeFile,\n * query: \"authentication\",\n * compressionRatio: 0.5,\n * });\n * console.log(result.output);\n * ```\n */\n async compact(input: CompactInput): Promise<CompactResult> {\n // Build request body with snake_case keys\n const body: Record<string, unknown> = {\n compression_ratio: input.compressionRatio ?? 0.5,\n preserve_recent: input.preserveRecent ?? 2,\n model: input.model ?? 'morph-compactor',\n include_line_ranges: input.includeLineRanges ?? true,\n include_markers: input.includeMarkers ?? true,\n };\n\n if (input.query !== undefined) body.query = input.query;\n\n // Normalize input: string → { input }, array → { messages }, messages field → { messages }\n if (input.messages) body.messages = input.messages;\n else if (typeof input.input === 'string') body.input = input.input;\n else if (Array.isArray(input.input)) body.messages = input.input;\n else throw new Error(\"Either 'input' or 'messages' must be provided\");\n\n try {\n return await this._client.post<CompactResult>('/v1/compact', { body, timeout: this.config.timeout });\n } catch (err) {\n // Preserve the historical `Compact API error <status>: ...` message shape.\n if (err instanceof MorphError) {\n throw new Error(`Compact API error ${err.statusCode}: ${err.message}`);\n }\n throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAM,kBAAkB;AACxB,IAAM,kBAAkB;AAExB,SAAS,cAAc,gBAAgE;AACrF,MAAI,0BAA0B,eAAgB,QAAO;AACrD,SAAO,IAAI,eAAe;AAAA,IACxB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OAAO,EAAE;AAAA,MACvE;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../factories/openai.ts","../factories/anthropic.ts","../factories/vercel.ts","../client.ts"],"sourcesContent":["/**\n * OpenAI Tool Factory for MorphClient\n * \n * Creates OpenAI-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool, createGitHubSearchTool } from '../tools/warp_grep/openai.js';\nimport { createEditFileTool } from '../tools/fastapply/openai.js';\nimport type { WarpGrepToolConfig, GitHubSearchToolConfig } from '../tools/warp_grep/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\n\n/**\n * Factory for creating OpenAI-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const editTool = morph.openai.createEditFileTool({ baseDir: './src' });\n * \n * // Use with OpenAI client\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [grepTool, editTool],\n * messages: [{ role: 'user', content: 'Find and fix the bug' }]\n * });\n * ```\n */\nexport class OpenAIToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create an OpenAI-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an OpenAI-compatible GitHub search tool\n *\n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns OpenAI ChatCompletionTool with execute and formatResult methods\n */\n createGitHubSearchTool(toolConfig?: Omit<GitHubSearchToolConfig, 'morphApiKey'>) {\n return createGitHubSearchTool({\n ...toolConfig,\n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Anthropic Tool Factory for MorphClient\n * \n * Creates Anthropic-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool, createGitHubSearchTool } from '../tools/warp_grep/anthropic.js';\nimport { createEditFileTool } from '../tools/fastapply/anthropic.js';\nimport { createExploreSubagent } from '../subagents/anthropic.js';\nimport type { WarpGrepToolConfig, GitHubSearchToolConfig } from '../tools/warp_grep/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\nimport type { ExploreSubagentConfig } from '../subagents/types.js';\n\n/**\n * Factory for creating Anthropic-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.anthropic.createWarpGrepTool({ repoRoot: '.' });\n * const editTool = morph.anthropic.createEditFileTool({ baseDir: './src' });\n * \n * // Use with Anthropic client\n * const response = await anthropic.messages.create({\n * model: 'claude-sonnet-4-5-20250929',\n * tools: [grepTool, editTool],\n * messages: [{ role: 'user', content: 'Find and fix the bug' }]\n * });\n * ```\n */\nexport class AnthropicToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create an Anthropic-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n\n }\n\n /**\n * Create an Anthropic-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Anthropic-compatible GitHub search tool\n *\n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Anthropic Tool with execute and formatResult methods\n */\n createGitHubSearchTool(toolConfig?: Omit<GitHubSearchToolConfig, 'morphApiKey'>) {\n return createGitHubSearchTool({\n ...toolConfig,\n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Explore subagent that searches the codebase and returns summaries\n *\n * @param config - Subagent configuration including client and model (morphApiKey inherited from MorphClient)\n * @returns Explore subagent with .tool, .run(), and .stream() methods\n */\n createExploreSubagent(config: Omit<ExploreSubagentConfig, 'morphApiKey'> & { client: any; model: string }) {\n return createExploreSubagent({\n ...config,\n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Vercel AI SDK Tool Factory for MorphClient\n * \n * Creates Vercel AI SDK-compatible tools that inherit the API key from MorphClient.\n */\n\nimport type { LanguageModel } from 'ai';\nimport type { MorphClientConfig } from '../client.js';\nimport { createWarpGrepTool, createGitHubSearchTool } from '../tools/warp_grep/vercel.js';\nimport { createEditFileTool } from '../tools/fastapply/vercel.js';\nimport { createExploreSubagent } from '../subagents/vercel.js';\nimport type { WarpGrepToolConfig, GitHubSearchToolConfig } from '../tools/warp_grep/types.js';\nimport type { EditFileConfig } from '../tools/fastapply/types.js';\nimport type { ExploreSubagentConfig } from '../subagents/types.js';\n\n/**\n * Factory for creating Vercel AI SDK-compatible tools with inherited API key\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });\n * \n * const grepTool = morph.vercel.createWarpGrepTool({ repoRoot: '.' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * \n * // Use with Vercel AI SDK\n * const result = await generateText({\n * model: anthropic('claude-sonnet-4-5-20250929'),\n * tools: { grep: grepTool, edit: editTool },\n * prompt: 'Find and fix the bug'\n * });\n * ```\n */\nexport class VercelToolFactory {\n constructor(private config: MorphClientConfig) {}\n\n /**\n * Create a Vercel AI SDK-compatible warp grep tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createWarpGrepTool(toolConfig: Omit<WarpGrepToolConfig, 'morphApiKey'>) {\n return createWarpGrepTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible edit file tool\n * \n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createEditFileTool(toolConfig: Omit<EditFileConfig, 'morphApiKey'> = {}) {\n return createEditFileTool({ \n ...toolConfig, \n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create a Vercel AI SDK-compatible GitHub search tool\n *\n * @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)\n * @returns Vercel AI SDK tool\n */\n createGitHubSearchTool(toolConfig?: Omit<GitHubSearchToolConfig, 'morphApiKey'>) {\n return createGitHubSearchTool({\n ...toolConfig,\n morphApiKey: this.config.apiKey,\n });\n }\n\n /**\n * Create an Explore subagent that searches the codebase and returns summaries\n *\n * @param config - Subagent configuration including model (morphApiKey inherited from MorphClient)\n * @returns Explore subagent with .tool, .run(), and .stream() methods\n */\n createExploreSubagent(config: Omit<ExploreSubagentConfig, 'morphApiKey'> & { model: LanguageModel }) {\n return createExploreSubagent({\n ...config,\n morphApiKey: this.config.apiKey,\n });\n }\n}\n\n","/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface\n * \n * @example\n * ```typescript\n * import { MorphClient } from '@morphllm/morphsdk';\n * \n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * \n * // Direct execution\n * await morph.fastApply.execute({ target_filepath: 'src/index.ts', ... });\n * await morph.warpGrep.execute({ query: 'Find auth', repoRoot: '.' });\n * \n * // Tool creation for AI agents (API key inherited)\n * const grepTool = morph.openai.createWarpGrepTool({ repoRoot: '.' });\n * const editTool = morph.vercel.createEditFileTool({ baseDir: './src' });\n * \n * // Use tools with OpenAI\n * const response = await openai.chat.completions.create({\n * model: 'gpt-4o',\n * tools: [grepTool],\n * messages: [{ role: 'user', content: 'Find the bug' }]\n * });\n * ```\n */\n\nimport type { RetryConfig } from './tools/utils/resilience.js';\nimport { MorphAPIClient } from './core/client.js';\nimport { logger } from './logger.js';\nimport { FastApplyClient } from './tools/fastapply/core.js';\nimport { WarpGrepClient } from './tools/warp_grep/client.js';\nimport { CompactClient } from './tools/compact/core.js';\nimport { OpenAIRouter, AnthropicRouter, GeminiRouter, RawRouter, RouterClassifier } from './modelrouter/core.js';\nimport { OpenAIToolFactory, AnthropicToolFactory, VercelToolFactory } from './factories/index.js';\n\n/**\n * Configuration for the MorphClient\n */\nexport interface MorphClientConfig {\n /** Morph API key for authentication (defaults to MORPH_API_KEY env var) */\n apiKey?: string;\n /** Enable debug logging across all tools */\n debug?: boolean;\n /** Default timeout in milliseconds for API requests */\n timeout?: number;\n /** Retry configuration for failed requests */\n retryConfig?: RetryConfig;\n}\n\n/**\n * Unified Morph SDK Client\n * \n * Provides access to all Morph tools through a single interface:\n * - fastApply: AI-powered file editing with intelligent merging\n * - warpGrep: Fast code search with ripgrep\n * - git: Version control operations\n * - routers: Intelligent model selection (OpenAI, Anthropic, Gemini)\n * - openai/anthropic/vercel: Tool factories for agent frameworks\n */\nexport class MorphClient extends MorphAPIClient {\n /** Client configuration */\n public config: MorphClientConfig;\n\n /** FastApply tool for editing files with AI-powered merge */\n public fastApply: FastApplyClient;\n\n /** WarpGrep tool for fast code search using ripgrep */\n public warpGrep: WarpGrepClient;\n\n /** Model routers for intelligent model selection */\n public routers: {\n openai: OpenAIRouter;\n anthropic: AnthropicRouter;\n gemini: GeminiRouter;\n raw: RawRouter;\n classify: RouterClassifier;\n };\n\n /** OpenAI-compatible tool factories */\n public openai: OpenAIToolFactory;\n\n /** Anthropic-compatible tool factories */\n public anthropic: AnthropicToolFactory;\n\n /** Vercel AI SDK tool factories */\n public vercel: VercelToolFactory;\n\n /** Compact context with line ranges */\n public compact: CompactClient['compact'];\n\n /**\n * Create a new Morph SDK client\n * \n * @param config - Client configuration (apiKey, debug, timeout, retryConfig)\n * \n * @example\n * ```typescript\n * const morph = new MorphClient({ \n * apiKey: process.env.MORPH_API_KEY,\n * debug: true,\n * timeout: 60000\n * });\n * ```\n */\n constructor(config: MorphClientConfig = {}) {\n // MorphClient *is* the transport: it owns auth/host/retries/timeout and every\n // resource below shares it by reference (the OpenAI SDK pattern).\n super({\n apiKey: config.apiKey,\n timeout: config.timeout,\n retryConfig: config.retryConfig,\n debug: config.debug,\n });\n\n // An explicit key is required (sub-resources like Git depend on it); this\n // preserves the long-standing eager-throw on construction.\n if (!config.apiKey) {\n throw new Error('Morph API key is required. Pass it as { apiKey } when constructing MorphClient.');\n }\n\n this.config = config;\n logger.debug('MorphClient', 'initialized', { debug: !!config.debug, timeout: config.timeout });\n\n // Attach every resource, sharing this single transport.\n this.fastApply = new FastApplyClient(this);\n this.warpGrep = new WarpGrepClient(this);\n\n this.routers = {\n openai: new OpenAIRouter(this),\n anthropic: new AnthropicRouter(this),\n gemini: new GeminiRouter(this),\n raw: new RawRouter(this),\n classify: new RouterClassifier(this),\n };\n\n const compactClient = new CompactClient(this);\n this.compact = compactClient.compact.bind(compactClient);\n\n // Tool factories build framework-specific tool definitions from the same config.\n this.openai = new OpenAIToolFactory(config);\n this.anthropic = new AnthropicToolFactory(config);\n this.vercel = new VercelToolFactory(config);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BO,IAAM,oBAAN,MAA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;AAAA,IAChB,CAAC;AAID,QAAI,CAAC,OAAO,QAAQ;AAClB,YAAM,IAAI,MAAM,iFAAiF;AAAA,IACnG;AAEA,SAAK,SAAS;AACd,WAAO,MAAM,eAAe,eAAe,EAAE,OAAO,CAAC,CAAC,OAAO,OAAO,SAAS,OAAO,QAAQ,CAAC;AAG7F,SAAK,YAAY,IAAI,gBAAgB,IAAI;AACzC,SAAK,WAAW,IAAI,eAAe,IAAI;AAEvC,SAAK,UAAU;AAAA,MACb,QAAQ,IAAI,aAAa,IAAI;AAAA,MAC7B,WAAW,IAAI,gBAAgB,IAAI;AAAA,MACnC,QAAQ,IAAI,aAAa,IAAI;AAAA,MAC7B,KAAK,IAAI,UAAU,IAAI;AAAA,MACvB,UAAU,IAAI,iBAAiB,IAAI;AAAA,IACrC;AAEA,UAAM,gBAAgB,IAAI,cAAc,IAAI;AAC5C,SAAK,UAAU,cAAc,QAAQ,KAAK,aAAa;AAGvD,SAAK,SAAS,IAAI,kBAAkB,MAAM;AAC1C,SAAK,YAAY,IAAI,qBAAqB,MAAM;AAChD,SAAK,SAAS,IAAI,kBAAkB,MAAM;AAAA,EAC5C;AACF;","names":["createWarpGrepTool","createEditFileTool","createGitHubSearchTool","createWarpGrepTool","createEditFileTool","createGitHubSearchTool","createExploreSubagent"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/agent/config.ts"],"sourcesContent":["// Parse timeout from env, defaulting to 30 seconds\nconst parseEnvTimeout = (envValue: string | undefined, defaultMs: number): number => {\n if (!envValue) return defaultMs;\n const parsed = parseInt(envValue, 10);\n return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;\n};\n\nexport const AGENT_CONFIG = {\n MAX_TURNS: 6,\n /** Default timeout for model calls. Can be overridden via MORPH_WARP_GREP_TIMEOUT env var (in ms) */\n TIMEOUT_MS: parseEnvTimeout(process.env.MORPH_WARP_GREP_TIMEOUT, 60_000),\n MAX_CONTEXT_CHARS: 321_600,\n MAX_OUTPUT_LINES: 200,\n MAX_LIST_RESULTS: 500,\n MAX_READ_LINES: 800,\n MAX_LIST_DEPTH: 3,\n LIST_TIMEOUT_MS: 2_000,\n};\n\n/**\n * Comprehensive exclusion list for directories and files\n * These patterns are used with ripgrep's -g flag\n */\nconst BUILTIN_EXCLUDES = [\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n \n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'packages', 'Pods', '.bundle',\n \n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs', '*.egg-info',\n \n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n \n // Cache directories\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n \n // IDE/Editor\n '.idea', '.vscode', '.vs',\n \n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n \n // Temporary\n 'tmp', 'temp', '.tmp', '.temp',\n \n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n \n // Binary/minified\n '*.min.js', '*.min.css', '*.bundle.js',\n '*.wasm', '*.so', '*.dll', '*.pyc',\n '*.map', '*.js.map',\n \n // Hidden directories catch-all\n '.*',\n];\n\nexport const DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || '')\n .split(',')\n .map(s => s.trim())\n .filter(Boolean)\n .concat(BUILTIN_EXCLUDES);\n\nexport const DEFAULT_MODEL = 'morph-warp-grep-v2.1';\n"],"mappings":";AACA,IAAM,kBAAkB,CAAC,UAA8B,cAA8B;AACnF,MAAI,CAAC,SAAU,QAAO;AACtB,QAAM,SAAS,SAAS,UAAU,EAAE;AACpC,SAAO,MAAM,MAAM,KAAK,UAAU,IAAI,YAAY;AACpD;AAEO,IAAM,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EACjB,OAAO,OAAO,EACd,OAAO,gBAAgB;AAEnB,IAAM,gBAAgB;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../logger.ts"],"sourcesContent":["/**\n * Edge-safe logger.\n *\n * This module is imported transitively by the edge entrypoint\n * (`@morphllm/morphsdk/edge`) via fastapply, modelrouter, etc.\n * Edge runtimes (Vercel Edge Functions, Cloudflare Workers, Deno Deploy)\n * run on V8 isolates — not Node.js — so Node built-ins like fs don't\n * exist. A top-level static import of fs would crash at module-load time,\n * even if createWriteStream is only called conditionally.\n *\n * Fix: we use a dynamic import() behind a runtime check. In Node the\n * import resolves and file logging works normally. In edge runtimes the\n * import rejects and we silently fall back to console-only logging.\n */\n\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\ninterface WriteStream {\n write(chunk: string): boolean;\n}\n\nclass MorphLogger {\n private enabled: boolean;\n private fileStream: WriteStream | null;\n /** Resolves once the file stream is initialized (or immediately if no file logging). */\n readonly ready: Promise<void>;\n\n constructor() {\n this.enabled = typeof process !== 'undefined' &&\n (process.env.MORPH_DEBUG === '1' || !!process.env.MORPH_LOG_FILE);\n this.fileStream = null;\n\n const f = typeof process !== 'undefined' ? process.env.MORPH_LOG_FILE : undefined;\n if (f) {\n // Dynamic import — never evaluated at parse time, so edge runtimes\n // don't blow up with \"Module 'fs' not found\".\n this.ready = import('fs')\n .then((fs) => {\n this.fileStream = fs.createWriteStream(f, { flags: 'a' });\n })\n .catch(() => {\n // Edge runtime — fs unavailable, silently skip file logging\n });\n } else {\n this.ready = Promise.resolve();\n }\n }\n\n debug(component: string, msg: string, data?: Record<string, unknown>) { this._log('debug', component, msg, data); }\n info(component: string, msg: string, data?: Record<string, unknown>) { this._log('info', component, msg, data); }\n warn(component: string, msg: string, data?: Record<string, unknown>) { this._log('warn', component, msg, data); }\n error(component: string, msg: string, data?: Record<string, unknown>) { this._log('error', component, msg, data); }\n\n enable() { this.enabled = true; }\n get isEnabled() { return this.enabled; }\n\n private _log(level: LogLevel, component: string, msg: string, data?: Record<string, unknown>) {\n if (level !== 'error' && !this.enabled) return;\n const ts = new Date().toISOString();\n const prefix = `[${ts}] [${level.toUpperCase()}] [${component}]`;\n console.error(data ? `${prefix} ${msg} ${JSON.stringify(data)}` : `${prefix} ${msg}`);\n this.fileStream?.write(JSON.stringify({ ts, level, component, msg, ...(data && { data }) }) + '\\n');\n }\n}\n\nexport const logger = new MorphLogger();\n"],"mappings":";AAqBA,IAAM,cAAN,MAAkB;AAAA,EACR;AAAA,EACA;AAAA;AAAA,EAEC;AAAA,EAET,cAAc;AACZ,SAAK,UAAU,OAAO,YAAY,gBAC/B,QAAQ,IAAI,gBAAgB,OAAO,CAAC,CAAC,QAAQ,IAAI;AACpD,SAAK,aAAa;AAElB,UAAM,IAAI,OAAO,YAAY,cAAc,QAAQ,IAAI,iBAAiB;AACxE,QAAI,GAAG;AAGL,WAAK,QAAQ,OAAO,IAAI,EACrB,KAAK,CAAC,OAAO;AACZ,aAAK,aAAa,GAAG,kBAAkB,GAAG,EAAE,OAAO,IAAI,CAAC;AAAA,MAC1D,CAAC,EACA,MAAM,MAAM;AAAA,MAEb,CAAC;AAAA,IACL,OAAO;AACL,WAAK,QAAQ,QAAQ,QAAQ;AAAA,IAC/B;AAAA,EACF;AAAA,EAEA,MAAM,WAAmB,KAAa,MAAgC;AAAE,SAAK,KAAK,SAAS,WAAW,KAAK,IAAI;AAAA,EAAG;AAAA,EAClH,KAAK,WAAmB,KAAa,MAAgC;AAAE,SAAK,KAAK,QAAQ,WAAW,KAAK,IAAI;AAAA,EAAG;AAAA,EAChH,KAAK,WAAmB,KAAa,MAAgC;AAAE,SAAK,KAAK,QAAQ,WAAW,KAAK,IAAI;AAAA,EAAG;AAAA,EAChH,MAAM,WAAmB,KAAa,MAAgC;AAAE,SAAK,KAAK,SAAS,WAAW,KAAK,IAAI;AAAA,EAAG;AAAA,EAElH,SAAS;AAAE,SAAK,UAAU;AAAA,EAAM;AAAA,EAChC,IAAI,YAAY;AAAE,WAAO,KAAK;AAAA,EAAS;AAAA,EAE/B,KAAK,OAAiB,WAAmB,KAAa,MAAgC;AAC5F,QAAI,UAAU,WAAW,CAAC,KAAK,QAAS;AACxC,UAAM,MAAK,oBAAI,KAAK,GAAE,YAAY;AAClC,UAAM,SAAS,IAAI,EAAE,MAAM,MAAM,YAAY,CAAC,MAAM,SAAS;AAC7D,YAAQ,MAAM,OAAO,GAAG,MAAM,IAAI,GAAG,IAAI,KAAK,UAAU,IAAI,CAAC,KAAK,GAAG,MAAM,IAAI,GAAG,EAAE;AACpF,SAAK,YAAY,MAAM,KAAK,UAAU,EAAE,IAAI,OAAO,WAAW,KAAK,GAAI,QAAQ,EAAE,KAAK,EAAG,CAAC,IAAI,IAAI;AAAA,EACpG;AACF;AAEO,IAAM,SAAS,IAAI,YAAY;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/agent/parser.ts"],"sourcesContent":["// Helpers for parsing string-format tool arguments from OpenAI tool calls\n\nimport type { FinishFileSpec } from './types.js';\n\n/** Parse \"lines\" string from read tool (e.g. \"1-50\" or \"1-20,45-80\") into structured args */\nexport function parseReadLines(linesStr: string): { start?: number; end?: number; lines?: Array<[number, number]> } {\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of linesStr.split(',')) {\n const trimmed = rangeStr.trim();\n if (!trimmed) continue;\n const parts = trimmed.split('-').map(v => parseInt(v.trim(), 10));\n if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {\n ranges.push([parts[0], parts[1]]);\n } else if (Number.isFinite(parts[0])) {\n ranges.push([parts[0], parts[0]]);\n }\n }\n if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };\n if (ranges.length > 1) return { lines: ranges };\n return {};\n}\n\n/** Parse \"files\" string from finish tool (e.g. \"src/auth.py:1-50\\nsrc/user.py\" or space-separated) into FinishFileSpec[] */\nexport function parseFinishFiles(filesStr: string): FinishFileSpec[] {\n const files: FinishFileSpec[] = [];\n // Split on whitespace (training uses space-separated, SDK also supports newlines)\n for (const line of filesStr.trim().split(/\\s+/)) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n // Skip Windows drive letter prefix (e.g. \"C:\") to avoid splitting on it\n const searchFrom = /^[A-Za-z]:/.test(trimmed) ? 2 : 0;\n const colonIdx = trimmed.indexOf(':', searchFrom);\n if (colonIdx === -1) {\n files.push({ path: trimmed, lines: '*' });\n continue;\n }\n const filePath = trimmed.slice(0, colonIdx);\n const rangesPart = trimmed.slice(colonIdx + 1);\n if (!rangesPart.trim() || rangesPart.trim() === '*') {\n files.push({ path: filePath, lines: '*' });\n continue;\n }\n const ranges: Array<[number, number]> = [];\n for (const rangeStr of rangesPart.split(',')) {\n const rt = rangeStr.trim();\n if (!rt) continue;\n const parts = rt.split('-').map(v => parseInt(v.trim(), 10));\n if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {\n ranges.push([parts[0], parts[1]]);\n } else if (Number.isFinite(parts[0])) {\n ranges.push([parts[0], parts[0]]);\n }\n }\n files.push({ path: filePath, lines: ranges.length > 0 ? ranges : '*' });\n }\n return files;\n}\n\n/** Extract directory path from a list_directory command string (e.g. \"ls -la src/\" → \"src/\") */\nexport function extractPathFromCommand(command: string): string {\n const tokens = command.trim().split(/\\s+/);\n const pathTokens = tokens.slice(1).filter(t => !t.startsWith('-') && !t.startsWith('|') && !t.startsWith('\\\\('));\n return pathTokens[0] || '.';\n}\n"],"mappings":";AAKO,SAAS,eAAe,UAAqF;AAClH,QAAM,SAAkC,CAAC;AACzC,aAAW,YAAY,SAAS,MAAM,GAAG,GAAG;AAC1C,UAAM,UAAU,SAAS,KAAK;AAC9B,QAAI,CAAC,QAAS;AACd,UAAM,QAAQ,QAAQ,MAAM,GAAG,EAAE,IAAI,OAAK,SAAS,EAAE,KAAK,GAAG,EAAE,CAAC;AAChE,QAAI,MAAM,UAAU,KAAK,OAAO,S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K,GAAG,EAAE,CAAC;AAC3D,UAAI,MAAM,UAAU,KAAK,OAAO,SAAS,MAAM,CAAC,CAAC,KAAK,OAAO,SAAS,MAAM,CAAC,CAAC,GAAG;AAC/E,eAAO,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;AAAA,MAClC,WAAW,OAAO,SAAS,MAAM,CAAC,CAAC,GAAG;AACpC,eAAO,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC;AAAA,MAClC;AAAA,IACF;AACA,UAAM,KAAK,EAAE,MAAM,UAAU,OAAO,OAAO,SAAS,IAAI,SAAS,IAAI,CAAC;AAAA,EACxE;AACA,SAAO;AACT;AAGO,SAAS,uBAAuB,SAAyB;AAC9D,QAAM,SAAS,QAAQ,KAAK,EAAE,MAAM,KAAK;AACzC,QAAM,aAAa,OAAO,MAAM,CAAC,EAAE,OAAO,OAAK,CAAC,EAAE,WAAW,GAAG,KAAK,CAAC,EAAE,WAAW,GAAG,KAAK,CAAC,EAAE,WAAW,KAAK,CAAC;AAC/G,SAAO,WAAW,CAAC,KAAK;AAC1B;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/utils/files.ts"],"sourcesContent":["import fs from 'fs/promises';\n\nexport async function readAllLines(filePath: string): Promise<string[]> {\n const content = await fs.readFile(filePath, 'utf8');\n // Preserve newlines; split keeping consistency\n return content.split(/\\r?\\n/);\n}\n\n\n"],"mappings":";AAAA,OAAO,QAAQ;AAEf,eAAsB,aAAa,UAAqC;AACtE,QAAM,UAAU,MAAM,GAAG,SAAS,UAAU,MAAM;AAElD,SAAO,QAAQ,MAAM,OAAO;AAC9B;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/index.ts"],"sourcesContent":["/**\n * Morph Warp Grep SDK\n * \n * Fast and accurate code search tool for AI agents.\n * Uses ripgrep locally, or use `remoteCommands` for sandbox environments.\n * \n * @example Local usage\n * ```typescript\n * // With MorphClient (recommended)\n * import { MorphClient } from '@morphllm/morphsdk';\n * \n * const morph = new MorphClient({ morphApiKey: process.env.MORPH_API_KEY });\n * const result = await morph.warpGrep.execute({\n * searchTerm: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * ```\n * \n * @example\n * ```typescript\n * // Standalone client\n * import { WarpGrepClient } from '@morphllm/morphsdk/tools/warp-grep';\n * \n * const client = new WarpGrepClient({ morphApiKey: process.env.MORPH_API_KEY });\n * const result = await client.execute({\n * searchTerm: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n * ```\n * \n * @example\n * ```typescript\n * // As a tool for AI agents\n * import { createWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const tool = createWarpGrepTool({ repoRoot: '.' });\n * // Pass to Claude, GPT, Gemini, etc.\n * ```\n * \n * @example Remote sandbox (E2B, Modal, Daytona, etc.)\n * ```typescript\n * import { createMorphWarpGrepTool } from '@morphllm/morphsdk/tools/warp-grep/anthropic';\n * \n * const tool = createMorphWarpGrepTool({\n * repoRoot: '/home/repo',\n * remoteCommands: {\n * grep: async (pattern, path) => (await sandbox.run(`rg '${pattern}' '${path}'`)).stdout,\n * read: async (path, start, end) => (await sandbox.run(`sed -n '${start},${end}p' '${path}'`)).stdout,\n * listDir: async (path, maxDepth) => (await sandbox.run(`find '${path}' -maxdepth ${maxDepth}`)).stdout,\n * },\n * });\n * ```\n * \n * @example Provider-agnostic usage (bring your own tool abstraction)\n * ```typescript\n * import { \n * warpGrepInputSchema,\n * executeToolCall,\n * WARP_GREP_TOOL_NAME,\n * WARP_GREP_DESCRIPTION,\n * } from '@morphllm/morphsdk/tools/warp-grep';\n * \n * // Use with your own tool definition abstraction\n * const toolDef = createToolDef({\n * name: WARP_GREP_TOOL_NAME,\n * description: WARP_GREP_DESCRIPTION,\n * schema: warpGrepInputSchema,\n * });\n * \n * // Execute\n * const result = await executeToolCall(\n * { search_term: 'Find auth middleware' },\n * { repoRoot: '.', morphApiKey: process.env.MORPH_API_KEY }\n * );\n * ```\n */\n\nimport { z } from 'zod';\n\n/** Provider-agnostic Zod schema for warp grep input */\nexport const warpGrepInputSchema = z.object({\n search_term: z.string().describe('Search problem statement that this subagent is supposed to research for'),\n});\n\nexport type WarpGrepInputSchema = z.infer<typeof warpGrepInputSchema>;\n\n// Core client and functions\nexport { WarpGrepClient, executeWarpGrep, executeToolCall, formatResult, executeGitHubReadFile, formatGitHubReadFileResult } from './client.js';\n\n// Types\nexport type {\n WarpGrepClientConfig,\n WarpGrepInput,\n WarpGrepResult,\n WarpGrepContext,\n WarpGrepToolConfig,\n WarpGrepProvider,\n GrepResult,\n ReadResult,\n ListDirectoryEntry,\n RemoteCommands,\n WarpGrepStep,\n GitHubSearchInput,\n GitHubSearchToolConfig,\n GitHubReadFileInput,\n GitHubReadFileResult,\n GitHubReadFileToolConfig,\n} from './types.js';\n\n// Prompts\nexport {\n WARP_GREP_DESCRIPTION,\n WARP_GREP_TOOL_NAME,\n GITHUB_SEARCH_TOOL_NAME,\n GITHUB_SEARCH_DESCRIPTION,\n GITHUB_SEARCH_INPUT_SCHEMA,\n GITHUB_READ_FILE_TOOL_NAME,\n GITHUB_READ_FILE_DESCRIPTION,\n GITHUB_READ_FILE_INPUT_SCHEMA,\n} from './prompts.js';\n\n// Providers (re-exported for convenience)\nexport { LocalRipgrepProvider, RemoteCommandsProvider, createCodeStorageHttpCommands } from './providers/index.js';\nexport type { CodeStorageHttpConfig } from './providers/index.js';\n\n// Path utilities (for handling model path prediction issues)\nexport { fixPathRepetition } from './utils/paths.js';\n\n// Agent internals (advanced usage)\nexport { runWarpGrep, runWarpGrepStreaming } from './agent/index.js';\nexport type { AgentRunResult, SessionConfig, ChatMessage } from './agent/index.js';\n\n// Internal agent tools (for harness builders)\nexport { toolGrep, toolRead, toolListDirectory, readFinishFiles, normalizeFinishFiles } from './agent/tools/index.js';\n\n// Provider adapters are available via dedicated import paths:\n// - '@morphllm/morphsdk/tools/warp-grep/anthropic'\n// - '@morphllm/morphsdk/tools/warp-grep/openai'\n// - '@morphllm/morphsdk/tools/warp-grep/gemini'\n// - '@morphllm/morphsdk/tools/warp-grep/vercel'\n"],"mappings":";AA6EA,SAAS,SAAS;AAGX,IAAM,sBAAsB,EAAE,OAAO;AAAA,EAC1C,aAAa,EAAE,OAAO,EAAE,SAAS,yEAAyE;AAC5G,CAAC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/agent/tools/grep.ts","../tools/warp_grep/agent/tools/read.ts","../tools/warp_grep/agent/tools/list_directory.ts","../tools/warp_grep/agent/tools/glob.ts","../tools/warp_grep/agent/tools/finish.ts","../tools/warp_grep/agent/helpers.ts"],"sourcesContent":["import type { WarpGrepProvider } from '../../providers/types.js';\n\nexport async function toolGrep(\n provider: WarpGrepProvider,\n args: { pattern: string; path: string; glob?: string; context_lines?: number; case_sensitive?: boolean }\n): Promise<{ output: string }> {\n const res = await provider.grep(args);\n \n // Return errors as output - let the model see and handle them\n if (res.error) {\n return { output: res.error };\n }\n \n if (!res.lines.length) {\n return { output: 'no matches' };\n }\n \n return { output: res.lines.join('\\n') };\n}\n\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nfunction isValidRange(start: unknown, end: unknown): boolean {\n return (\n typeof start === 'number' &&\n typeof end === 'number' &&\n Number.isFinite(start) &&\n Number.isFinite(end) &&\n start > 0 &&\n end >= start\n );\n}\n\nexport async function toolRead(\n provider: WarpGrepProvider,\n args: { path: string; start?: number; end?: number; lines?: Array<[number, number]> }\n): Promise<string> {\n if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {\n const validRanges: Array<[number, number]> = [];\n for (const range of args.lines) {\n if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {\n validRanges.push([range[0], range[1]]);\n }\n }\n \n if (validRanges.length === 0) {\n const res = await provider.read({ path: args.path });\n if (res.error) return res.error;\n if (!res.lines.length) return '(empty file)';\n return res.lines.join('\\n');\n }\n \n const chunks: string[] = [];\n for (const [start, end] of validRanges) {\n const res = await provider.read({ path: args.path, start, end });\n if (res.error) return res.error;\n chunks.push(res.lines.join('\\n'));\n }\n if (chunks.every(c => c === '')) return '(empty file)';\n return chunks.join('\\n...\\n');\n }\n\n const res = await provider.read({ path: args.path, start: args.start, end: args.end });\n if (res.error) {\n return res.error;\n }\n if (!res.lines.length) return '(empty file)';\n return res.lines.join('\\n');\n}\n\n","import type { WarpGrepProvider } from '../../providers/types.js';\nimport { AGENT_CONFIG } from '../config.js';\nimport path from 'path';\n\nexport async function toolListDirectory(\n provider: WarpGrepProvider,\n args: { path: string; pattern?: string | null; maxResults?: number; maxDepth?: number },\n repoRoot?: string,\n): Promise<string> {\n\n const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;\n const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n\n const entries = await provider.listDirectory({\n path: args.path,\n pattern: args.pattern ?? null,\n maxResults,\n maxDepth,\n });\n\n if (!entries.length) return 'empty';\n\n // Flat absolute paths (matches training format)\n // If repoRoot is available, convert relative paths to absolute\n if (repoRoot) {\n const absRoot = repoRoot;\n const lines = entries.map(e => path.join(absRoot, e.path));\n return lines.join('\\n');\n }\n\n // Fallback: return relative paths if repoRoot not available\n return entries.map(e => e.path).join('\\n');\n}\n","import type { WarpGrepProvider } from '../../providers/types.js';\n\nexport async function toolGlob(\n provider: WarpGrepProvider,\n args: { pattern: string; path?: string }\n): Promise<string> {\n const res = await provider.glob(args);\n\n if (res.error) {\n return res.error;\n }\n\n if (!res.files.length) {\n return 'no matches';\n }\n\n // Match training output format exactly\n const header = `Found ${res.totalFound} file(s) matching \"${args.pattern}\" within ${res.searchDir}, sorted by modification time (newest first):`;\n const body = res.files.join('\\n');\n const truncated = res.totalFound > res.files.length\n ? `\\n[${res.totalFound - res.files.length} files truncated]`\n : '';\n return `${header}\\n---\\n${body}\\n---${truncated}`;\n}\n","import type { FinishFileSpec } from '../types.js';\n\nfunction isValidRange(range: unknown): range is [number, number] {\n return (\n Array.isArray(range) &&\n range.length >= 2 &&\n typeof range[0] === 'number' &&\n typeof range[1] === 'number' &&\n Number.isFinite(range[0]) &&\n Number.isFinite(range[1]) &&\n range[0] > 0 &&\n range[1] >= range[0]\n );\n}\n\nfunction extractValidRanges(lines: unknown): Array<[number, number]> | null {\n if (!Array.isArray(lines)) return null;\n const valid: Array<[number, number]> = [];\n for (const range of lines) {\n if (isValidRange(range)) {\n valid.push([range[0], range[1]]);\n }\n }\n return valid.length > 0 ? valid : null;\n}\n\nexport function normalizeFinishFiles(files: FinishFileSpec[]): FinishFileSpec[] {\n return files.map((f) => {\n if (f.lines === '*') return { path: f.path, lines: '*' };\n const validRanges = extractValidRanges(f.lines);\n if (!validRanges) return { path: f.path, lines: '*' };\n return { path: f.path, lines: mergeRanges(validRanges) };\n });\n}\n\nexport async function readFinishFiles(\n repoRoot: string,\n files: FinishFileSpec[],\n reader: (path: string, start?: number, end?: number) => Promise<string[]>\n): Promise<{ path: string; ranges: '*' | Array<[number, number]>; content: string }[]> {\n const out: { path: string; ranges: '*' | Array<[number, number]>; content: string }[] = [];\n for (const f of files) {\n const validRanges = f.lines === '*' ? null : extractValidRanges(f.lines);\n if (f.lines === '*' || !validRanges) {\n const lines = await reader(f.path);\n out.push({ path: f.path, ranges: '*', content: lines.join('\\n') });\n } else {\n const ranges = mergeRanges(validRanges);\n const chunks: string[] = [];\n for (let i = 0; i < ranges.length; i++) {\n const [s, e] = ranges[i];\n if (i === 0 && s > 1) {\n chunks.push(`// ... existing code, block starting at line ${s} ...`);\n } else if (i > 0) {\n chunks.push(`// ... existing code, block starting at line ${s} ...`);\n }\n const lines = await reader(f.path, s, e);\n chunks.push(lines.join('\\n'));\n }\n out.push({ path: f.path, ranges, content: chunks.join('\\n') });\n }\n }\n return out;\n}\n\nfunction mergeRanges(ranges: Array<[number, number]>): Array<[number, number]> {\n if (!ranges.length) return [];\n const sorted = [...ranges].sort((a, b) => a[0] - b[0]);\n const merged: Array<[number, number]> = [];\n let [cs, ce] = sorted[0];\n for (let i = 1; i < sorted.length; i++) {\n const [s, e] = sorted[i];\n if (s <= ce + 1) {\n ce = Math.max(ce, e);\n } else {\n merged.push([cs, ce]);\n cs = s;\n ce = e;\n }\n }\n merged.push([cs, ce]);\n return merged;\n}\n\n","/**\n * Shared helper functions for warp-grep agent loop.\n * Used by both the internal runner and exported for harness users.\n */\n\nimport path from 'path';\nimport { AGENT_CONFIG } from './config.js';\nimport type { ChatMessage } from './types.js';\nimport type { WarpGrepProvider, ListDirectoryEntry } from '../providers/types.js';\n\nconst TRUNCATED_MARKER = '[truncated for context limit]';\n\n/**\n * Get the character size of a ChatMessage (handles all message types).\n */\nfunction getMessageSize(m: ChatMessage): number {\n if (m.role === 'tool') return m.content.length;\n if (m.role === 'assistant') {\n let size = typeof m.content === 'string' ? m.content.length : 0;\n if (m.tool_calls) {\n size += m.tool_calls.reduce((s, tc) => s + tc.function.name.length + tc.function.arguments.length, 0);\n }\n return size;\n }\n // system or user\n return (m as { content: string }).content.length;\n}\n\n/**\n * Format the turn counter message shown to the model.\n */\nexport function formatTurnMessage(turnsUsed: number, maxTurns: number): string {\n const turnsRemaining = maxTurns - turnsUsed;\n if (turnsRemaining === 1) {\n return `\\nYou have used ${turnsUsed} turns, you only have 1 turn remaining. You have run out of turns to explore the code base and MUST call the finish tool now`;\n }\n return `\\nYou have used ${turnsUsed} turn${turnsUsed === 1 ? '' : 's'} and have ${turnsRemaining} remaining`;\n}\n\n/**\n * Calculate and format the context budget indicator.\n */\nexport function calculateContextBudget(messages: ChatMessage[]): string {\n const totalChars = messages.reduce((sum, m) => sum + getMessageSize(m), 0);\n const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;\n const percent = Math.floor((totalChars / maxChars) * 100);\n const usedK = Math.floor(totalChars / 1000);\n const maxK = Math.floor(maxChars / 1000);\n return `<context_budget>${percent}% (${usedK}K/${maxK}K chars)</context_budget>`;\n}\n\n/**\n * Build the initial state message containing repo structure and search term.\n */\nexport async function buildInitialState(\n repoRoot: string,\n searchTerm: string,\n provider: WarpGrepProvider,\n options?: { search_type?: string },\n): Promise<string> {\n const budget = calculateContextBudget([]);\n const turnTag = `You have used 0 turns and have ${AGENT_CONFIG.MAX_TURNS} remaining`;\n const treeDepth = options?.search_type === 'node_modules' ? 1 : 2;\n\n const absRoot = repoRoot;\n\n try {\n const entries = await provider.listDirectory({\n path: '.',\n maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,\n maxDepth: treeDepth,\n });\n\n // Flat list of absolute paths (matches training format)\n // First line is the repo root, then one absolute path per entry\n const lines = [absRoot];\n for (const e of entries) {\n lines.push(path.join(absRoot, e.path));\n }\n\n return `<repo_structure>\\n${lines.join('\\n')}\\n</repo_structure>\\n\\n<search_string>\\n${searchTerm}\\n</search_string>\\n${budget}\\n${turnTag}`;\n } catch {\n return `<repo_structure>\\n${absRoot}\\n</repo_structure>\\n\\n<search_string>\\n${searchTerm}\\n</search_string>\\n${budget}\\n${turnTag}`;\n }\n}\n\n/**\n * Format directory entries as an indented tree string.\n */\nexport function formatListDirectoryTree(entries: ListDirectoryEntry[]): string {\n if (!entries.length) return 'empty';\n return entries\n .map((e) => {\n const indent = ' '.repeat(e.depth);\n const name = e.type === 'dir' ? `${e.name}/` : e.name;\n return `${indent}${name}`;\n })\n .join('\\n');\n}\n\n/**\n * Enforce hard context limit by truncating tool result messages.\n * Preserves the first user message (initial query) and all assistant messages.\n * Truncates tool/user messages from oldest to newest until under the threshold.\n *\n * @param messages - The conversation messages array (mutated in place)\n * @param maxChars - Maximum total character count (defaults to AGENT_CONFIG.MAX_CONTEXT_CHARS)\n * @returns The same messages array, truncated if necessary\n */\nexport function enforceContextLimit(\n messages: ChatMessage[],\n maxChars: number = AGENT_CONFIG.MAX_CONTEXT_CHARS\n): ChatMessage[] {\n const getTotalChars = () => messages.reduce((sum, m) => sum + getMessageSize(m), 0);\n\n if (getTotalChars() <= maxChars) {\n return messages;\n }\n\n // Find indices of truncatable messages (tool results and non-first user messages)\n const truncatableIndices: number[] = [];\n let firstUserSkipped = false;\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n if (m.role === 'tool') {\n truncatableIndices.push(i);\n } else if (m.role === 'user') {\n if (!firstUserSkipped) {\n firstUserSkipped = true;\n continue; // Skip first user message (contains the search query)\n }\n truncatableIndices.push(i);\n }\n }\n\n // Truncate from oldest to newest until under limit\n for (const idx of truncatableIndices) {\n if (getTotalChars() <= maxChars) {\n break;\n }\n const m = messages[idx];\n if (m.role === 'tool' && m.content !== TRUNCATED_MARKER) {\n messages[idx] = { role: 'tool', tool_call_id: m.tool_call_id, content: TRUNCATED_MARKER };\n } else if (m.role === 'user' && (m as { content: string }).content !== TRUNCATED_MARKER) {\n messages[idx] = { role: 'user', content: TRUNCATED_MARKER };\n }\n }\n\n return messages;\n}\n"],"mappings":";;;;;AAEA,eAAsB,SACpB,UACA,MAC6B;AAC7B,QAAM,MAAM,MAAM,SAAS,KAAK,IAAI;AAGpC,MAAI,IAAI,OAAO;AACb,WAAO,EAAE,QAAQ,IAAI,MAAM;AAAA,EAC7B;AAEA,MAAI,CAAC,IAAI,MAAM,QAAQ;AACrB,WAAO,EAAE,QAAQ,aAAa;AAAA,EAChC;AAEA,SAAO,EAAE,QAAQ,IAAI,MAAM,KAAK,IAAI,EAAE;AACxC;;;AChBA,SAAS,aAAa,OAAgB,KAAuB;AAC3D,SACE,OAAO,UAAU,YACjB,OAAO,QAAQ,YACf,OAAO,SAAS,KAAK,KACrB,OAAO,SAAS,GAAG,KACnB,QAAQ,KACR,OAAO;AAEX;AAEA,eAAsB,SACpB,UACA,MACiB;AACjB,MAAI,KAAK,SAAS,MAAM,QAAQ,KAAK,KAAK,KAAK,KAAK,MAAM,SAAS,GAAG;AACpE,UAAM,cAAuC,CAAC;AAC9C,eAAW,SAAS,KAAK,OAAO;AAC9B,UAAI,MAAM,Q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C,UAAM,OAAO,EAAE,SAAS,QAAQ,GAAG,EAAE,IAAI,MAAM,EAAE;AACjD,WAAO,GAAG,MAAM,GAAG,IAAI;AAAA,EACzB,CAAC,EACA,KAAK,IAAI;AACd;AAWO,SAAS,oBACd,UACA,WAAmB,aAAa,mBACjB;AACf,QAAM,gBAAgB,MAAM,SAAS,OAAO,CAAC,KAAK,MAAM,MAAM,eAAe,CAAC,GAAG,CAAC;AAElF,MAAI,cAAc,KAAK,UAAU;AAC/B,WAAO;AAAA,EACT;AAGA,QAAM,qBAA+B,CAAC;AACtC,MAAI,mBAAmB;AACvB,WAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,UAAM,IAAI,SAAS,CAAC;AACpB,QAAI,EAAE,SAAS,QAAQ;AACrB,yBAAmB,KAAK,CAAC;AAAA,IAC3B,WAAW,EAAE,SAAS,QAAQ;AAC5B,UAAI,CAAC,kBAAkB;AACrB,2BAAmB;AACnB;AAAA,MACF;AACA,yBAAmB,KAAK,CAAC;AAAA,IAC3B;AAAA,EACF;AAGA,aAAW,OAAO,oBAAoB;AACpC,QAAI,cAAc,KAAK,UAAU;AAC/B;AAAA,IACF;AACA,UAAM,IAAI,SAAS,GAAG;AACtB,QAAI,EAAE,SAAS,UAAU,EAAE,YAAY,kBAAkB;AACvD,eAAS,GAAG,IAAI,EAAE,MAAM,QAAQ,cAAc,EAAE,cAAc,SAAS,iBAAiB;AAAA,IAC1F,WAAW,EAAE,SAAS,UAAW,EAA0B,YAAY,kBAAkB;AACvF,eAAS,GAAG,IAAI,EAAE,MAAM,QAAQ,SAAS,iBAAiB;AAAA,IAC5D;AAAA,EACF;AAEA,SAAO;AACT;","names":["res","isValidRange","path","path"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../modelrouter/core.ts"],"sourcesContent":["/**\n * Core implementation for intelligent model routing.\n *\n * Routers are thin resources over the shared `MorphAPIClient` transport: they\n * POST to `/v1/router/<provider>` and map the response. Auth, retries, timeouts,\n * and the SDK-version header all live in the transport.\n */\nimport { MorphAPIClient } from '../core/client.js';\nimport { APIResource } from '../core/resource.js';\nimport { MorphError } from '../tools/utils/resilience.js';\nimport { logger } from '../logger.js';\nimport type {\n RouterConfig,\n RouterInput,\n RouterResult,\n RawRouterResult,\n ComplexityLevel,\n Provider,\n ClassifyInput,\n ClassifyResult,\n} from './types.js';\n\nconst DEFAULT_API_URL = 'https://api.morphllm.com';\nconst DEFAULT_TIMEOUT = 5000; // 5 seconds (responses typically <500ms)\n\nfunction resolveClient(clientOrConfig: MorphAPIClient | RouterConfig): MorphAPIClient {\n if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;\n return new MorphAPIClient({\n apiKey: clientOrConfig.apiKey,\n baseURL: clientOrConfig.apiUrl ?? DEFAULT_API_URL,\n timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT,\n retryConfig: clientOrConfig.retryConfig,\n debug: clientOrConfig.debug,\n });\n}\n\nabstract class BaseRouter extends APIResource {\n protected provider: Provider;\n protected timeout: number;\n\n constructor(provider: Provider, clientOrConfig: MorphAPIClient | RouterConfig = {}) {\n super(resolveClient(clientOrConfig));\n this.provider = provider;\n const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;\n this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT;\n }\n\n /** Throw the historical \"API key is required\" message when no key is resolvable. */\n protected requireApiKey(): void {\n if (!this._client.resolveApiKey()) {\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\n /** POST to the router and surface failures as `Router API error (<status>): ...`. */\n protected async route<T>(provider: string, input: RouterInput): Promise<T> {\n try {\n return await this._client.post<T>(`/v1/router/${provider}`, {\n body: { input: input.input, mode: input.mode || 'balanced' },\n timeout: this.timeout,\n });\n } catch (error) {\n if (error instanceof MorphError) {\n throw new Error(`Router API error (${error.statusCode}): ${error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Select the optimal model for a given input and mode\n */\n async selectModel(input: RouterInput): Promise<RouterResult> {\n this.requireApiKey();\n logger.debug('ModelRouter', 'request', { provider: this.provider, mode: input.mode || 'balanced' });\n const apiResult = await this.route<{ model: string; confidence?: number }>(this.provider, input);\n logger.debug('ModelRouter', 'selected', { provider: this.provider, model: apiResult.model });\n return { model: apiResult.model };\n }\n}\n\n/**\n * OpenAI model router for GPT-5 series\n *\n * @deprecated Prefer `MorphClient` (`new MorphClient({ apiKey }).routers.openai`). In edge\n * runtimes where `MorphClient` is unavailable, pass a shared transport:\n * `new OpenAIRouter(new MorphAPIClient({ apiKey }))`. Kept only for backwards compatibility.\n */\nexport class OpenAIRouter extends BaseRouter {\n constructor(clientOrConfig: MorphAPIClient | RouterConfig = {}) {\n super('openai', clientOrConfig);\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 *\n * @deprecated Prefer `MorphClient` (`new MorphClient({ apiKey }).routers.anthropic`). In edge\n * runtimes where `MorphClient` is unavailable, pass a shared transport:\n * `new AnthropicRouter(new MorphAPIClient({ apiKey }))`. Kept only for backwards compatibility.\n */\nexport class AnthropicRouter extends BaseRouter {\n constructor(clientOrConfig: MorphAPIClient | RouterConfig = {}) {\n super('anthropic', clientOrConfig);\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 *\n * @deprecated Prefer `MorphClient` (`new MorphClient({ apiKey }).routers.gemini`). In edge\n * runtimes where `MorphClient` is unavailable, pass a shared transport:\n * `new GeminiRouter(new MorphAPIClient({ apiKey }))`. Kept only for backwards compatibility.\n */\nexport class GeminiRouter extends BaseRouter {\n constructor(clientOrConfig: MorphAPIClient | RouterConfig = {}) {\n super('gemini', clientOrConfig);\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 *\n * @deprecated Prefer `MorphClient` (`new MorphClient({ apiKey }).routers.raw`). In edge\n * runtimes where `MorphClient` is unavailable, pass a shared transport:\n * `new RawRouter(new MorphAPIClient({ apiKey }))`. Kept only for backwards compatibility.\n */\nexport class RawRouter extends BaseRouter {\n constructor(clientOrConfig: MorphAPIClient | RouterConfig = {}) {\n super('raw' as Provider, clientOrConfig);\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 this.requireApiKey();\n logger.debug('RawRouter', 'request', { mode: input.mode || 'balanced' });\n\n const apiResult = await this.route<{ model?: string; difficulty?: string; confidence?: number }>('raw', input);\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 logger.debug('RawRouter', 'classified', { difficulty });\n return { difficulty };\n }\n}\n\n/**\n * Classifier for `/v1/router/classify`.\n *\n * Returns the raw difficulty/ambiguity/domain signals without mapping them to a\n * model. The caller owns the policy — this is what `@morphllm/morphrouter` uses\n * so the routing matrix configured in the dashboard stays the source of truth.\n */\nexport class RouterClassifier extends APIResource {\n private timeout: number;\n\n constructor(clientOrConfig: MorphAPIClient | RouterConfig = {}) {\n super(resolveClient(clientOrConfig));\n const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;\n this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT;\n }\n\n /** Classify an input across the requested axes (all three by default). */\n async classify(input: ClassifyInput): Promise<ClassifyResult> {\n if (!this._client.resolveApiKey()) {\n throw new Error(\n 'Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config.',\n );\n }\n logger.debug('RouterClassifier', 'request', { classes: input.classes ?? 'all' });\n try {\n const res = await this._client.post<{ classifications: ClassifyResult }>('/v1/router/classify', {\n body: { input: input.input, ...(input.classes ? { classes: input.classes } : {}) },\n timeout: this.timeout,\n });\n logger.debug('RouterClassifier', 'classified', {\n difficulty: res.classifications.difficulty?.label,\n ambiguity: res.classifications.ambiguity?.label,\n domain: res.classifications.domain?.label,\n });\n return res.classifications;\n } catch (error) {\n if (error instanceof MorphError) {\n throw new Error(`Router API error (${error.statusCode}): ${error.message}`);\n }\n throw error;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,IAAM,kBAAkB;AACxB,IAAM,kBAAkB;AAExB,SAAS,cAAc,gBAA+D;AACpF,MAAI,0BAA0B,eAAgB,QAAO;AACrD,SAAO,IAAI,eAAe;AAAA,IACxB,QAAQ,eAAe;AAAA,IACvB,SAAS,eAAe,UAAU;AAAA,IAClC,SAAS,eAAe,WAAW;AAAA,IACnC,aAAa,eAAe;AAAA,IAC5B,OAAO,eAAe;AAAA,EACxB,CAAC;AACH;AAEA,IAAe,aAAf,cAAkC,YAAY;AAAA,EAClC;AAAA,EACA;AAAA,EAEV,YAAY,UAAoB,iBAAgD,CAAC,GAAG;AAClF,UAAM,cAAc,cAAc,CAAC;AACnC,SAAK,WAAW;AAChB,UAAM,MAAM,0BAA0B,iBAAiB,CAAC,IAAI;AAC5D,SAAK,UAAU,IAAI,WAAW;AAAA,EAChC;AAAA;AAAA,EAGU,gBAAsB;AAC9B,QAAI,CAAC,KAAK,QAAQ,cAAc,GAAG;AACjC,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AA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AS,MAAM,QAAQ,IAAI,CAAC,EAAG;AAAA,QACjF,SAAS,KAAK;AAAA,MAChB,CAAC;AACD,aAAO,MAAM,oBAAoB,cAAc;AAAA,QAC7C,YAAY,IAAI,gBAAgB,YAAY;AAAA,QAC5C,WAAW,IAAI,gBAAgB,WAAW;AAAA,QAC1C,QAAQ,IAAI,gBAAgB,QAAQ;AAAA,MACtC,CAAC;AACD,aAAO,IAAI;AAAA,IACb,SAAS,OAAO;AACd,UAAI,iBAAiB,YAAY;AAC/B,cAAM,IAAI,MAAM,qBAAqB,MAAM,UAAU,MAAM,MAAM,OAAO,EAAE;AAAA,MAC5E;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/providers/local.ts"],"sourcesContent":["import fs from 'fs/promises';\nimport fssync from 'fs';\nimport path from 'path';\nimport { runRipgrep } from '../utils/ripgrep.js';\nimport { ensureWithinRepo, resolveUnderRepo, toRepoRelative, isSymlink, isTextualFile, fixPathRepetition } from '../utils/paths.js';\nimport type { WarpGrepProvider, GrepResult, ReadResult, GlobResult, ListDirectoryEntry } from './types.js';\nimport { readAllLines } from '../utils/files.js';\nimport { DEFAULT_EXCLUDES, AGENT_CONFIG } from '../agent/config.js';\n\n/**\n * Directories/files to always skip (exact name match)\n */\nconst SKIP_NAMES = new Set([\n // Version control\n '.git', '.svn', '.hg', '.bzr',\n // Dependencies\n 'node_modules', 'bower_components', '.pnpm', '.yarn',\n 'vendor', 'Pods', '.bundle',\n // Python\n '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',\n '.venv', 'venv', '.tox', '.nox', '.eggs',\n // Build outputs\n 'dist', 'build', 'out', 'output', 'target', '_build',\n '.next', '.nuxt', '.output', '.vercel', '.netlify',\n // Cache\n '.cache', '.parcel-cache', '.turbo', '.nx', '.gradle',\n // IDE\n '.idea', '.vscode', '.vs',\n // Coverage\n 'coverage', '.coverage', 'htmlcov', '.nyc_output',\n // Temp\n 'tmp', 'temp', '.tmp', '.temp',\n // Lock files\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb',\n 'Cargo.lock', 'Gemfile.lock', 'poetry.lock',\n]);\n\n/**\n * File extensions to skip\n */\n\nconst SKIP_EXTENSIONS = new Set([\n '.min.js', '.min.css', '.bundle.js',\n '.wasm', '.so', '.dll', '.pyc',\n '.map', '.js.map',\n]);\n\n/**\n * Check if a filename should be skipped\n */\nfunction shouldSkip(name: string, allowNames?: Set<string>): boolean {\n // Allow explicitly permitted names through\n if (allowNames?.has(name)) return false;\n\n // Skip exact name matches\n if (SKIP_NAMES.has(name)) return true;\n\n // Skip hidden files/directories (start with .)\n if (name.startsWith('.')) return true;\n\n // Skip files with certain extensions\n for (const ext of SKIP_EXTENSIONS) {\n if (name.endsWith(ext)) return true;\n }\n\n return false;\n}\n\nexport class LocalRipgrepProvider implements WarpGrepProvider {\n private readonly allowNames?: Set<string>;\n\n constructor(\n private readonly repoRoot: string,\n private readonly excludes: string[] = DEFAULT_EXCLUDES,\n options?: { allowNames?: string[] },\n ) {\n if (options?.allowNames?.length) {\n this.allowNames = new Set(options.allowNames);\n }\n }\n\n async grep(params: { pattern: string; path: string; glob?: string; context_lines?: number; case_sensitive?: boolean }): Promise<GrepResult> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch (err) {\n return {\n lines: [],\n error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat) return { lines: [] };\n const targetArg = abs === path.resolve(this.repoRoot) ? '.' : toRepoRelative(this.repoRoot, abs);\n const contextLines = params.context_lines !== undefined ? String(params.context_lines) : '1';\n const args = [\n '--no-config',\n '--no-heading',\n '--with-filename',\n '--line-number',\n '--color=never',\n '--trim',\n '--max-columns=400',\n '-C', contextLines,\n ...(params.case_sensitive === false ? ['--ignore-case'] : []),\n ...(params.glob ? ['--glob', params.glob] : []),\n ...this.excludes.filter(e => !this.allowNames?.has(e)).flatMap((e) => ['-g', `!${e}`]),\n params.pattern,\n targetArg || '.',\n ];\n const res = await runRipgrep(args, { cwd: this.repoRoot });\n \n // Gracefully handle ripgrep not being available\n if (res.exitCode === -1) {\n return {\n lines: [],\n error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required but failed to execute. Please install it:\\n` +\n ` • macOS: brew install ripgrep\\n` +\n ` • Ubuntu/Debian: apt install ripgrep\\n` +\n ` • Windows: choco install ripgrep\\n` +\n ` • Or visit: https://github.com/BurntSushi/ripgrep#installation\\n` +\n `Exit code: ${res.exitCode}${res.stderr ? `\\nDetails: ${res.stderr}` : ''}`,\n };\n }\n \n // Handle other ripgrep errors gracefully\n if (res.exitCode !== 0 && res.exitCode !== 1) {\n return {\n lines: [],\n error: `[RIPGREP ERROR] grep failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ''}`,\n };\n }\n \n const lines = (res.stdout || '')\n .trim()\n .split(/\\r?\\n/)\n .filter((l) => l.length > 0);\n if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {\n const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines };\n }\n\n async read(params: { path: string; start?: number; end?: number }): Promise<ReadResult> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch (err) {\n return {\n lines: [],\n error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n let stat = await fs.stat(abs).catch(() => null);\n\n // Handle duplicate path segments from model predictions\n if (!stat || !stat.isFile()) {\n const fixedPath = fixPathRepetition(abs);\n if (fixedPath) {\n const fixedStat = await fs.stat(fixedPath).catch(() => null);\n if (fixedStat?.isFile()) {\n abs = fixedPath;\n stat = fixedStat;\n }\n }\n }\n\n // Gracefully handle file not found / not a file\n if (!stat || !stat.isFile()) {\n return {\n lines: [],\n error: `[FILE NOT FOUND] You tried to read \"${params.path}\" but there is no file at this path. ` +\n `Double-check the path exists and is spelled correctly.`,\n };\n }\n \n // Gracefully handle symlinks\n if (isSymlink(abs)) {\n return {\n lines: [],\n error: `[SYMLINK] You tried to read \"${params.path}\" but this is a symlink. ` +\n `Try reading the actual file it points to instead.`,\n };\n }\n \n // Gracefully handle non-text or too-large files\n if (!isTextualFile(abs)) {\n return {\n lines: [],\n error: `[UNREADABLE FILE] You tried to read \"${params.path}\" but this file is either too large ` +\n `or not a text file, so it cannot be read. Try a different file.`,\n };\n }\n \n let lines: string[];\n try {\n lines = await readAllLines(abs);\n } catch (err) {\n return {\n lines: [],\n error: `[READ ERROR] Failed to read \"${params.path}\": ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n const total = lines.length;\n const rawStart = params.start;\n const rawEnd = params.end;\n \n let s = 1;\n let e = total;\n \n const startValid = rawStart === undefined || (Number.isFinite(rawStart) && rawStart > 0);\n const endValid = rawEnd === undefined || (Number.isFinite(rawEnd) && rawEnd > 0);\n \n if (startValid && endValid) {\n s = rawStart ?? 1;\n e = Math.min(rawEnd ?? total, total);\n if ((s > total && total > 0) || (s > e)) {\n s = 1;\n e = total;\n }\n }\n const out: string[] = [];\n for (let i = s; i <= e; i += 1) {\n const content = lines[i - 1] ?? '';\n out.push(`${i}|${content}`);\n }\n if (out.length > AGENT_CONFIG.MAX_READ_LINES) {\n const truncated = out.slice(0, AGENT_CONFIG.MAX_READ_LINES);\n truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${out.length} lines)`);\n return { lines: truncated };\n }\n \n return { lines: out };\n }\n\n async listDirectory(params: { path: string; pattern?: string | null; maxResults?: number; maxDepth?: number }): Promise<ListDirectoryEntry[]> {\n let abs: string;\n try {\n abs = resolveUnderRepo(this.repoRoot, params.path);\n } catch {\n // Path outside repo - return empty (graceful failure)\n return [];\n }\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat || !stat.isDirectory()) {\n return [];\n }\n const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;\n const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;\n const regex = params.pattern ? new RegExp(params.pattern) : null;\n const repoRoot = this.repoRoot;\n const allowNames = this.allowNames;\n\n const results: ListDirectoryEntry[] = [];\n let timedOut = false;\n const startTime = Date.now();\n\n async function walk(dir: string, depth: number) {\n if (Date.now() - startTime > AGENT_CONFIG.LIST_TIMEOUT_MS) {\n timedOut = true;\n return;\n }\n if (depth > maxDepth || results.length >= maxResults) return;\n let entries: import('fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return; // skip unreadable directories (ENOENT, EACCES, etc.)\n }\n for (const entry of entries) {\n if (timedOut || results.length >= maxResults) break;\n\n // Simple name-based filtering - skip junk dirs/files\n if (shouldSkip(entry.name, allowNames)) continue;\n \n // Apply user-provided pattern filter\n if (regex && !regex.test(entry.name)) continue;\n \n const full = path.join(dir, entry.name);\n const isDir = entry.isDirectory();\n \n results.push({\n name: entry.name,\n path: toRepoRelative(repoRoot, full),\n type: isDir ? 'dir' : 'file',\n depth,\n });\n if (isDir) {\n await walk(full, depth + 1);\n }\n }\n }\n await walk(abs, 0);\n return results;\n }\n\n async glob(params: { pattern: string; path?: string }): Promise<GlobResult> {\n let abs: string;\n try {\n abs = params.path ? resolveUnderRepo(this.repoRoot, params.path) : this.repoRoot;\n } catch (err) {\n return { files: [], searchDir: this.repoRoot, totalFound: 0, error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}` };\n }\n const stat = await fs.stat(abs).catch(() => null);\n if (!stat || !stat.isDirectory()) {\n return { files: [], searchDir: abs, totalFound: 0, error: `[PATH ERROR] Directory not found: ${params.path || '.'}` };\n }\n\n const targetArg = abs === path.resolve(this.repoRoot) ? '.' : toRepoRelative(this.repoRoot, abs);\n const args = [\n '--no-config',\n '--files',\n '--color=never',\n '-g', params.pattern,\n ...this.excludes.filter(e => !this.allowNames?.has(e)).flatMap(e => ['-g', `!${e}`]),\n targetArg || '.',\n ];\n\n const res = await runRipgrep(args, { cwd: this.repoRoot });\n if (res.exitCode === -1) {\n return { files: [], searchDir: abs, totalFound: 0, error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required for glob search.` };\n }\n if (res.exitCode !== 0 && res.exitCode !== 1) {\n return { files: [], searchDir: abs, totalFound: 0, error: `[GLOB ERROR] glob failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ''}` };\n }\n\n // Convert to absolute paths\n const absRoot = path.resolve(this.repoRoot);\n const relFiles = (res.stdout || '').trim().split(/\\r?\\n/).filter(l => l.length > 0);\n const absFiles = relFiles.map(f => path.resolve(absRoot, f));\n\n // Sort by mtime descending (newest first), matching training format\n const withMtime: Array<{ file: string; mtime: number }> = [];\n for (const f of absFiles) {\n const s = await fs.stat(f).catch(() => null);\n withMtime.push({ file: f, mtime: s?.mtimeMs ?? 0 });\n }\n withMtime.sort((a, b) => b.mtime - a.mtime);\n\n const totalFound = withMtime.length;\n return { files: withMtime.slice(0, 100).map(f => f.file), searchDir: abs, totalFound };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ;AAEf,OAAO,UAAU;AAUjB,IAAM,aAAa,oBAAI,IAAI;AAAA;AAAA,EAEzB;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAO;AAAA;AAAA,EAEvB;AAAA,EAAgB;AAAA,EAAoB;AAAA,EAAS;AAAA,EAC7C;AAAA,EAAU;AAAA,EAAQ;AAAA;AAAA,EAElB;AAAA,EAAe;AAAA,EAAiB;AAAA,EAAe;AAAA,EAC/C;AAAA,EAAS;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAQ;AAAA;AAAA,EAEjC;AAAA,EAAQ;AAAA,EAAS;AAAA,EAAO;AAAA,EAAU;AAAA,EAAU;AAAA,EA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KAAK,QAAQ;AAC1C,UAAM,YAAY,IAAI,UAAU,IAAI,KAAK,EAAE,MAAM,OAAO,EAAE,OAAO,OAAK,EAAE,SAAS,CAAC;AAClF,UAAM,WAAW,SAAS,IAAI,OAAK,KAAK,QAAQ,SAAS,CAAC,CAAC;AAG3D,UAAM,YAAoD,CAAC;AAC3D,eAAW,KAAK,UAAU;AACxB,YAAM,IAAI,MAAM,GAAG,KAAK,CAAC,EAAE,MAAM,MAAM,IAAI;AAC3C,gBAAU,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,WAAW,EAAE,CAAC;AAAA,IACpD;AACA,cAAU,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAE1C,UAAM,aAAa,UAAU;AAC7B,WAAO,EAAE,OAAO,UAAU,MAAM,GAAG,GAAG,EAAE,IAAI,OAAK,EAAE,IAAI,GAAG,WAAW,KAAK,WAAW;AAAA,EACvF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/client.ts"],"sourcesContent":["/**\n * WarpGrep client for programmatic code search\n */\n\nimport { runWarpGrep, runWarpGrepStreaming } from './agent/runner.js';\nimport { logger } from '../../logger.js';\nimport { RemoteCommandsProvider } from './providers/remote.js';\nimport type { WarpGrepProvider } from './providers/types.js';\nimport type { AgentRunResult, WarpGrepStep } from './agent/types.js';\nimport type {\n WarpGrepClientConfig,\n WarpGrepInput,\n WarpGrepResult,\n WarpGrepContext,\n WarpGrepToolConfig,\n GitHubSearchInput,\n GitHubReadFileInput,\n GitHubReadFileResult,\n RemoteCommands,\n} from './types.js';\nimport { createCodeStorageHttpCommands } from './providers/code_storage_http.js';\nimport { parseGitHubUrl } from './utils/github.js';\nimport { compactFileContexts } from '../compact/utils.js';\nimport { MorphAPIClient } from '../../core/client.js';\nimport { APIResource } from '../../core/resource.js';\n\nconst DEFAULT_CODE_SEARCH_URL = 'https://api.morphllm.com';\n\n/**\n * Lazy-load LocalRipgrepProvider to avoid importing Node.js-specific\n * modules (child_process, fs) in edge environments like Cloudflare Workers.\n * Only loads when actually needed (i.e., when no remoteCommands or provider is specified).\n */\nasync function getLocalProvider(repoRoot: string, excludes?: string[], allowNames?: string[]): Promise<WarpGrepProvider> {\n const { LocalRipgrepProvider } = await import('./providers/local.js');\n const opts = allowNames?.length ? { allowNames } : undefined;\n return new LocalRipgrepProvider(repoRoot, excludes, opts);\n}\n\n/**\n * WarpGrep client for programmatic code search\n * \n * @example\n * ```typescript\n * import { WarpGrepClient } from '@morphllm/morphsdk';\n * \n * const client = new WarpGrepClient({ morphApiKey: process.env.MORPH_API_KEY });\n * \n * // Simple usage - defaults to LocalRipgrepProvider\n * const result = await client.execute({\n * searchTerm: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n *\n * // With custom excludes\n * const result = await client.execute({\n * searchTerm: 'Find database models',\n * repoRoot: '.',\n * excludes: ['node_modules', '.git', 'dist']\n * });\n * ```\n *\n * @deprecated Prefer the unified `MorphClient` (`new MorphClient({ apiKey }).warpGrep`).\n * Standalone clients remain only for backwards compatibility and may be removed in a future\n * major version — do not use them in new code.\n */\nexport class WarpGrepClient extends APIResource {\n private config: WarpGrepClientConfig;\n\n constructor(clientOrConfig: MorphAPIClient | WarpGrepClientConfig = {}) {\n const isClient = clientOrConfig instanceof MorphAPIClient;\n super(\n isClient\n ? clientOrConfig\n : new MorphAPIClient({\n apiKey: clientOrConfig.morphApiKey,\n baseURL: clientOrConfig.morphApiUrl,\n timeout: clientOrConfig.timeout,\n retryConfig: clientOrConfig.retryConfig,\n debug: clientOrConfig.debug,\n }),\n );\n const cfg: WarpGrepClientConfig = isClient ? {} : clientOrConfig;\n // The agent loop talks to /v1/chat/completions through the `openai` package\n // (see agent/runner.ts), sourcing credentials/host/timeout from the transport.\n // `timeout` stays undefined-able so the runner's env-aware default still applies.\n this.config = {\n ...cfg,\n morphApiKey: this._client.resolveApiKey(),\n morphApiUrl: this._client.baseURL,\n timeout: this._client.timeout,\n retryConfig: this._client.retryConfig,\n debug: this._client.debug,\n };\n }\n\n /**\n * Execute a code search\n *\n * @param input - Search parameters including searchTerm, repoRoot, and optional provider\n * @returns Search results with relevant code contexts, or an AsyncGenerator if streamSteps is true\n *\n * @example\n * ```typescript\n * // Standard execution\n * const result = await client.execute({\n * searchTerm: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n *\n * if (result.success) {\n * for (const ctx of result.contexts) {\n * console.log(`File: ${ctx.file}`);\n * console.log(ctx.content);\n * }\n * }\n *\n * // Streaming execution\n * const stream = client.execute({\n * searchTerm: 'Find auth middleware',\n * repoRoot: '.',\n * streamSteps: true\n * });\n *\n * for await (const step of stream) {\n * console.log(`Turn ${step.turn}:`, step.toolCalls);\n * }\n * ```\n */\n execute(input: WarpGrepInput & { streamSteps: true }): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined>;\n execute(input: WarpGrepInput & { streamSteps?: false | undefined }): Promise<WarpGrepResult>;\n execute(input: WarpGrepInput): Promise<WarpGrepResult> | AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n const toolConfig: WarpGrepToolConfig = {\n repoRoot: input.repoRoot,\n remoteCommands: input.remoteCommands,\n provider: input.provider,\n excludes: input.excludes,\n includes: input.includes,\n debug: input.debug ?? this.config.debug,\n morphApiKey: this.config.morphApiKey,\n morphApiUrl: this.config.morphApiUrl,\n retryConfig: this.config.retryConfig,\n timeout: this.config.timeout,\n search_type: input.search_type,\n };\n\n if (input.streamSteps) {\n return executeToolCallStreaming({ search_term: input.searchTerm }, toolConfig);\n }\n return executeToolCall({ search_term: input.searchTerm }, toolConfig);\n }\n\n /**\n * Search a public GitHub repository\n *\n * @example\n * ```typescript\n * // Simple usage\n * const result = await client.searchGitHub({\n * searchTerm: 'Find authentication middleware',\n * github: 'vercel/next.js',\n * });\n *\n * // With streaming\n * const stream = client.searchGitHub({\n * searchTerm: 'Find auth middleware',\n * github: 'https://github.com/vercel/next.js',\n * streamSteps: true,\n * });\n * for await (const step of stream) {\n * console.log(`Turn ${step.turn}:`, step.toolCalls);\n * }\n * ```\n */\n searchGitHub(input: GitHubSearchInput & { streamSteps: true }): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined>;\n searchGitHub(input: GitHubSearchInput & { streamSteps?: false | undefined }): Promise<WarpGrepResult>;\n searchGitHub(input: GitHubSearchInput): Promise<WarpGrepResult> | AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n if (input.streamSteps) {\n return this._searchGitHubStreaming(input);\n }\n return this._searchGitHubAsync(input);\n }\n\n /**\n * Read a single file from a public GitHub repository\n *\n * @example\n * ```typescript\n * const result = await client.readGitHubFile({\n * github: 'vercel/next.js',\n * path: 'src/server/app-render/index.tsx',\n * startLine: 1,\n * endLine: 50,\n * });\n * if (result.success) console.log(result.content);\n * ```\n */\n async readGitHubFile(input: GitHubReadFileInput): Promise<GitHubReadFileResult> {\n return executeGitHubReadFile(input, { timeout: this.config.timeout });\n }\n\n private async _resolveGitHubRepo(input: GitHubSearchInput): Promise<{ repo: string; remoteCommands: RemoteCommands }> {\n const { owner, repo } = parseGitHubUrl(input.github);\n const baseUrl = this.config.codeSearchUrl || DEFAULT_CODE_SEARCH_URL;\n logger.debug('WarpGrep', 'github_resolve', { owner_repo: `${owner}/${repo}`, branch: input.branch });\n\n const resolveStart = Date.now();\n const importRes = await fetch(`${baseUrl}/api/code-search/get-or-create?url=${encodeURIComponent(`${owner}/${repo}`)}`, {\n headers: this.config.morphApiKey ? { Authorization: `Bearer ${this.config.morphApiKey}` } : undefined,\n });\n if (!importRes.ok) {\n const text = await importRes.text().catch(() => importRes.statusText);\n logger.error('WarpGrep', 'github_resolve_failed', { owner_repo: `${owner}/${repo}`, status: importRes.status, error: text });\n throw new Error(`Failed to import repo ${owner}/${repo}: ${text}`);\n }\n const { repoId, defaultBranch } = await importRes.json();\n logger.debug('WarpGrep', 'github_repo_fetched', { repo_id: repoId, default_branch: defaultBranch, latency_ms: Date.now() - resolveStart });\n\n return {\n repo,\n remoteCommands: createCodeStorageHttpCommands({\n baseUrl,\n repoId,\n branch: input.branch || defaultBranch,\n apiKey: this.config.morphApiKey,\n }),\n };\n }\n\n private async _searchGitHubAsync(input: GitHubSearchInput): Promise<WarpGrepResult> {\n try {\n const { remoteCommands } = await this._resolveGitHubRepo(input);\n return this.execute({\n searchTerm: input.searchTerm,\n repoRoot: '.',\n remoteCommands,\n });\n } catch (error) {\n return { success: false, error: error instanceof Error ? error.message : String(error) };\n }\n }\n\n private async *_searchGitHubStreaming(input: GitHubSearchInput): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n let remoteCommands: RemoteCommands;\n try {\n ({ remoteCommands } = await this._resolveGitHubRepo(input));\n } catch (error) {\n return { success: false, error: error instanceof Error ? error.message : String(error) };\n }\n\n const generator = this.execute({\n searchTerm: input.searchTerm,\n repoRoot: '.',\n remoteCommands,\n streamSteps: true,\n });\n\n let result: WarpGrepResult;\n for (;;) {\n const { value, done } = await generator.next();\n if (done) {\n result = value;\n break;\n }\n yield value;\n }\n return result;\n }\n}\n\n/**\n * Execute a warp grep search directly\n *\n * @param input - Search parameters\n * @param config - Optional client configuration\n * @returns Search results, or an AsyncGenerator if streamSteps is true\n *\n * @example\n * ```typescript\n * import { executeWarpGrep } from '@morphllm/morphsdk/tools/warp-grep';\n *\n * const result = await executeWarpGrep({\n * searchTerm: 'Find authentication middleware',\n * repoRoot: '.'\n * });\n *\n * // Streaming\n * const stream = executeWarpGrep({\n * searchTerm: 'Find auth',\n * repoRoot: '.',\n * streamSteps: true\n * });\n * for await (const step of stream) {\n * console.log(step.turn, step.toolCalls);\n * }\n * ```\n */\nexport function executeWarpGrep(\n input: WarpGrepInput & { streamSteps: true },\n config?: WarpGrepClientConfig\n): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined>;\nexport function executeWarpGrep(\n input: WarpGrepInput & { streamSteps?: false | undefined },\n config?: WarpGrepClientConfig\n): Promise<WarpGrepResult>;\nexport function executeWarpGrep(\n input: WarpGrepInput,\n config?: WarpGrepClientConfig\n): Promise<WarpGrepResult> | AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n const client = new WarpGrepClient(config);\n if (input.streamSteps) {\n return client.execute({ ...input, streamSteps: true });\n }\n return client.execute({ ...input, streamSteps: false });\n}\n\nexport async function executeToolCall(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): Promise<WarpGrepResult> {\n const parsed = typeof input === 'string' ? JSON.parse(input) : input;\n\n // Priority: remoteCommands > provider > LocalRipgrepProvider (lazy-loaded for edge compatibility)\n const allowNames = config.search_type === 'node_modules' ? ['node_modules'] : undefined;\n const provider = config.remoteCommands\n ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands)\n : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);\n\n const result = await runWarpGrep({\n searchTerm: parsed.search_term,\n repoRoot: config.repoRoot,\n provider,\n excludes: config.excludes,\n includes: config.includes,\n debug: config.debug ?? false,\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: config.timeout,\n search_type: config.search_type,\n });\n\n return processAgentResult(result, parsed.search_term, config.morphApiKey, config.morphApiUrl);\n}\n\n/**\n * Helper to process AgentRunResult into WarpGrepResult\n */\nasync function processAgentResult(\n result: AgentRunResult,\n searchTerm: string,\n apiKey?: string,\n apiUrl?: string\n): Promise<WarpGrepResult> {\n const finish = result.finish;\n if (result.terminationReason !== 'completed' || !finish?.metadata) {\n const errorDetails = result.errors?.map(e => e.message).join('; ') || 'unknown reason';\n console.error(`[warp_grep] processAgentResult failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);\n return { success: false, error: `Search did not complete: ${errorDetails}` };\n }\n\n const contexts: WarpGrepContext[] = (finish.resolved ?? []).map(r => ({\n file: r.path,\n content: r.content,\n lines: r.ranges,\n }));\n\n try {\n const compactable = contexts.map(c => ({ path: c.file, content: c.content }));\n const compacted = await compactFileContexts(compactable, searchTerm, apiKey, apiUrl);\n for (let i = 0; i < contexts.length; i++) {\n contexts[i].content = compacted[i].content;\n }\n } catch (error) {\n console.error(`[warp_grep] Failed to compact result contexts:`, error);\n }\n\n return { success: true, contexts, summary: finish.payload };\n}\n\n/**\n * Streaming version of executeToolCall that yields WarpGrepStep for each turn.\n */\nexport async function* executeToolCallStreaming(\n input: { search_term: string } | string,\n config: WarpGrepToolConfig\n): AsyncGenerator<WarpGrepStep, WarpGrepResult, undefined> {\n const parsed = typeof input === 'string' ? JSON.parse(input) : input;\n\n // Priority: remoteCommands > provider > LocalRipgrepProvider (lazy-loaded for edge compatibility)\n const allowNames = config.search_type === 'node_modules' ? ['node_modules'] : undefined;\n const provider = config.remoteCommands\n ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands)\n : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);\n\n const generator = runWarpGrepStreaming({\n searchTerm: parsed.search_term,\n repoRoot: config.repoRoot,\n provider,\n excludes: config.excludes,\n includes: config.includes,\n debug: config.debug ?? false,\n morphApiKey: config.morphApiKey,\n morphApiUrl: config.morphApiUrl,\n retryConfig: config.retryConfig,\n timeout: config.timeout,\n search_type: config.search_type,\n });\n\n // Forward all yielded steps\n let agentResult: AgentRunResult;\n for (;;) {\n const { value, done } = await generator.next();\n if (done) {\n agentResult = value;\n break;\n }\n yield value;\n }\n\n // `await` is load-bearing: an async generator hands its `return` value back as\n // the `done` result without awaiting it, so returning the Promise directly would\n // surface an un-awaited Promise to streaming consumers instead of the result.\n return await processAgentResult(agentResult, parsed.search_term, config.morphApiKey, config.morphApiUrl);\n}\n\n/**\n * Fetch raw file content from a public GitHub repository.\n * Tries the given branch first, then falls back to main/master/develop.\n */\nasync function fetchRawGitHubFile(\n owner: string,\n repo: string,\n filePath: string,\n branch?: string,\n timeout?: number,\n): Promise<{ content: string; branch: string }> {\n const branches = branch ? [branch] : ['HEAD'];\n const fallbacks = ['main', 'master', 'develop'];\n\n const fetchWithTimeout = (url: string) =>\n timeout ? fetch(url, { signal: AbortSignal.timeout(timeout) }) : fetch(url);\n\n for (const b of branches) {\n const url = `https://raw.githubusercontent.com/${owner}/${repo}/${b}/${filePath}`;\n const res = await fetchWithTimeout(url);\n if (res.ok) return { content: await res.text(), branch: b };\n }\n\n for (const fb of fallbacks) {\n if (branch && fb === branch) continue;\n const url = `https://raw.githubusercontent.com/${owner}/${repo}/${fb}/${filePath}`;\n const res = await fetchWithTimeout(url);\n if (res.ok) return { content: await res.text(), branch: fb };\n }\n\n throw new Error(`File not found: ${owner}/${repo}/${filePath}`);\n}\n\n/**\n * Read a single file (or line range) from a public GitHub repository\n */\nexport async function executeGitHubReadFile(\n input: GitHubReadFileInput,\n config?: { timeout?: number },\n): Promise<GitHubReadFileResult> {\n try {\n const { owner, repo } = parseGitHubUrl(input.github);\n const { content: raw, branch } = await fetchRawGitHubFile(\n owner, repo, input.path, input.branch, config?.timeout,\n );\n\n const allLines = raw.split('\\n');\n const totalLines = allLines.length;\n const start = Math.max(1, input.startLine ?? 1);\n const end = Math.min(totalLines, input.endLine ?? totalLines);\n\n const selected = allLines.slice(start - 1, end);\n const padWidth = String(end).length;\n const numbered = selected\n .map((line, i) => `${String(start + i).padStart(padWidth)}|${line}`)\n .join('\\n');\n\n return {\n success: true,\n content: numbered,\n path: input.path,\n github: `${owner}/${repo}`,\n branch,\n lineRange: [start, end],\n totalLines,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Format a GitHub read file result for display or tool responses\n */\nexport function formatGitHubReadFileResult(result: GitHubReadFileResult): string {\n if (!result.success) {\n return `Failed to read file: ${result.error}`;\n }\n\n const rangeStr = result.lineRange\n ? ` (lines ${result.lineRange[0]}-${result.lineRange[1]} of ${result.totalLines})`\n : '';\n\n return `File: ${result.github}/${result.path}${rangeStr}\\n\\n${result.content}`;\n}\n\n/**\n * Format warp grep results for display or tool responses\n * \n * @param result - The search result\n * @returns Formatted string representation\n */\nexport function formatResult(result: WarpGrepResult): string {\n if (!result.success) {\n return `Search failed: ${result.error}`;\n }\n\n if (!result.contexts || result.contexts.length === 0) {\n return 'No relevant code found. Try rephrasing your search term.';\n }\n\n const parts: string[] = [];\n parts.push(`Morph Fast Context subagent performed search on repository:\\n`);\n parts.push('Relevant context found:');\n\n for (const ctx of result.contexts) {\n const rangeStr = !ctx.lines || ctx.lines === '*'\n ? '*'\n : ctx.lines.map(([s, e]) => `${s}-${e}`).join(',');\n parts.push(`- ${ctx.file}:${rangeStr}`);\n }\n\n parts.push('\\nHere is the content of files:\\n');\n\n for (const ctx of result.contexts) {\n const rangeStr = !ctx.lines || ctx.lines === '*'\n ? ''\n : ` lines=\"${ctx.lines.map(([s, e]) => `${s}-${e}`).join(',')}\"`;\n parts.push(`<file path=\"${ctx.file}\"${rangeStr}>`);\n parts.push(ctx.content);\n parts.push('</file>\\n');\n }\n\n return parts.join('\\n');\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,IAAM,0BAA0B;AAOhC,eAAe,iBAAiB,UAAkB,UAAqB,YAAkD;AACvH,QAAM,EAAE,qBAAqB,IAAI,MAAM,OAAO,sCAAsB;AACpE,QAAM,OAAO,YAAY,SAAS,EAAE,WAAW,IAAI;AACnD,SAAO,IAAI,qBAAqB,UAAU,UAAU,IAAI;AAC1D;AA6BO,IAAM,iBAAN,cAA6B,YAAY;AAAA,EACtC;AAAA,EAER,YAAY,iBAAwD,CAAC,GAAG;AACtE,UAAM,WAAW,0BAA0B;AAC3C;AAAA,MACE,WACI,iBACA,IAAI,eAAe;AAAA,QACjB,QAAQ,eAAe;AAAA,QACvB,SAAS,eAAe;AAAA,QACxB,SAAS,eAAe;AAAA,QACxB,aAAa,eAAe;AAAA,QAC5B,OAAO,eAAe;AAAA,MACxB,CAAC;AAAA,IACP;AACA,UAAM,MAA4B,WAAW,CAAC,IAAI;AAIlD,SAAK,SAAS;AAAA,MAC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
|
-
{"version":3,"sources":["../core/error.ts"],"sourcesContent":["/**\n * Single error mapper for the SDK transport.\n *\n * Consolidates the per-tool error handling that used to live in every client\n * (compact, github, …) into one place, preserving the actionable\n * 401/429 messaging. Reuses the existing `MorphError` type so callers that\n * `instanceof MorphError` keep working.\n */\nimport { MorphError } from '../tools/utils/resilience.js';\n\ninterface ApiErrorBody {\n error?: { message?: string; code?: string; type?: string };\n message?: string;\n}\n\n/**\n * Turn a non-OK `Response` into a `MorphError`, extracting the API's error\n * message when present and marking 429/503 as retryable.\n */\nexport async function toMorphError(response: Response): Promise<MorphError> {\n let message = `Morph API request failed (${response.status})`;\n let code = 'api_error';\n\n try {\n const body = (await response.json()) as ApiErrorBody;\n message = body.error?.message ?? body.message ?? message;\n code = body.error?.code ?? body.error?.type ?? code;\n } catch {\n // Non-JSON body — keep the status-based default message.\n }\n\n if (response.status === 401) code = 'authentication_error';\n if (response.status === 429) code = 'rate_limit_exceeded';\n\n const retryable = response.status === 429 || response.status === 503;\n return new MorphError(message, code, response.status, retryable);\n}\n"],"mappings":";;;;;AAmBA,eAAsB,aAAa,UAAyC;AAC1E,MAAI,UAAU,6BAA6B,SAAS,MAAM;AAC1D,MAAI,OAAO;AAEX,MAAI;AACF,UAAM,OAAQ,MAAM,SAAS,KAAK;AAClC,cAAU,KAAK,OAAO,WAAW,KAAK,WAAW;AACjD,WAAO,KAAK,OAAO,QAAQ,KAAK,OAAO,QAAQ;AAAA,EACjD,QAAQ;AAAA,EAER;AAEA,MAAI,SAAS,WAAW,IAAK,QAAO;AACpC,MAAI,SAAS,WAAW,IAAK,QAAO;AAEpC,QAAM,YAAY,SAAS,WAAW,OAAO,SAAS,WAAW;AACjE,SAAO,IAAI,WAAW,SAAS,MAAM,SAAS,QAAQ,SAAS;AACjE;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../tools/warp_grep/providers/code_storage_http.ts"],"sourcesContent":["/**\n * HTTP-based RemoteCommands for code search against the Morph landing API.\n *\n * Translates grep/read/listDir into POST requests to the code-search endpoints,\n * so the WarpGrep agent can search GitHub repositories that have been indexed\n * by the Morph code storage service.\n */\n\nimport type { RemoteCommands } from '../types.js';\n\n/**\n * The WarpGrep model addresses files as if the repo were checked out at\n * /home/ubuntu/repo (its training root), while the code-search endpoints\n * expect repo-relative paths. Strip the training root and any leading\n * slashes at this boundary — the same normalization the dashboard\n * playground applies via warpgrep-mock-paths.ts.\n */\nconst MODEL_REPO_ROOT = /^\\/?home\\/ubuntu\\/repo(?:\\/|$)/;\n\nexport function toRepoRelative(path: string): string {\n if (!path) return path;\n const stripped = path.replace(MODEL_REPO_ROOT, '').replace(/^\\.?\\/+/, '');\n return stripped || '.';\n}\n\nexport interface CodeStorageHttpConfig {\n /** Base URL for the code search API (e.g. \"https://api.morphllm.com\") */\n baseUrl: string;\n /** Repository ID returned by the get-or-create endpoint */\n repoId: string;\n /** Git branch to search */\n branch: string;\n /** Morph API key, forwarded as a Bearer token (api.morphllm.com requires it) */\n apiKey?: string;\n}\n\nasync function post(url: string, body: Record<string, unknown>, op: string, apiKey?: string): Promise<string> {\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n },\n body: JSON.stringify(body),\n });\n if (!res.ok) {\n const text = await res.text().catch(() => res.statusText);\n // Return error as content instead of throwing so the agent can handle it gracefully\n try {\n const parsed = JSON.parse(text);\n if (parsed.error) return `Error: ${parsed.error}`;\n } catch { /* not JSON, fall through */ }\n return `Error: ${op} failed (${res.status}): ${text}`;\n }\n const data = await res.json();\n if (data.error) throw new Error(data.error);\n return data.stdout;\n}\n\nexport function createCodeStorageHttpCommands(config: CodeStorageHttpConfig): RemoteCommands {\n const { baseUrl, repoId, branch, apiKey } = config;\n const encodedRepoId = encodeURIComponent(repoId);\n\n return {\n grep: (pattern: string, path: string, glob?: string) =>\n post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path: toRepoRelative(path), glob, branch }, 'grep', apiKey),\n\n read: (path: string, start: number, end: number) =>\n post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path: toRepoRelative(path), start, end, branch }, 'read', apiKey),\n\n listDir: (path: string, maxDepth: number) =>\n post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path: toRepoRelative(path), maxDepth, branch }, 'list', apiKey),\n };\n}\n"],"mappings":";AAiBA,IAAM,kBAAkB;AAEjB,SAAS,eAAe,MAAsB;AACnD,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,WAAW,KAAK,QAAQ,iBAAiB,EAAE,EAAE,QAAQ,WAAW,EAAE;AACxE,SAAO,YAAY;AACrB;AAaA,eAAe,KAAK,KAAa,MAA+B,IAAY,QAAkC;AAC5G,QAAM,MAAM,MAAM,MAAM,KAAK;AAAA,IAC3B,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,GAAI,SAAS,EAAE,eAAe,UAAU,MAAM,GAAG,IAAI,CAAC;AAAA,IACxD;AAAA,IACA,MAAM,KAAK,UAAU,IAAI;AAAA,EAC3B,CAAC;AACD,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,MAAM,IAAI,UAAU;AAExD,QAAI;AACF,YAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,UAAI,OAAO,MAAO,QAAO,UAAU,OAAO,KAAK;AAAA,IACjD,QAAQ;AAAA,IAA+B;AACvC,WAAO,UAAU,EAAE,YAAY,IAAI,MAAM,MAAM,IAAI;AAAA,EACrD;AACA,QAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,MAAI,KAAK,MAAO,OAAM,IAAI,MAAM,KAAK,KAAK;AAC1C,SAAO,KAAK;AACd;AAEO,SAAS,8BAA8B,QAA+C;AAC3F,QAAM,EAAE,SAAS,QAAQ,QAAQ,OAAO,IAAI;AAC5C,QAAM,gBAAgB,mBAAmB,MAAM;AAE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