@sagentlab/navarch-runtime 0.1.186 → 0.1.188

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.
@@ -0,0 +1,604 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.gitHistoryShapes = exports.GitHistoryError = exports.GIT_HISTORY_TOKEN_ENV = exports.GIT_HISTORY_TOOL_NAMES = exports.GIT_HISTORY_SERVER_NAME = void 0;
7
+ exports.validRepositoryPath = validRepositoryPath;
8
+ exports.createGitHistory = createGitHistory;
9
+ exports.startGitHistoryServer = startGitHistoryServer;
10
+ const node_child_process_1 = require("node:child_process");
11
+ const node_crypto_1 = require("node:crypto");
12
+ const node_fs_1 = require("node:fs");
13
+ const node_http_1 = require("node:http");
14
+ const node_path_1 = __importDefault(require("node:path"));
15
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
16
+ const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
17
+ const zod_1 = require("zod");
18
+ const kill_agent_cjs_1 = require("../kill-agent.cjs");
19
+ /**
20
+ * Read-only git history for a Navi repository question.
21
+ *
22
+ * A read-only conversation has no shell (adapters/claude-conversation.cts), so
23
+ * the agent could see `.git/objects/pack` but not read a single commit: "who
24
+ * wrote this", "what changed last week" and "lines per author" all failed.
25
+ * Giving it Bash would undo the boundary that makes a question unable to
26
+ * change anything, and `git` alone can write files (`git log --output=`), run
27
+ * configured programs (external diff, textconv, pager) or reach the network.
28
+ *
29
+ * So the runtime runs git itself and exposes five fixed queries over a
30
+ * loopback MCP server that lives for one turn:
31
+ *
32
+ * - The agent never supplies a git argument. It supplies typed values, each
33
+ * validated and placed in a fixed argv position. Revisions are resolved to a
34
+ * commit hash first, so nothing the agent wrote reaches git as a revision or
35
+ * an option. Paths follow `--` with pathspec magic disabled.
36
+ * - Queries run without system or user git config, without a pager, external
37
+ * diff or textconv, and without network access.
38
+ * - Output is parsed as a stream and capped, so a large history cannot exhaust
39
+ * the runtime's memory or the agent's context.
40
+ *
41
+ * Direct clones are blobless (workspace.cts), which is enough for commit
42
+ * metadata but not for line counts, blame or patches. The first query that
43
+ * needs file contents downloads them once, with the same checkout credential
44
+ * the clone used. That credential stays in this process and its git child; the
45
+ * agent never receives it.
46
+ */
47
+ exports.GIT_HISTORY_SERVER_NAME = "navarch_git";
48
+ exports.GIT_HISTORY_TOOL_NAMES = ["git_log", "git_contributors", "git_blame", "git_show", "git_diff"];
49
+ /** Environment variable that carries the turn's bearer to an agent that reads it from there (Codex). */
50
+ exports.GIT_HISTORY_TOKEN_ENV = "NAVARCH_CHAT_GIT_HISTORY_TOKEN";
51
+ const QUERY_TIMEOUT_MS = 60_000;
52
+ /** Whole-history line counts read every commit's diff. */
53
+ const CONTRIBUTORS_TIMEOUT_MS = 150_000;
54
+ /** One-time download of file contents for a blobless checkout; a turn lasts at most nine minutes. */
55
+ const BACKFILL_TIMEOUT_MS = 3 * 60_000;
56
+ const MAX_OUTPUT_CHARS = 24_000;
57
+ const MAX_LINE_CHARS = 300;
58
+ const MAX_CONTRIBUTORS = 100;
59
+ /** Queries one turn may run; a question needs a handful. */
60
+ const MAX_CALLS = 60;
61
+ const STDERR_TAIL_CHARS = 2_000;
62
+ /** Written inside `.git` so it is removed with the checkout it describes. */
63
+ const FULL_HISTORY_MARKER = "navarch-full-history";
64
+ const NULL_DEVICE = process.platform === "win32" ? "NUL" : "/dev/null";
65
+ const RECORD = "\x1e";
66
+ const FIELD = "\x1f";
67
+ /** A message that is safe and useful to show the agent. */
68
+ class GitHistoryError extends Error {
69
+ }
70
+ exports.GitHistoryError = GitHistoryError;
71
+ /**
72
+ * A branch, tag or commit expression such as `main`, `origin/dev`, `a1b2c3d`
73
+ * or `HEAD~3`. No leading `-` (an option), no `..` (a range), no `:` (a blob
74
+ * path) and no whitespace.
75
+ */
76
+ const REVISION = /^(?!-)(?!.*\.\.)[A-Za-z0-9_./@^~{}-]{1,200}$/;
77
+ function validRepositoryPath(value) {
78
+ if (!value || value.length > 1_000 || /[\0\n\r]/.test(value))
79
+ return false;
80
+ if (node_path_1.default.posix.isAbsolute(value) || node_path_1.default.win32.isAbsolute(value))
81
+ return false;
82
+ return !value.split(/[\\/]/).includes("..");
83
+ }
84
+ const revision = zod_1.z.string().regex(REVISION, "Use a branch name, tag or commit hash such as main, origin/dev, a1b2c3d or HEAD~3.");
85
+ const repositoryPath = zod_1.z.string().refine(validRepositoryPath, "Use a path relative to the repository root, without `..`.");
86
+ const dateText = zod_1.z.string().regex(/^[A-Za-z0-9 :.,+/-]{1,64}$/, "Use a date such as 2026-01-31 or `3 months ago`.");
87
+ const searchText = zod_1.z.string().min(1).max(200).refine((value) => !/[\0\n\r]/.test(value), "Use a single line of text.");
88
+ const scope = {
89
+ ref: revision.default("HEAD").describe("Branch, tag or commit to read history from. Other branches are `origin/<name>`."),
90
+ exclude_ref: revision.optional().describe("Leave out commits reachable from this revision, e.g. `origin/main` to see only a branch's own commits."),
91
+ path: repositoryPath.optional().describe("Limit to commits that touch this file or directory."),
92
+ since: dateText.optional().describe("Only commits after this date, e.g. `2026-01-01` or `3 months ago`."),
93
+ until: dateText.optional().describe("Only commits before this date."),
94
+ author: searchText.optional().describe("Only commits whose author name or email contains this text (case-insensitive)."),
95
+ };
96
+ exports.gitHistoryShapes = {
97
+ log: {
98
+ ...scope,
99
+ message: searchText.optional().describe("Only commits whose message contains this text (case-insensitive)."),
100
+ stats: zod_1.z.boolean().default(false).describe("Add files changed and lines added/removed per commit."),
101
+ limit: zod_1.z.number().int().min(1).max(200).default(30),
102
+ skip: zod_1.z.number().int().min(0).max(1_000_000).default(0).describe("Commits to skip, for paging."),
103
+ },
104
+ contributors: {
105
+ ...scope,
106
+ include_merges: zod_1.z.boolean().default(false).describe("Count merge commits as commits. They add no lines either way."),
107
+ line_counts: zod_1.z.boolean().default(true).describe("Include lines added and removed. Set false for commit counts only, which is faster."),
108
+ },
109
+ blame: {
110
+ path: repositoryPath.describe("File to annotate."),
111
+ ref: revision.default("HEAD"),
112
+ start_line: zod_1.z.number().int().min(1).max(10_000_000).default(1),
113
+ max_lines: zod_1.z.number().int().min(1).max(400).default(200),
114
+ },
115
+ show: {
116
+ commit: revision.describe("Commit to show."),
117
+ path: repositoryPath.optional().describe("Limit the stat and patch to this file or directory."),
118
+ patch: zod_1.z.boolean().default(false).describe("Include the diff text, not only the per-file summary."),
119
+ },
120
+ diff: {
121
+ base: revision.describe("Revision to compare from."),
122
+ head: revision.default("HEAD").describe("Revision to compare to."),
123
+ path: repositoryPath.optional(),
124
+ patch: zod_1.z.boolean().default(false).describe("Include the diff text, not only the per-file summary."),
125
+ from_merge_base: zod_1.z.boolean().default(false).describe("Compare `head` with the commit where it diverged from `base`, i.e. only what `head` added."),
126
+ },
127
+ };
128
+ const GIT_OPTIONS = [
129
+ "--no-pager",
130
+ "-c", "color.ui=false",
131
+ "-c", "core.quotePath=false",
132
+ "-c", "core.fsmonitor=false",
133
+ "-c", `core.hooksPath=${NULL_DEVICE}`,
134
+ "-c", "log.showSignature=false",
135
+ "-c", "gc.auto=0",
136
+ "-c", "maintenance.auto=false",
137
+ ];
138
+ /** Local queries: no system or user config, no prompts, no index refresh, no network. */
139
+ function queryEnv(base) {
140
+ return {
141
+ ...base,
142
+ GIT_CONFIG_NOSYSTEM: "1",
143
+ GIT_CONFIG_GLOBAL: NULL_DEVICE,
144
+ GIT_TERMINAL_PROMPT: "0",
145
+ GIT_OPTIONAL_LOCKS: "0",
146
+ // `:(exclude)`, `:/` and globs in a path are taken literally.
147
+ GIT_LITERAL_PATHSPECS: "1",
148
+ // A missing object is an error, never a fetch. Older git ignores the first
149
+ // variable; the second leaves it no transport to fetch with.
150
+ GIT_NO_LAZY_FETCH: "1",
151
+ GIT_ALLOW_PROTOCOL: "none",
152
+ };
153
+ }
154
+ function clip(text, limit = MAX_LINE_CHARS) {
155
+ return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
156
+ }
157
+ /** How many leading lines fit in one answer. Always at least one. */
158
+ function fitting(lines) {
159
+ let used = 0;
160
+ let count = 0;
161
+ for (const line of lines) {
162
+ used += line.length + 1;
163
+ if (count > 0 && used > MAX_OUTPUT_CHARS)
164
+ break;
165
+ count += 1;
166
+ }
167
+ return count;
168
+ }
169
+ function githubLogin(email) {
170
+ return /^(?:\d+\+)?([A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))@users\.noreply\.github\.com$/i.exec(email)?.[1] ?? null;
171
+ }
172
+ function createGitHistory(options) {
173
+ const env = queryEnv(options.env);
174
+ const queryMs = options.timeouts?.queryMs ?? QUERY_TIMEOUT_MS;
175
+ let fullHistory;
176
+ function run(args, opts) {
177
+ return new Promise((resolve) => {
178
+ if (options.signal?.aborted) {
179
+ resolve({ code: null, stdout: "", stderr: "", truncated: false, timedOut: false });
180
+ return;
181
+ }
182
+ const child = (0, node_child_process_1.spawn)("git", [...GIT_OPTIONS, ...args], {
183
+ cwd: options.checkout,
184
+ env: opts.env,
185
+ detached: process.platform !== "win32",
186
+ stdio: ["ignore", "pipe", "pipe"],
187
+ });
188
+ const maxChars = opts.maxChars ?? MAX_OUTPUT_CHARS;
189
+ let stdout = "";
190
+ let stderr = "";
191
+ let pending = "";
192
+ let truncated = false;
193
+ let timedOut = false;
194
+ let stopped = false;
195
+ const stop = () => {
196
+ if (stopped)
197
+ return;
198
+ stopped = true;
199
+ (0, kill_agent_cjs_1.killAgent)(child);
200
+ };
201
+ const timer = setTimeout(() => { timedOut = true; stop(); }, opts.timeoutMs);
202
+ const onAbort = () => stop();
203
+ options.signal?.addEventListener("abort", onAbort, { once: true });
204
+ child.stdout.setEncoding("utf8");
205
+ child.stdout.on("data", (chunk) => {
206
+ if (stopped)
207
+ return;
208
+ if (!opts.onLine) {
209
+ stdout += chunk;
210
+ if (stdout.length > maxChars) {
211
+ stdout = stdout.slice(0, maxChars);
212
+ truncated = true;
213
+ stop();
214
+ }
215
+ return;
216
+ }
217
+ pending += chunk;
218
+ let end;
219
+ while ((end = pending.indexOf("\n")) >= 0) {
220
+ const line = pending.slice(0, end);
221
+ pending = pending.slice(end + 1);
222
+ if (opts.onLine(line) === false) {
223
+ truncated = true;
224
+ stop();
225
+ return;
226
+ }
227
+ }
228
+ });
229
+ child.stderr.setEncoding("utf8");
230
+ child.stderr.on("data", (chunk) => { stderr = (stderr + chunk).slice(-STDERR_TAIL_CHARS); });
231
+ let settled = false;
232
+ const finish = (code) => {
233
+ if (settled)
234
+ return;
235
+ settled = true;
236
+ clearTimeout(timer);
237
+ options.signal?.removeEventListener("abort", onAbort);
238
+ if (opts.onLine && pending && !stopped)
239
+ opts.onLine(pending);
240
+ resolve({ code, stdout, stderr, truncated, timedOut });
241
+ };
242
+ child.on("error", () => finish(null));
243
+ child.on("close", (code) => finish(code));
244
+ });
245
+ }
246
+ /** Throws unless git finished normally or was stopped on purpose at an output limit. */
247
+ function check(result, what) {
248
+ if (options.signal?.aborted)
249
+ throw new GitHistoryError("This conversation turn was stopped.");
250
+ if (result.timedOut) {
251
+ throw new GitHistoryError(`${what} took too long. Narrow it with \`since\`, \`until\`, \`path\` or a smaller \`limit\`.`);
252
+ }
253
+ if (result.truncated || result.code === 0)
254
+ return result;
255
+ // git's own message names the bad revision or path; it carries no credential (local query, no network).
256
+ const reason = result.stderr.trim().split("\n").filter(Boolean).slice(-3).join(" ");
257
+ throw new GitHistoryError(`${what} failed${reason ? `: ${clip(reason, 400)}` : "."}`);
258
+ }
259
+ async function resolve(rev) {
260
+ const result = await run(["rev-parse", "--verify", "--quiet", `${rev}^{commit}`], { env, timeoutMs: queryMs });
261
+ if (options.signal?.aborted)
262
+ throw new GitHistoryError("This conversation turn was stopped.");
263
+ const hash = result.stdout.trim();
264
+ if (result.code !== 0 || !/^[0-9a-f]{40,64}$/.test(hash)) {
265
+ throw new GitHistoryError(`Unknown revision \`${rev}\`. Use a branch, tag or commit that exists in this checkout; branches other than the checked-out one are \`origin/<name>\`.`);
266
+ }
267
+ return hash;
268
+ }
269
+ /**
270
+ * True when every reachable file version is present locally. A blobless
271
+ * checkout is completed once per checkout; a failed download is not retried
272
+ * within the same turn.
273
+ */
274
+ function ensureFullHistory() {
275
+ fullHistory ??= (async () => {
276
+ const marker = node_path_1.default.join(options.checkout, ".git", FULL_HISTORY_MARKER);
277
+ if (await node_fs_1.promises.stat(marker).then(() => true, () => false))
278
+ return true;
279
+ const filter = await run(["config", "--get", "remote.origin.partialclonefilter"], { env, timeoutMs: queryMs });
280
+ if (filter.code !== 0 || !filter.stdout.trim())
281
+ return true; // an ordinary, complete clone
282
+ // The filter is recorded even when the server ignored it and sent
283
+ // everything, so look for an object that is really absent. A blobless
284
+ // checkout shows one within its newest commits.
285
+ let missing = false;
286
+ const probe = await run(["rev-list", "--objects", "--missing=print", "--all"], {
287
+ env, timeoutMs: queryMs,
288
+ onLine: (line) => { missing = line.startsWith("?"); return !missing; },
289
+ });
290
+ if (!missing && probe.code === 0) {
291
+ await node_fs_1.promises.writeFile(marker, "", { mode: 0o600 }).catch(() => undefined);
292
+ return true;
293
+ }
294
+ if (!options.fetchEnv)
295
+ return false;
296
+ const fetched = await run(["fetch", "--quiet", "--refetch", "--no-filter", "--no-tags", "--no-write-fetch-head", "origin"], { env: options.fetchEnv, timeoutMs: options.timeouts?.backfillMs ?? BACKFILL_TIMEOUT_MS });
297
+ if (fetched.code !== 0 || fetched.timedOut)
298
+ return false;
299
+ await node_fs_1.promises.writeFile(marker, "", { mode: 0o600 }).catch(() => undefined);
300
+ return true;
301
+ })();
302
+ return fullHistory;
303
+ }
304
+ async function requireFullHistory(what) {
305
+ if (await ensureFullHistory())
306
+ return;
307
+ if (options.signal?.aborted)
308
+ throw new GitHistoryError("This conversation turn was stopped.");
309
+ throw new GitHistoryError(`${what} needs file contents from earlier commits, and this machine could not download them for this checkout. ` +
310
+ "Commit-level questions still work: git_log without `stats`, and git_contributors with `line_counts` false.");
311
+ }
312
+ /** Revision and filter arguments shared by git_log and git_contributors, plus a description of them. */
313
+ async function scopeArgs(args) {
314
+ const head = await resolve(args.ref);
315
+ const exclude = args.exclude_ref ? await resolve(args.exclude_ref) : null;
316
+ const filters = [];
317
+ const described = [];
318
+ if (args.since) {
319
+ filters.push(`--since=${args.since}`);
320
+ described.push(`since ${args.since}`);
321
+ }
322
+ if (args.until) {
323
+ filters.push(`--until=${args.until}`);
324
+ described.push(`until ${args.until}`);
325
+ }
326
+ if (args.author) {
327
+ filters.push(`--author=${args.author}`);
328
+ described.push(`author matching "${args.author}"`);
329
+ }
330
+ if (exclude)
331
+ described.push(`not in ${args.exclude_ref}`);
332
+ if (args.path)
333
+ described.push(`touching ${args.path}`);
334
+ return {
335
+ argv: [...filters, head, ...(exclude ? [`^${exclude}`] : []), "--", ...(args.path ? [args.path] : [])],
336
+ label: `${args.ref} (${head.slice(0, 10)})${described.length ? `, ${described.join(", ")}` : ""}`,
337
+ };
338
+ }
339
+ const NUMSTAT = /^(\d+|-)\t(\d+|-)\t/;
340
+ const DIFF_OPTIONS = ["--no-color", "--no-ext-diff", "--no-textconv"];
341
+ // `--author` and `--grep` are plain substrings, never patterns.
342
+ const MATCH_OPTIONS = ["--fixed-strings", "--regexp-ignore-case"];
343
+ async function log(args) {
344
+ if (args.stats)
345
+ await requireFullHistory("Per-commit line counts");
346
+ const { argv, label } = await scopeArgs(args);
347
+ const commits = [];
348
+ check(await run([
349
+ "log", "--no-decorate", ...DIFF_OPTIONS, ...MATCH_OPTIONS,
350
+ `--max-count=${args.limit}`, `--skip=${args.skip}`,
351
+ `--format=${RECORD}%H${FIELD}%aN${FIELD}%aE${FIELD}%aI${FIELD}%P${FIELD}%s`,
352
+ ...(args.stats ? ["--numstat"] : []),
353
+ ...(args.message ? [`--grep=${args.message}`] : []),
354
+ ...argv,
355
+ ], {
356
+ env, timeoutMs: queryMs,
357
+ onLine: (line) => {
358
+ if (line.startsWith(RECORD)) {
359
+ const [hash = "", name = "", email = "", date = "", parents = "", subject = ""] = line.slice(1).split(FIELD);
360
+ commits.push({ hash, name, email, date, merge: parents.trim().includes(" "), subject, files: 0, added: 0, removed: 0 });
361
+ return;
362
+ }
363
+ const stat = NUMSTAT.exec(line);
364
+ const commit = commits.at(-1);
365
+ if (!stat || !commit)
366
+ return;
367
+ commit.files += 1;
368
+ if (stat[1] !== "-")
369
+ commit.added += Number(stat[1]);
370
+ if (stat[2] !== "-")
371
+ commit.removed += Number(stat[2]);
372
+ },
373
+ }), "The commit listing");
374
+ if (!commits.length)
375
+ return `No commits found in ${label}${args.skip ? ` after skipping ${args.skip}` : ""}.`;
376
+ const lines = commits.map((commit) => {
377
+ const stats = !args.stats ? "" : commit.merge ? " [merge]" : ` [${commit.files} file${commit.files === 1 ? "" : "s"}, +${commit.added} -${commit.removed}]`;
378
+ return `${commit.hash.slice(0, 10)} ${commit.date.slice(0, 10)} ${clip(`${commit.name} <${commit.email}>`, 80)} ${clip(commit.subject, 160)}${stats}`;
379
+ });
380
+ const shown = fitting(lines);
381
+ const more = shown < lines.length || commits.length === args.limit
382
+ ? `\nThere may be more: call again with skip=${args.skip + shown}.`
383
+ : "";
384
+ return `Commits in ${label}, newest first (${shown} shown${args.skip ? `, ${args.skip} skipped` : ""}):\n${lines.slice(0, shown).join("\n")}${more}`;
385
+ }
386
+ async function contributors(args) {
387
+ // Line counts need file contents. Without them the answer is still useful
388
+ // as commit counts, so that is what is returned, with the reason.
389
+ const lineCounts = args.line_counts && await ensureFullHistory();
390
+ if (options.signal?.aborted)
391
+ throw new GitHistoryError("This conversation turn was stopped.");
392
+ const { argv, label } = await scopeArgs(args);
393
+ const authors = new Map();
394
+ let current;
395
+ check(await run([
396
+ "log", ...DIFF_OPTIONS, ...MATCH_OPTIONS,
397
+ `--format=${RECORD}%aN${FIELD}%aE`,
398
+ ...(lineCounts ? ["--numstat"] : []),
399
+ ...(args.include_merges ? [] : ["--no-merges"]),
400
+ ...argv,
401
+ ], {
402
+ env, timeoutMs: options.timeouts?.contributorsMs ?? CONTRIBUTORS_TIMEOUT_MS,
403
+ onLine: (line) => {
404
+ if (line.startsWith(RECORD)) {
405
+ const [name = "", email = ""] = line.slice(1).split(FIELD);
406
+ const key = email.trim().toLowerCase() || `name:${name}`;
407
+ current = authors.get(key);
408
+ // History is read newest first, so the first name seen is the current one.
409
+ if (!current)
410
+ authors.set(key, current = { name, email, commits: 0, added: 0, removed: 0 });
411
+ current.commits += 1;
412
+ return;
413
+ }
414
+ const stat = NUMSTAT.exec(line);
415
+ if (!stat || !current)
416
+ return;
417
+ if (stat[1] !== "-")
418
+ current.added += Number(stat[1]);
419
+ if (stat[2] !== "-")
420
+ current.removed += Number(stat[2]);
421
+ },
422
+ }), "The contributor summary");
423
+ const merges = args.include_merges ? "merge commits included" : "merge commits excluded";
424
+ if (!authors.size)
425
+ return `No commits found in ${label} (${merges}).`;
426
+ const ranked = [...authors.values()].sort((a, b) => lineCounts ? (b.added + b.removed) - (a.added + a.removed) || b.commits - a.commits : b.commits - a.commits);
427
+ const total = ranked.reduce((sum, author) => ({
428
+ commits: sum.commits + author.commits, added: sum.added + author.added, removed: sum.removed + author.removed,
429
+ }), { commits: 0, added: 0, removed: 0 });
430
+ const rows = ranked.slice(0, MAX_CONTRIBUTORS).map((author) => {
431
+ const login = githubLogin(author.email);
432
+ const identity = `${clip(`${author.name} <${author.email}>`, 120)}${login ? ` (GitHub: ${login})` : ""}`;
433
+ return lineCounts
434
+ ? `${String(author.commits).padStart(7)} ${`+${author.added}`.padStart(9)} ${`-${author.removed}`.padStart(9)} ${identity}`
435
+ : `${String(author.commits).padStart(7)} ${identity}`;
436
+ });
437
+ const notes = [
438
+ "Authors are git author identities (name and email, with the repository's .mailmap applied), not GitHub accounts. " +
439
+ "One person can appear under several emails. A GitHub login is shown only when the email is a GitHub noreply address.",
440
+ ...(lineCounts ? ["Binary files count as 0 lines."] : []),
441
+ ...(args.line_counts && !lineCounts
442
+ ? ["Line counts are unavailable: this machine could not download file contents for earlier commits, so only commits are counted."]
443
+ : []),
444
+ ];
445
+ return [
446
+ `Contributors to ${label}, ${merges}, by ${lineCounts ? "lines changed" : "commits"}:`,
447
+ lineCounts ? "commits added removed author" : "commits author",
448
+ ...rows,
449
+ ...(ranked.length > MAX_CONTRIBUTORS ? [`… and ${ranked.length - MAX_CONTRIBUTORS} more authors with fewer changes.`] : []),
450
+ `Total: ${total.commits} commit${total.commits === 1 ? "" : "s"}${lineCounts ? `, +${total.added} -${total.removed}` : ""} by ${ranked.length} author${ranked.length === 1 ? "" : "s"}.`,
451
+ ...notes,
452
+ ].join("\n");
453
+ }
454
+ async function blame(args) {
455
+ await requireFullHistory("Blame");
456
+ const commit = await resolve(args.ref);
457
+ const lines = [];
458
+ const result = check(await run(["blame", "--no-textconv", "--date=short", "--abbrev=10", "-L", `${args.start_line},`, commit, "--", args.path], { env, timeoutMs: queryMs, onLine: (line) => { lines.push(clip(line)); return lines.length < args.max_lines; } }), `Blame of ${args.path}`);
459
+ const shown = fitting(lines);
460
+ const last = args.start_line + shown - 1;
461
+ return [
462
+ `Blame of ${args.path} at ${args.ref} (${commit.slice(0, 10)}), lines ${args.start_line}-${last}:`,
463
+ ...lines.slice(0, shown),
464
+ ...(result.truncated || shown < lines.length ? [`More lines follow: call again with start_line=${last + 1}.`] : []),
465
+ ].join("\n");
466
+ }
467
+ function capped(result) {
468
+ const text = result.stdout.trimEnd().replace(/\n{3,}/g, "\n\n");
469
+ return result.truncated ? `${text}\n[output truncated: narrow it with \`path\`, or leave out \`patch\`]` : text;
470
+ }
471
+ async function show(args) {
472
+ await requireFullHistory("A commit's changes");
473
+ const commit = await resolve(args.commit);
474
+ return capped(check(await run([
475
+ "show", ...DIFF_OPTIONS, "--stat=160",
476
+ ...(args.patch ? ["--patch"] : []),
477
+ "--format=commit %H%nParents: %P%nAuthor: %aN <%aE>%nAuthorDate: %aI%nCommitter: %cN <%cE>%nCommitDate: %cI%n%n%B",
478
+ commit, "--", ...(args.path ? [args.path] : []),
479
+ ], { env, timeoutMs: queryMs }), "Showing the commit"));
480
+ }
481
+ async function diff(args) {
482
+ await requireFullHistory("A diff");
483
+ const head = await resolve(args.head);
484
+ let base = await resolve(args.base);
485
+ let from = `${args.base} (${base.slice(0, 10)})`;
486
+ if (args.from_merge_base) {
487
+ const merged = await run(["merge-base", base, head], { env, timeoutMs: queryMs });
488
+ const found = merged.stdout.trim();
489
+ if (merged.code !== 0 || !/^[0-9a-f]{40,64}$/.test(found)) {
490
+ throw new GitHistoryError(`\`${args.base}\` and \`${args.head}\` share no common commit.`);
491
+ }
492
+ base = found;
493
+ from = `the merge base of ${args.base} and ${args.head} (${base.slice(0, 10)})`;
494
+ }
495
+ const result = check(await run([
496
+ "diff", ...DIFF_OPTIONS, "--stat=160",
497
+ ...(args.patch ? ["--patch"] : []),
498
+ base, head, "--", ...(args.path ? [args.path] : []),
499
+ ], { env, timeoutMs: queryMs }), "The diff");
500
+ const body = capped(result);
501
+ return `Changes from ${from} to ${args.head} (${head.slice(0, 10)})${args.path ? ` in ${args.path}` : ""}:\n${body || "No differences."}`;
502
+ }
503
+ return { log, contributors, blame, show, diff };
504
+ }
505
+ const TOOL_DESCRIPTIONS = {
506
+ git_log: "List commits (hash, date, author, subject), newest first, with optional filters and per-commit line counts. Read-only.",
507
+ git_contributors: "Summarize who changed the repository: commits, lines added and lines removed per author, over the whole history or a date range, path or branch. Use this for per-author or per-account contribution questions. Read-only.",
508
+ git_blame: "Show which commit and author last changed each line of a file. Read-only.",
509
+ git_show: "Show one commit: author, dates, full message and per-file change summary, optionally with the diff text. Read-only.",
510
+ git_diff: "Summarize the changes between two revisions per file, optionally with the diff text. Read-only.",
511
+ };
512
+ /**
513
+ * Serves the git history tools to one conversation turn on a loopback port
514
+ * with an unguessable bearer. Close it when the turn ends.
515
+ */
516
+ async function startGitHistoryServer(options) {
517
+ const token = (0, node_crypto_1.randomBytes)(32).toString("hex");
518
+ const stopping = new AbortController();
519
+ const onAbort = () => stopping.abort();
520
+ options.signal?.addEventListener("abort", onAbort, { once: true });
521
+ if (options.signal?.aborted)
522
+ stopping.abort();
523
+ const history = createGitHistory({ ...options, signal: stopping.signal });
524
+ let closed = false;
525
+ let calls = 0;
526
+ // One git process at a time: a turn cannot fan out into the machine's CPU.
527
+ let queue = Promise.resolve();
528
+ const answer = (work) => {
529
+ const next = queue.then(async () => {
530
+ try {
531
+ if (closed)
532
+ throw new GitHistoryError("This conversation turn has ended.");
533
+ if (++calls > MAX_CALLS)
534
+ throw new GitHistoryError(`This turn reached its limit of ${MAX_CALLS} git history queries. Answer from what you have.`);
535
+ return { content: [{ type: "text", text: await work() }] };
536
+ }
537
+ catch (error) {
538
+ // Only messages written for the agent leave this process.
539
+ const text = error instanceof GitHistoryError ? error.message : "The git history query could not run.";
540
+ return { isError: true, content: [{ type: "text", text }] };
541
+ }
542
+ });
543
+ queue = next;
544
+ return next;
545
+ };
546
+ const http = (0, node_http_1.createServer)(async (req, res) => {
547
+ // Loopback only, with a per-turn bearer. A browser page that can reach the port is refused.
548
+ if (req.headers.origin || req.headers.authorization !== `Bearer ${token}`) {
549
+ res.writeHead(403).end();
550
+ return;
551
+ }
552
+ if (closed) {
553
+ res.writeHead(410).end();
554
+ return;
555
+ }
556
+ if (req.url !== "/mcp" || req.method !== "POST") {
557
+ res.writeHead(405).end();
558
+ return;
559
+ }
560
+ const server = new mcp_js_1.McpServer({ name: "navarch-git", version: "1.0.0" });
561
+ const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
562
+ const annotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
563
+ server.registerTool("git_log", { description: TOOL_DESCRIPTIONS.git_log, inputSchema: exports.gitHistoryShapes.log, annotations }, (args) => answer(() => history.log(args)));
564
+ server.registerTool("git_contributors", { description: TOOL_DESCRIPTIONS.git_contributors, inputSchema: exports.gitHistoryShapes.contributors, annotations }, (args) => answer(() => history.contributors(args)));
565
+ server.registerTool("git_blame", { description: TOOL_DESCRIPTIONS.git_blame, inputSchema: exports.gitHistoryShapes.blame, annotations }, (args) => answer(() => history.blame(args)));
566
+ server.registerTool("git_show", { description: TOOL_DESCRIPTIONS.git_show, inputSchema: exports.gitHistoryShapes.show, annotations }, (args) => answer(() => history.show(args)));
567
+ server.registerTool("git_diff", { description: TOOL_DESCRIPTIONS.git_diff, inputSchema: exports.gitHistoryShapes.diff, annotations }, (args) => answer(() => history.diff(args)));
568
+ res.on("close", () => { void transport.close(); void server.close(); });
569
+ try {
570
+ await server.connect(transport);
571
+ await transport.handleRequest(req, res);
572
+ }
573
+ catch {
574
+ if (!res.headersSent)
575
+ res.writeHead(500).end();
576
+ }
577
+ });
578
+ await new Promise((resolve, reject) => {
579
+ http.once("error", reject);
580
+ http.listen(0, "127.0.0.1", resolve);
581
+ });
582
+ const address = http.address();
583
+ if (!address || typeof address === "string") {
584
+ http.close();
585
+ throw new Error("Git history listener unavailable.");
586
+ }
587
+ const url = `http://127.0.0.1:${address.port}/mcp`;
588
+ return {
589
+ url,
590
+ token,
591
+ config: { type: "http", url, headers: { Authorization: `Bearer ${token}` } },
592
+ async close() {
593
+ if (closed)
594
+ return;
595
+ closed = true;
596
+ options.signal?.removeEventListener("abort", onAbort);
597
+ stopping.abort();
598
+ const stopped = new Promise((resolve) => http.close(() => resolve()));
599
+ http.closeAllConnections();
600
+ await queue.catch(() => undefined);
601
+ await stopped;
602
+ },
603
+ };
604
+ }