repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/klaus/src/runtime/standard.ts

Raw
File outline
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { readFile, stat } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { promisify } from "node:util";
import { dbg } from "../debug.js";
import { SDK_VERSION } from "../protocol.js";

const execFileAsync = promisify(execFile);
const require = createRequire(import.meta.url);

const CHECKSUMS: Record<string, string> = {
	"darwin-arm64":
		"1c196c456373b57818ae87df84aecee96cb659448c0d6a6bbb401ac5758431b2",
	"darwin-x64":
		"d10bc7bb1720435f8830aa3ee74085f09348d2b1a2a152bdee251b770d76cc73",
	"linux-arm64":
		"28d736120a6b14c5eae1ad1470e73371818c9c2fa41e0b3c7040207aa2d4edee",
	"linux-arm64-musl":
		"a47d45149ea7c74e4474bce3c7628c4643b0541801b42053d6e26fd5e3203fdd",
	"linux-x64":
		"0933b286cf94e1b2504b35ac165ab76b8f822735d53371c56393988c23040d58",
	"linux-x64-musl":
		"33546c2f7947bbfdb46a969123c5329e607c414045cd3645a29aa3cfe023c6ab",
	"win32-arm64":
		"645800d24201c93e5fd6f4308e0292bba9a75900693667401cdffb4361f8e616",
	"win32-x64":
		"223bc058b5aef48138876e28de5d00387e4fd7362a18e733143bf00819c01aab",
};

let resolution: Promise<string> | undefined;

function platformKey(): string {
	dbg?.("runtime.standard.platformKey.start", {
		platform: process.platform,
		arch: process.arch,
	});
	if (process.arch !== "arm64" && process.arch !== "x64") {
		throw new Error(
			`Klaus does not support ${process.platform} ${process.arch}.`,
		);
	}
	if (process.platform === "darwin" || process.platform === "win32") {
		return `${process.platform}-${process.arch}`;
	}
	if (process.platform !== "linux") {
		throw new Error(
			`Klaus does not support ${process.platform} ${process.arch}.`,
		);
	}
	const report = process.report?.getReport();
	const glibc =
		report && typeof report === "object"
			? (report as { header?: { glibcVersionRuntime?: string } }).header
					?.glibcVersionRuntime
			: undefined;
	return `linux-${process.arch}${glibc ? "" : "-musl"}`;
}

async function sha256(path: string): Promise<string> {
	const hash = createHash("sha256");
	for await (const chunk of createReadStream(path)) hash.update(chunk);
	return hash.digest("hex");
}

async function resolve(): Promise<string> {
	dbg?.("runtime.standard.resolve.start");
	const key = platformKey();
	const packageName = `@anthropic-ai/claude-agent-sdk-${key}`;
	let packageJson: string;
	try {
		packageJson = require.resolve(`${packageName}/package.json`);
	} catch {
		throw new Error(`Klaus runtime ${packageName}@${SDK_VERSION} is missing.`);
	}
	const metadata = JSON.parse(await readFile(packageJson, "utf8")) as {
		version?: unknown;
	};
	if (metadata.version !== SDK_VERSION) {
		throw new Error(
			`Klaus runtime ${packageName} has version ${String(metadata.version)}, expected ${SDK_VERSION}.`,
		);
	}
	const executable = join(
		dirname(packageJson),
		process.platform === "win32" ? "claude.exe" : "claude",
	);
	if (!(await stat(executable)).isFile()) {
		throw new Error(`Klaus runtime executable is missing from ${packageName}.`);
	}
	if ((await sha256(executable)) !== CHECKSUMS[key]) {
		throw new Error(`Klaus runtime checksum mismatch for ${key}.`);
	}
	await execFileAsync(executable, ["--version"], {
		timeout: 30_000,
		maxBuffer: 64 * 1024,
	});
	dbg?.("runtime.standard.resolve.end", { key, packageName, executable });
	return executable;
}

export function resolveStandardRuntime(): Promise<string> {
	dbg?.("runtime.standard.resolveCached", { cached: Boolean(resolution) });
	resolution ??= resolve().catch((error) => {
		dbg?.("runtime.standard.resolve.error", {
			error: error instanceof Error ? error.message : String(error),
		});
		resolution = undefined;
		throw error;
	});
	return resolution;
}