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":
		"5efecaff231b798be3c66def9be54183623b328b80eaef17f93c43987024e82a",
	"darwin-x64":
		"2cbc002b32778bd70aa2e668ada920c54d9aacd91b71dbd5619c01ca148ae533",
	"linux-arm64":
		"7bbed5a9b0fc2e4ec67bad3490d06ca91b86d6b037d47520b7898951757d1b8a",
	"linux-arm64-musl":
		"53b58ffbeb3f9325f0ca5eb54fd03cd0346bd197328fa1e68a700ac8e097e6c1",
	"linux-x64":
		"4ae40dd1784e85753e742e09f267d29ecbb82890361ad3817d27560866d364a6",
	"linux-x64-musl":
		"df6502c5978420d71fb32fe41b4ca956a7eb3f6245fc11a03ca2cde7f03b8f93",
	"win32-arm64":
		"df26e336df846f4b68edda1021af5aecc1f8172d9f045ee33a480916385b35f9",
	"win32-x64":
		"f2f5d1a155167488aeb32cd263e15436253c7b1681ae147c9e73e4d6bbc3c852",
};

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;
}