repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/overkill/lib/rollouts.ts

Raw
File outline
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import {
	createAgentSession,
	DefaultResourceLoader,
	SessionManager,
	SettingsManager,
} from "@earendil-works/pi-coding-agent";
import {
	buildCheckerInput,
	type CheckerResult,
	fingerprintSource,
	truncateUtf8,
} from "./checker.ts";
import type {
	LoadedSkill,
	SourceSkill,
	ValidatedItem,
	ValidatedSuite,
} from "./contracts.ts";
import {
	type BaselineScore,
	persistBaselineCheckpoint,
	persistScoreCache,
	readBaselineCheckpoint,
	readScoreCache,
	writePrivateText,
} from "./run-state.ts";

const READ_ONLY_TOOLS = ["read", "grep", "find", "ls"] as const;
export const TARGET_CALL_TIMEOUT_MS = 900_000;

type FrozenModel = { provider: string; id: string; thinking: string };

type TargetEvent = {
	type: string;
	toolCallId?: string;
	toolName?: string;
	args?: unknown;
	result?: { content?: Array<{ type?: string; text?: string }> };
	isError?: boolean;
	message?: {
		role?: string;
		stopReason?: string;
		content?: Array<{ type?: string; text?: string }>;
	};
};

export type TargetSession = {
	prompt: (
		text: string,
		options?: { expandPromptTemplates?: boolean },
	) => Promise<void>;
	subscribe: (listener: (event: TargetEvent) => void) => () => void;
	abort: () => Promise<void>;
	dispose: () => void;
};

export type TargetSdkSeam = {
	DefaultResourceLoader: new (
		options: Record<string, unknown>,
	) => {
		reload: () => Promise<void>;
	};
	SettingsManager: { inMemory: (settings: unknown) => unknown };
	SessionManager: { inMemory: (cwd: string) => unknown };
	createAgentSession: (options: Record<string, unknown>) => Promise<{
		session: TargetSession;
	}>;
};

export const defaultTargetSdk: TargetSdkSeam = {
	DefaultResourceLoader:
		DefaultResourceLoader as unknown as TargetSdkSeam["DefaultResourceLoader"],
	SettingsManager:
		SettingsManager as unknown as TargetSdkSeam["SettingsManager"],
	SessionManager: SessionManager as unknown as TargetSdkSeam["SessionManager"],
	createAgentSession:
		createAgentSession as unknown as TargetSdkSeam["createAgentSession"],
};

export async function promptTarget(
	target: TargetSession,
	prompt: string,
): Promise<void> {
	let timer: ReturnType<typeof setTimeout> | undefined;
	try {
		await Promise.race([
			target.prompt(prompt, { expandPromptTemplates: true }),
			new Promise<never>((_, reject) => {
				timer = setTimeout(() => {
					void target.abort().catch(() => {});
					reject(
						new Error(
							`target rollout timed out after ${TARGET_CALL_TIMEOUT_MS / 1000}s`,
						),
					);
				}, TARGET_CALL_TIMEOUT_MS);
			}),
		]);
	} finally {
		if (timer !== undefined) clearTimeout(timer);
	}
}

export type BaselineSeam = {
	createTarget: () => Promise<TargetSession>;
	executeChecker?: (options: {
		checkerPath: string;
		suitePath: string;
		input: string;
		expectedSuiteFingerprint?: string;
		signal?: AbortSignal;
	}) => Promise<CheckerResult>;
	scoreResponse?: (options: {
		item: ValidatedItem;
		response: string;
		input: string;
		signal?: AbortSignal;
	}) => Promise<CheckerResult>;
};

export class RolloutCancelledError extends Error {
	constructor() {
		super("baseline rollout cancelled");
	}
}

function bodyHash(body: string): string {
	return createHash("sha256").update(body, "utf8").digest("hex");
}

function idOrder(left: string, right: string): number {
	const leftPoints = Array.from(left);
	const rightPoints = Array.from(right);
	for (
		let index = 0;
		index < Math.min(leftPoints.length, rightPoints.length);
		index += 1
	) {
		const difference =
			(leftPoints[index]?.codePointAt(0) ?? 0) -
			(rightPoints[index]?.codePointAt(0) ?? 0);
		if (difference !== 0) return difference;
	}
	return leftPoints.length - rightPoints.length;
}

function textBlocks(
	content: Array<{ type?: string; text?: string }> | undefined,
	maximumBytes: number,
): string {
	let text = "";
	for (const block of content ?? []) {
		if (block.type !== "text" || typeof block.text !== "string") continue;
		text = truncateUtf8(`${text}${block.text}`, maximumBytes);
	}
	return text;
}

function evidenceFilename(id: string, hash?: string): string {
	const itemHash = createHash("sha256")
		.update(id, "utf8")
		.digest("hex")
		.slice(0, 16);
	return hash === undefined
		? `evidence-${itemHash}.json`
		: `evidence-${hash.slice(0, 16)}-${itemHash}.json`;
}

function pendingResponseFilename(
	id: string,
	hash?: string,
	cacheFilename?: string,
): string {
	const namespace = cacheFilename
		? `${createHash("sha256").update(cacheFilename).digest("hex").slice(0, 16)}-`
		: "";
	return evidenceFilename(id, hash).replace(
		/^evidence-/,
		`pending-response-${namespace}`,
	);
}

async function persistPendingResponse(
	directory: string,
	filename: string,
	response: string,
	input: string,
): Promise<void> {
	await writePrivateText(
		directory,
		filename,
		`${JSON.stringify({ version: 1, response, input })}\n`,
	);
}

async function readPendingResponse(
	directory: string,
	filename: string,
): Promise<{ response: string; input: string } | undefined> {
	try {
		const value: unknown = JSON.parse(
			await readFile(join(directory, filename), "utf8"),
		);
		if (
			typeof value !== "object" ||
			value === null ||
			Array.isArray(value) ||
			Object.keys(value).length !== 3
		)
			throw new Error("pending target response is malformed");
		const record = value as Record<string, unknown>;
		if (
			record.version !== 1 ||
			typeof record.response !== "string" ||
			Buffer.byteLength(record.response, "utf8") > 64 * 1024 ||
			typeof record.input !== "string" ||
			Buffer.byteLength(record.input, "utf8") > 1024 * 1024
		)
			throw new Error("pending target response is malformed");
		JSON.parse(record.input);
		return { response: record.response, input: record.input };
	} catch (error) {
		if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
		throw error;
	}
}

export async function writeCandidateSnapshot(options: {
	directory: string;
	source: SourceSkill;
	body?: string;
	filename?: string;
}): Promise<string> {
	return await writePrivateText(
		options.directory,
		options.filename ?? "baseline-snapshot.md",
		`${options.source.frontmatter}${options.body ?? options.source.body}`,
	);
}

export async function createIsolatedTargetSession(
	options: {
		cwd: string;
		agentDir: string;
		sourcePath: string;
		loadedSkill: LoadedSkill;
		candidatePath: string;
		model: FrozenModel;
		targetModel: unknown;
	},
	sdk: TargetSdkSeam,
): Promise<TargetSession> {
	const settingsManager = sdk.SettingsManager.inMemory({
		compaction: { enabled: false },
		retry: { enabled: false },
	});
	const loader = new sdk.DefaultResourceLoader({
		cwd: options.cwd,
		agentDir: options.agentDir,
		settingsManager,
		noExtensions: true,
		noSkills: true,
		noPromptTemplates: true,
		noThemes: true,
		noContextFiles: true,
		additionalSkillPaths: [options.sourcePath],
		skillsOverride: (base: {
			skills: Array<Record<string, unknown>>;
			diagnostics: unknown[];
		}) => {
			if (base.skills.length !== 1)
				throw new Error("isolated target must load exactly one source skill");
			const skill = base.skills[0];
			if (!skill)
				throw new Error("isolated target source skill is unavailable");
			return {
				skills: [
					{
						...skill,
						filePath: options.candidatePath,
						baseDir: options.loadedSkill.sourceInfo.baseDir ?? skill.baseDir,
						sourceInfo: options.loadedSkill.sourceInfo,
					},
				],
				diagnostics: base.diagnostics,
			};
		},
	});
	await loader.reload();
	const result = await sdk.createAgentSession({
		cwd: options.cwd,
		agentDir: options.agentDir,
		model: options.targetModel,
		thinkingLevel: options.model.thinking,
		tools: [...READ_ONLY_TOOLS],
		sessionManager: sdk.SessionManager.inMemory(options.cwd),
		settingsManager,
		resourceLoader: loader,
	});
	return result.session;
}

async function persistEvidence(
	directory: string,
	filename: string,
	input: string,
	result: CheckerResult,
): Promise<void> {
	await writePrivateText(
		directory,
		filename,
		`${JSON.stringify({ input: JSON.parse(input), result })}\n`,
	);
}

function cancelled(signal: AbortSignal | undefined): boolean {
	return signal?.aborted === true;
}

function assertCacheMatchesItems(
	scores: readonly BaselineScore[],
	items: readonly ValidatedItem[],
	label: string,
): void {
	const ids = new Set(items.map((item) => item.id));
	if (scores.some((score) => !ids.has(score.id)))
		throw new Error(`${label} contains scores outside the requested split`);
}

async function rehydrateEvidence(
	directory: string,
	score: BaselineScore,
): Promise<BaselineScore & { trajectory: unknown; checker: CheckerResult }> {
	const evidence: unknown = JSON.parse(
		await readFile(join(directory, score.evidenceFile), "utf8"),
	);
	if (
		typeof evidence !== "object" ||
		evidence === null ||
		Array.isArray(evidence)
	)
		throw new Error("cached rollout evidence is malformed");
	const { input, result } = evidence as { input?: unknown; result?: unknown };
	if (typeof input !== "object" || input === null || Array.isArray(input))
		throw new Error("cached rollout trajectory is malformed");
	if (typeof result !== "object" || result === null || Array.isArray(result))
		throw new Error("cached checker evidence is malformed");
	return { ...score, trajectory: input, checker: result as CheckerResult };
}

export async function runValidationBaseline(
	options: {
		directory: string;
		cwd: string;
		agentDir: string;
		sourcePath: string;
		sourceFingerprint?: string;
		source: SourceSkill;
		loadedSkill: LoadedSkill;
		model: FrozenModel;
		suite?: ValidatedSuite;
		items: readonly ValidatedItem[];
		body?: string;
		cacheFilename?: string;
		snapshotFilename?: string;
		baselineCheckpoint?: boolean;
		signal?: AbortSignal;
		onProgress?: (progress: {
			completed: number;
			total: number;
			mean?: number;
		}) => void | Promise<void>;
		onTargetCall?: () => void | Promise<void>;
		onCheckerCall?: () => void | Promise<void>;
	},
	seam: BaselineSeam,
): Promise<{ mean: number; completed: number; bodyHash: string }> {
	const body = options.body ?? options.source.body;
	const hash = bodyHash(body);
	const baselineCheckpoint =
		options.baselineCheckpoint ?? options.body === undefined;
	await writeCandidateSnapshot({
		directory: options.directory,
		source: options.source,
		body,
		filename: options.snapshotFilename,
	});
	const existing = baselineCheckpoint
		? await readBaselineCheckpoint(options.directory)
		: undefined;
	if (existing && existing.bodyHash !== hash)
		throw new Error("baseline checkpoint body does not match source");
	const cached = await readScoreCache(options.directory, options.cacheFilename);
	if (cached && cached.bodyHash !== hash)
		throw new Error("score cache body does not match candidate");
	const items = [...options.items].sort((left, right) =>
		idOrder(left.id, right.id),
	);
	assertCacheMatchesItems(cached?.scores ?? [], items, "score cache");
	assertCacheMatchesItems(existing?.scores ?? [], items, "baseline checkpoint");
	const scoreById = new Map<string, BaselineScore>();
	for (const score of cached?.scores ?? []) scoreById.set(score.id, score);
	for (const score of existing?.scores ?? []) scoreById.set(score.id, score);
	const checkpoint = async (
		stage: "baseline" | "baseline_complete" | "interrupted",
	) => {
		const scores = items
			.map((item) => scoreById.get(item.id))
			.filter((score): score is BaselineScore => score !== undefined);
		if (baselineCheckpoint)
			await persistBaselineCheckpoint(options.directory, {
				version: 1,
				stage,
				bodyHash: hash,
				completedItemIds: scores.map((score) => score.id),
				total: items.length,
				scores,
			});
		await options.onProgress?.({
			completed: scores.length,
			total: items.length,
			...(scores.length === 0
				? {}
				: {
						mean:
							scores.reduce((sum, score) => sum + score.score, 0) /
							scores.length,
					}),
		});
	};
	const revalidateSource = async () => {
		if (options.sourceFingerprint === undefined) return;
		if (
			fingerprintSource(await readFile(options.sourcePath)) !==
			options.sourceFingerprint
		)
			throw new Error("source fingerprint changed");
	};
	const scorePendingResponse = async (
		item: ValidatedItem,
		response: string,
		input: string,
	) => {
		await revalidateSource();
		await options.onCheckerCall?.();
		let result: CheckerResult;
		try {
			result = seam.scoreResponse
				? await seam.scoreResponse({
						item,
						response,
						input,
						signal: options.signal,
					})
				: await (() => {
						if (!seam.executeChecker || !options.suite)
							throw new Error("rollout requires a response scorer");
						return seam.executeChecker({
							checkerPath: options.suite.checkerPath,
							suitePath: options.suite.suitePath,
							input,
							...(options.suite.fingerprint === undefined
								? {}
								: {
										expectedSuiteFingerprint: options.suite.fingerprint,
									}),
							signal: options.signal,
						});
					})();
		} finally {
			await revalidateSource();
		}
		if (cancelled(options.signal)) throw new RolloutCancelledError();
		const score: BaselineScore = {
			id: item.id,
			score: result.score,
			passed: result.passed,
			...(result.feedback === undefined ? {} : { feedback: result.feedback }),
			evidenceFile: evidenceFilename(
				item.id,
				baselineCheckpoint ? undefined : hash,
			),
		};
		await persistEvidence(options.directory, score.evidenceFile, input, result);
		scoreById.set(item.id, score);
		const scores = items
			.map((candidate) => scoreById.get(candidate.id))
			.filter(
				(candidate): candidate is BaselineScore => candidate !== undefined,
			);
		await persistScoreCache(
			options.directory,
			{ version: 1, bodyHash: hash, scores },
			options.cacheFilename,
		);
		await checkpoint("baseline");
	};
	try {
		await checkpoint("baseline");
		for (const item of items) {
			if (cancelled(options.signal)) throw new RolloutCancelledError();
			if (scoreById.has(item.id)) continue;
			const pendingFilename = pendingResponseFilename(
				item.id,
				baselineCheckpoint ? undefined : hash,
				options.cacheFilename,
			);
			const pending = await readPendingResponse(
				options.directory,
				pendingFilename,
			);
			if (pending) {
				await scorePendingResponse(item, pending.response, pending.input);
				continue;
			}
			const target = await seam.createTarget();
			const assistantTexts: string[] = [];
			const startedCalls: Array<{
				id: string;
				name: string;
				input: unknown;
				outputText?: string;
				isError?: boolean;
			}> = [];
			const callsById = new Map<string, (typeof startedCalls)[number]>();
			let finalResponse: string | undefined;
			let abortPromise: Promise<void> | undefined;
			const requestAbort = () => {
				abortPromise ??= target.abort();
				return abortPromise;
			};
			const unsubscribe = target.subscribe((event) => {
				if (
					event.type === "tool_execution_start" &&
					event.toolCallId &&
					event.toolName
				) {
					const call = {
						id: event.toolCallId,
						name: event.toolName,
						input: event.args ?? {},
					};
					startedCalls.push(call);
					callsById.set(call.id, call);
					if (startedCalls.length > 64) {
						const dropped = startedCalls.shift();
						if (dropped) callsById.delete(dropped.id);
					}
				}
				if (event.type === "tool_execution_end" && event.toolCallId) {
					const call = callsById.get(event.toolCallId);
					if (call) {
						call.outputText = textBlocks(event.result?.content, 8 * 1024);
						call.isError = event.isError === true;
					}
				}
				if (event.type !== "message_end" || event.message?.role !== "assistant")
					return;
				const text = textBlocks(event.message.content, 8 * 1024);
				assistantTexts.push(text);
				if (assistantTexts.length > 64) assistantTexts.shift();
				const response = textBlocks(event.message.content, 64 * 1024);
				if (
					event.message.stopReason === "stop" ||
					event.message.stopReason === "length"
				) {
					finalResponse = response;
				} else {
					finalResponse = undefined;
				}
			});
			const abortListener = () => {
				void requestAbort();
			};
			options.signal?.addEventListener("abort", abortListener, { once: true });
			try {
				if (cancelled(options.signal)) {
					await requestAbort();
					throw new RolloutCancelledError();
				}
				await options.onTargetCall?.();
				if (cancelled(options.signal)) {
					await requestAbort();
					throw new RolloutCancelledError();
				}
				await promptTarget(
					target,
					`/skill:${options.source.name} ${item.prompt}`,
				);
				if (finalResponse === undefined) {
					if (cancelled(options.signal)) {
						await requestAbort();
						throw new RolloutCancelledError();
					}
					throw new Error(
						"target rollout has no final successful assistant message",
					);
				}
				const toolCalls = startedCalls
					.filter(
						(
							call,
						): call is (typeof startedCalls)[number] & {
							outputText: string;
							isError: boolean;
						} => call.outputText !== undefined && call.isError !== undefined,
					)
					.map(({ name, input: callInput, outputText, isError }) => ({
						name,
						input: callInput,
						outputText,
						isError,
					}));
				const input = buildCheckerInput({
					item,
					response: finalResponse,
					assistantTexts,
					toolCalls,
				});
				await persistPendingResponse(
					options.directory,
					pendingFilename,
					finalResponse,
					input,
				);
				if (cancelled(options.signal)) throw new RolloutCancelledError();
				await scorePendingResponse(item, finalResponse, input);
			} finally {
				options.signal?.removeEventListener("abort", abortListener);
				unsubscribe();
				await Promise.resolve(target.dispose());
			}
		}
	} catch (error) {
		if (error instanceof RolloutCancelledError || cancelled(options.signal)) {
			await checkpoint("interrupted");
			throw new RolloutCancelledError();
		}
		throw error;
	}
	const scores = items.map((item) => scoreById.get(item.id));
	if (scores.some((score) => score === undefined))
		throw new Error("baseline did not score every validation item");
	const completeScores = scores as BaselineScore[];
	const mean =
		completeScores.reduce((sum, score) => sum + score.score, 0) /
		completeScores.length;
	await checkpoint("baseline_complete");
	if (cancelled(options.signal)) {
		await checkpoint("interrupted");
		throw new RolloutCancelledError();
	}
	return { mean, completed: completeScores.length, bodyHash: hash };
}

export async function runSplitRollout(
	options: {
		directory: string;
		cwd: string;
		agentDir: string;
		sourcePath: string;
		sourceFingerprint?: string;
		source: SourceSkill;
		loadedSkill: LoadedSkill;
		model: FrozenModel;
		suite?: ValidatedSuite;
		items: readonly ValidatedItem[];
		body: string;
		split: "train" | "validation" | "test";
		signal?: AbortSignal;
		onProgress?: (progress: {
			completed: number;
			total: number;
			mean?: number;
		}) => void | Promise<void>;
		onTargetCall?: () => void | Promise<void>;
		onCheckerCall?: () => void | Promise<void>;
	},
	seam: BaselineSeam,
): Promise<{
	mean: number;
	completed: number;
	bodyHash: string;
	scores: BaselineScore[];
}> {
	const hash = bodyHash(options.body);
	const result = await runValidationBaseline(
		{
			...options,
			cacheFilename: `scores-${hash}-${options.split}.json`,
			snapshotFilename: `candidate-${hash}.md`,
			baselineCheckpoint: false,
		},
		seam,
	);
	const cache = await readScoreCache(
		options.directory,
		`scores-${hash}-${options.split}.json`,
	);
	if (!cache || cache.bodyHash !== hash)
		throw new Error("candidate rollout cache was not persisted");
	assertCacheMatchesItems(
		cache.scores,
		options.items,
		"candidate rollout cache",
	);
	const byId = new Map(cache.scores.map((score) => [score.id, score]));
	const ordered = options.items.map((item) => byId.get(item.id));
	if (ordered.some((score) => score === undefined))
		throw new Error(
			"candidate rollout cache did not score every requested split item",
		);
	return {
		...result,
		scores: await Promise.all(
			(ordered as BaselineScore[]).map(
				async (score) => await rehydrateEvidence(options.directory, score),
			),
		),
	};
}