Skip to content

armgit / pibot

Public Imported from GitHub
0

Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.

perf(desktop): Windows ships MinGit as its verified zip, unpacked on first need

leen.zhou737ede8eaadc
diff --git a/THIRD_PARTY_NOTICES b/THIRD_PARTY_NOTICES
index 0075d55..5adafba 100644
--- a/THIRD_PARTY_NOTICES
+++ b/THIRD_PARTY_NOTICES
@@ -62,10 +62,11 @@ Bundled binaries and assets
apps/desktop/resources/licenses/
8. MinGit (Git for Windows) 2.56.1 (bundled unmodified in the Windows desktop
- app only, as resources/bin/git/)
+ app only, as the release zip in resources/bin/mingit/)
Source: https://github.com/git-for-windows/git/releases/tag/v2.56.1.windows.1
License: GNU General Public License, version 2 (Git), plus the licenses of
- its bundled components; full texts ship in resources/bin/git/LICENSE.txt.
+ its bundled components; full texts ship in resources/bin/mingit/LICENSE.txt
+ and inside the zip.
Pi Bot runs it as a separate program; the GPL does not apply to the rest of
Pi Bot. Details and corresponding source: apps/desktop/resources/licenses/mingit.md
diff --git a/apps/desktop/resources/licenses/mingit.md b/apps/desktop/resources/licenses/mingit.md
index 209befb..7c29a23 100644
--- a/apps/desktop/resources/licenses/mingit.md
+++ b/apps/desktop/resources/licenses/mingit.md
@@ -2,19 +2,21 @@
The Windows installer of Pi Bot bundles MinGit, the minimal distribution of Git for Windows, so
that Git is available on computers that have none. Pi Bot runs it as a separate program and uses
-it only when no Git is installed on the computer.
+it only when no Git is installed on the computer. It ships as the official release zip; the first
+time Git is needed, Pi Bot checks the zip's SHA-256 and unpacks it, unchanged, into
+`%LOCALAPPDATA%\Pi Bot\runtimes\mingit\`.
| Files | Version | License | Source |
|---|---|---|---|
-| `resources/bin/git/` (MinGit-2.56.1-64-bit.zip on x64, MinGit-2.56.1-arm64.zip on arm64) | Git for Windows 2.56.1 (`v2.56.1.windows.1`) | GNU General Public License, version 2 (Git), plus the licenses of the bundled components | https://github.com/git-for-windows/git/releases/tag/v2.56.1.windows.1 |
+| `resources/bin/mingit/` (MinGit-2.56.1-64-bit.zip on x64, MinGit-2.56.1-arm64.zip on arm64) | Git for Windows 2.56.1 (`v2.56.1.windows.1`) | GNU General Public License, version 2 (Git), plus the licenses of the bundled components | https://github.com/git-for-windows/git/releases/tag/v2.56.1.windows.1 |
MinGit is distributed unmodified, exactly as published in the release above (SHA-256
`4a92850b6e917da4fd010669b614b55dccf5b0ec333a534cc4be4700dfefdafd` for x64,
`96571e442e90523a90e5fd8661b4c4e43bc192910f3c6db938816e6955b4cc8c` for arm64).
The complete license texts, including the GNU General Public License version 2 and the licenses
-of every component MinGit contains, are in `resources/bin/git/LICENSE.txt` of the installed
-application.
+of every component MinGit contains, are in `resources/bin/mingit/LICENSE.txt` of the installed
+application (and `LICENSE.txt` inside the zip and the unpacked copy).
Corresponding source code:
diff --git a/apps/desktop/scripts/package/prepare-mingit.d.mts b/apps/desktop/scripts/package/prepare-mingit.d.mts
new file mode 100644
index 0000000..fd82b9c
--- /dev/null
+++ b/apps/desktop/scripts/package/prepare-mingit.d.mts
@@ -0,0 +1,8 @@
+export declare const MINGIT_VERSION: string;
+/** Archive name and pinned SHA-256 per Windows architecture. */
+export declare const MINGIT_DIGESTS: Readonly<Record<string, readonly [string, string]>>;
+export declare function prepareMinGit(
+ desktop: string,
+ arch: string,
+ binDirectory: string,
+): Promise<string>;
diff --git a/apps/desktop/scripts/package/prepare-mingit.mjs b/apps/desktop/scripts/package/prepare-mingit.mjs
index b72745d..1dce39f 100644
--- a/apps/desktop/scripts/package/prepare-mingit.mjs
+++ b/apps/desktop/scripts/package/prepare-mingit.mjs
@@ -2,19 +2,24 @@
// and group parallel steps, the changes panel, commits and review all need it. System Git still
// wins at runtime (packages/execution/src/git/git-program.ts lists the bundled copy last).
//
+// It ships as the release zip itself, not unpacked: the unpacked tree is ~380 files, ~190 of them
+// executables and DLLs (89 MB), which the installer had to decompress and Windows Defender had to
+// scan one by one; installs went from 47 s to 108-143 s. Pi Bot unpacks the zip once, on first
+// need, into its own cache (packages/execution/src/git/bundled-git.ts), after checking the digest
+// this script writes into mingit.json.
+//
// Official Git for Windows release, exact version, SHA-256 pinned here (the release notes' table
// and GitHub's asset digest agree) and checked before anything is unpacked. Shipped unmodified
// under GPLv2; the source link is in apps/desktop/resources/licenses/mingit.md.
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
-import { access, cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
+import { chmod, copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
export const MINGIT_VERSION = "2.56.1";
const RELEASE = "v2.56.1.windows.1";
-const DIGESTS = {
+export const MINGIT_DIGESTS = {
x64: [
"MinGit-2.56.1-64-bit.zip",
"4a92850b6e917da4fd010669b614b55dccf5b0ec333a534cc4be4700dfefdafd",
@@ -29,10 +34,10 @@ const run = promisify(execFile);
/**
* Downloads (or reuses from .cache) and verifies MinGit for one Windows architecture, then
- * replaces `<binDirectory>/git` with the unpacked tree; `git/cmd/git.exe` is what runtime looks for.
+ * replaces `<binDirectory>/mingit` with the verified zip, its manifest and the licence text.
*/
export async function prepareMinGit(desktop, arch, binDirectory) {
- const entry = DIGESTS[arch];
+ const entry = MINGIT_DIGESTS[arch];
if (!entry) throw new Error(`No pinned MinGit for win-${arch}`);
const [name, expected] = entry;
const cache = join(desktop, "../../.cache/pibot-mingit", RELEASE);
@@ -61,29 +66,32 @@ export async function prepareMinGit(desktop, arch, binDirectory) {
throw new Error(`MinGit checksum mismatch for win-${arch}`);
}
if (downloaded) await writeFile(archive, bytes, { mode: 0o600 });
- const temporary = await mkdtemp(join(tmpdir(), "pibot-mingit-"));
- try {
- await run("unzip", ["-q", archive, "-d", temporary]);
- // The launcher and the licence must exist before the previous copy is replaced.
- await Promise.all([
- access(join(temporary, "cmd", "git.exe")),
- access(join(temporary, "LICENSE.txt")),
- ]);
- const target = join(binDirectory, "git");
- await rm(target, { recursive: true, force: true });
- await mkdir(binDirectory, { recursive: true });
- await cp(temporary, target, { recursive: true });
- console.info(
- JSON.stringify({
- event: "package.mingit",
- version: MINGIT_VERSION,
- release: RELEASE,
- target: `win-${arch}`,
- sha256: actual,
- }),
- );
- return join(target, "cmd", "git.exe");
- } finally {
- await rm(temporary, { recursive: true, force: true });
- }
+ // The launcher must be in the archive; the licence travels beside it as well as inside it.
+ const { stdout: listing } = await run("unzip", ["-Z1", archive], { maxBuffer: 4 * 1024 * 1024 });
+ const names = new Set(listing.split(/\r?\n/));
+ if (!names.has("cmd/git.exe") || !names.has("LICENSE.txt"))
+ throw new Error(`MinGit archive for win-${arch} lacks cmd/git.exe or LICENSE.txt`);
+ const { stdout: licence } = await run("unzip", ["-p", archive, "LICENSE.txt"], {
+ encoding: "buffer",
+ maxBuffer: 16 * 1024 * 1024,
+ });
+ // Builds before the zip layout left the unpacked tree in the same output folder.
+ await rm(join(binDirectory, "git"), { recursive: true, force: true });
+ const target = join(binDirectory, "mingit");
+ await rm(target, { recursive: true, force: true });
+ await mkdir(target, { recursive: true });
+ await copyFile(archive, join(target, name));
+ // The cache copy is private to the builder; the shipped one is an ordinary resource file.
+ await chmod(join(target, name), 0o644);
+ await writeFile(join(target, "LICENSE.txt"), licence);
+ const manifest = {
+ release: RELEASE,
+ version: MINGIT_VERSION,
+ archive: name,
+ sha256: actual,
+ size: bytes.byteLength,
+ };
+ await writeFile(join(target, "mingit.json"), `${JSON.stringify(manifest, null, 2)}\n`);
+ console.info(JSON.stringify({ event: "package.mingit", ...manifest, target: `win-${arch}` }));
+ return join(target, name);
}
diff --git a/apps/desktop/scripts/package/verify-target-package.ts b/apps/desktop/scripts/package/verify-target-package.ts
index 74fce1a..d26ab69 100644
--- a/apps/desktop/scripts/package/verify-target-package.ts
+++ b/apps/desktop/scripts/package/verify-target-package.ts
@@ -1,7 +1,10 @@
import assert from "node:assert/strict";
-import { existsSync, readFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
import { join } from "node:path";
import { extractFile, listPackage } from "@electron/asar";
+import { unzipSync } from "fflate";
import { appRun, linuxLauncher } from "./linux-launcher.mjs";
import { packagedElectron, verifyPackageFuses } from "./package-fuses.ts";
import {
@@ -10,6 +13,7 @@ import {
type PackageArch,
type PackageMode,
} from "./package-options.ts";
+import { MINGIT_DIGESTS } from "./prepare-mingit.mjs";
import { verifyChildNode } from "./verify-child-node.ts";
import { verifyNativePrebuilds } from "./verify-native-prebuilds.ts";
import { verifyCodeMapGrammars, verifySemanticLibraries } from "./verify-semantic-libraries.ts";
@@ -65,9 +69,7 @@ export async function verifyTargetPackage(
verifyTargetBinary(join(resources, "bin", win ? "rg.exe" : "rg"), platform, arch);
verifyChildNode(resources, platform, arch);
if (win) {
- // Bundled MinGit: runtime resolves bin/git/cmd/git.exe after any installed Git.
- verifyTargetBinary(join(resources, "bin", "git", "cmd", "git.exe"), platform, arch);
- assert(existsSync(join(resources, "bin", "git", "LICENSE.txt")), "Missing MinGit licence");
+ verifyBundledMinGit(resources, arch);
assert(existsSync(join(resources, "licenses", "mingit.md")), "Missing MinGit notice");
}
verifyCodeMapGrammars(join(resources, "wasm", "codemap"));
@@ -97,3 +99,35 @@ export async function verifyTargetPackage(
`Verified packaged entries and resources: ${platform}-${arch}. Target OS runtime acceptance is still required.`,
);
}
+
+/**
+ * Windows ships MinGit as its pinned release zip (bin/mingit), unpacked by the app on first need
+ * (packages/execution/src/git/bundled-git.ts). The manifest must name the pinned digest, the zip
+ * must match it, and its git.exe must be the target CPU; the licence ships beside and inside it.
+ */
+function verifyBundledMinGit(resources: string, arch: PackageArch) {
+ const folder = join(resources, "bin", "mingit");
+ assert(!existsSync(join(resources, "bin", "git")), "Unpacked MinGit tree must not ship");
+ const manifest = JSON.parse(readFileSync(join(folder, "mingit.json"), "utf8"));
+ const pinned = MINGIT_DIGESTS[arch];
+ assert(pinned, `No pinned MinGit for win-${arch}`);
+ assert.equal(manifest.archive, pinned[0], "Wrong MinGit archive");
+ assert.equal(manifest.sha256, pinned[1], "Wrong MinGit digest");
+ const archive = readFileSync(join(folder, manifest.archive));
+ assert.equal(archive.length, manifest.size, "Wrong MinGit archive size");
+ assert.equal(createHash("sha256").update(archive).digest("hex"), pinned[1], "MinGit zip altered");
+ assert(existsSync(join(folder, "LICENSE.txt")), "Missing MinGit licence");
+ const entries = unzipSync(archive, {
+ filter: (file) => file.name === "cmd/git.exe" || file.name === "LICENSE.txt",
+ });
+ assert(entries["LICENSE.txt"], "MinGit zip lacks its licence");
+ const git = entries["cmd/git.exe"];
+ assert(git, "MinGit zip lacks cmd/git.exe");
+ const temporary = mkdtempSync(join(tmpdir(), "pibot-verify-mingit-"));
+ try {
+ writeFileSync(join(temporary, "git.exe"), git);
+ verifyTargetBinary(join(temporary, "git.exe"), "win32", arch);
+ } finally {
+ rmSync(temporary, { recursive: true, force: true });
+ }
+}
diff --git a/packages/execution/src/command/command-context.ts b/packages/execution/src/command/command-context.ts
index 646928b..43050f0 100644
--- a/packages/execution/src/command/command-context.ts
+++ b/packages/execution/src/command/command-context.ts
@@ -10,6 +10,7 @@ import type {
import { ExecError } from "../core/types.ts";
import { dockerArguments, verifyDockerConnection } from "../docker/docker.ts";
import { dockerProgram } from "../docker/docker-program.ts";
+import { findGit } from "../git/git-process.ts";
import type { createSandboxProfiles } from "../sandbox/sandbox-profiles.ts";
import type { NetworkProxy } from "../web/network-proxy.ts";
import type { BackgroundProcessRecord, createBackgroundJobs } from "./background.ts";
@@ -130,6 +131,22 @@ export async function commandResources(
throw new ExecError("invalid_input");
// Only an issued permit leads to an unsandboxed spawn (command-run consumes it first).
const outside = "outsideSandbox" in input && input.outsideSandbox !== undefined;
+ // Windows packages unpack their MinGit on first need (bundled-git.ts). A command that names Git
+ // waits for it so `git` resolves on its PATH; any other command only starts the unpack.
+ if (options.platform === "win32" && !input.docker) {
+ const unpack = findGit(options);
+ if (/\bgit\b/i.test(input.command))
+ await new Promise<void>((resolve, reject) => {
+ const stop = () => reject(signal.reason);
+ if (signal.aborted) stop();
+ signal.addEventListener("abort", stop, { once: true });
+ // findGit settles undefined on any failure; the command then runs without bundled Git.
+ void unpack.then(() => {
+ signal.removeEventListener("abort", stop);
+ resolve();
+ });
+ });
+ }
const env = mergeSecretEnv(
outside
? userTerminalEnvironment(
diff --git a/packages/execution/src/command/environment.ts b/packages/execution/src/command/environment.ts
index 765da20..c39f7ba 100644
--- a/packages/execution/src/command/environment.ts
+++ b/packages/execution/src/command/environment.ts
@@ -1,6 +1,7 @@
import { statSync } from "node:fs";
import { posix, win32 } from "node:path";
import { ExecError } from "../core/types.ts";
+import { bundledGit, bundledGitReady } from "../git/bundled-git.ts";
import { commandPaths } from "./command-paths.ts";
/**
@@ -35,20 +36,18 @@ function windowsUserPath(original: Readonly<NodeJS.ProcessEnv>, taken: readonly
}
/**
- * Windows builds ship MinGit (resources/bin/git); most Windows computers have no Git. Its `cmd`
+ * Windows builds ship MinGit (bundled-git.ts); most Windows computers have no Git. Its `cmd`
* folder goes after everything else on PATH, so an installed Git always wins and the bundled copy
- * only fills the gap. Nothing is added on other platforms, in dev runs, or for an odd path.
+ * only fills the gap. Only a fully unpacked copy is added (command-context unpacks it first).
+ * Nothing is added on other platforms, in dev runs, or for an odd path.
*/
-function bundledGitPath(platform: NodeJS.Platform, resourcesDir: string | undefined) {
- if (platform !== "win32" || !resourcesDir) return [];
- if (!win32.isAbsolute(resourcesDir) || /[\0\r\n;%"]/.test(resourcesDir)) return [];
- const directory = win32.join(resourcesDir, "bin", "git", "cmd");
- try {
- return statSync(directory).isDirectory() ? [directory] : [];
- } catch {
- // No bundled Git (dev run, non-Windows build): commands see only the user's own PATH.
- return [];
- }
+function bundledGitPath(
+ platform: NodeJS.Platform,
+ original: Readonly<NodeJS.ProcessEnv>,
+ resourcesDir: string | undefined,
+) {
+ const git = bundledGit(platform, original, resourcesDir);
+ return git && bundledGitReady(git) ? [win32.dirname(git.program)] : [];
}
export function commandEnvironment(
@@ -80,7 +79,7 @@ export function commandEnvironment(
// Explicit choices and the launcher environment select the user's Node/toolchain on Unix.
// Windows retains System32 precedence. No variables other than PATH are imported here.
const search = windows
- ? [...paths, ...additions, ...user, ...bundledGitPath(platform, resourcesDir)]
+ ? [...paths, ...additions, ...user, ...bundledGitPath(platform, original, resourcesDir)]
: [...additions, ...user, ...paths];
return {
PATH: [...new Set(search)].join(delimiter),
diff --git a/packages/execution/src/git/bundled-git-unzip.ts b/packages/execution/src/git/bundled-git-unzip.ts
new file mode 100644
index 0000000..8219783
--- /dev/null
+++ b/packages/execution/src/git/bundled-git-unzip.ts
@@ -0,0 +1,123 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { inflateRaw } from "node:zlib";
+
+const inflate = promisify(inflateRaw);
+// MinGit has under 600 entries; the bound only stops a malformed directory from looping long.
+const MAX_ENTRIES = 5_000;
+const MAX_ENTRY = 256 * 1024 * 1024;
+// Windows Defender scans every new executable as it is written; a few writes in flight overlap
+// those scans without flooding the disk.
+const PARALLEL_WRITES = 8;
+// Windows-invalid name characters (and stream names via ':'); control characters are refused
+// separately because a regex range over them is easy to misread.
+const UNSAFE_NAME = /[<>:"|?*\\]/;
+const control = (part: string) => [...part].some((char) => char.charCodeAt(0) < 0x20);
+
+interface Entry {
+ name: string;
+ method: number;
+ compressed: number;
+ size: number;
+ local: number;
+}
+
+/**
+ * Unpacks the bundled MinGit zip into an empty folder. The caller has already matched the
+ * archive's SHA-256, so this is the published release; the checks below still refuse anything a
+ * damaged reader could turn into a write outside `target` (absolute, `..`, drive or stream names).
+ * Only stored and deflate entries without ZIP64 or encryption, which is what MinGit uses.
+ */
+export async function unzipInto(archive: Buffer, target: string, signal: AbortSignal) {
+ const entries = centralDirectory(archive);
+ const folders = new Set<string>();
+ const files: Entry[] = [];
+ for (const entry of entries) {
+ const parts = entry.name.split("/");
+ if (entry.name.endsWith("/")) parts.pop();
+ if (
+ !parts.length ||
+ parts.some(
+ (part) => !part || part === "." || part === ".." || UNSAFE_NAME.test(part) || control(part),
+ )
+ )
+ throw new Error("bundled_git_archive_unsafe");
+ if (entry.name.endsWith("/")) folders.add(join(target, ...parts));
+ else {
+ if (parts.length > 1) folders.add(join(target, ...parts.slice(0, -1)));
+ files.push(entry);
+ }
+ }
+ for (const folder of [...folders].sort((a, b) => a.length - b.length)) {
+ signal.throwIfAborted();
+ await mkdir(folder, { recursive: true });
+ }
+ let next = 0;
+ const worker = async () => {
+ while (next < files.length) {
+ signal.throwIfAborted();
+ const entry = files[next++] as Entry;
+ const data = await contents(archive, entry);
+ // `wx`: the folder is new and private to this extraction; an existing name means a duplicate.
+ await writeFile(join(target, ...entry.name.split("/")), data, { flag: "wx", signal });
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(PARALLEL_WRITES, files.length) }, worker));
+}
+
+function centralDirectory(archive: Buffer): Entry[] {
+ const end = endOfCentralDirectory(archive);
+ const count = archive.readUInt16LE(end + 10);
+ const size = archive.readUInt32LE(end + 12);
+ let offset = archive.readUInt32LE(end + 16);
+ if (count > MAX_ENTRIES || offset + size > end) throw new Error("bundled_git_archive_invalid");
+ const entries: Entry[] = [];
+ for (let index = 0; index < count; index++) {
+ if (offset + 46 > end || archive.readUInt32LE(offset) !== 0x02014b50)
+ throw new Error("bundled_git_archive_invalid");
+ const flags = archive.readUInt16LE(offset + 8);
+ const method = archive.readUInt16LE(offset + 10);
+ const compressed = archive.readUInt32LE(offset + 20);
+ const uncompressed = archive.readUInt32LE(offset + 24);
+ const nameLength = archive.readUInt16LE(offset + 28);
+ const extraLength = archive.readUInt16LE(offset + 30);
+ const commentLength = archive.readUInt16LE(offset + 32);
+ const local = archive.readUInt32LE(offset + 42);
+ const name = archive.subarray(offset + 46, offset + 46 + nameLength).toString("utf8");
+ offset += 46 + nameLength + extraLength + commentLength;
+ if (flags & 0x1 || (method !== 0 && method !== 8) || uncompressed > MAX_ENTRY)
+ throw new Error("bundled_git_archive_unsupported");
+ entries.push({ name, method, compressed, size: uncompressed, local });
+ }
+ return entries;
+}
+
+async function contents(archive: Buffer, entry: Entry): Promise<Buffer> {
+ if (entry.local + 30 > archive.length || archive.readUInt32LE(entry.local) !== 0x04034b50)
+ throw new Error("bundled_git_archive_invalid");
+ const start =
+ entry.local +
+ 30 +
+ archive.readUInt16LE(entry.local + 26) +
+ archive.readUInt16LE(entry.local + 28);
+ const raw = archive.subarray(start, start + entry.compressed);
+ if (raw.length !== entry.compressed) throw new Error("bundled_git_archive_invalid");
+ // Inflating off the main thread keeps a ~100 MB unpack from stalling the brain's event loop.
+ const data =
+ entry.method === 0
+ ? raw
+ : await inflate(raw, { maxOutputLength: Math.max(1, entry.size) }).catch(() => {
+ throw new Error("bundled_git_archive_invalid");
+ });
+ if (data.length !== entry.size) throw new Error("bundled_git_archive_invalid");
+ return data;
+}
+
+function endOfCentralDirectory(archive: Buffer) {
+ if (archive.length < 22) throw new Error("bundled_git_archive_invalid");
+ const floor = Math.max(0, archive.length - 22 - 0xffff);
+ for (let index = archive.length - 22; index >= floor; index--)
+ if (archive.readUInt32LE(index) === 0x06054b50) return index;
+ throw new Error("bundled_git_archive_invalid");
+}
diff --git a/packages/execution/src/git/bundled-git.ts b/packages/execution/src/git/bundled-git.ts
new file mode 100644
index 0000000..50d6062
--- /dev/null
+++ b/packages/execution/src/git/bundled-git.ts
@@ -0,0 +1,223 @@
+import { createHash, randomBytes } from "node:crypto";
+import { readFileSync, statSync } from "node:fs";
+import { mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import { win32 } from "node:path";
+import { z } from "zod";
+import { unzipInto } from "./bundled-git-unzip.ts";
+
+/**
+ * Windows builds ship MinGit as one verified zip (resources/bin/mingit), not as an unpacked tree:
+ * the ~190 executables and DLLs of the tree made the installer write and Defender scan each one,
+ * which took a Windows install from 47 s to 108–143 s. The zip is unpacked once, on first need,
+ * into Pi Bot's own per-user cache: %LOCALAPPDATA%\Pi Bot\runtimes\mingit\<version>-<digest>.
+ * Local, not the roaming data folder, so ~100 MB of binaries never travel with a roaming profile;
+ * and keyed by digest, so every installed version and data folder shares one copy.
+ */
+const MANIFEST = z.strictObject({
+ release: z.string().regex(/^v\d+\.\d+\.\d+\.windows\.\d+$/),
+ version: z.string().regex(/^\d+\.\d+\.\d+$/),
+ archive: z.string().regex(/^MinGit-[\w.-]+\.zip$/),
+ sha256: z.string().regex(/^[0-9a-f]{64}$/),
+ size: z
+ .number()
+ .int()
+ .positive()
+ .max(200 * 1024 * 1024),
+});
+type Manifest = z.infer<typeof MANIFEST>;
+const MARKER = ".pibot-mingit.json";
+// Long enough for a loaded VM with Defender scanning every write; a lock older than this is dead.
+const EXTRACT_DEADLINE_MS = 5 * 60_000;
+const STALE_LOCK_MS = 10 * 60_000;
+// A damaged archive fails the same way every time; do not re-read 40 MB for each Git call.
+const FAILURE_BACKOFF_MS = 10 * 60_000;
+
+export interface BundledGit {
+ manifest: Manifest;
+ archive: string;
+ /** The unpacked MinGit root; `cmd\git.exe` is the program. */
+ home: string;
+ program: string;
+}
+
+const env = (values: Readonly<NodeJS.ProcessEnv>, name: string) =>
+ Object.entries(values).find(([key]) => key.toUpperCase() === name)?.[1];
+const plainPath = (path: string | undefined): path is string =>
+ !!path && win32.isAbsolute(path) && !/[\0\r\n;%"]/.test(path);
+
+/** The bundled MinGit of a packaged Windows build, or undefined (dev run, other platforms). */
+export function bundledGit(
+ platform: NodeJS.Platform,
+ values: Readonly<NodeJS.ProcessEnv>,
+ resourcesDir: string | undefined,
+): BundledGit | undefined {
+ const local = env(values, "LOCALAPPDATA");
+ if (platform !== "win32" || !plainPath(resourcesDir) || !plainPath(local)) return undefined;
+ const folder = win32.join(resourcesDir, "bin", "mingit");
+ let manifest: Manifest;
+ try {
+ manifest = MANIFEST.parse(JSON.parse(readFileSync(win32.join(folder, "mingit.json"), "utf8")));
+ } catch {
+ // No manifest is a dev run or a build without MinGit; a malformed one is treated the same,
+ // so Git falls back to git_unavailable instead of running something unverified.
+ return undefined;
+ }
+ const home = win32.join(
+ local,
+ "Pi Bot",
+ "runtimes",
+ "mingit",
+ `${manifest.version}-${manifest.sha256.slice(0, 12)}`,
+ );
+ return {
+ manifest,
+ archive: win32.join(folder, manifest.archive),
+ home,
+ program: win32.join(home, "cmd", "git.exe"),
+ };
+}
+
+/** Whether the copy is fully unpacked; the marker is the last thing written before the rename. */
+export function bundledGitReady(git: BundledGit) {
+ try {
+ return statSync(win32.join(git.home, MARKER)).isFile();
+ } catch {
+ // Not unpacked yet; the first Git need unpacks it.
+ return false;
+ }
+}
+
+/**
+ * Unpacks the bundled MinGit if needed and returns its git.exe. Serialized across concurrent
+ * callers and processes (two instances with separate data folders share the cache) by an
+ * exclusive lock file; the copy is built in a private temporary folder and renamed into place, so
+ * a crash or a power cut never leaves a half-unpacked Git that looks complete.
+ */
+export async function prepareBundledGit(git: BundledGit): Promise<string> {
+ const signal = AbortSignal.timeout(EXTRACT_DEADLINE_MS);
+ const parent = win32.dirname(git.home);
+ const name = win32.basename(git.home);
+ const lock = win32.join(parent, `${name}.lock`);
+ const failed = win32.join(parent, `${name}.failed`);
+ await mkdir(parent, { recursive: true });
+ for (;;) {
+ if (bundledGitReady(git)) return git.program;
+ await recentFailure(failed);
+ const handle = await open(lock, "wx").catch(async (error: NodeJS.ErrnoException) => {
+ if (error.code !== "EEXIST") throw error;
+ await breakStaleLock(lock);
+ return undefined;
+ });
+ if (!handle) {
+ // Another caller is unpacking; wait for its marker (or its failure) instead of racing it.
+ await pause(250, signal);
+ continue;
+ }
+ try {
+ await handle
+ .writeFile(JSON.stringify({ pid: process.pid, at: Date.now() }))
+ .finally(() => handle.close());
+ if (bundledGitReady(git)) return git.program;
+ await extract(git, parent, name, signal).catch(async (error) => {
+ await writeFile(failed, JSON.stringify({ at: Date.now() })).catch(() => {
+ // Without the record the next need simply tries again; the failure itself is reported.
+ });
+ throw error;
+ });
+ return git.program;
+ } finally {
+ await rm(lock, { force: true });
+ }
+ }
+}
+
+async function extract(git: BundledGit, parent: string, name: string, signal: AbortSignal) {
+ // Leftovers of an unpack that was killed: this lock holder is the only writer for this name.
+ for (const entry of await readdir(parent))
+ if (entry.startsWith(`${name}.tmp-`))
+ await rm(win32.join(parent, entry), { recursive: true, force: true });
+ const archive = await readFile(git.archive, { signal });
+ const digest = createHash("sha256").update(archive).digest("hex");
+ if (archive.length !== git.manifest.size || digest !== git.manifest.sha256)
+ throw new Error("bundled_git_checksum_mismatch");
+ const temporary = win32.join(parent, `${name}.tmp-${randomBytes(6).toString("hex")}`);
+ try {
+ await mkdir(temporary);
+ await unzipInto(archive, temporary, signal);
+ await stat(win32.join(temporary, "cmd", "git.exe"));
+ await writeFile(
+ win32.join(temporary, MARKER),
+ JSON.stringify({ release: git.manifest.release, sha256: git.manifest.sha256 }),
+ );
+ // A folder without the marker is an older partial copy (or one a person emptied); replace it.
+ await rm(git.home, { recursive: true, force: true });
+ await renameWithRetry(temporary, git.home, signal);
+ } finally {
+ await rm(temporary, { recursive: true, force: true });
+ }
+}
+
+/** Defender and the indexer briefly hold fresh executables open, which fails a folder rename. */
+async function renameWithRetry(from: string, to: string, signal: AbortSignal) {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await rename(from, to);
+ return;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (attempt >= 40 || !["EPERM", "EACCES", "EBUSY"].includes(code ?? "")) throw error;
+ await pause(250, signal);
+ }
+ }
+}
+
+async function recentFailure(path: string) {
+ try {
+ if (Date.now() - (await stat(path)).mtimeMs < FAILURE_BACKOFF_MS)
+ throw new Error("bundled_git_unpack_failed_recently");
+ await rm(path, { force: true });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ }
+}
+
+async function breakStaleLock(path: string) {
+ try {
+ const { pid, at } = z
+ .object({ pid: z.number().int(), at: z.number() })
+ .parse(JSON.parse(await readFile(path, "utf8")));
+ if (Date.now() - at < STALE_LOCK_MS && alive(pid)) return;
+ } catch (error) {
+ // A lock being written right now has no content yet; only an old unreadable one is stale.
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
+ const age = await stat(path).then(
+ (info) => Date.now() - info.mtimeMs,
+ () => 0,
+ );
+ if (age < 5_000) return;
+ }
+ await rm(path, { force: true });
+}
+
+function alive(pid: number) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ // EPERM: the process exists but belongs to someone else, so the lock is still held.
+ return (error as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+function pause(ms: number, signal: AbortSignal) {
+ return new Promise<void>((resolve, reject) => {
+ const done = () => {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", done);
+ if (signal.aborted) reject(signal.reason);
+ else resolve();
+ };
+ const timer = setTimeout(done, ms);
+ signal.addEventListener("abort", done, { once: true });
+ });
+}
diff --git a/packages/execution/src/git/git-config-process.ts b/packages/execution/src/git/git-config-process.ts
index 6a73fd6..18726c0 100644
--- a/packages/execution/src/git/git-config-process.ts
+++ b/packages/execution/src/git/git-config-process.ts
@@ -3,7 +3,8 @@ import { constants } from "node:fs";
import { access } from "node:fs/promises";
import { delimiter, dirname, isAbsolute, join } from "node:path";
import { ExecError } from "../core/types.ts";
-import { killGit } from "./git-process.ts";
+import { bundledGit } from "./bundled-git.ts";
+import { killGit, unpackBundledGit } from "./git-process.ts";
import { gitPrograms } from "./git-program.ts";
export interface GitConfigurationProcessOptions {
@@ -34,7 +35,10 @@ export async function configurationGitProgram(
throw error;
}
}
- return undefined;
+ const bundled = bundledGit(options.platform, options.env, options.resourcesDir)?.program;
+ return bundled && (requested === "git" || requested === bundled)
+ ? unpackBundledGit(options)
+ : undefined;
}
/** Fixed Git config operations only, against a disposable file, with no ambient configuration. */
diff --git a/packages/execution/src/git/git-process.ts b/packages/execution/src/git/git-process.ts
index aafbfc8..37069c8 100644
--- a/packages/execution/src/git/git-process.ts
+++ b/packages/execution/src/git/git-process.ts
@@ -3,6 +3,7 @@ import { constants } from "node:fs";
import { access } from "node:fs/promises";
import { posix, win32 } from "node:path";
import { ExecError } from "../core/types.ts";
+import { bundledGit, prepareBundledGit } from "./bundled-git.ts";
import { gitPrograms } from "./git-program.ts";
/** Shared by the read-only runner and the Windows user-write path: no shell, ever. */
@@ -35,7 +36,20 @@ export async function findGit(
// Missing candidates are expected; the next fixed location is checked.
}
}
- return undefined;
+ return unpackBundledGit(options);
+}
+
+/**
+ * No installed Git and no unpacked copy yet: unpack the bundled MinGit (Windows packages only).
+ * A failure is the same as having no Git, so callers fall back as before (git_unavailable, take
+ * turns); the next need after the failure backoff tries again.
+ */
+export async function unpackBundledGit(
+ options: Pick<GitProcessOptions, "platform" | "env" | "resourcesDir">,
+) {
+ const git = bundledGit(options.platform, options.env, options.resourcesDir);
+ if (!git) return undefined;
+ return prepareBundledGit(git).catch(() => undefined);
}
export function gitEnvironment(options: GitProcessOptions, executable: string): NodeJS.ProcessEnv {
diff --git a/packages/execution/src/git/git-program.ts b/packages/execution/src/git/git-program.ts
index b987d11..a5e8b11 100644
--- a/packages/execution/src/git/git-program.ts
+++ b/packages/execution/src/git/git-program.ts
@@ -1,4 +1,5 @@
import { win32 } from "node:path";
+import { bundledGit } from "./bundled-git.ts";
/**
* Repository configuration can name programs (fsmonitor, hooks, pagers, external diff, transports).
@@ -89,11 +90,10 @@ export function gitPrograms(
)
.concat(
// Packaged Windows builds ship MinGit (most Windows computers have no Git). It is last so
- // the user's own Git, with their credential manager and LFS, wins. It lives inside Pi Bot's
- // own install, so whoever could replace it could replace Pi Bot. Dev runs have none.
- resourcesDir && win32.isAbsolute(resourcesDir) && !/[\0\r\n]/.test(resourcesDir)
- ? [win32.join(resourcesDir, "bin", "git", "cmd", "git.exe")]
- : [],
+ // the user's own Git, with their credential manager and LFS, wins. It is unpacked from
+ // the install's verified zip into Pi Bot's own cache (bundled-git.ts), a per-user folder
+ // like the LOCALAPPDATA Git above. Dev runs have none.
+ bundledGit(platform, env, resourcesDir)?.program ?? [],
);
}
return ["/usr/bin/git", "/usr/local/bin/git", "/bin/git"];