Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/pipi/config.ts

Raw
import { readdir, readFile, stat } from "node:fs/promises";
import { join } from "node:path";
import type {
	ExtensionAPI,
	ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import { type TObject, Type } from "typebox";
import { Compile } from "typebox/compile";
import { dbg, span } from "./src/debug.ts";
import {
	defineIntegerSetting,
	MAX_TIMER_MS,
	resolveSetting,
	type SettingDeclaration,
} from "./src/pi-ext-settings.ts";

export const TIERS = ["tiny", "small", "medium", "large", "huge"] as const;
export type Tier = (typeof TIERS)[number];
export const ConfigSchema: TObject = Type.Object(
	{
		model: Type.Optional(Type.String({ minLength: 3 })),
		tier: Type.Optional(Type.Union(TIERS.map((value) => Type.Literal(value)))),
		thinkingLevel: Type.Optional(
			Type.Union(
				["off", "minimal", "low", "medium", "high", "xhigh", "max"].map(
					(value) => Type.Literal(value),
				),
			),
		),
		tools: Type.Optional(Type.Array(Type.String())),
		extensions: Type.Optional(Type.Array(Type.String())),
		skills: Type.Optional(Type.Array(Type.String())),
		prompts: Type.Optional(Type.Array(Type.String())),
		noExtensions: Type.Optional(Type.Boolean()),
		noSkills: Type.Optional(Type.Boolean()),
		noPromptTemplates: Type.Optional(Type.Boolean()),
		noContextFiles: Type.Optional(Type.Boolean()),
		flags: Type.Optional(
			Type.Record(Type.String(), Type.Union([Type.String(), Type.Boolean()])),
		),
		sections: Type.Optional(Type.Record(Type.String(), Type.String())),
		customPrompt: Type.Optional(Type.String()),
		appendSystemPrompt: Type.Optional(Type.String()),
		forceSystemPrompt: Type.Optional(Type.String()),
		outputSchema: Type.Optional(
			Type.Union([Type.Record(Type.String(), Type.Unknown()), Type.Null()]),
		),
		timeoutMs: Type.Optional(
			Type.Union([
				Type.Integer({ minimum: 1, maximum: MAX_TIMER_MS }),
				Type.Null(),
			]),
		),
	},
	{ additionalProperties: false },
);
export interface Config {
	model?: string;
	tier?: Tier;
	thinkingLevel?:
		| "off"
		| "minimal"
		| "low"
		| "medium"
		| "high"
		| "xhigh"
		| "max";
	tools?: string[];
	extensions?: string[];
	skills?: string[];
	prompts?: string[];
	noExtensions?: boolean;
	noSkills?: boolean;
	noPromptTemplates?: boolean;
	noContextFiles?: boolean;
	flags?: Record<string, string | boolean>;
	sections?: Record<string, string>;
	customPrompt?: string;
	appendSystemPrompt?: string;
	forceSystemPrompt?: string;
	outputSchema?: Record<string, unknown> | null;
	timeoutMs?: number | null;
}
export interface AgentPreset {
	name: string;
	description: string;
	config: Config;
	directory: string;
}
export interface Catalog {
	agents: AgentPreset[];
	dynamic: string[];
	diagnostics: string[];
}
export interface ModelTier {
	model: string | null;
	thinkingLevel: NonNullable<Config["thinkingLevel"]>;
	instructions: string;
}
export interface TierSettings {
	modelTiers: Partial<Record<Tier, Partial<ModelTier>>>;
	providerModelTiers: Record<string, Partial<Record<Tier, Partial<ModelTier>>>>;
}
const DEFAULT_TIERS: Record<Tier, ModelTier> = {
	tiny: {
		model: null,
		thinkingLevel: "low",
		instructions: "No unresolved judgement.",
	},
	small: {
		model: null,
		thinkingLevel: "low",
		instructions: "Few local decisions; low consequence.",
	},
	medium: {
		model: null,
		thinkingLevel: "medium",
		instructions:
			"Several related decisions; moderate ambiguity or consequence.",
	},
	large: {
		model: null,
		thinkingLevel: "high",
		instructions:
			"Many dependent decisions; substantial ambiguity or consequence.",
	},
	huge: {
		model: null,
		thinkingLevel: "max",
		instructions:
			"Exceptional residual burden after decomposition and verification.",
	},
};
function object(value: unknown): value is Record<string, unknown> {
	return value !== null && typeof value === "object" && !Array.isArray(value);
}
function tierMap(value: unknown): TierSettings["modelTiers"] {
	if (!object(value)) throw new Error("Expected tier configuration object");
	for (const [key, tier] of Object.entries(value)) {
		if (
			!TIERS.includes(key as Tier) ||
			!object(tier) ||
			Object.keys(tier).some(
				(field) => !["model", "thinkingLevel", "instructions"].includes(field),
			) ||
			("model" in tier &&
				tier["model"] !== null &&
				(typeof tier["model"] !== "string" ||
					tier["model"].indexOf("/") <= 0 ||
					tier["model"].endsWith("/"))) ||
			("thinkingLevel" in tier &&
				!["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(
					tier["thinkingLevel"] as string,
				)) ||
			("instructions" in tier &&
				(typeof tier["instructions"] !== "string" ||
					!tier["instructions"].trim()))
		)
			throw new Error(
				"Invalid tier: expected model, thinkingLevel and selection instructions",
			);
	}
	return value as TierSettings["modelTiers"];
}
export const PIPI_SETTING: SettingDeclaration<TierSettings> = {
	key: "pipi",
	default: { modelTiers: {}, providerModelTiers: {} },
	parse(value) {
		if (
			!object(value) ||
			Object.keys(value).some(
				(key) =>
					!["modelTiers", "providerModelTiers", "timeoutMs"].includes(key),
			)
		)
			return undefined;
		const providers = value["providerModelTiers"] ?? {};
		if (!object(providers)) return undefined;
		return {
			modelTiers: tierMap(value["modelTiers"] ?? {}),
			providerModelTiers: Object.fromEntries(
				Object.entries(providers).map(([name, tiers]) => [
					name,
					tierMap(tiers),
				]),
			),
		};
	},
};
export const TIMEOUT_SETTING: SettingDeclaration<number> = defineIntegerSetting(
	{
		key: "pipi.timeoutMs",
		label: "Call deadline",
		description:
			"Wall-clock deadline per pipi call; an expired deadline aborts the child and preserves its session for continuation.",
		range: { min: 1_000, max: MAX_TIMER_MS },
		default: 14_400_000,
		env: "PIPI_TIMEOUT_MS",
	},
);
export function callDeadline(pi: ExtensionAPI, ctx: ExtensionContext): number {
	const result = resolveSetting(pi, ctx, TIMEOUT_SETTING);
	if (!result.ok) throw new Error(result.error);
	return result.value;
}
export function effectiveTiers(
	values: TierSettings,
	provider?: string,
): Record<Tier, ModelTier> {
	return Object.fromEntries(
		TIERS.map((name) => [
			name,
			{
				...DEFAULT_TIERS[name],
				...values.modelTiers[name],
				...(provider ? values.providerModelTiers[provider]?.[name] : {}),
			},
		]),
	) as Record<Tier, ModelTier>;
}
export function tierGuidance(values: TierSettings, provider?: string): string {
	return [
		"User recommendations, not restrictions. Explicit provider/model and thinkingLevel may override a tier; omit model/tier to inherit.",
		...TIERS.map((name) => {
			const tier = effectiveTiers(values, provider)[name];
			return `- ${name}: ${tier.model ?? "inherited model"}; ${tier.thinkingLevel}; ${tier.instructions}`;
		}),
	].join("\n");
}
export function settings(
	pi: ExtensionAPI,
	ctx: ExtensionContext,
): TierSettings {
	const result = resolveSetting(pi, ctx, PIPI_SETTING);
	if (!result.ok) throw new Error(result.error);
	return result.value;
}

async function directories(path: string): Promise<string[]> {
	try {
		return (await readdir(path, { withFileTypes: true }))
			.filter((entry) => entry.isDirectory())
			.map((entry) => entry.name)
			.sort();
	} catch (error) {
		if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
		throw error;
	}
}
export async function discover(agentDir: string): Promise<Catalog> {
	const finish = span?.("discovery");
	const agents: AgentPreset[] = [],
		diagnostics: string[] = [];
	let names: string[] = [];
	try {
		names = await directories(join(agentDir, "pipi", "agents"));
	} catch {
		diagnostics.push("Agent preset directory unavailable");
	}
	for (const name of names) {
		const directory = join(agentDir, "pipi", "agents", name);
		const configPath = join(directory, "config.json");
		try {
			await stat(configPath);
		} catch (error) {
			if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
			diagnostics.push(
				`Preset ${JSON.stringify(name)} unavailable: invalid config.json`,
			);
			continue;
		}
		try {
			const value: unknown = JSON.parse(await readFile(configPath, "utf8"));
			if (
				!object(value) ||
				typeof value["description"] !== "string" ||
				!value["description"].trim()
			)
				throw new Error("description required");
			const { description, ...config } = value;
			// Library files are strict JSON; model-issued tool calls retain native coercion.
			validateConfig(config);
			agents.push({ name, description, config, directory });
		} catch {
			diagnostics.push(
				`Preset ${JSON.stringify(name)} unavailable: invalid config.json`,
			);
			dbg?.("discovery.invalid", { count: 1 });
		}
	}
	let dynamic: string[] = [];
	try {
		const root = join(agentDir, "pipi", "dynamic");
		dynamic = [];
		for (const name of await directories(root))
			try {
				if ((await stat(join(root, name, "index.ts"))).isFile())
					dynamic.push(name);
			} catch (error) {
				if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
			}
	} catch {
		diagnostics.push("Dynamic extension directory unavailable");
	}
	finish?.("finish", { count: agents.length });
	return { agents, dynamic, diagnostics };
}
export async function instructions(
	preset: AgentPreset | undefined,
): Promise<string | undefined> {
	if (!preset) return undefined;
	try {
		return await readFile(join(preset.directory, "instructions.md"), "utf8");
	} catch (error) {
		if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
		throw error;
	}
}
export function selectModel(
	config: Config,
	values: TierSettings,
	provider: string | undefined,
): string | undefined {
	if (config.model) return config.model;
	if (!config.tier) return undefined;
	return effectiveTiers(values, provider)[config.tier].model ?? undefined;
}

const configValidator = Compile(ConfigSchema);
export function validateConfig(value: unknown): asserts value is Config {
	if (!configValidator.Check(value))
		throw new Error("Invalid preset configuration");
}