import { createHash } from "node:crypto"; import { defineTool } from "@earendil-works/pi-coding-agent"; import { Type } from "typebox"; import { canonicalJson, type DeterministicCheck, defaultStructuredOutputSdk, type FrozenTask, type StructuredOutputSdkSeam, } from "./aftermath-mining.ts"; import type { CheckerResult } from "./checker.ts"; export type DeterministicCheckResult = { type: DeterministicCheck["type"]; passed: boolean; }; export type DeterministicScore = { score: number; passed: boolean; checks: DeterministicCheckResult[]; }; export function normalizeResponse(response: string): string { return response.replace(/\r\n?/g, "\n"); } function normalizedHeading(value: string): string { return value.trim().replace(/\s+/gu, " ").toLowerCase(); } function hasAtxHeading(response: string, expected: string): boolean { for (const line of normalizeResponse(response).split("\n")) { const match = /^(?:#{1,6})[\t ]+(.*)$/u.exec(line); if (!match) continue; const content = (match[1] ?? "").replace(/[\t ]*#+[\t ]*$/u, ""); if (normalizedHeading(content) === normalizedHeading(expected)) return true; } return false; } function evaluateCheck(response: string, check: DeterministicCheck): boolean { const normalized = normalizeResponse(response); if (check.type === "contains") { if (check.caseSensitive) return normalized.includes(check.value); return normalized.toLowerCase().includes(check.value.toLowerCase()); } if (check.type === "section_present") return hasAtxHeading(normalized, check.heading); const count = Array.from(normalized).length; return check.type === "min_chars" ? count >= check.count : count <= check.count; } /** Scores declaration-order local checks without invoking a model. */ export function evaluateDeterministicChecks( response: string, checks: readonly DeterministicCheck[], ): DeterministicScore { if (checks.length === 0) throw new Error("deterministic task requires checks"); const results = checks.map((check) => ({ type: check.type, passed: evaluateCheck(response, check), })); const passedCount = results.filter((result) => result.passed).length; return { score: passedCount / results.length, passed: passedCount === results.length, checks: results, }; } export function responseHash(response: string): string { return createHash("sha256") .update(normalizeResponse(response), "utf8") .digest("hex"); } const rubricOutput = defineTool({ name: "structured_output", label: "Structured output", description: "Return one rubric judgment as the final action.", parameters: Type.Object( { score: Type.Number(), passed: Type.Boolean(), rationale: Type.String(), }, { additionalProperties: false }, ), async execute(_id, params) { return { content: [{ type: "text" as const, text: "Rubric judgment received." }], details: params, terminate: true, }; }, }); export type RubricJudgeSession = { prompt: ( text: string, options?: { expandPromptTemplates?: boolean }, ) => Promise; subscribe: ( listener: (event: { type: string; toolName?: string; isError?: boolean; result?: { details?: unknown }; }) => void, ) => () => void; abort: () => Promise; dispose: () => void | Promise; }; export async function createRubricJudgeSession( options: { cwd: string; agentDir: string; model: { thinking: string }; targetModel: unknown; modelRegistry: unknown; }, sdk: StructuredOutputSdkSeam = defaultStructuredOutputSdk, ): Promise { 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, modelRegistry: options.modelRegistry as never, thinkingLevel: options.model.thinking as never, tools: ["structured_output"], customTools: [rubricOutput], sessionManager: sdk.SessionManager.inMemory(options.cwd), settingsManager, resourceLoader: loader, }); return result.session as unknown as RubricJudgeSession; } export class RubricJudgeCancelledError extends Error { constructor() { super("rubric judge cancelled"); } } export type RubricJudgeResult = { score: number; passed: boolean; rationale: string; cacheKey: string; }; function boundedResponse(response: string): string { const maximum = 64 * 1024; const marker = "…[truncated]"; if (Buffer.byteLength(response, "utf8") <= maximum) return normalizeResponse(response); let result = ""; for (const character of normalizeResponse(response)) { if ( Buffer.byteLength(result, "utf8") + Buffer.byteLength(character, "utf8") + Buffer.byteLength(marker, "utf8") > maximum ) break; result += character; } return `${result}${marker}`; } export function rubricCacheKey(taskId: string, response: string): string { return `${taskId}:${responseHash(boundedResponse(response))}`; } function judgeResult(value: unknown): Omit { if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("rubric judge output must be an object"); const record = value as Record; if ( Object.keys(record).length !== 3 || Object.keys(record).some( (key) => key !== "score" && key !== "passed" && key !== "rationale", ) ) throw new Error("rubric judge output has unknown fields"); if ( typeof record.score !== "number" || !Number.isFinite(record.score) || record.score < 0 || record.score > 1 || typeof record.passed !== "boolean" || typeof record.rationale !== "string" || Buffer.byteLength(record.rationale, "utf8") > 4096 ) throw new Error("rubric judge output is invalid"); return { score: record.score, passed: record.passed, rationale: record.rationale, }; } export function generatedTaskPrompt( task: Pick, ): string { return `${task.intent}\n\nContext:\n${task.context}`; } export function createGeneratedTaskScorer( tasks: readonly FrozenTask[], options: { judge?: ( task: FrozenTask, response: string, signal?: AbortSignal, ) => Promise>; } = {}, ): (options: { id: string; response: string; signal?: AbortSignal; }) => Promise { const byId = new Map(tasks.map((task) => [task.id, task])); return async ({ id, response, signal }) => { const task = byId.get(id); if (!task) throw new Error("generated task is not frozen"); if (task.checks) { const result = evaluateDeterministicChecks(response, task.checks); return { score: result.score, passed: result.passed, feedback: `${result.checks.filter((check) => check.passed).length}/${result.checks.length} deterministic checks passed`, checks: result.checks, }; } if (!task.rubric || !options.judge) throw new Error("rubric task requires a frozen judge"); const result = await options.judge(task, response, signal); return { score: result.score, passed: result.passed, feedback: result.rationale, }; }; } /** Runs one fresh, terminating structured-output rubric judgment. */ export async function runRubricJudge( task: Pick< FrozenTask, | "id" | "intent" | "context" | "sourceSessionIds" | "observedOutcome" | "rubric" >, response: string, seam: { createSession: () => Promise }, signal?: AbortSignal, onCall?: () => Promise, ): Promise { if (!task.rubric) throw new Error("rubric task requires a rubric"); const session = await seam.createSession(); const bounded = boundedResponse(response); const cacheKey = rubricCacheKey(task.id, response); let output: unknown; let outputs = 0; let abortPromise: Promise | undefined; const abort = () => (abortPromise ??= session.abort()); 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 abort(); signal?.addEventListener("abort", onAbort, { once: true }); try { if (signal?.aborted) { await abort(); throw new RubricJudgeCancelledError(); } await onCall?.(); if (signal?.aborted) { await abort(); throw new RubricJudgeCancelledError(); } await session.prompt( `Judge the frozen task response and terminate by calling structured_output exactly once with {"score":number,"passed":boolean,"rationale":string}.\ninput:${canonicalJson({ judgePromptVersion: 1, task, response: bounded })}`, { expandPromptTemplates: false }, ); // A valid terminating output is durable work: return it so callers can // persist the cache before their cancellation checkpoint. if (outputs === 1) return { ...judgeResult(output), cacheKey }; if (signal?.aborted) { await abort(); throw new RubricJudgeCancelledError(); } throw new Error("rubric judge must emit exactly one structured output"); } finally { signal?.removeEventListener("abort", onAbort); unsubscribe(); await Promise.resolve(session.dispose()); } }