repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/overkill/lib/aftermath-mining.ts

Raw
File outline
import { createHash } from "node:crypto";
import {
	createAgentSession,
	DefaultResourceLoader,
	defineTool,
	SessionManager,
	SettingsManager,
} from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";

export type DeterministicCheck =
	| { type: "contains"; value: string; caseSensitive: boolean }
	| { type: "section_present"; heading: string }
	| { type: "min_chars"; count: number }
	| { type: "max_chars"; count: number };

export type FrozenTask = {
	id: string;
	intent: string;
	context: string;
	sourceSessionIds: string[];
	observedOutcome?: string;
	checks?: DeterministicCheck[];
	rubric?: string;
};

function bytes(value: string): number {
	return Buffer.byteLength(value, "utf8");
}

function exactObject(
	value: unknown,
	fields: readonly string[],
	label: string,
): Record<string, unknown> {
	if (typeof value !== "object" || value === null || Array.isArray(value))
		throw new Error(`${label} must be an object`);
	for (const field of Object.keys(value))
		if (!fields.includes(field))
			throw new Error(`${label} has unknown field: ${field}`);
	return value as Record<string, unknown>;
}

function boundedText(
	value: unknown,
	maximum: number,
	label: string,
	trim = false,
): string {
	if (typeof value !== "string") throw new Error(`${label} must be a string`);
	const normalized = value.replace(/\r\n?/g, "\n");
	const result = trim ? normalized.trim() : normalized;
	if (bytes(result) === 0 || bytes(result) > maximum)
		throw new Error(`${label} is out of bounds`);
	return result;
}

function canonicalize(value: unknown): unknown {
	if (Array.isArray(value)) return value.map(canonicalize);
	if (typeof value !== "object" || value === null) return value;
	return Object.fromEntries(
		Object.entries(value as Record<string, unknown>)
			.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
			.map(([key, child]) => [key, canonicalize(child)]),
	);
}

export function canonicalJson(value: unknown): string {
	return JSON.stringify(canonicalize(value));
}

function validateCheck(value: unknown): DeterministicCheck {
	const record = exactObject(
		value,
		["type", "value", "caseSensitive", "heading", "count"],
		"check",
	);
	if (record.type === "contains") {
		for (const key of Object.keys(record))
			if (key !== "type" && key !== "value" && key !== "caseSensitive")
				throw new Error("contains check has unknown field");
		if (typeof record.caseSensitive !== "boolean")
			throw new Error("contains case sensitivity is required");
		return {
			type: "contains",
			value: boundedText(record.value, 1024, "contains value", true),
			caseSensitive: record.caseSensitive,
		};
	}
	if (record.type === "section_present") {
		for (const key of Object.keys(record))
			if (key !== "type" && key !== "heading")
				throw new Error("section check has unknown field");
		return {
			type: "section_present",
			heading: boundedText(record.heading, 1024, "section heading", true),
		};
	}
	if (record.type === "min_chars" || record.type === "max_chars") {
		for (const key of Object.keys(record))
			if (key !== "type" && key !== "count")
				throw new Error("character check has unknown field");
		if (
			typeof record.count !== "number" ||
			!Number.isInteger(record.count) ||
			record.count < 0 ||
			record.count > 65_536
		)
			throw new Error("character count is invalid");
		return { type: record.type, count: record.count };
	}
	throw new Error("unknown deterministic check");
}

function taskPayload(task: Omit<FrozenTask, "id">): Record<string, unknown> {
	return {
		intent: task.intent,
		context: task.context,
		sourceSessionIds: [...task.sourceSessionIds].sort(),
		...(task.observedOutcome === undefined
			? {}
			: { observedOutcome: task.observedOutcome }),
		...(task.checks === undefined ? {} : { checks: task.checks }),
		...(task.rubric === undefined ? {} : { rubric: task.rubric }),
	};
}

export function taskId(task: Omit<FrozenTask, "id">): string {
	return `task-${createHash("sha256")
		.update(canonicalJson(taskPayload(task)), "utf8")
		.digest("hex")}`;
}

export function validateAndFreezeTasks(options: {
	proposals: readonly unknown[];
	harvestedSessionIds: ReadonlySet<string>;
	maximum?: number;
}): FrozenTask[] {
	const frozen = new Map<string, FrozenTask>();
	for (const proposal of options.proposals) {
		try {
			const record = exactObject(
				proposal,
				[
					"intent",
					"context",
					"sourceSessionIds",
					"observedOutcome",
					"checks",
					"rubric",
				],
				"task proposal",
			);
			const intent = boundedText(record.intent, 512, "intent", true);
			const context = boundedText(record.context, 4096, "context", true);
			if (!Array.isArray(record.sourceSessionIds))
				throw new Error("source session IDs are required");
			const sourceSessionIds = record.sourceSessionIds.map((id) => {
				const normalized = boundedText(id, 1024, "source session ID", true);
				if (!options.harvestedSessionIds.has(normalized))
					throw new Error("source session ID is unknown");
				return normalized;
			});
			const uniqueSourceIds = [...new Set(sourceSessionIds)].sort();
			if (
				sourceSessionIds.length !== uniqueSourceIds.length ||
				uniqueSourceIds.length < 2 ||
				uniqueSourceIds.length > 32
			)
				throw new Error("task is not recurring");
			const hasChecks = record.checks !== undefined;
			const hasRubric = record.rubric !== undefined;
			if (hasChecks === hasRubric)
				throw new Error("task requires checks xor rubric");
			const task: Omit<FrozenTask, "id"> = {
				intent,
				context,
				sourceSessionIds: uniqueSourceIds,
				...(record.observedOutcome === undefined
					? {}
					: {
							observedOutcome: boundedText(
								record.observedOutcome,
								2048,
								"observed outcome",
								true,
							),
						}),
			};
			if (hasChecks) {
				if (
					!Array.isArray(record.checks) ||
					record.checks.length < 1 ||
					record.checks.length > 8
				)
					throw new Error("checks are out of bounds");
				task.checks = record.checks.map(validateCheck);
			} else task.rubric = boundedText(record.rubric, 8192, "rubric", true);
			const id = taskId(task);
			frozen.set(id, { id, ...task });
		} catch {
			// One malformed proposal is discarded; a malformed model response shape
			// is rejected before this function is called.
		}
	}
	if (options.proposals.length > 0 && frozen.size === 0)
		throw new Error(
			`all ${options.proposals.length} miner proposals violated the required task schema`,
		);
	return [...frozen.values()]
		.sort((left, right) =>
			left.id < right.id ? -1 : left.id > right.id ? 1 : 0,
		)
		.slice(0, options.maximum ?? 30);
}

export function chunkConsecutively<T>(
	values: readonly T[],
	maximum = 20,
): T[][] {
	if (!Number.isInteger(maximum) || maximum < 1)
		throw new Error("invalid chunk size");
	const chunks: T[][] = [];
	for (let index = 0; index < values.length; index += maximum)
		chunks.push(values.slice(index, index + maximum));
	return chunks;
}

export function estimateMiningCalls(readableSessions: number): {
	mining: number;
	aggregation: number;
	total: number;
} {
	if (!Number.isInteger(readableSessions) || readableSessions < 0)
		throw new Error("readable session count is invalid");
	const mining = Math.ceil(readableSessions / 20);
	let aggregation = 0;
	for (let level = mining; level > 1; level = Math.ceil(level / 20))
		aggregation += Math.ceil(level / 20);
	return { mining, aggregation, total: mining + aggregation };
}

export type MiningSession = {
	prompt: (
		text: string,
		options?: { expandPromptTemplates?: boolean },
	) => Promise<void>;
	subscribe: (
		listener: (event: {
			type: string;
			toolName?: string;
			result?: { details?: unknown };
			isError?: boolean;
		}) => void,
	) => () => void;
	abort: () => Promise<void>;
	dispose: () => void | Promise<void>;
};

export type StructuredOutputSdkSeam = {
	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: MiningSession }>;
};

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

const deterministicCheck = Type.Union([
	Type.Object(
		{
			type: Type.Literal("contains"),
			value: Type.String(),
			caseSensitive: Type.Boolean(),
		},
		{ additionalProperties: false },
	),
	Type.Object(
		{ type: Type.Literal("section_present"), heading: Type.String() },
		{ additionalProperties: false },
	),
	Type.Object(
		{ type: Type.Literal("min_chars"), count: Type.Integer() },
		{ additionalProperties: false },
	),
	Type.Object(
		{ type: Type.Literal("max_chars"), count: Type.Integer() },
		{ additionalProperties: false },
	),
]);

const taskFields = {
	intent: Type.String(),
	context: Type.String(),
	sourceSessionIds: Type.Array(Type.String(), { minItems: 2, maxItems: 32 }),
	observedOutcome: Type.Optional(Type.String()),
};

const taskProposal = Type.Union([
	Type.Object(
		{
			...taskFields,
			checks: Type.Array(deterministicCheck, { minItems: 1, maxItems: 8 }),
		},
		{ additionalProperties: false },
	),
	Type.Object(
		{ ...taskFields, rubric: Type.String() },
		{ additionalProperties: false },
	),
]);

const miningOutput = defineTool({
	name: "structured_output",
	label: "Structured output",
	description: "Return exact recurring task proposals as the final action.",
	parameters: Type.Object(
		{ tasks: Type.Array(taskProposal) },
		{ additionalProperties: false },
	),
	async execute(_id, params) {
		return {
			content: [
				{ type: "text" as const, text: "Structured mining output received." },
			],
			details: params,
			terminate: true,
		};
	},
});

export async function createMiningSession(
	options: {
		cwd: string;
		agentDir: string;
		model: { thinking: string };
		targetModel: unknown;
	},
	sdk: StructuredOutputSdkSeam = defaultStructuredOutputSdk,
): Promise<MiningSession> {
	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,
	});
	await loader.reload();
	const result = await sdk.createAgentSession({
		cwd: options.cwd,
		agentDir: options.agentDir,
		model: options.targetModel as never,
		thinkingLevel: options.model.thinking as never,
		tools: ["structured_output"],
		customTools: [miningOutput],
		sessionManager: sdk.SessionManager.inMemory(options.cwd),
		settingsManager,
		resourceLoader: loader,
	});
	return result.session as unknown as MiningSession;
}

const MINING_ATTEMPTS = 2;

export class MiningOutputError extends Error {}

async function structuredTasks(
	session: MiningSession,
	prompt: string,
	maximum: number,
	signal?: AbortSignal,
	onCall?: () => Promise<void>,
): Promise<unknown[]> {
	let output: unknown;
	let outputs = 0;
	const unsubscribe = session.subscribe((event) => {
		if (
			event.type === "tool_execution_end" &&
			event.toolName === "structured_output" &&
			!event.isError
		) {
			outputs += 1;
			output = event.result?.details;
		}
	});
	const onAbort = () => void session.abort();
	signal?.addEventListener("abort", onAbort, { once: true });
	try {
		if (signal?.aborted) throw new Error("mining cancelled");
		await onCall?.();
		if (signal?.aborted) throw new Error("mining cancelled");
		await session.prompt(prompt, { expandPromptTemplates: false });
		if (signal?.aborted) throw new Error("mining cancelled");
		try {
			if (
				outputs !== 1 ||
				typeof output !== "object" ||
				output === null ||
				Array.isArray(output)
			)
				throw new Error(
					`miner emitted ${outputs} successful structured outputs; expected exactly one`,
				);
			const record = exactObject(output, ["tasks"], "miner output");
			if (!Array.isArray(record.tasks) || record.tasks.length > maximum)
				throw new Error("miner output task cap exceeded");
			const json = canonicalJson(output);
			if (bytes(json) > (maximum === 10 ? 64 * 1024 : 128 * 1024))
				throw new Error("miner output byte cap exceeded");
			return record.tasks;
		} catch (error) {
			throw new MiningOutputError(
				error instanceof Error ? error.message : String(error),
			);
		}
	} finally {
		signal?.removeEventListener("abort", onAbort);
		unsubscribe();
		await Promise.resolve(session.dispose());
	}
}

async function structuredTasksWithRetry(options: {
	createSession: () => Promise<MiningSession>;
	prompt: string;
	maximum: number;
	phase: "mining" | "aggregation";
	signal?: AbortSignal;
	onCall?: (
		phase: "mining" | "aggregation",
		attempt: number,
		maximumAttempts: number,
	) => Promise<void>;
}): Promise<unknown[]> {
	for (let attempt = 1; attempt <= MINING_ATTEMPTS; attempt += 1) {
		try {
			return await structuredTasks(
				await options.createSession(),
				`${options.prompt}\nEvery task must contain intent, context, 2–32 exact sourceSessionIds copied from the input, optional observedOutcome, and exactly one of: rubric string; checks array using contains {value, caseSensitive}, section_present {heading}, min_chars {count}, or max_chars {count}. Preserve this exact schema during aggregation. You must call structured_output exactly once as your final action; never print JSON as text. If no valid recurring proposal exists, call it with an empty tasks array.${attempt > 1 ? " This is a retry because the previous session ended without one valid structured_output call." : ""}`,
				options.maximum,
				options.signal,
				options.onCall
					? async () =>
							await options.onCall?.(options.phase, attempt, MINING_ATTEMPTS)
					: undefined,
			);
		} catch (error) {
			if (!(error instanceof MiningOutputError) || attempt === MINING_ATTEMPTS)
				throw error;
		}
	}
	throw new Error("mining retry state is unreachable");
}

export async function mineTaskProposals(options: {
	digests: readonly unknown[];
	target: { name: string; description: string };
	createSession: () => Promise<MiningSession>;
	signal?: AbortSignal;
	onChunk?: (index: number, output: unknown[]) => Promise<void>;
	onLevel?: (level: number, index: number, output: unknown[]) => Promise<void>;
	onCall?: (
		phase: "mining" | "aggregation",
		attempt: number,
		maximumAttempts: number,
	) => Promise<void>;
	completedChunks?: ReadonlyMap<number, unknown[]>;
	completedLevels?: ReadonlyMap<number, unknown[][]>;
}): Promise<unknown[]> {
	const target = `targetSkill:${canonicalJson(options.target)}\nPropose only recurring tasks whose correct completion requires this target skill's described capability. Omit generic workflows and tasks belonging to other skills.`;
	let outputs: unknown[][] = [];
	for (const [index, group] of chunkConsecutively(
		options.digests,
		20,
	).entries()) {
		const saved = options.completedChunks?.get(index);
		const output =
			saved ??
			(await structuredTasksWithRetry({
				createSession: options.createSession,
				prompt: `phase:mine\n${target}\nExtract no more than 10 recurring, checkable task proposals.\ndigests:${canonicalJson(group)}`,
				maximum: 10,
				phase: "mining",
				signal: options.signal,
				onCall: options.onCall,
			}));
		if (!saved) await options.onChunk?.(index, output);
		outputs.push(output);
	}
	for (let level = 0; outputs.length > 1; level += 1) {
		const next: unknown[][] = [];
		for (const [index, group] of chunkConsecutively(outputs, 20).entries()) {
			const saved = options.completedLevels?.get(level)?.[index];
			const output =
				saved ??
				(await structuredTasksWithRetry({
					createSession: options.createSession,
					prompt: `phase:aggregate\n${target}\nConsolidate at most 30 recurring task proposals. Remove anything irrelevant to the target skill.\noutputs:${canonicalJson(group)}`,
					maximum: 30,
					phase: "aggregation",
					signal: options.signal,
					onCall: options.onCall,
				}));
			if (!saved) await options.onLevel?.(level, index, output);
			next.push(output);
		}
		outputs = next;
	}
	return outputs[0] ?? [];
}

export function assignSplits(tasks: readonly FrozenTask[]): {
	train: string[];
	validation: string[];
	test: string[];
} {
	if (tasks.length === 0) return { train: [], validation: [], test: [] };
	const sorted = [...tasks]
		.map((task) => ({
			id: task.id,
			digest: createHash("sha256").update(`split\0${task.id}`, "utf8").digest(),
		}))
		.sort(
			(left, right) =>
				Buffer.compare(left.digest, right.digest) ||
				(left.id < right.id ? -1 : left.id > right.id ? 1 : 0),
		);
	const [first, second, third] = sorted;
	if (!first) throw new Error("task split is unavailable");
	const splits = {
		train: [first.id],
		validation: second ? [second.id] : [],
		test: third ? [third.id] : [],
	};
	for (const item of sorted.slice(3)) {
		const byte = item.digest.at(0);
		if (byte === undefined) throw new Error("invalid split digest");
		const bucket = byte % 5;
		if (bucket <= 2) splits.train.push(item.id);
		else if (bucket === 3) splits.validation.push(item.id);
		else splits.test.push(item.id);
	}
	return splits;
}