@mergelight/cli 0.1.20 → 0.1.24
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 +2 -2
- package/dist/cli.js +23 -13
- package/dist/cloud.js +2 -2
- package/dist/connect.js +1 -1
- package/dist/init.js +42 -14
- package/dist/mcp/code-server.js +414 -0
- package/dist/mcp/server.js +13 -11
- package/dist/prompt.js +5 -3
- package/dist/providers/agy-login.js +60 -0
- package/dist/providers/antigravity.js +385 -0
- package/dist/providers/codex.js +38 -6
- package/dist/providers/index.js +23 -2
- package/dist/publish/markdown.js +11 -5
- package/dist/publish/publish.js +19 -8
- package/dist/review.js +18 -13
- package/dist/setup.js +8 -2
- package/dist/update.js +16 -1
- package/package.json +1 -1
- package/scripts/refresh-login.mjs +21 -2
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ AI code review that runs on the ChatGPT or Claude plan you already pay for. Merg
|
|
|
6
6
|
|
|
7
7
|
**Reviews on every pull request.** Set it up at [mergelight.dev/setup](https://mergelight.dev/setup). It runs in your own GitHub Actions, on your own plan. See the [GitHub Action guide](https://github.com/mergelightai/mergelight/blob/main/docs/github-action.md).
|
|
8
8
|
|
|
9
|
-
**Findings in your coding agent.** One command adds the MCP server and the skill to Claude Code, Codex and
|
|
9
|
+
**Findings in your coding agent.** One command adds the MCP server and the skill to Claude Code, Codex, Cursor and Antigravity:
|
|
10
10
|
|
|
11
11
|
```bash
|
|
12
12
|
npx @mergelight/cli init
|
|
@@ -70,7 +70,7 @@ Two more commands, used by the GitHub Action:
|
|
|
70
70
|
- `mergelight post review.json` posts a review saved with `--out`.
|
|
71
71
|
- `mergelight approve owner/repo#123 --by login` turns a 🟡 "needs a human" check green after someone approves the PR. A 🔴 "blocked" check stays blocked until a fix.
|
|
72
72
|
|
|
73
|
-
`mergelight init` adds Mergelight to your coding agents, and `mergelight mcp` is the MCP server they start, so Claude Code, Codex or
|
|
73
|
+
`mergelight init` adds Mergelight to your coding agents, and `mergelight mcp` is the MCP server they start, so Claude Code, Codex, Cursor or Antigravity can read a PR's findings and mark them handled. `mergelight setup owner/repo` sets up the GitHub Action from a terminal.
|
|
74
74
|
|
|
75
75
|
The exit code is `2` when the review finds a bug that blocks the merge, `1` on errors and `0` otherwise. With `--post` it is `0` unless the review fails, since the check carries the verdict. On a personal `gh` login, where GitHub doesn't allow checks, the summary comment carries it instead.
|
|
76
76
|
|
package/dist/cli.js
CHANGED
|
@@ -10,6 +10,7 @@ import { answerReplyBody, decisionsFromAnswer, teamAnswerFromEnv, withDecisions
|
|
|
10
10
|
import { publishTeamChecks } from "./publish/team-checks.js";
|
|
11
11
|
import { answerRemembered, confirmReasons, approveCheck, checkHeldTitle, checkLimitTitle, checkLoginTitle, failCheck, failSummary, previousReview, publishReview, startCheck, startSummary, syncApproval, UNREVIEWED, APPROVALS_OFF, updatePendingSummary } from "./publish/publish.js";
|
|
12
12
|
import { configuredModel, HeldLoginError, LimitError, LoginError, loginFailureMessage } from "./providers/codex.js";
|
|
13
|
+
import { isProvider } from "./providers/index.js";
|
|
13
14
|
import { heldLoginNotice, limitNotice, loginNotice } from "./publish/markdown.js";
|
|
14
15
|
import { renderRejected, renderTerminal } from "./render.js";
|
|
15
16
|
import { reviewPullRequest } from "./review.js";
|
|
@@ -26,7 +27,7 @@ Usage
|
|
|
26
27
|
mergelight review <pr> [options] Review a pull request
|
|
27
28
|
mergelight post <review.json> Post a saved review to its pull request
|
|
28
29
|
mergelight approve <pr> --by <login> Turn a "needs a human" check green after approval
|
|
29
|
-
mergelight init Add Mergelight to your coding agents: Claude Code, Codex and
|
|
30
|
+
mergelight init Add Mergelight to your coding agents: Claude Code, Codex, Cursor and Antigravity
|
|
30
31
|
mergelight mcp Run the MCP server, so your coding agent can read findings
|
|
31
32
|
mergelight setup <owner/repo> Set up the GitHub Action on a repository
|
|
32
33
|
mergelight connect <pr> In the Action: connect ChatGPT from the pull request
|
|
@@ -48,11 +49,12 @@ Options
|
|
|
48
49
|
--no-approve With --post or post: never approve the pull request, and take back an approval Mergelight gave
|
|
49
50
|
--json Print the review as JSON
|
|
50
51
|
--out <file> Also write the JSON review to a file
|
|
51
|
-
--provider <name> Who hunts for problems: codex or
|
|
52
|
+
--provider <name> Who hunts for problems: codex, claude or antigravity (default: codex)
|
|
52
53
|
--model <name> Model for the hunters (default: your Codex config, or opus on Claude)
|
|
53
54
|
--effort <level> Reasoning effort: low, medium, high (default: high)
|
|
54
|
-
--verify-with <name> Who checks the findings: claude or
|
|
55
|
-
(default: claude when Claude Code is installed
|
|
55
|
+
--verify-with <name> Who checks the findings: claude, codex or antigravity
|
|
56
|
+
(default: claude when Claude Code is installed; with
|
|
57
|
+
--provider antigravity, Antigravity checks its own)
|
|
56
58
|
--verify-missed <name>
|
|
57
59
|
The AI that was meant to check but had no login: the summary says so
|
|
58
60
|
--verify-model <name> Model for the checker (default for claude: opus)
|
|
@@ -76,6 +78,7 @@ Options
|
|
|
76
78
|
-v, --version Show the version
|
|
77
79
|
|
|
78
80
|
Reviews run on your own logged-in Codex CLI, and Claude Code if you check with it.
|
|
81
|
+
Antigravity logs in with ANTIGRAVITY_AUTH_JSON (a Google AI plan's login) or GEMINI_API_KEY.
|
|
79
82
|
Your code and your AI login are never sent to Mergelight.
|
|
80
83
|
`;
|
|
81
84
|
function progressPrinter() {
|
|
@@ -213,19 +216,19 @@ async function main() {
|
|
|
213
216
|
}
|
|
214
217
|
const dryRun = Boolean(values["dry-run"]);
|
|
215
218
|
const provider = values.provider;
|
|
216
|
-
if (provider !== undefined && provider
|
|
217
|
-
log(`mergelight: --provider must be codex or
|
|
219
|
+
if (provider !== undefined && !isProvider(provider)) {
|
|
220
|
+
log(`mergelight: --provider must be codex, claude or antigravity, not "${provider}"`);
|
|
218
221
|
return 1;
|
|
219
222
|
}
|
|
220
223
|
const verifyWith = values["verify-with"];
|
|
221
|
-
if (verifyWith !== undefined && verifyWith
|
|
222
|
-
log(`mergelight: --verify-with must be codex or
|
|
224
|
+
if (verifyWith !== undefined && !isProvider(verifyWith)) {
|
|
225
|
+
log(`mergelight: --verify-with must be codex, claude or antigravity, not "${verifyWith}"`);
|
|
223
226
|
return 1;
|
|
224
227
|
}
|
|
225
228
|
// The AI the team asked to check, which had no login, so the reviewer's own AI checked instead.
|
|
226
229
|
const verifyMissed = values["verify-missed"];
|
|
227
|
-
if (verifyMissed !== undefined && verifyMissed
|
|
228
|
-
log(`mergelight: --verify-missed must be codex or
|
|
230
|
+
if (verifyMissed !== undefined && !isProvider(verifyMissed)) {
|
|
231
|
+
log(`mergelight: --verify-missed must be codex, claude or antigravity, not "${verifyMissed}"`);
|
|
229
232
|
return 1;
|
|
230
233
|
}
|
|
231
234
|
if (command === "post") {
|
|
@@ -236,6 +239,11 @@ async function main() {
|
|
|
236
239
|
}
|
|
237
240
|
const ref = parsePrRef(target, values.repo ?? (await currentRepo()));
|
|
238
241
|
if (command === "jobs") {
|
|
242
|
+
// A job changes files, and agy has no way to keep its hands inside one folder: jobs stay on Codex and Claude.
|
|
243
|
+
if (provider === "antigravity") {
|
|
244
|
+
log("mergelight: jobs run on Codex or Claude. Antigravity can review and check, but not run jobs.");
|
|
245
|
+
return 1;
|
|
246
|
+
}
|
|
239
247
|
const progress = progressPrinter();
|
|
240
248
|
try {
|
|
241
249
|
// A log line clears the progress line first, so the two never run together in a terminal.
|
|
@@ -274,8 +282,9 @@ async function main() {
|
|
|
274
282
|
log(`mergelight: --for must be review or check, not "${values.for}"`);
|
|
275
283
|
return 1;
|
|
276
284
|
}
|
|
277
|
-
|
|
278
|
-
|
|
285
|
+
// The checker to connect is Codex or Claude; the reviewer can be any AI, Antigravity too.
|
|
286
|
+
if (check && ((ai !== "codex" && ai !== "claude") || !isProvider(reviewer) || ai === reviewer)) {
|
|
287
|
+
log("mergelight: connect --for check needs --ai, codex or claude, and --reviewer, codex, claude or antigravity, and not the same.");
|
|
279
288
|
return 1;
|
|
280
289
|
}
|
|
281
290
|
// For a review, --ai claude offers only Claude's link: the workflow says Claude reviews, and it has no login yet.
|
|
@@ -385,7 +394,7 @@ async function main() {
|
|
|
385
394
|
checkRunId = await startCheck(api, headSha, provider ?? "codex", handedOver, record);
|
|
386
395
|
// Says which AI reviews from the start. The models' exact names follow once the first reviewer answers.
|
|
387
396
|
// Without --provider the review runs on Codex, as reviewPullRequest decides.
|
|
388
|
-
const firstGuess = values.model ?? (provider === "claude" ? "opus" : configuredModel());
|
|
397
|
+
const firstGuess = values.model ?? (provider === "claude" ? "opus" : provider === "antigravity" ? null : configuredModel());
|
|
389
398
|
summaryComment = await startSummary(api, ref.number, { reviewer: { name: provider ?? "codex", model: firstGuess ?? null } }, process.env.MERGELIGHT_PROMPT || undefined).catch((e) => {
|
|
390
399
|
log(`Couldn't post the summary yet: ${e.message}`);
|
|
391
400
|
return null;
|
|
@@ -419,6 +428,7 @@ async function main() {
|
|
|
419
428
|
memories: cloud.memories,
|
|
420
429
|
rules: cloud.rules,
|
|
421
430
|
rulesUnread: cloud.failed === true,
|
|
431
|
+
planEnded: cloud.planEnded === true,
|
|
422
432
|
skills: cloud.skills,
|
|
423
433
|
writtenSkills: cloud.writtenSkills,
|
|
424
434
|
checks: cloud.checks,
|
package/dist/cloud.js
CHANGED
|
@@ -291,9 +291,9 @@ export async function fetchContext(deps = {}) {
|
|
|
291
291
|
return { ...NOTHING, failed: true };
|
|
292
292
|
}
|
|
293
293
|
const answer = res.answer;
|
|
294
|
-
// Not on the dashboard: nothing of it, but whether the org's plan includes Jobs still counts.
|
|
294
|
+
// Not on the dashboard: nothing of it, but whether the org's plan includes Jobs still counts, and whether its plan ended.
|
|
295
295
|
if (answer?.connected !== true)
|
|
296
|
-
return { ...NOTHING, answered: true, ...(answer?.jobs === true ? { jobs: true } : {}) };
|
|
296
|
+
return { ...NOTHING, answered: true, ...(answer?.jobs === true ? { jobs: true } : {}), ...(answer?.plan_ended === true ? { planEnded: true } : {}) };
|
|
297
297
|
const skills = Array.isArray(answer.skills) ? answer.skills.filter(isSkillPath).slice(0, 10) : [];
|
|
298
298
|
return { connected: true, answered: true, memories: readMemories(answer.memories), rules: readRules(answer.rules), skills, checks: readChecks(answer.checks), writtenSkills: readWrittenSkills(answer.written_skills), jobs: answer.jobs === true };
|
|
299
299
|
}
|
package/dist/connect.js
CHANGED
|
@@ -90,7 +90,7 @@ export function loginName(ai) {
|
|
|
90
90
|
}
|
|
91
91
|
/** The name of the AI that does the work. */
|
|
92
92
|
export function aiName(ai) {
|
|
93
|
-
return ai === "codex" ? "Codex" : "Claude";
|
|
93
|
+
return ai === "codex" ? "Codex" : ai === "antigravity" ? "Antigravity" : "Claude";
|
|
94
94
|
}
|
|
95
95
|
/**
|
|
96
96
|
* The comment that asks to connect the AI that checks the review. The review doesn't wait for it longer
|
package/dist/init.js
CHANGED
|
@@ -23,6 +23,28 @@ function addSkill(deps, skills) {
|
|
|
23
23
|
cpSync(deps.skillDir, join(skills, "mergelight"), { recursive: true });
|
|
24
24
|
}
|
|
25
25
|
const why = (r) => (r.stderr || r.stdout).trim().split("\n").at(-1)?.slice(0, 200) ?? "no reason given";
|
|
26
|
+
/**
|
|
27
|
+
* Adds the server as "mergelight" to an agent's JSON file of MCP servers, keeping everything else in it.
|
|
28
|
+
* A file that isn't a JSON object is never overwritten: false, and it stays as it was.
|
|
29
|
+
*/
|
|
30
|
+
function addToMcpFile(file, entry) {
|
|
31
|
+
let config = {};
|
|
32
|
+
if (existsSync(file)) {
|
|
33
|
+
try {
|
|
34
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
35
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
36
|
+
return false;
|
|
37
|
+
config = parsed;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const servers = config.mcpServers && typeof config.mcpServers === "object" ? config.mcpServers : {};
|
|
44
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
45
|
+
writeFileSync(file, `${JSON.stringify({ ...config, mcpServers: { ...servers, mergelight: entry } }, null, 2)}\n`);
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
26
48
|
export async function init(deps) {
|
|
27
49
|
const server = serverCommand(deps.cliPath);
|
|
28
50
|
let added = 0;
|
|
@@ -51,19 +73,7 @@ export async function init(deps) {
|
|
|
51
73
|
const cursor = join(deps.home, ".cursor");
|
|
52
74
|
if (existsSync(cursor)) {
|
|
53
75
|
const file = join(cursor, "mcp.json");
|
|
54
|
-
|
|
55
|
-
if (existsSync(file)) {
|
|
56
|
-
try {
|
|
57
|
-
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
58
|
-
config = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
59
|
-
}
|
|
60
|
-
catch {
|
|
61
|
-
config = null;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
if (config) {
|
|
65
|
-
const servers = config.mcpServers && typeof config.mcpServers === "object" ? config.mcpServers : {};
|
|
66
|
-
writeFileSync(file, `${JSON.stringify({ ...config, mcpServers: { ...servers, mergelight: { type: "stdio", ...server } } }, null, 2)}\n`);
|
|
76
|
+
if (addToMcpFile(file, { type: "stdio", ...server })) {
|
|
67
77
|
addSkill(deps, join(cursor, "skills"));
|
|
68
78
|
deps.log("✓ MCP server and skill added for Cursor");
|
|
69
79
|
added++;
|
|
@@ -71,8 +81,26 @@ export async function init(deps) {
|
|
|
71
81
|
else
|
|
72
82
|
deps.log(`Cursor: ${file} isn't valid JSON, so it's left as it is. To add Mergelight by hand, see ${DOCS}`);
|
|
73
83
|
}
|
|
84
|
+
// Antigravity, Google's agent app and its CLI (agy). Both read one shared file for MCP servers. ~/.gemini alone
|
|
85
|
+
// is Gemini CLI's, so only the folders Antigravity makes, or its CLI on the PATH, count as a sign that it is here.
|
|
86
|
+
const gemini = join(deps.home, ".gemini");
|
|
87
|
+
const agyCli = existsSync(join(gemini, "antigravity-cli")) || (await has(deps, "agy"));
|
|
88
|
+
if (agyCli || ["antigravity", "antigravity-ide", "config"].some((d) => existsSync(join(gemini, d)))) {
|
|
89
|
+
const file = join(gemini, "config", "mcp_config.json");
|
|
90
|
+
// Antigravity has no "type" field: a server with a command is a local one.
|
|
91
|
+
if (addToMcpFile(file, server)) {
|
|
92
|
+
// The app reads global skills from config/skills, and the CLI from antigravity-cli/skills.
|
|
93
|
+
addSkill(deps, join(gemini, "config", "skills"));
|
|
94
|
+
if (agyCli)
|
|
95
|
+
addSkill(deps, join(gemini, "antigravity-cli", "skills"));
|
|
96
|
+
deps.log("✓ MCP server and skill added for Antigravity");
|
|
97
|
+
added++;
|
|
98
|
+
}
|
|
99
|
+
else
|
|
100
|
+
deps.log(`Antigravity: ${file} isn't valid JSON, so it's left as it is. To add Mergelight by hand, see ${DOCS}`);
|
|
101
|
+
}
|
|
74
102
|
if (!added) {
|
|
75
|
-
deps.log(`No coding agent was set up. Mergelight looks for Claude Code, Codex and
|
|
103
|
+
deps.log(`No coding agent was set up. Mergelight looks for Claude Code, Codex, Cursor and Antigravity. To add it by hand, see ${DOCS}`);
|
|
76
104
|
return 1;
|
|
77
105
|
}
|
|
78
106
|
if (!(await has(deps, "gh")))
|
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { closeSync, lstatSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { run } from "../run.js";
|
|
6
|
+
import { serve, SERVER_VERSION } from "./server.js";
|
|
7
|
+
/**
|
|
8
|
+
* Mergelight's own read-only code tools, as an MCP server, for an agent that has no safe way to search
|
|
9
|
+
* code by itself. Antigravity's agy only searches through its shell, and a shell in a pull request's
|
|
10
|
+
* checkout could run the pull request's code next to the AI's login. These tools are plain Node: they
|
|
11
|
+
* read files and never run anything from the checkout. The one program they start is git, with fixed
|
|
12
|
+
* arguments, to show a file as an older commit had it.
|
|
13
|
+
*
|
|
14
|
+
* Every path is followed through links first and must end inside one of the folders the server was
|
|
15
|
+
* started with, so a link the pull request planted can't lead out of the checkout. Links are followed by
|
|
16
|
+
* the operating system (realpath.native), never by Node's JavaScript realpath, which resolves "up/.."
|
|
17
|
+
* as text: a link "evil -> up/../passwd" next to "up -> /etc" and a decoy "passwd" would pass that check
|
|
18
|
+
* while opening the link reads /etc/passwd. What is read is the real path the check saw, never the link.
|
|
19
|
+
*/
|
|
20
|
+
const real = (p) => realpathSync.native(p);
|
|
21
|
+
export const CODE_SERVER_NAME = "mergelight_code";
|
|
22
|
+
export const CODE_SERVER_TOOLS = ["read_code", "search_code", "find_files", "list_folder", "read_file_at_commit"];
|
|
23
|
+
const MAX_FILES = 100_000;
|
|
24
|
+
const MAX_READ_BYTES = 5_000_000;
|
|
25
|
+
/** read_code reads in pages, so a big file such as a huge pull request's saved diff can still be read. */
|
|
26
|
+
const MAX_PAGED_BYTES = 50_000_000;
|
|
27
|
+
const MAX_SEARCH_BYTES = 1_000_000;
|
|
28
|
+
const MAX_LINE = 2_000;
|
|
29
|
+
const READ_LINES = 400;
|
|
30
|
+
const MAX_READ_LINES = 2_000;
|
|
31
|
+
const SEARCH_RESULTS = 100;
|
|
32
|
+
const MAX_SEARCH_RESULTS = 400;
|
|
33
|
+
const SEARCH_MS = 20_000;
|
|
34
|
+
const LIST_MAX = 1_000;
|
|
35
|
+
const FIND_MAX = 500;
|
|
36
|
+
class ToolError extends Error {
|
|
37
|
+
}
|
|
38
|
+
/** The folders the server reads, as they really are on disk. The first is the checkout. */
|
|
39
|
+
function realRoots(roots) {
|
|
40
|
+
const out = roots.map((r) => {
|
|
41
|
+
try {
|
|
42
|
+
return real(r);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return resolve(r);
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
if (!out.length)
|
|
49
|
+
throw new Error("The code server needs a folder to read.");
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
const insideOf = (roots, p) => roots.some((r) => p === r || p.startsWith(r.endsWith(sep) ? r : r + sep));
|
|
53
|
+
/** A path the model gave, as a real path inside the folders, or an error that says why not. */
|
|
54
|
+
function place(roots, given) {
|
|
55
|
+
const p = typeof given === "string" && given.trim() ? given.trim() : ".";
|
|
56
|
+
if (p.startsWith("~") || /^[a-z]+:/i.test(p))
|
|
57
|
+
throw new ToolError(`${p}: only paths inside the checkout can be read.`);
|
|
58
|
+
const abs = isAbsolute(p) ? p : resolve(roots[0], p);
|
|
59
|
+
let found;
|
|
60
|
+
try {
|
|
61
|
+
found = real(abs);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
throw new ToolError(`${p}: no such file or folder.`);
|
|
65
|
+
}
|
|
66
|
+
if (!insideOf(roots, found))
|
|
67
|
+
throw new ToolError(`${p}: only paths inside the checkout can be read.`);
|
|
68
|
+
return found;
|
|
69
|
+
}
|
|
70
|
+
/** How a path is shown: relative to the checkout when it's in it. */
|
|
71
|
+
const shown = (roots, p) => {
|
|
72
|
+
const rel = relative(roots[0], p);
|
|
73
|
+
return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel.split(sep).join("/") : p;
|
|
74
|
+
};
|
|
75
|
+
/** True when the start of a file has a NUL byte, as binaries do and text doesn't. */
|
|
76
|
+
function looksBinary(file) {
|
|
77
|
+
const fd = openSync(file, "r");
|
|
78
|
+
try {
|
|
79
|
+
const buf = Buffer.alloc(8_192);
|
|
80
|
+
const n = readSync(fd, buf, 0, buf.length, 0);
|
|
81
|
+
return buf.subarray(0, n).includes(0);
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
closeSync(fd);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const cut = (line) => (line.length > MAX_LINE ? `${line.slice(0, MAX_LINE)} [line cut at ${MAX_LINE} characters]` : line);
|
|
88
|
+
function numbered(text, offset, limit, label) {
|
|
89
|
+
const lines = text.split("\n");
|
|
90
|
+
if (lines.length > 1 && lines.at(-1) === "")
|
|
91
|
+
lines.pop();
|
|
92
|
+
const start = Math.max(1, Math.floor(Number(offset) || 1));
|
|
93
|
+
const count = Math.min(MAX_READ_LINES, Math.max(1, Math.floor(Number(limit) || READ_LINES)));
|
|
94
|
+
const end = Math.min(lines.length, start + count - 1);
|
|
95
|
+
if (start > lines.length)
|
|
96
|
+
return `${label} has ${lines.length} lines; line ${start} is past the end.`;
|
|
97
|
+
const body = lines.slice(start - 1, end).map((l, i) => `${start + i}\t${cut(l)}`).join("\n");
|
|
98
|
+
const more = end < lines.length ? `\n[lines ${start}-${end} of ${lines.length}: read on with offset ${end + 1}]` : "";
|
|
99
|
+
return `${body}${more}`;
|
|
100
|
+
}
|
|
101
|
+
/** Every file under a folder, as real paths inside the folders. Links to folders aren't followed; .git is skipped. */
|
|
102
|
+
function filesUnder(roots, dir) {
|
|
103
|
+
const files = [];
|
|
104
|
+
const todo = [dir];
|
|
105
|
+
while (todo.length) {
|
|
106
|
+
const at = todo.pop();
|
|
107
|
+
let names;
|
|
108
|
+
try {
|
|
109
|
+
names = readdirSync(at);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
for (const name of names.sort()) {
|
|
115
|
+
if (name === ".git")
|
|
116
|
+
continue;
|
|
117
|
+
const path = join(at, name);
|
|
118
|
+
const kind = lstatSync(path, { throwIfNoEntry: false });
|
|
119
|
+
if (!kind)
|
|
120
|
+
continue;
|
|
121
|
+
if (kind.isDirectory())
|
|
122
|
+
todo.push(path);
|
|
123
|
+
else if (kind.isFile())
|
|
124
|
+
files.push(path);
|
|
125
|
+
else if (kind.isSymbolicLink()) {
|
|
126
|
+
// The file the link really leads to, as the system follows it, is the one listed and read.
|
|
127
|
+
try {
|
|
128
|
+
const target = real(path);
|
|
129
|
+
if (insideOf(roots, target) && statSync(target).isFile())
|
|
130
|
+
files.push(target);
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// A broken link has nothing to read.
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (files.length >= MAX_FILES)
|
|
137
|
+
return { files, cut: true };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return { files: files.sort(), cut: false };
|
|
141
|
+
}
|
|
142
|
+
/** A glob as a regular expression: ** for any folders, * and ? inside one name, {a,b} for either. */
|
|
143
|
+
export function globRegex(glob) {
|
|
144
|
+
let out = "";
|
|
145
|
+
let depth = 0;
|
|
146
|
+
for (let i = 0; i < glob.length; i++) {
|
|
147
|
+
const ch = glob[i];
|
|
148
|
+
if (ch === "*") {
|
|
149
|
+
if (glob[i + 1] === "*") {
|
|
150
|
+
const slash = glob[i + 2] === "/";
|
|
151
|
+
out += slash ? "(?:.*/)?" : ".*";
|
|
152
|
+
i += slash ? 2 : 1;
|
|
153
|
+
}
|
|
154
|
+
else
|
|
155
|
+
out += "[^/]*";
|
|
156
|
+
}
|
|
157
|
+
else if (ch === "?")
|
|
158
|
+
out += "[^/]";
|
|
159
|
+
else if (ch === "{") {
|
|
160
|
+
depth++;
|
|
161
|
+
out += "(?:";
|
|
162
|
+
}
|
|
163
|
+
else if (ch === "}" && depth > 0) {
|
|
164
|
+
depth--;
|
|
165
|
+
out += ")";
|
|
166
|
+
}
|
|
167
|
+
else if (ch === "," && depth > 0)
|
|
168
|
+
out += "|";
|
|
169
|
+
else
|
|
170
|
+
out += ch.replace(/[.+^$()|[\]\\]/g, "\\$&");
|
|
171
|
+
}
|
|
172
|
+
return new RegExp(`^${out}$`);
|
|
173
|
+
}
|
|
174
|
+
/** Whether a path matches a glob. A glob without a slash matches a file's name in any folder. */
|
|
175
|
+
function globMatch(glob, rel) {
|
|
176
|
+
const re = globRegex(glob.replace(/^\.\//, ""));
|
|
177
|
+
return glob.includes("/") ? re.test(rel) : re.test(rel.split("/").pop() ?? rel);
|
|
178
|
+
}
|
|
179
|
+
function readCode(roots, args) {
|
|
180
|
+
const file = place(roots, args.path);
|
|
181
|
+
const info = statSync(file);
|
|
182
|
+
if (info.isDirectory())
|
|
183
|
+
throw new ToolError(`${shown(roots, file)} is a folder: use list_folder.`);
|
|
184
|
+
if (info.size > MAX_PAGED_BYTES)
|
|
185
|
+
throw new ToolError(`${shown(roots, file)} is larger than ${MAX_PAGED_BYTES / 1_000_000} MB.`);
|
|
186
|
+
if (looksBinary(file))
|
|
187
|
+
return `${shown(roots, file)} is a binary file.`;
|
|
188
|
+
return numbered(readFileSync(file, "utf8"), args.offset, args.limit, shown(roots, file));
|
|
189
|
+
}
|
|
190
|
+
function searchCode(roots, args) {
|
|
191
|
+
// Models also call the pattern "query" or "regex": either works.
|
|
192
|
+
if (typeof args.pattern !== "string" || !args.pattern)
|
|
193
|
+
args = { ...args, pattern: typeof args.query === "string" ? args.query : args.regex };
|
|
194
|
+
if (typeof args.pattern !== "string" || !args.pattern)
|
|
195
|
+
throw new ToolError("pattern is required: a regular expression, as JavaScript writes them.");
|
|
196
|
+
let re;
|
|
197
|
+
try {
|
|
198
|
+
re = new RegExp(args.pattern, args.ignore_case === true ? "i" : "");
|
|
199
|
+
}
|
|
200
|
+
catch (err) {
|
|
201
|
+
throw new ToolError(`pattern isn't a valid regular expression: ${err.message}`);
|
|
202
|
+
}
|
|
203
|
+
const where = place(roots, args.path);
|
|
204
|
+
const glob = typeof args.glob === "string" && args.glob.trim() ? args.glob.trim() : null;
|
|
205
|
+
const context = Math.min(5, Math.max(0, Math.floor(Number(args.context) || 0)));
|
|
206
|
+
const max = Math.min(MAX_SEARCH_RESULTS, Math.max(1, Math.floor(Number(args.max_results) || SEARCH_RESULTS)));
|
|
207
|
+
const listing = statSync(where).isDirectory() ? filesUnder(roots, where) : { files: [where], cut: false };
|
|
208
|
+
const started = Date.now();
|
|
209
|
+
const out = [];
|
|
210
|
+
let found = 0;
|
|
211
|
+
let large = 0;
|
|
212
|
+
let stopped = null;
|
|
213
|
+
for (const file of listing.files) {
|
|
214
|
+
const rel = shown(roots, file);
|
|
215
|
+
if (glob && !globMatch(glob, rel))
|
|
216
|
+
continue;
|
|
217
|
+
if (Date.now() - started > SEARCH_MS) {
|
|
218
|
+
stopped = "the search took too long";
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
let text;
|
|
222
|
+
try {
|
|
223
|
+
if (statSync(file).size > MAX_SEARCH_BYTES) {
|
|
224
|
+
large++;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (looksBinary(file))
|
|
228
|
+
continue;
|
|
229
|
+
text = readFileSync(file, "utf8");
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
const lines = text.split("\n");
|
|
235
|
+
const line = (j, hit) => `${rel}${hit ? ":" : "-"}${j + 1}${hit ? ":" : "-"}${cut(lines[j])}`;
|
|
236
|
+
// Where each line of this file went in the output, so a line first shown as context can become a match.
|
|
237
|
+
const at = new Map();
|
|
238
|
+
let last = -1;
|
|
239
|
+
for (let i = 0; i < lines.length; i++) {
|
|
240
|
+
// Very long lines, like minified code, are searched in part, so one can't hold the search up.
|
|
241
|
+
if (!re.test(lines[i].slice(0, 4 * MAX_LINE)))
|
|
242
|
+
continue;
|
|
243
|
+
const from = Math.max(0, i - context, last + 1);
|
|
244
|
+
if (context && out.length && from > last + 1)
|
|
245
|
+
out.push("--");
|
|
246
|
+
const shownBefore = at.get(i);
|
|
247
|
+
if (shownBefore !== undefined)
|
|
248
|
+
out[shownBefore] = line(i, true);
|
|
249
|
+
for (let j = from; j <= Math.min(lines.length - 1, i + context); j++) {
|
|
250
|
+
at.set(j, out.length);
|
|
251
|
+
out.push(line(j, j === i));
|
|
252
|
+
last = j;
|
|
253
|
+
}
|
|
254
|
+
found++;
|
|
255
|
+
if (found >= max) {
|
|
256
|
+
stopped = `it reached ${max} matches: narrow it with path or glob`;
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (stopped)
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
const notes = [
|
|
264
|
+
stopped ? `[stopped early: ${stopped}]` : "",
|
|
265
|
+
listing.cut ? `[only the first ${MAX_FILES} files were searched]` : "",
|
|
266
|
+
large ? `[${large} file${large === 1 ? "" : "s"} over ${MAX_SEARCH_BYTES / 1_000_000} MB not searched: read ${large === 1 ? "it" : "them"} with read_code]` : "",
|
|
267
|
+
].filter(Boolean);
|
|
268
|
+
// A search that stopped early found nothing in what it read: it says so, not that nothing is there.
|
|
269
|
+
if (!found)
|
|
270
|
+
return [`No matches for /${args.pattern}/${glob ? ` in files matching ${glob}` : ""}${notes.length ? " in the files searched" : ""}.`, ...notes].join("\n");
|
|
271
|
+
return [...out, ...notes].join("\n");
|
|
272
|
+
}
|
|
273
|
+
function findFiles(roots, args) {
|
|
274
|
+
// Models also call the glob "glob", as search_code names it: either works.
|
|
275
|
+
const pattern = typeof args.pattern === "string" && args.pattern.trim() ? args.pattern.trim() : typeof args.glob === "string" ? args.glob.trim() : "";
|
|
276
|
+
if (!pattern)
|
|
277
|
+
throw new ToolError('pattern is required: a glob such as "**/*.test.ts" or "*.sql".');
|
|
278
|
+
const listing = filesUnder(roots, place(roots, args.path));
|
|
279
|
+
const hits = listing.files.map((f) => shown(roots, f)).filter((rel) => globMatch(pattern, rel));
|
|
280
|
+
const partial = listing.cut ? [`[only the first ${MAX_FILES} files were looked at: narrow it with path]`] : [];
|
|
281
|
+
if (!hits.length)
|
|
282
|
+
return [`No files match ${pattern}.`, ...partial].join("\n");
|
|
283
|
+
return [...hits.slice(0, FIND_MAX), ...(hits.length > FIND_MAX ? [`[${hits.length - FIND_MAX} more: narrow the pattern]`] : []), ...partial].join("\n");
|
|
284
|
+
}
|
|
285
|
+
function listFolder(roots, args) {
|
|
286
|
+
const dir = place(roots, args.path);
|
|
287
|
+
if (!statSync(dir).isDirectory())
|
|
288
|
+
throw new ToolError(`${shown(roots, dir)} is a file: use read_code.`);
|
|
289
|
+
const names = readdirSync(dir).filter((n) => n !== ".git").sort();
|
|
290
|
+
const lines = names.slice(0, LIST_MAX).map((name) => {
|
|
291
|
+
const kind = lstatSync(join(dir, name), { throwIfNoEntry: false });
|
|
292
|
+
return kind?.isDirectory() ? `${name}/` : kind?.isSymbolicLink() ? `${name} (link)` : name;
|
|
293
|
+
});
|
|
294
|
+
if (!lines.length)
|
|
295
|
+
return `${shown(roots, dir)} is empty.`;
|
|
296
|
+
return [...lines, ...(names.length > LIST_MAX ? [`[${names.length - LIST_MAX} more]`] : [])].join("\n");
|
|
297
|
+
}
|
|
298
|
+
/** A path as git names it in a commit: relative, with no way to be read as an option or to climb out. */
|
|
299
|
+
function repoPath(given) {
|
|
300
|
+
const p = typeof given === "string" ? given.trim().replace(/^\.\//, "").replace(/\\/g, "/") : "";
|
|
301
|
+
if (!p || p.startsWith("/") || p.startsWith("-") || p.split("/").some((part) => part === ".." || part === "") || /[\0\n\r]/.test(p)) {
|
|
302
|
+
throw new ToolError("path must be the file's path in the repository, such as src/app.ts.");
|
|
303
|
+
}
|
|
304
|
+
return p;
|
|
305
|
+
}
|
|
306
|
+
async function readAtCommit(roots, args) {
|
|
307
|
+
const commit = typeof args.commit === "string" ? args.commit.trim() : "";
|
|
308
|
+
if (!/^[0-9a-f]{7,64}$/i.test(commit))
|
|
309
|
+
throw new ToolError("commit must be a commit's hash, such as the merge base the prompt names.");
|
|
310
|
+
const path = repoPath(args.path);
|
|
311
|
+
// Fixed arguments, and no settings but the checkout's own, which Mergelight wrote: no pager, no textconv, no fsmonitor.
|
|
312
|
+
const r = await run("git", ["-c", "core.fsmonitor=false", "-c", "core.pager=cat", "--no-pager", "show", "--no-textconv", `${commit}:${path}`], {
|
|
313
|
+
cwd: roots[0],
|
|
314
|
+
timeoutMs: 15_000,
|
|
315
|
+
// HOME is never the checkout: a .gitconfig the pull request put there must not count, whatever git version reads it.
|
|
316
|
+
env: { PATH: process.env.PATH ?? "/usr/bin:/bin", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_TERMINAL_PROMPT: "0", HOME: tmpdir() },
|
|
317
|
+
});
|
|
318
|
+
if (r.code !== 0)
|
|
319
|
+
throw new ToolError(`${path} at ${commit.slice(0, 12)}: ${(r.stderr.trim().split("\n").pop() ?? "not found").slice(0, 200)}`);
|
|
320
|
+
if (r.stdout.length > MAX_READ_BYTES)
|
|
321
|
+
throw new ToolError(`${path} at ${commit.slice(0, 12)} is larger than ${MAX_READ_BYTES / 1_000_000} MB.`);
|
|
322
|
+
if (r.stdout.includes("\0"))
|
|
323
|
+
return `${path} at ${commit.slice(0, 12)} is a binary file.`;
|
|
324
|
+
return numbered(r.stdout, args.offset, args.limit, `${path} at ${commit.slice(0, 12)}`);
|
|
325
|
+
}
|
|
326
|
+
const PATH_ARG = { type: "string", description: "A path inside the checkout, relative to it or absolute." };
|
|
327
|
+
const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
328
|
+
/** The server for these folders. The first one is the checkout, which relative paths start from. */
|
|
329
|
+
export function codeServer(folders) {
|
|
330
|
+
const roots = realRoots(folders);
|
|
331
|
+
const tool = (fn) => async (args) => fn(roots, args);
|
|
332
|
+
return {
|
|
333
|
+
info: { name: CODE_SERVER_NAME, title: "Mergelight code reader", version: SERVER_VERSION },
|
|
334
|
+
instructions: "Read-only tools for the checkout under review: read_code reads a file with line numbers, search_code searches file contents with a regular expression, " +
|
|
335
|
+
"find_files finds files by a glob, list_folder lists a folder, and read_file_at_commit shows a file as an older commit had it. Nothing here can write or run code.",
|
|
336
|
+
text: (result) => (typeof result === "string" ? result : JSON.stringify(result)),
|
|
337
|
+
tools: [
|
|
338
|
+
{
|
|
339
|
+
name: "read_code",
|
|
340
|
+
title: "Read a file",
|
|
341
|
+
description: `Read a text file in the checkout, with line numbers. ${READ_LINES} lines at a time unless limit says more (at most ${MAX_READ_LINES}); offset is the first line, from 1.`,
|
|
342
|
+
inputSchema: { type: "object", properties: { path: PATH_ARG, offset: { type: "integer", minimum: 1 }, limit: { type: "integer", minimum: 1, maximum: MAX_READ_LINES } }, required: ["path"], additionalProperties: false },
|
|
343
|
+
annotations: { title: "Read a file", ...READ_ONLY },
|
|
344
|
+
run: tool(readCode),
|
|
345
|
+
},
|
|
346
|
+
{
|
|
347
|
+
name: "search_code",
|
|
348
|
+
title: "Search the code",
|
|
349
|
+
description: 'Search file contents in the checkout with a regular expression (JavaScript syntax), like grep -n. Each match is "path:line:text"; with context, the lines around it are "path-line-text". ' +
|
|
350
|
+
'path limits it to a folder or one file; glob limits it to files such as "*.ts" or "src/**/*.sql".',
|
|
351
|
+
inputSchema: {
|
|
352
|
+
type: "object",
|
|
353
|
+
properties: {
|
|
354
|
+
pattern: { type: "string" },
|
|
355
|
+
path: PATH_ARG,
|
|
356
|
+
glob: { type: "string" },
|
|
357
|
+
ignore_case: { type: "boolean" },
|
|
358
|
+
context: { type: "integer", minimum: 0, maximum: 5 },
|
|
359
|
+
max_results: { type: "integer", minimum: 1, maximum: MAX_SEARCH_RESULTS },
|
|
360
|
+
},
|
|
361
|
+
required: ["pattern"],
|
|
362
|
+
additionalProperties: false,
|
|
363
|
+
},
|
|
364
|
+
annotations: { title: "Search the code", ...READ_ONLY },
|
|
365
|
+
run: tool(searchCode),
|
|
366
|
+
},
|
|
367
|
+
{
|
|
368
|
+
name: "find_files",
|
|
369
|
+
title: "Find files",
|
|
370
|
+
description: 'Find files in the checkout whose path matches a glob: ** for any folders, * inside a name, {a,b} for either. A glob without a slash matches file names in every folder, such as "*.test.ts".',
|
|
371
|
+
inputSchema: { type: "object", properties: { pattern: { type: "string" }, path: PATH_ARG }, required: ["pattern"], additionalProperties: false },
|
|
372
|
+
annotations: { title: "Find files", ...READ_ONLY },
|
|
373
|
+
run: tool(findFiles),
|
|
374
|
+
},
|
|
375
|
+
{
|
|
376
|
+
name: "list_folder",
|
|
377
|
+
title: "List a folder",
|
|
378
|
+
description: "List what a folder in the checkout holds. Folders end with a slash. Without path, the checkout's top folder.",
|
|
379
|
+
inputSchema: { type: "object", properties: { path: PATH_ARG }, additionalProperties: false },
|
|
380
|
+
annotations: { title: "List a folder", ...READ_ONLY },
|
|
381
|
+
run: tool(listFolder),
|
|
382
|
+
},
|
|
383
|
+
{
|
|
384
|
+
name: "read_file_at_commit",
|
|
385
|
+
title: "Read a file at a commit",
|
|
386
|
+
description: "Read a file as a commit had it, with line numbers: give the commit's hash, such as the merge base, and the file's path in the repository. Use it to see code the pull request removed or changed.",
|
|
387
|
+
inputSchema: {
|
|
388
|
+
type: "object",
|
|
389
|
+
properties: { commit: { type: "string" }, path: { type: "string" }, offset: { type: "integer", minimum: 1 }, limit: { type: "integer", minimum: 1, maximum: MAX_READ_LINES } },
|
|
390
|
+
required: ["commit", "path"],
|
|
391
|
+
additionalProperties: false,
|
|
392
|
+
},
|
|
393
|
+
annotations: { title: "Read a file at a commit", ...READ_ONLY },
|
|
394
|
+
run: tool(readAtCommit),
|
|
395
|
+
},
|
|
396
|
+
],
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
/** Started as its own program by the agent: the folders to read come as a JSON list. */
|
|
400
|
+
if (process.argv[1] && (() => {
|
|
401
|
+
try {
|
|
402
|
+
return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
return false;
|
|
406
|
+
}
|
|
407
|
+
})()) {
|
|
408
|
+
const folders = JSON.parse(process.argv[2] ?? "[]");
|
|
409
|
+
if (!Array.isArray(folders) || !folders.every((f) => typeof f === "string")) {
|
|
410
|
+
process.stderr.write("mergelight code server: pass the folders to read as a JSON list\n");
|
|
411
|
+
process.exit(2);
|
|
412
|
+
}
|
|
413
|
+
await serve(process.stdin, process.stdout, codeServer(folders));
|
|
414
|
+
}
|