Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/klaus/src/sdk-version.ts

Raw
import { existsSync, readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";

// The claude-agent-sdk version is derived from the actually-installed package
// rather than pinned, so the dependency can float. The package's `exports` map
// blocks resolving `./package.json` directly, so the root is located by walking
// up from the resolved entry. The core package is platform-agnostic and present
// wherever Pi installed klaus's dependencies, so this resolves on every runtime.

const require = createRequire(import.meta.url);
const SDK = "@anthropic-ai/claude-agent-sdk";

function sdkRoot(): string {
	let dir = dirname(require.resolve(SDK));
	while (true) {
		const manifest = join(dir, "package.json");
		if (existsSync(manifest)) {
			const parsed = JSON.parse(readFileSync(manifest, "utf8")) as {
				name?: unknown;
			};
			if (parsed.name === SDK) return dir;
		}
		const parent = dirname(dir);
		if (parent === dir) throw new Error(`Cannot locate ${SDK} package root.`);
		dir = parent;
	}
}

function readVersion(file: string): string {
	const version = (
		JSON.parse(readFileSync(join(sdkRoot(), file), "utf8")) as {
			version?: unknown;
		}
	).version;
	return typeof version === "string" ? version : "0";
}

let sdk: string | undefined;
let claude: string | undefined;

/** Version of the installed `@anthropic-ai/claude-agent-sdk` package. */
export function sdkVersion(): string {
	sdk ??= readVersion("package.json");
	return sdk;
}

/** Claude binary version declared by the installed SDK manifest. */
export function claudeVersion(): string {
	claude ??= readVersion("manifest.json");
	return claude;
}