@morphllm/morphsdk 0.2.201 → 0.2.203
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-2PPYWRMZ.js +3 -4
- package/dist/{chunk-DBNSOYQ3.js → chunk-2UIOCSVJ.js} +3 -24
- package/dist/chunk-44OIEPIO.js +4 -23
- package/dist/chunk-4EQQGUZ7.cjs +104 -0
- package/dist/chunk-4OUGA3KS.js +1 -5
- package/dist/chunk-4R5MDGL6.cjs +280 -0
- package/dist/chunk-65W4I66Q.cjs +103 -0
- package/dist/{chunk-WBTXEJOC.js → chunk-66THRMD7.js} +10 -35
- package/dist/chunk-6TZCVTW5.js +3 -4
- package/dist/chunk-6WP7EA4F.js +2 -4
- package/dist/chunk-74A4HLIO.cjs +42 -0
- package/dist/chunk-75ZPJI57.cjs +9 -0
- package/dist/chunk-7NA7X7W2.cjs +77 -0
- package/dist/chunk-7PJYY46L.cjs +2 -0
- package/dist/chunk-AFF6XYKL.cjs +71 -0
- package/dist/{chunk-P2KW2O5R.js → chunk-AJBZA23L.js} +3 -25
- package/dist/chunk-AWFZKS27.cjs +11 -0
- package/dist/{chunk-FVT4PU4I.js → chunk-AXEKIRRY.js} +22 -62
- package/dist/chunk-B3FD67F2.cjs +256 -0
- package/dist/chunk-BJBWWIZV.cjs +2 -0
- package/dist/{chunk-M6AVXUM4.js → chunk-E3XNKAMI.js} +5 -15
- package/dist/{chunk-TS3OJ4LA.js → chunk-E7FLETFO.js} +2 -8
- package/dist/{chunk-EQAWWVKV.js → chunk-EI2M567U.js} +2 -6
- package/dist/chunk-EJTL2BOZ.cjs +42 -0
- package/dist/chunk-ETBRAKVV.js +1 -5
- package/dist/{chunk-VOXUA5ZH.js → chunk-EZ2OFDBJ.js} +5 -19
- package/dist/chunk-FBOZIVVQ.js +1 -0
- package/dist/{chunk-TZC3EOZS.js → chunk-GDFPZ3NJ.js} +4 -19
- package/dist/{chunk-LISSWRUD.js → chunk-GIQAIHUI.js} +8 -33
- package/dist/chunk-GSUQGDCL.cjs +235 -0
- package/dist/{chunk-5NSYDT36.js → chunk-H3HRSRR5.js} +4 -12
- package/dist/chunk-HDP4QAZL.js +1 -4
- package/dist/chunk-HMLYJVZM.cjs +410 -0
- package/dist/chunk-IPJA3ZS6.cjs +10 -0
- package/dist/{chunk-B376VMIH.js → chunk-IUM6CQYX.js} +3 -12
- package/dist/{chunk-OVLUL5AC.js → chunk-J56Q6C4Y.js} +4 -18
- package/dist/chunk-JBTR3FQD.cjs +135 -0
- package/dist/chunk-JNQKQKHS.cjs +81 -0
- package/dist/chunk-JOZC4T6C.cjs +168 -0
- package/dist/{chunk-ILY5N5NJ.js → chunk-JUGNTIVU.js} +6 -19
- package/dist/{chunk-SU7AAS3O.js → chunk-JY6COF3X.js} +5 -22
- package/dist/{chunk-JBAY3PRV.js → chunk-KLVJIC2O.js} +5 -17
- package/dist/chunk-KSZYOX6S.cjs +91 -0
- package/dist/chunk-KVGZ2TSG.cjs +274 -0
- package/dist/chunk-LDM7RNNN.js +1 -0
- package/dist/{chunk-RZOJ4GSY.js → chunk-LLQH6CCB.js} +10 -28
- package/dist/chunk-M34E2AMK.js +1 -5
- package/dist/chunk-MF56KEI4.js +1 -4
- package/dist/chunk-MLKGABMK.js +1 -3
- package/dist/{chunk-I26FQELI.js → chunk-MLPZKUCO.js} +11 -5
- package/dist/chunk-MWXJ6DZ2.cjs +21 -0
- package/dist/{chunk-NWGRW4V7.js → chunk-N7UKZ5X7.js} +2 -6
- package/dist/chunk-NDUC7OV6.cjs +74 -0
- package/dist/{chunk-RJXAXR7Q.js → chunk-NLACTMZT.js} +6 -19
- package/dist/chunk-NNKBKENK.cjs +15 -0
- package/dist/chunk-NRG6QX3L.js +1 -3
- package/dist/chunk-OCCGJ4S6.js +8 -0
- package/dist/chunk-ODY2NKQU.cjs +50 -0
- package/dist/chunk-OM5ZSXQW.cjs +91 -0
- package/dist/chunk-OOEORM7H.cjs +334 -0
- package/dist/chunk-OPDWMD4Q.js +1 -3
- package/dist/{chunk-BZXOAC2R.js → chunk-OSL4CNSO.js} +7 -23
- package/dist/chunk-OXXMTDOY.cjs +86 -0
- package/dist/chunk-PA3UTI4A.js +1 -4
- package/dist/chunk-QEEAIXL5.cjs +74 -0
- package/dist/chunk-RYVW7RUM.js +2 -6
- package/dist/chunk-S6QBPXBI.cjs +107 -0
- package/dist/chunk-TL34BLQD.cjs +10 -0
- package/dist/chunk-TPZHMD7J.cjs +72 -0
- package/dist/chunk-UAPK3AIJ.js +1 -10
- package/dist/chunk-UF5IKELS.cjs +26 -0
- package/dist/chunk-UNX7V6P6.cjs +60 -0
- package/dist/chunk-UUCRWJJR.cjs +313 -0
- package/dist/chunk-VDFLPO7B.cjs +396 -0
- package/dist/chunk-VHD7CW5O.cjs +43 -0
- package/dist/chunk-VL4QNALG.cjs +50 -0
- package/dist/chunk-WR7LSUIR.cjs +213 -0
- package/dist/chunk-XE6D4J63.cjs +72 -0
- package/dist/chunk-ZLG2M2I4.cjs +21 -0
- package/dist/chunk-ZSHVXDA2.js +4 -10
- package/dist/client.cjs +40 -4353
- package/dist/client.js +32 -37
- package/dist/core/client.cjs +10 -476
- package/dist/core/client.js +6 -11
- package/dist/core/error.cjs +8 -251
- package/dist/core/error.js +4 -9
- package/dist/core/index.cjs +20 -488
- package/dist/core/index.js +8 -19
- package/dist/core/resource.cjs +9 -33
- package/dist/core/resource.js +2 -7
- package/dist/edge.cjs +62 -1111
- package/dist/edge.js +10 -42
- package/dist/index.cjs +115 -4424
- package/dist/index.js +39 -87
- package/dist/modelrouter/core.cjs +28 -648
- package/dist/modelrouter/core.js +8 -21
- package/dist/modelrouter/index.cjs +28 -648
- package/dist/modelrouter/index.js +8 -21
- package/dist/modelrouter/types.cjs +1 -17
- package/dist/modelrouter/types.js +1 -0
- package/dist/subagents/anthropic.cjs +27 -2777
- package/dist/subagents/anthropic.js +19 -24
- package/dist/subagents/index.cjs +14 -95
- package/dist/subagents/index.js +2 -11
- package/dist/subagents/prompts.cjs +14 -93
- package/dist/subagents/prompts.js +2 -11
- package/dist/subagents/types.cjs +1 -17
- package/dist/subagents/types.js +1 -0
- package/dist/subagents/vercel.cjs +27 -2754
- package/dist/subagents/vercel.js +19 -24
- package/dist/tools/compact/core.cjs +12 -548
- package/dist/tools/compact/core.js +8 -13
- package/dist/tools/compact/index.cjs +17 -595
- package/dist/tools/compact/index.js +9 -17
- package/dist/tools/compact/types.cjs +1 -17
- package/dist/tools/compact/types.js +1 -0
- package/dist/tools/fastapply/anthropic.cjs +27 -891
- package/dist/tools/fastapply/anthropic.js +11 -24
- package/dist/tools/fastapply/apply.cjs +28 -672
- package/dist/tools/fastapply/apply.js +4 -19
- package/dist/tools/fastapply/core.cjs +37 -1061
- package/dist/tools/fastapply/core.js +9 -29
- package/dist/tools/fastapply/index.cjs +62 -1062
- package/dist/tools/fastapply/index.js +14 -44
- package/dist/tools/fastapply/openai.cjs +32 -901
- package/dist/tools/fastapply/openai.js +11 -26
- package/dist/tools/fastapply/prompts.cjs +10 -62
- package/dist/tools/fastapply/prompts.js +2 -9
- package/dist/tools/fastapply/types.cjs +1 -17
- package/dist/tools/fastapply/types.js +1 -0
- package/dist/tools/fastapply/vercel.cjs +25 -897
- package/dist/tools/fastapply/vercel.js +11 -22
- package/dist/tools/index.cjs +62 -1062
- package/dist/tools/index.js +14 -44
- package/dist/tools/utils/resilience.cjs +15 -312
- package/dist/tools/utils/resilience.js +3 -12
- package/dist/tools/warp_grep/agent/config.cjs +16 -127
- package/dist/tools/warp_grep/agent/config.js +2 -11
- package/dist/tools/warp_grep/agent/formatter.cjs +12 -48
- package/dist/tools/warp_grep/agent/formatter.js +2 -9
- package/dist/tools/warp_grep/agent/parser.cjs +16 -83
- package/dist/tools/warp_grep/agent/parser.js +2 -11
- package/dist/tools/warp_grep/agent/runner.cjs +15 -1081
- package/dist/tools/warp_grep/agent/runner.js +7 -14
- package/dist/tools/warp_grep/agent/types.cjs +1 -17
- package/dist/tools/warp_grep/agent/types.js +1 -0
- package/dist/tools/warp_grep/anthropic.cjs +47 -2554
- package/dist/tools/warp_grep/anthropic.js +19 -35
- package/dist/tools/warp_grep/client.cjs +49 -2464
- package/dist/tools/warp_grep/client.js +17 -34
- package/dist/tools/warp_grep/gemini.cjs +48 -2483
- package/dist/tools/warp_grep/gemini.js +21 -41
- package/dist/tools/warp_grep/harness.cjs +81 -929
- package/dist/tools/warp_grep/harness.js +12 -51
- package/dist/tools/warp_grep/index.cjs +124 -2568
- package/dist/tools/warp_grep/index.js +24 -87
- package/dist/tools/warp_grep/openai.cjs +53 -2568
- package/dist/tools/warp_grep/openai.js +19 -37
- package/dist/tools/warp_grep/providers/code_storage_http.cjs +12 -65
- package/dist/tools/warp_grep/providers/code_storage_http.js +2 -9
- package/dist/tools/warp_grep/providers/local.cjs +10 -582
- package/dist/tools/warp_grep/providers/local.js +6 -11
- package/dist/tools/warp_grep/providers/remote.cjs +8 -331
- package/dist/tools/warp_grep/providers/remote.js +3 -8
- package/dist/tools/warp_grep/providers/types.cjs +1 -17
- package/dist/tools/warp_grep/providers/types.js +1 -0
- package/dist/tools/warp_grep/utils/files.cjs +9 -42
- package/dist/tools/warp_grep/utils/files.js +2 -7
- package/dist/tools/warp_grep/utils/github.cjs +9 -43
- package/dist/tools/warp_grep/utils/github.js +2 -7
- package/dist/tools/warp_grep/utils/paths.cjs +28 -104
- package/dist/tools/warp_grep/utils/paths.js +2 -17
- package/dist/tools/warp_grep/utils/ripgrep.cjs +9 -86
- package/dist/tools/warp_grep/utils/ripgrep.js +2 -7
- package/dist/tools/warp_grep/vercel.cjs +53 -2550
- package/dist/tools/warp_grep/vercel.js +19 -37
- package/dist/version.cjs +7 -225
- package/dist/version.js +2 -7
- package/package.json +2 -2
- package/dist/chunk-UZCXOOZO.js +0 -203
package/dist/index.cjs
CHANGED
|
@@ -1,4425 +1,116 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
var
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
)
|
|
31
|
-
var
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
var
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
"./modelrouter": {
|
|
117
|
-
types: "./dist/modelrouter/index.d.ts",
|
|
118
|
-
import: "./dist/modelrouter/index.js",
|
|
119
|
-
require: "./dist/modelrouter/index.cjs"
|
|
120
|
-
},
|
|
121
|
-
"./tools/compact": {
|
|
122
|
-
types: "./dist/tools/compact/index.d.ts",
|
|
123
|
-
import: "./dist/tools/compact/index.js",
|
|
124
|
-
require: "./dist/tools/compact/index.cjs"
|
|
125
|
-
},
|
|
126
|
-
"./subagents": {
|
|
127
|
-
types: "./dist/subagents/index.d.ts",
|
|
128
|
-
import: "./dist/subagents/index.js",
|
|
129
|
-
require: "./dist/subagents/index.cjs"
|
|
130
|
-
},
|
|
131
|
-
"./subagents/vercel": {
|
|
132
|
-
types: "./dist/subagents/vercel.d.ts",
|
|
133
|
-
import: "./dist/subagents/vercel.js",
|
|
134
|
-
require: "./dist/subagents/vercel.cjs"
|
|
135
|
-
},
|
|
136
|
-
"./subagents/anthropic": {
|
|
137
|
-
types: "./dist/subagents/anthropic.d.ts",
|
|
138
|
-
import: "./dist/subagents/anthropic.js",
|
|
139
|
-
require: "./dist/subagents/anthropic.cjs"
|
|
140
|
-
},
|
|
141
|
-
"./ai-sdk": {
|
|
142
|
-
types: "./dist/ai-sdk/index.d.ts",
|
|
143
|
-
import: "./dist/ai-sdk/index.js",
|
|
144
|
-
require: "./dist/ai-sdk/index.cjs"
|
|
145
|
-
}
|
|
146
|
-
},
|
|
147
|
-
files: [
|
|
148
|
-
"dist/**/*.js",
|
|
149
|
-
"dist/**/*.cjs",
|
|
150
|
-
"dist/**/*.d.ts",
|
|
151
|
-
"!dist/**/__tests__/**",
|
|
152
|
-
"!dist/**/*.test.*"
|
|
153
|
-
],
|
|
154
|
-
scripts: {
|
|
155
|
-
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",
|
|
156
|
-
prepare: "npm run build",
|
|
157
|
-
typecheck: "tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json",
|
|
158
|
-
lint: "eslint .",
|
|
159
|
-
test: "vitest run",
|
|
160
|
-
"test:watch": "vitest watch",
|
|
161
|
-
"test:anthropic": "vitest run anthropic",
|
|
162
|
-
"test:openai": "vitest run openai",
|
|
163
|
-
"test:vercel": "vitest run vercel",
|
|
164
|
-
"test:git": "vitest run git",
|
|
165
|
-
"test:agent": "npx tsx tests/fullAgentTest.ts",
|
|
166
|
-
"test:integration": "npx tsx tests/fullIntegrationTest.ts",
|
|
167
|
-
"test:e2e": "vitest run --config vitest.e2e.config.ts",
|
|
168
|
-
"release:patch": "npm version patch && npm publish",
|
|
169
|
-
"release:minor": "npm version minor && npm publish",
|
|
170
|
-
"release:major": "npm version major && npm publish"
|
|
171
|
-
},
|
|
172
|
-
keywords: [
|
|
173
|
-
"morph",
|
|
174
|
-
"fast-apply",
|
|
175
|
-
"cli",
|
|
176
|
-
"sdk",
|
|
177
|
-
"edit-file"
|
|
178
|
-
],
|
|
179
|
-
engines: {
|
|
180
|
-
node: ">=18"
|
|
181
|
-
},
|
|
182
|
-
license: "MIT",
|
|
183
|
-
dependencies: {
|
|
184
|
-
"@vscode/ripgrep": "^1.17.0",
|
|
185
|
-
ai: ">=5.0.0",
|
|
186
|
-
diff: "^7.0.0",
|
|
187
|
-
openai: "^4.52.7",
|
|
188
|
-
zod: ">=3.23.0"
|
|
189
|
-
},
|
|
190
|
-
devDependencies: {
|
|
191
|
-
"@ai-sdk/anthropic": "^2.0.70",
|
|
192
|
-
"@ai-sdk/openai": "^2.0.35",
|
|
193
|
-
"@anthropic-ai/sdk": "^0.30.1",
|
|
194
|
-
"@google/generative-ai": "^0.24.1",
|
|
195
|
-
"@types/diff": "^7.0.2",
|
|
196
|
-
"@types/node": "^20.14.10",
|
|
197
|
-
"@typescript-eslint/eslint-plugin": "^7.18.0",
|
|
198
|
-
"@typescript-eslint/parser": "^7.18.0",
|
|
199
|
-
dotenv: "^16.4.5",
|
|
200
|
-
eslint: "^8.57.0",
|
|
201
|
-
shx: "^0.3.4",
|
|
202
|
-
tsup: "^8.5.0",
|
|
203
|
-
tsx: "^4.16.2",
|
|
204
|
-
typescript: "^5.5.4",
|
|
205
|
-
vitest: "^2.1.6"
|
|
206
|
-
},
|
|
207
|
-
peerDependencies: {
|
|
208
|
-
"@ai-sdk/openai-compatible": ">=2.0.74 <4",
|
|
209
|
-
"@anthropic-ai/sdk": ">=0.25.0",
|
|
210
|
-
"@google/generative-ai": ">=0.21.0",
|
|
211
|
-
ai: ">=5.0.0",
|
|
212
|
-
zod: ">=3.23.0"
|
|
213
|
-
},
|
|
214
|
-
peerDependenciesMeta: {
|
|
215
|
-
"@anthropic-ai/sdk": {
|
|
216
|
-
optional: true
|
|
217
|
-
},
|
|
218
|
-
"@google/generative-ai": {
|
|
219
|
-
optional: true
|
|
220
|
-
},
|
|
221
|
-
ai: {
|
|
222
|
-
optional: true
|
|
223
|
-
},
|
|
224
|
-
zod: {
|
|
225
|
-
optional: true
|
|
226
|
-
}
|
|
227
|
-
},
|
|
228
|
-
publishConfig: {
|
|
229
|
-
access: "public"
|
|
230
|
-
}
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
});
|
|
234
|
-
|
|
235
|
-
// version.ts
|
|
236
|
-
var SDK_VERSION;
|
|
237
|
-
var init_version = __esm({
|
|
238
|
-
"version.ts"() {
|
|
239
|
-
"use strict";
|
|
240
|
-
init_package();
|
|
241
|
-
SDK_VERSION = package_default.version;
|
|
242
|
-
}
|
|
243
|
-
});
|
|
244
|
-
|
|
245
|
-
// logger.ts
|
|
246
|
-
var MorphLogger, logger;
|
|
247
|
-
var init_logger = __esm({
|
|
248
|
-
"logger.ts"() {
|
|
249
|
-
"use strict";
|
|
250
|
-
MorphLogger = class {
|
|
251
|
-
enabled;
|
|
252
|
-
fileStream;
|
|
253
|
-
/** Resolves once the file stream is initialized (or immediately if no file logging). */
|
|
254
|
-
ready;
|
|
255
|
-
constructor() {
|
|
256
|
-
this.enabled = typeof process !== "undefined" && (process.env.MORPH_DEBUG === "1" || !!process.env.MORPH_LOG_FILE);
|
|
257
|
-
this.fileStream = null;
|
|
258
|
-
const f = typeof process !== "undefined" ? process.env.MORPH_LOG_FILE : void 0;
|
|
259
|
-
if (f) {
|
|
260
|
-
this.ready = import("fs").then((fs4) => {
|
|
261
|
-
this.fileStream = fs4.createWriteStream(f, { flags: "a" });
|
|
262
|
-
}).catch(() => {
|
|
263
|
-
});
|
|
264
|
-
} else {
|
|
265
|
-
this.ready = Promise.resolve();
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
debug(component, msg, data) {
|
|
269
|
-
this._log("debug", component, msg, data);
|
|
270
|
-
}
|
|
271
|
-
info(component, msg, data) {
|
|
272
|
-
this._log("info", component, msg, data);
|
|
273
|
-
}
|
|
274
|
-
warn(component, msg, data) {
|
|
275
|
-
this._log("warn", component, msg, data);
|
|
276
|
-
}
|
|
277
|
-
error(component, msg, data) {
|
|
278
|
-
this._log("error", component, msg, data);
|
|
279
|
-
}
|
|
280
|
-
enable() {
|
|
281
|
-
this.enabled = true;
|
|
282
|
-
}
|
|
283
|
-
get isEnabled() {
|
|
284
|
-
return this.enabled;
|
|
285
|
-
}
|
|
286
|
-
_log(level, component, msg, data) {
|
|
287
|
-
if (level !== "error" && !this.enabled) return;
|
|
288
|
-
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
289
|
-
const prefix = `[${ts}] [${level.toUpperCase()}] [${component}]`;
|
|
290
|
-
console.error(data ? `${prefix} ${msg} ${JSON.stringify(data)}` : `${prefix} ${msg}`);
|
|
291
|
-
this.fileStream?.write(JSON.stringify({ ts, level, component, msg, ...data && { data } }) + "\n");
|
|
292
|
-
}
|
|
293
|
-
};
|
|
294
|
-
logger = new MorphLogger();
|
|
295
|
-
}
|
|
296
|
-
});
|
|
297
|
-
|
|
298
|
-
// tools/fastapply/anchors.ts
|
|
299
|
-
function escapeRegExp(value) {
|
|
300
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
301
|
-
}
|
|
302
|
-
function findNamespace(values) {
|
|
303
|
-
for (let namespace = 0; namespace < Number.MAX_SAFE_INTEGER; namespace++) {
|
|
304
|
-
const prefix = `\u27EAM${namespace}:`;
|
|
305
|
-
if (values.every((value) => !value.includes(prefix))) {
|
|
306
|
-
return namespace;
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
throw new Error("Unable to allocate a Fast Apply anchor namespace");
|
|
310
|
-
}
|
|
311
|
-
function htmlLabel(token) {
|
|
312
|
-
if (!token.startsWith("<")) return "text";
|
|
313
|
-
const match = token.match(/^<\s*(!doctype|\/?[a-zA-Z][\w:-]*)/);
|
|
314
|
-
return (match?.[1] ?? "tag").toLowerCase();
|
|
315
|
-
}
|
|
316
|
-
function htmlTokenUnits(value, visibleTags = /* @__PURE__ */ new Set()) {
|
|
317
|
-
return (value.match(/<[^>]*>|[^<]+/g) ?? [value]).map((token) => ({
|
|
318
|
-
value: token,
|
|
319
|
-
label: htmlLabel(token),
|
|
320
|
-
anchorable: token.length >= DEFAULT_MIN_ANCHOR_LINE_LENGTH && !visibleTags.has(htmlLabel(token).replace(/^\//, ""))
|
|
321
|
-
}));
|
|
322
|
-
}
|
|
323
|
-
function sourceUnits(originalCode, editContext) {
|
|
324
|
-
const trimmed = originalCode.trimStart().toLowerCase();
|
|
325
|
-
const looksLikeHtml = (trimmed.startsWith("<!doctype") || trimmed.startsWith("<html")) && /<\/html\s*>/i.test(originalCode);
|
|
326
|
-
if (looksLikeHtml) {
|
|
327
|
-
const contextWords = new Set(
|
|
328
|
-
editContext.join(" ").toLowerCase().match(/[a-z][\w:-]*/g) ?? []
|
|
329
|
-
);
|
|
330
|
-
return htmlTokenUnits(originalCode, contextWords);
|
|
331
|
-
}
|
|
332
|
-
const parts = originalCode.split(/(\r\n|\n|\r)/);
|
|
333
|
-
const units = [];
|
|
334
|
-
for (let index = 0; index < parts.length; index += 2) {
|
|
335
|
-
const line = parts[index] ?? "";
|
|
336
|
-
const lineEnding = parts[index + 1] ?? "";
|
|
337
|
-
units.push({
|
|
338
|
-
value: line,
|
|
339
|
-
label: "line",
|
|
340
|
-
anchorable: line.length >= DEFAULT_MIN_ANCHOR_LINE_LENGTH
|
|
341
|
-
});
|
|
342
|
-
if (lineEnding) {
|
|
343
|
-
units.push({ value: lineEnding, anchorable: false });
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
return units;
|
|
347
|
-
}
|
|
348
|
-
function copyCount(value) {
|
|
349
|
-
const words = {
|
|
350
|
-
one: 1,
|
|
351
|
-
two: 2,
|
|
352
|
-
three: 3,
|
|
353
|
-
four: 4,
|
|
354
|
-
five: 5,
|
|
355
|
-
six: 6,
|
|
356
|
-
seven: 7,
|
|
357
|
-
eight: 8,
|
|
358
|
-
nine: 9,
|
|
359
|
-
ten: 10
|
|
360
|
-
};
|
|
361
|
-
return /^\d+$/.test(value) ? Number(value) : words[value.toLowerCase()];
|
|
362
|
-
}
|
|
363
|
-
function structuralExpectation(originalCode, editContext) {
|
|
364
|
-
const context = editContext.join(" ");
|
|
365
|
-
const match = context.match(
|
|
366
|
-
/(?:for every|for each|each)\s+([a-z][\w:-]*)[\s\S]{0,120}?add\s+(one|two|three|four|five|six|seven|eight|nine|ten|\d+)\s+identical cop(?:y|ies)/i
|
|
367
|
-
);
|
|
368
|
-
if (!match) return void 0;
|
|
369
|
-
const tag = match[1].toLowerCase();
|
|
370
|
-
const addedCopies = copyCount(match[2]);
|
|
371
|
-
if (addedCopies === void 0) return void 0;
|
|
372
|
-
const tagPattern = new RegExp(`<${escapeRegExp(tag)}(?:\\s|>)`, "gi");
|
|
373
|
-
const originalCount = originalCode.match(tagPattern)?.length ?? 0;
|
|
374
|
-
if (originalCount === 0) return void 0;
|
|
375
|
-
return { tag, expectedCount: originalCount * (addedCopies + 1) };
|
|
376
|
-
}
|
|
377
|
-
function createAnchorCompactionPlan(originalCode, collisionValues = []) {
|
|
378
|
-
const namespace = findNamespace([originalCode, ...collisionValues]);
|
|
379
|
-
const expectation = structuralExpectation(originalCode, collisionValues);
|
|
380
|
-
const markerPrefix = `\u27EAM${namespace}:`;
|
|
381
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
382
|
-
const values = [];
|
|
383
|
-
const markers = [];
|
|
384
|
-
let anchorCount = 0;
|
|
385
|
-
let skeleton = "";
|
|
386
|
-
for (const unit of sourceUnits(originalCode, collisionValues)) {
|
|
387
|
-
if (!unit.anchorable) {
|
|
388
|
-
skeleton += unit.value;
|
|
389
|
-
continue;
|
|
390
|
-
}
|
|
391
|
-
let id = definitions.get(unit.value);
|
|
392
|
-
if (id === void 0) {
|
|
393
|
-
id = values.length;
|
|
394
|
-
definitions.set(unit.value, id);
|
|
395
|
-
values.push(unit.value);
|
|
396
|
-
markers.push(`${markerPrefix}${id}:${unit.label ?? "unit"}\u27EB`);
|
|
397
|
-
}
|
|
398
|
-
skeleton += markers[id];
|
|
399
|
-
anchorCount++;
|
|
400
|
-
}
|
|
401
|
-
if (anchorCount === 0 || skeleton.length >= originalCode.length) {
|
|
402
|
-
return void 0;
|
|
403
|
-
}
|
|
404
|
-
const definitionsBegin = `\u27EAMORPH_DEFINITIONS_BEGIN_${namespace}\u27EB`;
|
|
405
|
-
const definitionsEnd = `\u27EAMORPH_DEFINITIONS_END_${namespace}\u27EB`;
|
|
406
|
-
const codeBegin = `\u27EAMORPH_CODE_BEGIN_${namespace}\u27EB`;
|
|
407
|
-
const serializedDefinitions = values.map((value, id) => `${markers[id]}=${JSON.stringify(value)}`).join("\n");
|
|
408
|
-
const code = [
|
|
409
|
-
definitionsBegin,
|
|
410
|
-
serializedDefinitions,
|
|
411
|
-
definitionsEnd,
|
|
412
|
-
codeBegin,
|
|
413
|
-
skeleton
|
|
414
|
-
].join("\n");
|
|
415
|
-
const instructionSuffix = `
|
|
416
|
-
|
|
417
|
-
LARGE-FILE ANCHOR PROTOCOL:
|
|
418
|
-
The <code> block starts with an exact anchor definition table, then ${codeBegin}, then the source skeleton.
|
|
419
|
-
Each ${markerPrefix}N:kind\u27EB placeholder represents the exact source fragment in its matching JSON-string definition. The kind suffix describes its HTML tag, text, or source line.
|
|
420
|
-
Return only the updated source skeleton after ${codeBegin}; never return the definition table or protocol delimiters.
|
|
421
|
-
Copy a placeholder exactly when its source fragment is unchanged. You may repeat, reorder, or remove placeholders when the requested edit requires it.
|
|
422
|
-
To modify an anchored fragment, output the modified source instead of its placeholder.
|
|
423
|
-
Do not invent or alter placeholder IDs.`;
|
|
424
|
-
const markerPattern = new RegExp(`${escapeRegExp(markerPrefix)}(\\d+):[^\u27EB]+\u27EB`, "g");
|
|
425
|
-
return {
|
|
426
|
-
code,
|
|
427
|
-
instructionSuffix,
|
|
428
|
-
anchorCount,
|
|
429
|
-
uniqueAnchorCount: values.length,
|
|
430
|
-
hasStructuralValidation: expectation !== void 0,
|
|
431
|
-
expand(content) {
|
|
432
|
-
const codeBeginIndex = content.lastIndexOf(codeBegin);
|
|
433
|
-
const skeletonContent = codeBeginIndex >= 0 ? content.slice(codeBeginIndex + codeBegin.length).replace(/^\r?\n/, "") : content;
|
|
434
|
-
const expanded = skeletonContent.replace(markerPattern, (marker, idText) => {
|
|
435
|
-
const id = Number(idText);
|
|
436
|
-
const value = values[id];
|
|
437
|
-
return value === void 0 || markers[id] !== marker ? marker : value;
|
|
438
|
-
});
|
|
439
|
-
if (expanded.includes(markerPrefix)) {
|
|
440
|
-
throw new FastApplyAnchorIntegrityError();
|
|
441
|
-
}
|
|
442
|
-
if (expectation) {
|
|
443
|
-
const tagPattern = new RegExp(`<${escapeRegExp(expectation.tag)}(?:\\s|>)`, "gi");
|
|
444
|
-
const actualCount = expanded.match(tagPattern)?.length ?? 0;
|
|
445
|
-
if (actualCount !== expectation.expectedCount) {
|
|
446
|
-
throw new FastApplyAnchorIntegrityError();
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
return expanded;
|
|
450
|
-
}
|
|
451
|
-
};
|
|
452
|
-
}
|
|
453
|
-
var DEFAULT_MIN_ANCHOR_LINE_LENGTH, DEFAULT_ANCHOR_COMPACTION_THRESHOLD, FastApplyAnchorIntegrityError;
|
|
454
|
-
var init_anchors = __esm({
|
|
455
|
-
"tools/fastapply/anchors.ts"() {
|
|
456
|
-
"use strict";
|
|
457
|
-
DEFAULT_MIN_ANCHOR_LINE_LENGTH = 24;
|
|
458
|
-
DEFAULT_ANCHOR_COMPACTION_THRESHOLD = 128 * 1024;
|
|
459
|
-
FastApplyAnchorIntegrityError = class extends Error {
|
|
460
|
-
code = "anchor_integrity_failed";
|
|
461
|
-
completionId;
|
|
462
|
-
constructor(completionId) {
|
|
463
|
-
super(
|
|
464
|
-
"Fast Apply failed large-file anchor integrity checks. The partial result was discarded safely."
|
|
465
|
-
);
|
|
466
|
-
this.name = "FastApplyAnchorIntegrityError";
|
|
467
|
-
this.completionId = completionId;
|
|
468
|
-
}
|
|
469
|
-
};
|
|
470
|
-
}
|
|
471
|
-
});
|
|
472
|
-
|
|
473
|
-
// tools/fastapply/apply.ts
|
|
474
|
-
var apply_exports = {};
|
|
475
|
-
__export(apply_exports, {
|
|
476
|
-
FastApplyAnchorIntegrityError: () => FastApplyAnchorIntegrityError,
|
|
477
|
-
FastApplyContextLengthError: () => FastApplyContextLengthError,
|
|
478
|
-
applyEdit: () => applyEdit,
|
|
479
|
-
callMorphAPI: () => callMorphAPI,
|
|
480
|
-
countChanges: () => countChanges,
|
|
481
|
-
generateUdiff: () => generateUdiff
|
|
482
|
-
});
|
|
483
|
-
function isAsyncIterable(value) {
|
|
484
|
-
return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
|
|
485
|
-
}
|
|
486
|
-
async function collectCompletion(response) {
|
|
487
|
-
if (!isAsyncIterable(response)) {
|
|
488
|
-
const completion = response;
|
|
489
|
-
return {
|
|
490
|
-
content: completion.choices?.[0]?.message?.content ?? "",
|
|
491
|
-
completionId: completion.id,
|
|
492
|
-
finishReason: completion.choices?.[0]?.finish_reason
|
|
493
|
-
};
|
|
494
|
-
}
|
|
495
|
-
const content = [];
|
|
496
|
-
let completionId;
|
|
497
|
-
let finishReason;
|
|
498
|
-
for await (const chunk of response) {
|
|
499
|
-
completionId = chunk.id ?? completionId;
|
|
500
|
-
for (const choice of chunk.choices ?? []) {
|
|
501
|
-
if (choice.delta?.content) {
|
|
502
|
-
content.push(choice.delta.content);
|
|
503
|
-
}
|
|
504
|
-
if (choice.finish_reason !== void 0 && choice.finish_reason !== null) {
|
|
505
|
-
finishReason = choice.finish_reason;
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
return { content: content.join(""), completionId, finishReason };
|
|
510
|
-
}
|
|
511
|
-
function generateUdiff(original, modified, filepath) {
|
|
512
|
-
return (0, import_diff.createTwoFilesPatch)(
|
|
513
|
-
filepath,
|
|
514
|
-
filepath,
|
|
515
|
-
original,
|
|
516
|
-
modified,
|
|
517
|
-
"Original",
|
|
518
|
-
"Modified"
|
|
519
|
-
);
|
|
520
|
-
}
|
|
521
|
-
function countChanges(original, modified) {
|
|
522
|
-
const diff = generateUdiff(original, modified, "file");
|
|
523
|
-
const lines = diff.split("\n");
|
|
524
|
-
let linesAdded = 0;
|
|
525
|
-
let linesRemoved = 0;
|
|
526
|
-
for (const line of lines) {
|
|
527
|
-
if (line.startsWith("+") && !line.startsWith("+++")) {
|
|
528
|
-
linesAdded++;
|
|
529
|
-
} else if (line.startsWith("-") && !line.startsWith("---")) {
|
|
530
|
-
linesRemoved++;
|
|
531
|
-
}
|
|
532
|
-
}
|
|
533
|
-
const linesModified = Math.min(linesAdded, linesRemoved);
|
|
534
|
-
return {
|
|
535
|
-
linesAdded: linesAdded - linesModified,
|
|
536
|
-
linesRemoved: linesRemoved - linesModified,
|
|
537
|
-
linesModified
|
|
538
|
-
};
|
|
539
|
-
}
|
|
540
|
-
async function callMorphAPI(originalCode, codeEdit, instructions, filepath, config) {
|
|
541
|
-
const apiKey = config.morphApiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
|
|
542
|
-
const apiUrl = config.morphApiUrl || DEFAULT_API_URL;
|
|
543
|
-
const useLarge = config.large ?? (typeof process !== "undefined" ? process.env?.MORPH_LARGE_APPLY !== "false" : true);
|
|
544
|
-
const model = useLarge ? "morph-v3-large" : "morph-v3-fast";
|
|
545
|
-
const timeout = config.timeout ?? DEFAULT_TIMEOUT2;
|
|
546
|
-
const debug = config.debug || false;
|
|
547
|
-
if (!apiKey) {
|
|
548
|
-
throw new Error(
|
|
549
|
-
"Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config."
|
|
550
|
-
);
|
|
551
|
-
}
|
|
552
|
-
const anchorThreshold = config.anchorCompactionThreshold ?? DEFAULT_ANCHOR_COMPACTION_THRESHOLD;
|
|
553
|
-
const anchorPlan = config.anchorCompaction !== false && originalCode.length >= anchorThreshold ? createAnchorCompactionPlan(originalCode, [codeEdit, instructions]) : void 0;
|
|
554
|
-
const requestCode = anchorPlan?.code ?? originalCode;
|
|
555
|
-
const requestInstructions = anchorPlan ? instructions + anchorPlan.instructionSuffix : instructions;
|
|
556
|
-
const message = `<instruction>${requestInstructions}</instruction>
|
|
557
|
-
<code>${requestCode}</code>
|
|
558
|
-
<update>${codeEdit}</update>`;
|
|
559
|
-
logger.debug("FastApply", "http_request", {
|
|
560
|
-
url: `${apiUrl}/v1/chat/completions`,
|
|
561
|
-
model,
|
|
562
|
-
filepath,
|
|
563
|
-
instruction_len: instructions.length,
|
|
564
|
-
original_len: originalCode.length,
|
|
565
|
-
request_code_len: requestCode.length,
|
|
566
|
-
code_edit_len: codeEdit.length,
|
|
567
|
-
anchor_count: anchorPlan?.anchorCount ?? 0,
|
|
568
|
-
unique_anchor_count: anchorPlan?.uniqueAnchorCount ?? 0
|
|
569
|
-
});
|
|
570
|
-
const startTime = Date.now();
|
|
571
|
-
const client = new import_openai.default({
|
|
572
|
-
apiKey,
|
|
573
|
-
baseURL: `${apiUrl}/v1`,
|
|
574
|
-
timeout,
|
|
575
|
-
maxRetries: config.retryConfig?.maxRetries ?? 3,
|
|
576
|
-
defaultHeaders: {
|
|
577
|
-
"X-Morph-SDK-Version": SDK_VERSION,
|
|
578
|
-
...anchorPlan ? { "X-Morph-Apply-Context": "extralong" } : {}
|
|
579
|
-
}
|
|
580
|
-
});
|
|
581
|
-
try {
|
|
582
|
-
const maxAttempts = anchorPlan?.hasStructuralValidation ? 2 : 1;
|
|
583
|
-
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
584
|
-
const response = await client.chat.completions.create({
|
|
585
|
-
model,
|
|
586
|
-
messages: [{ role: "user", content: message }],
|
|
587
|
-
stream: true
|
|
588
|
-
});
|
|
589
|
-
const completion = await collectCompletion(response);
|
|
590
|
-
if (completion.finishReason === "length") {
|
|
591
|
-
throw new FastApplyContextLengthError(completion.completionId);
|
|
592
|
-
}
|
|
593
|
-
let content = completion.content;
|
|
594
|
-
if (!content) {
|
|
595
|
-
throw new Error("Morph API returned empty response");
|
|
596
|
-
}
|
|
597
|
-
if (anchorPlan) {
|
|
598
|
-
try {
|
|
599
|
-
content = anchorPlan.expand(content);
|
|
600
|
-
} catch (error) {
|
|
601
|
-
if (error instanceof FastApplyAnchorIntegrityError) {
|
|
602
|
-
if (attempt < maxAttempts) {
|
|
603
|
-
logger.warn("FastApply", "anchor_validation_retry", {
|
|
604
|
-
attempt,
|
|
605
|
-
completion_id: completion.completionId
|
|
606
|
-
});
|
|
607
|
-
continue;
|
|
608
|
-
}
|
|
609
|
-
throw new FastApplyAnchorIntegrityError(completion.completionId);
|
|
610
|
-
}
|
|
611
|
-
throw error;
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
const elapsed = Date.now() - startTime;
|
|
615
|
-
logger.debug("FastApply", "http_response", { status: 200, completion_id: completion.completionId, content_len: content.length, latency_ms: elapsed });
|
|
616
|
-
return { content, completionId: completion.completionId };
|
|
617
|
-
}
|
|
618
|
-
throw new FastApplyAnchorIntegrityError();
|
|
619
|
-
} catch (error) {
|
|
620
|
-
const elapsed = Date.now() - startTime;
|
|
621
|
-
const status = error?.status || error?.response?.status;
|
|
622
|
-
logger.error("FastApply", "http_error", {
|
|
623
|
-
status,
|
|
624
|
-
error: error?.message,
|
|
625
|
-
latency_ms: elapsed
|
|
626
|
-
});
|
|
627
|
-
if (status === 401) {
|
|
628
|
-
const err = new Error(
|
|
629
|
-
"Authentication failed: Your Morph API key is invalid or has been revoked. Please visit https://morphllm.com to get a valid API key, then update your MCP configuration."
|
|
630
|
-
);
|
|
631
|
-
err.status = 401;
|
|
632
|
-
throw err;
|
|
633
|
-
}
|
|
634
|
-
if (status === 429) {
|
|
635
|
-
const err = new Error(
|
|
636
|
-
"Rate limited: You've exceeded your Morph API usage limits. Please visit https://morphllm.com to check your plan and purchase additional credits."
|
|
637
|
-
);
|
|
638
|
-
err.status = 429;
|
|
639
|
-
throw err;
|
|
640
|
-
}
|
|
641
|
-
throw error;
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
async function applyEdit(input, config = {}) {
|
|
645
|
-
const filepath = input.filepath || "file";
|
|
646
|
-
try {
|
|
647
|
-
logger.debug("FastApply", "apply_edit_start", { original_len: input.originalCode.length, code_edit_len: input.codeEdit.length });
|
|
648
|
-
const instruction = input.instruction ?? input.instructions ?? "";
|
|
649
|
-
const { content: mergedCode, completionId } = await callMorphAPI(
|
|
650
|
-
input.originalCode,
|
|
651
|
-
input.codeEdit,
|
|
652
|
-
instruction,
|
|
653
|
-
filepath,
|
|
654
|
-
config
|
|
655
|
-
);
|
|
656
|
-
const udiff = config.generateUdiff !== false ? generateUdiff(input.originalCode, mergedCode, filepath) : void 0;
|
|
657
|
-
const changes = countChanges(input.originalCode, mergedCode);
|
|
658
|
-
return {
|
|
659
|
-
success: true,
|
|
660
|
-
mergedCode,
|
|
661
|
-
udiff,
|
|
662
|
-
changes,
|
|
663
|
-
completionId
|
|
664
|
-
};
|
|
665
|
-
} catch (error) {
|
|
666
|
-
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
|
667
|
-
logger.error("FastApply", "apply_edit_error", { error: errorMessage });
|
|
668
|
-
const structuredError = error instanceof FastApplyContextLengthError || error instanceof FastApplyAnchorIntegrityError ? error : void 0;
|
|
669
|
-
return {
|
|
670
|
-
success: false,
|
|
671
|
-
changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
|
|
672
|
-
error: errorMessage,
|
|
673
|
-
errorCode: structuredError?.code,
|
|
674
|
-
completionId: structuredError?.completionId
|
|
675
|
-
};
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
var import_diff, import_openai, DEFAULT_API_URL, DEFAULT_TIMEOUT2, FastApplyContextLengthError;
|
|
679
|
-
var init_apply = __esm({
|
|
680
|
-
"tools/fastapply/apply.ts"() {
|
|
681
|
-
"use strict";
|
|
682
|
-
import_diff = require("diff");
|
|
683
|
-
import_openai = __toESM(require("openai"), 1);
|
|
684
|
-
init_version();
|
|
685
|
-
init_logger();
|
|
686
|
-
init_anchors();
|
|
687
|
-
init_anchors();
|
|
688
|
-
DEFAULT_API_URL = "https://api.morphllm.com";
|
|
689
|
-
DEFAULT_TIMEOUT2 = 6e5;
|
|
690
|
-
FastApplyContextLengthError = class extends Error {
|
|
691
|
-
code = "context_length_exceeded";
|
|
692
|
-
completionId;
|
|
693
|
-
constructor(completionId) {
|
|
694
|
-
super(
|
|
695
|
-
"Fast Apply exhausted its context window before producing the complete file. Retry with a smaller input/update or use sparse anchors for unchanged code."
|
|
696
|
-
);
|
|
697
|
-
this.name = "FastApplyContextLengthError";
|
|
698
|
-
this.completionId = completionId;
|
|
699
|
-
}
|
|
700
|
-
};
|
|
701
|
-
}
|
|
702
|
-
});
|
|
703
|
-
|
|
704
|
-
// tools/warp_grep/agent/config.ts
|
|
705
|
-
var parseEnvTimeout, AGENT_CONFIG, BUILTIN_EXCLUDES, DEFAULT_EXCLUDES, DEFAULT_MODEL;
|
|
706
|
-
var init_config = __esm({
|
|
707
|
-
"tools/warp_grep/agent/config.ts"() {
|
|
708
|
-
"use strict";
|
|
709
|
-
parseEnvTimeout = (envValue, defaultMs) => {
|
|
710
|
-
if (!envValue) return defaultMs;
|
|
711
|
-
const parsed = parseInt(envValue, 10);
|
|
712
|
-
return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;
|
|
713
|
-
};
|
|
714
|
-
AGENT_CONFIG = {
|
|
715
|
-
MAX_TURNS: 6,
|
|
716
|
-
/** Default timeout for model calls. Can be overridden via MORPH_WARP_GREP_TIMEOUT env var (in ms) */
|
|
717
|
-
TIMEOUT_MS: parseEnvTimeout(process.env.MORPH_WARP_GREP_TIMEOUT, 6e4),
|
|
718
|
-
MAX_CONTEXT_CHARS: 321600,
|
|
719
|
-
MAX_OUTPUT_LINES: 200,
|
|
720
|
-
MAX_LIST_RESULTS: 500,
|
|
721
|
-
MAX_READ_LINES: 800,
|
|
722
|
-
MAX_LIST_DEPTH: 3,
|
|
723
|
-
LIST_TIMEOUT_MS: 2e3
|
|
724
|
-
};
|
|
725
|
-
BUILTIN_EXCLUDES = [
|
|
726
|
-
// Version control
|
|
727
|
-
".git",
|
|
728
|
-
".svn",
|
|
729
|
-
".hg",
|
|
730
|
-
".bzr",
|
|
731
|
-
// Dependencies
|
|
732
|
-
"node_modules",
|
|
733
|
-
"bower_components",
|
|
734
|
-
".pnpm",
|
|
735
|
-
".yarn",
|
|
736
|
-
"vendor",
|
|
737
|
-
"packages",
|
|
738
|
-
"Pods",
|
|
739
|
-
".bundle",
|
|
740
|
-
// Python
|
|
741
|
-
"__pycache__",
|
|
742
|
-
".pytest_cache",
|
|
743
|
-
".mypy_cache",
|
|
744
|
-
".ruff_cache",
|
|
745
|
-
".venv",
|
|
746
|
-
"venv",
|
|
747
|
-
".tox",
|
|
748
|
-
".nox",
|
|
749
|
-
".eggs",
|
|
750
|
-
"*.egg-info",
|
|
751
|
-
// Build outputs
|
|
752
|
-
"dist",
|
|
753
|
-
"build",
|
|
754
|
-
"out",
|
|
755
|
-
"output",
|
|
756
|
-
"target",
|
|
757
|
-
"_build",
|
|
758
|
-
".next",
|
|
759
|
-
".nuxt",
|
|
760
|
-
".output",
|
|
761
|
-
".vercel",
|
|
762
|
-
".netlify",
|
|
763
|
-
// Cache directories
|
|
764
|
-
".cache",
|
|
765
|
-
".parcel-cache",
|
|
766
|
-
".turbo",
|
|
767
|
-
".nx",
|
|
768
|
-
".gradle",
|
|
769
|
-
// IDE/Editor
|
|
770
|
-
".idea",
|
|
771
|
-
".vscode",
|
|
772
|
-
".vs",
|
|
773
|
-
// Coverage
|
|
774
|
-
"coverage",
|
|
775
|
-
".coverage",
|
|
776
|
-
"htmlcov",
|
|
777
|
-
".nyc_output",
|
|
778
|
-
// Temporary
|
|
779
|
-
"tmp",
|
|
780
|
-
"temp",
|
|
781
|
-
".tmp",
|
|
782
|
-
".temp",
|
|
783
|
-
// Lock files
|
|
784
|
-
"package-lock.json",
|
|
785
|
-
"yarn.lock",
|
|
786
|
-
"pnpm-lock.yaml",
|
|
787
|
-
"bun.lockb",
|
|
788
|
-
"Cargo.lock",
|
|
789
|
-
"Gemfile.lock",
|
|
790
|
-
"poetry.lock",
|
|
791
|
-
// Binary/minified
|
|
792
|
-
"*.min.js",
|
|
793
|
-
"*.min.css",
|
|
794
|
-
"*.bundle.js",
|
|
795
|
-
"*.wasm",
|
|
796
|
-
"*.so",
|
|
797
|
-
"*.dll",
|
|
798
|
-
"*.pyc",
|
|
799
|
-
"*.map",
|
|
800
|
-
"*.js.map",
|
|
801
|
-
// Hidden directories catch-all
|
|
802
|
-
".*"
|
|
803
|
-
];
|
|
804
|
-
DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || "").split(",").map((s) => s.trim()).filter(Boolean).concat(BUILTIN_EXCLUDES);
|
|
805
|
-
DEFAULT_MODEL = "morph-warp-grep-v2.1";
|
|
806
|
-
}
|
|
807
|
-
});
|
|
808
|
-
|
|
809
|
-
// tools/warp_grep/utils/ripgrep.ts
|
|
810
|
-
function spawnRg(rgBinary, args, opts) {
|
|
811
|
-
return new Promise((resolve2) => {
|
|
812
|
-
const child = (0, import_child_process.spawn)(rgBinary, args, {
|
|
813
|
-
cwd: opts?.cwd,
|
|
814
|
-
env: { ...process.env, ...opts?.env || {} },
|
|
815
|
-
stdio: ["ignore", "pipe", "pipe"]
|
|
816
|
-
});
|
|
817
|
-
let stdout = "";
|
|
818
|
-
let stderr = "";
|
|
819
|
-
child.stdout.on("data", (d) => stdout += d.toString());
|
|
820
|
-
child.stderr.on("data", (d) => stderr += d.toString());
|
|
821
|
-
child.on("close", (code) => {
|
|
822
|
-
resolve2({ stdout, stderr, exitCode: typeof code === "number" ? code : -1 });
|
|
823
|
-
});
|
|
824
|
-
child.on("error", () => {
|
|
825
|
-
resolve2({ stdout: "", stderr: "Failed to spawn ripgrep.", exitCode: -1 });
|
|
826
|
-
});
|
|
827
|
-
});
|
|
828
|
-
}
|
|
829
|
-
function isBinaryFailure(result) {
|
|
830
|
-
if (result.exitCode === -1) return true;
|
|
831
|
-
if (result.stderr.includes("jemalloc") || result.stderr.includes("Unsupported system page size")) return true;
|
|
832
|
-
if (result.exitCode === 134) return true;
|
|
833
|
-
return false;
|
|
834
|
-
}
|
|
835
|
-
async function runRipgrep(args, opts) {
|
|
836
|
-
if (rgPathChecked && resolvedRgPath) {
|
|
837
|
-
return spawnRg(resolvedRgPath, args, opts);
|
|
838
|
-
}
|
|
839
|
-
if (!rgPathChecked) {
|
|
840
|
-
const result = await spawnRg(import_ripgrep.rgPath, args, opts);
|
|
841
|
-
if (!isBinaryFailure(result)) {
|
|
842
|
-
resolvedRgPath = import_ripgrep.rgPath;
|
|
843
|
-
rgPathChecked = true;
|
|
844
|
-
return result;
|
|
845
|
-
}
|
|
846
|
-
const fallbackResult = await spawnRg("rg", args, opts);
|
|
847
|
-
if (!isBinaryFailure(fallbackResult)) {
|
|
848
|
-
resolvedRgPath = "rg";
|
|
849
|
-
rgPathChecked = true;
|
|
850
|
-
return fallbackResult;
|
|
851
|
-
}
|
|
852
|
-
rgPathChecked = true;
|
|
853
|
-
return {
|
|
854
|
-
stdout: "",
|
|
855
|
-
stderr: "Failed to spawn ripgrep. Neither bundled nor system rg is available.",
|
|
856
|
-
exitCode: -1
|
|
857
|
-
};
|
|
858
|
-
}
|
|
859
|
-
return {
|
|
860
|
-
stdout: "",
|
|
861
|
-
stderr: "Failed to spawn ripgrep. Neither bundled nor system rg is available.",
|
|
862
|
-
exitCode: -1
|
|
863
|
-
};
|
|
864
|
-
}
|
|
865
|
-
var import_child_process, import_ripgrep, resolvedRgPath, rgPathChecked;
|
|
866
|
-
var init_ripgrep = __esm({
|
|
867
|
-
"tools/warp_grep/utils/ripgrep.ts"() {
|
|
868
|
-
"use strict";
|
|
869
|
-
import_child_process = require("child_process");
|
|
870
|
-
import_ripgrep = require("@vscode/ripgrep");
|
|
871
|
-
resolvedRgPath = null;
|
|
872
|
-
rgPathChecked = false;
|
|
873
|
-
}
|
|
874
|
-
});
|
|
875
|
-
|
|
876
|
-
// tools/warp_grep/utils/paths.ts
|
|
877
|
-
function resolveUnderRepo(repoRoot, targetPath) {
|
|
878
|
-
const absRoot = import_path5.default.resolve(repoRoot);
|
|
879
|
-
const resolved = import_path5.default.resolve(absRoot, targetPath);
|
|
880
|
-
ensureWithinRepo(absRoot, resolved);
|
|
881
|
-
return resolved;
|
|
882
|
-
}
|
|
883
|
-
function ensureWithinRepo(repoRoot, absTarget) {
|
|
884
|
-
const rel = import_path5.default.relative(import_path5.default.resolve(repoRoot), import_path5.default.resolve(absTarget));
|
|
885
|
-
if (rel.startsWith("..") || import_path5.default.isAbsolute(rel)) {
|
|
886
|
-
throw new Error(`Path outside repository root: ${absTarget}`);
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
function toRepoRelative2(repoRoot, absPath) {
|
|
890
|
-
return import_path5.default.relative(import_path5.default.resolve(repoRoot), import_path5.default.resolve(absPath));
|
|
891
|
-
}
|
|
892
|
-
function isSymlink(p) {
|
|
893
|
-
try {
|
|
894
|
-
const st = import_fs.default.lstatSync(p);
|
|
895
|
-
return st.isSymbolicLink();
|
|
896
|
-
} catch {
|
|
897
|
-
return false;
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
function fixPathRepetition(fullPath) {
|
|
901
|
-
const segments = fullPath.split(import_path5.default.sep).filter(Boolean);
|
|
902
|
-
if (segments.length < 2) return null;
|
|
903
|
-
for (let len = Math.floor(segments.length / 2); len >= 1; len--) {
|
|
904
|
-
for (let i = 0; i <= segments.length - 2 * len; i++) {
|
|
905
|
-
const first = segments.slice(i, i + len);
|
|
906
|
-
const second = segments.slice(i + len, i + 2 * len);
|
|
907
|
-
if (first.every((seg, idx) => seg === second[idx])) {
|
|
908
|
-
const fixed = [...segments.slice(0, i), ...segments.slice(i + len)];
|
|
909
|
-
return import_path5.default.sep + fixed.join(import_path5.default.sep);
|
|
910
|
-
}
|
|
911
|
-
}
|
|
912
|
-
}
|
|
913
|
-
return null;
|
|
914
|
-
}
|
|
915
|
-
function isTextualFile(filePath, maxBytes = 2e6) {
|
|
916
|
-
try {
|
|
917
|
-
const st = import_fs.default.statSync(filePath);
|
|
918
|
-
if (!st.isFile()) return false;
|
|
919
|
-
if (st.size > maxBytes) return false;
|
|
920
|
-
const fd = import_fs.default.openSync(filePath, "r");
|
|
921
|
-
const buf = Buffer.alloc(512);
|
|
922
|
-
const read = import_fs.default.readSync(fd, buf, 0, buf.length, 0);
|
|
923
|
-
import_fs.default.closeSync(fd);
|
|
924
|
-
for (let i = 0; i < read; i++) {
|
|
925
|
-
const c = buf[i];
|
|
926
|
-
if (c === 0) return false;
|
|
927
|
-
}
|
|
928
|
-
return true;
|
|
929
|
-
} catch {
|
|
930
|
-
return false;
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
var import_fs, import_path5;
|
|
934
|
-
var init_paths = __esm({
|
|
935
|
-
"tools/warp_grep/utils/paths.ts"() {
|
|
936
|
-
"use strict";
|
|
937
|
-
import_fs = __toESM(require("fs"), 1);
|
|
938
|
-
import_path5 = __toESM(require("path"), 1);
|
|
939
|
-
}
|
|
940
|
-
});
|
|
941
|
-
|
|
942
|
-
// tools/warp_grep/utils/files.ts
|
|
943
|
-
async function readAllLines(filePath) {
|
|
944
|
-
const content = await import_promises.default.readFile(filePath, "utf8");
|
|
945
|
-
return content.split(/\r?\n/);
|
|
946
|
-
}
|
|
947
|
-
var import_promises;
|
|
948
|
-
var init_files = __esm({
|
|
949
|
-
"tools/warp_grep/utils/files.ts"() {
|
|
950
|
-
"use strict";
|
|
951
|
-
import_promises = __toESM(require("fs/promises"), 1);
|
|
952
|
-
}
|
|
953
|
-
});
|
|
954
|
-
|
|
955
|
-
// tools/warp_grep/providers/local.ts
|
|
956
|
-
var local_exports = {};
|
|
957
|
-
__export(local_exports, {
|
|
958
|
-
LocalRipgrepProvider: () => LocalRipgrepProvider
|
|
959
|
-
});
|
|
960
|
-
function shouldSkip2(name, allowNames) {
|
|
961
|
-
if (allowNames?.has(name)) return false;
|
|
962
|
-
if (SKIP_NAMES2.has(name)) return true;
|
|
963
|
-
if (name.startsWith(".")) return true;
|
|
964
|
-
for (const ext of SKIP_EXTENSIONS2) {
|
|
965
|
-
if (name.endsWith(ext)) return true;
|
|
966
|
-
}
|
|
967
|
-
return false;
|
|
968
|
-
}
|
|
969
|
-
var import_promises2, import_path6, SKIP_NAMES2, SKIP_EXTENSIONS2, LocalRipgrepProvider;
|
|
970
|
-
var init_local = __esm({
|
|
971
|
-
"tools/warp_grep/providers/local.ts"() {
|
|
972
|
-
"use strict";
|
|
973
|
-
import_promises2 = __toESM(require("fs/promises"), 1);
|
|
974
|
-
import_path6 = __toESM(require("path"), 1);
|
|
975
|
-
init_ripgrep();
|
|
976
|
-
init_paths();
|
|
977
|
-
init_files();
|
|
978
|
-
init_config();
|
|
979
|
-
SKIP_NAMES2 = /* @__PURE__ */ new Set([
|
|
980
|
-
// Version control
|
|
981
|
-
".git",
|
|
982
|
-
".svn",
|
|
983
|
-
".hg",
|
|
984
|
-
".bzr",
|
|
985
|
-
// Dependencies
|
|
986
|
-
"node_modules",
|
|
987
|
-
"bower_components",
|
|
988
|
-
".pnpm",
|
|
989
|
-
".yarn",
|
|
990
|
-
"vendor",
|
|
991
|
-
"Pods",
|
|
992
|
-
".bundle",
|
|
993
|
-
// Python
|
|
994
|
-
"__pycache__",
|
|
995
|
-
".pytest_cache",
|
|
996
|
-
".mypy_cache",
|
|
997
|
-
".ruff_cache",
|
|
998
|
-
".venv",
|
|
999
|
-
"venv",
|
|
1000
|
-
".tox",
|
|
1001
|
-
".nox",
|
|
1002
|
-
".eggs",
|
|
1003
|
-
// Build outputs
|
|
1004
|
-
"dist",
|
|
1005
|
-
"build",
|
|
1006
|
-
"out",
|
|
1007
|
-
"output",
|
|
1008
|
-
"target",
|
|
1009
|
-
"_build",
|
|
1010
|
-
".next",
|
|
1011
|
-
".nuxt",
|
|
1012
|
-
".output",
|
|
1013
|
-
".vercel",
|
|
1014
|
-
".netlify",
|
|
1015
|
-
// Cache
|
|
1016
|
-
".cache",
|
|
1017
|
-
".parcel-cache",
|
|
1018
|
-
".turbo",
|
|
1019
|
-
".nx",
|
|
1020
|
-
".gradle",
|
|
1021
|
-
// IDE
|
|
1022
|
-
".idea",
|
|
1023
|
-
".vscode",
|
|
1024
|
-
".vs",
|
|
1025
|
-
// Coverage
|
|
1026
|
-
"coverage",
|
|
1027
|
-
".coverage",
|
|
1028
|
-
"htmlcov",
|
|
1029
|
-
".nyc_output",
|
|
1030
|
-
// Temp
|
|
1031
|
-
"tmp",
|
|
1032
|
-
"temp",
|
|
1033
|
-
".tmp",
|
|
1034
|
-
".temp",
|
|
1035
|
-
// Lock files
|
|
1036
|
-
"package-lock.json",
|
|
1037
|
-
"yarn.lock",
|
|
1038
|
-
"pnpm-lock.yaml",
|
|
1039
|
-
"bun.lockb",
|
|
1040
|
-
"Cargo.lock",
|
|
1041
|
-
"Gemfile.lock",
|
|
1042
|
-
"poetry.lock"
|
|
1043
|
-
]);
|
|
1044
|
-
SKIP_EXTENSIONS2 = /* @__PURE__ */ new Set([
|
|
1045
|
-
".min.js",
|
|
1046
|
-
".min.css",
|
|
1047
|
-
".bundle.js",
|
|
1048
|
-
".wasm",
|
|
1049
|
-
".so",
|
|
1050
|
-
".dll",
|
|
1051
|
-
".pyc",
|
|
1052
|
-
".map",
|
|
1053
|
-
".js.map"
|
|
1054
|
-
]);
|
|
1055
|
-
LocalRipgrepProvider = class {
|
|
1056
|
-
constructor(repoRoot, excludes = DEFAULT_EXCLUDES, options) {
|
|
1057
|
-
this.repoRoot = repoRoot;
|
|
1058
|
-
this.excludes = excludes;
|
|
1059
|
-
if (options?.allowNames?.length) {
|
|
1060
|
-
this.allowNames = new Set(options.allowNames);
|
|
1061
|
-
}
|
|
1062
|
-
}
|
|
1063
|
-
allowNames;
|
|
1064
|
-
async grep(params) {
|
|
1065
|
-
let abs;
|
|
1066
|
-
try {
|
|
1067
|
-
abs = resolveUnderRepo(this.repoRoot, params.path);
|
|
1068
|
-
} catch (err) {
|
|
1069
|
-
return {
|
|
1070
|
-
lines: [],
|
|
1071
|
-
error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`
|
|
1072
|
-
};
|
|
1073
|
-
}
|
|
1074
|
-
const stat = await import_promises2.default.stat(abs).catch(() => null);
|
|
1075
|
-
if (!stat) return { lines: [] };
|
|
1076
|
-
const targetArg = abs === import_path6.default.resolve(this.repoRoot) ? "." : toRepoRelative2(this.repoRoot, abs);
|
|
1077
|
-
const contextLines = params.context_lines !== void 0 ? String(params.context_lines) : "1";
|
|
1078
|
-
const args = [
|
|
1079
|
-
"--no-config",
|
|
1080
|
-
"--no-heading",
|
|
1081
|
-
"--with-filename",
|
|
1082
|
-
"--line-number",
|
|
1083
|
-
"--color=never",
|
|
1084
|
-
"--trim",
|
|
1085
|
-
"--max-columns=400",
|
|
1086
|
-
"-C",
|
|
1087
|
-
contextLines,
|
|
1088
|
-
...params.case_sensitive === false ? ["--ignore-case"] : [],
|
|
1089
|
-
...params.glob ? ["--glob", params.glob] : [],
|
|
1090
|
-
...this.excludes.filter((e) => !this.allowNames?.has(e)).flatMap((e) => ["-g", `!${e}`]),
|
|
1091
|
-
params.pattern,
|
|
1092
|
-
targetArg || "."
|
|
1093
|
-
];
|
|
1094
|
-
const res = await runRipgrep(args, { cwd: this.repoRoot });
|
|
1095
|
-
if (res.exitCode === -1) {
|
|
1096
|
-
return {
|
|
1097
|
-
lines: [],
|
|
1098
|
-
error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required but failed to execute. Please install it:
|
|
1099
|
-
\u2022 macOS: brew install ripgrep
|
|
1100
|
-
\u2022 Ubuntu/Debian: apt install ripgrep
|
|
1101
|
-
\u2022 Windows: choco install ripgrep
|
|
1102
|
-
\u2022 Or visit: https://github.com/BurntSushi/ripgrep#installation
|
|
1103
|
-
Exit code: ${res.exitCode}${res.stderr ? `
|
|
1104
|
-
Details: ${res.stderr}` : ""}`
|
|
1105
|
-
};
|
|
1106
|
-
}
|
|
1107
|
-
if (res.exitCode !== 0 && res.exitCode !== 1) {
|
|
1108
|
-
return {
|
|
1109
|
-
lines: [],
|
|
1110
|
-
error: `[RIPGREP ERROR] grep failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ""}`
|
|
1111
|
-
};
|
|
1112
|
-
}
|
|
1113
|
-
const lines = (res.stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
|
|
1114
|
-
if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {
|
|
1115
|
-
const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);
|
|
1116
|
-
truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);
|
|
1117
|
-
return { lines: truncated };
|
|
1118
|
-
}
|
|
1119
|
-
return { lines };
|
|
1120
|
-
}
|
|
1121
|
-
async read(params) {
|
|
1122
|
-
let abs;
|
|
1123
|
-
try {
|
|
1124
|
-
abs = resolveUnderRepo(this.repoRoot, params.path);
|
|
1125
|
-
} catch (err) {
|
|
1126
|
-
return {
|
|
1127
|
-
lines: [],
|
|
1128
|
-
error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`
|
|
1129
|
-
};
|
|
1130
|
-
}
|
|
1131
|
-
let stat = await import_promises2.default.stat(abs).catch(() => null);
|
|
1132
|
-
if (!stat || !stat.isFile()) {
|
|
1133
|
-
const fixedPath = fixPathRepetition(abs);
|
|
1134
|
-
if (fixedPath) {
|
|
1135
|
-
const fixedStat = await import_promises2.default.stat(fixedPath).catch(() => null);
|
|
1136
|
-
if (fixedStat?.isFile()) {
|
|
1137
|
-
abs = fixedPath;
|
|
1138
|
-
stat = fixedStat;
|
|
1139
|
-
}
|
|
1140
|
-
}
|
|
1141
|
-
}
|
|
1142
|
-
if (!stat || !stat.isFile()) {
|
|
1143
|
-
return {
|
|
1144
|
-
lines: [],
|
|
1145
|
-
error: `[FILE NOT FOUND] You tried to read "${params.path}" but there is no file at this path. Double-check the path exists and is spelled correctly.`
|
|
1146
|
-
};
|
|
1147
|
-
}
|
|
1148
|
-
if (isSymlink(abs)) {
|
|
1149
|
-
return {
|
|
1150
|
-
lines: [],
|
|
1151
|
-
error: `[SYMLINK] You tried to read "${params.path}" but this is a symlink. Try reading the actual file it points to instead.`
|
|
1152
|
-
};
|
|
1153
|
-
}
|
|
1154
|
-
if (!isTextualFile(abs)) {
|
|
1155
|
-
return {
|
|
1156
|
-
lines: [],
|
|
1157
|
-
error: `[UNREADABLE FILE] You tried to read "${params.path}" but this file is either too large or not a text file, so it cannot be read. Try a different file.`
|
|
1158
|
-
};
|
|
1159
|
-
}
|
|
1160
|
-
let lines;
|
|
1161
|
-
try {
|
|
1162
|
-
lines = await readAllLines(abs);
|
|
1163
|
-
} catch (err) {
|
|
1164
|
-
return {
|
|
1165
|
-
lines: [],
|
|
1166
|
-
error: `[READ ERROR] Failed to read "${params.path}": ${err instanceof Error ? err.message : String(err)}`
|
|
1167
|
-
};
|
|
1168
|
-
}
|
|
1169
|
-
const total = lines.length;
|
|
1170
|
-
const rawStart = params.start;
|
|
1171
|
-
const rawEnd = params.end;
|
|
1172
|
-
let s = 1;
|
|
1173
|
-
let e = total;
|
|
1174
|
-
const startValid = rawStart === void 0 || Number.isFinite(rawStart) && rawStart > 0;
|
|
1175
|
-
const endValid = rawEnd === void 0 || Number.isFinite(rawEnd) && rawEnd > 0;
|
|
1176
|
-
if (startValid && endValid) {
|
|
1177
|
-
s = rawStart ?? 1;
|
|
1178
|
-
e = Math.min(rawEnd ?? total, total);
|
|
1179
|
-
if (s > total && total > 0 || s > e) {
|
|
1180
|
-
s = 1;
|
|
1181
|
-
e = total;
|
|
1182
|
-
}
|
|
1183
|
-
}
|
|
1184
|
-
const out = [];
|
|
1185
|
-
for (let i = s; i <= e; i += 1) {
|
|
1186
|
-
const content = lines[i - 1] ?? "";
|
|
1187
|
-
out.push(`${i}|${content}`);
|
|
1188
|
-
}
|
|
1189
|
-
if (out.length > AGENT_CONFIG.MAX_READ_LINES) {
|
|
1190
|
-
const truncated = out.slice(0, AGENT_CONFIG.MAX_READ_LINES);
|
|
1191
|
-
truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${out.length} lines)`);
|
|
1192
|
-
return { lines: truncated };
|
|
1193
|
-
}
|
|
1194
|
-
return { lines: out };
|
|
1195
|
-
}
|
|
1196
|
-
async listDirectory(params) {
|
|
1197
|
-
let abs;
|
|
1198
|
-
try {
|
|
1199
|
-
abs = resolveUnderRepo(this.repoRoot, params.path);
|
|
1200
|
-
} catch {
|
|
1201
|
-
return [];
|
|
1202
|
-
}
|
|
1203
|
-
const stat = await import_promises2.default.stat(abs).catch(() => null);
|
|
1204
|
-
if (!stat || !stat.isDirectory()) {
|
|
1205
|
-
return [];
|
|
1206
|
-
}
|
|
1207
|
-
const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
|
|
1208
|
-
const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
|
|
1209
|
-
const regex = params.pattern ? new RegExp(params.pattern) : null;
|
|
1210
|
-
const repoRoot = this.repoRoot;
|
|
1211
|
-
const allowNames = this.allowNames;
|
|
1212
|
-
const results = [];
|
|
1213
|
-
let timedOut = false;
|
|
1214
|
-
const startTime = Date.now();
|
|
1215
|
-
async function walk(dir, depth) {
|
|
1216
|
-
if (Date.now() - startTime > AGENT_CONFIG.LIST_TIMEOUT_MS) {
|
|
1217
|
-
timedOut = true;
|
|
1218
|
-
return;
|
|
1219
|
-
}
|
|
1220
|
-
if (depth > maxDepth || results.length >= maxResults) return;
|
|
1221
|
-
let entries;
|
|
1222
|
-
try {
|
|
1223
|
-
entries = await import_promises2.default.readdir(dir, { withFileTypes: true });
|
|
1224
|
-
} catch {
|
|
1225
|
-
return;
|
|
1226
|
-
}
|
|
1227
|
-
for (const entry of entries) {
|
|
1228
|
-
if (timedOut || results.length >= maxResults) break;
|
|
1229
|
-
if (shouldSkip2(entry.name, allowNames)) continue;
|
|
1230
|
-
if (regex && !regex.test(entry.name)) continue;
|
|
1231
|
-
const full = import_path6.default.join(dir, entry.name);
|
|
1232
|
-
const isDir = entry.isDirectory();
|
|
1233
|
-
results.push({
|
|
1234
|
-
name: entry.name,
|
|
1235
|
-
path: toRepoRelative2(repoRoot, full),
|
|
1236
|
-
type: isDir ? "dir" : "file",
|
|
1237
|
-
depth
|
|
1238
|
-
});
|
|
1239
|
-
if (isDir) {
|
|
1240
|
-
await walk(full, depth + 1);
|
|
1241
|
-
}
|
|
1242
|
-
}
|
|
1243
|
-
}
|
|
1244
|
-
await walk(abs, 0);
|
|
1245
|
-
return results;
|
|
1246
|
-
}
|
|
1247
|
-
async glob(params) {
|
|
1248
|
-
let abs;
|
|
1249
|
-
try {
|
|
1250
|
-
abs = params.path ? resolveUnderRepo(this.repoRoot, params.path) : this.repoRoot;
|
|
1251
|
-
} catch (err) {
|
|
1252
|
-
return { files: [], searchDir: this.repoRoot, totalFound: 0, error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}` };
|
|
1253
|
-
}
|
|
1254
|
-
const stat = await import_promises2.default.stat(abs).catch(() => null);
|
|
1255
|
-
if (!stat || !stat.isDirectory()) {
|
|
1256
|
-
return { files: [], searchDir: abs, totalFound: 0, error: `[PATH ERROR] Directory not found: ${params.path || "."}` };
|
|
1257
|
-
}
|
|
1258
|
-
const targetArg = abs === import_path6.default.resolve(this.repoRoot) ? "." : toRepoRelative2(this.repoRoot, abs);
|
|
1259
|
-
const args = [
|
|
1260
|
-
"--no-config",
|
|
1261
|
-
"--files",
|
|
1262
|
-
"--color=never",
|
|
1263
|
-
"-g",
|
|
1264
|
-
params.pattern,
|
|
1265
|
-
...this.excludes.filter((e) => !this.allowNames?.has(e)).flatMap((e) => ["-g", `!${e}`]),
|
|
1266
|
-
targetArg || "."
|
|
1267
|
-
];
|
|
1268
|
-
const res = await runRipgrep(args, { cwd: this.repoRoot });
|
|
1269
|
-
if (res.exitCode === -1) {
|
|
1270
|
-
return { files: [], searchDir: abs, totalFound: 0, error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required for glob search.` };
|
|
1271
|
-
}
|
|
1272
|
-
if (res.exitCode !== 0 && res.exitCode !== 1) {
|
|
1273
|
-
return { files: [], searchDir: abs, totalFound: 0, error: `[GLOB ERROR] glob failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ""}` };
|
|
1274
|
-
}
|
|
1275
|
-
const absRoot = import_path6.default.resolve(this.repoRoot);
|
|
1276
|
-
const relFiles = (res.stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
|
|
1277
|
-
const absFiles = relFiles.map((f) => import_path6.default.resolve(absRoot, f));
|
|
1278
|
-
const withMtime = [];
|
|
1279
|
-
for (const f of absFiles) {
|
|
1280
|
-
const s = await import_promises2.default.stat(f).catch(() => null);
|
|
1281
|
-
withMtime.push({ file: f, mtime: s?.mtimeMs ?? 0 });
|
|
1282
|
-
}
|
|
1283
|
-
withMtime.sort((a, b) => b.mtime - a.mtime);
|
|
1284
|
-
const totalFound = withMtime.length;
|
|
1285
|
-
return { files: withMtime.slice(0, 100).map((f) => f.file), searchDir: abs, totalFound };
|
|
1286
|
-
}
|
|
1287
|
-
};
|
|
1288
|
-
}
|
|
1289
|
-
});
|
|
1290
|
-
|
|
1291
|
-
// index.ts
|
|
1292
|
-
var index_exports = {};
|
|
1293
|
-
__export(index_exports, {
|
|
1294
|
-
APIResource: () => APIResource,
|
|
1295
|
-
AnthropicRouter: () => AnthropicRouter,
|
|
1296
|
-
AnthropicToolFactory: () => AnthropicToolFactory,
|
|
1297
|
-
CompactClient: () => CompactClient,
|
|
1298
|
-
FastApplyAnchorIntegrityError: () => FastApplyAnchorIntegrityError,
|
|
1299
|
-
FastApplyClient: () => FastApplyClient,
|
|
1300
|
-
FastApplyContextLengthError: () => FastApplyContextLengthError,
|
|
1301
|
-
GeminiRouter: () => GeminiRouter,
|
|
1302
|
-
LocalRipgrepProvider: () => LocalRipgrepProvider,
|
|
1303
|
-
MorphAPIClient: () => MorphAPIClient,
|
|
1304
|
-
MorphClient: () => MorphClient,
|
|
1305
|
-
OpenAIRouter: () => OpenAIRouter,
|
|
1306
|
-
OpenAIToolFactory: () => OpenAIToolFactory,
|
|
1307
|
-
RawRouter: () => RawRouter,
|
|
1308
|
-
SDK_VERSION: () => SDK_VERSION,
|
|
1309
|
-
VercelToolFactory: () => VercelToolFactory,
|
|
1310
|
-
WarpGrepClient: () => WarpGrepClient,
|
|
1311
|
-
applyEdit: () => applyEdit
|
|
1312
|
-
});
|
|
1313
|
-
module.exports = __toCommonJS(index_exports);
|
|
1314
|
-
init_version();
|
|
1315
|
-
|
|
1316
|
-
// tools/utils/resilience.ts
|
|
1317
|
-
init_version();
|
|
1318
|
-
var DEFAULT_RETRY_CONFIG = {
|
|
1319
|
-
maxRetries: 3,
|
|
1320
|
-
initialDelay: 1e3,
|
|
1321
|
-
maxDelay: 3e4,
|
|
1322
|
-
backoffMultiplier: 2,
|
|
1323
|
-
retryableErrors: ["ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND"]
|
|
1324
|
-
};
|
|
1325
|
-
async function fetchWithRetry(url, options, retryConfig = {}) {
|
|
1326
|
-
const {
|
|
1327
|
-
maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,
|
|
1328
|
-
initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,
|
|
1329
|
-
maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,
|
|
1330
|
-
backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,
|
|
1331
|
-
retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,
|
|
1332
|
-
onRetry
|
|
1333
|
-
} = retryConfig;
|
|
1334
|
-
let lastError = null;
|
|
1335
|
-
let delay = initialDelay;
|
|
1336
|
-
options = { ...options, headers: { "X-Morph-SDK-Version": SDK_VERSION, ...options.headers } };
|
|
1337
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
1338
|
-
try {
|
|
1339
|
-
const response = await fetch(url, options);
|
|
1340
|
-
if (response.status === 429 || response.status === 503) {
|
|
1341
|
-
if (attempt < maxRetries) {
|
|
1342
|
-
const retryAfter = response.headers.get("Retry-After");
|
|
1343
|
-
const waitTime = retryAfter ? parseInt(retryAfter) * 1e3 : Math.min(delay, maxDelay);
|
|
1344
|
-
const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);
|
|
1345
|
-
if (onRetry) {
|
|
1346
|
-
onRetry(attempt + 1, error);
|
|
1347
|
-
}
|
|
1348
|
-
await sleep(waitTime);
|
|
1349
|
-
delay *= backoffMultiplier;
|
|
1350
|
-
continue;
|
|
1351
|
-
}
|
|
1352
|
-
}
|
|
1353
|
-
return response;
|
|
1354
|
-
} catch (error) {
|
|
1355
|
-
lastError = error;
|
|
1356
|
-
const isRetryable = retryableErrors.some(
|
|
1357
|
-
(errType) => lastError?.message?.includes(errType)
|
|
1358
|
-
);
|
|
1359
|
-
if (!isRetryable || attempt === maxRetries) {
|
|
1360
|
-
throw lastError;
|
|
1361
|
-
}
|
|
1362
|
-
const waitTime = Math.min(delay, maxDelay);
|
|
1363
|
-
if (onRetry) {
|
|
1364
|
-
onRetry(attempt + 1, lastError);
|
|
1365
|
-
}
|
|
1366
|
-
await sleep(waitTime);
|
|
1367
|
-
delay *= backoffMultiplier;
|
|
1368
|
-
}
|
|
1369
|
-
}
|
|
1370
|
-
throw lastError || new Error("Max retries exceeded");
|
|
1371
|
-
}
|
|
1372
|
-
async function withTimeout(promise, timeoutMs, errorMessage) {
|
|
1373
|
-
let timeoutId;
|
|
1374
|
-
const timeoutPromise = new Promise((_, reject) => {
|
|
1375
|
-
timeoutId = setTimeout(() => {
|
|
1376
|
-
reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));
|
|
1377
|
-
}, timeoutMs);
|
|
1378
|
-
});
|
|
1379
|
-
try {
|
|
1380
|
-
const result = await Promise.race([promise, timeoutPromise]);
|
|
1381
|
-
clearTimeout(timeoutId);
|
|
1382
|
-
return result;
|
|
1383
|
-
} catch (error) {
|
|
1384
|
-
clearTimeout(timeoutId);
|
|
1385
|
-
throw error;
|
|
1386
|
-
}
|
|
1387
|
-
}
|
|
1388
|
-
function sleep(ms) {
|
|
1389
|
-
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
1390
|
-
}
|
|
1391
|
-
var MorphError = class extends Error {
|
|
1392
|
-
constructor(message, code, statusCode, retryable = false) {
|
|
1393
|
-
super(message);
|
|
1394
|
-
this.code = code;
|
|
1395
|
-
this.statusCode = statusCode;
|
|
1396
|
-
this.retryable = retryable;
|
|
1397
|
-
this.name = "MorphError";
|
|
1398
|
-
}
|
|
1399
|
-
};
|
|
1400
|
-
|
|
1401
|
-
// core/client.ts
|
|
1402
|
-
init_logger();
|
|
1403
|
-
init_version();
|
|
1404
|
-
|
|
1405
|
-
// core/error.ts
|
|
1406
|
-
async function toMorphError(response) {
|
|
1407
|
-
let message = `Morph API request failed (${response.status})`;
|
|
1408
|
-
let code = "api_error";
|
|
1409
|
-
try {
|
|
1410
|
-
const body = await response.json();
|
|
1411
|
-
message = body.error?.message ?? body.message ?? message;
|
|
1412
|
-
code = body.error?.code ?? body.error?.type ?? code;
|
|
1413
|
-
} catch {
|
|
1414
|
-
}
|
|
1415
|
-
if (response.status === 401) code = "authentication_error";
|
|
1416
|
-
if (response.status === 429) code = "rate_limit_exceeded";
|
|
1417
|
-
const retryable = response.status === 429 || response.status === 503;
|
|
1418
|
-
return new MorphError(message, code, response.status, retryable);
|
|
1419
|
-
}
|
|
1420
|
-
|
|
1421
|
-
// core/client.ts
|
|
1422
|
-
var DEFAULT_BASE_URL = "https://api.morphllm.com";
|
|
1423
|
-
var DEFAULT_REPOS_URL = "https://repos.morphllm.com";
|
|
1424
|
-
var DEFAULT_TIMEOUT = 6e4;
|
|
1425
|
-
var env = (name) => typeof process !== "undefined" ? process.env?.[name] : void 0;
|
|
1426
|
-
var stripTrailingSlash = (url) => url.replace(/\/+$/, "");
|
|
1427
|
-
var MorphAPIClient = class {
|
|
1428
|
-
/** Explicit key as provided; resolved against env at request time. */
|
|
1429
|
-
apiKey;
|
|
1430
|
-
baseURL;
|
|
1431
|
-
reposURL;
|
|
1432
|
-
/** Explicit default timeout (ms), if set. The request default is applied lazily so
|
|
1433
|
-
* resources can read an undefined value and supply their own fallback. */
|
|
1434
|
-
timeout;
|
|
1435
|
-
retryConfig;
|
|
1436
|
-
debug;
|
|
1437
|
-
constructor(options = {}) {
|
|
1438
|
-
this.apiKey = options.apiKey;
|
|
1439
|
-
this.baseURL = stripTrailingSlash(options.baseURL ?? DEFAULT_BASE_URL);
|
|
1440
|
-
this.reposURL = stripTrailingSlash(options.reposURL ?? env("MORPH_SEARCH_URL") ?? DEFAULT_REPOS_URL);
|
|
1441
|
-
this.timeout = options.timeout;
|
|
1442
|
-
this.retryConfig = options.retryConfig;
|
|
1443
|
-
this.debug = options.debug ?? false;
|
|
1444
|
-
if (this.debug) logger.enable();
|
|
1445
|
-
}
|
|
1446
|
-
/** The key actually used for requests: explicit, else `MORPH_API_KEY`. */
|
|
1447
|
-
resolveApiKey() {
|
|
1448
|
-
return this.apiKey ?? env("MORPH_API_KEY");
|
|
1449
|
-
}
|
|
1450
|
-
/** Headers shared with tools that bring their own HTTP client (FastApply/WarpGrep via the `openai` package). */
|
|
1451
|
-
defaultHeaders() {
|
|
1452
|
-
return { "X-Morph-SDK-Version": SDK_VERSION };
|
|
1453
|
-
}
|
|
1454
|
-
buildURL(path6, baseURL) {
|
|
1455
|
-
if (/^https?:\/\//i.test(path6)) return path6;
|
|
1456
|
-
const base = stripTrailingSlash(baseURL ?? this.baseURL);
|
|
1457
|
-
return `${base}${path6.startsWith("/") ? "" : "/"}${path6}`;
|
|
1458
|
-
}
|
|
1459
|
-
buildHeaders(apiKey, extra) {
|
|
1460
|
-
return {
|
|
1461
|
-
"Content-Type": "application/json",
|
|
1462
|
-
"X-Morph-SDK-Version": SDK_VERSION,
|
|
1463
|
-
Authorization: `Bearer ${apiKey}`,
|
|
1464
|
-
...extra
|
|
1465
|
-
};
|
|
1466
|
-
}
|
|
1467
|
-
applyQuery(url, query) {
|
|
1468
|
-
if (!query) return url;
|
|
1469
|
-
const params = new URLSearchParams();
|
|
1470
|
-
for (const [key, value] of Object.entries(query)) {
|
|
1471
|
-
if (value !== void 0 && value !== null) params.set(key, String(value));
|
|
1472
|
-
}
|
|
1473
|
-
const qs = params.toString();
|
|
1474
|
-
return qs ? `${url}${url.includes("?") ? "&" : "?"}${qs}` : url;
|
|
1475
|
-
}
|
|
1476
|
-
async request(method, path6, opts = {}) {
|
|
1477
|
-
const apiKey = this.resolveApiKey();
|
|
1478
|
-
if (!apiKey) {
|
|
1479
|
-
throw new MorphError(
|
|
1480
|
-
"Morph API key not found. Set the MORPH_API_KEY environment variable or pass apiKey in config.",
|
|
1481
|
-
"missing_api_key",
|
|
1482
|
-
401
|
|
1483
|
-
);
|
|
1484
|
-
}
|
|
1485
|
-
const url = this.applyQuery(this.buildURL(path6, opts.baseURL), opts.query);
|
|
1486
|
-
const timeout = opts.timeout ?? this.timeout ?? DEFAULT_TIMEOUT;
|
|
1487
|
-
const init = {
|
|
1488
|
-
method,
|
|
1489
|
-
headers: this.buildHeaders(apiKey, opts.headers),
|
|
1490
|
-
...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
|
|
1491
|
-
...opts.signal ? { signal: opts.signal } : {}
|
|
1492
|
-
};
|
|
1493
|
-
logger.debug("MorphAPIClient", "request", { method, url });
|
|
1494
|
-
const response = await withTimeout(
|
|
1495
|
-
fetchWithRetry(url, init, this.retryConfig ?? {}),
|
|
1496
|
-
timeout,
|
|
1497
|
-
`Morph request to ${url} timed out after ${timeout}ms`
|
|
1498
|
-
);
|
|
1499
|
-
if (!response.ok) throw await toMorphError(response);
|
|
1500
|
-
if (opts.stream) return response;
|
|
1501
|
-
if (response.status === 204) return void 0;
|
|
1502
|
-
const text = await response.text();
|
|
1503
|
-
return text ? JSON.parse(text) : void 0;
|
|
1504
|
-
}
|
|
1505
|
-
get(path6, opts) {
|
|
1506
|
-
return this.request("GET", path6, opts);
|
|
1507
|
-
}
|
|
1508
|
-
post(path6, opts) {
|
|
1509
|
-
return this.request("POST", path6, opts);
|
|
1510
|
-
}
|
|
1511
|
-
delete(path6, opts) {
|
|
1512
|
-
return this.request("DELETE", path6, opts);
|
|
1513
|
-
}
|
|
1514
|
-
};
|
|
1515
|
-
|
|
1516
|
-
// client.ts
|
|
1517
|
-
init_logger();
|
|
1518
|
-
|
|
1519
|
-
// tools/fastapply/core.ts
|
|
1520
|
-
var import_path = require("path");
|
|
1521
|
-
init_logger();
|
|
1522
|
-
|
|
1523
|
-
// core/resource.ts
|
|
1524
|
-
var APIResource = class {
|
|
1525
|
-
_client;
|
|
1526
|
-
constructor(client) {
|
|
1527
|
-
this._client = client;
|
|
1528
|
-
}
|
|
1529
|
-
};
|
|
1530
|
-
|
|
1531
|
-
// tools/fastapply/core.ts
|
|
1532
|
-
init_apply();
|
|
1533
|
-
init_apply();
|
|
1534
|
-
var DEFAULT_CONFIG = {
|
|
1535
|
-
morphApiUrl: "https://api.morphllm.com",
|
|
1536
|
-
baseDir: process.cwd(),
|
|
1537
|
-
generateUdiff: true,
|
|
1538
|
-
autoWrite: true,
|
|
1539
|
-
timeout: 6e5,
|
|
1540
|
-
anchorCompaction: true,
|
|
1541
|
-
anchorCompactionThreshold: 128 * 1024,
|
|
1542
|
-
debug: false
|
|
1543
|
-
};
|
|
1544
|
-
var FastApplyClient = class extends APIResource {
|
|
1545
|
-
config;
|
|
1546
|
-
constructor(clientOrConfig = {}) {
|
|
1547
|
-
const isClient = clientOrConfig instanceof MorphAPIClient;
|
|
1548
|
-
super(
|
|
1549
|
-
isClient ? clientOrConfig : new MorphAPIClient({
|
|
1550
|
-
apiKey: clientOrConfig.apiKey,
|
|
1551
|
-
timeout: clientOrConfig.timeout ?? DEFAULT_CONFIG.timeout,
|
|
1552
|
-
retryConfig: clientOrConfig.retryConfig,
|
|
1553
|
-
debug: clientOrConfig.debug
|
|
1554
|
-
})
|
|
1555
|
-
);
|
|
1556
|
-
this.config = {
|
|
1557
|
-
morphApiKey: this._client.resolveApiKey(),
|
|
1558
|
-
morphApiUrl: this._client.baseURL,
|
|
1559
|
-
debug: this._client.debug,
|
|
1560
|
-
timeout: (isClient ? void 0 : clientOrConfig.timeout) ?? DEFAULT_CONFIG.timeout,
|
|
1561
|
-
retryConfig: this._client.retryConfig,
|
|
1562
|
-
generateUdiff: DEFAULT_CONFIG.generateUdiff,
|
|
1563
|
-
autoWrite: DEFAULT_CONFIG.autoWrite
|
|
1564
|
-
};
|
|
1565
|
-
}
|
|
1566
|
-
/**
|
|
1567
|
-
* Execute a file edit operation
|
|
1568
|
-
*
|
|
1569
|
-
* @param input - Edit parameters including filepath, instructions, and code_edit
|
|
1570
|
-
* @param overrides - Optional config overrides for this operation
|
|
1571
|
-
* @returns Edit result with success status and changes
|
|
1572
|
-
*/
|
|
1573
|
-
async execute(input, overrides) {
|
|
1574
|
-
return executeEditFile(input, { ...this.config, ...overrides });
|
|
1575
|
-
}
|
|
1576
|
-
/**
|
|
1577
|
-
* Apply an edit to code directly without file I/O
|
|
1578
|
-
*
|
|
1579
|
-
* Useful for sandbox environments or when you manage your own file system.
|
|
1580
|
-
* Compatible with the earlier OpenAI client API contract.
|
|
1581
|
-
*
|
|
1582
|
-
* @param input - Code and edit parameters
|
|
1583
|
-
* @param overrides - Optional config overrides for this operation
|
|
1584
|
-
* @returns Result with merged code
|
|
1585
|
-
*
|
|
1586
|
-
* @example
|
|
1587
|
-
* ```typescript
|
|
1588
|
-
* const result = await client.applyEdit({
|
|
1589
|
-
* originalCode: 'function hello() { return "world"; }',
|
|
1590
|
-
* codeEdit: 'function hello() { return "universe"; }',
|
|
1591
|
-
* instructions: 'Change return value'
|
|
1592
|
-
* });
|
|
1593
|
-
* console.log(result.mergedCode);
|
|
1594
|
-
* ```
|
|
1595
|
-
*/
|
|
1596
|
-
async applyEdit(input, overrides) {
|
|
1597
|
-
const { applyEdit: applyEdit2 } = await Promise.resolve().then(() => (init_apply(), apply_exports));
|
|
1598
|
-
return applyEdit2(input, { ...this.config, ...overrides });
|
|
1599
|
-
}
|
|
1600
|
-
};
|
|
1601
|
-
async function executeEditFile(input, config = {}) {
|
|
1602
|
-
const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;
|
|
1603
|
-
const fullPath = (0, import_path.resolve)((0, import_path.join)(baseDir, input.target_filepath));
|
|
1604
|
-
logger.debug("FastApply", "execute_start", { target_filepath: input.target_filepath, baseDir, autoWrite: config.autoWrite !== false });
|
|
1605
|
-
const relativePath = (0, import_path.relative)(baseDir, fullPath);
|
|
1606
|
-
if (relativePath.startsWith("..") || fullPath === baseDir) {
|
|
1607
|
-
logger.warn("FastApply", "security_check_failed", { target_filepath: input.target_filepath, relative: relativePath });
|
|
1608
|
-
return {
|
|
1609
|
-
success: false,
|
|
1610
|
-
filepath: input.target_filepath,
|
|
1611
|
-
changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
|
|
1612
|
-
error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`
|
|
1613
|
-
};
|
|
1614
|
-
}
|
|
1615
|
-
logger.debug("FastApply", "security_check", { resolved: fullPath, relative: relativePath });
|
|
1616
|
-
try {
|
|
1617
|
-
const { readFile, writeFile } = await import("fs/promises");
|
|
1618
|
-
const { callMorphAPI: callMorphAPI2, generateUdiff: generateUdiff2, countChanges: countChanges2 } = await Promise.resolve().then(() => (init_apply(), apply_exports));
|
|
1619
|
-
let originalCode = "";
|
|
1620
|
-
let fileExists = true;
|
|
1621
|
-
try {
|
|
1622
|
-
originalCode = await readFile(fullPath, "utf-8");
|
|
1623
|
-
logger.debug("FastApply", "file_read", { path: fullPath, exists: true, size_bytes: originalCode.length });
|
|
1624
|
-
} catch (error) {
|
|
1625
|
-
if (error.code !== "ENOENT") {
|
|
1626
|
-
throw error;
|
|
1627
|
-
}
|
|
1628
|
-
fileExists = false;
|
|
1629
|
-
logger.debug("FastApply", "file_read", { path: fullPath, exists: false });
|
|
1630
|
-
}
|
|
1631
|
-
const instruction = input.instruction ?? input.instructions ?? "";
|
|
1632
|
-
logger.debug("FastApply", "api_call", { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });
|
|
1633
|
-
const { content: mergedCode, completionId } = await callMorphAPI2(originalCode, input.code_edit, instruction, input.target_filepath, config);
|
|
1634
|
-
logger.debug("FastApply", "api_response", { completion_id: completionId, merged_len: mergedCode.length });
|
|
1635
|
-
const udiff = config.generateUdiff !== false ? generateUdiff2(originalCode, mergedCode, input.target_filepath) : void 0;
|
|
1636
|
-
if (config.autoWrite !== false) {
|
|
1637
|
-
await writeFile(fullPath, mergedCode, "utf-8");
|
|
1638
|
-
logger.debug("FastApply", "file_write", { path: fullPath, size_bytes: mergedCode.length });
|
|
1639
|
-
}
|
|
1640
|
-
const changes = countChanges2(originalCode, mergedCode);
|
|
1641
|
-
logger.debug("FastApply", "changes", { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });
|
|
1642
|
-
return {
|
|
1643
|
-
success: true,
|
|
1644
|
-
filepath: input.target_filepath,
|
|
1645
|
-
udiff,
|
|
1646
|
-
changes,
|
|
1647
|
-
completionId
|
|
1648
|
-
};
|
|
1649
|
-
} catch (error) {
|
|
1650
|
-
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
|
1651
|
-
const structuredError = error instanceof FastApplyContextLengthError || error instanceof FastApplyAnchorIntegrityError ? error : void 0;
|
|
1652
|
-
logger.error("FastApply", "execute_error", { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : void 0 });
|
|
1653
|
-
return {
|
|
1654
|
-
success: false,
|
|
1655
|
-
filepath: input.target_filepath,
|
|
1656
|
-
changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
|
|
1657
|
-
error: errorMessage,
|
|
1658
|
-
errorCode: structuredError?.code,
|
|
1659
|
-
completionId: structuredError?.completionId
|
|
1660
|
-
};
|
|
1661
|
-
}
|
|
1662
|
-
}
|
|
1663
|
-
|
|
1664
|
-
// tools/warp_grep/agent/runner.ts
|
|
1665
|
-
init_config();
|
|
1666
|
-
|
|
1667
|
-
// tools/warp_grep/agent/parser.ts
|
|
1668
|
-
function parseReadLines(linesStr) {
|
|
1669
|
-
const ranges = [];
|
|
1670
|
-
for (const rangeStr of linesStr.split(",")) {
|
|
1671
|
-
const trimmed = rangeStr.trim();
|
|
1672
|
-
if (!trimmed) continue;
|
|
1673
|
-
const parts = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
|
|
1674
|
-
if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
|
|
1675
|
-
ranges.push([parts[0], parts[1]]);
|
|
1676
|
-
} else if (Number.isFinite(parts[0])) {
|
|
1677
|
-
ranges.push([parts[0], parts[0]]);
|
|
1678
|
-
}
|
|
1679
|
-
}
|
|
1680
|
-
if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };
|
|
1681
|
-
if (ranges.length > 1) return { lines: ranges };
|
|
1682
|
-
return {};
|
|
1683
|
-
}
|
|
1684
|
-
function parseFinishFiles(filesStr) {
|
|
1685
|
-
const files = [];
|
|
1686
|
-
for (const line of filesStr.trim().split(/\s+/)) {
|
|
1687
|
-
const trimmed = line.trim();
|
|
1688
|
-
if (!trimmed) continue;
|
|
1689
|
-
const searchFrom = /^[A-Za-z]:/.test(trimmed) ? 2 : 0;
|
|
1690
|
-
const colonIdx = trimmed.indexOf(":", searchFrom);
|
|
1691
|
-
if (colonIdx === -1) {
|
|
1692
|
-
files.push({ path: trimmed, lines: "*" });
|
|
1693
|
-
continue;
|
|
1694
|
-
}
|
|
1695
|
-
const filePath = trimmed.slice(0, colonIdx);
|
|
1696
|
-
const rangesPart = trimmed.slice(colonIdx + 1);
|
|
1697
|
-
if (!rangesPart.trim() || rangesPart.trim() === "*") {
|
|
1698
|
-
files.push({ path: filePath, lines: "*" });
|
|
1699
|
-
continue;
|
|
1700
|
-
}
|
|
1701
|
-
const ranges = [];
|
|
1702
|
-
for (const rangeStr of rangesPart.split(",")) {
|
|
1703
|
-
const rt = rangeStr.trim();
|
|
1704
|
-
if (!rt) continue;
|
|
1705
|
-
const parts = rt.split("-").map((v) => parseInt(v.trim(), 10));
|
|
1706
|
-
if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
|
|
1707
|
-
ranges.push([parts[0], parts[1]]);
|
|
1708
|
-
} else if (Number.isFinite(parts[0])) {
|
|
1709
|
-
ranges.push([parts[0], parts[0]]);
|
|
1710
|
-
}
|
|
1711
|
-
}
|
|
1712
|
-
files.push({ path: filePath, lines: ranges.length > 0 ? ranges : "*" });
|
|
1713
|
-
}
|
|
1714
|
-
return files;
|
|
1715
|
-
}
|
|
1716
|
-
function extractPathFromCommand(command) {
|
|
1717
|
-
const tokens = command.trim().split(/\s+/);
|
|
1718
|
-
const pathTokens = tokens.slice(1).filter((t) => !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("\\("));
|
|
1719
|
-
return pathTokens[0] || ".";
|
|
1720
|
-
}
|
|
1721
|
-
|
|
1722
|
-
// tools/warp_grep/agent/tools/grep.ts
|
|
1723
|
-
async function toolGrep(provider, args) {
|
|
1724
|
-
const res = await provider.grep(args);
|
|
1725
|
-
if (res.error) {
|
|
1726
|
-
return { output: res.error };
|
|
1727
|
-
}
|
|
1728
|
-
if (!res.lines.length) {
|
|
1729
|
-
return { output: "no matches" };
|
|
1730
|
-
}
|
|
1731
|
-
return { output: res.lines.join("\n") };
|
|
1732
|
-
}
|
|
1733
|
-
|
|
1734
|
-
// tools/warp_grep/agent/tools/read.ts
|
|
1735
|
-
function isValidRange(start, end) {
|
|
1736
|
-
return typeof start === "number" && typeof end === "number" && Number.isFinite(start) && Number.isFinite(end) && start > 0 && end >= start;
|
|
1737
|
-
}
|
|
1738
|
-
async function toolRead(provider, args) {
|
|
1739
|
-
if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {
|
|
1740
|
-
const validRanges = [];
|
|
1741
|
-
for (const range of args.lines) {
|
|
1742
|
-
if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {
|
|
1743
|
-
validRanges.push([range[0], range[1]]);
|
|
1744
|
-
}
|
|
1745
|
-
}
|
|
1746
|
-
if (validRanges.length === 0) {
|
|
1747
|
-
const res2 = await provider.read({ path: args.path });
|
|
1748
|
-
if (res2.error) return res2.error;
|
|
1749
|
-
if (!res2.lines.length) return "(empty file)";
|
|
1750
|
-
return res2.lines.join("\n");
|
|
1751
|
-
}
|
|
1752
|
-
const chunks = [];
|
|
1753
|
-
for (const [start, end] of validRanges) {
|
|
1754
|
-
const res2 = await provider.read({ path: args.path, start, end });
|
|
1755
|
-
if (res2.error) return res2.error;
|
|
1756
|
-
chunks.push(res2.lines.join("\n"));
|
|
1757
|
-
}
|
|
1758
|
-
if (chunks.every((c) => c === "")) return "(empty file)";
|
|
1759
|
-
return chunks.join("\n...\n");
|
|
1760
|
-
}
|
|
1761
|
-
const res = await provider.read({ path: args.path, start: args.start, end: args.end });
|
|
1762
|
-
if (res.error) {
|
|
1763
|
-
return res.error;
|
|
1764
|
-
}
|
|
1765
|
-
if (!res.lines.length) return "(empty file)";
|
|
1766
|
-
return res.lines.join("\n");
|
|
1767
|
-
}
|
|
1768
|
-
|
|
1769
|
-
// tools/warp_grep/agent/tools/list_directory.ts
|
|
1770
|
-
init_config();
|
|
1771
|
-
var import_path2 = __toESM(require("path"), 1);
|
|
1772
|
-
async function toolListDirectory(provider, args, repoRoot) {
|
|
1773
|
-
const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;
|
|
1774
|
-
const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
|
|
1775
|
-
const entries = await provider.listDirectory({
|
|
1776
|
-
path: args.path,
|
|
1777
|
-
pattern: args.pattern ?? null,
|
|
1778
|
-
maxResults,
|
|
1779
|
-
maxDepth
|
|
1780
|
-
});
|
|
1781
|
-
if (!entries.length) return "empty";
|
|
1782
|
-
if (repoRoot) {
|
|
1783
|
-
const absRoot = repoRoot;
|
|
1784
|
-
const lines = entries.map((e) => import_path2.default.join(absRoot, e.path));
|
|
1785
|
-
return lines.join("\n");
|
|
1786
|
-
}
|
|
1787
|
-
return entries.map((e) => e.path).join("\n");
|
|
1788
|
-
}
|
|
1789
|
-
|
|
1790
|
-
// tools/warp_grep/agent/tools/glob.ts
|
|
1791
|
-
async function toolGlob(provider, args) {
|
|
1792
|
-
const res = await provider.glob(args);
|
|
1793
|
-
if (res.error) {
|
|
1794
|
-
return res.error;
|
|
1795
|
-
}
|
|
1796
|
-
if (!res.files.length) {
|
|
1797
|
-
return "no matches";
|
|
1798
|
-
}
|
|
1799
|
-
const header = `Found ${res.totalFound} file(s) matching "${args.pattern}" within ${res.searchDir}, sorted by modification time (newest first):`;
|
|
1800
|
-
const body = res.files.join("\n");
|
|
1801
|
-
const truncated = res.totalFound > res.files.length ? `
|
|
1802
|
-
[${res.totalFound - res.files.length} files truncated]` : "";
|
|
1803
|
-
return `${header}
|
|
1804
|
-
---
|
|
1805
|
-
${body}
|
|
1806
|
-
---${truncated}`;
|
|
1807
|
-
}
|
|
1808
|
-
|
|
1809
|
-
// tools/warp_grep/agent/tools/finish.ts
|
|
1810
|
-
function isValidRange2(range) {
|
|
1811
|
-
return Array.isArray(range) && range.length >= 2 && typeof range[0] === "number" && typeof range[1] === "number" && Number.isFinite(range[0]) && Number.isFinite(range[1]) && range[0] > 0 && range[1] >= range[0];
|
|
1812
|
-
}
|
|
1813
|
-
function extractValidRanges(lines) {
|
|
1814
|
-
if (!Array.isArray(lines)) return null;
|
|
1815
|
-
const valid = [];
|
|
1816
|
-
for (const range of lines) {
|
|
1817
|
-
if (isValidRange2(range)) {
|
|
1818
|
-
valid.push([range[0], range[1]]);
|
|
1819
|
-
}
|
|
1820
|
-
}
|
|
1821
|
-
return valid.length > 0 ? valid : null;
|
|
1822
|
-
}
|
|
1823
|
-
async function readFinishFiles(repoRoot, files, reader) {
|
|
1824
|
-
const out = [];
|
|
1825
|
-
for (const f of files) {
|
|
1826
|
-
const validRanges = f.lines === "*" ? null : extractValidRanges(f.lines);
|
|
1827
|
-
if (f.lines === "*" || !validRanges) {
|
|
1828
|
-
const lines = await reader(f.path);
|
|
1829
|
-
out.push({ path: f.path, ranges: "*", content: lines.join("\n") });
|
|
1830
|
-
} else {
|
|
1831
|
-
const ranges = mergeRanges(validRanges);
|
|
1832
|
-
const chunks = [];
|
|
1833
|
-
for (let i = 0; i < ranges.length; i++) {
|
|
1834
|
-
const [s, e] = ranges[i];
|
|
1835
|
-
if (i === 0 && s > 1) {
|
|
1836
|
-
chunks.push(`// ... existing code, block starting at line ${s} ...`);
|
|
1837
|
-
} else if (i > 0) {
|
|
1838
|
-
chunks.push(`// ... existing code, block starting at line ${s} ...`);
|
|
1839
|
-
}
|
|
1840
|
-
const lines = await reader(f.path, s, e);
|
|
1841
|
-
chunks.push(lines.join("\n"));
|
|
1842
|
-
}
|
|
1843
|
-
out.push({ path: f.path, ranges, content: chunks.join("\n") });
|
|
1844
|
-
}
|
|
1845
|
-
}
|
|
1846
|
-
return out;
|
|
1847
|
-
}
|
|
1848
|
-
function mergeRanges(ranges) {
|
|
1849
|
-
if (!ranges.length) return [];
|
|
1850
|
-
const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
|
|
1851
|
-
const merged = [];
|
|
1852
|
-
let [cs, ce] = sorted[0];
|
|
1853
|
-
for (let i = 1; i < sorted.length; i++) {
|
|
1854
|
-
const [s, e] = sorted[i];
|
|
1855
|
-
if (s <= ce + 1) {
|
|
1856
|
-
ce = Math.max(ce, e);
|
|
1857
|
-
} else {
|
|
1858
|
-
merged.push([cs, ce]);
|
|
1859
|
-
cs = s;
|
|
1860
|
-
ce = e;
|
|
1861
|
-
}
|
|
1862
|
-
}
|
|
1863
|
-
merged.push([cs, ce]);
|
|
1864
|
-
return merged;
|
|
1865
|
-
}
|
|
1866
|
-
|
|
1867
|
-
// tools/warp_grep/agent/helpers.ts
|
|
1868
|
-
var import_path3 = __toESM(require("path"), 1);
|
|
1869
|
-
init_config();
|
|
1870
|
-
var TRUNCATED_MARKER = "[truncated for context limit]";
|
|
1871
|
-
function getMessageSize(m) {
|
|
1872
|
-
if (m.role === "tool") return m.content.length;
|
|
1873
|
-
if (m.role === "assistant") {
|
|
1874
|
-
let size = typeof m.content === "string" ? m.content.length : 0;
|
|
1875
|
-
if (m.tool_calls) {
|
|
1876
|
-
size += m.tool_calls.reduce((s, tc) => s + tc.function.name.length + tc.function.arguments.length, 0);
|
|
1877
|
-
}
|
|
1878
|
-
return size;
|
|
1879
|
-
}
|
|
1880
|
-
return m.content.length;
|
|
1881
|
-
}
|
|
1882
|
-
function formatTurnMessage(turnsUsed, maxTurns) {
|
|
1883
|
-
const turnsRemaining = maxTurns - turnsUsed;
|
|
1884
|
-
if (turnsRemaining === 1) {
|
|
1885
|
-
return `
|
|
1886
|
-
You 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`;
|
|
1887
|
-
}
|
|
1888
|
-
return `
|
|
1889
|
-
You have used ${turnsUsed} turn${turnsUsed === 1 ? "" : "s"} and have ${turnsRemaining} remaining`;
|
|
1890
|
-
}
|
|
1891
|
-
function calculateContextBudget(messages) {
|
|
1892
|
-
const totalChars = messages.reduce((sum, m) => sum + getMessageSize(m), 0);
|
|
1893
|
-
const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;
|
|
1894
|
-
const percent = Math.floor(totalChars / maxChars * 100);
|
|
1895
|
-
const usedK = Math.floor(totalChars / 1e3);
|
|
1896
|
-
const maxK = Math.floor(maxChars / 1e3);
|
|
1897
|
-
return `<context_budget>${percent}% (${usedK}K/${maxK}K chars)</context_budget>`;
|
|
1898
|
-
}
|
|
1899
|
-
async function buildInitialState(repoRoot, searchTerm, provider, options) {
|
|
1900
|
-
const budget = calculateContextBudget([]);
|
|
1901
|
-
const turnTag = `You have used 0 turns and have ${AGENT_CONFIG.MAX_TURNS} remaining`;
|
|
1902
|
-
const treeDepth = options?.search_type === "node_modules" ? 1 : 2;
|
|
1903
|
-
const absRoot = repoRoot;
|
|
1904
|
-
try {
|
|
1905
|
-
const entries = await provider.listDirectory({
|
|
1906
|
-
path: ".",
|
|
1907
|
-
maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,
|
|
1908
|
-
maxDepth: treeDepth
|
|
1909
|
-
});
|
|
1910
|
-
const lines = [absRoot];
|
|
1911
|
-
for (const e of entries) {
|
|
1912
|
-
lines.push(import_path3.default.join(absRoot, e.path));
|
|
1913
|
-
}
|
|
1914
|
-
return `<repo_structure>
|
|
1915
|
-
${lines.join("\n")}
|
|
1916
|
-
</repo_structure>
|
|
1917
|
-
|
|
1918
|
-
<search_string>
|
|
1919
|
-
${searchTerm}
|
|
1920
|
-
</search_string>
|
|
1921
|
-
${budget}
|
|
1922
|
-
${turnTag}`;
|
|
1923
|
-
} catch {
|
|
1924
|
-
return `<repo_structure>
|
|
1925
|
-
${absRoot}
|
|
1926
|
-
</repo_structure>
|
|
1927
|
-
|
|
1928
|
-
<search_string>
|
|
1929
|
-
${searchTerm}
|
|
1930
|
-
</search_string>
|
|
1931
|
-
${budget}
|
|
1932
|
-
${turnTag}`;
|
|
1933
|
-
}
|
|
1934
|
-
}
|
|
1935
|
-
function enforceContextLimit(messages, maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS) {
|
|
1936
|
-
const getTotalChars = () => messages.reduce((sum, m) => sum + getMessageSize(m), 0);
|
|
1937
|
-
if (getTotalChars() <= maxChars) {
|
|
1938
|
-
return messages;
|
|
1939
|
-
}
|
|
1940
|
-
const truncatableIndices = [];
|
|
1941
|
-
let firstUserSkipped = false;
|
|
1942
|
-
for (let i = 0; i < messages.length; i++) {
|
|
1943
|
-
const m = messages[i];
|
|
1944
|
-
if (m.role === "tool") {
|
|
1945
|
-
truncatableIndices.push(i);
|
|
1946
|
-
} else if (m.role === "user") {
|
|
1947
|
-
if (!firstUserSkipped) {
|
|
1948
|
-
firstUserSkipped = true;
|
|
1949
|
-
continue;
|
|
1950
|
-
}
|
|
1951
|
-
truncatableIndices.push(i);
|
|
1952
|
-
}
|
|
1953
|
-
}
|
|
1954
|
-
for (const idx of truncatableIndices) {
|
|
1955
|
-
if (getTotalChars() <= maxChars) {
|
|
1956
|
-
break;
|
|
1957
|
-
}
|
|
1958
|
-
const m = messages[idx];
|
|
1959
|
-
if (m.role === "tool" && m.content !== TRUNCATED_MARKER) {
|
|
1960
|
-
messages[idx] = { role: "tool", tool_call_id: m.tool_call_id, content: TRUNCATED_MARKER };
|
|
1961
|
-
} else if (m.role === "user" && m.content !== TRUNCATED_MARKER) {
|
|
1962
|
-
messages[idx] = { role: "user", content: TRUNCATED_MARKER };
|
|
1963
|
-
}
|
|
1964
|
-
}
|
|
1965
|
-
return messages;
|
|
1966
|
-
}
|
|
1967
|
-
|
|
1968
|
-
// tools/warp_grep/agent/runner.ts
|
|
1969
|
-
var import_openai2 = __toESM(require("openai"), 1);
|
|
1970
|
-
init_version();
|
|
1971
|
-
var import_path4 = __toESM(require("path"), 1);
|
|
1972
|
-
init_logger();
|
|
1973
|
-
var DEFAULT_API_URL2 = "https://api.morphllm.com";
|
|
1974
|
-
var TOOL_SPECS = [
|
|
1975
|
-
{
|
|
1976
|
-
type: "function",
|
|
1977
|
-
function: {
|
|
1978
|
-
name: "list_directory",
|
|
1979
|
-
description: "Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.",
|
|
1980
|
-
parameters: {
|
|
1981
|
-
type: "object",
|
|
1982
|
-
properties: {
|
|
1983
|
-
command: {
|
|
1984
|
-
type: "string",
|
|
1985
|
-
description: "Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */)."
|
|
1986
|
-
}
|
|
1987
|
-
},
|
|
1988
|
-
required: ["command"]
|
|
1989
|
-
}
|
|
1990
|
-
}
|
|
1991
|
-
},
|
|
1992
|
-
{
|
|
1993
|
-
type: "function",
|
|
1994
|
-
function: {
|
|
1995
|
-
name: "grep_search",
|
|
1996
|
-
description: "Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.",
|
|
1997
|
-
parameters: {
|
|
1998
|
-
type: "object",
|
|
1999
|
-
properties: {
|
|
2000
|
-
pattern: {
|
|
2001
|
-
type: "string",
|
|
2002
|
-
description: "Regex pattern to search for in file contents (e.g. 'class\\s+\\w+Error', 'import|require|from', 'def (get|set|update)_user')."
|
|
2003
|
-
},
|
|
2004
|
-
path: {
|
|
2005
|
-
type: "string",
|
|
2006
|
-
description: "File or directory to search in. Defaults to current working directory."
|
|
2007
|
-
},
|
|
2008
|
-
glob: {
|
|
2009
|
-
type: "string",
|
|
2010
|
-
description: "Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*')."
|
|
2011
|
-
},
|
|
2012
|
-
limit: {
|
|
2013
|
-
type: "integer",
|
|
2014
|
-
description: "Limit output to first N matching lines. Shows all matches if not specified."
|
|
2015
|
-
}
|
|
2016
|
-
},
|
|
2017
|
-
required: ["pattern"]
|
|
2018
|
-
}
|
|
2019
|
-
}
|
|
2020
|
-
},
|
|
2021
|
-
{
|
|
2022
|
-
type: "function",
|
|
2023
|
-
function: {
|
|
2024
|
-
name: "glob",
|
|
2025
|
-
description: "Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.",
|
|
2026
|
-
parameters: {
|
|
2027
|
-
type: "object",
|
|
2028
|
-
properties: {
|
|
2029
|
-
pattern: {
|
|
2030
|
-
type: "string",
|
|
2031
|
-
description: "Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py')."
|
|
2032
|
-
},
|
|
2033
|
-
path: {
|
|
2034
|
-
type: "string",
|
|
2035
|
-
description: "Directory to search in. Defaults to repository root."
|
|
2036
|
-
}
|
|
2037
|
-
},
|
|
2038
|
-
required: ["pattern"]
|
|
2039
|
-
}
|
|
2040
|
-
}
|
|
2041
|
-
},
|
|
2042
|
-
{
|
|
2043
|
-
type: "function",
|
|
2044
|
-
function: {
|
|
2045
|
-
name: "read",
|
|
2046
|
-
description: "Read entire files or specific line ranges using absolute paths.",
|
|
2047
|
-
parameters: {
|
|
2048
|
-
type: "object",
|
|
2049
|
-
properties: {
|
|
2050
|
-
path: {
|
|
2051
|
-
type: "string",
|
|
2052
|
-
description: "File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path)."
|
|
2053
|
-
},
|
|
2054
|
-
lines: {
|
|
2055
|
-
type: "string",
|
|
2056
|
-
description: "Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file."
|
|
2057
|
-
}
|
|
2058
|
-
},
|
|
2059
|
-
required: ["path"]
|
|
2060
|
-
}
|
|
2061
|
-
}
|
|
2062
|
-
},
|
|
2063
|
-
{
|
|
2064
|
-
type: "function",
|
|
2065
|
-
function: {
|
|
2066
|
-
name: "finish",
|
|
2067
|
-
description: "Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.",
|
|
2068
|
-
parameters: {
|
|
2069
|
-
type: "object",
|
|
2070
|
-
properties: {
|
|
2071
|
-
files: {
|
|
2072
|
-
type: "string",
|
|
2073
|
-
description: "One file per line as path:lines (e.g. 'src/auth.py:1-15,25-50\\nsrc/user.py'). Omit line range to include entire file."
|
|
2074
|
-
}
|
|
2075
|
-
},
|
|
2076
|
-
required: ["files"]
|
|
2077
|
-
}
|
|
2078
|
-
}
|
|
2079
|
-
}
|
|
2080
|
-
];
|
|
2081
|
-
async function callModel(messages, model, options = {}) {
|
|
2082
|
-
const baseUrl = options.morphApiUrl || DEFAULT_API_URL2;
|
|
2083
|
-
const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
|
|
2084
|
-
const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
|
|
2085
|
-
const parsedUrl = new URL(baseUrl);
|
|
2086
|
-
const baseURL = parsedUrl.pathname === "/" ? `${baseUrl}/v1` : baseUrl;
|
|
2087
|
-
const client = new import_openai2.default({
|
|
2088
|
-
apiKey,
|
|
2089
|
-
baseURL,
|
|
2090
|
-
maxRetries: 0,
|
|
2091
|
-
timeout: timeoutMs,
|
|
2092
|
-
defaultHeaders: { "X-Morph-SDK-Version": SDK_VERSION }
|
|
2093
|
-
});
|
|
2094
|
-
const MAX_EMPTY_RETRIES = 1;
|
|
2095
|
-
logger.debug("WarpGrep", "model_call", { url: baseURL, model, message_count: messages.length });
|
|
2096
|
-
const callStartTime = Date.now();
|
|
2097
|
-
for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {
|
|
2098
|
-
let data;
|
|
2099
|
-
try {
|
|
2100
|
-
data = await client.chat.completions.create({
|
|
2101
|
-
model,
|
|
2102
|
-
temperature: 0,
|
|
2103
|
-
max_tokens: 2048,
|
|
2104
|
-
messages,
|
|
2105
|
-
tools: TOOL_SPECS,
|
|
2106
|
-
...options.search_type ? { search_type: options.search_type } : {}
|
|
2107
|
-
});
|
|
2108
|
-
} catch (error) {
|
|
2109
|
-
const callLatencyMs = Date.now() - callStartTime;
|
|
2110
|
-
if (error instanceof import_openai2.default.APIError) {
|
|
2111
|
-
logger.error("WarpGrep", "model_call_error", { status: error.status, error: error.message, latency_ms: callLatencyMs });
|
|
2112
|
-
if (error.status === 404) {
|
|
2113
|
-
const defaultMsg = "The endpoint you are trying to call is likely deprecated. Please update with: npm cache clean --force && npx -y @morphllm/morphmcp@latest or visit: https://morphllm.com/mcp";
|
|
2114
|
-
const errorText = error.message?.trim();
|
|
2115
|
-
throw new Error(errorText || defaultMsg);
|
|
2116
|
-
}
|
|
2117
|
-
} else {
|
|
2118
|
-
logger.error("WarpGrep", "model_call_error", { status: void 0, error: error instanceof Error ? error.message : String(error), latency_ms: callLatencyMs });
|
|
2119
|
-
}
|
|
2120
|
-
throw error;
|
|
2121
|
-
}
|
|
2122
|
-
const choice = data?.choices?.[0];
|
|
2123
|
-
const message = choice?.message;
|
|
2124
|
-
if (!message) {
|
|
2125
|
-
if (attempt === MAX_EMPTY_RETRIES) {
|
|
2126
|
-
throw new Error("Invalid response from model: no message in response");
|
|
2127
|
-
}
|
|
2128
|
-
await new Promise((resolve2) => setTimeout(resolve2, 200));
|
|
2129
|
-
continue;
|
|
2130
|
-
}
|
|
2131
|
-
const toolCalls = (message.tool_calls || []).map((tc) => ({
|
|
2132
|
-
id: tc.id,
|
|
2133
|
-
type: "function",
|
|
2134
|
-
function: { name: tc.function.name, arguments: tc.function.arguments }
|
|
2135
|
-
}));
|
|
2136
|
-
if (message.content || toolCalls.length > 0) {
|
|
2137
|
-
logger.debug("WarpGrep", "model_call_complete", { latency_ms: Date.now() - callStartTime, tool_calls_count: toolCalls.length, finish_reason: choice?.finish_reason ?? "unknown" });
|
|
2138
|
-
return { content: message.content ?? null, tool_calls: toolCalls };
|
|
2139
|
-
}
|
|
2140
|
-
if (attempt === MAX_EMPTY_RETRIES) {
|
|
2141
|
-
const finishReason = choice?.finish_reason ?? "unknown";
|
|
2142
|
-
throw new Error(
|
|
2143
|
-
`Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`
|
|
2144
|
-
);
|
|
2145
|
-
}
|
|
2146
|
-
await new Promise((resolve2) => setTimeout(resolve2, 200));
|
|
2147
|
-
}
|
|
2148
|
-
throw new Error("Invalid response from model");
|
|
2149
|
-
}
|
|
2150
|
-
function safeParseJSON(s) {
|
|
2151
|
-
try {
|
|
2152
|
-
return JSON.parse(s);
|
|
2153
|
-
} catch {
|
|
2154
|
-
return {};
|
|
2155
|
-
}
|
|
2156
|
-
}
|
|
2157
|
-
async function executeTool(provider, name, args, repoRoot) {
|
|
2158
|
-
switch (name) {
|
|
2159
|
-
case "grep_search": {
|
|
2160
|
-
const grepArgs = {
|
|
2161
|
-
pattern: args.pattern,
|
|
2162
|
-
path: args.path || "."
|
|
2163
|
-
};
|
|
2164
|
-
if (args.glob) grepArgs.glob = args.glob;
|
|
2165
|
-
if (args.case_sensitive !== void 0) grepArgs.case_sensitive = args.case_sensitive;
|
|
2166
|
-
const result = await toolGrep(provider, grepArgs);
|
|
2167
|
-
let output = result.output;
|
|
2168
|
-
if (args.limit && typeof args.limit === "number") {
|
|
2169
|
-
const lines = output.split("\n");
|
|
2170
|
-
if (lines.length > args.limit) {
|
|
2171
|
-
output = lines.slice(0, args.limit).join("\n") + `
|
|
2172
|
-
... (truncated at ${args.limit} lines)`;
|
|
2173
|
-
}
|
|
2174
|
-
}
|
|
2175
|
-
return output;
|
|
2176
|
-
}
|
|
2177
|
-
case "glob": {
|
|
2178
|
-
return toolGlob(provider, {
|
|
2179
|
-
pattern: args.pattern,
|
|
2180
|
-
path: args.path
|
|
2181
|
-
});
|
|
2182
|
-
}
|
|
2183
|
-
case "list_directory": {
|
|
2184
|
-
const dirPath = extractPathFromCommand(args.command || ".");
|
|
2185
|
-
return toolListDirectory(provider, { path: dirPath }, repoRoot);
|
|
2186
|
-
}
|
|
2187
|
-
case "read": {
|
|
2188
|
-
const readArgs = {
|
|
2189
|
-
path: args.path
|
|
2190
|
-
};
|
|
2191
|
-
if (args.lines && typeof args.lines === "string") {
|
|
2192
|
-
Object.assign(readArgs, parseReadLines(args.lines));
|
|
2193
|
-
}
|
|
2194
|
-
return toolRead(provider, readArgs);
|
|
2195
|
-
}
|
|
2196
|
-
default:
|
|
2197
|
-
return `Unknown tool: ${name}`;
|
|
2198
|
-
}
|
|
2199
|
-
}
|
|
2200
|
-
async function* runWarpGrepStreaming(config) {
|
|
2201
|
-
const totalStart = Date.now();
|
|
2202
|
-
const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
|
|
2203
|
-
const timings = { turns: [], timeout_ms: timeoutMs };
|
|
2204
|
-
const repoRoot = config.repoRoot || process.cwd();
|
|
2205
|
-
const model = config.model || DEFAULT_MODEL;
|
|
2206
|
-
const messages = [];
|
|
2207
|
-
const maxTurns = AGENT_CONFIG.MAX_TURNS;
|
|
2208
|
-
logger.debug("WarpGrep", "session_start", { search_term: config.searchTerm, model, max_turns: maxTurns });
|
|
2209
|
-
const initialStateStart = Date.now();
|
|
2210
|
-
const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });
|
|
2211
|
-
timings.initial_state_ms = Date.now() - initialStateStart;
|
|
2212
|
-
logger.debug("WarpGrep", "initial_state", { system_prompt_len: initialState.length, user_message_len: initialState.length });
|
|
2213
|
-
messages.push({ role: "user", content: initialState });
|
|
2214
|
-
const provider = config.provider;
|
|
2215
|
-
const errors = [];
|
|
2216
|
-
let finishMeta;
|
|
2217
|
-
let terminationReason = "terminated";
|
|
2218
|
-
for (let turn = 1; turn <= maxTurns; turn += 1) {
|
|
2219
|
-
const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
|
|
2220
|
-
logger.debug("WarpGrep", "turn_start", { turn, message_count: messages.length });
|
|
2221
|
-
const beforeChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
|
|
2222
|
-
enforceContextLimit(messages);
|
|
2223
|
-
const afterChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
|
|
2224
|
-
if (afterChars < beforeChars) {
|
|
2225
|
-
logger.debug("WarpGrep", "context_truncated", { before_chars: beforeChars, after_chars: afterChars });
|
|
2226
|
-
}
|
|
2227
|
-
const modelCallStart = Date.now();
|
|
2228
|
-
const response = await callModel(messages, model, {
|
|
2229
|
-
morphApiKey: config.morphApiKey,
|
|
2230
|
-
morphApiUrl: config.morphApiUrl,
|
|
2231
|
-
retryConfig: config.retryConfig,
|
|
2232
|
-
timeout: timeoutMs,
|
|
2233
|
-
search_type: config.search_type
|
|
2234
|
-
}).catch((e) => {
|
|
2235
|
-
const errMsg = e instanceof Error ? e.message : String(e);
|
|
2236
|
-
console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
|
|
2237
|
-
logger.error("WarpGrep", "error", { turn, error: errMsg, phase: "model_call" });
|
|
2238
|
-
errors.push({ message: errMsg });
|
|
2239
|
-
return null;
|
|
2240
|
-
});
|
|
2241
|
-
turnMetrics.morph_api_ms = Date.now() - modelCallStart;
|
|
2242
|
-
if (!response) {
|
|
2243
|
-
timings.turns.push(turnMetrics);
|
|
2244
|
-
break;
|
|
2245
|
-
}
|
|
2246
|
-
const toolCalls = response.tool_calls;
|
|
2247
|
-
logger.debug("WarpGrep", "model_response", { turn, tool_calls: toolCalls.map((tc) => tc.function.name), latency_ms: turnMetrics.morph_api_ms });
|
|
2248
|
-
messages.push({
|
|
2249
|
-
role: "assistant",
|
|
2250
|
-
content: response.content,
|
|
2251
|
-
...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
|
|
2252
|
-
});
|
|
2253
|
-
if (toolCalls.length === 0) {
|
|
2254
|
-
console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || "").slice(0, 500)}`);
|
|
2255
|
-
errors.push({ message: "No tool calls produced by the model." });
|
|
2256
|
-
terminationReason = "terminated";
|
|
2257
|
-
timings.turns.push(turnMetrics);
|
|
2258
|
-
break;
|
|
2259
|
-
}
|
|
2260
|
-
yield {
|
|
2261
|
-
turn,
|
|
2262
|
-
toolCalls: toolCalls.map((tc) => ({
|
|
2263
|
-
name: tc.function.name,
|
|
2264
|
-
arguments: safeParseJSON(tc.function.arguments)
|
|
2265
|
-
}))
|
|
2266
|
-
};
|
|
2267
|
-
const finishCall = toolCalls.find((tc) => tc.function.name === "finish");
|
|
2268
|
-
if (finishCall) {
|
|
2269
|
-
const args = safeParseJSON(finishCall.function.arguments);
|
|
2270
|
-
const filesStr = args.files || "";
|
|
2271
|
-
const files = parseFinishFiles(filesStr);
|
|
2272
|
-
finishMeta = { files };
|
|
2273
|
-
terminationReason = "completed";
|
|
2274
|
-
logger.debug("WarpGrep", "finish", { turns: turn, files: files.map((f) => f.path) });
|
|
2275
|
-
if (files.length === 0) {
|
|
2276
|
-
const payload2 = filesStr || "No relevant code found.";
|
|
2277
|
-
timings.turns.push(turnMetrics);
|
|
2278
|
-
timings.total_ms = Date.now() - totalStart;
|
|
2279
|
-
return {
|
|
2280
|
-
terminationReason: "completed",
|
|
2281
|
-
messages,
|
|
2282
|
-
finish: { payload: payload2, metadata: finishMeta },
|
|
2283
|
-
timings
|
|
2284
|
-
};
|
|
2285
|
-
}
|
|
2286
|
-
timings.turns.push(turnMetrics);
|
|
2287
|
-
break;
|
|
2288
|
-
}
|
|
2289
|
-
const toolExecStart = Date.now();
|
|
2290
|
-
const results = await Promise.all(
|
|
2291
|
-
toolCalls.map(async (tc) => {
|
|
2292
|
-
const args = safeParseJSON(tc.function.arguments);
|
|
2293
|
-
const argsSummary = Object.fromEntries(Object.entries(args).map(([k, v]) => [k, typeof v === "string" && v.length > 100 ? v.slice(0, 100) + "..." : v]));
|
|
2294
|
-
logger.debug("WarpGrep", "tool_exec", { turn, tool: tc.function.name, args_summary: argsSummary });
|
|
2295
|
-
const toolStart = Date.now();
|
|
2296
|
-
const output = await executeTool(provider, tc.function.name, args, repoRoot).catch((err) => String(err));
|
|
2297
|
-
logger.debug("WarpGrep", "tool_result", { turn, tool: tc.function.name, result_len: output.length, latency_ms: Date.now() - toolStart });
|
|
2298
|
-
return { tool_call_id: tc.id, content: output };
|
|
2299
|
-
})
|
|
2300
|
-
);
|
|
2301
|
-
turnMetrics.local_tools_ms = Date.now() - toolExecStart;
|
|
2302
|
-
for (const result of results) {
|
|
2303
|
-
messages.push({ role: "tool", tool_call_id: result.tool_call_id, content: result.content });
|
|
2304
|
-
}
|
|
2305
|
-
const turnMsg = formatTurnMessage(turn, maxTurns);
|
|
2306
|
-
const budget = calculateContextBudget(messages);
|
|
2307
|
-
messages.push({ role: "user", content: turnMsg + "\n" + budget });
|
|
2308
|
-
timings.turns.push(turnMetrics);
|
|
2309
|
-
}
|
|
2310
|
-
if (terminationReason !== "completed" || !finishMeta) {
|
|
2311
|
-
timings.total_ms = Date.now() - totalStart;
|
|
2312
|
-
return { terminationReason, messages, errors, timings };
|
|
2313
|
-
}
|
|
2314
|
-
const parts = ["Relevant context found:"];
|
|
2315
|
-
for (const f of finishMeta.files) {
|
|
2316
|
-
const ranges = f.lines === "*" ? "*" : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(", ") : "*";
|
|
2317
|
-
parts.push(`- ${f.path}: ${ranges}`);
|
|
2318
|
-
}
|
|
2319
|
-
const payload = parts.join("\n");
|
|
2320
|
-
const finishResolutionStart = Date.now();
|
|
2321
|
-
const fileReadErrors = [];
|
|
2322
|
-
const resolved = await readFinishFiles(
|
|
2323
|
-
repoRoot,
|
|
2324
|
-
finishMeta.files,
|
|
2325
|
-
async (p, s, e) => {
|
|
2326
|
-
let resolvedPath = p;
|
|
2327
|
-
if (!p.startsWith(repoRoot)) {
|
|
2328
|
-
const relative2 = p.startsWith("/") ? p.slice(1) : p;
|
|
2329
|
-
resolvedPath = import_path4.default.join(repoRoot, relative2);
|
|
2330
|
-
}
|
|
2331
|
-
try {
|
|
2332
|
-
const rr = await provider.read({ path: resolvedPath, start: s, end: e });
|
|
2333
|
-
return rr.lines.map((l) => {
|
|
2334
|
-
const idx = l.indexOf("|");
|
|
2335
|
-
return idx >= 0 ? l.slice(idx + 1) : l;
|
|
2336
|
-
});
|
|
2337
|
-
} catch (err) {
|
|
2338
|
-
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
2339
|
-
fileReadErrors.push({ path: resolvedPath, error: errorMsg });
|
|
2340
|
-
console.error(`[warp_grep] Failed to read file: ${resolvedPath} - ${errorMsg}`);
|
|
2341
|
-
return [`[couldn't find: ${resolvedPath}]`];
|
|
2342
|
-
}
|
|
2343
|
-
}
|
|
2344
|
-
);
|
|
2345
|
-
timings.finish_resolution_ms = Date.now() - finishResolutionStart;
|
|
2346
|
-
if (fileReadErrors.length > 0) {
|
|
2347
|
-
errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
|
|
2348
|
-
}
|
|
2349
|
-
timings.total_ms = Date.now() - totalStart;
|
|
2350
|
-
return {
|
|
2351
|
-
terminationReason: "completed",
|
|
2352
|
-
messages,
|
|
2353
|
-
finish: { payload, metadata: finishMeta, resolved },
|
|
2354
|
-
timings
|
|
2355
|
-
};
|
|
2356
|
-
}
|
|
2357
|
-
async function runWarpGrep(config) {
|
|
2358
|
-
const gen = runWarpGrepStreaming(config);
|
|
2359
|
-
let result = await gen.next();
|
|
2360
|
-
while (!result.done) {
|
|
2361
|
-
result = await gen.next();
|
|
2362
|
-
}
|
|
2363
|
-
return result.value;
|
|
2364
|
-
}
|
|
2365
|
-
|
|
2366
|
-
// tools/warp_grep/client.ts
|
|
2367
|
-
init_logger();
|
|
2368
|
-
|
|
2369
|
-
// tools/warp_grep/providers/remote.ts
|
|
2370
|
-
init_config();
|
|
2371
|
-
var SKIP_NAMES = /* @__PURE__ */ new Set([
|
|
2372
|
-
// Version control
|
|
2373
|
-
".git",
|
|
2374
|
-
".svn",
|
|
2375
|
-
".hg",
|
|
2376
|
-
".bzr",
|
|
2377
|
-
// Dependencies
|
|
2378
|
-
"node_modules",
|
|
2379
|
-
"bower_components",
|
|
2380
|
-
".pnpm",
|
|
2381
|
-
".yarn",
|
|
2382
|
-
"vendor",
|
|
2383
|
-
"Pods",
|
|
2384
|
-
".bundle",
|
|
2385
|
-
// Python
|
|
2386
|
-
"__pycache__",
|
|
2387
|
-
".pytest_cache",
|
|
2388
|
-
".mypy_cache",
|
|
2389
|
-
".ruff_cache",
|
|
2390
|
-
".venv",
|
|
2391
|
-
"venv",
|
|
2392
|
-
".tox",
|
|
2393
|
-
".nox",
|
|
2394
|
-
".eggs",
|
|
2395
|
-
// Build outputs
|
|
2396
|
-
"dist",
|
|
2397
|
-
"build",
|
|
2398
|
-
"out",
|
|
2399
|
-
"output",
|
|
2400
|
-
"target",
|
|
2401
|
-
"_build",
|
|
2402
|
-
".next",
|
|
2403
|
-
".nuxt",
|
|
2404
|
-
".output",
|
|
2405
|
-
".vercel",
|
|
2406
|
-
".netlify",
|
|
2407
|
-
// Cache
|
|
2408
|
-
".cache",
|
|
2409
|
-
".parcel-cache",
|
|
2410
|
-
".turbo",
|
|
2411
|
-
".nx",
|
|
2412
|
-
".gradle",
|
|
2413
|
-
// IDE
|
|
2414
|
-
".idea",
|
|
2415
|
-
".vscode",
|
|
2416
|
-
".vs",
|
|
2417
|
-
// Coverage
|
|
2418
|
-
"coverage",
|
|
2419
|
-
".coverage",
|
|
2420
|
-
"htmlcov",
|
|
2421
|
-
".nyc_output",
|
|
2422
|
-
// Temp
|
|
2423
|
-
"tmp",
|
|
2424
|
-
"temp",
|
|
2425
|
-
".tmp",
|
|
2426
|
-
".temp",
|
|
2427
|
-
// Lock files
|
|
2428
|
-
"package-lock.json",
|
|
2429
|
-
"yarn.lock",
|
|
2430
|
-
"pnpm-lock.yaml",
|
|
2431
|
-
"bun.lockb",
|
|
2432
|
-
"Cargo.lock",
|
|
2433
|
-
"Gemfile.lock",
|
|
2434
|
-
"poetry.lock"
|
|
2435
|
-
]);
|
|
2436
|
-
var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
2437
|
-
".min.js",
|
|
2438
|
-
".min.css",
|
|
2439
|
-
".bundle.js",
|
|
2440
|
-
".wasm",
|
|
2441
|
-
".so",
|
|
2442
|
-
".dll",
|
|
2443
|
-
".pyc",
|
|
2444
|
-
".map",
|
|
2445
|
-
".js.map"
|
|
2446
|
-
]);
|
|
2447
|
-
function shouldSkip(name) {
|
|
2448
|
-
if (SKIP_NAMES.has(name)) return true;
|
|
2449
|
-
if (name.startsWith(".")) return true;
|
|
2450
|
-
for (const ext of SKIP_EXTENSIONS) {
|
|
2451
|
-
if (name.endsWith(ext)) return true;
|
|
2452
|
-
}
|
|
2453
|
-
return false;
|
|
2454
|
-
}
|
|
2455
|
-
var RemoteCommandsProvider = class {
|
|
2456
|
-
constructor(repoRoot, commands) {
|
|
2457
|
-
this.repoRoot = repoRoot;
|
|
2458
|
-
this.commands = commands;
|
|
2459
|
-
}
|
|
2460
|
-
/**
|
|
2461
|
-
* Run grep command and parse ripgrep output
|
|
2462
|
-
*/
|
|
2463
|
-
async grep(params) {
|
|
2464
|
-
try {
|
|
2465
|
-
const stdout = await this.commands.grep(params.pattern, params.path, params.glob);
|
|
2466
|
-
const lines = (stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
|
|
2467
|
-
if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {
|
|
2468
|
-
const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);
|
|
2469
|
-
truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);
|
|
2470
|
-
return { lines: truncated };
|
|
2471
|
-
}
|
|
2472
|
-
return { lines };
|
|
2473
|
-
} catch (error) {
|
|
2474
|
-
return {
|
|
2475
|
-
lines: [],
|
|
2476
|
-
error: `[GREP ERROR] ${error instanceof Error ? error.message : String(error)}`
|
|
2477
|
-
};
|
|
2478
|
-
}
|
|
2479
|
-
}
|
|
2480
|
-
/**
|
|
2481
|
-
* Read file and add line numbers
|
|
2482
|
-
*/
|
|
2483
|
-
async read(params) {
|
|
2484
|
-
const rawStart = params.start;
|
|
2485
|
-
const rawEnd = params.end;
|
|
2486
|
-
const startValid = rawStart === void 0 || Number.isFinite(rawStart) && rawStart > 0;
|
|
2487
|
-
const endValid = rawEnd === void 0 || Number.isFinite(rawEnd) && rawEnd > 0;
|
|
2488
|
-
const rangeValid = startValid && endValid && (rawStart === void 0 || rawEnd === void 0 || rawStart <= rawEnd);
|
|
2489
|
-
const start = rangeValid && rawStart !== void 0 ? rawStart : 1;
|
|
2490
|
-
const end = rangeValid && rawEnd !== void 0 ? rawEnd : 1e6;
|
|
2491
|
-
try {
|
|
2492
|
-
const stdout = await this.commands.read(params.path, start, end);
|
|
2493
|
-
const contentLines = (stdout || "").split("\n");
|
|
2494
|
-
if (contentLines.length > 0 && contentLines[contentLines.length - 1] === "") {
|
|
2495
|
-
contentLines.pop();
|
|
2496
|
-
}
|
|
2497
|
-
const lines = contentLines.map((content, idx) => `${start + idx}|${content}`);
|
|
2498
|
-
if (lines.length > AGENT_CONFIG.MAX_READ_LINES) {
|
|
2499
|
-
const truncated = lines.slice(0, AGENT_CONFIG.MAX_READ_LINES);
|
|
2500
|
-
truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${lines.length} lines)`);
|
|
2501
|
-
return { lines: truncated };
|
|
2502
|
-
}
|
|
2503
|
-
return { lines };
|
|
2504
|
-
} catch (error) {
|
|
2505
|
-
return {
|
|
2506
|
-
lines: [],
|
|
2507
|
-
error: `[READ ERROR] ${error instanceof Error ? error.message : String(error)}`
|
|
2508
|
-
};
|
|
2509
|
-
}
|
|
2510
|
-
}
|
|
2511
|
-
/**
|
|
2512
|
-
* List directory and parse find output
|
|
2513
|
-
*/
|
|
2514
|
-
async listDirectory(params) {
|
|
2515
|
-
const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
|
|
2516
|
-
const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
|
|
2517
|
-
try {
|
|
2518
|
-
const stdout = await this.commands.listDir(params.path, maxDepth);
|
|
2519
|
-
const paths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
|
|
2520
|
-
const regex = params.pattern ? new RegExp(params.pattern) : null;
|
|
2521
|
-
const entries = [];
|
|
2522
|
-
for (const fullPath of paths) {
|
|
2523
|
-
if (fullPath === params.path || fullPath === this.repoRoot) continue;
|
|
2524
|
-
const name = fullPath.split("/").pop() || "";
|
|
2525
|
-
if (shouldSkip(name)) continue;
|
|
2526
|
-
if (regex && !regex.test(name)) continue;
|
|
2527
|
-
let relativePath = fullPath;
|
|
2528
|
-
if (fullPath.startsWith(this.repoRoot)) {
|
|
2529
|
-
relativePath = fullPath.slice(this.repoRoot.length).replace(/^\//, "");
|
|
2530
|
-
}
|
|
2531
|
-
const depth = relativePath.split("/").filter(Boolean).length - 1;
|
|
2532
|
-
const hasExtension = name.includes(".") && !name.startsWith(".");
|
|
2533
|
-
const type = hasExtension ? "file" : "dir";
|
|
2534
|
-
entries.push({
|
|
2535
|
-
name,
|
|
2536
|
-
path: relativePath,
|
|
2537
|
-
type,
|
|
2538
|
-
depth: Math.max(0, depth)
|
|
2539
|
-
});
|
|
2540
|
-
if (entries.length >= maxResults) break;
|
|
2541
|
-
}
|
|
2542
|
-
return entries;
|
|
2543
|
-
} catch (error) {
|
|
2544
|
-
return [];
|
|
2545
|
-
}
|
|
2546
|
-
}
|
|
2547
|
-
/**
|
|
2548
|
-
* Glob search - finds files matching a pattern.
|
|
2549
|
-
* Falls back to a grep --files approach via the listDir command.
|
|
2550
|
-
*/
|
|
2551
|
-
async glob(params) {
|
|
2552
|
-
const searchPath = params.path || this.repoRoot;
|
|
2553
|
-
try {
|
|
2554
|
-
const stdout = await this.commands.listDir(searchPath, 10);
|
|
2555
|
-
const allPaths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
|
|
2556
|
-
const globToRegex = (glob) => {
|
|
2557
|
-
const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
2558
|
-
return new RegExp(escaped);
|
|
2559
|
-
};
|
|
2560
|
-
const regex = globToRegex(params.pattern);
|
|
2561
|
-
const matched = allPaths.filter((p) => {
|
|
2562
|
-
const name = p.split("/").pop() || "";
|
|
2563
|
-
return regex.test(name) && !shouldSkip(name);
|
|
2564
|
-
});
|
|
2565
|
-
const totalFound = matched.length;
|
|
2566
|
-
return { files: matched.slice(0, 100), searchDir: searchPath, totalFound };
|
|
2567
|
-
} catch (error) {
|
|
2568
|
-
return {
|
|
2569
|
-
files: [],
|
|
2570
|
-
searchDir: searchPath,
|
|
2571
|
-
totalFound: 0,
|
|
2572
|
-
error: `[GLOB ERROR] ${error instanceof Error ? error.message : String(error)}`
|
|
2573
|
-
};
|
|
2574
|
-
}
|
|
2575
|
-
}
|
|
2576
|
-
};
|
|
2577
|
-
|
|
2578
|
-
// tools/warp_grep/providers/code_storage_http.ts
|
|
2579
|
-
var MODEL_REPO_ROOT = /^\/?home\/ubuntu\/repo(?:\/|$)/;
|
|
2580
|
-
function toRepoRelative(path6) {
|
|
2581
|
-
if (!path6) return path6;
|
|
2582
|
-
const stripped = path6.replace(MODEL_REPO_ROOT, "").replace(/^\.?\/+/, "");
|
|
2583
|
-
return stripped || ".";
|
|
2584
|
-
}
|
|
2585
|
-
async function post(url, body, op, apiKey) {
|
|
2586
|
-
const res = await fetch(url, {
|
|
2587
|
-
method: "POST",
|
|
2588
|
-
headers: {
|
|
2589
|
-
"Content-Type": "application/json",
|
|
2590
|
-
...apiKey ? { Authorization: `Bearer ${apiKey}` } : {}
|
|
2591
|
-
},
|
|
2592
|
-
body: JSON.stringify(body)
|
|
2593
|
-
});
|
|
2594
|
-
if (!res.ok) {
|
|
2595
|
-
const text = await res.text().catch(() => res.statusText);
|
|
2596
|
-
try {
|
|
2597
|
-
const parsed = JSON.parse(text);
|
|
2598
|
-
if (parsed.error) return `Error: ${parsed.error}`;
|
|
2599
|
-
} catch {
|
|
2600
|
-
}
|
|
2601
|
-
return `Error: ${op} failed (${res.status}): ${text}`;
|
|
2602
|
-
}
|
|
2603
|
-
const data = await res.json();
|
|
2604
|
-
if (data.error) throw new Error(data.error);
|
|
2605
|
-
return data.stdout;
|
|
2606
|
-
}
|
|
2607
|
-
function createCodeStorageHttpCommands(config) {
|
|
2608
|
-
const { baseUrl, repoId, branch, apiKey } = config;
|
|
2609
|
-
const encodedRepoId = encodeURIComponent(repoId);
|
|
2610
|
-
return {
|
|
2611
|
-
grep: (pattern, path6, glob) => post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path: toRepoRelative(path6), glob, branch }, "grep", apiKey),
|
|
2612
|
-
read: (path6, start, end) => post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path: toRepoRelative(path6), start, end, branch }, "read", apiKey),
|
|
2613
|
-
listDir: (path6, maxDepth) => post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path: toRepoRelative(path6), maxDepth, branch }, "list", apiKey)
|
|
2614
|
-
};
|
|
2615
|
-
}
|
|
2616
|
-
|
|
2617
|
-
// tools/warp_grep/utils/github.ts
|
|
2618
|
-
function parseGitHubUrl(input) {
|
|
2619
|
-
input = input.trim();
|
|
2620
|
-
const urlPattern = /^(?:https?:\/\/)?github\.com\/([^\/]+)\/([^\/\?\#]+)/;
|
|
2621
|
-
const match = input.match(urlPattern);
|
|
2622
|
-
if (match) {
|
|
2623
|
-
return { owner: match[1], repo: match[2].replace(/\.git$/, "") };
|
|
2624
|
-
}
|
|
2625
|
-
const shortPattern = /^([^\/]+)\/([^\/]+)$/;
|
|
2626
|
-
const shortMatch = input.match(shortPattern);
|
|
2627
|
-
if (shortMatch && !shortMatch[1].includes(".")) {
|
|
2628
|
-
return { owner: shortMatch[1], repo: shortMatch[2].replace(/\.git$/, "") };
|
|
2629
|
-
}
|
|
2630
|
-
throw new Error(
|
|
2631
|
-
`Invalid GitHub URL or shorthand: "${input}". Expected "owner/repo" or "https://github.com/owner/repo"`
|
|
2632
|
-
);
|
|
2633
|
-
}
|
|
2634
|
-
|
|
2635
|
-
// tools/compact/core.ts
|
|
2636
|
-
var DEFAULT_API_URL3 = "https://api.morphllm.com";
|
|
2637
|
-
var DEFAULT_TIMEOUT3 = 12e4;
|
|
2638
|
-
function resolveClient(clientOrConfig) {
|
|
2639
|
-
if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
|
|
2640
|
-
return new MorphAPIClient({
|
|
2641
|
-
apiKey: clientOrConfig.morphApiKey,
|
|
2642
|
-
baseURL: clientOrConfig.morphApiUrl ?? DEFAULT_API_URL3,
|
|
2643
|
-
timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT3,
|
|
2644
|
-
retryConfig: clientOrConfig.retryConfig,
|
|
2645
|
-
debug: clientOrConfig.debug
|
|
2646
|
-
});
|
|
2647
|
-
}
|
|
2648
|
-
var CompactClient = class extends APIResource {
|
|
2649
|
-
/** Resolved URL/timeout, exposed for backwards-compatible introspection. */
|
|
2650
|
-
config;
|
|
2651
|
-
constructor(clientOrConfig = {}) {
|
|
2652
|
-
super(resolveClient(clientOrConfig));
|
|
2653
|
-
const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
|
|
2654
|
-
this.config = {
|
|
2655
|
-
morphApiUrl: this._client.baseURL,
|
|
2656
|
-
timeout: cfg.timeout ?? DEFAULT_TIMEOUT3,
|
|
2657
|
-
debug: cfg.debug ?? false
|
|
2658
|
-
};
|
|
2659
|
-
}
|
|
2660
|
-
/**
|
|
2661
|
-
* Compact messages or text via /v1/compact.
|
|
2662
|
-
* Returns per-message `compacted_line_ranges` showing which lines were removed.
|
|
2663
|
-
*
|
|
2664
|
-
* @example
|
|
2665
|
-
* ```typescript
|
|
2666
|
-
* const client = new CompactClient({ morphApiKey: 'sk-...' });
|
|
2667
|
-
* const result = await client.compact({
|
|
2668
|
-
* input: codeFile,
|
|
2669
|
-
* query: "authentication",
|
|
2670
|
-
* compressionRatio: 0.5,
|
|
2671
|
-
* });
|
|
2672
|
-
* console.log(result.output);
|
|
2673
|
-
* ```
|
|
2674
|
-
*/
|
|
2675
|
-
async compact(input) {
|
|
2676
|
-
const body = {
|
|
2677
|
-
compression_ratio: input.compressionRatio ?? 0.5,
|
|
2678
|
-
preserve_recent: input.preserveRecent ?? 2,
|
|
2679
|
-
model: input.model ?? "morph-compactor",
|
|
2680
|
-
include_line_ranges: input.includeLineRanges ?? true,
|
|
2681
|
-
include_markers: input.includeMarkers ?? true
|
|
2682
|
-
};
|
|
2683
|
-
if (input.query !== void 0) body.query = input.query;
|
|
2684
|
-
if (input.messages) body.messages = input.messages;
|
|
2685
|
-
else if (typeof input.input === "string") body.input = input.input;
|
|
2686
|
-
else if (Array.isArray(input.input)) body.messages = input.input;
|
|
2687
|
-
else throw new Error("Either 'input' or 'messages' must be provided");
|
|
2688
|
-
try {
|
|
2689
|
-
return await this._client.post("/v1/compact", { body, timeout: this.config.timeout });
|
|
2690
|
-
} catch (err) {
|
|
2691
|
-
if (err instanceof MorphError) {
|
|
2692
|
-
throw new Error(`Compact API error ${err.statusCode}: ${err.message}`);
|
|
2693
|
-
}
|
|
2694
|
-
throw err;
|
|
2695
|
-
}
|
|
2696
|
-
}
|
|
2697
|
-
};
|
|
2698
|
-
|
|
2699
|
-
// tools/compact/utils.ts
|
|
2700
|
-
async function compactFileContexts(files, query, apiKey, apiUrl, maxTokens = 1e4, maxConcurrency = 3) {
|
|
2701
|
-
const totalLength = files.reduce((sum, file) => sum + file.content.length, 0);
|
|
2702
|
-
const estimatedTokens = totalLength / 3;
|
|
2703
|
-
if (estimatedTokens <= maxTokens) {
|
|
2704
|
-
return files;
|
|
2705
|
-
}
|
|
2706
|
-
let compressionRatio = maxTokens / estimatedTokens;
|
|
2707
|
-
compressionRatio = Math.max(0.3, Math.min(0.99, compressionRatio));
|
|
2708
|
-
const client = new CompactClient({
|
|
2709
|
-
morphApiKey: apiKey,
|
|
2710
|
-
morphApiUrl: apiUrl
|
|
2711
|
-
});
|
|
2712
|
-
const results = [];
|
|
2713
|
-
const inProgress = /* @__PURE__ */ new Set();
|
|
2714
|
-
for (const file of files) {
|
|
2715
|
-
if (file.content.length < 500) {
|
|
2716
|
-
results.push({ path: file.path, content: file.content });
|
|
2717
|
-
continue;
|
|
2718
|
-
}
|
|
2719
|
-
const task = async () => {
|
|
2720
|
-
try {
|
|
2721
|
-
const result = await client.compact({
|
|
2722
|
-
input: file.content,
|
|
2723
|
-
query,
|
|
2724
|
-
compressionRatio,
|
|
2725
|
-
preserveRecent: 0
|
|
2726
|
-
});
|
|
2727
|
-
results.push({ path: file.path, content: result.output });
|
|
2728
|
-
} catch (error) {
|
|
2729
|
-
console.error(`[compactFileContexts] Failed to compact file ${file.path}:`, error);
|
|
2730
|
-
results.push({ path: file.path, content: file.content });
|
|
2731
|
-
}
|
|
2732
|
-
};
|
|
2733
|
-
const promise = task().finally(() => inProgress.delete(promise));
|
|
2734
|
-
inProgress.add(promise);
|
|
2735
|
-
if (inProgress.size >= maxConcurrency) {
|
|
2736
|
-
await Promise.race(inProgress);
|
|
2737
|
-
}
|
|
2738
|
-
}
|
|
2739
|
-
await Promise.all(inProgress);
|
|
2740
|
-
const orderMap = new Map(files.map((f, i) => [f.path, i]));
|
|
2741
|
-
return results.sort((a, b) => (orderMap.get(a.path) ?? 0) - (orderMap.get(b.path) ?? 0));
|
|
2742
|
-
}
|
|
2743
|
-
|
|
2744
|
-
// tools/warp_grep/client.ts
|
|
2745
|
-
var DEFAULT_CODE_SEARCH_URL = "https://api.morphllm.com";
|
|
2746
|
-
async function getLocalProvider(repoRoot, excludes, allowNames) {
|
|
2747
|
-
const { LocalRipgrepProvider: LocalRipgrepProvider2 } = await Promise.resolve().then(() => (init_local(), local_exports));
|
|
2748
|
-
const opts = allowNames?.length ? { allowNames } : void 0;
|
|
2749
|
-
return new LocalRipgrepProvider2(repoRoot, excludes, opts);
|
|
2750
|
-
}
|
|
2751
|
-
var WarpGrepClient = class extends APIResource {
|
|
2752
|
-
config;
|
|
2753
|
-
constructor(clientOrConfig = {}) {
|
|
2754
|
-
const isClient = clientOrConfig instanceof MorphAPIClient;
|
|
2755
|
-
super(
|
|
2756
|
-
isClient ? clientOrConfig : new MorphAPIClient({
|
|
2757
|
-
apiKey: clientOrConfig.morphApiKey,
|
|
2758
|
-
baseURL: clientOrConfig.morphApiUrl,
|
|
2759
|
-
timeout: clientOrConfig.timeout,
|
|
2760
|
-
retryConfig: clientOrConfig.retryConfig,
|
|
2761
|
-
debug: clientOrConfig.debug
|
|
2762
|
-
})
|
|
2763
|
-
);
|
|
2764
|
-
const cfg = isClient ? {} : clientOrConfig;
|
|
2765
|
-
this.config = {
|
|
2766
|
-
...cfg,
|
|
2767
|
-
morphApiKey: this._client.resolveApiKey(),
|
|
2768
|
-
morphApiUrl: this._client.baseURL,
|
|
2769
|
-
timeout: this._client.timeout,
|
|
2770
|
-
retryConfig: this._client.retryConfig,
|
|
2771
|
-
debug: this._client.debug
|
|
2772
|
-
};
|
|
2773
|
-
}
|
|
2774
|
-
execute(input) {
|
|
2775
|
-
const toolConfig = {
|
|
2776
|
-
repoRoot: input.repoRoot,
|
|
2777
|
-
remoteCommands: input.remoteCommands,
|
|
2778
|
-
provider: input.provider,
|
|
2779
|
-
excludes: input.excludes,
|
|
2780
|
-
includes: input.includes,
|
|
2781
|
-
debug: input.debug ?? this.config.debug,
|
|
2782
|
-
morphApiKey: this.config.morphApiKey,
|
|
2783
|
-
morphApiUrl: this.config.morphApiUrl,
|
|
2784
|
-
retryConfig: this.config.retryConfig,
|
|
2785
|
-
timeout: this.config.timeout,
|
|
2786
|
-
search_type: input.search_type
|
|
2787
|
-
};
|
|
2788
|
-
if (input.streamSteps) {
|
|
2789
|
-
return executeToolCallStreaming({ search_term: input.searchTerm }, toolConfig);
|
|
2790
|
-
}
|
|
2791
|
-
return executeToolCall({ search_term: input.searchTerm }, toolConfig);
|
|
2792
|
-
}
|
|
2793
|
-
searchGitHub(input) {
|
|
2794
|
-
if (input.streamSteps) {
|
|
2795
|
-
return this._searchGitHubStreaming(input);
|
|
2796
|
-
}
|
|
2797
|
-
return this._searchGitHubAsync(input);
|
|
2798
|
-
}
|
|
2799
|
-
/**
|
|
2800
|
-
* Read a single file from a public GitHub repository
|
|
2801
|
-
*
|
|
2802
|
-
* @example
|
|
2803
|
-
* ```typescript
|
|
2804
|
-
* const result = await client.readGitHubFile({
|
|
2805
|
-
* github: 'vercel/next.js',
|
|
2806
|
-
* path: 'src/server/app-render/index.tsx',
|
|
2807
|
-
* startLine: 1,
|
|
2808
|
-
* endLine: 50,
|
|
2809
|
-
* });
|
|
2810
|
-
* if (result.success) console.log(result.content);
|
|
2811
|
-
* ```
|
|
2812
|
-
*/
|
|
2813
|
-
async readGitHubFile(input) {
|
|
2814
|
-
return executeGitHubReadFile(input, { timeout: this.config.timeout });
|
|
2815
|
-
}
|
|
2816
|
-
async _resolveGitHubRepo(input) {
|
|
2817
|
-
const { owner, repo } = parseGitHubUrl(input.github);
|
|
2818
|
-
const baseUrl = this.config.codeSearchUrl || DEFAULT_CODE_SEARCH_URL;
|
|
2819
|
-
logger.debug("WarpGrep", "github_resolve", { owner_repo: `${owner}/${repo}`, branch: input.branch });
|
|
2820
|
-
const resolveStart = Date.now();
|
|
2821
|
-
const importRes = await fetch(`${baseUrl}/api/code-search/get-or-create?url=${encodeURIComponent(`${owner}/${repo}`)}`, {
|
|
2822
|
-
headers: this.config.morphApiKey ? { Authorization: `Bearer ${this.config.morphApiKey}` } : void 0
|
|
2823
|
-
});
|
|
2824
|
-
if (!importRes.ok) {
|
|
2825
|
-
const text = await importRes.text().catch(() => importRes.statusText);
|
|
2826
|
-
logger.error("WarpGrep", "github_resolve_failed", { owner_repo: `${owner}/${repo}`, status: importRes.status, error: text });
|
|
2827
|
-
throw new Error(`Failed to import repo ${owner}/${repo}: ${text}`);
|
|
2828
|
-
}
|
|
2829
|
-
const { repoId, defaultBranch } = await importRes.json();
|
|
2830
|
-
logger.debug("WarpGrep", "github_repo_fetched", { repo_id: repoId, default_branch: defaultBranch, latency_ms: Date.now() - resolveStart });
|
|
2831
|
-
return {
|
|
2832
|
-
repo,
|
|
2833
|
-
remoteCommands: createCodeStorageHttpCommands({
|
|
2834
|
-
baseUrl,
|
|
2835
|
-
repoId,
|
|
2836
|
-
branch: input.branch || defaultBranch,
|
|
2837
|
-
apiKey: this.config.morphApiKey
|
|
2838
|
-
})
|
|
2839
|
-
};
|
|
2840
|
-
}
|
|
2841
|
-
async _searchGitHubAsync(input) {
|
|
2842
|
-
try {
|
|
2843
|
-
const { remoteCommands } = await this._resolveGitHubRepo(input);
|
|
2844
|
-
return this.execute({
|
|
2845
|
-
searchTerm: input.searchTerm,
|
|
2846
|
-
repoRoot: ".",
|
|
2847
|
-
remoteCommands
|
|
2848
|
-
});
|
|
2849
|
-
} catch (error) {
|
|
2850
|
-
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
2851
|
-
}
|
|
2852
|
-
}
|
|
2853
|
-
async *_searchGitHubStreaming(input) {
|
|
2854
|
-
let remoteCommands;
|
|
2855
|
-
try {
|
|
2856
|
-
({ remoteCommands } = await this._resolveGitHubRepo(input));
|
|
2857
|
-
} catch (error) {
|
|
2858
|
-
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
2859
|
-
}
|
|
2860
|
-
const generator = this.execute({
|
|
2861
|
-
searchTerm: input.searchTerm,
|
|
2862
|
-
repoRoot: ".",
|
|
2863
|
-
remoteCommands,
|
|
2864
|
-
streamSteps: true
|
|
2865
|
-
});
|
|
2866
|
-
let result;
|
|
2867
|
-
for (; ; ) {
|
|
2868
|
-
const { value, done } = await generator.next();
|
|
2869
|
-
if (done) {
|
|
2870
|
-
result = value;
|
|
2871
|
-
break;
|
|
2872
|
-
}
|
|
2873
|
-
yield value;
|
|
2874
|
-
}
|
|
2875
|
-
return result;
|
|
2876
|
-
}
|
|
2877
|
-
};
|
|
2878
|
-
async function executeToolCall(input, config) {
|
|
2879
|
-
const parsed = typeof input === "string" ? JSON.parse(input) : input;
|
|
2880
|
-
const allowNames = config.search_type === "node_modules" ? ["node_modules"] : void 0;
|
|
2881
|
-
const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);
|
|
2882
|
-
const result = await runWarpGrep({
|
|
2883
|
-
searchTerm: parsed.search_term,
|
|
2884
|
-
repoRoot: config.repoRoot,
|
|
2885
|
-
provider,
|
|
2886
|
-
excludes: config.excludes,
|
|
2887
|
-
includes: config.includes,
|
|
2888
|
-
debug: config.debug ?? false,
|
|
2889
|
-
morphApiKey: config.morphApiKey,
|
|
2890
|
-
morphApiUrl: config.morphApiUrl,
|
|
2891
|
-
retryConfig: config.retryConfig,
|
|
2892
|
-
timeout: config.timeout,
|
|
2893
|
-
search_type: config.search_type
|
|
2894
|
-
});
|
|
2895
|
-
return processAgentResult(result, parsed.search_term, config.morphApiKey, config.morphApiUrl);
|
|
2896
|
-
}
|
|
2897
|
-
async function processAgentResult(result, searchTerm, apiKey, apiUrl) {
|
|
2898
|
-
const finish = result.finish;
|
|
2899
|
-
if (result.terminationReason !== "completed" || !finish?.metadata) {
|
|
2900
|
-
const errorDetails = result.errors?.map((e) => e.message).join("; ") || "unknown reason";
|
|
2901
|
-
console.error(`[warp_grep] processAgentResult failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);
|
|
2902
|
-
return { success: false, error: `Search did not complete: ${errorDetails}` };
|
|
2903
|
-
}
|
|
2904
|
-
const contexts = (finish.resolved ?? []).map((r) => ({
|
|
2905
|
-
file: r.path,
|
|
2906
|
-
content: r.content,
|
|
2907
|
-
lines: r.ranges
|
|
2908
|
-
}));
|
|
2909
|
-
try {
|
|
2910
|
-
const compactable = contexts.map((c) => ({ path: c.file, content: c.content }));
|
|
2911
|
-
const compacted = await compactFileContexts(compactable, searchTerm, apiKey, apiUrl);
|
|
2912
|
-
for (let i = 0; i < contexts.length; i++) {
|
|
2913
|
-
contexts[i].content = compacted[i].content;
|
|
2914
|
-
}
|
|
2915
|
-
} catch (error) {
|
|
2916
|
-
console.error(`[warp_grep] Failed to compact result contexts:`, error);
|
|
2917
|
-
}
|
|
2918
|
-
return { success: true, contexts, summary: finish.payload };
|
|
2919
|
-
}
|
|
2920
|
-
async function* executeToolCallStreaming(input, config) {
|
|
2921
|
-
const parsed = typeof input === "string" ? JSON.parse(input) : input;
|
|
2922
|
-
const allowNames = config.search_type === "node_modules" ? ["node_modules"] : void 0;
|
|
2923
|
-
const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);
|
|
2924
|
-
const generator = runWarpGrepStreaming({
|
|
2925
|
-
searchTerm: parsed.search_term,
|
|
2926
|
-
repoRoot: config.repoRoot,
|
|
2927
|
-
provider,
|
|
2928
|
-
excludes: config.excludes,
|
|
2929
|
-
includes: config.includes,
|
|
2930
|
-
debug: config.debug ?? false,
|
|
2931
|
-
morphApiKey: config.morphApiKey,
|
|
2932
|
-
morphApiUrl: config.morphApiUrl,
|
|
2933
|
-
retryConfig: config.retryConfig,
|
|
2934
|
-
timeout: config.timeout,
|
|
2935
|
-
search_type: config.search_type
|
|
2936
|
-
});
|
|
2937
|
-
let agentResult;
|
|
2938
|
-
for (; ; ) {
|
|
2939
|
-
const { value, done } = await generator.next();
|
|
2940
|
-
if (done) {
|
|
2941
|
-
agentResult = value;
|
|
2942
|
-
break;
|
|
2943
|
-
}
|
|
2944
|
-
yield value;
|
|
2945
|
-
}
|
|
2946
|
-
return await processAgentResult(agentResult, parsed.search_term, config.morphApiKey, config.morphApiUrl);
|
|
2947
|
-
}
|
|
2948
|
-
async function fetchRawGitHubFile(owner, repo, filePath, branch, timeout) {
|
|
2949
|
-
const branches = branch ? [branch] : ["HEAD"];
|
|
2950
|
-
const fallbacks = ["main", "master", "develop"];
|
|
2951
|
-
const fetchWithTimeout = (url) => timeout ? fetch(url, { signal: AbortSignal.timeout(timeout) }) : fetch(url);
|
|
2952
|
-
for (const b of branches) {
|
|
2953
|
-
const url = `https://raw.githubusercontent.com/${owner}/${repo}/${b}/${filePath}`;
|
|
2954
|
-
const res = await fetchWithTimeout(url);
|
|
2955
|
-
if (res.ok) return { content: await res.text(), branch: b };
|
|
2956
|
-
}
|
|
2957
|
-
for (const fb of fallbacks) {
|
|
2958
|
-
if (branch && fb === branch) continue;
|
|
2959
|
-
const url = `https://raw.githubusercontent.com/${owner}/${repo}/${fb}/${filePath}`;
|
|
2960
|
-
const res = await fetchWithTimeout(url);
|
|
2961
|
-
if (res.ok) return { content: await res.text(), branch: fb };
|
|
2962
|
-
}
|
|
2963
|
-
throw new Error(`File not found: ${owner}/${repo}/${filePath}`);
|
|
2964
|
-
}
|
|
2965
|
-
async function executeGitHubReadFile(input, config) {
|
|
2966
|
-
try {
|
|
2967
|
-
const { owner, repo } = parseGitHubUrl(input.github);
|
|
2968
|
-
const { content: raw, branch } = await fetchRawGitHubFile(
|
|
2969
|
-
owner,
|
|
2970
|
-
repo,
|
|
2971
|
-
input.path,
|
|
2972
|
-
input.branch,
|
|
2973
|
-
config?.timeout
|
|
2974
|
-
);
|
|
2975
|
-
const allLines = raw.split("\n");
|
|
2976
|
-
const totalLines = allLines.length;
|
|
2977
|
-
const start = Math.max(1, input.startLine ?? 1);
|
|
2978
|
-
const end = Math.min(totalLines, input.endLine ?? totalLines);
|
|
2979
|
-
const selected = allLines.slice(start - 1, end);
|
|
2980
|
-
const padWidth = String(end).length;
|
|
2981
|
-
const numbered = selected.map((line, i) => `${String(start + i).padStart(padWidth)}|${line}`).join("\n");
|
|
2982
|
-
return {
|
|
2983
|
-
success: true,
|
|
2984
|
-
content: numbered,
|
|
2985
|
-
path: input.path,
|
|
2986
|
-
github: `${owner}/${repo}`,
|
|
2987
|
-
branch,
|
|
2988
|
-
lineRange: [start, end],
|
|
2989
|
-
totalLines
|
|
2990
|
-
};
|
|
2991
|
-
} catch (error) {
|
|
2992
|
-
return {
|
|
2993
|
-
success: false,
|
|
2994
|
-
error: error instanceof Error ? error.message : String(error)
|
|
2995
|
-
};
|
|
2996
|
-
}
|
|
2997
|
-
}
|
|
2998
|
-
function formatResult(result) {
|
|
2999
|
-
if (!result.success) {
|
|
3000
|
-
return `Search failed: ${result.error}`;
|
|
3001
|
-
}
|
|
3002
|
-
if (!result.contexts || result.contexts.length === 0) {
|
|
3003
|
-
return "No relevant code found. Try rephrasing your search term.";
|
|
3004
|
-
}
|
|
3005
|
-
const parts = [];
|
|
3006
|
-
parts.push(`Morph Fast Context subagent performed search on repository:
|
|
3007
|
-
`);
|
|
3008
|
-
parts.push("Relevant context found:");
|
|
3009
|
-
for (const ctx of result.contexts) {
|
|
3010
|
-
const rangeStr = !ctx.lines || ctx.lines === "*" ? "*" : ctx.lines.map(([s, e]) => `${s}-${e}`).join(",");
|
|
3011
|
-
parts.push(`- ${ctx.file}:${rangeStr}`);
|
|
3012
|
-
}
|
|
3013
|
-
parts.push("\nHere is the content of files:\n");
|
|
3014
|
-
for (const ctx of result.contexts) {
|
|
3015
|
-
const rangeStr = !ctx.lines || ctx.lines === "*" ? "" : ` lines="${ctx.lines.map(([s, e]) => `${s}-${e}`).join(",")}"`;
|
|
3016
|
-
parts.push(`<file path="${ctx.file}"${rangeStr}>`);
|
|
3017
|
-
parts.push(ctx.content);
|
|
3018
|
-
parts.push("</file>\n");
|
|
3019
|
-
}
|
|
3020
|
-
return parts.join("\n");
|
|
3021
|
-
}
|
|
3022
|
-
|
|
3023
|
-
// modelrouter/core.ts
|
|
3024
|
-
init_logger();
|
|
3025
|
-
var DEFAULT_API_URL4 = "https://api.morphllm.com";
|
|
3026
|
-
var DEFAULT_TIMEOUT4 = 5e3;
|
|
3027
|
-
function resolveClient2(clientOrConfig) {
|
|
3028
|
-
if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
|
|
3029
|
-
return new MorphAPIClient({
|
|
3030
|
-
apiKey: clientOrConfig.apiKey,
|
|
3031
|
-
baseURL: clientOrConfig.apiUrl ?? DEFAULT_API_URL4,
|
|
3032
|
-
timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT4,
|
|
3033
|
-
retryConfig: clientOrConfig.retryConfig,
|
|
3034
|
-
debug: clientOrConfig.debug
|
|
3035
|
-
});
|
|
3036
|
-
}
|
|
3037
|
-
var BaseRouter = class extends APIResource {
|
|
3038
|
-
provider;
|
|
3039
|
-
timeout;
|
|
3040
|
-
constructor(provider, clientOrConfig = {}) {
|
|
3041
|
-
super(resolveClient2(clientOrConfig));
|
|
3042
|
-
this.provider = provider;
|
|
3043
|
-
const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
|
|
3044
|
-
this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT4;
|
|
3045
|
-
}
|
|
3046
|
-
/** Throw the historical "API key is required" message when no key is resolvable. */
|
|
3047
|
-
requireApiKey() {
|
|
3048
|
-
if (!this._client.resolveApiKey()) {
|
|
3049
|
-
throw new Error(
|
|
3050
|
-
"Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config."
|
|
3051
|
-
);
|
|
3052
|
-
}
|
|
3053
|
-
}
|
|
3054
|
-
/** POST to the router and surface failures as `Router API error (<status>): ...`. */
|
|
3055
|
-
async route(provider, input) {
|
|
3056
|
-
try {
|
|
3057
|
-
return await this._client.post(`/v1/router/${provider}`, {
|
|
3058
|
-
body: { input: input.input, mode: input.mode || "balanced" },
|
|
3059
|
-
timeout: this.timeout
|
|
3060
|
-
});
|
|
3061
|
-
} catch (error) {
|
|
3062
|
-
if (error instanceof MorphError) {
|
|
3063
|
-
throw new Error(`Router API error (${error.statusCode}): ${error.message}`);
|
|
3064
|
-
}
|
|
3065
|
-
throw error;
|
|
3066
|
-
}
|
|
3067
|
-
}
|
|
3068
|
-
/**
|
|
3069
|
-
* Select the optimal model for a given input and mode
|
|
3070
|
-
*/
|
|
3071
|
-
async selectModel(input) {
|
|
3072
|
-
this.requireApiKey();
|
|
3073
|
-
logger.debug("ModelRouter", "request", { provider: this.provider, mode: input.mode || "balanced" });
|
|
3074
|
-
const apiResult = await this.route(this.provider, input);
|
|
3075
|
-
logger.debug("ModelRouter", "selected", { provider: this.provider, model: apiResult.model });
|
|
3076
|
-
return { model: apiResult.model };
|
|
3077
|
-
}
|
|
3078
|
-
};
|
|
3079
|
-
var OpenAIRouter = class extends BaseRouter {
|
|
3080
|
-
constructor(clientOrConfig = {}) {
|
|
3081
|
-
super("openai", clientOrConfig);
|
|
3082
|
-
}
|
|
3083
|
-
/**
|
|
3084
|
-
* Select optimal GPT-5 model
|
|
3085
|
-
*
|
|
3086
|
-
* @param input - User input and mode
|
|
3087
|
-
* @returns Selected model name (gpt-5-mini | gpt-5-low | gpt-5-medium | gpt-5-high)
|
|
3088
|
-
*/
|
|
3089
|
-
async selectModel(input) {
|
|
3090
|
-
return super.selectModel(input);
|
|
3091
|
-
}
|
|
3092
|
-
};
|
|
3093
|
-
var AnthropicRouter = class extends BaseRouter {
|
|
3094
|
-
constructor(clientOrConfig = {}) {
|
|
3095
|
-
super("anthropic", clientOrConfig);
|
|
3096
|
-
}
|
|
3097
|
-
/**
|
|
3098
|
-
* Select optimal Claude model
|
|
3099
|
-
*
|
|
3100
|
-
* @param input - User input and mode
|
|
3101
|
-
* @returns Selected model name (claude-4.5-haiku | claude-4.5-sonnet)
|
|
3102
|
-
*/
|
|
3103
|
-
async selectModel(input) {
|
|
3104
|
-
return super.selectModel(input);
|
|
3105
|
-
}
|
|
3106
|
-
};
|
|
3107
|
-
var GeminiRouter = class extends BaseRouter {
|
|
3108
|
-
constructor(clientOrConfig = {}) {
|
|
3109
|
-
super("gemini", clientOrConfig);
|
|
3110
|
-
}
|
|
3111
|
-
/**
|
|
3112
|
-
* Select optimal Gemini model
|
|
3113
|
-
*
|
|
3114
|
-
* @param input - User input and mode
|
|
3115
|
-
* @returns Selected model name (gemini-2.5-flash | gemini-2.5-pro)
|
|
3116
|
-
*/
|
|
3117
|
-
async selectModel(input) {
|
|
3118
|
-
return super.selectModel(input);
|
|
3119
|
-
}
|
|
3120
|
-
};
|
|
3121
|
-
var RawRouter = class extends BaseRouter {
|
|
3122
|
-
constructor(clientOrConfig = {}) {
|
|
3123
|
-
super("raw", clientOrConfig);
|
|
3124
|
-
}
|
|
3125
|
-
/**
|
|
3126
|
-
* Get raw difficulty classification
|
|
3127
|
-
*
|
|
3128
|
-
* @param input - User input and mode
|
|
3129
|
-
* @returns Raw difficulty (easy | medium | hard | needs_info)
|
|
3130
|
-
*/
|
|
3131
|
-
async classify(input) {
|
|
3132
|
-
this.requireApiKey();
|
|
3133
|
-
logger.debug("RawRouter", "request", { mode: input.mode || "balanced" });
|
|
3134
|
-
const apiResult = await this.route("raw", input);
|
|
3135
|
-
let difficulty;
|
|
3136
|
-
if (apiResult.difficulty === "") {
|
|
3137
|
-
difficulty = "medium";
|
|
3138
|
-
} else {
|
|
3139
|
-
difficulty = apiResult.difficulty || apiResult.model;
|
|
3140
|
-
}
|
|
3141
|
-
logger.debug("RawRouter", "classified", { difficulty });
|
|
3142
|
-
return { difficulty };
|
|
3143
|
-
}
|
|
3144
|
-
};
|
|
3145
|
-
var RouterClassifier = class extends APIResource {
|
|
3146
|
-
timeout;
|
|
3147
|
-
constructor(clientOrConfig = {}) {
|
|
3148
|
-
super(resolveClient2(clientOrConfig));
|
|
3149
|
-
const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
|
|
3150
|
-
this.timeout = cfg.timeout ?? DEFAULT_TIMEOUT4;
|
|
3151
|
-
}
|
|
3152
|
-
/** Classify an input across the requested axes (all three by default). */
|
|
3153
|
-
async classify(input) {
|
|
3154
|
-
if (!this._client.resolveApiKey()) {
|
|
3155
|
-
throw new Error(
|
|
3156
|
-
"Morph API key is required. Set MORPH_API_KEY environment variable or pass apiKey in config."
|
|
3157
|
-
);
|
|
3158
|
-
}
|
|
3159
|
-
logger.debug("RouterClassifier", "request", { classes: input.classes ?? "all" });
|
|
3160
|
-
try {
|
|
3161
|
-
const res = await this._client.post("/v1/router/classify", {
|
|
3162
|
-
body: { input: input.input, ...input.classes ? { classes: input.classes } : {} },
|
|
3163
|
-
timeout: this.timeout
|
|
3164
|
-
});
|
|
3165
|
-
logger.debug("RouterClassifier", "classified", {
|
|
3166
|
-
difficulty: res.classifications.difficulty?.label,
|
|
3167
|
-
ambiguity: res.classifications.ambiguity?.label,
|
|
3168
|
-
domain: res.classifications.domain?.label
|
|
3169
|
-
});
|
|
3170
|
-
return res.classifications;
|
|
3171
|
-
} catch (error) {
|
|
3172
|
-
if (error instanceof MorphError) {
|
|
3173
|
-
throw new Error(`Router API error (${error.statusCode}): ${error.message}`);
|
|
3174
|
-
}
|
|
3175
|
-
throw error;
|
|
3176
|
-
}
|
|
3177
|
-
}
|
|
3178
|
-
};
|
|
3179
|
-
|
|
3180
|
-
// tools/warp_grep/prompts.ts
|
|
3181
|
-
var WARP_GREP_TOOL_NAME = "codebase_search";
|
|
3182
|
-
var WARP_GREP_DESCRIPTION = 'Very fast code search exploration subagent (not a grep tool) that runs parallel grep and file read calls over multiple turns to locate relevant files and line ranges. The search term should be a targeted natural-language query describing what you are trying to find or accomplish, e.g. "Find where authentication requests are handled in the Express routes" or "How do callers of processOrder handle the error case?". Fill in extra context you can infer to make the query specific. Do not pass bare keywords or symbol names \u2014 use grep directly for exact symbol lookups. Use this tool first when exploring unfamiliar code. The results may be partial \u2014 follow up with classical search tools or direct file reads if needed.';
|
|
3183
|
-
var GITHUB_WARP_GREP_SEARCH_TOOL_NAME = "github_codebase_search";
|
|
3184
|
-
var GITHUB_WARP_GREP_SEARCH_DESCRIPTION = "Always use this when debugging errors in third-party dependencies to check for upstream fixes, open issues, or newer code pathsSearch tool for public GitHub repositories.Code search exploration subagent for public GitHub repositories (not your local workspace \u2014 use codebase_search for that). Runs parallel grep and file read calls to locate relevant files and line ranges in external github repositories without cloning the repository. Pass a targeted natural-language query, not bare keywords. Useful for understanding how a library works or investigating upstream bugs. You must provide either github_url or owner_repo (at least one required). ";
|
|
3185
|
-
var GITHUB_WARP_GREP_SEARCH_INPUT_SCHEMA = {
|
|
3186
|
-
type: "object",
|
|
3187
|
-
properties: {
|
|
3188
|
-
search_term: { type: "string", description: 'A targeted natural-language query describing what to find (e.g. "How does auth work for SSO users?"). Not a keyword or symbol name.' },
|
|
3189
|
-
github_url: { type: "string", description: 'GitHub repository URL to search (e.g. "https://github.com/vercel/next.js"). You must provide either github_url or owner_repo.' },
|
|
3190
|
-
owner_repo: { type: "string", description: 'Repository owner/repo shorthand (e.g. "vercel/next.js"). You must provide either github_url or owner_repo.' },
|
|
3191
|
-
branch: { type: "string", description: "Branch to search (defaults to the repository default branch)" }
|
|
3192
|
-
},
|
|
3193
|
-
required: ["search_term"]
|
|
3194
|
-
};
|
|
3195
|
-
var GITHUB_SEARCH_TOOL_NAME = GITHUB_WARP_GREP_SEARCH_TOOL_NAME;
|
|
3196
|
-
var GITHUB_SEARCH_DESCRIPTION = GITHUB_WARP_GREP_SEARCH_DESCRIPTION;
|
|
3197
|
-
var GITHUB_SEARCH_INPUT_SCHEMA = GITHUB_WARP_GREP_SEARCH_INPUT_SCHEMA;
|
|
3198
|
-
|
|
3199
|
-
// tools/warp_grep/openai.ts
|
|
3200
|
-
var TOOL_PARAMETERS = {
|
|
3201
|
-
type: "object",
|
|
3202
|
-
properties: {
|
|
3203
|
-
search_term: { type: "string", description: "Search problem statement that this subagent is supposed to research for" }
|
|
3204
|
-
},
|
|
3205
|
-
required: ["search_term"]
|
|
3206
|
-
};
|
|
3207
|
-
function createWarpGrepTool(config) {
|
|
3208
|
-
const tool4 = {
|
|
3209
|
-
type: "function",
|
|
3210
|
-
function: {
|
|
3211
|
-
name: config.name ?? WARP_GREP_TOOL_NAME,
|
|
3212
|
-
description: config.description ?? WARP_GREP_DESCRIPTION,
|
|
3213
|
-
parameters: TOOL_PARAMETERS
|
|
3214
|
-
}
|
|
3215
|
-
};
|
|
3216
|
-
return Object.assign(tool4, {
|
|
3217
|
-
execute: async (input) => {
|
|
3218
|
-
return executeToolCall(input, config);
|
|
3219
|
-
},
|
|
3220
|
-
formatResult: (result) => {
|
|
3221
|
-
return formatResult(result);
|
|
3222
|
-
}
|
|
3223
|
-
});
|
|
3224
|
-
}
|
|
3225
|
-
function createGitHubSearchTool(config) {
|
|
3226
|
-
const client = new WarpGrepClient(config);
|
|
3227
|
-
const tool4 = {
|
|
3228
|
-
type: "function",
|
|
3229
|
-
function: {
|
|
3230
|
-
name: GITHUB_SEARCH_TOOL_NAME,
|
|
3231
|
-
description: GITHUB_SEARCH_DESCRIPTION,
|
|
3232
|
-
parameters: GITHUB_SEARCH_INPUT_SCHEMA
|
|
3233
|
-
}
|
|
3234
|
-
};
|
|
3235
|
-
return Object.assign(tool4, {
|
|
3236
|
-
execute: async (input) => {
|
|
3237
|
-
const github = input.github_url || input.owner_repo;
|
|
3238
|
-
if (!github) {
|
|
3239
|
-
throw new Error("Please provide github search url or owner/repo id");
|
|
3240
|
-
}
|
|
3241
|
-
return client.searchGitHub({ searchTerm: input.search_term, github, branch: input.branch });
|
|
3242
|
-
},
|
|
3243
|
-
formatResult: (result) => {
|
|
3244
|
-
return formatResult(result);
|
|
3245
|
-
}
|
|
3246
|
-
});
|
|
3247
|
-
}
|
|
3248
|
-
|
|
3249
|
-
// tools/fastapply/prompts.ts
|
|
3250
|
-
var EDIT_FILE_TOOL_DESCRIPTION = `Use this tool to make an edit to an existing file.
|
|
3251
|
-
|
|
3252
|
-
This 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.
|
|
3253
|
-
|
|
3254
|
-
When writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.
|
|
3255
|
-
|
|
3256
|
-
For example:
|
|
3257
|
-
|
|
3258
|
-
// ... existing code ...
|
|
3259
|
-
FIRST_EDIT
|
|
3260
|
-
// ... existing code ...
|
|
3261
|
-
SECOND_EDIT
|
|
3262
|
-
// ... existing code ...
|
|
3263
|
-
THIRD_EDIT
|
|
3264
|
-
// ... existing code ...
|
|
3265
|
-
|
|
3266
|
-
You should still bias towards repeating as few lines of the original file as possible to convey the change.
|
|
3267
|
-
But, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.
|
|
3268
|
-
|
|
3269
|
-
DO 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.
|
|
3270
|
-
|
|
3271
|
-
If you plan on deleting a section, you must provide context before and after to delete it.
|
|
3272
|
-
|
|
3273
|
-
Make sure it is clear what the edit should be, and where it should be applied.
|
|
3274
|
-
Make 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.`;
|
|
3275
|
-
var 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:
|
|
3276
|
-
|
|
3277
|
-
// ... existing code ...
|
|
3278
|
-
{{ edit_1 }}
|
|
3279
|
-
// ... existing code ...
|
|
3280
|
-
{{ edit_2 }}
|
|
3281
|
-
// ... existing code ...
|
|
3282
|
-
|
|
3283
|
-
Often 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.
|
|
3284
|
-
|
|
3285
|
-
These 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.`;
|
|
3286
|
-
|
|
3287
|
-
// tools/fastapply/openai.ts
|
|
3288
|
-
var editFileTool = {
|
|
3289
|
-
type: "function",
|
|
3290
|
-
function: {
|
|
3291
|
-
name: "edit_file",
|
|
3292
|
-
description: EDIT_FILE_TOOL_DESCRIPTION,
|
|
3293
|
-
parameters: {
|
|
3294
|
-
type: "object",
|
|
3295
|
-
properties: {
|
|
3296
|
-
target_filepath: {
|
|
3297
|
-
type: "string",
|
|
3298
|
-
description: "The path of the target file to modify"
|
|
3299
|
-
},
|
|
3300
|
-
instruction: {
|
|
3301
|
-
type: "string",
|
|
3302
|
-
description: "A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."
|
|
3303
|
-
},
|
|
3304
|
-
code_edit: {
|
|
3305
|
-
type: "string",
|
|
3306
|
-
description: "Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections."
|
|
3307
|
-
}
|
|
3308
|
-
},
|
|
3309
|
-
required: ["target_filepath", "instruction", "code_edit"]
|
|
3310
|
-
}
|
|
3311
|
-
}
|
|
3312
|
-
};
|
|
3313
|
-
async function execute(input, config) {
|
|
3314
|
-
return executeEditFile(input, config);
|
|
3315
|
-
}
|
|
3316
|
-
function getSystemPrompt() {
|
|
3317
|
-
return EDIT_FILE_SYSTEM_PROMPT;
|
|
3318
|
-
}
|
|
3319
|
-
function formatResult2(result) {
|
|
3320
|
-
if (!result.success) {
|
|
3321
|
-
return `Error editing file: ${result.error}`;
|
|
3322
|
-
}
|
|
3323
|
-
const { changes } = result;
|
|
3324
|
-
return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;
|
|
3325
|
-
}
|
|
3326
|
-
function createEditFileTool(config = {}) {
|
|
3327
|
-
const toolDef = {
|
|
3328
|
-
...editFileTool,
|
|
3329
|
-
...config.description && {
|
|
3330
|
-
function: {
|
|
3331
|
-
...editFileTool.function,
|
|
3332
|
-
description: config.description
|
|
3333
|
-
}
|
|
3334
|
-
}
|
|
3335
|
-
};
|
|
3336
|
-
return Object.assign({}, toolDef, {
|
|
3337
|
-
execute: async (input) => {
|
|
3338
|
-
const parsedInput = typeof input === "string" ? JSON.parse(input) : input;
|
|
3339
|
-
return execute(parsedInput, config);
|
|
3340
|
-
},
|
|
3341
|
-
formatResult: (result) => {
|
|
3342
|
-
return formatResult2(result);
|
|
3343
|
-
},
|
|
3344
|
-
getSystemPrompt: () => {
|
|
3345
|
-
return getSystemPrompt();
|
|
3346
|
-
}
|
|
3347
|
-
});
|
|
3348
|
-
}
|
|
3349
|
-
|
|
3350
|
-
// factories/openai.ts
|
|
3351
|
-
var OpenAIToolFactory = class {
|
|
3352
|
-
constructor(config) {
|
|
3353
|
-
this.config = config;
|
|
3354
|
-
}
|
|
3355
|
-
/**
|
|
3356
|
-
* Create an OpenAI-compatible warp grep tool
|
|
3357
|
-
*
|
|
3358
|
-
* @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
|
|
3359
|
-
* @returns OpenAI ChatCompletionTool with execute and formatResult methods
|
|
3360
|
-
*/
|
|
3361
|
-
createWarpGrepTool(toolConfig) {
|
|
3362
|
-
return createWarpGrepTool({
|
|
3363
|
-
...toolConfig,
|
|
3364
|
-
morphApiKey: this.config.apiKey
|
|
3365
|
-
});
|
|
3366
|
-
}
|
|
3367
|
-
/**
|
|
3368
|
-
* Create an OpenAI-compatible edit file tool
|
|
3369
|
-
*
|
|
3370
|
-
* @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
|
|
3371
|
-
* @returns OpenAI ChatCompletionTool with execute and formatResult methods
|
|
3372
|
-
*/
|
|
3373
|
-
createEditFileTool(toolConfig = {}) {
|
|
3374
|
-
return createEditFileTool({
|
|
3375
|
-
...toolConfig,
|
|
3376
|
-
morphApiKey: this.config.apiKey
|
|
3377
|
-
});
|
|
3378
|
-
}
|
|
3379
|
-
/**
|
|
3380
|
-
* Create an OpenAI-compatible GitHub search tool
|
|
3381
|
-
*
|
|
3382
|
-
* @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
|
|
3383
|
-
* @returns OpenAI ChatCompletionTool with execute and formatResult methods
|
|
3384
|
-
*/
|
|
3385
|
-
createGitHubSearchTool(toolConfig) {
|
|
3386
|
-
return createGitHubSearchTool({
|
|
3387
|
-
...toolConfig,
|
|
3388
|
-
morphApiKey: this.config.apiKey
|
|
3389
|
-
});
|
|
3390
|
-
}
|
|
3391
|
-
};
|
|
3392
|
-
|
|
3393
|
-
// tools/warp_grep/anthropic.ts
|
|
3394
|
-
var INPUT_SCHEMA = {
|
|
3395
|
-
type: "object",
|
|
3396
|
-
properties: {
|
|
3397
|
-
search_term: { type: "string", description: "Search problem statement that this subagent is supposed to research for" }
|
|
3398
|
-
},
|
|
3399
|
-
required: ["search_term"]
|
|
3400
|
-
};
|
|
3401
|
-
function createWarpGrepTool2(config) {
|
|
3402
|
-
const tool4 = {
|
|
3403
|
-
name: config.name ?? WARP_GREP_TOOL_NAME,
|
|
3404
|
-
description: config.description ?? WARP_GREP_DESCRIPTION,
|
|
3405
|
-
input_schema: INPUT_SCHEMA
|
|
3406
|
-
};
|
|
3407
|
-
return Object.assign(tool4, {
|
|
3408
|
-
execute: async (input) => {
|
|
3409
|
-
return executeToolCall(input, config);
|
|
3410
|
-
},
|
|
3411
|
-
formatResult: (result) => {
|
|
3412
|
-
return formatResult(result);
|
|
3413
|
-
}
|
|
3414
|
-
});
|
|
3415
|
-
}
|
|
3416
|
-
function createGitHubSearchTool2(config) {
|
|
3417
|
-
const client = new WarpGrepClient(config);
|
|
3418
|
-
const tool4 = {
|
|
3419
|
-
name: GITHUB_SEARCH_TOOL_NAME,
|
|
3420
|
-
description: GITHUB_SEARCH_DESCRIPTION,
|
|
3421
|
-
input_schema: GITHUB_SEARCH_INPUT_SCHEMA
|
|
3422
|
-
};
|
|
3423
|
-
return Object.assign(tool4, {
|
|
3424
|
-
execute: async (input) => {
|
|
3425
|
-
const github = input.github_url || input.owner_repo;
|
|
3426
|
-
if (!github) {
|
|
3427
|
-
throw new Error("Please provide github search url or owner/repo id");
|
|
3428
|
-
}
|
|
3429
|
-
return client.searchGitHub({ searchTerm: input.search_term, github, branch: input.branch });
|
|
3430
|
-
},
|
|
3431
|
-
formatResult: (result) => {
|
|
3432
|
-
return formatResult(result);
|
|
3433
|
-
}
|
|
3434
|
-
});
|
|
3435
|
-
}
|
|
3436
|
-
|
|
3437
|
-
// tools/fastapply/anthropic.ts
|
|
3438
|
-
var editFileTool2 = {
|
|
3439
|
-
name: "edit_file",
|
|
3440
|
-
description: EDIT_FILE_TOOL_DESCRIPTION,
|
|
3441
|
-
input_schema: {
|
|
3442
|
-
type: "object",
|
|
3443
|
-
properties: {
|
|
3444
|
-
target_filepath: {
|
|
3445
|
-
type: "string",
|
|
3446
|
-
description: "The path of the target file to modify"
|
|
3447
|
-
},
|
|
3448
|
-
instruction: {
|
|
3449
|
-
type: "string",
|
|
3450
|
-
description: "A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."
|
|
3451
|
-
},
|
|
3452
|
-
code_edit: {
|
|
3453
|
-
type: "string",
|
|
3454
|
-
description: "Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections."
|
|
3455
|
-
}
|
|
3456
|
-
},
|
|
3457
|
-
required: ["target_filepath", "instruction", "code_edit"]
|
|
3458
|
-
}
|
|
3459
|
-
};
|
|
3460
|
-
function formatResult3(result) {
|
|
3461
|
-
if (!result.success) {
|
|
3462
|
-
return `Error editing file: ${result.error}`;
|
|
3463
|
-
}
|
|
3464
|
-
const { changes } = result;
|
|
3465
|
-
return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;
|
|
3466
|
-
}
|
|
3467
|
-
function createEditFileTool2(config = {}) {
|
|
3468
|
-
const toolDef = {
|
|
3469
|
-
...editFileTool2,
|
|
3470
|
-
...config.description && { description: config.description }
|
|
3471
|
-
};
|
|
3472
|
-
return Object.assign({}, toolDef, {
|
|
3473
|
-
execute: async (input) => {
|
|
3474
|
-
return executeEditFile(input, config);
|
|
3475
|
-
},
|
|
3476
|
-
formatResult: (result) => {
|
|
3477
|
-
return formatResult3(result);
|
|
3478
|
-
},
|
|
3479
|
-
getSystemPrompt: () => {
|
|
3480
|
-
return EDIT_FILE_SYSTEM_PROMPT;
|
|
3481
|
-
}
|
|
3482
|
-
});
|
|
3483
|
-
}
|
|
3484
|
-
|
|
3485
|
-
// subagents/prompts.ts
|
|
3486
|
-
var THOROUGHNESS_INSTRUCTIONS = {
|
|
3487
|
-
quick: `Do 1-2 targeted searches. Find the most relevant file/function quickly and summarize. Don't go deep.`,
|
|
3488
|
-
medium: `Do 2-4 searches. Start broad, then follow up on the most promising leads. Cover the main aspects.`,
|
|
3489
|
-
thorough: `Do 4-8 searches. Explore systematically: start broad, then drill into each relevant area. Cover edge cases, related files, and the full call chain. Leave no stone unturned.`
|
|
3490
|
-
};
|
|
3491
|
-
function getSystemPrompt2(thoroughness = "medium") {
|
|
3492
|
-
return `You are a codebase exploration specialist. Your job is to search a codebase and return a concise, accurate summary of what you find.
|
|
3493
|
-
|
|
3494
|
-
## Mode
|
|
3495
|
-
READ-ONLY. You cannot modify files. You can only search and read code.
|
|
3496
|
-
|
|
3497
|
-
## Strategy
|
|
3498
|
-
${THOROUGHNESS_INSTRUCTIONS[thoroughness]}
|
|
3499
|
-
|
|
3500
|
-
- Use multiple focused searches rather than one vague search
|
|
3501
|
-
- Follow imports, function calls, and type references to build complete understanding
|
|
3502
|
-
- If a search returns no results, try alternative terms (e.g., "auth" vs "authentication" vs "login")
|
|
3503
|
-
- Look at both implementation and tests when relevant
|
|
3504
|
-
|
|
3505
|
-
## Communication
|
|
3506
|
-
You have a \`send_message\` tool. Use it when:
|
|
3507
|
-
- You hit a fork in the road and need guidance ("Found auth in both src/middleware/ and legacy/auth/. Which should I focus on?")
|
|
3508
|
-
- You need clarification on ambiguous requests ("There are 3 auth strategies: JWT, session, OAuth. Which one?")
|
|
3509
|
-
- You want to share a key finding before continuing ("The main auth handler is in src/auth/index.ts. It delegates to strategy-specific modules. Continuing to trace JWT flow.")
|
|
3510
|
-
|
|
3511
|
-
Do NOT use send_message for routine status updates. Only use it when you genuinely need input or have a significant finding worth sharing before you're done.
|
|
3512
|
-
|
|
3513
|
-
## Output
|
|
3514
|
-
When you have enough information, output your final summary. Structure it as:
|
|
3515
|
-
1. Direct answer to the question
|
|
3516
|
-
2. Key files and their roles
|
|
3517
|
-
3. How the pieces connect
|
|
3518
|
-
|
|
3519
|
-
Be concise. The summary should be useful to another AI model that will use your findings to complete a task.`;
|
|
3520
|
-
}
|
|
3521
|
-
var CODEBASE_SEARCH_TOOL = {
|
|
3522
|
-
name: "codebase_search",
|
|
3523
|
-
description: "Search the codebase for relevant code. Takes a natural language search request describing what you want to find. Returns matching file contents with line numbers.",
|
|
3524
|
-
input_schema: {
|
|
3525
|
-
type: "object",
|
|
3526
|
-
properties: {
|
|
3527
|
-
searchRequest: {
|
|
3528
|
-
type: "string",
|
|
3529
|
-
description: "Natural language description of what to search for in the codebase"
|
|
3530
|
-
}
|
|
3531
|
-
},
|
|
3532
|
-
required: ["searchRequest"],
|
|
3533
|
-
additionalProperties: false
|
|
3534
|
-
}
|
|
3535
|
-
};
|
|
3536
|
-
var SEND_MESSAGE_TOOL = {
|
|
3537
|
-
name: "send_message",
|
|
3538
|
-
description: "Send a message to the orchestrating agent. Use this to ask questions, request clarification, or share important findings. The orchestrator may reply with additional context. Use sparingly \u2014 only when you genuinely need input or have a significant finding.",
|
|
3539
|
-
input_schema: {
|
|
3540
|
-
type: "object",
|
|
3541
|
-
properties: {
|
|
3542
|
-
message: {
|
|
3543
|
-
type: "string",
|
|
3544
|
-
description: "The message to send to the orchestrator"
|
|
3545
|
-
}
|
|
3546
|
-
},
|
|
3547
|
-
required: ["message"],
|
|
3548
|
-
additionalProperties: false
|
|
3549
|
-
}
|
|
3550
|
-
};
|
|
3551
|
-
|
|
3552
|
-
// subagents/anthropic.ts
|
|
3553
|
-
var DEFAULT_MAX_TURNS = {
|
|
3554
|
-
quick: 3,
|
|
3555
|
-
medium: 6,
|
|
3556
|
-
thorough: 12
|
|
3557
|
-
};
|
|
3558
|
-
function getMaxTurns(config) {
|
|
3559
|
-
return config.maxTurns ?? DEFAULT_MAX_TURNS[config.thoroughness ?? "medium"] ?? 6;
|
|
3560
|
-
}
|
|
3561
|
-
var TOOLS = [
|
|
3562
|
-
{
|
|
3563
|
-
name: CODEBASE_SEARCH_TOOL.name,
|
|
3564
|
-
description: CODEBASE_SEARCH_TOOL.description,
|
|
3565
|
-
input_schema: CODEBASE_SEARCH_TOOL.input_schema
|
|
3566
|
-
},
|
|
3567
|
-
{
|
|
3568
|
-
name: SEND_MESSAGE_TOOL.name,
|
|
3569
|
-
description: SEND_MESSAGE_TOOL.description,
|
|
3570
|
-
input_schema: SEND_MESSAGE_TOOL.input_schema
|
|
3571
|
-
}
|
|
3572
|
-
];
|
|
3573
|
-
function createExploreSubagent(config) {
|
|
3574
|
-
if (!config.repoRoot) {
|
|
3575
|
-
throw new Error("repoRoot is required for Explore subagent");
|
|
3576
|
-
}
|
|
3577
|
-
const warpGrep = new WarpGrepClient({
|
|
3578
|
-
morphApiKey: config.morphApiKey
|
|
3579
|
-
});
|
|
3580
|
-
const thoroughness = config.thoroughness ?? "medium";
|
|
3581
|
-
const maxTurns = getMaxTurns(config);
|
|
3582
|
-
const replyTimeout = config.replyTimeout ?? 3e4;
|
|
3583
|
-
async function runExplore(prompt, callbacks = {}) {
|
|
3584
|
-
const startTime = Date.now();
|
|
3585
|
-
const allContexts = [];
|
|
3586
|
-
let searchCount = 0;
|
|
3587
|
-
const timeoutMs = config.timeout;
|
|
3588
|
-
try {
|
|
3589
|
-
const messages = [{ role: "user", content: prompt }];
|
|
3590
|
-
let turns = 0;
|
|
3591
|
-
while (turns < maxTurns) {
|
|
3592
|
-
if (timeoutMs && Date.now() - startTime > timeoutMs) {
|
|
3593
|
-
return {
|
|
3594
|
-
success: false,
|
|
3595
|
-
summary: "",
|
|
3596
|
-
contexts: deduplicateContexts(allContexts),
|
|
3597
|
-
searchCount,
|
|
3598
|
-
durationMs: Date.now() - startTime,
|
|
3599
|
-
error: `Exploration timed out after ${timeoutMs}ms`
|
|
3600
|
-
};
|
|
3601
|
-
}
|
|
3602
|
-
const response = await config.client.messages.create({
|
|
3603
|
-
model: config.model,
|
|
3604
|
-
max_tokens: 4096,
|
|
3605
|
-
system: getSystemPrompt2(thoroughness),
|
|
3606
|
-
tools: TOOLS,
|
|
3607
|
-
messages
|
|
3608
|
-
});
|
|
3609
|
-
turns++;
|
|
3610
|
-
if (response.stop_reason === "end_turn" || !response.content.some((b) => b.type === "tool_use")) {
|
|
3611
|
-
const textBlock = response.content.find((b) => b.type === "text");
|
|
3612
|
-
const summary = textBlock?.text || "Exploration completed but no summary was generated.";
|
|
3613
|
-
callbacks.onStep?.({
|
|
3614
|
-
step: searchCount,
|
|
3615
|
-
searchRequest: "",
|
|
3616
|
-
contextsFound: allContexts.length,
|
|
3617
|
-
isFinal: true
|
|
3618
|
-
});
|
|
3619
|
-
return {
|
|
3620
|
-
success: true,
|
|
3621
|
-
summary,
|
|
3622
|
-
contexts: deduplicateContexts(allContexts),
|
|
3623
|
-
searchCount,
|
|
3624
|
-
durationMs: Date.now() - startTime
|
|
3625
|
-
};
|
|
3626
|
-
}
|
|
3627
|
-
messages.push({ role: "assistant", content: response.content });
|
|
3628
|
-
const toolResults = [];
|
|
3629
|
-
for (const block of response.content) {
|
|
3630
|
-
if (block.type !== "tool_use") continue;
|
|
3631
|
-
if (block.name === "codebase_search") {
|
|
3632
|
-
searchCount++;
|
|
3633
|
-
const input = block.input;
|
|
3634
|
-
const warpResult = await warpGrep.execute({
|
|
3635
|
-
searchTerm: input.searchRequest,
|
|
3636
|
-
repoRoot: config.repoRoot,
|
|
3637
|
-
excludes: config.excludes,
|
|
3638
|
-
includes: config.includes
|
|
3639
|
-
});
|
|
3640
|
-
if (warpResult.contexts) {
|
|
3641
|
-
allContexts.push(...warpResult.contexts);
|
|
3642
|
-
}
|
|
3643
|
-
callbacks.onStep?.({
|
|
3644
|
-
step: searchCount,
|
|
3645
|
-
searchRequest: input.searchRequest,
|
|
3646
|
-
contextsFound: warpResult.contexts?.length ?? 0,
|
|
3647
|
-
isFinal: false
|
|
3648
|
-
});
|
|
3649
|
-
toolResults.push({
|
|
3650
|
-
type: "tool_result",
|
|
3651
|
-
tool_use_id: block.id,
|
|
3652
|
-
content: formatResult(warpResult)
|
|
3653
|
-
});
|
|
3654
|
-
} else if (block.name === "send_message") {
|
|
3655
|
-
const input = block.input;
|
|
3656
|
-
const subagentMsg = {
|
|
3657
|
-
from: "explore",
|
|
3658
|
-
content: input.message,
|
|
3659
|
-
timestamp: Date.now()
|
|
3660
|
-
};
|
|
3661
|
-
let replyText = "";
|
|
3662
|
-
if (callbacks.onMessage) {
|
|
3663
|
-
replyText = await Promise.race([
|
|
3664
|
-
new Promise((resolve2) => {
|
|
3665
|
-
callbacks.onMessage(subagentMsg, (text) => {
|
|
3666
|
-
resolve2(text);
|
|
3667
|
-
});
|
|
3668
|
-
}),
|
|
3669
|
-
new Promise(
|
|
3670
|
-
(resolve2) => setTimeout(() => resolve2(""), replyTimeout)
|
|
3671
|
-
)
|
|
3672
|
-
]);
|
|
3673
|
-
}
|
|
3674
|
-
const toolResponse = replyText ? `Response from orchestrator: ${replyText}` : "No response. Continue with your best judgment.";
|
|
3675
|
-
toolResults.push({
|
|
3676
|
-
type: "tool_result",
|
|
3677
|
-
tool_use_id: block.id,
|
|
3678
|
-
content: toolResponse
|
|
3679
|
-
});
|
|
3680
|
-
}
|
|
3681
|
-
}
|
|
3682
|
-
messages.push({ role: "user", content: toolResults });
|
|
3683
|
-
}
|
|
3684
|
-
return {
|
|
3685
|
-
success: true,
|
|
3686
|
-
summary: "Exploration completed (max turns reached).",
|
|
3687
|
-
contexts: deduplicateContexts(allContexts),
|
|
3688
|
-
searchCount,
|
|
3689
|
-
durationMs: Date.now() - startTime
|
|
3690
|
-
};
|
|
3691
|
-
} catch (error) {
|
|
3692
|
-
return {
|
|
3693
|
-
success: false,
|
|
3694
|
-
summary: "",
|
|
3695
|
-
contexts: deduplicateContexts(allContexts),
|
|
3696
|
-
searchCount,
|
|
3697
|
-
durationMs: Date.now() - startTime,
|
|
3698
|
-
error: error instanceof Error ? error.message : String(error)
|
|
3699
|
-
};
|
|
3700
|
-
}
|
|
3701
|
-
}
|
|
3702
|
-
const exploreTool = Object.assign(
|
|
3703
|
-
{
|
|
3704
|
-
name: "explore",
|
|
3705
|
-
description: "Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings.",
|
|
3706
|
-
input_schema: {
|
|
3707
|
-
type: "object",
|
|
3708
|
-
properties: {
|
|
3709
|
-
searchRequest: {
|
|
3710
|
-
type: "string",
|
|
3711
|
-
description: "What to explore in the codebase. Be specific about what you want to understand."
|
|
3712
|
-
}
|
|
3713
|
-
},
|
|
3714
|
-
required: ["searchRequest"]
|
|
3715
|
-
}
|
|
3716
|
-
},
|
|
3717
|
-
{
|
|
3718
|
-
execute: async (input) => {
|
|
3719
|
-
return runExplore(input.searchRequest);
|
|
3720
|
-
},
|
|
3721
|
-
formatResult: (result) => {
|
|
3722
|
-
if (!result.success) {
|
|
3723
|
-
return `Exploration failed: ${result.error}`;
|
|
3724
|
-
}
|
|
3725
|
-
return result.summary;
|
|
3726
|
-
}
|
|
3727
|
-
}
|
|
3728
|
-
);
|
|
3729
|
-
return {
|
|
3730
|
-
/** Anthropic Tool definition for use in parent agents */
|
|
3731
|
-
tool: exploreTool,
|
|
3732
|
-
/** Run exploration with messaging support */
|
|
3733
|
-
run(prompt) {
|
|
3734
|
-
const messageHandlers = [];
|
|
3735
|
-
const stepHandlers = [];
|
|
3736
|
-
let resultPromise = null;
|
|
3737
|
-
const session = {
|
|
3738
|
-
on(event, handler) {
|
|
3739
|
-
if (event === "message") messageHandlers.push(handler);
|
|
3740
|
-
if (event === "step") stepHandlers.push(handler);
|
|
3741
|
-
return session;
|
|
3742
|
-
},
|
|
3743
|
-
send(_text) {
|
|
3744
|
-
},
|
|
3745
|
-
get result() {
|
|
3746
|
-
if (!resultPromise) {
|
|
3747
|
-
resultPromise = runExplore(prompt, {
|
|
3748
|
-
onStep: (step) => {
|
|
3749
|
-
for (const handler of stepHandlers) handler(step);
|
|
3750
|
-
},
|
|
3751
|
-
onMessage: (msg, reply) => {
|
|
3752
|
-
if (messageHandlers.length > 0) {
|
|
3753
|
-
for (const handler of messageHandlers) handler(msg, reply);
|
|
3754
|
-
} else {
|
|
3755
|
-
reply("");
|
|
3756
|
-
}
|
|
3757
|
-
}
|
|
3758
|
-
});
|
|
3759
|
-
}
|
|
3760
|
-
return resultPromise;
|
|
3761
|
-
}
|
|
3762
|
-
};
|
|
3763
|
-
return session;
|
|
3764
|
-
},
|
|
3765
|
-
/** Stream exploration events as an async generator */
|
|
3766
|
-
async *stream(prompt) {
|
|
3767
|
-
const events = [];
|
|
3768
|
-
let resolveNext = null;
|
|
3769
|
-
let done = false;
|
|
3770
|
-
const resultPromise = runExplore(prompt, {
|
|
3771
|
-
onStep: (step) => {
|
|
3772
|
-
events.push({
|
|
3773
|
-
type: "step",
|
|
3774
|
-
step: step.step,
|
|
3775
|
-
searchRequest: step.searchRequest,
|
|
3776
|
-
contextsFound: step.contextsFound,
|
|
3777
|
-
isFinal: step.isFinal
|
|
3778
|
-
});
|
|
3779
|
-
resolveNext?.();
|
|
3780
|
-
},
|
|
3781
|
-
onMessage: (msg, reply) => {
|
|
3782
|
-
events.push({
|
|
3783
|
-
type: "message",
|
|
3784
|
-
from: msg.from,
|
|
3785
|
-
content: msg.content,
|
|
3786
|
-
timestamp: msg.timestamp
|
|
3787
|
-
});
|
|
3788
|
-
resolveNext?.();
|
|
3789
|
-
reply("Continue with your best judgment.");
|
|
3790
|
-
}
|
|
3791
|
-
});
|
|
3792
|
-
while (!done) {
|
|
3793
|
-
if (events.length > 0) {
|
|
3794
|
-
yield events.shift();
|
|
3795
|
-
} else {
|
|
3796
|
-
const raceResult = await Promise.race([
|
|
3797
|
-
resultPromise.then((r) => ({ type: "done", result: r })),
|
|
3798
|
-
new Promise((resolve2) => {
|
|
3799
|
-
resolveNext = () => resolve2({ type: "event" });
|
|
3800
|
-
})
|
|
3801
|
-
]);
|
|
3802
|
-
if (raceResult.type === "done") {
|
|
3803
|
-
while (events.length > 0) {
|
|
3804
|
-
yield events.shift();
|
|
3805
|
-
}
|
|
3806
|
-
done = true;
|
|
3807
|
-
return raceResult.result;
|
|
3808
|
-
}
|
|
3809
|
-
}
|
|
3810
|
-
}
|
|
3811
|
-
return await resultPromise;
|
|
3812
|
-
}
|
|
3813
|
-
};
|
|
3814
|
-
}
|
|
3815
|
-
function deduplicateContexts(contexts) {
|
|
3816
|
-
const map = /* @__PURE__ */ new Map();
|
|
3817
|
-
for (const ctx of contexts) {
|
|
3818
|
-
const existing = map.get(ctx.file);
|
|
3819
|
-
if (!existing || ctx.content.length > existing.content.length) {
|
|
3820
|
-
map.set(ctx.file, ctx);
|
|
3821
|
-
}
|
|
3822
|
-
}
|
|
3823
|
-
return Array.from(map.values());
|
|
3824
|
-
}
|
|
3825
|
-
|
|
3826
|
-
// factories/anthropic.ts
|
|
3827
|
-
var AnthropicToolFactory = class {
|
|
3828
|
-
constructor(config) {
|
|
3829
|
-
this.config = config;
|
|
3830
|
-
}
|
|
3831
|
-
/**
|
|
3832
|
-
* Create an Anthropic-compatible warp grep tool
|
|
3833
|
-
*
|
|
3834
|
-
* @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
|
|
3835
|
-
* @returns Anthropic Tool with execute and formatResult methods
|
|
3836
|
-
*/
|
|
3837
|
-
createWarpGrepTool(toolConfig) {
|
|
3838
|
-
return createWarpGrepTool2({
|
|
3839
|
-
...toolConfig,
|
|
3840
|
-
morphApiKey: this.config.apiKey
|
|
3841
|
-
});
|
|
3842
|
-
}
|
|
3843
|
-
/**
|
|
3844
|
-
* Create an Anthropic-compatible edit file tool
|
|
3845
|
-
*
|
|
3846
|
-
* @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
|
|
3847
|
-
* @returns Anthropic Tool with execute and formatResult methods
|
|
3848
|
-
*/
|
|
3849
|
-
createEditFileTool(toolConfig = {}) {
|
|
3850
|
-
return createEditFileTool2({
|
|
3851
|
-
...toolConfig,
|
|
3852
|
-
morphApiKey: this.config.apiKey
|
|
3853
|
-
});
|
|
3854
|
-
}
|
|
3855
|
-
/**
|
|
3856
|
-
* Create an Anthropic-compatible GitHub search tool
|
|
3857
|
-
*
|
|
3858
|
-
* @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
|
|
3859
|
-
* @returns Anthropic Tool with execute and formatResult methods
|
|
3860
|
-
*/
|
|
3861
|
-
createGitHubSearchTool(toolConfig) {
|
|
3862
|
-
return createGitHubSearchTool2({
|
|
3863
|
-
...toolConfig,
|
|
3864
|
-
morphApiKey: this.config.apiKey
|
|
3865
|
-
});
|
|
3866
|
-
}
|
|
3867
|
-
/**
|
|
3868
|
-
* Create an Explore subagent that searches the codebase and returns summaries
|
|
3869
|
-
*
|
|
3870
|
-
* @param config - Subagent configuration including client and model (morphApiKey inherited from MorphClient)
|
|
3871
|
-
* @returns Explore subagent with .tool, .run(), and .stream() methods
|
|
3872
|
-
*/
|
|
3873
|
-
createExploreSubagent(config) {
|
|
3874
|
-
return createExploreSubagent({
|
|
3875
|
-
...config,
|
|
3876
|
-
morphApiKey: this.config.apiKey
|
|
3877
|
-
});
|
|
3878
|
-
}
|
|
3879
|
-
};
|
|
3880
|
-
|
|
3881
|
-
// tools/warp_grep/vercel.ts
|
|
3882
|
-
var import_ai = require("ai");
|
|
3883
|
-
var import_zod = require("zod");
|
|
3884
|
-
function createWarpGrepTool3(config) {
|
|
3885
|
-
const schema = config.inputSchema ?? import_zod.z.object({
|
|
3886
|
-
search_term: import_zod.z.string().describe("Search problem statement that this subagent is supposed to research for")
|
|
3887
|
-
});
|
|
3888
|
-
return (0, import_ai.tool)({
|
|
3889
|
-
description: config.description ?? WARP_GREP_DESCRIPTION,
|
|
3890
|
-
inputSchema: schema,
|
|
3891
|
-
execute: async (params) => {
|
|
3892
|
-
const steps = [];
|
|
3893
|
-
const generator = executeToolCallStreaming(params, config);
|
|
3894
|
-
let result;
|
|
3895
|
-
for (; ; ) {
|
|
3896
|
-
const { value, done } = await generator.next();
|
|
3897
|
-
if (done) {
|
|
3898
|
-
result = value;
|
|
3899
|
-
break;
|
|
3900
|
-
}
|
|
3901
|
-
steps.push(value);
|
|
3902
|
-
}
|
|
3903
|
-
if (!result.success) {
|
|
3904
|
-
throw new Error(`Failed to search codebase: ${result.error}`);
|
|
3905
|
-
}
|
|
3906
|
-
const allToolCalls = steps.flatMap((s) => s.toolCalls);
|
|
3907
|
-
return {
|
|
3908
|
-
success: true,
|
|
3909
|
-
contexts: result.contexts,
|
|
3910
|
-
summary: result.summary,
|
|
3911
|
-
progress: allToolCalls.length > 0 ? { turn: steps.length, toolCalls: allToolCalls } : void 0
|
|
3912
|
-
};
|
|
3913
|
-
}
|
|
3914
|
-
});
|
|
3915
|
-
}
|
|
3916
|
-
function createGitHubSearchTool3(config) {
|
|
3917
|
-
const client = new WarpGrepClient(config);
|
|
3918
|
-
return (0, import_ai.tool)({
|
|
3919
|
-
description: GITHUB_SEARCH_DESCRIPTION,
|
|
3920
|
-
inputSchema: import_zod.z.object({
|
|
3921
|
-
search_term: import_zod.z.string().describe("Search problem statement that this subagent is supposed to research for"),
|
|
3922
|
-
github_url: import_zod.z.string().optional().describe('GitHub repository URL to search (e.g. "https://github.com/vercel/next.js"). You must provide either github_url or owner_repo.'),
|
|
3923
|
-
owner_repo: import_zod.z.string().optional().describe('Repository owner/repo shorthand (e.g. "vercel/next.js"). You must provide either github_url or owner_repo.'),
|
|
3924
|
-
branch: import_zod.z.string().optional().describe("Branch to search (defaults to repo default branch)")
|
|
3925
|
-
}),
|
|
3926
|
-
execute: async (params) => {
|
|
3927
|
-
const github = params.github_url || params.owner_repo;
|
|
3928
|
-
if (!github) {
|
|
3929
|
-
throw new Error("Please provide github search url or owner/repo id");
|
|
3930
|
-
}
|
|
3931
|
-
const result = await client.searchGitHub({ searchTerm: params.search_term, github, branch: params.branch });
|
|
3932
|
-
if (!result.success) {
|
|
3933
|
-
throw new Error(`GitHub search failed: ${result.error}`);
|
|
3934
|
-
}
|
|
3935
|
-
return {
|
|
3936
|
-
success: true,
|
|
3937
|
-
contexts: result.contexts,
|
|
3938
|
-
summary: result.summary
|
|
3939
|
-
};
|
|
3940
|
-
}
|
|
3941
|
-
});
|
|
3942
|
-
}
|
|
3943
|
-
|
|
3944
|
-
// tools/fastapply/vercel.ts
|
|
3945
|
-
var import_ai2 = require("ai");
|
|
3946
|
-
var import_zod2 = require("zod");
|
|
3947
|
-
var editFileSchema = import_zod2.z.object({
|
|
3948
|
-
target_filepath: import_zod2.z.string().describe("The path of the target file to modify"),
|
|
3949
|
-
instruction: import_zod2.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
|
|
3950
|
-
code_edit: import_zod2.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
|
|
3951
|
-
});
|
|
3952
|
-
var editFileTool3 = (0, import_ai2.tool)({
|
|
3953
|
-
description: EDIT_FILE_TOOL_DESCRIPTION,
|
|
3954
|
-
inputSchema: editFileSchema,
|
|
3955
|
-
execute: async (params) => {
|
|
3956
|
-
const result = await executeEditFile({
|
|
3957
|
-
target_filepath: params.target_filepath,
|
|
3958
|
-
instruction: params.instruction,
|
|
3959
|
-
code_edit: params.code_edit
|
|
3960
|
-
});
|
|
3961
|
-
if (!result.success) {
|
|
3962
|
-
throw new Error(`Failed to edit file: ${result.error}`);
|
|
3963
|
-
}
|
|
3964
|
-
return {
|
|
3965
|
-
success: true,
|
|
3966
|
-
filepath: result.filepath,
|
|
3967
|
-
changes: result.changes,
|
|
3968
|
-
udiff: result.udiff
|
|
3969
|
-
};
|
|
3970
|
-
}
|
|
3971
|
-
});
|
|
3972
|
-
function createEditFileTool3(config = {}) {
|
|
3973
|
-
const schema = import_zod2.z.object({
|
|
3974
|
-
target_filepath: import_zod2.z.string().describe("The path of the target file to modify"),
|
|
3975
|
-
instruction: import_zod2.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
|
|
3976
|
-
code_edit: import_zod2.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
|
|
3977
|
-
});
|
|
3978
|
-
return (0, import_ai2.tool)({
|
|
3979
|
-
description: config.description || EDIT_FILE_TOOL_DESCRIPTION,
|
|
3980
|
-
inputSchema: schema,
|
|
3981
|
-
execute: async (params) => {
|
|
3982
|
-
const result = await executeEditFile(
|
|
3983
|
-
{
|
|
3984
|
-
target_filepath: params.target_filepath,
|
|
3985
|
-
instruction: params.instruction,
|
|
3986
|
-
code_edit: params.code_edit
|
|
3987
|
-
},
|
|
3988
|
-
config
|
|
3989
|
-
);
|
|
3990
|
-
if (!result.success) {
|
|
3991
|
-
throw new Error(`Failed to edit file: ${result.error}`);
|
|
3992
|
-
}
|
|
3993
|
-
return {
|
|
3994
|
-
success: true,
|
|
3995
|
-
filepath: result.filepath,
|
|
3996
|
-
changes: result.changes,
|
|
3997
|
-
udiff: result.udiff
|
|
3998
|
-
};
|
|
3999
|
-
}
|
|
4000
|
-
});
|
|
4001
|
-
}
|
|
4002
|
-
|
|
4003
|
-
// subagents/vercel.ts
|
|
4004
|
-
var import_ai3 = require("ai");
|
|
4005
|
-
var import_zod3 = require("zod");
|
|
4006
|
-
var DEFAULT_MAX_TURNS2 = {
|
|
4007
|
-
quick: 3,
|
|
4008
|
-
medium: 6,
|
|
4009
|
-
thorough: 12
|
|
4010
|
-
};
|
|
4011
|
-
function getMaxTurns2(config) {
|
|
4012
|
-
return config.maxTurns ?? DEFAULT_MAX_TURNS2[config.thoroughness ?? "medium"] ?? 6;
|
|
4013
|
-
}
|
|
4014
|
-
function createExploreSubagent2(config) {
|
|
4015
|
-
if (!config.repoRoot) {
|
|
4016
|
-
throw new Error("repoRoot is required for Explore subagent");
|
|
4017
|
-
}
|
|
4018
|
-
const warpGrep = new WarpGrepClient({
|
|
4019
|
-
morphApiKey: config.morphApiKey
|
|
4020
|
-
});
|
|
4021
|
-
const thoroughness = config.thoroughness ?? "medium";
|
|
4022
|
-
const replyTimeout = config.replyTimeout ?? 3e4;
|
|
4023
|
-
async function runExplore(prompt, callbacks = {}) {
|
|
4024
|
-
const startTime = Date.now();
|
|
4025
|
-
const allContexts = [];
|
|
4026
|
-
let searchCount = 0;
|
|
4027
|
-
const timeoutMs = config.timeout;
|
|
4028
|
-
const timeoutPromise = timeoutMs ? new Promise(
|
|
4029
|
-
(_, reject) => setTimeout(() => reject(new Error(`Exploration timed out after ${timeoutMs}ms`)), timeoutMs)
|
|
4030
|
-
) : null;
|
|
4031
|
-
const runPromise = (async () => {
|
|
4032
|
-
try {
|
|
4033
|
-
const codebaseSearchSchema = import_zod3.z.object({
|
|
4034
|
-
searchRequest: import_zod3.z.string().describe("Natural language description of what to search for")
|
|
4035
|
-
});
|
|
4036
|
-
const sendMessageSchema = import_zod3.z.object({
|
|
4037
|
-
message: import_zod3.z.string().describe("The message to send to the orchestrator")
|
|
4038
|
-
});
|
|
4039
|
-
const result = await (0, import_ai3.generateText)({
|
|
4040
|
-
model: config.model,
|
|
4041
|
-
system: getSystemPrompt2(thoroughness),
|
|
4042
|
-
prompt,
|
|
4043
|
-
tools: {
|
|
4044
|
-
codebase_search: (0, import_ai3.tool)({
|
|
4045
|
-
description: CODEBASE_SEARCH_TOOL.description,
|
|
4046
|
-
inputSchema: codebaseSearchSchema,
|
|
4047
|
-
execute: async (params) => {
|
|
4048
|
-
searchCount++;
|
|
4049
|
-
const warpResult = await warpGrep.execute({
|
|
4050
|
-
searchTerm: params.searchRequest,
|
|
4051
|
-
repoRoot: config.repoRoot,
|
|
4052
|
-
excludes: config.excludes,
|
|
4053
|
-
includes: config.includes
|
|
4054
|
-
});
|
|
4055
|
-
if (warpResult.contexts) {
|
|
4056
|
-
allContexts.push(...warpResult.contexts);
|
|
4057
|
-
}
|
|
4058
|
-
callbacks.onStep?.({
|
|
4059
|
-
step: searchCount,
|
|
4060
|
-
searchRequest: params.searchRequest,
|
|
4061
|
-
contextsFound: warpResult.contexts?.length ?? 0,
|
|
4062
|
-
isFinal: false
|
|
4063
|
-
});
|
|
4064
|
-
return formatResult(warpResult);
|
|
4065
|
-
}
|
|
4066
|
-
}),
|
|
4067
|
-
send_message: (0, import_ai3.tool)({
|
|
4068
|
-
description: SEND_MESSAGE_TOOL.description,
|
|
4069
|
-
inputSchema: sendMessageSchema,
|
|
4070
|
-
execute: async (params) => {
|
|
4071
|
-
const subagentMsg = {
|
|
4072
|
-
from: "explore",
|
|
4073
|
-
content: params.message,
|
|
4074
|
-
timestamp: Date.now()
|
|
4075
|
-
};
|
|
4076
|
-
const replyPromise = new Promise((resolve2) => {
|
|
4077
|
-
if (callbacks.onMessage) {
|
|
4078
|
-
callbacks.onMessage(subagentMsg, (replyText) => {
|
|
4079
|
-
resolve2(replyText);
|
|
4080
|
-
});
|
|
4081
|
-
} else {
|
|
4082
|
-
setTimeout(() => resolve2(""), replyTimeout);
|
|
4083
|
-
}
|
|
4084
|
-
});
|
|
4085
|
-
const reply = await Promise.race([
|
|
4086
|
-
replyPromise,
|
|
4087
|
-
new Promise(
|
|
4088
|
-
(resolve2) => setTimeout(() => resolve2(""), replyTimeout)
|
|
4089
|
-
)
|
|
4090
|
-
]);
|
|
4091
|
-
if (reply) {
|
|
4092
|
-
return `Response from orchestrator: ${reply}`;
|
|
4093
|
-
}
|
|
4094
|
-
return "No response. Continue with your best judgment.";
|
|
4095
|
-
}
|
|
4096
|
-
})
|
|
4097
|
-
},
|
|
4098
|
-
stopWhen: (0, import_ai3.stepCountIs)(getMaxTurns2(config))
|
|
4099
|
-
});
|
|
4100
|
-
callbacks.onStep?.({
|
|
4101
|
-
step: searchCount,
|
|
4102
|
-
searchRequest: "",
|
|
4103
|
-
contextsFound: allContexts.length,
|
|
4104
|
-
isFinal: true
|
|
4105
|
-
});
|
|
4106
|
-
const uniqueContexts = deduplicateContexts2(allContexts);
|
|
4107
|
-
return {
|
|
4108
|
-
success: true,
|
|
4109
|
-
summary: result.text || "Exploration completed but no summary was generated.",
|
|
4110
|
-
contexts: uniqueContexts,
|
|
4111
|
-
searchCount,
|
|
4112
|
-
durationMs: Date.now() - startTime
|
|
4113
|
-
};
|
|
4114
|
-
} catch (error) {
|
|
4115
|
-
return {
|
|
4116
|
-
success: false,
|
|
4117
|
-
summary: "",
|
|
4118
|
-
contexts: deduplicateContexts2(allContexts),
|
|
4119
|
-
searchCount,
|
|
4120
|
-
durationMs: Date.now() - startTime,
|
|
4121
|
-
error: error instanceof Error ? error.message : String(error)
|
|
4122
|
-
};
|
|
4123
|
-
}
|
|
4124
|
-
})();
|
|
4125
|
-
if (timeoutPromise) {
|
|
4126
|
-
try {
|
|
4127
|
-
return await Promise.race([runPromise, timeoutPromise]);
|
|
4128
|
-
} catch (error) {
|
|
4129
|
-
return {
|
|
4130
|
-
success: false,
|
|
4131
|
-
summary: "",
|
|
4132
|
-
contexts: deduplicateContexts2(allContexts),
|
|
4133
|
-
searchCount,
|
|
4134
|
-
durationMs: Date.now() - startTime,
|
|
4135
|
-
error: error instanceof Error ? error.message : String(error)
|
|
4136
|
-
};
|
|
4137
|
-
}
|
|
4138
|
-
}
|
|
4139
|
-
return runPromise;
|
|
4140
|
-
}
|
|
4141
|
-
const exploreToolSchema = import_zod3.z.object({
|
|
4142
|
-
searchRequest: import_zod3.z.string().describe("What to explore in the codebase. Be specific about what you want to understand.")
|
|
4143
|
-
});
|
|
4144
|
-
const exploreTool = (0, import_ai3.tool)({
|
|
4145
|
-
description: "Explore a codebase to answer questions about code structure, find implementations, trace call chains, and understand architecture. Returns a summary of findings. Use this for broad exploration rather than pinpoint keyword searches.",
|
|
4146
|
-
inputSchema: exploreToolSchema,
|
|
4147
|
-
execute: async (params) => {
|
|
4148
|
-
const result = await runExplore(params.searchRequest);
|
|
4149
|
-
return {
|
|
4150
|
-
success: result.success,
|
|
4151
|
-
summary: result.summary,
|
|
4152
|
-
searchCount: result.searchCount,
|
|
4153
|
-
error: result.error
|
|
4154
|
-
};
|
|
4155
|
-
}
|
|
4156
|
-
});
|
|
4157
|
-
return {
|
|
4158
|
-
/** Vercel AI SDK tool for use as a tool in parent agents */
|
|
4159
|
-
tool: exploreTool,
|
|
4160
|
-
/** Run exploration with messaging support */
|
|
4161
|
-
run(prompt) {
|
|
4162
|
-
const messageHandlers = [];
|
|
4163
|
-
const stepHandlers = [];
|
|
4164
|
-
let resultPromise = null;
|
|
4165
|
-
const session = {
|
|
4166
|
-
on(event, handler) {
|
|
4167
|
-
if (event === "message") messageHandlers.push(handler);
|
|
4168
|
-
if (event === "step") stepHandlers.push(handler);
|
|
4169
|
-
return session;
|
|
4170
|
-
},
|
|
4171
|
-
send(_text) {
|
|
4172
|
-
},
|
|
4173
|
-
get result() {
|
|
4174
|
-
if (!resultPromise) {
|
|
4175
|
-
resultPromise = runExplore(prompt, {
|
|
4176
|
-
onStep: (step) => {
|
|
4177
|
-
for (const handler of stepHandlers) handler(step);
|
|
4178
|
-
},
|
|
4179
|
-
onMessage: (msg, reply) => {
|
|
4180
|
-
if (messageHandlers.length > 0) {
|
|
4181
|
-
for (const handler of messageHandlers) handler(msg, reply);
|
|
4182
|
-
} else {
|
|
4183
|
-
reply("");
|
|
4184
|
-
}
|
|
4185
|
-
}
|
|
4186
|
-
});
|
|
4187
|
-
}
|
|
4188
|
-
return resultPromise;
|
|
4189
|
-
}
|
|
4190
|
-
};
|
|
4191
|
-
return session;
|
|
4192
|
-
},
|
|
4193
|
-
/** Stream exploration events as an async generator */
|
|
4194
|
-
async *stream(prompt) {
|
|
4195
|
-
const events = [];
|
|
4196
|
-
let resolveNext = null;
|
|
4197
|
-
let done = false;
|
|
4198
|
-
const resultPromise = runExplore(prompt, {
|
|
4199
|
-
onStep: (step) => {
|
|
4200
|
-
events.push({
|
|
4201
|
-
type: "step",
|
|
4202
|
-
step: step.step,
|
|
4203
|
-
searchRequest: step.searchRequest,
|
|
4204
|
-
contextsFound: step.contextsFound,
|
|
4205
|
-
isFinal: step.isFinal
|
|
4206
|
-
});
|
|
4207
|
-
resolveNext?.();
|
|
4208
|
-
},
|
|
4209
|
-
onMessage: (msg, reply) => {
|
|
4210
|
-
events.push({
|
|
4211
|
-
type: "message",
|
|
4212
|
-
from: msg.from,
|
|
4213
|
-
content: msg.content,
|
|
4214
|
-
timestamp: msg.timestamp
|
|
4215
|
-
});
|
|
4216
|
-
resolveNext?.();
|
|
4217
|
-
reply("Continue with your best judgment.");
|
|
4218
|
-
}
|
|
4219
|
-
});
|
|
4220
|
-
while (!done) {
|
|
4221
|
-
if (events.length > 0) {
|
|
4222
|
-
yield events.shift();
|
|
4223
|
-
} else {
|
|
4224
|
-
const raceResult = await Promise.race([
|
|
4225
|
-
resultPromise.then((r) => ({ type: "done", result: r })),
|
|
4226
|
-
new Promise((resolve2) => {
|
|
4227
|
-
resolveNext = () => resolve2({ type: "event" });
|
|
4228
|
-
})
|
|
4229
|
-
]);
|
|
4230
|
-
if (raceResult.type === "done") {
|
|
4231
|
-
while (events.length > 0) {
|
|
4232
|
-
yield events.shift();
|
|
4233
|
-
}
|
|
4234
|
-
done = true;
|
|
4235
|
-
return raceResult.result;
|
|
4236
|
-
}
|
|
4237
|
-
}
|
|
4238
|
-
}
|
|
4239
|
-
return await resultPromise;
|
|
4240
|
-
}
|
|
4241
|
-
};
|
|
4242
|
-
}
|
|
4243
|
-
function deduplicateContexts2(contexts) {
|
|
4244
|
-
const map = /* @__PURE__ */ new Map();
|
|
4245
|
-
for (const ctx of contexts) {
|
|
4246
|
-
const existing = map.get(ctx.file);
|
|
4247
|
-
if (!existing || ctx.content.length > existing.content.length) {
|
|
4248
|
-
map.set(ctx.file, ctx);
|
|
4249
|
-
}
|
|
4250
|
-
}
|
|
4251
|
-
return Array.from(map.values());
|
|
4252
|
-
}
|
|
4253
|
-
|
|
4254
|
-
// factories/vercel.ts
|
|
4255
|
-
var VercelToolFactory = class {
|
|
4256
|
-
constructor(config) {
|
|
4257
|
-
this.config = config;
|
|
4258
|
-
}
|
|
4259
|
-
/**
|
|
4260
|
-
* Create a Vercel AI SDK-compatible warp grep tool
|
|
4261
|
-
*
|
|
4262
|
-
* @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
|
|
4263
|
-
* @returns Vercel AI SDK tool
|
|
4264
|
-
*/
|
|
4265
|
-
createWarpGrepTool(toolConfig) {
|
|
4266
|
-
return createWarpGrepTool3({
|
|
4267
|
-
...toolConfig,
|
|
4268
|
-
morphApiKey: this.config.apiKey
|
|
4269
|
-
});
|
|
4270
|
-
}
|
|
4271
|
-
/**
|
|
4272
|
-
* Create a Vercel AI SDK-compatible edit file tool
|
|
4273
|
-
*
|
|
4274
|
-
* @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
|
|
4275
|
-
* @returns Vercel AI SDK tool
|
|
4276
|
-
*/
|
|
4277
|
-
createEditFileTool(toolConfig = {}) {
|
|
4278
|
-
return createEditFileTool3({
|
|
4279
|
-
...toolConfig,
|
|
4280
|
-
morphApiKey: this.config.apiKey
|
|
4281
|
-
});
|
|
4282
|
-
}
|
|
4283
|
-
/**
|
|
4284
|
-
* Create a Vercel AI SDK-compatible GitHub search tool
|
|
4285
|
-
*
|
|
4286
|
-
* @param toolConfig - Tool configuration (morphApiKey inherited from MorphClient)
|
|
4287
|
-
* @returns Vercel AI SDK tool
|
|
4288
|
-
*/
|
|
4289
|
-
createGitHubSearchTool(toolConfig) {
|
|
4290
|
-
return createGitHubSearchTool3({
|
|
4291
|
-
...toolConfig,
|
|
4292
|
-
morphApiKey: this.config.apiKey
|
|
4293
|
-
});
|
|
4294
|
-
}
|
|
4295
|
-
/**
|
|
4296
|
-
* Create an Explore subagent that searches the codebase and returns summaries
|
|
4297
|
-
*
|
|
4298
|
-
* @param config - Subagent configuration including model (morphApiKey inherited from MorphClient)
|
|
4299
|
-
* @returns Explore subagent with .tool, .run(), and .stream() methods
|
|
4300
|
-
*/
|
|
4301
|
-
createExploreSubagent(config) {
|
|
4302
|
-
return createExploreSubagent2({
|
|
4303
|
-
...config,
|
|
4304
|
-
morphApiKey: this.config.apiKey
|
|
4305
|
-
});
|
|
4306
|
-
}
|
|
4307
|
-
};
|
|
4308
|
-
|
|
4309
|
-
// client.ts
|
|
4310
|
-
var MorphClient = class extends MorphAPIClient {
|
|
4311
|
-
/** Client configuration */
|
|
4312
|
-
config;
|
|
4313
|
-
/** FastApply tool for editing files with AI-powered merge */
|
|
4314
|
-
fastApply;
|
|
4315
|
-
/** WarpGrep tool for fast code search using ripgrep */
|
|
4316
|
-
warpGrep;
|
|
4317
|
-
/** Model routers for intelligent model selection */
|
|
4318
|
-
routers;
|
|
4319
|
-
/** OpenAI-compatible tool factories */
|
|
4320
|
-
openai;
|
|
4321
|
-
/** Anthropic-compatible tool factories */
|
|
4322
|
-
anthropic;
|
|
4323
|
-
/** Vercel AI SDK tool factories */
|
|
4324
|
-
vercel;
|
|
4325
|
-
/** Compact context with line ranges */
|
|
4326
|
-
compact;
|
|
4327
|
-
/**
|
|
4328
|
-
* Create a new Morph SDK client
|
|
4329
|
-
*
|
|
4330
|
-
* @param config - Client configuration (apiKey, debug, timeout, retryConfig)
|
|
4331
|
-
*
|
|
4332
|
-
* @example
|
|
4333
|
-
* ```typescript
|
|
4334
|
-
* const morph = new MorphClient({
|
|
4335
|
-
* apiKey: process.env.MORPH_API_KEY,
|
|
4336
|
-
* debug: true,
|
|
4337
|
-
* timeout: 60000
|
|
4338
|
-
* });
|
|
4339
|
-
* ```
|
|
4340
|
-
*/
|
|
4341
|
-
constructor(config = {}) {
|
|
4342
|
-
super({
|
|
4343
|
-
apiKey: config.apiKey,
|
|
4344
|
-
timeout: config.timeout,
|
|
4345
|
-
retryConfig: config.retryConfig,
|
|
4346
|
-
debug: config.debug
|
|
4347
|
-
});
|
|
4348
|
-
if (!config.apiKey) {
|
|
4349
|
-
throw new Error("Morph API key is required. Pass it as { apiKey } when constructing MorphClient.");
|
|
4350
|
-
}
|
|
4351
|
-
this.config = config;
|
|
4352
|
-
logger.debug("MorphClient", "initialized", { debug: !!config.debug, timeout: config.timeout });
|
|
4353
|
-
this.fastApply = new FastApplyClient(this);
|
|
4354
|
-
this.warpGrep = new WarpGrepClient(this);
|
|
4355
|
-
this.routers = {
|
|
4356
|
-
openai: new OpenAIRouter(this),
|
|
4357
|
-
anthropic: new AnthropicRouter(this),
|
|
4358
|
-
gemini: new GeminiRouter(this),
|
|
4359
|
-
raw: new RawRouter(this),
|
|
4360
|
-
classify: new RouterClassifier(this)
|
|
4361
|
-
};
|
|
4362
|
-
const compactClient = new CompactClient(this);
|
|
4363
|
-
this.compact = compactClient.compact.bind(compactClient);
|
|
4364
|
-
this.openai = new OpenAIToolFactory(config);
|
|
4365
|
-
this.anthropic = new AnthropicToolFactory(config);
|
|
4366
|
-
this.vercel = new VercelToolFactory(config);
|
|
4367
|
-
}
|
|
4368
|
-
};
|
|
4369
|
-
|
|
4370
|
-
// tools/warp_grep/index.ts
|
|
4371
|
-
var import_zod4 = require("zod");
|
|
4372
|
-
|
|
4373
|
-
// tools/warp_grep/providers/index.ts
|
|
4374
|
-
init_local();
|
|
4375
|
-
|
|
4376
|
-
// tools/warp_grep/index.ts
|
|
4377
|
-
init_paths();
|
|
4378
|
-
|
|
4379
|
-
// tools/warp_grep/agent/index.ts
|
|
4380
|
-
init_config();
|
|
4381
|
-
|
|
4382
|
-
// tools/warp_grep/agent/formatter.ts
|
|
4383
|
-
var ToolOutputFormatter = class {
|
|
4384
|
-
format(toolName, _args, output, options = {}) {
|
|
4385
|
-
const name = (toolName ?? "").trim();
|
|
4386
|
-
if (!name) {
|
|
4387
|
-
return "";
|
|
4388
|
-
}
|
|
4389
|
-
const payload = output?.toString?.()?.trim?.() ?? "";
|
|
4390
|
-
const isError = Boolean(options.isError);
|
|
4391
|
-
if (!payload && !isError) {
|
|
4392
|
-
return "";
|
|
4393
|
-
}
|
|
4394
|
-
return `<tool_response>
|
|
4395
|
-
${payload}
|
|
4396
|
-
</tool_response>`;
|
|
4397
|
-
}
|
|
4398
|
-
};
|
|
4399
|
-
var sharedFormatter = new ToolOutputFormatter();
|
|
4400
|
-
|
|
4401
|
-
// tools/warp_grep/index.ts
|
|
4402
|
-
var warpGrepInputSchema = import_zod4.z.object({
|
|
4403
|
-
search_term: import_zod4.z.string().describe("Search problem statement that this subagent is supposed to research for")
|
|
4404
|
-
});
|
|
4405
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
4406
|
-
0 && (module.exports = {
|
|
4407
|
-
APIResource,
|
|
4408
|
-
AnthropicRouter,
|
|
4409
|
-
AnthropicToolFactory,
|
|
4410
|
-
CompactClient,
|
|
4411
|
-
FastApplyAnchorIntegrityError,
|
|
4412
|
-
FastApplyClient,
|
|
4413
|
-
FastApplyContextLengthError,
|
|
4414
|
-
GeminiRouter,
|
|
4415
|
-
LocalRipgrepProvider,
|
|
4416
|
-
MorphAPIClient,
|
|
4417
|
-
MorphClient,
|
|
4418
|
-
OpenAIRouter,
|
|
4419
|
-
OpenAIToolFactory,
|
|
4420
|
-
RawRouter,
|
|
4421
|
-
SDK_VERSION,
|
|
4422
|
-
VercelToolFactory,
|
|
4423
|
-
WarpGrepClient,
|
|
4424
|
-
applyEdit
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
require('./chunk-IPJA3ZS6.cjs');
|
|
4
|
+
var chunkOOEORM7H_cjs = require('./chunk-OOEORM7H.cjs');
|
|
5
|
+
require('./chunk-XE6D4J63.cjs');
|
|
6
|
+
require('./chunk-NNKBKENK.cjs');
|
|
7
|
+
require('./chunk-QEEAIXL5.cjs');
|
|
8
|
+
require('./chunk-UF5IKELS.cjs');
|
|
9
|
+
var chunkGSUQGDCL_cjs = require('./chunk-GSUQGDCL.cjs');
|
|
10
|
+
require('./chunk-KSZYOX6S.cjs');
|
|
11
|
+
require('./chunk-S6QBPXBI.cjs');
|
|
12
|
+
require('./chunk-7NA7X7W2.cjs');
|
|
13
|
+
require('./chunk-EJTL2BOZ.cjs');
|
|
14
|
+
require('./chunk-OXXMTDOY.cjs');
|
|
15
|
+
require('./chunk-JNQKQKHS.cjs');
|
|
16
|
+
require('./chunk-NDUC7OV6.cjs');
|
|
17
|
+
require('./chunk-74A4HLIO.cjs');
|
|
18
|
+
var chunkJBTR3FQD_cjs = require('./chunk-JBTR3FQD.cjs');
|
|
19
|
+
require('./chunk-4R5MDGL6.cjs');
|
|
20
|
+
require('./chunk-B3FD67F2.cjs');
|
|
21
|
+
var chunkUUCRWJJR_cjs = require('./chunk-UUCRWJJR.cjs');
|
|
22
|
+
require('./chunk-VHD7CW5O.cjs');
|
|
23
|
+
require('./chunk-WR7LSUIR.cjs');
|
|
24
|
+
require('./chunk-MWXJ6DZ2.cjs');
|
|
25
|
+
require('./chunk-HMLYJVZM.cjs');
|
|
26
|
+
require('./chunk-KVGZ2TSG.cjs');
|
|
27
|
+
require('./chunk-4EQQGUZ7.cjs');
|
|
28
|
+
require('./chunk-UNX7V6P6.cjs');
|
|
29
|
+
require('./chunk-ODY2NKQU.cjs');
|
|
30
|
+
require('./chunk-TPZHMD7J.cjs');
|
|
31
|
+
var chunkVDFLPO7B_cjs = require('./chunk-VDFLPO7B.cjs');
|
|
32
|
+
var chunkJOZC4T6C_cjs = require('./chunk-JOZC4T6C.cjs');
|
|
33
|
+
var chunkAFF6XYKL_cjs = require('./chunk-AFF6XYKL.cjs');
|
|
34
|
+
require('./chunk-7PJYY46L.cjs');
|
|
35
|
+
var chunk65W4I66Q_cjs = require('./chunk-65W4I66Q.cjs');
|
|
36
|
+
require('./chunk-VL4QNALG.cjs');
|
|
37
|
+
require('./chunk-ZLG2M2I4.cjs');
|
|
38
|
+
require('./chunk-OM5ZSXQW.cjs');
|
|
39
|
+
var chunkTL34BLQD_cjs = require('./chunk-TL34BLQD.cjs');
|
|
40
|
+
var chunkAWFZKS27_cjs = require('./chunk-AWFZKS27.cjs');
|
|
41
|
+
require('./chunk-75ZPJI57.cjs');
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
Object.defineProperty(exports, "LocalRipgrepProvider", {
|
|
46
|
+
enumerable: true,
|
|
47
|
+
get: function () { return chunkOOEORM7H_cjs.LocalRipgrepProvider; }
|
|
48
|
+
});
|
|
49
|
+
Object.defineProperty(exports, "AnthropicToolFactory", {
|
|
50
|
+
enumerable: true,
|
|
51
|
+
get: function () { return chunkGSUQGDCL_cjs.AnthropicToolFactory; }
|
|
52
|
+
});
|
|
53
|
+
Object.defineProperty(exports, "MorphClient", {
|
|
54
|
+
enumerable: true,
|
|
55
|
+
get: function () { return chunkGSUQGDCL_cjs.MorphClient; }
|
|
56
|
+
});
|
|
57
|
+
Object.defineProperty(exports, "OpenAIToolFactory", {
|
|
58
|
+
enumerable: true,
|
|
59
|
+
get: function () { return chunkGSUQGDCL_cjs.OpenAIToolFactory; }
|
|
60
|
+
});
|
|
61
|
+
Object.defineProperty(exports, "VercelToolFactory", {
|
|
62
|
+
enumerable: true,
|
|
63
|
+
get: function () { return chunkGSUQGDCL_cjs.VercelToolFactory; }
|
|
64
|
+
});
|
|
65
|
+
Object.defineProperty(exports, "FastApplyClient", {
|
|
66
|
+
enumerable: true,
|
|
67
|
+
get: function () { return chunkJBTR3FQD_cjs.FastApplyClient; }
|
|
68
|
+
});
|
|
69
|
+
Object.defineProperty(exports, "WarpGrepClient", {
|
|
70
|
+
enumerable: true,
|
|
71
|
+
get: function () { return chunkUUCRWJJR_cjs.WarpGrepClient; }
|
|
72
|
+
});
|
|
73
|
+
Object.defineProperty(exports, "FastApplyAnchorIntegrityError", {
|
|
74
|
+
enumerable: true,
|
|
75
|
+
get: function () { return chunkVDFLPO7B_cjs.FastApplyAnchorIntegrityError; }
|
|
76
|
+
});
|
|
77
|
+
Object.defineProperty(exports, "FastApplyContextLengthError", {
|
|
78
|
+
enumerable: true,
|
|
79
|
+
get: function () { return chunkVDFLPO7B_cjs.FastApplyContextLengthError; }
|
|
80
|
+
});
|
|
81
|
+
Object.defineProperty(exports, "applyEdit", {
|
|
82
|
+
enumerable: true,
|
|
83
|
+
get: function () { return chunkVDFLPO7B_cjs.applyEdit; }
|
|
84
|
+
});
|
|
85
|
+
Object.defineProperty(exports, "AnthropicRouter", {
|
|
86
|
+
enumerable: true,
|
|
87
|
+
get: function () { return chunkJOZC4T6C_cjs.AnthropicRouter; }
|
|
88
|
+
});
|
|
89
|
+
Object.defineProperty(exports, "GeminiRouter", {
|
|
90
|
+
enumerable: true,
|
|
91
|
+
get: function () { return chunkJOZC4T6C_cjs.GeminiRouter; }
|
|
92
|
+
});
|
|
93
|
+
Object.defineProperty(exports, "OpenAIRouter", {
|
|
94
|
+
enumerable: true,
|
|
95
|
+
get: function () { return chunkJOZC4T6C_cjs.OpenAIRouter; }
|
|
96
|
+
});
|
|
97
|
+
Object.defineProperty(exports, "RawRouter", {
|
|
98
|
+
enumerable: true,
|
|
99
|
+
get: function () { return chunkJOZC4T6C_cjs.RawRouter; }
|
|
100
|
+
});
|
|
101
|
+
Object.defineProperty(exports, "CompactClient", {
|
|
102
|
+
enumerable: true,
|
|
103
|
+
get: function () { return chunkAFF6XYKL_cjs.CompactClient; }
|
|
104
|
+
});
|
|
105
|
+
Object.defineProperty(exports, "MorphAPIClient", {
|
|
106
|
+
enumerable: true,
|
|
107
|
+
get: function () { return chunk65W4I66Q_cjs.MorphAPIClient; }
|
|
108
|
+
});
|
|
109
|
+
Object.defineProperty(exports, "SDK_VERSION", {
|
|
110
|
+
enumerable: true,
|
|
111
|
+
get: function () { return chunkTL34BLQD_cjs.SDK_VERSION; }
|
|
112
|
+
});
|
|
113
|
+
Object.defineProperty(exports, "APIResource", {
|
|
114
|
+
enumerable: true,
|
|
115
|
+
get: function () { return chunkAWFZKS27_cjs.APIResource; }
|
|
4425
116
|
});
|