repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/klaus/src/runtime/index.ts

Raw
File outline
import { mkdir, mkdtemp, rm } from "node:fs/promises";
import { validateHeaderName, validateHeaderValue } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { dbg } from "../debug.js";
import { resolveAndroidRuntime } from "./android.js";
import { resolveStandardRuntime } from "./standard.js";

const ENV_ALLOWLIST = [
	"PATH",
	"PATHEXT",
	"SystemRoot",
	"WINDIR",
	"ComSpec",
	"TMP",
	"TEMP",
	"TMPDIR",
	"LANG",
	"LC_ALL",
	"LC_CTYPE",
	"HTTP_PROXY",
	"HTTPS_PROXY",
	"NO_PROXY",
	"ALL_PROXY",
	"SSL_CERT_FILE",
	"SSL_CERT_DIR",
	"NODE_EXTRA_CA_CERTS",
	"PREFIX",
	"LD_LIBRARY_PATH",
] as const;

const RESERVED_HEADERS = new Set([
	"authorization",
	"connection",
	"content-length",
	"content-type",
	"host",
	"proxy-authorization",
	"transfer-encoding",
	"x-api-key",
]);

export interface ChildRuntime {
	executable?: string;
	configDir: string;
	env: Record<string, string>;
	betas: Array<"context-1m-2025-08-07">;
	cleanup(): Promise<void>;
}

function customHeaders(headers: Record<string, string | null>): {
	serialized?: string;
	betas: Array<"context-1m-2025-08-07">;
} {
	dbg?.("runtime.customHeaders.start", { headerNames: Object.keys(headers) });
	const lines: string[] = [];
	const betas: Array<"context-1m-2025-08-07"> = [];
	for (const [name, value] of Object.entries(headers)) {
		if (value === null) continue;
		const lower = name.toLowerCase();
		if (RESERVED_HEADERS.has(lower) || lower.startsWith("x-klaus-")) continue;
		try {
			validateHeaderName(name);
			validateHeaderValue(name, value);
		} catch {
			continue;
		}
		if (lower === "anthropic-beta") {
			if (
				value
					.split(",")
					.map((part) => part.trim())
					.includes("context-1m-2025-08-07")
			) {
				betas.push("context-1m-2025-08-07");
			}
			continue;
		}
		if (name.includes("\n") || value.includes("\n")) continue;
		lines.push(`${name}: ${value}`);
	}
	dbg?.("runtime.customHeaders.end", {
		forwardedCount: lines.length,
		betas,
	});
	return { serialized: lines.length ? lines.join("\n") : undefined, betas };
}

export async function createChildRuntime(
	oauthToken: string,
	headers: Record<string, string | null>,
	overrides: Record<string, string> = {},
): Promise<ChildRuntime> {
	dbg?.("runtime.create.start", {
		platform: process.platform,
		arch: process.arch,
		tokenLength: oauthToken.length,
		headerNames: Object.keys(headers),
		overrideNames: Object.keys(overrides),
	});
	const root = join(tmpdir(), "klaus");
	await mkdir(root, { recursive: true, mode: 0o700 });
	const configDir = await mkdtemp(join(root, "query-"));
	dbg?.("runtime.create.configDir", { root, configDir });
	const env: Record<string, string> = {};
	for (const key of ENV_ALLOWLIST) {
		const value = overrides[key] ?? process.env[key];
		if (value !== undefined) env[key] = value;
	}
	const mapped = customHeaders(headers);
	env.HOME = configDir;
	env.CLAUDE_CONFIG_DIR = configDir;
	env.CLAUDE_CODE_OAUTH_TOKEN = oauthToken;
	env.CLAUDE_AGENT_SDK_CLIENT_APP = "klaus/1";
	env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";
	env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY = "0";
	if (mapped.serialized) env.ANTHROPIC_CUSTOM_HEADERS = mapped.serialized;
	if (
		process.env.VITEST &&
		oauthToken === "fake" &&
		process.env.KLAUS_E2E_BASE_URL
	) {
		env.ANTHROPIC_BASE_URL = process.env.KLAUS_E2E_BASE_URL;
	}
	const cleanup = async () => {
		dbg?.("runtime.cleanup.start", { configDir });
		await rm(configDir, {
			recursive: true,
			force: true,
			maxRetries: 10,
			retryDelay: 100,
		});
		dbg?.("runtime.cleanup.end", { configDir });
	};
	try {
		const executable =
			process.platform === "android"
				? await resolveAndroidRuntime()
				: await resolveStandardRuntime();
		dbg?.("runtime.create.ready", {
			executable,
			configDir,
			envNames: Object.keys(env),
			clientApp: env.CLAUDE_AGENT_SDK_CLIENT_APP,
			betas: mapped.betas,
		});
		return {
			executable,
			configDir,
			env,
			betas: mapped.betas,
			cleanup,
		};
	} catch (error) {
		dbg?.("runtime.create.error", {
			error: error instanceof Error ? error.message : String(error),
		});
		await cleanup();
		throw error;
	}
}