Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript
7.1 KB
Raw Blame
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";

const PACKAGE = fileURLToPath(new URL("..", import.meta.url));
const LOCKFILE = join(PACKAGE, "..", "..", "pnpm-lock.yaml");
const IMPORTER = "packages/daemon";

/**
 * The exact versions pnpm installed for the daemon's own dependencies, read from
 * the `importers` section of the lockfile; workspace links are left out.
 */
export function lockedDependencies(
	lockfile: string = readFileSync(LOCKFILE, "utf8"),
): Record<string, string> {
	const versions: Record<string, string> = {};
	let section: "importer" | "dependencies" | undefined;
	let name: string | undefined;
	for (const line of lockfile.split("\n")) {
		if (/^ {2}\S/.test(line)) section = line.trim() === `${IMPORTER}:` ? "importer" : undefined;
		else if (section && /^ {4}\S/.test(line))
			section = line.trim() === "dependencies:" ? "dependencies" : "importer";
		else if (section === "dependencies" && /^ {6}\S/.test(line))
			name = line.trim().slice(0, -1).replace(/^'|'$/g, "");
		else if (section === "dependencies" && name && /^ {8}version: /.test(line)) {
			const version = line.trim().slice("version: ".length).split("(")[0] ?? "";
			if (!version.startsWith("link:")) versions[name] = version;
		}
	}
	if (Object.keys(versions).length === 0) throw new Error(`No ${IMPORTER} dependencies in the lockfile.`);
	return versions;
}

/**
 * An engine package's key in the lockfile's `packages:` section: two spaces, an optional quote,
 * the `@earendil-works/` name, `@`, then the version up to a peer suffix `(`, the quote or the `:`.
 * For `  '@earendil-works/[email protected]([email protected])':` that is `@earendil-works/pi-ai` and `1.4.0`.
 */
const ENGINE_PACKAGE_KEY = /^ {2}'?(?<name>@earendil-works\/[^@'/]+)@(?<version>[^(':]+)/;

function enginePackageKey(line: string): { name: string; version: string } | undefined {
	const { name, version } = ENGINE_PACKAGE_KEY.exec(line)?.groups ?? {};
	return name && version ? { name, version } : undefined;
}

/**
 * The lockfile's versions of the engine's own packages (`@earendil-works/*`) that the runtime
 * does not list directly. The engine asks for them with `^` ranges, so a fresh `npm install`
 * would take newer releases that may no longer fit it; the runtime pins them as `overrides`.
 */
export function lockedEnginePackages(
	direct: Record<string, string>,
	lockfile: string = readFileSync(LOCKFILE, "utf8"),
): Record<string, string> {
	const versions: Record<string, string> = {};
	let inPackages = false;
	for (const line of lockfile.split("\n")) {
		if (/^\S/.test(line)) inPackages = line.trim() === "packages:";
		const entry = inPackages ? enginePackageKey(line) : undefined;
		if (!entry || entry.name in direct) continue;
		const { name, version } = entry;
		if (versions[name] && versions[name] !== version)
			throw new Error(`The lockfile holds two versions of ${name}.`);
		versions[name] = version;
	}
	return versions;
}

/** Windows staging is explicit and refuses an absent build; Unix never needs the addon. */
export function runtimeWindowsStopArtifact(
	platform: NodeJS.Platform,
	artifact = join(PACKAGE, "native", "windows-stop.node"),
	present: (path: string) => boolean = existsSync,
): string | undefined {
	if (platform !== "win32") return undefined;
	if (!present(artifact))
		throw new Error(
			"Windows stop addon is missing. Run build:windows-stop with existing Node headers and node.lib first.",
		);
	return artifact;
}

/** A `pi` command that runs the runtime's own Node on the engine, from wherever the runtime folder is. */
export function piWrapper(engineEntry: string, platform: NodeJS.Platform = process.platform): string {
	if (platform === "win32") {
		return [
			"@echo off",
			"setlocal DisableDelayedExpansion",
			`"%~dp0..\\node\\bin\\node.exe" "%~dp0..\\daemon\\node_modules\\${engineEntry.replaceAll("/", "\\")}" %*`,
			"exit /b %errorlevel%",
			"",
		].join("\r\n");
	}
	return `#!/bin/sh
# The engine's \`pi\` command for an installed Gentle Dot runtime (generated by build:runtime).
self=$0
while [ -L "$self" ]; do
	link=$(readlink "$self")
	case $link in
		/*) self=$link ;;
		*) self=$(dirname "$self")/$link ;;
	esac
done
runtime=$(CDPATH= cd -- "$(dirname -- "$self")/.." && pwd -P) || exit 1
exec "$runtime/node/bin/node" "$runtime/daemon/node_modules/${engineEntry}" "$@"
`;
}

/** The engine's `pi` entry inside `node_modules`, from its package's `bin` (its exports hide `package.json`). */
function engineEntry(): string {
	const engine = join("@earendil-works", "pi-coding-agent");
	const require = createRequire(join(PACKAGE, "package.json"));
	for (const dir of require.resolve.paths(engine) ?? []) {
		const manifest = join(dir, engine, "package.json");
		if (!existsSync(manifest)) continue;
		const bin = (JSON.parse(readFileSync(manifest, "utf8")) as { bin?: Record<string, string> }).bin?.pi;
		if (!bin) throw new Error("The engine package has no `pi` command.");
		return `@earendil-works/pi-coding-agent/${bin.replace(/^\.\//, "")}`;
	}
	throw new Error("The assistant engine is missing. Run `pnpm install`.");
}

/**
 * Builds the daemon part of the installed runtime into `outDir`: `daemon/cli.mjs`
 * (the daemon and the protocol bundled; the engine and `ws` external), the files it
 * finds next to itself, a `package.json` for a flat install of the external
 * dependencies, and `bin/pi`. On Windows the wrapper is `bin/pi.cmd`, and the stop addon goes to
 * `daemon/native`. Nothing is installed.
 */
export async function buildRuntime(outDir: string): Promise<void> {
	const nativeArtifact = runtimeWindowsStopArtifact(process.platform);
	const daemon = join(outDir, "daemon");
	mkdirSync(join(daemon, "extensions"), { recursive: true });
	mkdirSync(join(outDir, "bin"), { recursive: true });
	const dependencies = lockedDependencies();
	await build({
		entryPoints: [join(PACKAGE, "src", "cli.ts")],
		outfile: join(daemon, "cli.mjs"),
		bundle: true,
		platform: "node",
		format: "esm",
		target: "node24",
		external: Object.keys(dependencies),
		logLevel: "error",
	});
	chmodSync(join(daemon, "cli.mjs"), 0o755);
	// The bundle finds these through `import.meta.url`, as the sources do in `src/`.
	copyFileSync(join(PACKAGE, "src", "identity.md"), join(daemon, "identity.md"));
	// The engine loads the guard with -e, and the guard imports its siblings.
	for (const name of ["approval-guard.ts", "screenshot-context.ts"]) {
		copyFileSync(join(PACKAGE, "src", "extensions", name), join(daemon, "extensions", name));
	}
	if (nativeArtifact) {
		mkdirSync(join(daemon, "native"), { recursive: true });
		copyFileSync(nativeArtifact, join(daemon, "native", "windows-stop.node"));
	}
	const manifest = {
		name: "gentle-dot-runtime",
		private: true,
		type: "module",
		dependencies,
		overrides: lockedEnginePackages(dependencies),
	};
	writeFileSync(join(daemon, "package.json"), `${JSON.stringify(manifest, null, "\t")}\n`);
	writeFileSync(
		join(outDir, "bin", process.platform === "win32" ? "pi.cmd" : "pi"),
		piWrapper(engineEntry()),
		{ mode: 0o755 },
	);
}