@morphllm/morphsdk 0.2.202 → 0.2.204
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +101 -0
- package/dist/chunk-2GMG5XKU.js +100 -0
- package/dist/chunk-2PPYWRMZ.js +3 -4
- package/dist/chunk-3HAHJYZQ.cjs +74 -0
- package/dist/{chunk-2XU3XXUE.js → chunk-3JROKKS4.js} +3 -25
- package/dist/{chunk-26K5EJD3.js → chunk-43JBUEIX.js} +4 -18
- package/dist/chunk-44OIEPIO.js +4 -23
- package/dist/chunk-4EQQGUZ7.cjs +104 -0
- package/dist/chunk-4OUGA3KS.js +1 -5
- package/dist/{chunk-VQDDL3UH.js → chunk-4TZBUFVP.js} +2 -8
- package/dist/{chunk-YAM6P5OQ.js → chunk-564XJOQP.js} +2 -6
- package/dist/chunk-5H3FKFOI.cjs +77 -0
- package/dist/chunk-5TTZQF4X.cjs +110 -0
- package/dist/chunk-6HAYJA6M.cjs +317 -0
- 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-7PJYY46L.cjs +2 -0
- package/dist/chunk-AWFZKS27.cjs +11 -0
- package/dist/chunk-BJBWWIZV.cjs +2 -0
- package/dist/chunk-DLYDIYDK.cjs +305 -0
- package/dist/{chunk-65TUD7JV.js → chunk-DYCMPDPV.js} +13 -29
- package/dist/{chunk-3CPI6ZIC.js → chunk-DZP7BR66.js} +22 -43
- package/dist/chunk-E63OPKP7.js +96 -0
- package/dist/chunk-E6V75LI6.cjs +334 -0
- package/dist/{chunk-XPHNS7NW.js → chunk-EJ6ID24K.js} +3 -12
- package/dist/chunk-EJTL2BOZ.cjs +42 -0
- package/dist/chunk-ETBRAKVV.js +1 -5
- package/dist/chunk-F633IVQA.cjs +91 -0
- package/dist/chunk-FBOZIVVQ.js +1 -0
- package/dist/{chunk-UKXCGQPS.js → chunk-FGA6EYC2.js} +35 -37
- package/dist/{chunk-CAWQEHKP.js → chunk-G4RODMXA.js} +4 -19
- package/dist/chunk-GUNGJC6X.cjs +256 -0
- package/dist/chunk-GYE3FY6Z.js +8 -0
- package/dist/chunk-HDP4QAZL.js +1 -4
- package/dist/chunk-HNMEBYIS.cjs +86 -0
- package/dist/chunk-HP3PCOTW.cjs +81 -0
- package/dist/{chunk-ICCGLO6V.js → chunk-IGXNLXPN.js} +12 -17
- package/dist/chunk-IPJA3ZS6.cjs +10 -0
- package/dist/chunk-JHC2R3HU.cjs +317 -0
- package/dist/{chunk-IBRBSDLT.js → chunk-JVMIFGZY.js} +5 -8
- package/dist/chunk-KF6S3EPJ.cjs +100 -0
- package/dist/chunk-KVGZ2TSG.cjs +274 -0
- package/dist/{chunk-6OYJC4TZ.js → chunk-L5SCKZVK.js} +13 -22
- package/dist/chunk-LDM7RNNN.js +1 -0
- package/dist/{chunk-UAZKHSEU.js → chunk-LQST3NW2.js} +5 -15
- package/dist/chunk-M34E2AMK.js +1 -5
- package/dist/chunk-MF56KEI4.js +1 -4
- package/dist/chunk-MLKGABMK.js +1 -3
- package/dist/chunk-MLPZKUCO.js +4 -5
- package/dist/chunk-MMX5PUGC.cjs +242 -0
- package/dist/chunk-MWXJ6DZ2.cjs +21 -0
- package/dist/chunk-NJWOWXUR.cjs +137 -0
- package/dist/chunk-NNKBKENK.cjs +15 -0
- package/dist/chunk-NRG6QX3L.js +1 -3
- package/dist/chunk-OCKEEEYE.cjs +433 -0
- package/dist/chunk-OENJO7YW.js +306 -0
- package/dist/chunk-OKLAYEBC.cjs +2 -0
- package/dist/chunk-OPDWMD4Q.js +1 -3
- package/dist/{chunk-D6YJ5X3C.js → chunk-OX5GN2KB.js} +26 -14
- package/dist/{chunk-JEVLCA5C.js → chunk-OYBOP47A.js} +18 -19
- package/dist/chunk-OZHCHPIE.js +1 -0
- package/dist/chunk-PA3UTI4A.js +1 -4
- package/dist/chunk-QEEAIXL5.cjs +74 -0
- package/dist/chunk-QT5LGZG3.cjs +10 -0
- package/dist/chunk-R3TUE7O2.cjs +107 -0
- package/dist/chunk-RYVW7RUM.js +2 -6
- package/dist/{chunk-LVKKICOB.js → chunk-SOQYE5A4.js} +36 -69
- package/dist/chunk-ST2OXLT5.cjs +91 -0
- package/dist/{chunk-SIFDK4AA.js → chunk-TH4MG73B.js} +3 -24
- package/dist/{chunk-OSL4CNSO.js → chunk-TLMAMVAW.js} +7 -23
- package/dist/chunk-TPZHMD7J.cjs +72 -0
- package/dist/{chunk-PDSIWL7I.js → chunk-U4PYAGNR.js} +6 -19
- package/dist/chunk-UAPK3AIJ.js +1 -10
- package/dist/chunk-UF5IKELS.cjs +26 -0
- package/dist/chunk-UHFVWYSP.cjs +408 -0
- package/dist/chunk-UKBSXYKE.cjs +280 -0
- package/dist/chunk-UNX7V6P6.cjs +60 -0
- package/dist/chunk-UZMMJ47A.cjs +107 -0
- package/dist/chunk-VHD7CW5O.cjs +43 -0
- package/dist/chunk-VL4QNALG.cjs +50 -0
- package/dist/chunk-VYE7O4FM.cjs +51 -0
- package/dist/chunk-WIYVT4UO.cjs +173 -0
- package/dist/chunk-WJHHO24M.cjs +91 -0
- package/dist/chunk-WR7LSUIR.cjs +213 -0
- package/dist/chunk-XE6D4J63.cjs +72 -0
- package/dist/chunk-YAUXTFIN.cjs +21 -0
- package/dist/{chunk-NFPRKZQ5.js → chunk-YJUCGZNN.js} +5 -22
- package/dist/chunk-ZSHVXDA2.js +4 -10
- package/dist/chunk-ZX6T3LNG.js +302 -0
- package/dist/{client-BWhi-vSj.d.ts → client-DSXbcxII.d.ts} +10 -1
- package/dist/client.cjs +44 -4360
- package/dist/client.d.ts +4 -2
- package/dist/client.js +36 -37
- package/dist/core/client.cjs +14 -476
- package/dist/core/client.d.ts +8 -0
- package/dist/core/client.js +10 -11
- package/dist/core/error.cjs +8 -251
- package/dist/core/error.js +4 -9
- package/dist/core/index.cjs +27 -491
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +12 -19
- package/dist/core/resource.cjs +9 -33
- package/dist/core/resource.d.ts +2 -0
- package/dist/core/resource.js +2 -7
- package/dist/edge.cjs +74 -1111
- package/dist/edge.d.ts +3 -0
- package/dist/edge.js +14 -42
- package/dist/guard-CvW03v4u.d.ts +59 -0
- package/dist/index.cjs +140 -4431
- package/dist/index.d.ts +6 -2
- package/dist/index.js +44 -87
- package/dist/modelrouter/core.cjs +35 -651
- package/dist/modelrouter/core.d.ts +2 -0
- package/dist/modelrouter/core.js +12 -21
- package/dist/modelrouter/index.cjs +35 -651
- package/dist/modelrouter/index.d.ts +2 -0
- package/dist/modelrouter/index.js +12 -21
- package/dist/modelrouter/types.cjs +1 -17
- package/dist/modelrouter/types.d.ts +5 -0
- package/dist/modelrouter/types.js +1 -0
- package/dist/subagents/anthropic.cjs +31 -2784
- package/dist/subagents/anthropic.d.ts +3 -1
- package/dist/subagents/anthropic.js +23 -24
- package/dist/subagents/index.cjs +14 -95
- package/dist/subagents/index.d.ts +3 -1
- package/dist/subagents/index.js +2 -11
- package/dist/subagents/prompts.cjs +14 -93
- package/dist/subagents/prompts.d.ts +3 -1
- package/dist/subagents/prompts.js +2 -11
- package/dist/subagents/types.cjs +1 -17
- package/dist/subagents/types.d.ts +3 -1
- package/dist/subagents/types.js +1 -0
- package/dist/subagents/vercel.cjs +31 -2761
- package/dist/subagents/vercel.d.ts +3 -1
- package/dist/subagents/vercel.js +23 -24
- package/dist/tools/compact/core.cjs +20 -552
- package/dist/tools/compact/core.d.ts +2 -0
- package/dist/tools/compact/core.js +12 -13
- package/dist/tools/compact/index.cjs +24 -598
- package/dist/tools/compact/index.d.ts +3 -1
- package/dist/tools/compact/index.js +13 -17
- package/dist/tools/compact/types.cjs +1 -17
- package/dist/tools/compact/types.d.ts +4 -4
- package/dist/tools/compact/types.js +1 -0
- package/dist/tools/fastapply/anthropic.cjs +39 -899
- package/dist/tools/fastapply/anthropic.d.ts +2 -0
- package/dist/tools/fastapply/anthropic.js +15 -24
- package/dist/tools/fastapply/apply.cjs +32 -672
- package/dist/tools/fastapply/apply.d.ts +2 -0
- package/dist/tools/fastapply/apply.js +8 -19
- package/dist/tools/fastapply/core.cjs +49 -1069
- package/dist/tools/fastapply/core.d.ts +3 -0
- package/dist/tools/fastapply/core.js +13 -29
- package/dist/tools/fastapply/index.cjs +56 -1052
- package/dist/tools/fastapply/index.d.ts +2 -0
- package/dist/tools/fastapply/index.js +18 -44
- package/dist/tools/fastapply/openai.cjs +45 -910
- package/dist/tools/fastapply/openai.d.ts +2 -0
- package/dist/tools/fastapply/openai.js +15 -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.d.ts +9 -4
- package/dist/tools/fastapply/types.js +1 -0
- package/dist/tools/fastapply/vercel.cjs +37 -905
- package/dist/tools/fastapply/vercel.d.ts +2 -0
- package/dist/tools/fastapply/vercel.js +15 -22
- package/dist/tools/index.cjs +56 -1052
- package/dist/tools/index.d.ts +2 -0
- package/dist/tools/index.js +18 -44
- package/dist/tools/pii/index.cjs +47 -0
- package/dist/tools/pii/index.d.ts +4 -0
- package/dist/tools/pii/index.js +6 -0
- package/dist/tools/pii/model.cjs +45 -0
- package/dist/tools/pii/model.d.ts +83 -0
- package/dist/tools/pii/model.js +4 -0
- package/dist/tools/pii/patterns.cjs +15 -0
- package/dist/tools/pii/patterns.d.ts +31 -0
- package/dist/tools/pii/patterns.js +2 -0
- package/dist/tools/pii/regex.cjs +32 -0
- package/dist/tools/pii/regex.d.ts +48 -0
- package/dist/tools/pii/regex.js +3 -0
- package/dist/tools/pii/types.cjs +2 -0
- package/dist/tools/pii/types.d.ts +108 -0
- package/dist/tools/pii/types.js +1 -0
- 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.d.ts +2 -0
- package/dist/tools/warp_grep/agent/parser.js +2 -11
- package/dist/tools/warp_grep/agent/runner.cjs +19 -1081
- package/dist/tools/warp_grep/agent/runner.d.ts +2 -0
- package/dist/tools/warp_grep/agent/runner.js +11 -14
- package/dist/tools/warp_grep/agent/types.cjs +1 -17
- package/dist/tools/warp_grep/agent/types.d.ts +4 -0
- package/dist/tools/warp_grep/agent/types.js +1 -0
- package/dist/tools/warp_grep/anthropic.cjs +51 -2561
- package/dist/tools/warp_grep/anthropic.d.ts +3 -1
- package/dist/tools/warp_grep/anthropic.js +23 -35
- package/dist/tools/warp_grep/client.cjs +53 -2471
- package/dist/tools/warp_grep/client.d.ts +3 -1
- package/dist/tools/warp_grep/client.js +21 -34
- package/dist/tools/warp_grep/gemini.cjs +52 -2490
- package/dist/tools/warp_grep/gemini.d.ts +3 -1
- package/dist/tools/warp_grep/gemini.js +25 -41
- package/dist/tools/warp_grep/harness.cjs +81 -936
- package/dist/tools/warp_grep/harness.d.ts +2 -0
- package/dist/tools/warp_grep/harness.js +12 -51
- package/dist/tools/warp_grep/index.cjs +128 -2575
- package/dist/tools/warp_grep/index.d.ts +3 -1
- package/dist/tools/warp_grep/index.js +28 -87
- package/dist/tools/warp_grep/openai.cjs +57 -2575
- package/dist/tools/warp_grep/openai.d.ts +3 -1
- package/dist/tools/warp_grep/openai.js +23 -37
- package/dist/tools/warp_grep/providers/code_storage_http.cjs +12 -65
- package/dist/tools/warp_grep/providers/code_storage_http.d.ts +3 -1
- package/dist/tools/warp_grep/providers/code_storage_http.js +2 -9
- package/dist/tools/warp_grep/providers/local.cjs +10 -589
- 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.d.ts +3 -1
- 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 -103
- package/dist/tools/warp_grep/utils/ripgrep.js +2 -7
- package/dist/tools/warp_grep/vercel.cjs +57 -2557
- package/dist/tools/warp_grep/vercel.d.ts +3 -1
- package/dist/tools/warp_grep/vercel.js +23 -37
- package/dist/{types-DxZLPogx.d.ts → types-BKhXjDCB.d.ts} +6 -1
- package/dist/version.cjs +7 -225
- package/dist/version.js +2 -7
- package/package.json +11 -2
- package/dist/chunk-E6TL6MIH.js +0 -203
|
@@ -1,2469 +1,29 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
var
|
|
6
|
-
var
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
28
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
29
|
-
mod
|
|
30
|
-
));
|
|
31
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
|
-
|
|
33
|
-
// tools/warp_grep/agent/config.ts
|
|
34
|
-
var parseEnvTimeout, AGENT_CONFIG, BUILTIN_EXCLUDES, DEFAULT_EXCLUDES, DEFAULT_MODEL;
|
|
35
|
-
var init_config = __esm({
|
|
36
|
-
"tools/warp_grep/agent/config.ts"() {
|
|
37
|
-
"use strict";
|
|
38
|
-
parseEnvTimeout = (envValue, defaultMs) => {
|
|
39
|
-
if (!envValue) return defaultMs;
|
|
40
|
-
const parsed = parseInt(envValue, 10);
|
|
41
|
-
return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;
|
|
42
|
-
};
|
|
43
|
-
AGENT_CONFIG = {
|
|
44
|
-
MAX_TURNS: 6,
|
|
45
|
-
/** Default timeout for model calls. Can be overridden via MORPH_WARP_GREP_TIMEOUT env var (in ms) */
|
|
46
|
-
TIMEOUT_MS: parseEnvTimeout(process.env.MORPH_WARP_GREP_TIMEOUT, 6e4),
|
|
47
|
-
MAX_CONTEXT_CHARS: 321600,
|
|
48
|
-
MAX_OUTPUT_LINES: 200,
|
|
49
|
-
MAX_LIST_RESULTS: 500,
|
|
50
|
-
MAX_READ_LINES: 800,
|
|
51
|
-
MAX_LIST_DEPTH: 3,
|
|
52
|
-
LIST_TIMEOUT_MS: 2e3
|
|
53
|
-
};
|
|
54
|
-
BUILTIN_EXCLUDES = [
|
|
55
|
-
// Version control
|
|
56
|
-
".git",
|
|
57
|
-
".svn",
|
|
58
|
-
".hg",
|
|
59
|
-
".bzr",
|
|
60
|
-
// Dependencies
|
|
61
|
-
"node_modules",
|
|
62
|
-
"bower_components",
|
|
63
|
-
".pnpm",
|
|
64
|
-
".yarn",
|
|
65
|
-
"vendor",
|
|
66
|
-
"packages",
|
|
67
|
-
"Pods",
|
|
68
|
-
".bundle",
|
|
69
|
-
// Python
|
|
70
|
-
"__pycache__",
|
|
71
|
-
".pytest_cache",
|
|
72
|
-
".mypy_cache",
|
|
73
|
-
".ruff_cache",
|
|
74
|
-
".venv",
|
|
75
|
-
"venv",
|
|
76
|
-
".tox",
|
|
77
|
-
".nox",
|
|
78
|
-
".eggs",
|
|
79
|
-
"*.egg-info",
|
|
80
|
-
// Build outputs
|
|
81
|
-
"dist",
|
|
82
|
-
"build",
|
|
83
|
-
"out",
|
|
84
|
-
"output",
|
|
85
|
-
"target",
|
|
86
|
-
"_build",
|
|
87
|
-
".next",
|
|
88
|
-
".nuxt",
|
|
89
|
-
".output",
|
|
90
|
-
".vercel",
|
|
91
|
-
".netlify",
|
|
92
|
-
// Cache directories
|
|
93
|
-
".cache",
|
|
94
|
-
".parcel-cache",
|
|
95
|
-
".turbo",
|
|
96
|
-
".nx",
|
|
97
|
-
".gradle",
|
|
98
|
-
// IDE/Editor
|
|
99
|
-
".idea",
|
|
100
|
-
".vscode",
|
|
101
|
-
".vs",
|
|
102
|
-
// Coverage
|
|
103
|
-
"coverage",
|
|
104
|
-
".coverage",
|
|
105
|
-
"htmlcov",
|
|
106
|
-
".nyc_output",
|
|
107
|
-
// Temporary
|
|
108
|
-
"tmp",
|
|
109
|
-
"temp",
|
|
110
|
-
".tmp",
|
|
111
|
-
".temp",
|
|
112
|
-
// Lock files
|
|
113
|
-
"package-lock.json",
|
|
114
|
-
"yarn.lock",
|
|
115
|
-
"pnpm-lock.yaml",
|
|
116
|
-
"bun.lockb",
|
|
117
|
-
"Cargo.lock",
|
|
118
|
-
"Gemfile.lock",
|
|
119
|
-
"poetry.lock",
|
|
120
|
-
// Binary/minified
|
|
121
|
-
"*.min.js",
|
|
122
|
-
"*.min.css",
|
|
123
|
-
"*.bundle.js",
|
|
124
|
-
"*.wasm",
|
|
125
|
-
"*.so",
|
|
126
|
-
"*.dll",
|
|
127
|
-
"*.pyc",
|
|
128
|
-
"*.map",
|
|
129
|
-
"*.js.map",
|
|
130
|
-
// Hidden directories catch-all
|
|
131
|
-
".*"
|
|
132
|
-
];
|
|
133
|
-
DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || "").split(",").map((s) => s.trim()).filter(Boolean).concat(BUILTIN_EXCLUDES);
|
|
134
|
-
DEFAULT_MODEL = "morph-warp-grep-v2.1";
|
|
135
|
-
}
|
|
136
|
-
});
|
|
137
|
-
|
|
138
|
-
// tools/warp_grep/utils/ripgrep.ts
|
|
139
|
-
function spawnRg(rgBinary, args, opts) {
|
|
140
|
-
return new Promise((resolve) => {
|
|
141
|
-
const child = (0, import_child_process.spawn)(rgBinary, args, {
|
|
142
|
-
cwd: opts?.cwd,
|
|
143
|
-
env: { ...process.env, ...opts?.env || {} },
|
|
144
|
-
stdio: ["ignore", "pipe", "pipe"]
|
|
145
|
-
});
|
|
146
|
-
let stdout = "";
|
|
147
|
-
let stderr = "";
|
|
148
|
-
child.stdout.on("data", (d) => stdout += d.toString());
|
|
149
|
-
child.stderr.on("data", (d) => stderr += d.toString());
|
|
150
|
-
child.on("close", (code) => {
|
|
151
|
-
resolve({ stdout, stderr, exitCode: typeof code === "number" ? code : -1 });
|
|
152
|
-
});
|
|
153
|
-
child.on("error", () => {
|
|
154
|
-
resolve({ stdout: "", stderr: "Failed to spawn ripgrep.", exitCode: -1 });
|
|
155
|
-
});
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
async function preferredRgPath() {
|
|
159
|
-
try {
|
|
160
|
-
return (await import("@vscode/ripgrep")).rgPath ?? "rg";
|
|
161
|
-
} catch {
|
|
162
|
-
return "rg";
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
function isBinaryFailure(result) {
|
|
166
|
-
if (result.exitCode === -1) return true;
|
|
167
|
-
if (result.stderr.includes("jemalloc") || result.stderr.includes("Unsupported system page size")) return true;
|
|
168
|
-
if (result.exitCode === 134) return true;
|
|
169
|
-
return false;
|
|
170
|
-
}
|
|
171
|
-
async function runRipgrep(args, opts) {
|
|
172
|
-
if (rgPathChecked && resolvedRgPath) {
|
|
173
|
-
return spawnRg(resolvedRgPath, args, opts);
|
|
174
|
-
}
|
|
175
|
-
if (!rgPathChecked) {
|
|
176
|
-
const rgPath = await preferredRgPath();
|
|
177
|
-
const result = await spawnRg(rgPath, args, opts);
|
|
178
|
-
if (!isBinaryFailure(result)) {
|
|
179
|
-
resolvedRgPath = rgPath;
|
|
180
|
-
rgPathChecked = true;
|
|
181
|
-
return result;
|
|
182
|
-
}
|
|
183
|
-
const fallbackResult = await spawnRg("rg", args, opts);
|
|
184
|
-
if (!isBinaryFailure(fallbackResult)) {
|
|
185
|
-
resolvedRgPath = "rg";
|
|
186
|
-
rgPathChecked = true;
|
|
187
|
-
return fallbackResult;
|
|
188
|
-
}
|
|
189
|
-
rgPathChecked = true;
|
|
190
|
-
return {
|
|
191
|
-
stdout: "",
|
|
192
|
-
stderr: "Failed to spawn ripgrep. Neither bundled nor system rg is available.",
|
|
193
|
-
exitCode: -1
|
|
194
|
-
};
|
|
195
|
-
}
|
|
196
|
-
return {
|
|
197
|
-
stdout: "",
|
|
198
|
-
stderr: "Failed to spawn ripgrep. Neither bundled nor system rg is available.",
|
|
199
|
-
exitCode: -1
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
var import_child_process, resolvedRgPath, rgPathChecked;
|
|
203
|
-
var init_ripgrep = __esm({
|
|
204
|
-
"tools/warp_grep/utils/ripgrep.ts"() {
|
|
205
|
-
"use strict";
|
|
206
|
-
import_child_process = require("child_process");
|
|
207
|
-
resolvedRgPath = null;
|
|
208
|
-
rgPathChecked = false;
|
|
209
|
-
}
|
|
210
|
-
});
|
|
211
|
-
|
|
212
|
-
// tools/warp_grep/utils/paths.ts
|
|
213
|
-
function resolveUnderRepo(repoRoot, targetPath) {
|
|
214
|
-
const absRoot = import_path4.default.resolve(repoRoot);
|
|
215
|
-
const resolved = import_path4.default.resolve(absRoot, targetPath);
|
|
216
|
-
ensureWithinRepo(absRoot, resolved);
|
|
217
|
-
return resolved;
|
|
218
|
-
}
|
|
219
|
-
function ensureWithinRepo(repoRoot, absTarget) {
|
|
220
|
-
const rel = import_path4.default.relative(import_path4.default.resolve(repoRoot), import_path4.default.resolve(absTarget));
|
|
221
|
-
if (rel.startsWith("..") || import_path4.default.isAbsolute(rel)) {
|
|
222
|
-
throw new Error(`Path outside repository root: ${absTarget}`);
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
function toRepoRelative2(repoRoot, absPath) {
|
|
226
|
-
return import_path4.default.relative(import_path4.default.resolve(repoRoot), import_path4.default.resolve(absPath));
|
|
227
|
-
}
|
|
228
|
-
function isSymlink(p) {
|
|
229
|
-
try {
|
|
230
|
-
const st = import_fs.default.lstatSync(p);
|
|
231
|
-
return st.isSymbolicLink();
|
|
232
|
-
} catch {
|
|
233
|
-
return false;
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
function fixPathRepetition(fullPath) {
|
|
237
|
-
const segments = fullPath.split(import_path4.default.sep).filter(Boolean);
|
|
238
|
-
if (segments.length < 2) return null;
|
|
239
|
-
for (let len = Math.floor(segments.length / 2); len >= 1; len--) {
|
|
240
|
-
for (let i = 0; i <= segments.length - 2 * len; i++) {
|
|
241
|
-
const first = segments.slice(i, i + len);
|
|
242
|
-
const second = segments.slice(i + len, i + 2 * len);
|
|
243
|
-
if (first.every((seg, idx) => seg === second[idx])) {
|
|
244
|
-
const fixed = [...segments.slice(0, i), ...segments.slice(i + len)];
|
|
245
|
-
return import_path4.default.sep + fixed.join(import_path4.default.sep);
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
return null;
|
|
250
|
-
}
|
|
251
|
-
function isTextualFile(filePath, maxBytes = 2e6) {
|
|
252
|
-
try {
|
|
253
|
-
const st = import_fs.default.statSync(filePath);
|
|
254
|
-
if (!st.isFile()) return false;
|
|
255
|
-
if (st.size > maxBytes) return false;
|
|
256
|
-
const fd = import_fs.default.openSync(filePath, "r");
|
|
257
|
-
const buf = Buffer.alloc(512);
|
|
258
|
-
const read = import_fs.default.readSync(fd, buf, 0, buf.length, 0);
|
|
259
|
-
import_fs.default.closeSync(fd);
|
|
260
|
-
for (let i = 0; i < read; i++) {
|
|
261
|
-
const c = buf[i];
|
|
262
|
-
if (c === 0) return false;
|
|
263
|
-
}
|
|
264
|
-
return true;
|
|
265
|
-
} catch {
|
|
266
|
-
return false;
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
var import_fs, import_path4;
|
|
270
|
-
var init_paths = __esm({
|
|
271
|
-
"tools/warp_grep/utils/paths.ts"() {
|
|
272
|
-
"use strict";
|
|
273
|
-
import_fs = __toESM(require("fs"), 1);
|
|
274
|
-
import_path4 = __toESM(require("path"), 1);
|
|
275
|
-
}
|
|
276
|
-
});
|
|
277
|
-
|
|
278
|
-
// tools/warp_grep/utils/files.ts
|
|
279
|
-
async function readAllLines(filePath) {
|
|
280
|
-
const content = await import_promises.default.readFile(filePath, "utf8");
|
|
281
|
-
return content.split(/\r?\n/);
|
|
282
|
-
}
|
|
283
|
-
var import_promises;
|
|
284
|
-
var init_files = __esm({
|
|
285
|
-
"tools/warp_grep/utils/files.ts"() {
|
|
286
|
-
"use strict";
|
|
287
|
-
import_promises = __toESM(require("fs/promises"), 1);
|
|
288
|
-
}
|
|
289
|
-
});
|
|
290
|
-
|
|
291
|
-
// tools/warp_grep/providers/local.ts
|
|
292
|
-
var local_exports = {};
|
|
293
|
-
__export(local_exports, {
|
|
294
|
-
LocalRipgrepProvider: () => LocalRipgrepProvider
|
|
295
|
-
});
|
|
296
|
-
function shouldSkip2(name, allowNames) {
|
|
297
|
-
if (allowNames?.has(name)) return false;
|
|
298
|
-
if (SKIP_NAMES2.has(name)) return true;
|
|
299
|
-
if (name.startsWith(".")) return true;
|
|
300
|
-
for (const ext of SKIP_EXTENSIONS2) {
|
|
301
|
-
if (name.endsWith(ext)) return true;
|
|
302
|
-
}
|
|
303
|
-
return false;
|
|
304
|
-
}
|
|
305
|
-
var import_promises2, import_path5, SKIP_NAMES2, SKIP_EXTENSIONS2, LocalRipgrepProvider;
|
|
306
|
-
var init_local = __esm({
|
|
307
|
-
"tools/warp_grep/providers/local.ts"() {
|
|
308
|
-
"use strict";
|
|
309
|
-
import_promises2 = __toESM(require("fs/promises"), 1);
|
|
310
|
-
import_path5 = __toESM(require("path"), 1);
|
|
311
|
-
init_ripgrep();
|
|
312
|
-
init_paths();
|
|
313
|
-
init_files();
|
|
314
|
-
init_config();
|
|
315
|
-
SKIP_NAMES2 = /* @__PURE__ */ new Set([
|
|
316
|
-
// Version control
|
|
317
|
-
".git",
|
|
318
|
-
".svn",
|
|
319
|
-
".hg",
|
|
320
|
-
".bzr",
|
|
321
|
-
// Dependencies
|
|
322
|
-
"node_modules",
|
|
323
|
-
"bower_components",
|
|
324
|
-
".pnpm",
|
|
325
|
-
".yarn",
|
|
326
|
-
"vendor",
|
|
327
|
-
"Pods",
|
|
328
|
-
".bundle",
|
|
329
|
-
// Python
|
|
330
|
-
"__pycache__",
|
|
331
|
-
".pytest_cache",
|
|
332
|
-
".mypy_cache",
|
|
333
|
-
".ruff_cache",
|
|
334
|
-
".venv",
|
|
335
|
-
"venv",
|
|
336
|
-
".tox",
|
|
337
|
-
".nox",
|
|
338
|
-
".eggs",
|
|
339
|
-
// Build outputs
|
|
340
|
-
"dist",
|
|
341
|
-
"build",
|
|
342
|
-
"out",
|
|
343
|
-
"output",
|
|
344
|
-
"target",
|
|
345
|
-
"_build",
|
|
346
|
-
".next",
|
|
347
|
-
".nuxt",
|
|
348
|
-
".output",
|
|
349
|
-
".vercel",
|
|
350
|
-
".netlify",
|
|
351
|
-
// Cache
|
|
352
|
-
".cache",
|
|
353
|
-
".parcel-cache",
|
|
354
|
-
".turbo",
|
|
355
|
-
".nx",
|
|
356
|
-
".gradle",
|
|
357
|
-
// IDE
|
|
358
|
-
".idea",
|
|
359
|
-
".vscode",
|
|
360
|
-
".vs",
|
|
361
|
-
// Coverage
|
|
362
|
-
"coverage",
|
|
363
|
-
".coverage",
|
|
364
|
-
"htmlcov",
|
|
365
|
-
".nyc_output",
|
|
366
|
-
// Temp
|
|
367
|
-
"tmp",
|
|
368
|
-
"temp",
|
|
369
|
-
".tmp",
|
|
370
|
-
".temp",
|
|
371
|
-
// Lock files
|
|
372
|
-
"package-lock.json",
|
|
373
|
-
"yarn.lock",
|
|
374
|
-
"pnpm-lock.yaml",
|
|
375
|
-
"bun.lockb",
|
|
376
|
-
"Cargo.lock",
|
|
377
|
-
"Gemfile.lock",
|
|
378
|
-
"poetry.lock"
|
|
379
|
-
]);
|
|
380
|
-
SKIP_EXTENSIONS2 = /* @__PURE__ */ new Set([
|
|
381
|
-
".min.js",
|
|
382
|
-
".min.css",
|
|
383
|
-
".bundle.js",
|
|
384
|
-
".wasm",
|
|
385
|
-
".so",
|
|
386
|
-
".dll",
|
|
387
|
-
".pyc",
|
|
388
|
-
".map",
|
|
389
|
-
".js.map"
|
|
390
|
-
]);
|
|
391
|
-
LocalRipgrepProvider = class {
|
|
392
|
-
constructor(repoRoot, excludes = DEFAULT_EXCLUDES, options) {
|
|
393
|
-
this.repoRoot = repoRoot;
|
|
394
|
-
this.excludes = excludes;
|
|
395
|
-
if (options?.allowNames?.length) {
|
|
396
|
-
this.allowNames = new Set(options.allowNames);
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
allowNames;
|
|
400
|
-
async grep(params) {
|
|
401
|
-
let abs;
|
|
402
|
-
try {
|
|
403
|
-
abs = resolveUnderRepo(this.repoRoot, params.path);
|
|
404
|
-
} catch (err) {
|
|
405
|
-
return {
|
|
406
|
-
lines: [],
|
|
407
|
-
error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`
|
|
408
|
-
};
|
|
409
|
-
}
|
|
410
|
-
const stat = await import_promises2.default.stat(abs).catch(() => null);
|
|
411
|
-
if (!stat) return { lines: [] };
|
|
412
|
-
const targetArg = abs === import_path5.default.resolve(this.repoRoot) ? "." : toRepoRelative2(this.repoRoot, abs);
|
|
413
|
-
const contextLines = params.context_lines !== void 0 ? String(params.context_lines) : "1";
|
|
414
|
-
const args = [
|
|
415
|
-
"--no-config",
|
|
416
|
-
"--no-heading",
|
|
417
|
-
"--with-filename",
|
|
418
|
-
"--line-number",
|
|
419
|
-
"--color=never",
|
|
420
|
-
"--trim",
|
|
421
|
-
"--max-columns=400",
|
|
422
|
-
"-C",
|
|
423
|
-
contextLines,
|
|
424
|
-
...params.case_sensitive === false ? ["--ignore-case"] : [],
|
|
425
|
-
...params.glob ? ["--glob", params.glob] : [],
|
|
426
|
-
...this.excludes.filter((e) => !this.allowNames?.has(e)).flatMap((e) => ["-g", `!${e}`]),
|
|
427
|
-
params.pattern,
|
|
428
|
-
targetArg || "."
|
|
429
|
-
];
|
|
430
|
-
const res = await runRipgrep(args, { cwd: this.repoRoot });
|
|
431
|
-
if (res.exitCode === -1) {
|
|
432
|
-
return {
|
|
433
|
-
lines: [],
|
|
434
|
-
error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required but failed to execute. Please install it:
|
|
435
|
-
\u2022 macOS: brew install ripgrep
|
|
436
|
-
\u2022 Ubuntu/Debian: apt install ripgrep
|
|
437
|
-
\u2022 Windows: choco install ripgrep
|
|
438
|
-
\u2022 Or visit: https://github.com/BurntSushi/ripgrep#installation
|
|
439
|
-
Exit code: ${res.exitCode}${res.stderr ? `
|
|
440
|
-
Details: ${res.stderr}` : ""}`
|
|
441
|
-
};
|
|
442
|
-
}
|
|
443
|
-
if (res.exitCode !== 0 && res.exitCode !== 1) {
|
|
444
|
-
return {
|
|
445
|
-
lines: [],
|
|
446
|
-
error: `[RIPGREP ERROR] grep failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ""}`
|
|
447
|
-
};
|
|
448
|
-
}
|
|
449
|
-
const lines = (res.stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
|
|
450
|
-
if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {
|
|
451
|
-
const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);
|
|
452
|
-
truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);
|
|
453
|
-
return { lines: truncated };
|
|
454
|
-
}
|
|
455
|
-
return { lines };
|
|
456
|
-
}
|
|
457
|
-
async read(params) {
|
|
458
|
-
let abs;
|
|
459
|
-
try {
|
|
460
|
-
abs = resolveUnderRepo(this.repoRoot, params.path);
|
|
461
|
-
} catch (err) {
|
|
462
|
-
return {
|
|
463
|
-
lines: [],
|
|
464
|
-
error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`
|
|
465
|
-
};
|
|
466
|
-
}
|
|
467
|
-
let stat = await import_promises2.default.stat(abs).catch(() => null);
|
|
468
|
-
if (!stat || !stat.isFile()) {
|
|
469
|
-
const fixedPath = fixPathRepetition(abs);
|
|
470
|
-
if (fixedPath) {
|
|
471
|
-
const fixedStat = await import_promises2.default.stat(fixedPath).catch(() => null);
|
|
472
|
-
if (fixedStat?.isFile()) {
|
|
473
|
-
abs = fixedPath;
|
|
474
|
-
stat = fixedStat;
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
if (!stat || !stat.isFile()) {
|
|
479
|
-
return {
|
|
480
|
-
lines: [],
|
|
481
|
-
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.`
|
|
482
|
-
};
|
|
483
|
-
}
|
|
484
|
-
if (isSymlink(abs)) {
|
|
485
|
-
return {
|
|
486
|
-
lines: [],
|
|
487
|
-
error: `[SYMLINK] You tried to read "${params.path}" but this is a symlink. Try reading the actual file it points to instead.`
|
|
488
|
-
};
|
|
489
|
-
}
|
|
490
|
-
if (!isTextualFile(abs)) {
|
|
491
|
-
return {
|
|
492
|
-
lines: [],
|
|
493
|
-
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.`
|
|
494
|
-
};
|
|
495
|
-
}
|
|
496
|
-
let lines;
|
|
497
|
-
try {
|
|
498
|
-
lines = await readAllLines(abs);
|
|
499
|
-
} catch (err) {
|
|
500
|
-
return {
|
|
501
|
-
lines: [],
|
|
502
|
-
error: `[READ ERROR] Failed to read "${params.path}": ${err instanceof Error ? err.message : String(err)}`
|
|
503
|
-
};
|
|
504
|
-
}
|
|
505
|
-
const total = lines.length;
|
|
506
|
-
const rawStart = params.start;
|
|
507
|
-
const rawEnd = params.end;
|
|
508
|
-
let s = 1;
|
|
509
|
-
let e = total;
|
|
510
|
-
const startValid = rawStart === void 0 || Number.isFinite(rawStart) && rawStart > 0;
|
|
511
|
-
const endValid = rawEnd === void 0 || Number.isFinite(rawEnd) && rawEnd > 0;
|
|
512
|
-
if (startValid && endValid) {
|
|
513
|
-
s = rawStart ?? 1;
|
|
514
|
-
e = Math.min(rawEnd ?? total, total);
|
|
515
|
-
if (s > total && total > 0 || s > e) {
|
|
516
|
-
s = 1;
|
|
517
|
-
e = total;
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
const out = [];
|
|
521
|
-
for (let i = s; i <= e; i += 1) {
|
|
522
|
-
const content = lines[i - 1] ?? "";
|
|
523
|
-
out.push(`${i}|${content}`);
|
|
524
|
-
}
|
|
525
|
-
if (out.length > AGENT_CONFIG.MAX_READ_LINES) {
|
|
526
|
-
const truncated = out.slice(0, AGENT_CONFIG.MAX_READ_LINES);
|
|
527
|
-
truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${out.length} lines)`);
|
|
528
|
-
return { lines: truncated };
|
|
529
|
-
}
|
|
530
|
-
return { lines: out };
|
|
531
|
-
}
|
|
532
|
-
async listDirectory(params) {
|
|
533
|
-
let abs;
|
|
534
|
-
try {
|
|
535
|
-
abs = resolveUnderRepo(this.repoRoot, params.path);
|
|
536
|
-
} catch {
|
|
537
|
-
return [];
|
|
538
|
-
}
|
|
539
|
-
const stat = await import_promises2.default.stat(abs).catch(() => null);
|
|
540
|
-
if (!stat || !stat.isDirectory()) {
|
|
541
|
-
return [];
|
|
542
|
-
}
|
|
543
|
-
const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
|
|
544
|
-
const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
|
|
545
|
-
const regex = params.pattern ? new RegExp(params.pattern) : null;
|
|
546
|
-
const repoRoot = this.repoRoot;
|
|
547
|
-
const allowNames = this.allowNames;
|
|
548
|
-
const results = [];
|
|
549
|
-
let timedOut = false;
|
|
550
|
-
const startTime = Date.now();
|
|
551
|
-
async function walk(dir, depth) {
|
|
552
|
-
if (Date.now() - startTime > AGENT_CONFIG.LIST_TIMEOUT_MS) {
|
|
553
|
-
timedOut = true;
|
|
554
|
-
return;
|
|
555
|
-
}
|
|
556
|
-
if (depth > maxDepth || results.length >= maxResults) return;
|
|
557
|
-
let entries;
|
|
558
|
-
try {
|
|
559
|
-
entries = await import_promises2.default.readdir(dir, { withFileTypes: true });
|
|
560
|
-
} catch {
|
|
561
|
-
return;
|
|
562
|
-
}
|
|
563
|
-
for (const entry of entries) {
|
|
564
|
-
if (timedOut || results.length >= maxResults) break;
|
|
565
|
-
if (shouldSkip2(entry.name, allowNames)) continue;
|
|
566
|
-
if (regex && !regex.test(entry.name)) continue;
|
|
567
|
-
const full = import_path5.default.join(dir, entry.name);
|
|
568
|
-
const isDir = entry.isDirectory();
|
|
569
|
-
results.push({
|
|
570
|
-
name: entry.name,
|
|
571
|
-
path: toRepoRelative2(repoRoot, full),
|
|
572
|
-
type: isDir ? "dir" : "file",
|
|
573
|
-
depth
|
|
574
|
-
});
|
|
575
|
-
if (isDir) {
|
|
576
|
-
await walk(full, depth + 1);
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
|
-
await walk(abs, 0);
|
|
581
|
-
return results;
|
|
582
|
-
}
|
|
583
|
-
async glob(params) {
|
|
584
|
-
let abs;
|
|
585
|
-
try {
|
|
586
|
-
abs = params.path ? resolveUnderRepo(this.repoRoot, params.path) : this.repoRoot;
|
|
587
|
-
} catch (err) {
|
|
588
|
-
return { files: [], searchDir: this.repoRoot, totalFound: 0, error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}` };
|
|
589
|
-
}
|
|
590
|
-
const stat = await import_promises2.default.stat(abs).catch(() => null);
|
|
591
|
-
if (!stat || !stat.isDirectory()) {
|
|
592
|
-
return { files: [], searchDir: abs, totalFound: 0, error: `[PATH ERROR] Directory not found: ${params.path || "."}` };
|
|
593
|
-
}
|
|
594
|
-
const targetArg = abs === import_path5.default.resolve(this.repoRoot) ? "." : toRepoRelative2(this.repoRoot, abs);
|
|
595
|
-
const args = [
|
|
596
|
-
"--no-config",
|
|
597
|
-
"--files",
|
|
598
|
-
"--color=never",
|
|
599
|
-
"-g",
|
|
600
|
-
params.pattern,
|
|
601
|
-
...this.excludes.filter((e) => !this.allowNames?.has(e)).flatMap((e) => ["-g", `!${e}`]),
|
|
602
|
-
targetArg || "."
|
|
603
|
-
];
|
|
604
|
-
const res = await runRipgrep(args, { cwd: this.repoRoot });
|
|
605
|
-
if (res.exitCode === -1) {
|
|
606
|
-
return { files: [], searchDir: abs, totalFound: 0, error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required for glob search.` };
|
|
607
|
-
}
|
|
608
|
-
if (res.exitCode !== 0 && res.exitCode !== 1) {
|
|
609
|
-
return { files: [], searchDir: abs, totalFound: 0, error: `[GLOB ERROR] glob failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ""}` };
|
|
610
|
-
}
|
|
611
|
-
const absRoot = import_path5.default.resolve(this.repoRoot);
|
|
612
|
-
const relFiles = (res.stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
|
|
613
|
-
const absFiles = relFiles.map((f) => import_path5.default.resolve(absRoot, f));
|
|
614
|
-
const withMtime = [];
|
|
615
|
-
for (const f of absFiles) {
|
|
616
|
-
const s = await import_promises2.default.stat(f).catch(() => null);
|
|
617
|
-
withMtime.push({ file: f, mtime: s?.mtimeMs ?? 0 });
|
|
618
|
-
}
|
|
619
|
-
withMtime.sort((a, b) => b.mtime - a.mtime);
|
|
620
|
-
const totalFound = withMtime.length;
|
|
621
|
-
return { files: withMtime.slice(0, 100).map((f) => f.file), searchDir: abs, totalFound };
|
|
622
|
-
}
|
|
623
|
-
};
|
|
624
|
-
}
|
|
625
|
-
});
|
|
626
|
-
|
|
627
|
-
// tools/warp_grep/gemini.ts
|
|
628
|
-
var gemini_exports = {};
|
|
629
|
-
__export(gemini_exports, {
|
|
630
|
-
createGitHubReadFileTool: () => createGitHubReadFileTool,
|
|
631
|
-
createGitHubSearchTool: () => createGitHubSearchTool,
|
|
632
|
-
createMorphWarpGrepTool: () => createMorphWarpGrepTool,
|
|
633
|
-
createWarpGrepTool: () => createWarpGrepTool,
|
|
634
|
-
default: () => gemini_default,
|
|
635
|
-
execute: () => execute,
|
|
636
|
-
formatResult: () => formatResult,
|
|
637
|
-
warpGrepFunctionDeclaration: () => warpGrepFunctionDeclaration
|
|
638
|
-
});
|
|
639
|
-
module.exports = __toCommonJS(gemini_exports);
|
|
640
|
-
|
|
641
|
-
// tools/warp_grep/agent/runner.ts
|
|
642
|
-
init_config();
|
|
643
|
-
|
|
644
|
-
// tools/warp_grep/agent/parser.ts
|
|
645
|
-
function parseReadLines(linesStr) {
|
|
646
|
-
const ranges = [];
|
|
647
|
-
for (const rangeStr of linesStr.split(",")) {
|
|
648
|
-
const trimmed = rangeStr.trim();
|
|
649
|
-
if (!trimmed) continue;
|
|
650
|
-
const parts = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
|
|
651
|
-
if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
|
|
652
|
-
ranges.push([parts[0], parts[1]]);
|
|
653
|
-
} else if (Number.isFinite(parts[0])) {
|
|
654
|
-
ranges.push([parts[0], parts[0]]);
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
if (ranges.length === 1) return { start: ranges[0][0], end: ranges[0][1] };
|
|
658
|
-
if (ranges.length > 1) return { lines: ranges };
|
|
659
|
-
return {};
|
|
660
|
-
}
|
|
661
|
-
function parseFinishFiles(filesStr) {
|
|
662
|
-
const files = [];
|
|
663
|
-
for (const line of filesStr.trim().split(/\s+/)) {
|
|
664
|
-
const trimmed = line.trim();
|
|
665
|
-
if (!trimmed) continue;
|
|
666
|
-
const searchFrom = /^[A-Za-z]:/.test(trimmed) ? 2 : 0;
|
|
667
|
-
const colonIdx = trimmed.indexOf(":", searchFrom);
|
|
668
|
-
if (colonIdx === -1) {
|
|
669
|
-
files.push({ path: trimmed, lines: "*" });
|
|
670
|
-
continue;
|
|
671
|
-
}
|
|
672
|
-
const filePath = trimmed.slice(0, colonIdx);
|
|
673
|
-
const rangesPart = trimmed.slice(colonIdx + 1);
|
|
674
|
-
if (!rangesPart.trim() || rangesPart.trim() === "*") {
|
|
675
|
-
files.push({ path: filePath, lines: "*" });
|
|
676
|
-
continue;
|
|
677
|
-
}
|
|
678
|
-
const ranges = [];
|
|
679
|
-
for (const rangeStr of rangesPart.split(",")) {
|
|
680
|
-
const rt = rangeStr.trim();
|
|
681
|
-
if (!rt) continue;
|
|
682
|
-
const parts = rt.split("-").map((v) => parseInt(v.trim(), 10));
|
|
683
|
-
if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
|
|
684
|
-
ranges.push([parts[0], parts[1]]);
|
|
685
|
-
} else if (Number.isFinite(parts[0])) {
|
|
686
|
-
ranges.push([parts[0], parts[0]]);
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
files.push({ path: filePath, lines: ranges.length > 0 ? ranges : "*" });
|
|
690
|
-
}
|
|
691
|
-
return files;
|
|
692
|
-
}
|
|
693
|
-
function extractPathFromCommand(command) {
|
|
694
|
-
const tokens = command.trim().split(/\s+/);
|
|
695
|
-
const pathTokens = tokens.slice(1).filter((t) => !t.startsWith("-") && !t.startsWith("|") && !t.startsWith("\\("));
|
|
696
|
-
return pathTokens[0] || ".";
|
|
697
|
-
}
|
|
698
|
-
|
|
699
|
-
// tools/warp_grep/agent/tools/grep.ts
|
|
700
|
-
async function toolGrep(provider, args) {
|
|
701
|
-
const res = await provider.grep(args);
|
|
702
|
-
if (res.error) {
|
|
703
|
-
return { output: res.error };
|
|
704
|
-
}
|
|
705
|
-
if (!res.lines.length) {
|
|
706
|
-
return { output: "no matches" };
|
|
707
|
-
}
|
|
708
|
-
return { output: res.lines.join("\n") };
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
// tools/warp_grep/agent/tools/read.ts
|
|
712
|
-
function isValidRange(start, end) {
|
|
713
|
-
return typeof start === "number" && typeof end === "number" && Number.isFinite(start) && Number.isFinite(end) && start > 0 && end >= start;
|
|
714
|
-
}
|
|
715
|
-
async function toolRead(provider, args) {
|
|
716
|
-
if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {
|
|
717
|
-
const validRanges = [];
|
|
718
|
-
for (const range of args.lines) {
|
|
719
|
-
if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {
|
|
720
|
-
validRanges.push([range[0], range[1]]);
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
if (validRanges.length === 0) {
|
|
724
|
-
const res2 = await provider.read({ path: args.path });
|
|
725
|
-
if (res2.error) return res2.error;
|
|
726
|
-
if (!res2.lines.length) return "(empty file)";
|
|
727
|
-
return res2.lines.join("\n");
|
|
728
|
-
}
|
|
729
|
-
const chunks = [];
|
|
730
|
-
for (const [start, end] of validRanges) {
|
|
731
|
-
const res2 = await provider.read({ path: args.path, start, end });
|
|
732
|
-
if (res2.error) return res2.error;
|
|
733
|
-
chunks.push(res2.lines.join("\n"));
|
|
734
|
-
}
|
|
735
|
-
if (chunks.every((c) => c === "")) return "(empty file)";
|
|
736
|
-
return chunks.join("\n...\n");
|
|
737
|
-
}
|
|
738
|
-
const res = await provider.read({ path: args.path, start: args.start, end: args.end });
|
|
739
|
-
if (res.error) {
|
|
740
|
-
return res.error;
|
|
741
|
-
}
|
|
742
|
-
if (!res.lines.length) return "(empty file)";
|
|
743
|
-
return res.lines.join("\n");
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
// tools/warp_grep/agent/tools/list_directory.ts
|
|
747
|
-
init_config();
|
|
748
|
-
var import_path = __toESM(require("path"), 1);
|
|
749
|
-
async function toolListDirectory(provider, args, repoRoot) {
|
|
750
|
-
const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_LIST_RESULTS;
|
|
751
|
-
const maxDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
|
|
752
|
-
const entries = await provider.listDirectory({
|
|
753
|
-
path: args.path,
|
|
754
|
-
pattern: args.pattern ?? null,
|
|
755
|
-
maxResults,
|
|
756
|
-
maxDepth
|
|
757
|
-
});
|
|
758
|
-
if (!entries.length) return "empty";
|
|
759
|
-
if (repoRoot) {
|
|
760
|
-
const absRoot = repoRoot;
|
|
761
|
-
const lines = entries.map((e) => import_path.default.join(absRoot, e.path));
|
|
762
|
-
return lines.join("\n");
|
|
763
|
-
}
|
|
764
|
-
return entries.map((e) => e.path).join("\n");
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
// tools/warp_grep/agent/tools/glob.ts
|
|
768
|
-
async function toolGlob(provider, args) {
|
|
769
|
-
const res = await provider.glob(args);
|
|
770
|
-
if (res.error) {
|
|
771
|
-
return res.error;
|
|
772
|
-
}
|
|
773
|
-
if (!res.files.length) {
|
|
774
|
-
return "no matches";
|
|
775
|
-
}
|
|
776
|
-
const header = `Found ${res.totalFound} file(s) matching "${args.pattern}" within ${res.searchDir}, sorted by modification time (newest first):`;
|
|
777
|
-
const body = res.files.join("\n");
|
|
778
|
-
const truncated = res.totalFound > res.files.length ? `
|
|
779
|
-
[${res.totalFound - res.files.length} files truncated]` : "";
|
|
780
|
-
return `${header}
|
|
781
|
-
---
|
|
782
|
-
${body}
|
|
783
|
-
---${truncated}`;
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
// tools/warp_grep/agent/tools/finish.ts
|
|
787
|
-
function isValidRange2(range) {
|
|
788
|
-
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];
|
|
789
|
-
}
|
|
790
|
-
function extractValidRanges(lines) {
|
|
791
|
-
if (!Array.isArray(lines)) return null;
|
|
792
|
-
const valid = [];
|
|
793
|
-
for (const range of lines) {
|
|
794
|
-
if (isValidRange2(range)) {
|
|
795
|
-
valid.push([range[0], range[1]]);
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
return valid.length > 0 ? valid : null;
|
|
799
|
-
}
|
|
800
|
-
async function readFinishFiles(repoRoot, files, reader) {
|
|
801
|
-
const out = [];
|
|
802
|
-
for (const f of files) {
|
|
803
|
-
const validRanges = f.lines === "*" ? null : extractValidRanges(f.lines);
|
|
804
|
-
if (f.lines === "*" || !validRanges) {
|
|
805
|
-
const lines = await reader(f.path);
|
|
806
|
-
out.push({ path: f.path, ranges: "*", content: lines.join("\n") });
|
|
807
|
-
} else {
|
|
808
|
-
const ranges = mergeRanges(validRanges);
|
|
809
|
-
const chunks = [];
|
|
810
|
-
for (let i = 0; i < ranges.length; i++) {
|
|
811
|
-
const [s, e] = ranges[i];
|
|
812
|
-
if (i === 0 && s > 1) {
|
|
813
|
-
chunks.push(`// ... existing code, block starting at line ${s} ...`);
|
|
814
|
-
} else if (i > 0) {
|
|
815
|
-
chunks.push(`// ... existing code, block starting at line ${s} ...`);
|
|
816
|
-
}
|
|
817
|
-
const lines = await reader(f.path, s, e);
|
|
818
|
-
chunks.push(lines.join("\n"));
|
|
819
|
-
}
|
|
820
|
-
out.push({ path: f.path, ranges, content: chunks.join("\n") });
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
return out;
|
|
824
|
-
}
|
|
825
|
-
function mergeRanges(ranges) {
|
|
826
|
-
if (!ranges.length) return [];
|
|
827
|
-
const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
|
|
828
|
-
const merged = [];
|
|
829
|
-
let [cs, ce] = sorted[0];
|
|
830
|
-
for (let i = 1; i < sorted.length; i++) {
|
|
831
|
-
const [s, e] = sorted[i];
|
|
832
|
-
if (s <= ce + 1) {
|
|
833
|
-
ce = Math.max(ce, e);
|
|
834
|
-
} else {
|
|
835
|
-
merged.push([cs, ce]);
|
|
836
|
-
cs = s;
|
|
837
|
-
ce = e;
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
merged.push([cs, ce]);
|
|
841
|
-
return merged;
|
|
842
|
-
}
|
|
843
|
-
|
|
844
|
-
// tools/warp_grep/agent/helpers.ts
|
|
845
|
-
var import_path2 = __toESM(require("path"), 1);
|
|
846
|
-
init_config();
|
|
847
|
-
var TRUNCATED_MARKER = "[truncated for context limit]";
|
|
848
|
-
function getMessageSize(m) {
|
|
849
|
-
if (m.role === "tool") return m.content.length;
|
|
850
|
-
if (m.role === "assistant") {
|
|
851
|
-
let size = typeof m.content === "string" ? m.content.length : 0;
|
|
852
|
-
if (m.tool_calls) {
|
|
853
|
-
size += m.tool_calls.reduce((s, tc) => s + tc.function.name.length + tc.function.arguments.length, 0);
|
|
854
|
-
}
|
|
855
|
-
return size;
|
|
856
|
-
}
|
|
857
|
-
return m.content.length;
|
|
858
|
-
}
|
|
859
|
-
function formatTurnMessage(turnsUsed, maxTurns) {
|
|
860
|
-
const turnsRemaining = maxTurns - turnsUsed;
|
|
861
|
-
if (turnsRemaining === 1) {
|
|
862
|
-
return `
|
|
863
|
-
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`;
|
|
864
|
-
}
|
|
865
|
-
return `
|
|
866
|
-
You have used ${turnsUsed} turn${turnsUsed === 1 ? "" : "s"} and have ${turnsRemaining} remaining`;
|
|
867
|
-
}
|
|
868
|
-
function calculateContextBudget(messages) {
|
|
869
|
-
const totalChars = messages.reduce((sum, m) => sum + getMessageSize(m), 0);
|
|
870
|
-
const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;
|
|
871
|
-
const percent = Math.floor(totalChars / maxChars * 100);
|
|
872
|
-
const usedK = Math.floor(totalChars / 1e3);
|
|
873
|
-
const maxK = Math.floor(maxChars / 1e3);
|
|
874
|
-
return `<context_budget>${percent}% (${usedK}K/${maxK}K chars)</context_budget>`;
|
|
875
|
-
}
|
|
876
|
-
async function buildInitialState(repoRoot, searchTerm, provider, options) {
|
|
877
|
-
const budget = calculateContextBudget([]);
|
|
878
|
-
const turnTag = `You have used 0 turns and have ${AGENT_CONFIG.MAX_TURNS} remaining`;
|
|
879
|
-
const treeDepth = options?.search_type === "node_modules" ? 1 : 2;
|
|
880
|
-
const absRoot = repoRoot;
|
|
881
|
-
try {
|
|
882
|
-
const entries = await provider.listDirectory({
|
|
883
|
-
path: ".",
|
|
884
|
-
maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,
|
|
885
|
-
maxDepth: treeDepth
|
|
886
|
-
});
|
|
887
|
-
const lines = [absRoot];
|
|
888
|
-
for (const e of entries) {
|
|
889
|
-
lines.push(import_path2.default.join(absRoot, e.path));
|
|
890
|
-
}
|
|
891
|
-
return `<repo_structure>
|
|
892
|
-
${lines.join("\n")}
|
|
893
|
-
</repo_structure>
|
|
894
|
-
|
|
895
|
-
<search_string>
|
|
896
|
-
${searchTerm}
|
|
897
|
-
</search_string>
|
|
898
|
-
${budget}
|
|
899
|
-
${turnTag}`;
|
|
900
|
-
} catch {
|
|
901
|
-
return `<repo_structure>
|
|
902
|
-
${absRoot}
|
|
903
|
-
</repo_structure>
|
|
904
|
-
|
|
905
|
-
<search_string>
|
|
906
|
-
${searchTerm}
|
|
907
|
-
</search_string>
|
|
908
|
-
${budget}
|
|
909
|
-
${turnTag}`;
|
|
910
|
-
}
|
|
911
|
-
}
|
|
912
|
-
function enforceContextLimit(messages, maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS) {
|
|
913
|
-
const getTotalChars = () => messages.reduce((sum, m) => sum + getMessageSize(m), 0);
|
|
914
|
-
if (getTotalChars() <= maxChars) {
|
|
915
|
-
return messages;
|
|
916
|
-
}
|
|
917
|
-
const truncatableIndices = [];
|
|
918
|
-
let firstUserSkipped = false;
|
|
919
|
-
for (let i = 0; i < messages.length; i++) {
|
|
920
|
-
const m = messages[i];
|
|
921
|
-
if (m.role === "tool") {
|
|
922
|
-
truncatableIndices.push(i);
|
|
923
|
-
} else if (m.role === "user") {
|
|
924
|
-
if (!firstUserSkipped) {
|
|
925
|
-
firstUserSkipped = true;
|
|
926
|
-
continue;
|
|
927
|
-
}
|
|
928
|
-
truncatableIndices.push(i);
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
for (const idx of truncatableIndices) {
|
|
932
|
-
if (getTotalChars() <= maxChars) {
|
|
933
|
-
break;
|
|
934
|
-
}
|
|
935
|
-
const m = messages[idx];
|
|
936
|
-
if (m.role === "tool" && m.content !== TRUNCATED_MARKER) {
|
|
937
|
-
messages[idx] = { role: "tool", tool_call_id: m.tool_call_id, content: TRUNCATED_MARKER };
|
|
938
|
-
} else if (m.role === "user" && m.content !== TRUNCATED_MARKER) {
|
|
939
|
-
messages[idx] = { role: "user", content: TRUNCATED_MARKER };
|
|
940
|
-
}
|
|
941
|
-
}
|
|
942
|
-
return messages;
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
// tools/warp_grep/agent/runner.ts
|
|
946
|
-
var import_openai = __toESM(require("openai"), 1);
|
|
947
|
-
|
|
948
|
-
// package.json
|
|
949
|
-
var package_default = {
|
|
950
|
-
name: "@morphllm/morphsdk",
|
|
951
|
-
version: "0.2.202",
|
|
952
|
-
description: "TypeScript SDK and CLI for Morph Fast Apply integration",
|
|
953
|
-
type: "module",
|
|
954
|
-
main: "./dist/index.cjs",
|
|
955
|
-
module: "./dist/index.js",
|
|
956
|
-
types: "./dist/index.d.ts",
|
|
957
|
-
exports: {
|
|
958
|
-
".": {
|
|
959
|
-
types: "./dist/index.d.ts",
|
|
960
|
-
import: "./dist/index.js",
|
|
961
|
-
require: "./dist/index.cjs"
|
|
962
|
-
},
|
|
963
|
-
"./logger": {
|
|
964
|
-
types: "./dist/logger.d.ts",
|
|
965
|
-
import: "./dist/logger.js",
|
|
966
|
-
require: "./dist/logger.cjs"
|
|
967
|
-
},
|
|
968
|
-
"./edge": {
|
|
969
|
-
types: "./dist/edge.d.ts",
|
|
970
|
-
import: "./dist/edge.js",
|
|
971
|
-
require: "./dist/edge.cjs"
|
|
972
|
-
},
|
|
973
|
-
"./tools/warp-grep": {
|
|
974
|
-
types: "./dist/tools/warp_grep/index.d.ts",
|
|
975
|
-
import: "./dist/tools/warp_grep/index.js",
|
|
976
|
-
require: "./dist/tools/warp_grep/index.cjs"
|
|
977
|
-
},
|
|
978
|
-
"./tools/warp-grep/openai": {
|
|
979
|
-
types: "./dist/tools/warp_grep/openai.d.ts",
|
|
980
|
-
import: "./dist/tools/warp_grep/openai.js",
|
|
981
|
-
require: "./dist/tools/warp_grep/openai.cjs"
|
|
982
|
-
},
|
|
983
|
-
"./tools/warp-grep/anthropic": {
|
|
984
|
-
types: "./dist/tools/warp_grep/anthropic.d.ts",
|
|
985
|
-
import: "./dist/tools/warp_grep/anthropic.js",
|
|
986
|
-
require: "./dist/tools/warp_grep/anthropic.cjs"
|
|
987
|
-
},
|
|
988
|
-
"./tools/warp-grep/vercel": {
|
|
989
|
-
types: "./dist/tools/warp_grep/vercel.d.ts",
|
|
990
|
-
import: "./dist/tools/warp_grep/vercel.js",
|
|
991
|
-
require: "./dist/tools/warp_grep/vercel.cjs"
|
|
992
|
-
},
|
|
993
|
-
"./tools/warp-grep/client": {
|
|
994
|
-
types: "./dist/tools/warp_grep/client.d.ts",
|
|
995
|
-
import: "./dist/tools/warp_grep/client.js",
|
|
996
|
-
require: "./dist/tools/warp_grep/client.cjs"
|
|
997
|
-
},
|
|
998
|
-
"./tools/warp-grep/gemini": {
|
|
999
|
-
types: "./dist/tools/warp_grep/gemini.d.ts",
|
|
1000
|
-
import: "./dist/tools/warp_grep/gemini.js",
|
|
1001
|
-
require: "./dist/tools/warp_grep/gemini.cjs"
|
|
1002
|
-
},
|
|
1003
|
-
"./tools/warp-grep/harness": {
|
|
1004
|
-
types: "./dist/tools/warp_grep/harness.d.ts",
|
|
1005
|
-
import: "./dist/tools/warp_grep/harness.js",
|
|
1006
|
-
require: "./dist/tools/warp_grep/harness.cjs"
|
|
1007
|
-
},
|
|
1008
|
-
"./tools/fastapply": {
|
|
1009
|
-
types: "./dist/tools/fastapply/index.d.ts",
|
|
1010
|
-
import: "./dist/tools/fastapply/index.js",
|
|
1011
|
-
require: "./dist/tools/fastapply/index.cjs"
|
|
1012
|
-
},
|
|
1013
|
-
"./tools/fastapply/anthropic": {
|
|
1014
|
-
types: "./dist/tools/fastapply/anthropic.d.ts",
|
|
1015
|
-
import: "./dist/tools/fastapply/anthropic.js",
|
|
1016
|
-
require: "./dist/tools/fastapply/anthropic.cjs"
|
|
1017
|
-
},
|
|
1018
|
-
"./tools/fastapply/openai": {
|
|
1019
|
-
types: "./dist/tools/fastapply/openai.d.ts",
|
|
1020
|
-
import: "./dist/tools/fastapply/openai.js",
|
|
1021
|
-
require: "./dist/tools/fastapply/openai.cjs"
|
|
1022
|
-
},
|
|
1023
|
-
"./tools/fastapply/vercel": {
|
|
1024
|
-
types: "./dist/tools/fastapply/vercel.d.ts",
|
|
1025
|
-
import: "./dist/tools/fastapply/vercel.js",
|
|
1026
|
-
require: "./dist/tools/fastapply/vercel.cjs"
|
|
1027
|
-
},
|
|
1028
|
-
"./modelrouter": {
|
|
1029
|
-
types: "./dist/modelrouter/index.d.ts",
|
|
1030
|
-
import: "./dist/modelrouter/index.js",
|
|
1031
|
-
require: "./dist/modelrouter/index.cjs"
|
|
1032
|
-
},
|
|
1033
|
-
"./tools/compact": {
|
|
1034
|
-
types: "./dist/tools/compact/index.d.ts",
|
|
1035
|
-
import: "./dist/tools/compact/index.js",
|
|
1036
|
-
require: "./dist/tools/compact/index.cjs"
|
|
1037
|
-
},
|
|
1038
|
-
"./subagents": {
|
|
1039
|
-
types: "./dist/subagents/index.d.ts",
|
|
1040
|
-
import: "./dist/subagents/index.js",
|
|
1041
|
-
require: "./dist/subagents/index.cjs"
|
|
1042
|
-
},
|
|
1043
|
-
"./subagents/vercel": {
|
|
1044
|
-
types: "./dist/subagents/vercel.d.ts",
|
|
1045
|
-
import: "./dist/subagents/vercel.js",
|
|
1046
|
-
require: "./dist/subagents/vercel.cjs"
|
|
1047
|
-
},
|
|
1048
|
-
"./subagents/anthropic": {
|
|
1049
|
-
types: "./dist/subagents/anthropic.d.ts",
|
|
1050
|
-
import: "./dist/subagents/anthropic.js",
|
|
1051
|
-
require: "./dist/subagents/anthropic.cjs"
|
|
1052
|
-
},
|
|
1053
|
-
"./ai-sdk": {
|
|
1054
|
-
types: "./dist/ai-sdk/index.d.ts",
|
|
1055
|
-
import: "./dist/ai-sdk/index.js",
|
|
1056
|
-
require: "./dist/ai-sdk/index.cjs"
|
|
1057
|
-
}
|
|
1058
|
-
},
|
|
1059
|
-
files: [
|
|
1060
|
-
"dist/**/*.js",
|
|
1061
|
-
"dist/**/*.cjs",
|
|
1062
|
-
"dist/**/*.d.ts",
|
|
1063
|
-
"!dist/**/__tests__/**",
|
|
1064
|
-
"!dist/**/*.test.*"
|
|
1065
|
-
],
|
|
1066
|
-
scripts: {
|
|
1067
|
-
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",
|
|
1068
|
-
prepare: "npm run build",
|
|
1069
|
-
typecheck: "tsc --noEmit && tsc --noEmit -p ai-sdk/tsconfig.json",
|
|
1070
|
-
lint: "eslint .",
|
|
1071
|
-
test: "vitest run",
|
|
1072
|
-
"test:watch": "vitest watch",
|
|
1073
|
-
"test:anthropic": "vitest run anthropic",
|
|
1074
|
-
"test:openai": "vitest run openai",
|
|
1075
|
-
"test:vercel": "vitest run vercel",
|
|
1076
|
-
"test:git": "vitest run git",
|
|
1077
|
-
"test:agent": "npx tsx tests/fullAgentTest.ts",
|
|
1078
|
-
"test:integration": "npx tsx tests/fullIntegrationTest.ts",
|
|
1079
|
-
"test:e2e": "vitest run --config vitest.e2e.config.ts",
|
|
1080
|
-
"release:patch": "npm version patch && npm publish",
|
|
1081
|
-
"release:minor": "npm version minor && npm publish",
|
|
1082
|
-
"release:major": "npm version major && npm publish"
|
|
1083
|
-
},
|
|
1084
|
-
keywords: [
|
|
1085
|
-
"morph",
|
|
1086
|
-
"fast-apply",
|
|
1087
|
-
"cli",
|
|
1088
|
-
"sdk",
|
|
1089
|
-
"edit-file"
|
|
1090
|
-
],
|
|
1091
|
-
engines: {
|
|
1092
|
-
node: ">=18"
|
|
1093
|
-
},
|
|
1094
|
-
license: "MIT",
|
|
1095
|
-
dependencies: {
|
|
1096
|
-
"@vscode/ripgrep": "^1.17.0",
|
|
1097
|
-
ai: ">=5.0.0",
|
|
1098
|
-
diff: "^7.0.0",
|
|
1099
|
-
openai: "^4.52.7",
|
|
1100
|
-
zod: ">=3.23.0"
|
|
1101
|
-
},
|
|
1102
|
-
devDependencies: {
|
|
1103
|
-
"@ai-sdk/anthropic": "^2.0.70",
|
|
1104
|
-
"@ai-sdk/openai": "^2.0.35",
|
|
1105
|
-
"@anthropic-ai/sdk": "^0.30.1",
|
|
1106
|
-
"@google/generative-ai": "^0.24.1",
|
|
1107
|
-
"@types/diff": "^7.0.2",
|
|
1108
|
-
"@types/node": "^20.14.10",
|
|
1109
|
-
"@typescript-eslint/eslint-plugin": "^7.18.0",
|
|
1110
|
-
"@typescript-eslint/parser": "^7.18.0",
|
|
1111
|
-
dotenv: "^16.4.5",
|
|
1112
|
-
eslint: "^8.57.0",
|
|
1113
|
-
shx: "^0.3.4",
|
|
1114
|
-
tsup: "^8.5.0",
|
|
1115
|
-
tsx: "^4.16.2",
|
|
1116
|
-
typescript: "^5.5.4",
|
|
1117
|
-
vitest: "^2.1.6"
|
|
1118
|
-
},
|
|
1119
|
-
peerDependencies: {
|
|
1120
|
-
"@ai-sdk/openai-compatible": ">=2.0.74 <4",
|
|
1121
|
-
"@anthropic-ai/sdk": ">=0.25.0",
|
|
1122
|
-
"@google/generative-ai": ">=0.21.0",
|
|
1123
|
-
ai: ">=5.0.0",
|
|
1124
|
-
zod: ">=3.23.0"
|
|
1125
|
-
},
|
|
1126
|
-
peerDependenciesMeta: {
|
|
1127
|
-
"@anthropic-ai/sdk": {
|
|
1128
|
-
optional: true
|
|
1129
|
-
},
|
|
1130
|
-
"@google/generative-ai": {
|
|
1131
|
-
optional: true
|
|
1132
|
-
},
|
|
1133
|
-
ai: {
|
|
1134
|
-
optional: true
|
|
1135
|
-
},
|
|
1136
|
-
zod: {
|
|
1137
|
-
optional: true
|
|
1138
|
-
}
|
|
1139
|
-
},
|
|
1140
|
-
publishConfig: {
|
|
1141
|
-
access: "public"
|
|
1142
|
-
}
|
|
1143
|
-
};
|
|
1144
|
-
|
|
1145
|
-
// version.ts
|
|
1146
|
-
var SDK_VERSION = package_default.version;
|
|
1147
|
-
|
|
1148
|
-
// tools/warp_grep/agent/runner.ts
|
|
1149
|
-
var import_path3 = __toESM(require("path"), 1);
|
|
1150
|
-
|
|
1151
|
-
// logger.ts
|
|
1152
|
-
var MorphLogger = class {
|
|
1153
|
-
enabled;
|
|
1154
|
-
fileStream;
|
|
1155
|
-
/** Resolves once the file stream is initialized (or immediately if no file logging). */
|
|
1156
|
-
ready;
|
|
1157
|
-
constructor() {
|
|
1158
|
-
this.enabled = typeof process !== "undefined" && (process.env.MORPH_DEBUG === "1" || !!process.env.MORPH_LOG_FILE);
|
|
1159
|
-
this.fileStream = null;
|
|
1160
|
-
const f = typeof process !== "undefined" ? process.env.MORPH_LOG_FILE : void 0;
|
|
1161
|
-
if (f) {
|
|
1162
|
-
this.ready = import("fs").then((fs4) => {
|
|
1163
|
-
this.fileStream = fs4.createWriteStream(f, { flags: "a" });
|
|
1164
|
-
}).catch(() => {
|
|
1165
|
-
});
|
|
1166
|
-
} else {
|
|
1167
|
-
this.ready = Promise.resolve();
|
|
1168
|
-
}
|
|
1169
|
-
}
|
|
1170
|
-
debug(component, msg, data) {
|
|
1171
|
-
this._log("debug", component, msg, data);
|
|
1172
|
-
}
|
|
1173
|
-
info(component, msg, data) {
|
|
1174
|
-
this._log("info", component, msg, data);
|
|
1175
|
-
}
|
|
1176
|
-
warn(component, msg, data) {
|
|
1177
|
-
this._log("warn", component, msg, data);
|
|
1178
|
-
}
|
|
1179
|
-
error(component, msg, data) {
|
|
1180
|
-
this._log("error", component, msg, data);
|
|
1181
|
-
}
|
|
1182
|
-
enable() {
|
|
1183
|
-
this.enabled = true;
|
|
1184
|
-
}
|
|
1185
|
-
get isEnabled() {
|
|
1186
|
-
return this.enabled;
|
|
1187
|
-
}
|
|
1188
|
-
_log(level, component, msg, data) {
|
|
1189
|
-
if (level !== "error" && !this.enabled) return;
|
|
1190
|
-
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
1191
|
-
const prefix = `[${ts}] [${level.toUpperCase()}] [${component}]`;
|
|
1192
|
-
console.error(data ? `${prefix} ${msg} ${JSON.stringify(data)}` : `${prefix} ${msg}`);
|
|
1193
|
-
this.fileStream?.write(JSON.stringify({ ts, level, component, msg, ...data && { data } }) + "\n");
|
|
1194
|
-
}
|
|
1195
|
-
};
|
|
1196
|
-
var logger = new MorphLogger();
|
|
1197
|
-
|
|
1198
|
-
// tools/warp_grep/agent/runner.ts
|
|
1199
|
-
var DEFAULT_API_URL = "https://api.morphllm.com";
|
|
1200
|
-
var TOOL_SPECS = [
|
|
1201
|
-
{
|
|
1202
|
-
type: "function",
|
|
1203
|
-
function: {
|
|
1204
|
-
name: "list_directory",
|
|
1205
|
-
description: "Execute ls or find commands to explore directory structure. Max 500 results. Common junk directories are excluded automatically.",
|
|
1206
|
-
parameters: {
|
|
1207
|
-
type: "object",
|
|
1208
|
-
properties: {
|
|
1209
|
-
command: {
|
|
1210
|
-
type: "string",
|
|
1211
|
-
description: "Full ls or find command (e.g. ls -la src/, find . -maxdepth 2 -type f -name '*.py', find . -type d, ls -d */)."
|
|
1212
|
-
}
|
|
1213
|
-
},
|
|
1214
|
-
required: ["command"]
|
|
1215
|
-
}
|
|
1216
|
-
}
|
|
1217
|
-
},
|
|
1218
|
-
{
|
|
1219
|
-
type: "function",
|
|
1220
|
-
function: {
|
|
1221
|
-
name: "grep_search",
|
|
1222
|
-
description: "Search for a regex pattern in file contents. Returns matching lines with file paths and line numbers. Case-insensitive. Respects .gitignore.",
|
|
1223
|
-
parameters: {
|
|
1224
|
-
type: "object",
|
|
1225
|
-
properties: {
|
|
1226
|
-
pattern: {
|
|
1227
|
-
type: "string",
|
|
1228
|
-
description: "Regex pattern to search for in file contents (e.g. 'class\\s+\\w+Error', 'import|require|from', 'def (get|set|update)_user')."
|
|
1229
|
-
},
|
|
1230
|
-
path: {
|
|
1231
|
-
type: "string",
|
|
1232
|
-
description: "File or directory to search in. Defaults to current working directory."
|
|
1233
|
-
},
|
|
1234
|
-
glob: {
|
|
1235
|
-
type: "string",
|
|
1236
|
-
description: "Glob pattern to filter files (e.g. '*.py', '*.{ts,tsx,js,jsx,py,go}', 'src/**/*.go', '!*.test.*')."
|
|
1237
|
-
},
|
|
1238
|
-
limit: {
|
|
1239
|
-
type: "integer",
|
|
1240
|
-
description: "Limit output to first N matching lines. Shows all matches if not specified."
|
|
1241
|
-
}
|
|
1242
|
-
},
|
|
1243
|
-
required: ["pattern"]
|
|
1244
|
-
}
|
|
1245
|
-
}
|
|
1246
|
-
},
|
|
1247
|
-
{
|
|
1248
|
-
type: "function",
|
|
1249
|
-
function: {
|
|
1250
|
-
name: "glob",
|
|
1251
|
-
description: "Find files by name/extension using glob patterns. Returns absolute paths sorted by modification time (newest first). Respects .gitignore. Max 100 results.",
|
|
1252
|
-
parameters: {
|
|
1253
|
-
type: "object",
|
|
1254
|
-
properties: {
|
|
1255
|
-
pattern: {
|
|
1256
|
-
type: "string",
|
|
1257
|
-
description: "Glob pattern to match files (e.g. '*.py', 'src/**/*.js', '*.{ts,tsx}', 'test_*.py')."
|
|
1258
|
-
},
|
|
1259
|
-
path: {
|
|
1260
|
-
type: "string",
|
|
1261
|
-
description: "Directory to search in. Defaults to repository root."
|
|
1262
|
-
}
|
|
1263
|
-
},
|
|
1264
|
-
required: ["pattern"]
|
|
1265
|
-
}
|
|
1266
|
-
}
|
|
1267
|
-
},
|
|
1268
|
-
{
|
|
1269
|
-
type: "function",
|
|
1270
|
-
function: {
|
|
1271
|
-
name: "read",
|
|
1272
|
-
description: "Read entire files or specific line ranges using absolute paths.",
|
|
1273
|
-
parameters: {
|
|
1274
|
-
type: "object",
|
|
1275
|
-
properties: {
|
|
1276
|
-
path: {
|
|
1277
|
-
type: "string",
|
|
1278
|
-
description: "File path to read, using absolute path (e.g. '/home/ubuntu/repo/src/main.py' or windows path)."
|
|
1279
|
-
},
|
|
1280
|
-
lines: {
|
|
1281
|
-
type: "string",
|
|
1282
|
-
description: "Optional line range (e.g. '1-50' or '1-20,45-80'). Omit to read entire file."
|
|
1283
|
-
}
|
|
1284
|
-
},
|
|
1285
|
-
required: ["path"]
|
|
1286
|
-
}
|
|
1287
|
-
}
|
|
1288
|
-
},
|
|
1289
|
-
{
|
|
1290
|
-
type: "function",
|
|
1291
|
-
function: {
|
|
1292
|
-
name: "finish",
|
|
1293
|
-
description: "Submit final answer with all relevant code locations. Include imports and over-include rather than miss context.",
|
|
1294
|
-
parameters: {
|
|
1295
|
-
type: "object",
|
|
1296
|
-
properties: {
|
|
1297
|
-
files: {
|
|
1298
|
-
type: "string",
|
|
1299
|
-
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."
|
|
1300
|
-
}
|
|
1301
|
-
},
|
|
1302
|
-
required: ["files"]
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
}
|
|
1306
|
-
];
|
|
1307
|
-
async function callModel(messages, model, options = {}) {
|
|
1308
|
-
const baseUrl = options.morphApiUrl || DEFAULT_API_URL;
|
|
1309
|
-
const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
|
|
1310
|
-
const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
|
|
1311
|
-
const parsedUrl = new URL(baseUrl);
|
|
1312
|
-
const baseURL = parsedUrl.pathname === "/" ? `${baseUrl}/v1` : baseUrl;
|
|
1313
|
-
const client = new import_openai.default({
|
|
1314
|
-
apiKey,
|
|
1315
|
-
baseURL,
|
|
1316
|
-
maxRetries: 0,
|
|
1317
|
-
timeout: timeoutMs,
|
|
1318
|
-
defaultHeaders: { "X-Morph-SDK-Version": SDK_VERSION }
|
|
1319
|
-
});
|
|
1320
|
-
const MAX_EMPTY_RETRIES = 1;
|
|
1321
|
-
logger.debug("WarpGrep", "model_call", { url: baseURL, model, message_count: messages.length });
|
|
1322
|
-
const callStartTime = Date.now();
|
|
1323
|
-
for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {
|
|
1324
|
-
let data;
|
|
1325
|
-
try {
|
|
1326
|
-
data = await client.chat.completions.create({
|
|
1327
|
-
model,
|
|
1328
|
-
temperature: 0,
|
|
1329
|
-
max_tokens: 2048,
|
|
1330
|
-
messages,
|
|
1331
|
-
tools: TOOL_SPECS,
|
|
1332
|
-
...options.search_type ? { search_type: options.search_type } : {}
|
|
1333
|
-
});
|
|
1334
|
-
} catch (error) {
|
|
1335
|
-
const callLatencyMs = Date.now() - callStartTime;
|
|
1336
|
-
if (error instanceof import_openai.default.APIError) {
|
|
1337
|
-
logger.error("WarpGrep", "model_call_error", { status: error.status, error: error.message, latency_ms: callLatencyMs });
|
|
1338
|
-
if (error.status === 404) {
|
|
1339
|
-
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";
|
|
1340
|
-
const errorText = error.message?.trim();
|
|
1341
|
-
throw new Error(errorText || defaultMsg);
|
|
1342
|
-
}
|
|
1343
|
-
} else {
|
|
1344
|
-
logger.error("WarpGrep", "model_call_error", { status: void 0, error: error instanceof Error ? error.message : String(error), latency_ms: callLatencyMs });
|
|
1345
|
-
}
|
|
1346
|
-
throw error;
|
|
1347
|
-
}
|
|
1348
|
-
const choice = data?.choices?.[0];
|
|
1349
|
-
const message = choice?.message;
|
|
1350
|
-
if (!message) {
|
|
1351
|
-
if (attempt === MAX_EMPTY_RETRIES) {
|
|
1352
|
-
throw new Error("Invalid response from model: no message in response");
|
|
1353
|
-
}
|
|
1354
|
-
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
1355
|
-
continue;
|
|
1356
|
-
}
|
|
1357
|
-
const toolCalls = (message.tool_calls || []).map((tc) => ({
|
|
1358
|
-
id: tc.id,
|
|
1359
|
-
type: "function",
|
|
1360
|
-
function: { name: tc.function.name, arguments: tc.function.arguments }
|
|
1361
|
-
}));
|
|
1362
|
-
if (message.content || toolCalls.length > 0) {
|
|
1363
|
-
logger.debug("WarpGrep", "model_call_complete", { latency_ms: Date.now() - callStartTime, tool_calls_count: toolCalls.length, finish_reason: choice?.finish_reason ?? "unknown" });
|
|
1364
|
-
return { content: message.content ?? null, tool_calls: toolCalls };
|
|
1365
|
-
}
|
|
1366
|
-
if (attempt === MAX_EMPTY_RETRIES) {
|
|
1367
|
-
const finishReason = choice?.finish_reason ?? "unknown";
|
|
1368
|
-
throw new Error(
|
|
1369
|
-
`Invalid response from model: no content and no tool_calls, finish_reason=${finishReason}`
|
|
1370
|
-
);
|
|
1371
|
-
}
|
|
1372
|
-
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
1373
|
-
}
|
|
1374
|
-
throw new Error("Invalid response from model");
|
|
1375
|
-
}
|
|
1376
|
-
function safeParseJSON(s) {
|
|
1377
|
-
try {
|
|
1378
|
-
return JSON.parse(s);
|
|
1379
|
-
} catch {
|
|
1380
|
-
return {};
|
|
1381
|
-
}
|
|
1382
|
-
}
|
|
1383
|
-
async function executeTool(provider, name, args, repoRoot) {
|
|
1384
|
-
switch (name) {
|
|
1385
|
-
case "grep_search": {
|
|
1386
|
-
const grepArgs = {
|
|
1387
|
-
pattern: args.pattern,
|
|
1388
|
-
path: args.path || "."
|
|
1389
|
-
};
|
|
1390
|
-
if (args.glob) grepArgs.glob = args.glob;
|
|
1391
|
-
if (args.case_sensitive !== void 0) grepArgs.case_sensitive = args.case_sensitive;
|
|
1392
|
-
const result = await toolGrep(provider, grepArgs);
|
|
1393
|
-
let output = result.output;
|
|
1394
|
-
if (args.limit && typeof args.limit === "number") {
|
|
1395
|
-
const lines = output.split("\n");
|
|
1396
|
-
if (lines.length > args.limit) {
|
|
1397
|
-
output = lines.slice(0, args.limit).join("\n") + `
|
|
1398
|
-
... (truncated at ${args.limit} lines)`;
|
|
1399
|
-
}
|
|
1400
|
-
}
|
|
1401
|
-
return output;
|
|
1402
|
-
}
|
|
1403
|
-
case "glob": {
|
|
1404
|
-
return toolGlob(provider, {
|
|
1405
|
-
pattern: args.pattern,
|
|
1406
|
-
path: args.path
|
|
1407
|
-
});
|
|
1408
|
-
}
|
|
1409
|
-
case "list_directory": {
|
|
1410
|
-
const dirPath = extractPathFromCommand(args.command || ".");
|
|
1411
|
-
return toolListDirectory(provider, { path: dirPath }, repoRoot);
|
|
1412
|
-
}
|
|
1413
|
-
case "read": {
|
|
1414
|
-
const readArgs = {
|
|
1415
|
-
path: args.path
|
|
1416
|
-
};
|
|
1417
|
-
if (args.lines && typeof args.lines === "string") {
|
|
1418
|
-
Object.assign(readArgs, parseReadLines(args.lines));
|
|
1419
|
-
}
|
|
1420
|
-
return toolRead(provider, readArgs);
|
|
1421
|
-
}
|
|
1422
|
-
default:
|
|
1423
|
-
return `Unknown tool: ${name}`;
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
async function* runWarpGrepStreaming(config) {
|
|
1427
|
-
const totalStart = Date.now();
|
|
1428
|
-
const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
|
|
1429
|
-
const timings = { turns: [], timeout_ms: timeoutMs };
|
|
1430
|
-
const repoRoot = config.repoRoot || process.cwd();
|
|
1431
|
-
const model = config.model || DEFAULT_MODEL;
|
|
1432
|
-
const messages = [];
|
|
1433
|
-
const maxTurns = AGENT_CONFIG.MAX_TURNS;
|
|
1434
|
-
logger.debug("WarpGrep", "session_start", { search_term: config.searchTerm, model, max_turns: maxTurns });
|
|
1435
|
-
const initialStateStart = Date.now();
|
|
1436
|
-
const initialState = await buildInitialState(repoRoot, config.searchTerm, config.provider, { search_type: config.search_type });
|
|
1437
|
-
timings.initial_state_ms = Date.now() - initialStateStart;
|
|
1438
|
-
logger.debug("WarpGrep", "initial_state", { system_prompt_len: initialState.length, user_message_len: initialState.length });
|
|
1439
|
-
messages.push({ role: "user", content: initialState });
|
|
1440
|
-
const provider = config.provider;
|
|
1441
|
-
const errors = [];
|
|
1442
|
-
let finishMeta;
|
|
1443
|
-
let terminationReason = "terminated";
|
|
1444
|
-
for (let turn = 1; turn <= maxTurns; turn += 1) {
|
|
1445
|
-
const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
|
|
1446
|
-
logger.debug("WarpGrep", "turn_start", { turn, message_count: messages.length });
|
|
1447
|
-
const beforeChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
|
|
1448
|
-
enforceContextLimit(messages);
|
|
1449
|
-
const afterChars = messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0);
|
|
1450
|
-
if (afterChars < beforeChars) {
|
|
1451
|
-
logger.debug("WarpGrep", "context_truncated", { before_chars: beforeChars, after_chars: afterChars });
|
|
1452
|
-
}
|
|
1453
|
-
const modelCallStart = Date.now();
|
|
1454
|
-
const response = await callModel(messages, model, {
|
|
1455
|
-
morphApiKey: config.morphApiKey,
|
|
1456
|
-
morphApiUrl: config.morphApiUrl,
|
|
1457
|
-
retryConfig: config.retryConfig,
|
|
1458
|
-
timeout: timeoutMs,
|
|
1459
|
-
search_type: config.search_type
|
|
1460
|
-
}).catch((e) => {
|
|
1461
|
-
const errMsg = e instanceof Error ? e.message : String(e);
|
|
1462
|
-
console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
|
|
1463
|
-
logger.error("WarpGrep", "error", { turn, error: errMsg, phase: "model_call" });
|
|
1464
|
-
errors.push({ message: errMsg });
|
|
1465
|
-
return null;
|
|
1466
|
-
});
|
|
1467
|
-
turnMetrics.morph_api_ms = Date.now() - modelCallStart;
|
|
1468
|
-
if (!response) {
|
|
1469
|
-
timings.turns.push(turnMetrics);
|
|
1470
|
-
break;
|
|
1471
|
-
}
|
|
1472
|
-
const toolCalls = response.tool_calls;
|
|
1473
|
-
logger.debug("WarpGrep", "model_response", { turn, tool_calls: toolCalls.map((tc) => tc.function.name), latency_ms: turnMetrics.morph_api_ms });
|
|
1474
|
-
messages.push({
|
|
1475
|
-
role: "assistant",
|
|
1476
|
-
content: response.content,
|
|
1477
|
-
...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
|
|
1478
|
-
});
|
|
1479
|
-
if (toolCalls.length === 0) {
|
|
1480
|
-
console.error(`[warp_grep] No tool calls on turn ${turn}. Content: ${(response.content || "").slice(0, 500)}`);
|
|
1481
|
-
errors.push({ message: "No tool calls produced by the model." });
|
|
1482
|
-
terminationReason = "terminated";
|
|
1483
|
-
timings.turns.push(turnMetrics);
|
|
1484
|
-
break;
|
|
1485
|
-
}
|
|
1486
|
-
yield {
|
|
1487
|
-
turn,
|
|
1488
|
-
toolCalls: toolCalls.map((tc) => ({
|
|
1489
|
-
name: tc.function.name,
|
|
1490
|
-
arguments: safeParseJSON(tc.function.arguments)
|
|
1491
|
-
}))
|
|
1492
|
-
};
|
|
1493
|
-
const finishCall = toolCalls.find((tc) => tc.function.name === "finish");
|
|
1494
|
-
if (finishCall) {
|
|
1495
|
-
const args = safeParseJSON(finishCall.function.arguments);
|
|
1496
|
-
const filesStr = args.files || "";
|
|
1497
|
-
const files = parseFinishFiles(filesStr);
|
|
1498
|
-
finishMeta = { files };
|
|
1499
|
-
terminationReason = "completed";
|
|
1500
|
-
logger.debug("WarpGrep", "finish", { turns: turn, files: files.map((f) => f.path) });
|
|
1501
|
-
if (files.length === 0) {
|
|
1502
|
-
const payload2 = filesStr || "No relevant code found.";
|
|
1503
|
-
timings.turns.push(turnMetrics);
|
|
1504
|
-
timings.total_ms = Date.now() - totalStart;
|
|
1505
|
-
return {
|
|
1506
|
-
terminationReason: "completed",
|
|
1507
|
-
messages,
|
|
1508
|
-
finish: { payload: payload2, metadata: finishMeta },
|
|
1509
|
-
timings
|
|
1510
|
-
};
|
|
1511
|
-
}
|
|
1512
|
-
timings.turns.push(turnMetrics);
|
|
1513
|
-
break;
|
|
1514
|
-
}
|
|
1515
|
-
const toolExecStart = Date.now();
|
|
1516
|
-
const results = await Promise.all(
|
|
1517
|
-
toolCalls.map(async (tc) => {
|
|
1518
|
-
const args = safeParseJSON(tc.function.arguments);
|
|
1519
|
-
const argsSummary = Object.fromEntries(Object.entries(args).map(([k, v]) => [k, typeof v === "string" && v.length > 100 ? v.slice(0, 100) + "..." : v]));
|
|
1520
|
-
logger.debug("WarpGrep", "tool_exec", { turn, tool: tc.function.name, args_summary: argsSummary });
|
|
1521
|
-
const toolStart = Date.now();
|
|
1522
|
-
const output = await executeTool(provider, tc.function.name, args, repoRoot).catch((err) => String(err));
|
|
1523
|
-
logger.debug("WarpGrep", "tool_result", { turn, tool: tc.function.name, result_len: output.length, latency_ms: Date.now() - toolStart });
|
|
1524
|
-
return { tool_call_id: tc.id, content: output };
|
|
1525
|
-
})
|
|
1526
|
-
);
|
|
1527
|
-
turnMetrics.local_tools_ms = Date.now() - toolExecStart;
|
|
1528
|
-
for (const result of results) {
|
|
1529
|
-
messages.push({ role: "tool", tool_call_id: result.tool_call_id, content: result.content });
|
|
1530
|
-
}
|
|
1531
|
-
const turnMsg = formatTurnMessage(turn, maxTurns);
|
|
1532
|
-
const budget = calculateContextBudget(messages);
|
|
1533
|
-
messages.push({ role: "user", content: turnMsg + "\n" + budget });
|
|
1534
|
-
timings.turns.push(turnMetrics);
|
|
1535
|
-
}
|
|
1536
|
-
if (terminationReason !== "completed" || !finishMeta) {
|
|
1537
|
-
timings.total_ms = Date.now() - totalStart;
|
|
1538
|
-
return { terminationReason, messages, errors, timings };
|
|
1539
|
-
}
|
|
1540
|
-
const parts = ["Relevant context found:"];
|
|
1541
|
-
for (const f of finishMeta.files) {
|
|
1542
|
-
const ranges = f.lines === "*" ? "*" : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(", ") : "*";
|
|
1543
|
-
parts.push(`- ${f.path}: ${ranges}`);
|
|
1544
|
-
}
|
|
1545
|
-
const payload = parts.join("\n");
|
|
1546
|
-
const finishResolutionStart = Date.now();
|
|
1547
|
-
const fileReadErrors = [];
|
|
1548
|
-
const resolved = await readFinishFiles(
|
|
1549
|
-
repoRoot,
|
|
1550
|
-
finishMeta.files,
|
|
1551
|
-
async (p, s, e) => {
|
|
1552
|
-
let resolvedPath = p;
|
|
1553
|
-
if (!p.startsWith(repoRoot)) {
|
|
1554
|
-
const relative = p.startsWith("/") ? p.slice(1) : p;
|
|
1555
|
-
resolvedPath = import_path3.default.join(repoRoot, relative);
|
|
1556
|
-
}
|
|
1557
|
-
try {
|
|
1558
|
-
const rr = await provider.read({ path: resolvedPath, start: s, end: e });
|
|
1559
|
-
return rr.lines.map((l) => {
|
|
1560
|
-
const idx = l.indexOf("|");
|
|
1561
|
-
return idx >= 0 ? l.slice(idx + 1) : l;
|
|
1562
|
-
});
|
|
1563
|
-
} catch (err) {
|
|
1564
|
-
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
1565
|
-
fileReadErrors.push({ path: resolvedPath, error: errorMsg });
|
|
1566
|
-
console.error(`[warp_grep] Failed to read file: ${resolvedPath} - ${errorMsg}`);
|
|
1567
|
-
return [`[couldn't find: ${resolvedPath}]`];
|
|
1568
|
-
}
|
|
1569
|
-
}
|
|
1570
|
-
);
|
|
1571
|
-
timings.finish_resolution_ms = Date.now() - finishResolutionStart;
|
|
1572
|
-
if (fileReadErrors.length > 0) {
|
|
1573
|
-
errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
|
|
1574
|
-
}
|
|
1575
|
-
timings.total_ms = Date.now() - totalStart;
|
|
1576
|
-
return {
|
|
1577
|
-
terminationReason: "completed",
|
|
1578
|
-
messages,
|
|
1579
|
-
finish: { payload, metadata: finishMeta, resolved },
|
|
1580
|
-
timings
|
|
1581
|
-
};
|
|
1582
|
-
}
|
|
1583
|
-
async function runWarpGrep(config) {
|
|
1584
|
-
const gen = runWarpGrepStreaming(config);
|
|
1585
|
-
let result = await gen.next();
|
|
1586
|
-
while (!result.done) {
|
|
1587
|
-
result = await gen.next();
|
|
1588
|
-
}
|
|
1589
|
-
return result.value;
|
|
1590
|
-
}
|
|
1591
|
-
|
|
1592
|
-
// tools/warp_grep/providers/remote.ts
|
|
1593
|
-
init_config();
|
|
1594
|
-
var SKIP_NAMES = /* @__PURE__ */ new Set([
|
|
1595
|
-
// Version control
|
|
1596
|
-
".git",
|
|
1597
|
-
".svn",
|
|
1598
|
-
".hg",
|
|
1599
|
-
".bzr",
|
|
1600
|
-
// Dependencies
|
|
1601
|
-
"node_modules",
|
|
1602
|
-
"bower_components",
|
|
1603
|
-
".pnpm",
|
|
1604
|
-
".yarn",
|
|
1605
|
-
"vendor",
|
|
1606
|
-
"Pods",
|
|
1607
|
-
".bundle",
|
|
1608
|
-
// Python
|
|
1609
|
-
"__pycache__",
|
|
1610
|
-
".pytest_cache",
|
|
1611
|
-
".mypy_cache",
|
|
1612
|
-
".ruff_cache",
|
|
1613
|
-
".venv",
|
|
1614
|
-
"venv",
|
|
1615
|
-
".tox",
|
|
1616
|
-
".nox",
|
|
1617
|
-
".eggs",
|
|
1618
|
-
// Build outputs
|
|
1619
|
-
"dist",
|
|
1620
|
-
"build",
|
|
1621
|
-
"out",
|
|
1622
|
-
"output",
|
|
1623
|
-
"target",
|
|
1624
|
-
"_build",
|
|
1625
|
-
".next",
|
|
1626
|
-
".nuxt",
|
|
1627
|
-
".output",
|
|
1628
|
-
".vercel",
|
|
1629
|
-
".netlify",
|
|
1630
|
-
// Cache
|
|
1631
|
-
".cache",
|
|
1632
|
-
".parcel-cache",
|
|
1633
|
-
".turbo",
|
|
1634
|
-
".nx",
|
|
1635
|
-
".gradle",
|
|
1636
|
-
// IDE
|
|
1637
|
-
".idea",
|
|
1638
|
-
".vscode",
|
|
1639
|
-
".vs",
|
|
1640
|
-
// Coverage
|
|
1641
|
-
"coverage",
|
|
1642
|
-
".coverage",
|
|
1643
|
-
"htmlcov",
|
|
1644
|
-
".nyc_output",
|
|
1645
|
-
// Temp
|
|
1646
|
-
"tmp",
|
|
1647
|
-
"temp",
|
|
1648
|
-
".tmp",
|
|
1649
|
-
".temp",
|
|
1650
|
-
// Lock files
|
|
1651
|
-
"package-lock.json",
|
|
1652
|
-
"yarn.lock",
|
|
1653
|
-
"pnpm-lock.yaml",
|
|
1654
|
-
"bun.lockb",
|
|
1655
|
-
"Cargo.lock",
|
|
1656
|
-
"Gemfile.lock",
|
|
1657
|
-
"poetry.lock"
|
|
1658
|
-
]);
|
|
1659
|
-
var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
1660
|
-
".min.js",
|
|
1661
|
-
".min.css",
|
|
1662
|
-
".bundle.js",
|
|
1663
|
-
".wasm",
|
|
1664
|
-
".so",
|
|
1665
|
-
".dll",
|
|
1666
|
-
".pyc",
|
|
1667
|
-
".map",
|
|
1668
|
-
".js.map"
|
|
1669
|
-
]);
|
|
1670
|
-
function shouldSkip(name) {
|
|
1671
|
-
if (SKIP_NAMES.has(name)) return true;
|
|
1672
|
-
if (name.startsWith(".")) return true;
|
|
1673
|
-
for (const ext of SKIP_EXTENSIONS) {
|
|
1674
|
-
if (name.endsWith(ext)) return true;
|
|
1675
|
-
}
|
|
1676
|
-
return false;
|
|
1677
|
-
}
|
|
1678
|
-
var RemoteCommandsProvider = class {
|
|
1679
|
-
constructor(repoRoot, commands) {
|
|
1680
|
-
this.repoRoot = repoRoot;
|
|
1681
|
-
this.commands = commands;
|
|
1682
|
-
}
|
|
1683
|
-
/**
|
|
1684
|
-
* Run grep command and parse ripgrep output
|
|
1685
|
-
*/
|
|
1686
|
-
async grep(params) {
|
|
1687
|
-
try {
|
|
1688
|
-
const stdout = await this.commands.grep(params.pattern, params.path, params.glob);
|
|
1689
|
-
const lines = (stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
|
|
1690
|
-
if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {
|
|
1691
|
-
const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);
|
|
1692
|
-
truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);
|
|
1693
|
-
return { lines: truncated };
|
|
1694
|
-
}
|
|
1695
|
-
return { lines };
|
|
1696
|
-
} catch (error) {
|
|
1697
|
-
return {
|
|
1698
|
-
lines: [],
|
|
1699
|
-
error: `[GREP ERROR] ${error instanceof Error ? error.message : String(error)}`
|
|
1700
|
-
};
|
|
1701
|
-
}
|
|
1702
|
-
}
|
|
1703
|
-
/**
|
|
1704
|
-
* Read file and add line numbers
|
|
1705
|
-
*/
|
|
1706
|
-
async read(params) {
|
|
1707
|
-
const rawStart = params.start;
|
|
1708
|
-
const rawEnd = params.end;
|
|
1709
|
-
const startValid = rawStart === void 0 || Number.isFinite(rawStart) && rawStart > 0;
|
|
1710
|
-
const endValid = rawEnd === void 0 || Number.isFinite(rawEnd) && rawEnd > 0;
|
|
1711
|
-
const rangeValid = startValid && endValid && (rawStart === void 0 || rawEnd === void 0 || rawStart <= rawEnd);
|
|
1712
|
-
const start = rangeValid && rawStart !== void 0 ? rawStart : 1;
|
|
1713
|
-
const end = rangeValid && rawEnd !== void 0 ? rawEnd : 1e6;
|
|
1714
|
-
try {
|
|
1715
|
-
const stdout = await this.commands.read(params.path, start, end);
|
|
1716
|
-
const contentLines = (stdout || "").split("\n");
|
|
1717
|
-
if (contentLines.length > 0 && contentLines[contentLines.length - 1] === "") {
|
|
1718
|
-
contentLines.pop();
|
|
1719
|
-
}
|
|
1720
|
-
const lines = contentLines.map((content, idx) => `${start + idx}|${content}`);
|
|
1721
|
-
if (lines.length > AGENT_CONFIG.MAX_READ_LINES) {
|
|
1722
|
-
const truncated = lines.slice(0, AGENT_CONFIG.MAX_READ_LINES);
|
|
1723
|
-
truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_READ_LINES} of ${lines.length} lines)`);
|
|
1724
|
-
return { lines: truncated };
|
|
1725
|
-
}
|
|
1726
|
-
return { lines };
|
|
1727
|
-
} catch (error) {
|
|
1728
|
-
return {
|
|
1729
|
-
lines: [],
|
|
1730
|
-
error: `[READ ERROR] ${error instanceof Error ? error.message : String(error)}`
|
|
1731
|
-
};
|
|
1732
|
-
}
|
|
1733
|
-
}
|
|
1734
|
-
/**
|
|
1735
|
-
* List directory and parse find output
|
|
1736
|
-
*/
|
|
1737
|
-
async listDirectory(params) {
|
|
1738
|
-
const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
|
|
1739
|
-
const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
|
|
1740
|
-
try {
|
|
1741
|
-
const stdout = await this.commands.listDir(params.path, maxDepth);
|
|
1742
|
-
const paths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
|
|
1743
|
-
const regex = params.pattern ? new RegExp(params.pattern) : null;
|
|
1744
|
-
const entries = [];
|
|
1745
|
-
for (const fullPath of paths) {
|
|
1746
|
-
if (fullPath === params.path || fullPath === this.repoRoot) continue;
|
|
1747
|
-
const name = fullPath.split("/").pop() || "";
|
|
1748
|
-
if (shouldSkip(name)) continue;
|
|
1749
|
-
if (regex && !regex.test(name)) continue;
|
|
1750
|
-
let relativePath = fullPath;
|
|
1751
|
-
if (fullPath.startsWith(this.repoRoot)) {
|
|
1752
|
-
relativePath = fullPath.slice(this.repoRoot.length).replace(/^\//, "");
|
|
1753
|
-
}
|
|
1754
|
-
const depth = relativePath.split("/").filter(Boolean).length - 1;
|
|
1755
|
-
const hasExtension = name.includes(".") && !name.startsWith(".");
|
|
1756
|
-
const type = hasExtension ? "file" : "dir";
|
|
1757
|
-
entries.push({
|
|
1758
|
-
name,
|
|
1759
|
-
path: relativePath,
|
|
1760
|
-
type,
|
|
1761
|
-
depth: Math.max(0, depth)
|
|
1762
|
-
});
|
|
1763
|
-
if (entries.length >= maxResults) break;
|
|
1764
|
-
}
|
|
1765
|
-
return entries;
|
|
1766
|
-
} catch (error) {
|
|
1767
|
-
return [];
|
|
1768
|
-
}
|
|
1769
|
-
}
|
|
1770
|
-
/**
|
|
1771
|
-
* Glob search - finds files matching a pattern.
|
|
1772
|
-
* Falls back to a grep --files approach via the listDir command.
|
|
1773
|
-
*/
|
|
1774
|
-
async glob(params) {
|
|
1775
|
-
const searchPath = params.path || this.repoRoot;
|
|
1776
|
-
try {
|
|
1777
|
-
const stdout = await this.commands.listDir(searchPath, 10);
|
|
1778
|
-
const allPaths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
|
|
1779
|
-
const globToRegex = (glob) => {
|
|
1780
|
-
const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
1781
|
-
return new RegExp(escaped);
|
|
1782
|
-
};
|
|
1783
|
-
const regex = globToRegex(params.pattern);
|
|
1784
|
-
const matched = allPaths.filter((p) => {
|
|
1785
|
-
const name = p.split("/").pop() || "";
|
|
1786
|
-
return regex.test(name) && !shouldSkip(name);
|
|
1787
|
-
});
|
|
1788
|
-
const totalFound = matched.length;
|
|
1789
|
-
return { files: matched.slice(0, 100), searchDir: searchPath, totalFound };
|
|
1790
|
-
} catch (error) {
|
|
1791
|
-
return {
|
|
1792
|
-
files: [],
|
|
1793
|
-
searchDir: searchPath,
|
|
1794
|
-
totalFound: 0,
|
|
1795
|
-
error: `[GLOB ERROR] ${error instanceof Error ? error.message : String(error)}`
|
|
1796
|
-
};
|
|
1797
|
-
}
|
|
1798
|
-
}
|
|
1799
|
-
};
|
|
1800
|
-
|
|
1801
|
-
// tools/warp_grep/providers/code_storage_http.ts
|
|
1802
|
-
var MODEL_REPO_ROOT = /^\/?home\/ubuntu\/repo(?:\/|$)/;
|
|
1803
|
-
function toRepoRelative(path6) {
|
|
1804
|
-
if (!path6) return path6;
|
|
1805
|
-
const stripped = path6.replace(MODEL_REPO_ROOT, "").replace(/^\.?\/+/, "");
|
|
1806
|
-
return stripped || ".";
|
|
1807
|
-
}
|
|
1808
|
-
async function post(url, body, op, apiKey) {
|
|
1809
|
-
const res = await fetch(url, {
|
|
1810
|
-
method: "POST",
|
|
1811
|
-
headers: {
|
|
1812
|
-
"Content-Type": "application/json",
|
|
1813
|
-
...apiKey ? { Authorization: `Bearer ${apiKey}` } : {}
|
|
1814
|
-
},
|
|
1815
|
-
body: JSON.stringify(body)
|
|
1816
|
-
});
|
|
1817
|
-
if (!res.ok) {
|
|
1818
|
-
const text = await res.text().catch(() => res.statusText);
|
|
1819
|
-
try {
|
|
1820
|
-
const parsed = JSON.parse(text);
|
|
1821
|
-
if (parsed.error) return `Error: ${parsed.error}`;
|
|
1822
|
-
} catch {
|
|
1823
|
-
}
|
|
1824
|
-
return `Error: ${op} failed (${res.status}): ${text}`;
|
|
1825
|
-
}
|
|
1826
|
-
const data = await res.json();
|
|
1827
|
-
if (data.error) throw new Error(data.error);
|
|
1828
|
-
return data.stdout;
|
|
1829
|
-
}
|
|
1830
|
-
function createCodeStorageHttpCommands(config) {
|
|
1831
|
-
const { baseUrl, repoId, branch, apiKey } = config;
|
|
1832
|
-
const encodedRepoId = encodeURIComponent(repoId);
|
|
1833
|
-
return {
|
|
1834
|
-
grep: (pattern, path6, glob) => post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path: toRepoRelative(path6), glob, branch }, "grep", apiKey),
|
|
1835
|
-
read: (path6, start, end) => post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path: toRepoRelative(path6), start, end, branch }, "read", apiKey),
|
|
1836
|
-
listDir: (path6, maxDepth) => post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path: toRepoRelative(path6), maxDepth, branch }, "list", apiKey)
|
|
1837
|
-
};
|
|
1838
|
-
}
|
|
1839
|
-
|
|
1840
|
-
// tools/warp_grep/utils/github.ts
|
|
1841
|
-
function parseGitHubUrl(input) {
|
|
1842
|
-
input = input.trim();
|
|
1843
|
-
const urlPattern = /^(?:https?:\/\/)?github\.com\/([^\/]+)\/([^\/\?\#]+)/;
|
|
1844
|
-
const match = input.match(urlPattern);
|
|
1845
|
-
if (match) {
|
|
1846
|
-
return { owner: match[1], repo: match[2].replace(/\.git$/, "") };
|
|
1847
|
-
}
|
|
1848
|
-
const shortPattern = /^([^\/]+)\/([^\/]+)$/;
|
|
1849
|
-
const shortMatch = input.match(shortPattern);
|
|
1850
|
-
if (shortMatch && !shortMatch[1].includes(".")) {
|
|
1851
|
-
return { owner: shortMatch[1], repo: shortMatch[2].replace(/\.git$/, "") };
|
|
1852
|
-
}
|
|
1853
|
-
throw new Error(
|
|
1854
|
-
`Invalid GitHub URL or shorthand: "${input}". Expected "owner/repo" or "https://github.com/owner/repo"`
|
|
1855
|
-
);
|
|
1856
|
-
}
|
|
1857
|
-
|
|
1858
|
-
// tools/utils/resilience.ts
|
|
1859
|
-
var DEFAULT_RETRY_CONFIG = {
|
|
1860
|
-
maxRetries: 3,
|
|
1861
|
-
initialDelay: 1e3,
|
|
1862
|
-
maxDelay: 3e4,
|
|
1863
|
-
backoffMultiplier: 2,
|
|
1864
|
-
retryableErrors: ["ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND"]
|
|
1865
|
-
};
|
|
1866
|
-
async function fetchWithRetry(url, options, retryConfig = {}) {
|
|
1867
|
-
const {
|
|
1868
|
-
maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,
|
|
1869
|
-
initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,
|
|
1870
|
-
maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,
|
|
1871
|
-
backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,
|
|
1872
|
-
retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,
|
|
1873
|
-
onRetry
|
|
1874
|
-
} = retryConfig;
|
|
1875
|
-
let lastError = null;
|
|
1876
|
-
let delay = initialDelay;
|
|
1877
|
-
options = { ...options, headers: { "X-Morph-SDK-Version": SDK_VERSION, ...options.headers } };
|
|
1878
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
1879
|
-
try {
|
|
1880
|
-
const response = await fetch(url, options);
|
|
1881
|
-
if (response.status === 429 || response.status === 503) {
|
|
1882
|
-
if (attempt < maxRetries) {
|
|
1883
|
-
const retryAfter = response.headers.get("Retry-After");
|
|
1884
|
-
const waitTime = retryAfter ? parseInt(retryAfter) * 1e3 : Math.min(delay, maxDelay);
|
|
1885
|
-
const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);
|
|
1886
|
-
if (onRetry) {
|
|
1887
|
-
onRetry(attempt + 1, error);
|
|
1888
|
-
}
|
|
1889
|
-
await sleep(waitTime);
|
|
1890
|
-
delay *= backoffMultiplier;
|
|
1891
|
-
continue;
|
|
1892
|
-
}
|
|
1893
|
-
}
|
|
1894
|
-
return response;
|
|
1895
|
-
} catch (error) {
|
|
1896
|
-
lastError = error;
|
|
1897
|
-
const isRetryable = retryableErrors.some(
|
|
1898
|
-
(errType) => lastError?.message?.includes(errType)
|
|
1899
|
-
);
|
|
1900
|
-
if (!isRetryable || attempt === maxRetries) {
|
|
1901
|
-
throw lastError;
|
|
1902
|
-
}
|
|
1903
|
-
const waitTime = Math.min(delay, maxDelay);
|
|
1904
|
-
if (onRetry) {
|
|
1905
|
-
onRetry(attempt + 1, lastError);
|
|
1906
|
-
}
|
|
1907
|
-
await sleep(waitTime);
|
|
1908
|
-
delay *= backoffMultiplier;
|
|
1909
|
-
}
|
|
1910
|
-
}
|
|
1911
|
-
throw lastError || new Error("Max retries exceeded");
|
|
1912
|
-
}
|
|
1913
|
-
async function withTimeout(promise, timeoutMs, errorMessage) {
|
|
1914
|
-
let timeoutId;
|
|
1915
|
-
const timeoutPromise = new Promise((_, reject) => {
|
|
1916
|
-
timeoutId = setTimeout(() => {
|
|
1917
|
-
reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));
|
|
1918
|
-
}, timeoutMs);
|
|
1919
|
-
});
|
|
1920
|
-
try {
|
|
1921
|
-
const result = await Promise.race([promise, timeoutPromise]);
|
|
1922
|
-
clearTimeout(timeoutId);
|
|
1923
|
-
return result;
|
|
1924
|
-
} catch (error) {
|
|
1925
|
-
clearTimeout(timeoutId);
|
|
1926
|
-
throw error;
|
|
1927
|
-
}
|
|
1928
|
-
}
|
|
1929
|
-
function sleep(ms) {
|
|
1930
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1931
|
-
}
|
|
1932
|
-
var MorphError = class extends Error {
|
|
1933
|
-
constructor(message, code, statusCode, retryable = false) {
|
|
1934
|
-
super(message);
|
|
1935
|
-
this.code = code;
|
|
1936
|
-
this.statusCode = statusCode;
|
|
1937
|
-
this.retryable = retryable;
|
|
1938
|
-
this.name = "MorphError";
|
|
1939
|
-
}
|
|
1940
|
-
};
|
|
1941
|
-
|
|
1942
|
-
// core/error.ts
|
|
1943
|
-
async function toMorphError(response) {
|
|
1944
|
-
let message = `Morph API request failed (${response.status})`;
|
|
1945
|
-
let code = "api_error";
|
|
1946
|
-
try {
|
|
1947
|
-
const body = await response.json();
|
|
1948
|
-
message = body.error?.message ?? body.message ?? message;
|
|
1949
|
-
code = body.error?.code ?? body.error?.type ?? code;
|
|
1950
|
-
} catch {
|
|
1951
|
-
}
|
|
1952
|
-
if (response.status === 401) code = "authentication_error";
|
|
1953
|
-
if (response.status === 429) code = "rate_limit_exceeded";
|
|
1954
|
-
const retryable = response.status === 429 || response.status === 503;
|
|
1955
|
-
return new MorphError(message, code, response.status, retryable);
|
|
1956
|
-
}
|
|
1957
|
-
|
|
1958
|
-
// core/client.ts
|
|
1959
|
-
var DEFAULT_BASE_URL = "https://api.morphllm.com";
|
|
1960
|
-
var DEFAULT_REPOS_URL = "https://repos.morphllm.com";
|
|
1961
|
-
var DEFAULT_TIMEOUT = 6e4;
|
|
1962
|
-
var env = (name) => typeof process !== "undefined" ? process.env?.[name] : void 0;
|
|
1963
|
-
var stripTrailingSlash = (url) => url.replace(/\/+$/, "");
|
|
1964
|
-
var MorphAPIClient = class {
|
|
1965
|
-
/** Explicit key as provided; resolved against env at request time. */
|
|
1966
|
-
apiKey;
|
|
1967
|
-
baseURL;
|
|
1968
|
-
reposURL;
|
|
1969
|
-
/** Explicit default timeout (ms), if set. The request default is applied lazily so
|
|
1970
|
-
* resources can read an undefined value and supply their own fallback. */
|
|
1971
|
-
timeout;
|
|
1972
|
-
retryConfig;
|
|
1973
|
-
debug;
|
|
1974
|
-
constructor(options = {}) {
|
|
1975
|
-
this.apiKey = options.apiKey;
|
|
1976
|
-
this.baseURL = stripTrailingSlash(options.baseURL ?? DEFAULT_BASE_URL);
|
|
1977
|
-
this.reposURL = stripTrailingSlash(options.reposURL ?? env("MORPH_SEARCH_URL") ?? DEFAULT_REPOS_URL);
|
|
1978
|
-
this.timeout = options.timeout;
|
|
1979
|
-
this.retryConfig = options.retryConfig;
|
|
1980
|
-
this.debug = options.debug ?? false;
|
|
1981
|
-
if (this.debug) logger.enable();
|
|
1982
|
-
}
|
|
1983
|
-
/** The key actually used for requests: explicit, else `MORPH_API_KEY`. */
|
|
1984
|
-
resolveApiKey() {
|
|
1985
|
-
return this.apiKey ?? env("MORPH_API_KEY");
|
|
1986
|
-
}
|
|
1987
|
-
/** Headers shared with tools that bring their own HTTP client (FastApply/WarpGrep via the `openai` package). */
|
|
1988
|
-
defaultHeaders() {
|
|
1989
|
-
return { "X-Morph-SDK-Version": SDK_VERSION };
|
|
1990
|
-
}
|
|
1991
|
-
buildURL(path6, baseURL) {
|
|
1992
|
-
if (/^https?:\/\//i.test(path6)) return path6;
|
|
1993
|
-
const base = stripTrailingSlash(baseURL ?? this.baseURL);
|
|
1994
|
-
return `${base}${path6.startsWith("/") ? "" : "/"}${path6}`;
|
|
1995
|
-
}
|
|
1996
|
-
buildHeaders(apiKey, extra) {
|
|
1997
|
-
return {
|
|
1998
|
-
"Content-Type": "application/json",
|
|
1999
|
-
"X-Morph-SDK-Version": SDK_VERSION,
|
|
2000
|
-
Authorization: `Bearer ${apiKey}`,
|
|
2001
|
-
...extra
|
|
2002
|
-
};
|
|
2003
|
-
}
|
|
2004
|
-
applyQuery(url, query) {
|
|
2005
|
-
if (!query) return url;
|
|
2006
|
-
const params = new URLSearchParams();
|
|
2007
|
-
for (const [key, value] of Object.entries(query)) {
|
|
2008
|
-
if (value !== void 0 && value !== null) params.set(key, String(value));
|
|
2009
|
-
}
|
|
2010
|
-
const qs = params.toString();
|
|
2011
|
-
return qs ? `${url}${url.includes("?") ? "&" : "?"}${qs}` : url;
|
|
2012
|
-
}
|
|
2013
|
-
async request(method, path6, opts = {}) {
|
|
2014
|
-
const apiKey = this.resolveApiKey();
|
|
2015
|
-
if (!apiKey) {
|
|
2016
|
-
throw new MorphError(
|
|
2017
|
-
"Morph API key not found. Set the MORPH_API_KEY environment variable or pass apiKey in config.",
|
|
2018
|
-
"missing_api_key",
|
|
2019
|
-
401
|
|
2020
|
-
);
|
|
2021
|
-
}
|
|
2022
|
-
const url = this.applyQuery(this.buildURL(path6, opts.baseURL), opts.query);
|
|
2023
|
-
const timeout = opts.timeout ?? this.timeout ?? DEFAULT_TIMEOUT;
|
|
2024
|
-
const init = {
|
|
2025
|
-
method,
|
|
2026
|
-
headers: this.buildHeaders(apiKey, opts.headers),
|
|
2027
|
-
...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
|
|
2028
|
-
...opts.signal ? { signal: opts.signal } : {}
|
|
2029
|
-
};
|
|
2030
|
-
logger.debug("MorphAPIClient", "request", { method, url });
|
|
2031
|
-
const response = await withTimeout(
|
|
2032
|
-
fetchWithRetry(url, init, this.retryConfig ?? {}),
|
|
2033
|
-
timeout,
|
|
2034
|
-
`Morph request to ${url} timed out after ${timeout}ms`
|
|
2035
|
-
);
|
|
2036
|
-
if (!response.ok) throw await toMorphError(response);
|
|
2037
|
-
if (opts.stream) return response;
|
|
2038
|
-
if (response.status === 204) return void 0;
|
|
2039
|
-
const text = await response.text();
|
|
2040
|
-
return text ? JSON.parse(text) : void 0;
|
|
2041
|
-
}
|
|
2042
|
-
get(path6, opts) {
|
|
2043
|
-
return this.request("GET", path6, opts);
|
|
2044
|
-
}
|
|
2045
|
-
post(path6, opts) {
|
|
2046
|
-
return this.request("POST", path6, opts);
|
|
2047
|
-
}
|
|
2048
|
-
delete(path6, opts) {
|
|
2049
|
-
return this.request("DELETE", path6, opts);
|
|
2050
|
-
}
|
|
2051
|
-
};
|
|
2052
|
-
|
|
2053
|
-
// core/resource.ts
|
|
2054
|
-
var APIResource = class {
|
|
2055
|
-
_client;
|
|
2056
|
-
constructor(client) {
|
|
2057
|
-
this._client = client;
|
|
2058
|
-
}
|
|
2059
|
-
};
|
|
2060
|
-
|
|
2061
|
-
// tools/compact/core.ts
|
|
2062
|
-
var DEFAULT_API_URL2 = "https://api.morphllm.com";
|
|
2063
|
-
var DEFAULT_TIMEOUT2 = 12e4;
|
|
2064
|
-
function resolveClient(clientOrConfig) {
|
|
2065
|
-
if (clientOrConfig instanceof MorphAPIClient) return clientOrConfig;
|
|
2066
|
-
return new MorphAPIClient({
|
|
2067
|
-
apiKey: clientOrConfig.morphApiKey,
|
|
2068
|
-
baseURL: clientOrConfig.morphApiUrl ?? DEFAULT_API_URL2,
|
|
2069
|
-
timeout: clientOrConfig.timeout ?? DEFAULT_TIMEOUT2,
|
|
2070
|
-
retryConfig: clientOrConfig.retryConfig,
|
|
2071
|
-
debug: clientOrConfig.debug
|
|
2072
|
-
});
|
|
2073
|
-
}
|
|
2074
|
-
var CompactClient = class extends APIResource {
|
|
2075
|
-
/** Resolved URL/timeout, exposed for backwards-compatible introspection. */
|
|
2076
|
-
config;
|
|
2077
|
-
constructor(clientOrConfig = {}) {
|
|
2078
|
-
super(resolveClient(clientOrConfig));
|
|
2079
|
-
const cfg = clientOrConfig instanceof MorphAPIClient ? {} : clientOrConfig;
|
|
2080
|
-
this.config = {
|
|
2081
|
-
morphApiUrl: this._client.baseURL,
|
|
2082
|
-
timeout: cfg.timeout ?? DEFAULT_TIMEOUT2,
|
|
2083
|
-
debug: cfg.debug ?? false
|
|
2084
|
-
};
|
|
2085
|
-
}
|
|
2086
|
-
/**
|
|
2087
|
-
* Compact messages or text via /v1/compact.
|
|
2088
|
-
* Returns per-message `compacted_line_ranges` showing which lines were removed.
|
|
2089
|
-
*
|
|
2090
|
-
* @example
|
|
2091
|
-
* ```typescript
|
|
2092
|
-
* const client = new CompactClient({ morphApiKey: 'sk-...' });
|
|
2093
|
-
* const result = await client.compact({
|
|
2094
|
-
* input: codeFile,
|
|
2095
|
-
* query: "authentication",
|
|
2096
|
-
* compressionRatio: 0.5,
|
|
2097
|
-
* });
|
|
2098
|
-
* console.log(result.output);
|
|
2099
|
-
* ```
|
|
2100
|
-
*/
|
|
2101
|
-
async compact(input) {
|
|
2102
|
-
const body = {
|
|
2103
|
-
compression_ratio: input.compressionRatio ?? 0.5,
|
|
2104
|
-
preserve_recent: input.preserveRecent ?? 2,
|
|
2105
|
-
model: input.model ?? "morph-compactor",
|
|
2106
|
-
include_line_ranges: input.includeLineRanges ?? true,
|
|
2107
|
-
include_markers: input.includeMarkers ?? true
|
|
2108
|
-
};
|
|
2109
|
-
if (input.query !== void 0) body.query = input.query;
|
|
2110
|
-
if (input.messages) body.messages = input.messages;
|
|
2111
|
-
else if (typeof input.input === "string") body.input = input.input;
|
|
2112
|
-
else if (Array.isArray(input.input)) body.messages = input.input;
|
|
2113
|
-
else throw new Error("Either 'input' or 'messages' must be provided");
|
|
2114
|
-
try {
|
|
2115
|
-
return await this._client.post("/v1/compact", { body, timeout: this.config.timeout });
|
|
2116
|
-
} catch (err) {
|
|
2117
|
-
if (err instanceof MorphError) {
|
|
2118
|
-
throw new Error(`Compact API error ${err.statusCode}: ${err.message}`);
|
|
2119
|
-
}
|
|
2120
|
-
throw err;
|
|
2121
|
-
}
|
|
2122
|
-
}
|
|
2123
|
-
};
|
|
2124
|
-
|
|
2125
|
-
// tools/compact/utils.ts
|
|
2126
|
-
async function compactFileContexts(files, query, apiKey, apiUrl, maxTokens = 1e4, maxConcurrency = 3) {
|
|
2127
|
-
const totalLength = files.reduce((sum, file) => sum + file.content.length, 0);
|
|
2128
|
-
const estimatedTokens = totalLength / 3;
|
|
2129
|
-
if (estimatedTokens <= maxTokens) {
|
|
2130
|
-
return files;
|
|
2131
|
-
}
|
|
2132
|
-
let compressionRatio = maxTokens / estimatedTokens;
|
|
2133
|
-
compressionRatio = Math.max(0.3, Math.min(0.99, compressionRatio));
|
|
2134
|
-
const client = new CompactClient({
|
|
2135
|
-
morphApiKey: apiKey,
|
|
2136
|
-
morphApiUrl: apiUrl
|
|
2137
|
-
});
|
|
2138
|
-
const results = [];
|
|
2139
|
-
const inProgress = /* @__PURE__ */ new Set();
|
|
2140
|
-
for (const file of files) {
|
|
2141
|
-
if (file.content.length < 500) {
|
|
2142
|
-
results.push({ path: file.path, content: file.content });
|
|
2143
|
-
continue;
|
|
2144
|
-
}
|
|
2145
|
-
const task = async () => {
|
|
2146
|
-
try {
|
|
2147
|
-
const result = await client.compact({
|
|
2148
|
-
input: file.content,
|
|
2149
|
-
query,
|
|
2150
|
-
compressionRatio,
|
|
2151
|
-
preserveRecent: 0
|
|
2152
|
-
});
|
|
2153
|
-
results.push({ path: file.path, content: result.output });
|
|
2154
|
-
} catch (error) {
|
|
2155
|
-
console.error(`[compactFileContexts] Failed to compact file ${file.path}:`, error);
|
|
2156
|
-
results.push({ path: file.path, content: file.content });
|
|
2157
|
-
}
|
|
2158
|
-
};
|
|
2159
|
-
const promise = task().finally(() => inProgress.delete(promise));
|
|
2160
|
-
inProgress.add(promise);
|
|
2161
|
-
if (inProgress.size >= maxConcurrency) {
|
|
2162
|
-
await Promise.race(inProgress);
|
|
2163
|
-
}
|
|
2164
|
-
}
|
|
2165
|
-
await Promise.all(inProgress);
|
|
2166
|
-
const orderMap = new Map(files.map((f, i) => [f.path, i]));
|
|
2167
|
-
return results.sort((a, b) => (orderMap.get(a.path) ?? 0) - (orderMap.get(b.path) ?? 0));
|
|
2168
|
-
}
|
|
2169
|
-
|
|
2170
|
-
// tools/warp_grep/client.ts
|
|
2171
|
-
var DEFAULT_CODE_SEARCH_URL = "https://api.morphllm.com";
|
|
2172
|
-
async function getLocalProvider(repoRoot, excludes, allowNames) {
|
|
2173
|
-
const { LocalRipgrepProvider: LocalRipgrepProvider2 } = await Promise.resolve().then(() => (init_local(), local_exports));
|
|
2174
|
-
const opts = allowNames?.length ? { allowNames } : void 0;
|
|
2175
|
-
return new LocalRipgrepProvider2(repoRoot, excludes, opts);
|
|
2176
|
-
}
|
|
2177
|
-
var WarpGrepClient = class extends APIResource {
|
|
2178
|
-
config;
|
|
2179
|
-
constructor(clientOrConfig = {}) {
|
|
2180
|
-
const isClient = clientOrConfig instanceof MorphAPIClient;
|
|
2181
|
-
super(
|
|
2182
|
-
isClient ? clientOrConfig : new MorphAPIClient({
|
|
2183
|
-
apiKey: clientOrConfig.morphApiKey,
|
|
2184
|
-
baseURL: clientOrConfig.morphApiUrl,
|
|
2185
|
-
timeout: clientOrConfig.timeout,
|
|
2186
|
-
retryConfig: clientOrConfig.retryConfig,
|
|
2187
|
-
debug: clientOrConfig.debug
|
|
2188
|
-
})
|
|
2189
|
-
);
|
|
2190
|
-
const cfg = isClient ? {} : clientOrConfig;
|
|
2191
|
-
this.config = {
|
|
2192
|
-
...cfg,
|
|
2193
|
-
morphApiKey: this._client.resolveApiKey(),
|
|
2194
|
-
morphApiUrl: this._client.baseURL,
|
|
2195
|
-
timeout: this._client.timeout,
|
|
2196
|
-
retryConfig: this._client.retryConfig,
|
|
2197
|
-
debug: this._client.debug
|
|
2198
|
-
};
|
|
2199
|
-
}
|
|
2200
|
-
execute(input) {
|
|
2201
|
-
const toolConfig = {
|
|
2202
|
-
repoRoot: input.repoRoot,
|
|
2203
|
-
remoteCommands: input.remoteCommands,
|
|
2204
|
-
provider: input.provider,
|
|
2205
|
-
excludes: input.excludes,
|
|
2206
|
-
includes: input.includes,
|
|
2207
|
-
debug: input.debug ?? this.config.debug,
|
|
2208
|
-
morphApiKey: this.config.morphApiKey,
|
|
2209
|
-
morphApiUrl: this.config.morphApiUrl,
|
|
2210
|
-
retryConfig: this.config.retryConfig,
|
|
2211
|
-
timeout: this.config.timeout,
|
|
2212
|
-
search_type: input.search_type
|
|
2213
|
-
};
|
|
2214
|
-
if (input.streamSteps) {
|
|
2215
|
-
return executeToolCallStreaming({ search_term: input.searchTerm }, toolConfig);
|
|
2216
|
-
}
|
|
2217
|
-
return executeToolCall({ search_term: input.searchTerm }, toolConfig);
|
|
2218
|
-
}
|
|
2219
|
-
searchGitHub(input) {
|
|
2220
|
-
if (input.streamSteps) {
|
|
2221
|
-
return this._searchGitHubStreaming(input);
|
|
2222
|
-
}
|
|
2223
|
-
return this._searchGitHubAsync(input);
|
|
2224
|
-
}
|
|
2225
|
-
/**
|
|
2226
|
-
* Read a single file from a public GitHub repository
|
|
2227
|
-
*
|
|
2228
|
-
* @example
|
|
2229
|
-
* ```typescript
|
|
2230
|
-
* const result = await client.readGitHubFile({
|
|
2231
|
-
* github: 'vercel/next.js',
|
|
2232
|
-
* path: 'src/server/app-render/index.tsx',
|
|
2233
|
-
* startLine: 1,
|
|
2234
|
-
* endLine: 50,
|
|
2235
|
-
* });
|
|
2236
|
-
* if (result.success) console.log(result.content);
|
|
2237
|
-
* ```
|
|
2238
|
-
*/
|
|
2239
|
-
async readGitHubFile(input) {
|
|
2240
|
-
return executeGitHubReadFile(input, { timeout: this.config.timeout });
|
|
2241
|
-
}
|
|
2242
|
-
async _resolveGitHubRepo(input) {
|
|
2243
|
-
const { owner, repo } = parseGitHubUrl(input.github);
|
|
2244
|
-
const baseUrl = this.config.codeSearchUrl || DEFAULT_CODE_SEARCH_URL;
|
|
2245
|
-
logger.debug("WarpGrep", "github_resolve", { owner_repo: `${owner}/${repo}`, branch: input.branch });
|
|
2246
|
-
const resolveStart = Date.now();
|
|
2247
|
-
const importRes = await fetch(`${baseUrl}/api/code-search/get-or-create?url=${encodeURIComponent(`${owner}/${repo}`)}`, {
|
|
2248
|
-
headers: this.config.morphApiKey ? { Authorization: `Bearer ${this.config.morphApiKey}` } : void 0
|
|
2249
|
-
});
|
|
2250
|
-
if (!importRes.ok) {
|
|
2251
|
-
const text = await importRes.text().catch(() => importRes.statusText);
|
|
2252
|
-
logger.error("WarpGrep", "github_resolve_failed", { owner_repo: `${owner}/${repo}`, status: importRes.status, error: text });
|
|
2253
|
-
throw new Error(`Failed to import repo ${owner}/${repo}: ${text}`);
|
|
2254
|
-
}
|
|
2255
|
-
const { repoId, defaultBranch } = await importRes.json();
|
|
2256
|
-
logger.debug("WarpGrep", "github_repo_fetched", { repo_id: repoId, default_branch: defaultBranch, latency_ms: Date.now() - resolveStart });
|
|
2257
|
-
return {
|
|
2258
|
-
repo,
|
|
2259
|
-
remoteCommands: createCodeStorageHttpCommands({
|
|
2260
|
-
baseUrl,
|
|
2261
|
-
repoId,
|
|
2262
|
-
branch: input.branch || defaultBranch,
|
|
2263
|
-
apiKey: this.config.morphApiKey
|
|
2264
|
-
})
|
|
2265
|
-
};
|
|
2266
|
-
}
|
|
2267
|
-
async _searchGitHubAsync(input) {
|
|
2268
|
-
try {
|
|
2269
|
-
const { remoteCommands } = await this._resolveGitHubRepo(input);
|
|
2270
|
-
return this.execute({
|
|
2271
|
-
searchTerm: input.searchTerm,
|
|
2272
|
-
repoRoot: ".",
|
|
2273
|
-
remoteCommands
|
|
2274
|
-
});
|
|
2275
|
-
} catch (error) {
|
|
2276
|
-
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
2277
|
-
}
|
|
2278
|
-
}
|
|
2279
|
-
async *_searchGitHubStreaming(input) {
|
|
2280
|
-
let remoteCommands;
|
|
2281
|
-
try {
|
|
2282
|
-
({ remoteCommands } = await this._resolveGitHubRepo(input));
|
|
2283
|
-
} catch (error) {
|
|
2284
|
-
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
2285
|
-
}
|
|
2286
|
-
const generator = this.execute({
|
|
2287
|
-
searchTerm: input.searchTerm,
|
|
2288
|
-
repoRoot: ".",
|
|
2289
|
-
remoteCommands,
|
|
2290
|
-
streamSteps: true
|
|
2291
|
-
});
|
|
2292
|
-
let result;
|
|
2293
|
-
for (; ; ) {
|
|
2294
|
-
const { value, done } = await generator.next();
|
|
2295
|
-
if (done) {
|
|
2296
|
-
result = value;
|
|
2297
|
-
break;
|
|
2298
|
-
}
|
|
2299
|
-
yield value;
|
|
2300
|
-
}
|
|
2301
|
-
return result;
|
|
2302
|
-
}
|
|
2303
|
-
};
|
|
2304
|
-
async function executeToolCall(input, config) {
|
|
2305
|
-
const parsed = typeof input === "string" ? JSON.parse(input) : input;
|
|
2306
|
-
const allowNames = config.search_type === "node_modules" ? ["node_modules"] : void 0;
|
|
2307
|
-
const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);
|
|
2308
|
-
const result = await runWarpGrep({
|
|
2309
|
-
searchTerm: parsed.search_term,
|
|
2310
|
-
repoRoot: config.repoRoot,
|
|
2311
|
-
provider,
|
|
2312
|
-
excludes: config.excludes,
|
|
2313
|
-
includes: config.includes,
|
|
2314
|
-
debug: config.debug ?? false,
|
|
2315
|
-
morphApiKey: config.morphApiKey,
|
|
2316
|
-
morphApiUrl: config.morphApiUrl,
|
|
2317
|
-
retryConfig: config.retryConfig,
|
|
2318
|
-
timeout: config.timeout,
|
|
2319
|
-
search_type: config.search_type
|
|
2320
|
-
});
|
|
2321
|
-
return processAgentResult(result, parsed.search_term, config.morphApiKey, config.morphApiUrl);
|
|
2322
|
-
}
|
|
2323
|
-
async function processAgentResult(result, searchTerm, apiKey, apiUrl) {
|
|
2324
|
-
const finish = result.finish;
|
|
2325
|
-
if (result.terminationReason !== "completed" || !finish?.metadata) {
|
|
2326
|
-
const errorDetails = result.errors?.map((e) => e.message).join("; ") || "unknown reason";
|
|
2327
|
-
console.error(`[warp_grep] processAgentResult failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);
|
|
2328
|
-
return { success: false, error: `Search did not complete: ${errorDetails}` };
|
|
2329
|
-
}
|
|
2330
|
-
const contexts = (finish.resolved ?? []).map((r) => ({
|
|
2331
|
-
file: r.path,
|
|
2332
|
-
content: r.content,
|
|
2333
|
-
lines: r.ranges
|
|
2334
|
-
}));
|
|
2335
|
-
try {
|
|
2336
|
-
const compactable = contexts.map((c) => ({ path: c.file, content: c.content }));
|
|
2337
|
-
const compacted = await compactFileContexts(compactable, searchTerm, apiKey, apiUrl);
|
|
2338
|
-
for (let i = 0; i < contexts.length; i++) {
|
|
2339
|
-
contexts[i].content = compacted[i].content;
|
|
2340
|
-
}
|
|
2341
|
-
} catch (error) {
|
|
2342
|
-
console.error(`[warp_grep] Failed to compact result contexts:`, error);
|
|
2343
|
-
}
|
|
2344
|
-
return { success: true, contexts, summary: finish.payload };
|
|
2345
|
-
}
|
|
2346
|
-
async function* executeToolCallStreaming(input, config) {
|
|
2347
|
-
const parsed = typeof input === "string" ? JSON.parse(input) : input;
|
|
2348
|
-
const allowNames = config.search_type === "node_modules" ? ["node_modules"] : void 0;
|
|
2349
|
-
const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes, allowNames);
|
|
2350
|
-
const generator = runWarpGrepStreaming({
|
|
2351
|
-
searchTerm: parsed.search_term,
|
|
2352
|
-
repoRoot: config.repoRoot,
|
|
2353
|
-
provider,
|
|
2354
|
-
excludes: config.excludes,
|
|
2355
|
-
includes: config.includes,
|
|
2356
|
-
debug: config.debug ?? false,
|
|
2357
|
-
morphApiKey: config.morphApiKey,
|
|
2358
|
-
morphApiUrl: config.morphApiUrl,
|
|
2359
|
-
retryConfig: config.retryConfig,
|
|
2360
|
-
timeout: config.timeout,
|
|
2361
|
-
search_type: config.search_type
|
|
2362
|
-
});
|
|
2363
|
-
let agentResult;
|
|
2364
|
-
for (; ; ) {
|
|
2365
|
-
const { value, done } = await generator.next();
|
|
2366
|
-
if (done) {
|
|
2367
|
-
agentResult = value;
|
|
2368
|
-
break;
|
|
2369
|
-
}
|
|
2370
|
-
yield value;
|
|
2371
|
-
}
|
|
2372
|
-
return await processAgentResult(agentResult, parsed.search_term, config.morphApiKey, config.morphApiUrl);
|
|
2373
|
-
}
|
|
2374
|
-
async function fetchRawGitHubFile(owner, repo, filePath, branch, timeout) {
|
|
2375
|
-
const branches = branch ? [branch] : ["HEAD"];
|
|
2376
|
-
const fallbacks = ["main", "master", "develop"];
|
|
2377
|
-
const fetchWithTimeout = (url) => timeout ? fetch(url, { signal: AbortSignal.timeout(timeout) }) : fetch(url);
|
|
2378
|
-
for (const b of branches) {
|
|
2379
|
-
const url = `https://raw.githubusercontent.com/${owner}/${repo}/${b}/${filePath}`;
|
|
2380
|
-
const res = await fetchWithTimeout(url);
|
|
2381
|
-
if (res.ok) return { content: await res.text(), branch: b };
|
|
2382
|
-
}
|
|
2383
|
-
for (const fb of fallbacks) {
|
|
2384
|
-
if (branch && fb === branch) continue;
|
|
2385
|
-
const url = `https://raw.githubusercontent.com/${owner}/${repo}/${fb}/${filePath}`;
|
|
2386
|
-
const res = await fetchWithTimeout(url);
|
|
2387
|
-
if (res.ok) return { content: await res.text(), branch: fb };
|
|
2388
|
-
}
|
|
2389
|
-
throw new Error(`File not found: ${owner}/${repo}/${filePath}`);
|
|
2390
|
-
}
|
|
2391
|
-
async function executeGitHubReadFile(input, config) {
|
|
2392
|
-
try {
|
|
2393
|
-
const { owner, repo } = parseGitHubUrl(input.github);
|
|
2394
|
-
const { content: raw, branch } = await fetchRawGitHubFile(
|
|
2395
|
-
owner,
|
|
2396
|
-
repo,
|
|
2397
|
-
input.path,
|
|
2398
|
-
input.branch,
|
|
2399
|
-
config?.timeout
|
|
2400
|
-
);
|
|
2401
|
-
const allLines = raw.split("\n");
|
|
2402
|
-
const totalLines = allLines.length;
|
|
2403
|
-
const start = Math.max(1, input.startLine ?? 1);
|
|
2404
|
-
const end = Math.min(totalLines, input.endLine ?? totalLines);
|
|
2405
|
-
const selected = allLines.slice(start - 1, end);
|
|
2406
|
-
const padWidth = String(end).length;
|
|
2407
|
-
const numbered = selected.map((line, i) => `${String(start + i).padStart(padWidth)}|${line}`).join("\n");
|
|
2408
|
-
return {
|
|
2409
|
-
success: true,
|
|
2410
|
-
content: numbered,
|
|
2411
|
-
path: input.path,
|
|
2412
|
-
github: `${owner}/${repo}`,
|
|
2413
|
-
branch,
|
|
2414
|
-
lineRange: [start, end],
|
|
2415
|
-
totalLines
|
|
2416
|
-
};
|
|
2417
|
-
} catch (error) {
|
|
2418
|
-
return {
|
|
2419
|
-
success: false,
|
|
2420
|
-
error: error instanceof Error ? error.message : String(error)
|
|
2421
|
-
};
|
|
2422
|
-
}
|
|
2423
|
-
}
|
|
2424
|
-
function formatGitHubReadFileResult(result) {
|
|
2425
|
-
if (!result.success) {
|
|
2426
|
-
return `Failed to read file: ${result.error}`;
|
|
2427
|
-
}
|
|
2428
|
-
const rangeStr = result.lineRange ? ` (lines ${result.lineRange[0]}-${result.lineRange[1]} of ${result.totalLines})` : "";
|
|
2429
|
-
return `File: ${result.github}/${result.path}${rangeStr}
|
|
2430
|
-
|
|
2431
|
-
${result.content}`;
|
|
2432
|
-
}
|
|
2433
|
-
function formatResult(result) {
|
|
2434
|
-
if (!result.success) {
|
|
2435
|
-
return `Search failed: ${result.error}`;
|
|
2436
|
-
}
|
|
2437
|
-
if (!result.contexts || result.contexts.length === 0) {
|
|
2438
|
-
return "No relevant code found. Try rephrasing your search term.";
|
|
2439
|
-
}
|
|
2440
|
-
const parts = [];
|
|
2441
|
-
parts.push(`Morph Fast Context subagent performed search on repository:
|
|
2442
|
-
`);
|
|
2443
|
-
parts.push("Relevant context found:");
|
|
2444
|
-
for (const ctx of result.contexts) {
|
|
2445
|
-
const rangeStr = !ctx.lines || ctx.lines === "*" ? "*" : ctx.lines.map(([s, e]) => `${s}-${e}`).join(",");
|
|
2446
|
-
parts.push(`- ${ctx.file}:${rangeStr}`);
|
|
2447
|
-
}
|
|
2448
|
-
parts.push("\nHere is the content of files:\n");
|
|
2449
|
-
for (const ctx of result.contexts) {
|
|
2450
|
-
const rangeStr = !ctx.lines || ctx.lines === "*" ? "" : ` lines="${ctx.lines.map(([s, e]) => `${s}-${e}`).join(",")}"`;
|
|
2451
|
-
parts.push(`<file path="${ctx.file}"${rangeStr}>`);
|
|
2452
|
-
parts.push(ctx.content);
|
|
2453
|
-
parts.push("</file>\n");
|
|
2454
|
-
}
|
|
2455
|
-
return parts.join("\n");
|
|
2456
|
-
}
|
|
2457
|
-
|
|
2458
|
-
// tools/warp_grep/prompts.ts
|
|
2459
|
-
var WARP_GREP_TOOL_NAME = "codebase_search";
|
|
2460
|
-
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.';
|
|
2461
|
-
var GITHUB_WARP_GREP_SEARCH_TOOL_NAME = "github_codebase_search";
|
|
2462
|
-
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). ";
|
|
2463
|
-
var GITHUB_SEARCH_TOOL_NAME = GITHUB_WARP_GREP_SEARCH_TOOL_NAME;
|
|
2464
|
-
var GITHUB_SEARCH_DESCRIPTION = GITHUB_WARP_GREP_SEARCH_DESCRIPTION;
|
|
2465
|
-
var GITHUB_READ_FILE_TOOL_NAME = "readfile_github_search";
|
|
2466
|
-
var GITHUB_READ_FILE_DESCRIPTION = "Read a single file (or a line range) from a public GitHub repository. ONLY USE THIS WHEN YOU ALREADY KNOW THE EXACT FILE PATH YOU WANT TO READ, for example after finding it via github_codebase_search results. Takes owner/repo shorthand and the file path within the repo. Optionally specify startLine and endLine (1-based) to read a specific range. Returns the file content with line numbers.";
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var chunkEJTL2BOZ_cjs = require('../../chunk-EJTL2BOZ.cjs');
|
|
6
|
+
var chunkJHC2R3HU_cjs = require('../../chunk-JHC2R3HU.cjs');
|
|
7
|
+
require('../../chunk-WR7LSUIR.cjs');
|
|
8
|
+
require('../../chunk-MWXJ6DZ2.cjs');
|
|
9
|
+
require('../../chunk-OCKEEEYE.cjs');
|
|
10
|
+
require('../../chunk-VHD7CW5O.cjs');
|
|
11
|
+
require('../../chunk-KVGZ2TSG.cjs');
|
|
12
|
+
require('../../chunk-UNX7V6P6.cjs');
|
|
13
|
+
require('../../chunk-4EQQGUZ7.cjs');
|
|
14
|
+
require('../../chunk-VYE7O4FM.cjs');
|
|
15
|
+
require('../../chunk-F633IVQA.cjs');
|
|
16
|
+
require('../../chunk-5TTZQF4X.cjs');
|
|
17
|
+
require('../../chunk-VL4QNALG.cjs');
|
|
18
|
+
require('../../chunk-KF6S3EPJ.cjs');
|
|
19
|
+
require('../../chunk-6HAYJA6M.cjs');
|
|
20
|
+
require('../../chunk-R3TUE7O2.cjs');
|
|
21
|
+
require('../../chunk-DLYDIYDK.cjs');
|
|
22
|
+
require('../../chunk-YAUXTFIN.cjs');
|
|
23
|
+
require('../../chunk-WJHHO24M.cjs');
|
|
24
|
+
require('../../chunk-QT5LGZG3.cjs');
|
|
25
|
+
require('../../chunk-AWFZKS27.cjs');
|
|
26
|
+
require('../../chunk-75ZPJI57.cjs');
|
|
2467
27
|
|
|
2468
28
|
// tools/warp_grep/gemini.ts
|
|
2469
29
|
var TOOL_PARAMETERS = {
|
|
@@ -2477,25 +37,25 @@ var TOOL_PARAMETERS = {
|
|
|
2477
37
|
required: ["search_term"]
|
|
2478
38
|
};
|
|
2479
39
|
var warpGrepFunctionDeclaration = {
|
|
2480
|
-
name: WARP_GREP_TOOL_NAME,
|
|
2481
|
-
description: WARP_GREP_DESCRIPTION,
|
|
40
|
+
name: chunkEJTL2BOZ_cjs.WARP_GREP_TOOL_NAME,
|
|
41
|
+
description: chunkEJTL2BOZ_cjs.WARP_GREP_DESCRIPTION,
|
|
2482
42
|
parameters: TOOL_PARAMETERS
|
|
2483
43
|
};
|
|
2484
44
|
async function execute(input, config) {
|
|
2485
|
-
return executeToolCall(input, config);
|
|
45
|
+
return chunkJHC2R3HU_cjs.executeToolCall(input, config);
|
|
2486
46
|
}
|
|
2487
47
|
function createWarpGrepTool(config) {
|
|
2488
48
|
const declaration = {
|
|
2489
|
-
name: config.name ?? WARP_GREP_TOOL_NAME,
|
|
2490
|
-
description: config.description ?? WARP_GREP_DESCRIPTION,
|
|
49
|
+
name: config.name ?? chunkEJTL2BOZ_cjs.WARP_GREP_TOOL_NAME,
|
|
50
|
+
description: config.description ?? chunkEJTL2BOZ_cjs.WARP_GREP_DESCRIPTION,
|
|
2491
51
|
parameters: TOOL_PARAMETERS
|
|
2492
52
|
};
|
|
2493
53
|
return Object.assign(declaration, {
|
|
2494
54
|
execute: async (input) => {
|
|
2495
|
-
return executeToolCall(input, config);
|
|
55
|
+
return chunkJHC2R3HU_cjs.executeToolCall(input, config);
|
|
2496
56
|
},
|
|
2497
57
|
formatResult: (result) => {
|
|
2498
|
-
return formatResult(result);
|
|
58
|
+
return chunkJHC2R3HU_cjs.formatResult(result);
|
|
2499
59
|
}
|
|
2500
60
|
});
|
|
2501
61
|
}
|
|
@@ -2511,10 +71,10 @@ var GITHUB_SEARCH_PARAMETERS = {
|
|
|
2511
71
|
required: ["search_term"]
|
|
2512
72
|
};
|
|
2513
73
|
function createGitHubSearchTool(config) {
|
|
2514
|
-
const client = new WarpGrepClient(config);
|
|
74
|
+
const client = new chunkJHC2R3HU_cjs.WarpGrepClient(config);
|
|
2515
75
|
const declaration = {
|
|
2516
|
-
name: GITHUB_SEARCH_TOOL_NAME,
|
|
2517
|
-
description: GITHUB_SEARCH_DESCRIPTION,
|
|
76
|
+
name: chunkEJTL2BOZ_cjs.GITHUB_SEARCH_TOOL_NAME,
|
|
77
|
+
description: chunkEJTL2BOZ_cjs.GITHUB_SEARCH_DESCRIPTION,
|
|
2518
78
|
parameters: GITHUB_SEARCH_PARAMETERS
|
|
2519
79
|
};
|
|
2520
80
|
return Object.assign(declaration, {
|
|
@@ -2526,7 +86,7 @@ function createGitHubSearchTool(config) {
|
|
|
2526
86
|
return client.searchGitHub({ searchTerm: input.search_term, github, branch: input.branch });
|
|
2527
87
|
},
|
|
2528
88
|
formatResult: (result) => {
|
|
2529
|
-
return formatResult(result);
|
|
89
|
+
return chunkJHC2R3HU_cjs.formatResult(result);
|
|
2530
90
|
}
|
|
2531
91
|
});
|
|
2532
92
|
}
|
|
@@ -2543,27 +103,29 @@ var GITHUB_READ_FILE_PARAMETERS = {
|
|
|
2543
103
|
};
|
|
2544
104
|
function createGitHubReadFileTool(config) {
|
|
2545
105
|
const declaration = {
|
|
2546
|
-
name: GITHUB_READ_FILE_TOOL_NAME,
|
|
2547
|
-
description: GITHUB_READ_FILE_DESCRIPTION,
|
|
106
|
+
name: chunkEJTL2BOZ_cjs.GITHUB_READ_FILE_TOOL_NAME,
|
|
107
|
+
description: chunkEJTL2BOZ_cjs.GITHUB_READ_FILE_DESCRIPTION,
|
|
2548
108
|
parameters: GITHUB_READ_FILE_PARAMETERS
|
|
2549
109
|
};
|
|
2550
110
|
return Object.assign(declaration, {
|
|
2551
111
|
execute: async (input) => {
|
|
2552
|
-
return executeGitHubReadFile(input, config);
|
|
112
|
+
return chunkJHC2R3HU_cjs.executeGitHubReadFile(input, config);
|
|
2553
113
|
},
|
|
2554
114
|
formatResult: (result) => {
|
|
2555
|
-
return formatGitHubReadFileResult(result);
|
|
115
|
+
return chunkJHC2R3HU_cjs.formatGitHubReadFileResult(result);
|
|
2556
116
|
}
|
|
2557
117
|
});
|
|
2558
118
|
}
|
|
2559
119
|
var gemini_default = warpGrepFunctionDeclaration;
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
createMorphWarpGrepTool,
|
|
2565
|
-
createWarpGrepTool,
|
|
2566
|
-
execute,
|
|
2567
|
-
formatResult,
|
|
2568
|
-
warpGrepFunctionDeclaration
|
|
120
|
+
|
|
121
|
+
Object.defineProperty(exports, "formatResult", {
|
|
122
|
+
enumerable: true,
|
|
123
|
+
get: function () { return chunkJHC2R3HU_cjs.formatResult; }
|
|
2569
124
|
});
|
|
125
|
+
exports.createGitHubReadFileTool = createGitHubReadFileTool;
|
|
126
|
+
exports.createGitHubSearchTool = createGitHubSearchTool;
|
|
127
|
+
exports.createMorphWarpGrepTool = createMorphWarpGrepTool;
|
|
128
|
+
exports.createWarpGrepTool = createWarpGrepTool;
|
|
129
|
+
exports.default = gemini_default;
|
|
130
|
+
exports.execute = execute;
|
|
131
|
+
exports.warpGrepFunctionDeclaration = warpGrepFunctionDeclaration;
|