repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/gratis/src/kilo.ts

Raw
File outline
import type {
	ExtensionAPI,
	ProviderConfig,
} from "@earendil-works/pi-coding-agent";

export const KILO_PROVIDER = "kilo";
const BASE_URL = "https://ai-gateway.kilo.ai/api/v1";
const MAX_OUTPUT_TOKENS = 32_768;
const FREE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
/** Environment variable holding the Kilo key; Pi resolves `$NAME` references. */
export const KILO_KEY_ENV = "KILO_API_KEY";

type ModelConfig = NonNullable<ProviderConfig["models"]>[number];

function chatModel(
	id: string,
	name: string,
	contextWindow: number,
	maxTokens: number,
): ModelConfig {
	return {
		id,
		name,
		// Kilo accepts reasoning fields, but Pi requests stay plain until verified.
		reasoning: false,
		input: ["text"],
		cost: FREE,
		contextWindow,
		maxTokens: Math.min(maxTokens, MAX_OUTPUT_TOKENS),
	};
}

/** Free models verified with Pi-sized prompts and tool calls; used until a refresh succeeds. */
const SEED: ModelConfig[] = [
	chatModel("kilo-auto/free", "Kilo Auto Free", 256_000, 32_768),
	chatModel(
		"stealth/glyph-cluster",
		"Stealth: Glyph Cluster (free)",
		256_000,
		256_000,
	),
	chatModel(
		"recursive/flint-v1.0:free",
		"Recursive: Flint (free)",
		262_144,
		235_929,
	),
	chatModel(
		"reflection/beam-free",
		"Reflection: Beam 1.0 (free)",
		1_048_576,
		131_072,
	),
];

function record(value: unknown): Record<string, unknown> {
	return typeof value === "object" && value !== null && !Array.isArray(value)
		? (value as Record<string, unknown>)
		: {};
}

function positive(value: unknown): number | undefined {
	return typeof value === "number" && Number.isFinite(value) && value > 0
		? value
		: undefined;
}

function strings(value: unknown): string[] {
	return Array.isArray(value)
		? value.filter((item): item is string => typeof item === "string")
		: [];
}

/** Free, text-only, tool-capable models from Kilo's `/models` response. */
export function kiloModels(data: unknown): ModelConfig[] {
	const models: ModelConfig[] = [];
	const list = record(data)["data"];
	for (const raw of Array.isArray(list) ? list.slice(0, 2048) : []) {
		const model = record(raw);
		const id = model["id"];
		if (typeof id !== "string" || !id) continue;
		const pricing = record(model["pricing"]);
		const free =
			model["isFree"] === true ||
			(pricing["prompt"] === "0" && pricing["completion"] === "0");
		const architecture = record(model["architecture"]);
		const textOnly =
			strings(architecture["output_modalities"]).join() === "text" &&
			strings(architecture["input_modalities"]).includes("text");
		// Coding turns need tool calls.
		const tools = strings(model["supported_parameters"]).includes("tools");
		const contextWindow = positive(model["context_length"]);
		if (!free || !textOnly || !tools || !contextWindow) continue;
		const name = typeof model["name"] === "string" ? model["name"] : id;
		models.push(
			chatModel(
				id,
				name,
				contextWindow,
				positive(record(model["top_provider"])["max_completion_tokens"]) ??
					16_384,
			),
		);
	}
	return models;
}

/** Kilo AI Gateway: OpenAI-compatible, free models refresh from the live catalog. */
export function registerKilo(pi: Pick<ExtensionAPI, "registerProvider">): void {
	pi.registerProvider(KILO_PROVIDER, {
		name: "Kilo",
		baseUrl: BASE_URL,
		apiKey: `$${KILO_KEY_ENV}`,
		api: "openai-completions",
		models: SEED,
		async refreshModels(context) {
			if (!context.allowNetwork) return SEED;
			const key =
				context.credential?.type === "api_key"
					? context.credential.key
					: process.env[KILO_KEY_ENV];
			const response = await fetch(`${BASE_URL}/models`, {
				headers: key ? { Authorization: `Bearer ${key}` } : {},
				signal: AbortSignal.any([context.signal, AbortSignal.timeout(15_000)]),
			});
			if (!response.ok) {
				await response.body?.cancel();
				throw new Error(`Kilo models HTTP ${response.status}`);
			}
			const models = kiloModels(await response.json());
			// An empty or malformed catalog keeps the verified seed.
			return models.length ? models : SEED;
		},
	});
}