Skip to content

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.

30.8 KB
Raw Blame
import { spawn, spawnSync } from "node:child_process";
import os from "node:os";
import path from "node:path";

export interface ExecResult {
  exitCode: number | null;
  signal: NodeJS.Signals | null;
  timedOut: boolean;
  durationMs: number;
  stdout: string;
  stderr: string;
  truncated: boolean;
  error?: string;
}

export interface ExecOptions {
  cwd: string;
  timeoutMs: number;
  maxOutputBytes?: number;
  env?: NodeJS.ProcessEnv;
}

const DEFAULT_MAX_OUTPUT_BYTES = 1024 * 1024; // 1 MiB

const WINDOWS_CODEPAGE_LABELS: Record<number, string> = {
  866: "ibm866",
  874: "windows-874",
  936: "gb18030",
  54936: "gb18030",
  950: "big5",
  932: "shift_jis",
  949: "euc-kr",
  1250: "windows-1250",
  1251: "windows-1251",
  1252: "windows-1252",
  1253: "windows-1253",
  1254: "windows-1254",
  1255: "windows-1255",
  1256: "windows-1256",
  1257: "windows-1257",
  1258: "windows-1258",
  65001: "utf-8",
};

const strictUtf8Decoder = new TextDecoder("utf-8", { fatal: true });
let cachedWindowsFallbackEncoding: string | null | undefined;
const fallbackDecoderCache = new Map<string, TextDecoder>();

export function parseWindowsCodePage(output: string): string | null {
  const match = /\b(\d{3,5})\b/.exec(output);
  if (!match) return null;
  const cp = Number.parseInt(match[1]!, 10);
  const mapped = WINDOWS_CODEPAGE_LABELS[cp];
  return mapped && mapped !== "utf-8" ? mapped : null;
}

function stripTrailingIncompleteUtf8(buf: Buffer): Buffer {
  if (buf.length === 0) return buf;
  let i = buf.length - 1;
  const minIdx = Math.max(0, buf.length - 4);
  while (i >= minIdx && (buf[i]! & 0xc0) === 0x80) {
    i--;
  }
  if (i < minIdx) return buf;
  const lead = buf[i]!;
  if ((lead & 0x80) === 0) return buf;
  let expectedLen = 0;
  if ((lead & 0xe0) === 0xc0) expectedLen = 2;
  else if ((lead & 0xf0) === 0xe0) expectedLen = 3;
  else if ((lead & 0xf8) === 0xf0) expectedLen = 4;
  else return buf;
  return buf.length - i < expectedLen ? buf.subarray(0, i) : buf;
}

function getWindowsSystem32Binary(name: string): { bin: string; cwd: string } {
  const systemRoot = process.env.SystemRoot || process.env.WINDIR || "";
  if (systemRoot) {
    return {
      bin: path.join(systemRoot, "System32", name),
      cwd: systemRoot,
    };
  }
  return { bin: name, cwd: process.cwd() };
}

function getWindowsFallbackEncoding(): string | null {
  if (cachedWindowsFallbackEncoding !== undefined) {
    return cachedWindowsFallbackEncoding;
  }
  try {
    const { bin: chcpBin, cwd } = getWindowsSystem32Binary("chcp.com");
    const res = spawnSync(chcpBin, [], {
      cwd,
      encoding: "latin1",
      timeout: 1500,
      windowsHide: true,
    });
    if (!res.error && res.status === 0) {
      const mapped = parseWindowsCodePage(res.stdout || "");
      if (mapped) {
        cachedWindowsFallbackEncoding = mapped;
        return cachedWindowsFallbackEncoding;
      }
    }
  } catch {
    // Ignore probe errors and fall back to UTF-8
  }
  cachedWindowsFallbackEncoding = null;
  return null;
}

/**
 * Decodes child-process stdout/stderr buffers as UTF-8 first, falling back to
 * the Windows active console codepage (e.g. `gb18030` for CP936) per line when
 * non-UTF-8 bytes are present so valid UTF-8 lines in mixed-encoding output do
 * not turn into mojibake.
 */
export function decodeProcessOutput(
  buf: Buffer,
  truncated = false,
  fallbackEncoding?: string,
): string {
  if (buf.length === 0) return "";
  const candidate = truncated ? stripTrailingIncompleteUtf8(buf) : buf;
  try {
    return strictUtf8Decoder.decode(candidate);
  } catch {
    const label =
      fallbackEncoding ??
      (process.platform === "win32" ? getWindowsFallbackEncoding() : null);
    if (!label || label === "utf-8") {
      return buf.toString("utf8");
    }
    let decoder: TextDecoder;
    try {
      const cached = fallbackDecoderCache.get(label);
      if (cached) {
        decoder = cached;
      } else {
        decoder = new TextDecoder(label);
        fallbackDecoderCache.set(label, decoder);
      }
    } catch {
      return buf.toString("utf8");
    }
    if (buf.indexOf(0x0a) === -1) {
      return decoder.decode(buf);
    }
    const parts: string[] = [];
    let offset = 0;
    while (offset < buf.length) {
      const nl = buf.indexOf(0x0a, offset);
      const end = nl === -1 ? buf.length : nl + 1;
      const line = buf.subarray(offset, end);
      const lineCandidate =
        truncated && end === buf.length ? stripTrailingIncompleteUtf8(line) : line;
      try {
        parts.push(strictUtf8Decoder.decode(lineCandidate));
      } catch {
        parts.push(decoder.decode(line));
      }
      offset = end;
    }
    return parts.join("");
  }
}

/**
 * agy aborts an MCP tool call after 180 s ("timed out after 3m0s") and drops
 * its result. All commands of one tool call share this budget; the remaining
 * 30 s cover Windows process-tree kill grace, host scheduling, and formatting.
 */
export const MCP_CALL_BUDGET_SEC = 150;

function killChildTree(pid: number | undefined, detached: boolean): NodeJS.Timeout | null {
  if (!pid) return null;
  if (process.platform === "win32") {
    const fallbackKill = (): void => {
      try {
        process.kill(pid, "SIGTERM");
      } catch {
        // Already exited
      }
    };
    try {
      const { bin: taskkillBin, cwd } = getWindowsSystem32Binary("taskkill.exe");
      const killer = spawn(taskkillBin, ["/PID", String(pid), "/T", "/F"], {
        cwd,
        stdio: "ignore",
        windowsHide: true,
      });
      killer.on("error", fallbackKill);
      killer.unref();
    } catch {
      fallbackKill();
    }
    return null;
  }

  try {
    if (detached) {
      process.kill(-pid, "SIGTERM");
    } else {
      process.kill(pid, "SIGTERM");
    }
  } catch {
    // Process may already have exited
  }
  const sigkillTimer = setTimeout(() => {
    try {
      if (detached) {
        process.kill(-pid, "SIGKILL");
      } else {
        process.kill(pid, "SIGKILL");
      }
    } catch {
      // Already exited
    }
  }, 400);
  sigkillTimer.unref();
  return sigkillTimer;
}

export function execBinaryAsync(
  bin: string,
  args: string[],
  options: ExecOptions,
): Promise<ExecResult> {
  return spawnAndCollect(bin, args, false, options);
}

export type WindowsPowerShellBin = "pwsh" | "powershell.exe";
export type WindowsShellProbe = (bin: WindowsPowerShellBin) => Promise<boolean>;

const WINDOWS_PS_DOUBLE_QUOTABLE_VAR_RE =
  /(?<![\\`])(?:\$env:[A-Za-z_][A-Za-z0-9_]*|\$(?:LASTEXITCODE|PSVersionTable|PSScriptRoot|PROFILE)\b)/i;
const WINDOWS_PS_UNQUOTED_SYNTAX_RE =
  /(?<![\\`])\$(?:HOME|PWD|null|true|false|_)\b|\$\([^)]|@\(|(?:^|[;\r\n])\s*\$[A-Za-z_][A-Za-z0-9_]*\s*=/im;
const WINDOWS_PS_CMDLET_RE =
  /(?:^|[;|&({\r\n]\s*)(?:Get|Set|New|Remove|Test|Select|Where|ForEach|Sort|Group|Measure|Compare|ConvertTo|ConvertFrom|Export|Import|Invoke|Start|Stop|Restart|Wait|Read|Write|Out|Format|Resolve|Join|Split|Copy|Move|Rename|Clear|Add|Push|Pop|Enable|Disable)-[A-Z][A-Za-z0-9]*\b(?!-)/;
const WINDOWS_CMD_ENV_VAR_RE = /%[A-Za-z_][A-Za-z0-9_()]*%/;
const WINDOWS_CMD_UNQUOTED_SYNTAX_RE =
  /(?:^|[;&|(\r\n])\s*@?(?:set\s+(?:\/[ap]\s+|[A-Za-z_][A-Za-z0-9_]*=)|(?:setlocal|endlocal|rem|call|goto)\b(?!-)|::|(?:cd|chdir)\s+\/d\b|if\s+(?:\/i\s+(?:not\s+)?|(?:not\s+)?(?:errorlevel\s+\d|exist\s|defined\s|cmdextversion\s+\d|[^(\r\n;&|]*==))|for\s+(?:\/[dflr]\b|%%?[A-Za-z]\s+in\b))|(?<![\\`])(?:>>?|<)\s*nul(?=$|[\s;&|)])/i;
const WINDOWS_CMD_QUOTED_SET_AT_POS_RE =
  /^@?set[ \t]+(?:\/[ap][ \t]+)?"[A-Za-z_][A-Za-z0-9_]*=/i;
const WINDOWS_PS51_CHAIN_OPERATOR_RE = /&&|\|\|/;
const EXPLICIT_POWERSHELL_INVOCATION_RE =
  /^\s*(?:["']?)(?:pwsh|powershell)(?:\.exe)?(?:["']?)(?:\s|$)/i;
const PS_NON_INVOCATION_TAIL_RE =
  /^(?:[|;&+}=),*?]|(?:[1-6*])?>|-(?:c|i)?(?:eq|ne|gt|ge|lt|le|like|notlike|match|notmatch|replace|split|join|in|notin|contains|notcontains|is|isnot|as|and|or|xor|shl|shr|band|bor|bxor)\b|-f\b|$)/i;
const PS_UTF8_PREFIX =
  "try { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}; $OutputEncoding = [System.Text.UTF8Encoding]::new($false);";

const WINDOWS_PS_WRAPPER_BIN_RE =
  /^(?:"(?:pwsh|powershell)(?:\.exe)?"|'(?:pwsh|powershell)(?:\.exe)?'|(?:pwsh|powershell)(?:\.exe)?)(?=\s)/i;

const WINDOWS_PS_BENIGN_FLAGS = new Set([
  "-noprofile",
  "-nop",
  "-noninteractive",
  "-noni",
  "-nologo",
  "-nol",
]);

const WINDOWS_UNWRAP_SAFE_BINS = new Set([
  "git",
  "rg",
  "node",
  "npm",
  "npx",
  "pnpm",
  "yarn",
  "bun",
  "deno",
  "python",
  "python3",
  "py",
  "pip",
  "pip3",
  "pytest",
  "uv",
  "ruff",
  "mypy",
  "flake8",
  "black",
  "go",
  "cargo",
  "rustc",
  "rustup",
  "java",
  "javac",
  "mvn",
  "gradle",
  "tsc",
  "tsx",
  "eslint",
  "prettier",
  "vitest",
  "jest",
  "biome",
  "dotnet",
  "cmake",
  "make",
  "ninja",
  "gcc",
  "g++",
  "clang",
  "gh",
  "docker",
  "kubectl",
  "terraform",
  "agy",
]);

const WINDOWS_UNWRAP_FORBIDDEN_META_RE =
  /[|;&><`$(){}@%!^*\r\n'#,?\[\]~\x00-\x08\x0b\x0c\x0e-\x1f\u0085\u00a0\u2013-\u2015\u2018-\u201f\u2028\u2029\u3000]/;

function hasSafeBalancedDoubleQuotes(text: string): boolean {
  if (/\\+"/.test(text)) return false;
  let count = 0;
  for (let i = 0; i < text.length; i++) {
    if (text[i] === '"') count++;
  }
  return count % 2 === 0;
}

/**
 * Unwraps trivial `powershell -Command "..."` / `pwsh -c "..."` wrappers around
 * single allowlisted cross-platform CLI binaries (e.g. `git`, `npm`, `node`,
 * `rg`, `pytest`, `cargo`) so Windows avoids paying PowerShell startup latency.
 *
 * PowerShell cmdlets, aliases (`del`, `rm`, `ls`, `echo`, `curl`, etc.), pipes,
 * redirections, variables, quoting edge cases, or non-benign PowerShell flags
 * are NEVER unwrapped so shell semantics remain 100% faithful.
 */
export function unwrapTrivialWindowsPowerShellCommand(command: string): string {
  const trimmed = command.trim();
  const binMatch = WINDOWS_PS_WRAPPER_BIN_RE.exec(trimmed);
  if (!binMatch) return command;

  let rest = trimmed.slice(binMatch[0].length);
  let sawCommandFlag = false;
  while (true) {
    rest = rest.trimStart();
    if (!rest) return command;
    const tokMatch = /^(\S+)/.exec(rest);
    if (!tokMatch) return command;
    const tok = tokMatch[1]!;
    const lower = tok.toLowerCase();
    rest = rest.slice(tok.length);
    if (lower === "-command" || lower === "-c") {
      if (!/^\s/.test(rest)) return command;
      sawCommandFlag = true;
      break;
    }
    if (!WINDOWS_PS_BENIGN_FLAGS.has(lower)) {
      return command;
    }
  }
  if (!sawCommandFlag) return command;

  const payload = rest.trim();
  if (!payload) return command;

  let inner: string;
  if (payload[0] === '"' || payload[0] === "'") {
    const quote = payload[0];
    if (payload.length < 2 || payload.indexOf(quote, 1) !== payload.length - 1) {
      return command;
    }
    const rawInner = payload.slice(1, -1);
    if (quote === '"' && rawInner.endsWith("\\")) {
      return command;
    }
    inner = rawInner.trim();
    if (quote === "'" && inner.includes('"') && !hasSafeBalancedDoubleQuotes(inner)) {
      return command;
    }
  } else {
    if (/^[-&./\\]/.test(payload)) return command;
    if (payload.includes('"') && !hasSafeBalancedDoubleQuotes(payload)) {
      return command;
    }
    inner = payload;
  }

  if (!inner || WINDOWS_UNWRAP_FORBIDDEN_META_RE.test(inner)) {
    return command;
  }

  const firstTok = /^(\S+)/.exec(inner)?.[1];
  if (!firstTok || !/^[A-Za-z0-9_+.-]+$/.test(firstTok)) {
    return command;
  }
  const baseBin = firstTok.toLowerCase().replace(/\.(?:exe|cmd|bat)$/, "");
  if (!WINDOWS_UNWRAP_SAFE_BINS.has(baseBin)) {
    return command;
  }
  if (needsPowerShellOnWindows(inner)) {
    return command;
  }
  return inner;
}

/**
 * Detects unquoted PowerShell `; ` statement chaining while keeping legitimate
 * `cmd.exe` commands (e.g. `%VAR%`, compact `key=a;b` / `-cp a.jar;b.jar`,
 * `set FOO=...`, `if errorlevel ...`, `2>nul`) and commands mixing `;` with
 * PowerShell 5.1-incompatible chain operators (`&&`, `||`, cmd `&`) on `cmd.exe`.
 */
function hasPowerShellSemicolonChaining(
  command: string,
  withoutSingle: string,
  unquoted: string,
): boolean {
  if (
    WINDOWS_CMD_ENV_VAR_RE.test(withoutSingle) ||
    WINDOWS_CMD_UNQUOTED_SYNTAX_RE.test(unquoted) ||
    WINDOWS_PS51_CHAIN_OPERATOR_RE.test(unquoted)
  ) {
    return false;
  }

  let quote: '"' | "'" | null = null;
  let sawLeadingToken = false;
  let atStatementStart = true;
  let hasSemicolonChain = false;

  for (let i = 0; i < command.length; i++) {
    const ch = command[i]!;
    const next = command[i + 1];
    if (quote === "'") {
      if (ch === "'") {
        if (next === "'") {
          i++;
        } else {
          quote = null;
        }
      }
      continue;
    }
    if (quote === '"') {
      if ((ch === "\\" || ch === "`") && (next === ch || next === '"')) {
        i++;
        continue;
      }
      if (ch === '"') {
        if (next === '"') {
          i++;
        } else {
          quote = null;
        }
      }
      continue;
    }
    if (ch === "'") {
      quote = "'";
      sawLeadingToken = true;
      atStatementStart = false;
      continue;
    }
    if (ch === '"') {
      quote = '"';
      sawLeadingToken = true;
      atStatementStart = false;
      continue;
    }
    if (ch === ";") {
      const prev = i > 0 ? command[i - 1] : "";
      const prevPrev = i > 1 ? command[i - 2] : "";
      const isEscaped =
        prev === "^" ||
        prev === "`" ||
        (prev === "\\" && (i === 1 || /\s/.test(prevPrev!)));
      if (sawLeadingToken && !isEscaped && (next === " " || next === "\t")) {
        let j = i + 1;
        while (j < command.length && (command[j] === " " || command[j] === "\t")) {
          j++;
        }
        if (
          j < command.length &&
          command[j] !== "\r" &&
          command[j] !== "\n" &&
          command[j] !== ";"
        ) {
          hasSemicolonChain = true;
        }
      }
      atStatementStart = true;
      continue;
    }
    if (ch === "&") {
      const prev = i > 0 ? command[i - 1] : "";
      if (prev !== ">" && !atStatementStart) {
        return false;
      }
      if (atStatementStart) {
        sawLeadingToken = true;
        atStatementStart = false;
      }
      continue;
    }
    if (ch === "\r" || ch === "\n") {
      sawLeadingToken = false;
      atStatementStart = true;
      continue;
    }
    if (ch === "|" || ch === "(" || ch === "{") {
      atStatementStart = true;
      continue;
    }
    if (ch === " " || ch === "\t") {
      continue;
    }
    if (atStatementStart && WINDOWS_CMD_QUOTED_SET_AT_POS_RE.test(command.slice(i))) {
      return false;
    }
    sawLeadingToken = true;
    atStatementStart = false;
  }

  return hasSemicolonChain;
}

export interface ExplicitWindowsPowerShellInvocation {
  requestedBin: WindowsPowerShellBin;
  script: string;
}

/**
 * Extracts standalone `powershell`/`pwsh` `-Command`/`-c` invocations that could
 * not be unwrapped to `cmd.exe` (because they use cmdlets, pipelines, `;`, etc.)
 * so Windows can spawn PowerShell directly (`shell: false`) with `-NoLogo`,
 * `-NoProfile`, `-NonInteractive`, and UTF-8 OutputEncoding — avoiding an extra
 * `cmd.exe` wrapper, `$PROFILE` startup errors/latency, and legacy codepage mojibake.
 *
 * Returns `null` whenever non-benign flags (`-ExecutionPolicy`, `-File`,
 * `-EncodedCommand`, `-WorkingDirectory`, etc.), outer `cmd.exe` chains/pipes
 * after the closing quote, inner quote escapes, `%VAR%` expansions, or newlines
 * are present so specialized invocations preserve exact `cmd.exe` semantics.
 */
export function extractExplicitWindowsPowerShellInvocation(
  command: string,
): ExplicitWindowsPowerShellInvocation | null {
  const trimmed = command.trim();
  if (!trimmed || /[\r\n\x00]/.test(trimmed)) return null;
  const binMatch = WINDOWS_PS_WRAPPER_BIN_RE.exec(trimmed);
  if (!binMatch) return null;

  const rawBinToken = binMatch[0].replace(/^["']|["']$/g, "").toLowerCase();
  const requestedBin: WindowsPowerShellBin = rawBinToken.startsWith("pwsh")
    ? "pwsh"
    : "powershell.exe";

  let rest = trimmed.slice(binMatch[0].length);
  let sawCommandFlag = false;
  while (true) {
    rest = rest.trimStart();
    if (!rest) return null;
    const tokMatch = /^(\S+)/.exec(rest);
    if (!tokMatch) return null;
    const tok = tokMatch[1]!;
    const lower = tok.toLowerCase();
    rest = rest.slice(tok.length);
    if (lower === "-command" || lower === "-c") {
      if (!/^\s/.test(rest)) return null;
      sawCommandFlag = true;
      break;
    }
    if (!WINDOWS_PS_BENIGN_FLAGS.has(lower)) {
      return null;
    }
  }
  if (!sawCommandFlag) return null;

  const payload = rest.trim();
  if (!payload || WINDOWS_CMD_ENV_VAR_RE.test(payload)) {
    return null;
  }

  let script: string;
  if (payload[0] === '"' || payload[0] === "'") {
    const quote = payload[0];
    if (payload.length < 2 || payload.indexOf(quote, 1) !== payload.length - 1) {
      return null;
    }
    const rawInner = payload.slice(1, -1);
    if (quote === '"' && rawInner.endsWith("\\")) {
      return null;
    }
    script = rawInner.trim();
  } else {
    if (payload.startsWith("-") || /[&|<>^"`']/.test(payload)) {
      return null;
    }
    script = payload;
  }

  if (!script) return null;
  return { requestedBin, script };
}

function stripQuotedSpans(command: string, stripDoubleQuotes: boolean): string {
  let out = "";
  let quote: '"' | "'" | null = null;
  for (let i = 0; i < command.length; i++) {
    const ch = command[i]!;
    const next = command[i + 1];
    if (quote === "'") {
      if (ch === "'") {
        if (next === "'") {
          i++;
        } else {
          quote = null;
          out += " ";
        }
      }
      continue;
    }
    if (quote === '"') {
      if ((ch === "\\" || ch === "`") && (next === ch || next === '"')) {
        i++;
        if (!stripDoubleQuotes) out += ch + next;
        continue;
      }
      if (ch === '"') {
        if (next === '"') {
          i++;
          if (!stripDoubleQuotes) out += '""';
        } else {
          quote = null;
          out += stripDoubleQuotes ? " " : '"';
        }
        continue;
      }
      if (!stripDoubleQuotes) out += ch;
      continue;
    }
    if (ch === "'") {
      quote = "'";
      out += " ";
      continue;
    }
    if (ch === '"') {
      quote = '"';
      out += stripDoubleQuotes ? " " : '"';
      continue;
    }
    out += ch;
  }
  return out;
}

/**
 * Detects whether a Windows command uses PowerShell syntax (`$env:VAR`, automatic
 * variables, subexpressions, PascalCase `Verb-Noun` cmdlets, or unquoted `; `
 * statement chaining outside cmd.exe / PowerShell 5.1-incompatible constructs)
 * so cross-platform/cmd commands keep fast `cmd.exe` execution without altering
 * quoting behavior.
 */
export function needsPowerShellOnWindows(command: string): boolean {
  if (!command || EXPLICIT_POWERSHELL_INVOCATION_RE.test(command)) {
    return false;
  }
  const withoutSingle = stripQuotedSpans(command, false);
  if (WINDOWS_PS_DOUBLE_QUOTABLE_VAR_RE.test(withoutSingle)) {
    return true;
  }
  const unquoted = stripQuotedSpans(command, true);
  return (
    WINDOWS_PS_UNQUOTED_SYNTAX_RE.test(unquoted) ||
    WINDOWS_PS_CMDLET_RE.test(unquoted) ||
    hasPowerShellSemicolonChaining(command, withoutSingle, unquoted)
  );
}

/**
 * Prepends `&` when a PowerShell command starts with a quoted executable path
 * followed by whitespace + arguments (e.g. `"C:\Program Files\nodejs\node.exe" -v`),
 * while leaving PowerShell string expressions (`"$Env:PATH".Split(';')`,
 * `"$Env:FOO" > out.txt`, `'it''s' + $Env:FOO`, etc.) untouched.
 */
export function formatPowerShellCommand(command: string): string {
  const trimmed = command.trim();
  if (!trimmed || (trimmed[0] !== '"' && trimmed[0] !== "'")) {
    return command;
  }
  const quote = trimmed[0];
  let idx = 1;
  while (idx < trimmed.length) {
    if (quote === '"' && trimmed[idx] === "`" && idx + 1 < trimmed.length) {
      idx += 2;
      continue;
    }
    if (trimmed[idx] === quote) {
      // Both PowerShell '...' (`''`) and "..." (`""`) escape doubled quotes
      if (trimmed[idx + 1] === quote) {
        idx += 2;
        continue;
      }
      const afterQuote = trimmed.slice(idx + 1);
      const rest = afterQuote.replace(/^[ \t]+/, "");
      if (rest.length === afterQuote.length || !rest || /^[\r\n]/.test(rest)) {
        return command;
      }
      if (!PS_NON_INVOCATION_TAIL_RE.test(rest)) {
        return `& ${trimmed}`;
      }
      return command;
    }
    idx++;
  }
  return command;
}

export function buildPowerShellUtf8Command(command: string): string {
  return `${PS_UTF8_PREFIX} ${formatPowerShellCommand(command)}`;
}

let cachedWindowsPowerShell: WindowsPowerShellBin | null | undefined;
let cachedWindowsPowerShellExecPath: string | null = null;
let cachedLegacyPowerShellExecPath: string | null | undefined;
let pendingWindowsPowerShellProbe: Promise<WindowsPowerShellBin | null> | null = null;
let pendingLegacyPowerShellProbe: Promise<string | null> | null = null;

async function probeShellExecPath(bin: WindowsPowerShellBin): Promise<string | null> {
  const { bin: whereBin, cwd } = getWindowsSystem32Binary("where.exe");
  const exeQuery = bin.toLowerCase().endsWith(".exe") ? bin : `${bin}.exe`;
  const whereRes = await execBinaryAsync(whereBin, [exeQuery], {
    cwd,
    timeoutMs: 2000,
    maxOutputBytes: 4096,
  });
  if (!whereRes.error && !whereRes.timedOut) {
    if (whereRes.exitCode !== 0) return null;
    const resolved = whereRes.stdout
      .split(/\r?\n/)
      .map((line) => line.trim())
      .find((line) => /\.exe$/i.test(line));
    return resolved ?? null;
  }
  const res = await execBinaryAsync(
    exeQuery,
    ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", "exit 0"],
    {
      cwd,
      timeoutMs: 3000,
      maxOutputBytes: 4096,
    },
  );
  if (!res.error && !res.timedOut && res.exitCode === 0) {
    return exeQuery;
  }
  return null;
}

async function defaultProbeWindowsShell(bin: WindowsPowerShellBin): Promise<boolean> {
  const resolved = await probeShellExecPath(bin);
  if (bin === "powershell.exe") {
    cachedLegacyPowerShellExecPath = resolved;
  }
  if (resolved) {
    cachedWindowsPowerShellExecPath = resolved;
    return true;
  }
  return false;
}

export async function resolveExplicitWindowsPowerShellExecPath(
  requestedBin: WindowsPowerShellBin,
  probeExecPath: (bin: WindowsPowerShellBin) => Promise<string | null> = probeShellExecPath,
): Promise<string | null> {
  const preferred = await resolveWindowsPowerShell();
  if (requestedBin === "pwsh") {
    return preferred === "pwsh" ? (cachedWindowsPowerShellExecPath ?? "pwsh") : null;
  }
  if (preferred === "powershell.exe" && cachedWindowsPowerShellExecPath) {
    return cachedWindowsPowerShellExecPath;
  }
  if (cachedLegacyPowerShellExecPath !== undefined) {
    return cachedLegacyPowerShellExecPath;
  }
  if (pendingLegacyPowerShellProbe) {
    return pendingLegacyPowerShellProbe;
  }
  pendingLegacyPowerShellProbe = (async () => {
    try {
      const resolved = await probeExecPath("powershell.exe");
      cachedLegacyPowerShellExecPath = resolved;
      return resolved;
    } finally {
      pendingLegacyPowerShellProbe = null;
    }
  })();
  return pendingLegacyPowerShellProbe;
}

/**
 * Resolves the preferred PowerShell executable on Windows (`pwsh` -> `powershell.exe`
 * -> `null`), caching the probe result across calls.
 */
export async function resolveWindowsPowerShell(
  probe: WindowsShellProbe = defaultProbeWindowsShell,
): Promise<WindowsPowerShellBin | null> {
  if (cachedWindowsPowerShell !== undefined) {
    return cachedWindowsPowerShell;
  }
  if (pendingWindowsPowerShellProbe) {
    return pendingWindowsPowerShellProbe;
  }

  pendingWindowsPowerShellProbe = (async () => {
    try {
      cachedWindowsPowerShellExecPath = null;
      if (await probe("pwsh")) {
        cachedWindowsPowerShell = "pwsh";
        return cachedWindowsPowerShell;
      }
      cachedWindowsPowerShellExecPath = null;
      if (await probe("powershell.exe")) {
        cachedWindowsPowerShell = "powershell.exe";
        return cachedWindowsPowerShell;
      }
      cachedWindowsPowerShellExecPath = null;
      cachedWindowsPowerShell = null;
      return null;
    } finally {
      pendingWindowsPowerShellProbe = null;
    }
  })();

  return pendingWindowsPowerShellProbe;
}

export function resetWindowsShellCache(): void {
  cachedWindowsPowerShell = undefined;
  cachedWindowsPowerShellExecPath = null;
  cachedLegacyPowerShellExecPath = undefined;
  pendingWindowsPowerShellProbe = null;
  pendingLegacyPowerShellProbe = null;
}

function hasDefinedEnvKey(
  env: NodeJS.ProcessEnv,
  key: string,
  platform: NodeJS.Platform,
): boolean {
  if (env[key] !== undefined) return true;
  if (platform !== "win32") return false;
  const upper = key.toUpperCase();
  for (const existing of Object.keys(env)) {
    if (existing.toUpperCase() === upper && env[existing] !== undefined) {
      return true;
    }
  }
  return false;
}

export function withNonInteractiveGitEnv(
  baseEnv: NodeJS.ProcessEnv = process.env,
  platform: NodeJS.Platform = process.platform,
): NodeJS.ProcessEnv {
  const result: NodeJS.ProcessEnv = { ...baseEnv };
  if (!hasDefinedEnvKey(baseEnv, "GIT_TERMINAL_PROMPT", platform)) {
    result.GIT_TERMINAL_PROMPT = "0";
  }
  if (!hasDefinedEnvKey(baseEnv, "GCM_INTERACTIVE", platform)) {
    result.GCM_INTERACTIVE = "never";
  }
  return result;
}

export async function runShellCommandAsync(
  command: string,
  options: ExecOptions,
): Promise<ExecResult> {
  const effectiveOptions: ExecOptions = {
    ...options,
    env: withNonInteractiveGitEnv(options.env),
  };
  if (process.platform === "win32") {
    const effectiveCommand = unwrapTrivialWindowsPowerShellCommand(command);
    const explicitPs = extractExplicitWindowsPowerShellInvocation(effectiveCommand);
    if (explicitPs) {
      const explicitExecPath = await resolveExplicitWindowsPowerShellExecPath(
        explicitPs.requestedBin,
      );
      if (explicitExecPath) {
        const utf8Command = buildPowerShellUtf8Command(explicitPs.script);
        return spawnAndCollect(
          explicitExecPath,
          ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", utf8Command],
          false,
          effectiveOptions,
        );
      }
    }
    if (needsPowerShellOnWindows(effectiveCommand)) {
      const psBin = await resolveWindowsPowerShell();
      if (psBin) {
        const utf8Command = buildPowerShellUtf8Command(effectiveCommand);
        return spawnAndCollect(
          cachedWindowsPowerShellExecPath ?? psBin,
          ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", utf8Command],
          false,
          effectiveOptions,
        );
      }
    }
    return spawnAndCollect(effectiveCommand, [], true, effectiveOptions);
  }
  return spawnAndCollect(command, [], true, effectiveOptions);
}

function spawnAndCollect(
  commandOrBin: string,
  args: string[],
  shell: boolean,
  options: ExecOptions,
): Promise<ExecResult> {
  const startMs = Date.now();
  const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
  const detached = process.platform !== "win32";

  return new Promise<ExecResult>((resolve) => {
    let stdoutBytes = 0;
    let stderrBytes = 0;
    let stdoutTruncated = false;
    let stderrTruncated = false;
    let timedOut = false;
    let settled = false;

    const stdoutChunks: Buffer[] = [];
    const stderrChunks: Buffer[] = [];

    let child;
    try {
      child = spawn(commandOrBin, args, {
        cwd: options.cwd,
        shell,
        detached,
        windowsHide: true,
        stdio: ["ignore", "pipe", "pipe"],
        env: options.env ?? process.env,
      });
    } catch (err) {
      resolve({
        exitCode: null,
        signal: null,
        timedOut: false,
        durationMs: Date.now() - startMs,
        stdout: "",
        stderr: "",
        truncated: false,
        error: err instanceof Error ? err.message : String(err),
      });
      return;
    }

    let settleFallbackTimer: NodeJS.Timeout | null = null;
    let sigkillTimer: NodeJS.Timeout | null = null;
    const timer = setTimeout(() => {
      timedOut = true;
      sigkillTimer = killChildTree(child.pid, detached);
      settleFallbackTimer = setTimeout(() => {
        child.stdout?.destroy();
        child.stderr?.destroy();
        finish(null, "SIGKILL");
      }, 1500);
      settleFallbackTimer.unref();
    }, Math.max(100, options.timeoutMs));
    timer.unref();

    const finish = (
      exitCode: number | null,
      signal: NodeJS.Signals | null,
      error?: string,
    ) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      if (sigkillTimer) clearTimeout(sigkillTimer);
      if (settleFallbackTimer) clearTimeout(settleFallbackTimer);
      resolve({
        exitCode,
        signal,
        timedOut,
        durationMs: Date.now() - startMs,
        stdout: decodeProcessOutput(Buffer.concat(stdoutChunks), stdoutTruncated),
        stderr: decodeProcessOutput(Buffer.concat(stderrChunks), stderrTruncated),
        truncated: stdoutTruncated || stderrTruncated,
        error,
      });
    };

    child.stdout?.on("data", (chunk: Buffer) => {
      if (stdoutBytes >= maxOutputBytes) {
        stdoutTruncated = true;
        return;
      }
      const remaining = maxOutputBytes - stdoutBytes;
      if (chunk.length > remaining) {
        stdoutChunks.push(chunk.subarray(0, remaining));
        stdoutBytes += remaining;
        stdoutTruncated = true;
      } else {
        stdoutChunks.push(chunk);
        stdoutBytes += chunk.length;
      }
    });

    child.stderr?.on("data", (chunk: Buffer) => {
      if (stderrBytes >= maxOutputBytes) {
        stderrTruncated = true;
        return;
      }
      const remaining = maxOutputBytes - stderrBytes;
      if (chunk.length > remaining) {
        stderrChunks.push(chunk.subarray(0, remaining));
        stderrBytes += remaining;
        stderrTruncated = true;
      } else {
        stderrChunks.push(chunk);
        stderrBytes += chunk.length;
      }
    });

    child.on("error", (err) => {
      finish(null, null, err.message);
    });

    child.on("close", (code, signal) => {
      finish(code, signal);
    });
  });
}

let cachedRgAvailable: boolean | null = null;
let pendingRgProbe: Promise<boolean> | null = null;

export async function isRipgrepAvailable(): Promise<boolean> {
  if (cachedRgAvailable !== null) return cachedRgAvailable;
  if (pendingRgProbe) return pendingRgProbe;

  let probe: Promise<boolean> | null = null;
  probe = (async () => {
    try {
      const res = await execBinaryAsync("rg", ["--version"], {
        cwd: os.tmpdir(),
        timeoutMs: 2000,
        maxOutputBytes: 4096,
      });
      const available = !res.error && !res.timedOut && res.exitCode === 0;
      if (!res.timedOut && pendingRgProbe === probe) {
        cachedRgAvailable = available;
      }
      return available;
    } finally {
      if (pendingRgProbe === probe) {
        pendingRgProbe = null;
      }
    }
  })();

  pendingRgProbe = probe;
  return probe;
}

export function resetRipgrepCache(): void {
  cachedRgAvailable = null;
  pendingRgProbe = null;
}