Non-invasive MCP accelerator plugin for Google Antigravity (CLI/Desktop/IDE): cuts LLM turns (-34%), token quota (-31%), and upload traffic (-40%) without affecting native UI or diffs.
TypeScript ai-agentai-codingantigravityantigravity-cliantigravity-ideantigravity-pluginscoding-agentcontext-optimizationdeveloper-productivitydeveloper-toolsgeminigoogle-antigravitylatency-optimizationmcpmcp-pluginmcp-servermodel-context-protocolperformanceplugintoken-optimization
import { promises as fs, type Dirent } from "node:fs";
import os from "node:os";
import path from "node:path";
export const DEFAULT_IGNORE_DIRS = new Set([
".git",
".hg",
".svn",
"node_modules",
"dist",
"build",
"out",
"target",
".next",
".nuxt",
".svelte-kit",
".cache",
".turbo",
"coverage",
"__pycache__",
".venv",
"venv",
".tox",
".pytest_cache",
".mypy_cache",
".ruff_cache",
".gradle",
".idea",
"vendor",
]);
export function expandHome(inputPath: string): string {
if (inputPath === "~") return os.homedir();
if (inputPath.startsWith("~/") || inputPath.startsWith("~\\")) {
return path.join(os.homedir(), inputPath.slice(2));
}
return inputPath;
}
export function resolvePath(inputPath: string, baseDir?: string): string {
const expanded = expandHome(inputPath.trim());
const root = baseDir ? path.resolve(expandHome(baseDir)) : process.cwd();
return path.resolve(root, expanded);
}
export function toPosixPath(p: string): string {
return p.split(path.sep).join("/");
}
export function isLikelyBinary(buf: Buffer): boolean {
const limit = Math.min(buf.length, 8192);
for (let i = 0; i < limit; i++) {
if (buf[i] === 0) return true;
}
return false;
}
export interface TextFileContent {
content: string;
/** UTF-8 BOM-stripped text (same coordinate space as `content`) retaining original line endings. */
rawContent: string;
eol: "\r\n" | "\n";
mixedEol: boolean;
hasBom: boolean;
size: number;
mode: number;
rawBuffer: Buffer;
}
export function hasUtf8Bom(buf: Buffer): boolean {
return buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf;
}
export function detectUtf16Bom(buf: Buffer): "UTF-16 LE" | "UTF-16 BE" | null {
if (buf.length < 2) return null;
if (buf[0] === 0xff && buf[1] === 0xfe) {
// Distinguish UTF-32 LE BOM (FF FE 00 00) from UTF-16 LE (FF FE ...)
if (buf.length >= 4 && buf[2] === 0x00 && buf[3] === 0x00) {
return null;
}
return "UTF-16 LE";
}
if (buf[0] === 0xfe && buf[1] === 0xff) {
return "UTF-16 BE";
}
return null;
}
const LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
/** Decodes a UTF-16 payload (BOM already removed) without ICU; rejects malformed or binary data. */
function decodeUtf16Payload(
payload: Buffer,
bom: "UTF-16 LE" | "UTF-16 BE",
filePath: string,
): string {
if (payload.length % 2 !== 0) {
throw new Error(`Malformed UTF-16 file cannot be read as text: ${filePath} [${bom}]`);
}
const le = bom === "UTF-16 LE" ? payload : Buffer.from(payload).swap16();
const text = le.toString("utf16le");
if (text.includes("\0")) {
throw new Error(`Binary file cannot be read as text: ${filePath}`);
}
if (LONE_SURROGATE_RE.test(text)) {
throw new Error(`Malformed UTF-16 file cannot be read as text: ${filePath} [${bom}]`);
}
return text;
}
export async function readTextFile(
filePath: string,
maxBytes = 10 * 1024 * 1024,
options: { decodeUtf16?: boolean } = {},
): Promise<TextFileContent> {
const stat = await fs.stat(filePath);
if (!stat.isFile()) {
throw new Error(`Not a regular file: ${filePath}`);
}
if (stat.size > maxBytes) {
throw new Error(
`File exceeds maximum size (${stat.size} bytes > ${maxBytes} bytes): ${filePath}`,
);
}
const buf = await fs.readFile(filePath);
const utf16Bom = detectUtf16Bom(buf);
if (utf16Bom && !options.decodeUtf16) {
throw new Error(
`UTF-16 encoded file is not supported (convert to UTF-8 first): ${filePath} [${utf16Bom}]`,
);
}
if (!utf16Bom && isLikelyBinary(buf)) {
throw new Error(`Binary file cannot be read as text: ${filePath}`);
}
const hasBom = !utf16Bom && hasUtf8Bom(buf);
// Read-only callers may decode BOM-marked UTF-16 (e.g. Windows PowerShell 5.1 `>` output).
const rawContent = utf16Bom
? decodeUtf16Payload(buf.subarray(2), utf16Bom, filePath)
: (hasBom ? buf.subarray(3) : buf).toString("utf8");
let crlfCount = 0;
let lfOnlyCount = 0;
for (let i = 0; i < rawContent.length; i++) {
if (rawContent[i] === "\n") {
if (i > 0 && rawContent[i - 1] === "\r") crlfCount++;
else lfOnlyCount++;
}
}
const eol: "\r\n" | "\n" = crlfCount > lfOnlyCount ? "\r\n" : "\n";
const mixedEol = crlfCount > 0 && lfOnlyCount > 0;
return {
content: rawContent,
rawContent,
eol,
mixedEol,
hasBom,
size: stat.size,
mode: stat.mode & 0o7777,
rawBuffer: buf,
};
}
/**
* Convert a glob pattern (supporting **, *, ?, {a,b}, [abc]) to a RegExp
* matching POSIX-normalized relative paths.
*/
export function globToRegExp(pattern: string): RegExp {
const normalized = pattern
.trim()
.replace(/\\/g, "/")
.replace(/^\.\//, "")
.replace(/\*{3,}/g, "**")
.replace(/(?:\*\*\/)+/g, "**/");
const re = `^${compileGlobBody(normalized)}$`;
try {
return new RegExp(re);
} catch (err) {
throw new Error(
`Invalid glob pattern '${pattern}': ${err instanceof Error ? err.message : String(err)}`,
);
}
}
function compileGlobBody(normalized: string): string {
let re = "";
let i = 0;
while (i < normalized.length) {
const ch = normalized[i]!;
if (ch === "*") {
if (normalized[i + 1] === "*") {
if (normalized[i + 2] === "/") {
re += "(?:.*/)?";
i += 3;
} else {
re += ".*";
i += 2;
}
} else {
re += "[^/]*";
i += 1;
}
} else if (ch === "?") {
re += "[^/]";
i += 1;
} else if (ch === "[") {
const close = findClosingBracket(normalized, i);
if (close === -1) {
re += "\\[";
i += 1;
} else {
let inner = normalized.slice(i + 1, close);
const negated = inner.startsWith("!") || inner.startsWith("^");
if (negated) inner = inner.slice(1);
inner = inner.replace(/\\/g, "\\\\").replace(/\]/g, "\\]");
re += negated ? `(?!/)[${"^"}${inner}]` : `[${inner}]`;
i = close + 1;
}
} else if (ch === "{") {
const close = findMatchingBrace(normalized, i);
if (close === -1) {
re += "\\{";
i += 1;
} else {
const parts = splitBraceAlternatives(normalized.slice(i + 1, close));
const sub = parts
.map((part) => compileGlobBody(part.replace(/\*{3,}/g, "**").replace(/(?:\*\*\/)+/g, "**/")))
.join("|");
re += `(?:${sub})`;
i = close + 1;
}
} else if (".+^$()|\\".includes(ch)) {
re += "\\" + ch;
i += 1;
} else {
re += ch;
i += 1;
}
}
return re;
}
function findClosingBracket(str: string, openIdx: number): number {
let i = openIdx + 1;
if (i < str.length && (str[i] === "!" || str[i] === "^")) i++;
if (i < str.length && str[i] === "]") i++; // leading `]` is a literal member of the class
for (; i < str.length; i++) {
if (str[i] === "]") return i;
}
return -1;
}
function findMatchingBrace(str: string, openIdx: number): number {
let depth = 0;
for (let i = openIdx; i < str.length; i++) {
if (str[i] === "[") {
const close = findClosingBracket(str, i);
if (close !== -1) {
i = close;
continue;
}
}
if (str[i] === "{") depth++;
else if (str[i] === "}") {
depth--;
if (depth === 0) return i;
}
}
return -1;
}
function splitBraceAlternatives(inner: string): string[] {
const parts: string[] = [];
let depth = 0;
let start = 0;
for (let i = 0; i < inner.length; i++) {
const ch = inner[i];
if (ch === "[") {
const close = findClosingBracket(inner, i);
if (close !== -1) {
i = close;
continue;
}
}
if (ch === "{") depth++;
else if (ch === "}") depth--;
else if (ch === "," && depth === 0) {
parts.push(inner.slice(start, i));
start = i + 1;
}
}
parts.push(inner.slice(start));
return parts;
}
export interface WalkOptions {
maxFiles?: number;
maxDepth?: number;
includeHidden?: boolean;
ignoreDirs?: Set<string>;
fileFilter?: (relPosixPath: string) => boolean;
/** Optional wall-clock soft budget in ms; stops cleanly and marks timedOut + truncated. */
timeoutMs?: number;
/** Optional cap on visited directories (readdir calls) to prevent runaway walks when few files match. */
maxDirs?: number;
}
export interface WalkResult {
files: string[];
truncated: boolean;
timedOut?: boolean;
dirsTruncated?: boolean;
}
export async function walkFiles(
rootDir: string,
options: WalkOptions = {},
): Promise<WalkResult> {
const maxFiles = Math.max(0, Math.trunc(options.maxFiles ?? 5000));
const maxDepth = options.maxDepth ?? 32;
const includeHidden = options.includeHidden ?? false;
const ignoreDirs = options.ignoreDirs ?? DEFAULT_IGNORE_DIRS;
const fileFilter = options.fileFilter;
const timeoutMs =
options.timeoutMs !== undefined &&
Number.isFinite(options.timeoutMs) &&
options.timeoutMs > 0
? Math.max(1, Math.trunc(options.timeoutMs))
: null;
const deadline = timeoutMs !== null ? Date.now() + timeoutMs : null;
const maxDirs =
options.maxDirs !== undefined &&
Number.isFinite(options.maxDirs) &&
options.maxDirs > 0
? Math.max(1, Math.trunc(options.maxDirs))
: null;
const files: string[] = [];
let truncated = false;
let filesTruncated = false;
let timedOut = false;
let dirsTruncated = false;
let visitedDirs = 0;
// Global concurrency semaphore caps simultaneous fs.readdir calls across all
// recursion depths to prevent EMFILE FD exhaustion on nested workspaces.
const MAX_CONCURRENT_READDIRS = 16;
const DEFAULT_BATCH_SIZE = 8;
let activeReaddirs = 0;
const waitQueue: Array<() => void> = [];
const drainWaiters = (): void => {
while (waitQueue.length > 0) {
waitQueue.shift()!();
}
};
const markTruncated = (): void => {
if (truncated) return;
truncated = true;
drainWaiters();
};
const canStartRead = (): boolean => {
if (truncated) return false;
if (deadline !== null && Date.now() >= deadline) {
timedOut = true;
markTruncated();
return false;
}
return true;
};
const stoppedStatus = (): "dirs_limit" | "timed_out" | "stopped" => {
if (filesTruncated) return "stopped";
if (timedOut) return "timed_out";
if (dirsTruncated) return "dirs_limit";
return "stopped";
};
// Taper sibling prefetch width as remaining maxDirs budget shrinks so later
// siblings do not consume directory quota ahead of earlier siblings' subtrees
// while keeping full 8-way concurrency when budget is plentiful.
const computeBatchSize = (): number => {
if (maxDirs === null) return DEFAULT_BATCH_SIZE;
const remaining = maxDirs - visitedDirs - waitQueue.length;
return Math.min(
DEFAULT_BATCH_SIZE,
Math.max(1, Math.floor(remaining / DEFAULT_BATCH_SIZE)),
);
};
const timeoutTimer =
timeoutMs !== null
? setTimeout(() => {
if (!truncated) {
timedOut = true;
markTruncated();
}
}, timeoutMs)
: null;
timeoutTimer?.unref();
type ReadDirOutcome =
| { status: "scanned"; entries: Dirent[] }
| { status: "error" }
| { status: "dirs_limit" }
| { status: "timed_out" }
| { status: "stopped" };
const readDirBounded = async (dir: string): Promise<ReadDirOutcome> => {
if (!canStartRead()) return { status: stoppedStatus() };
if (maxDirs !== null && visitedDirs >= maxDirs) {
return { status: "dirs_limit" };
}
while (activeReaddirs >= MAX_CONCURRENT_READDIRS) {
await new Promise<void>((resolve) => waitQueue.push(resolve));
if (!canStartRead()) return { status: stoppedStatus() };
if (maxDirs !== null && visitedDirs >= maxDirs) {
return { status: "dirs_limit" };
}
}
if (!canStartRead()) return { status: stoppedStatus() };
if (maxDirs !== null && visitedDirs >= maxDirs) {
return { status: "dirs_limit" };
}
visitedDirs++;
if (maxDirs !== null && visitedDirs >= maxDirs) {
drainWaiters();
}
activeReaddirs++;
try {
const entries = await fs.readdir(dir, { withFileTypes: true });
return { status: "scanned", entries };
} catch {
return { status: "error" };
} finally {
activeReaddirs--;
if (truncated || (maxDirs !== null && visitedDirs >= maxDirs)) {
drainWaiters();
} else {
const next = waitQueue.shift();
if (next) next();
}
}
};
interface DirScanResult {
status: "scanned" | "error" | "dirs_limit" | "timed_out" | "stopped";
localFiles: string[];
subdirs: Array<{ abs: string; rel: string }>;
}
const scanDir = async (dir: string, relDir: string): Promise<DirScanResult> => {
const readRes = await readDirBounded(dir);
if (readRes.status !== "scanned") {
return { status: readRes.status, localFiles: [], subdirs: [] };
}
if (filesTruncated) {
return { status: "stopped", localFiles: [], subdirs: [] };
}
const entries = readRes.entries;
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
const localFiles: string[] = [];
const subdirs: Array<{ abs: string; rel: string }> = [];
for (const entry of entries) {
const name = entry.name;
if (!includeHidden && name.startsWith(".")) {
if (!(entry.isDirectory() && name === ".agents")) {
continue;
}
}
const relPosix = relDir ? `${relDir}/${name}` : name;
if (entry.isDirectory()) {
if (ignoreDirs.has(name)) continue;
subdirs.push({ abs: path.join(dir, name), rel: relPosix });
} else if (entry.isFile()) {
if (fileFilter && !fileFilter(relPosix)) continue;
localFiles.push(relPosix);
}
}
return { status: "scanned", localFiles, subdirs };
};
// Prefetch sibling directories concurrently in bounded batches while emitting
// matched files in deterministic lexicographical DFS order and only marking
// `truncated` when a (maxFiles + 1)-th matching file or scan budget is hit.
// Returns true iff this directory and its entire reachable subtree completed
// without truncation, so callers preserve already-scanned sibling results up
// to the exact DFS truncation boundary without introducing DFS holes.
async function visit(
dir: string,
relDir: string,
depth: number,
prefetched?: Promise<DirScanResult>,
): Promise<boolean> {
if (depth > maxDepth) return true;
if (!prefetched) {
if (!canStartRead()) return false;
if (maxDirs !== null && visitedDirs >= maxDirs) {
dirsTruncated = true;
markTruncated();
return false;
}
}
const res = await (prefetched ?? scanDir(dir, relDir));
if (res.status === "dirs_limit") {
dirsTruncated = true;
markTruncated();
return false;
}
if (res.status === "timed_out") {
timedOut = true;
markTruncated();
return false;
}
if (res.status === "stopped") {
return false;
}
if (res.status === "error") {
return true;
}
for (const relPosix of res.localFiles) {
if (files.length >= maxFiles) {
filesTruncated = true;
markTruncated();
return false;
}
files.push(relPosix);
}
if (depth >= maxDepth || res.subdirs.length === 0) return true;
for (let i = 0; i < res.subdirs.length; ) {
if (!canStartRead()) return false;
if (maxDirs !== null && visitedDirs >= maxDirs) {
dirsTruncated = true;
markTruncated();
return false;
}
const batchSize = computeBatchSize();
const slice = res.subdirs.slice(i, i + batchSize);
i += slice.length;
const prefetches = slice.map((sub) => scanDir(sub.abs, sub.rel));
let completedInSlice = 0;
try {
for (let j = 0; j < slice.length; j++) {
if (filesTruncated) return false;
const completed = await visit(
slice[j]!.abs,
slice[j]!.rel,
depth + 1,
prefetches[j],
);
if (!completed) return false;
completedInSlice = j + 1;
}
} catch (err) {
markTruncated();
throw err;
} finally {
// Ensure no sibling prefetches remain in flight after early truncation or error
// (avoids dangling directory handles / EBUSY on Windows temp cleanup).
if (completedInSlice < prefetches.length) {
await Promise.allSettled(prefetches);
}
}
}
return true;
}
try {
await visit(rootDir, "", 0);
} finally {
if (timeoutTimer) clearTimeout(timeoutTimer);
}
return {
files,
truncated,
...(timedOut ? { timedOut: true } : {}),
...(dirsTruncated ? { dirsTruncated: true } : {}),
};
}