import type { AssistantMessage } from "@earendil-works/pi-ai"; import { parseEnumeratedDecision } from "./utils.ts"; import type { Decision } from "./utils.ts"; export type JudgeErrorKind = | "provider-error" | "aborted" | "truncated" | "blocked-tool-request" | "empty-answer" | "malformed-findings" | "incomplete-response"; type CorrectableJudgeError = "blocked-tool-request" | "malformed-findings"; export interface JudgeResult { decisions: Decision[] | null; errorKind: JudgeErrorKind | null; // Saved as written in the log, never sent into the conversation. parseError: string | null; attemptedTools: string[]; /** The head says its end condition is met. Only heads with ends_when act on it. */ done?: true; } function boundedName(name: string): string { return typeof name === "string" && /^[a-zA-Z0-9_.:-]{1,64}$/.test(name) ? name : "(name omitted)"; } export function classifyJudgeResponse(response: AssistantMessage): JudgeResult { const attemptedTools = [...new Set(response.content.flatMap(block => block.type === "toolCall" ? [boundedName(block.name)] : []))].slice(0, 8); const failed = (errorKind: JudgeErrorKind): JudgeResult => ({ decisions: null, errorKind, parseError: null, attemptedTools }); if (response.stopReason === "error") return failed("provider-error"); if (response.stopReason === "aborted") return failed("aborted"); if (response.stopReason === "length") return failed("truncated"); if (response.stopReason !== "stop" && response.stopReason !== "toolUse") return failed("incomplete-response"); if (attemptedTools.length > 0) return failed("blocked-tool-request"); if (response.stopReason !== "stop") return failed("incomplete-response"); const text = response.content.flatMap(block => block.type === "text" ? [block.text] : []).join("\n"); if (!text.trim()) return failed("empty-answer"); const parsed = parseEnumeratedDecision(text); return { decisions: parsed.decisions, errorKind: parsed.error ? "malformed-findings" : null, parseError: parsed.error, attemptedTools, ...(parsed.done && { done: true }), }; } export const JUDGE_ERROR_DESCRIPTIONS: Record = { "provider-error": "provider returned an error", aborted: "provider stopped the response", truncated: "output was cut short; no findings or tool requests were accepted", "blocked-tool-request": "head requested tools it cannot run; nothing ran and there was no retry", "empty-answer": "answer text is missing (empty or thinking-only); expected findings JSON", "malformed-findings": "completed answer did not match the required findings JSON", "incomplete-response": "provider did not mark the response as finished", };