repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/klaus/src/models.ts

Raw
File outline
import type {
	AnthropicMessagesCompat,
	Api,
	Model,
} from "@earendil-works/pi-ai";
import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";
import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
import { dbg } from "./debug.js";
import {
	isKlausModelId,
	type KlausModelId,
	MODEL_SELECTORS,
} from "./protocol.js";

export const MODEL_IDS = Object.keys(MODEL_SELECTORS) as KlausModelId[];

const FABLE_FALLBACK_IDS = ["claude-opus-4-8", "claude-opus-5"] as const;

/** Pi model lookup, satisfied by `ModelRegistry.find` or the builtin catalog. */
export type AnthropicModelSource = (
	modelId: KlausModelId,
) => Model<Api> | undefined;

export const builtinSource: AnthropicModelSource = (modelId) =>
	getBuiltinModel("anthropic", modelId);

/** Pi catalog entries may be tuned for the direct Anthropic API, where request
 * headers unlock capacity that the Claude Agent SDK path does not provide.
 * Klaus drops those headers, so it must not advertise more than the builtin
 * catalog promises for the same model. */
function clampToBaseline(
	modelId: string,
	field: "contextWindow" | "maxTokens",
	value: number,
	baseline: Model<Api> | undefined,
): number {
	const ceiling = baseline?.[field];
	if (ceiling === undefined || value <= ceiling) return value;
	dbg?.("models.clamp", { modelId, field, value, ceiling });
	return ceiling;
}

function fableCompat(model: Model<Api>): Model<Api>["compat"] {
	return {
		...(structuredClone(model.compat) as AnthropicMessagesCompat),
		allowedFallbackModels: FABLE_FALLBACK_IDS.flatMap((id) => {
			const fallback = getBuiltinModel("anthropic", id);
			return fallback
				? [
						{
							provider: "anthropic",
							model: id,
							cost: structuredClone(fallback.cost),
						},
					]
				: [];
		}),
	} satisfies AnthropicMessagesCompat;
}

/** Project one Pi Anthropic model onto the Klaus provider. Transport-owned
 * fields (`api`, `baseUrl`, `headers`, sampling parameters) are never
 * inherited, because the Claude Agent SDK owns the request. */
export function projectModel(model: Model<Api>): ProviderModelConfig {
	dbg?.("models.projectModel", { provider: model.provider, modelId: model.id });
	const baseline = isKlausModelId(model.id)
		? getBuiltinModel("anthropic", model.id)
		: undefined;
	return {
		id: model.id,
		name: model.name,
		reasoning: model.reasoning,
		thinkingLevelMap: model.thinkingLevelMap,
		input: [...model.input],
		cost: structuredClone(model.cost),
		compat:
			model.id === "claude-fable-5-1"
				? fableCompat(model)
				: structuredClone(model.compat),
		contextWindow: clampToBaseline(
			model.id,
			"contextWindow",
			model.contextWindow,
			baseline,
		),
		maxTokens: clampToBaseline(
			model.id,
			"maxTokens",
			model.maxTokens,
			baseline,
		),
	};
}

/** Project every advertised Klaus model that the source still knows. */
export function projectModels(
	source: AnthropicModelSource,
): ProviderModelConfig[] {
	const models = MODEL_IDS.flatMap((id) => {
		const model = source(id);
		dbg?.("models.lookup", { modelId: id, found: Boolean(model) });
		return model ? [projectModel(model)] : [];
	});
	dbg?.("models.projectModels", { count: models.length });
	return models;
}

/** Stable identity of a projected catalog, used to skip redundant provider
 * registrations. */
export function modelsSignature(models: ProviderModelConfig[]): string {
	return JSON.stringify(models);
}