/** * Pure helpers for hydra observations. * Extracted for testability; no pi runtime or I/O dependencies. */ import type { Message } from "@earendil-works/pi-ai"; // A head's feedback reaches the agent at its next step, or starts a turn if idle. const HEAD_DELIVERIES = ["steer"] as const; // What a head may decide: noop sends nothing. const HEAD_ACTIONS = ["noop", ...HEAD_DELIVERIES] as const; // note is Hydra's own route and never a head's choice: the finding is added to // the conversation without starting a turn (during shutdown, and for reviews of // a cancelled run). // print is deprecated: retained internally, but no head may choose it. export const DELIVERY_ACTIONS = [...HEAD_DELIVERIES, "note", "print"] as const; export type DeliveryAction = (typeof DELIVERY_ACTIONS)[number]; export type Action = "noop" | DeliveryAction; // complete_observation calls noop "none". export const OBSERVATION_DELIVERIES = ["none", ...HEAD_DELIVERIES] as const; export type ObservationDelivery = (typeof OBSERVATION_DELIVERIES)[number]; export const HEAD_OPERATIONS = ["add", "remove"] as const; // How long an added head lives: ongoing checks after every response until it // is removed or its end condition is met; once makes exactly one check. export const HEAD_LIFETIMES = ["ongoing", "once"] as const; export type HeadLifetimeName = (typeof HEAD_LIFETIMES)[number]; export type HeadOperation = (typeof HEAD_OPERATIONS)[number]; export interface DeliveryRecord { head: string; delivery: DeliveryAction; message: string; } export interface DeliveryContext { lastByThisHead: Omit | null; pending: DeliveryRecord[]; } export interface PersistedDelivery extends DeliveryRecord { timestamp: number; } export interface Decision { action: Action; reason: string; message: string; } /** * Heads say `none`, the internals say `noop`. The two names exist because the * internal one came first and the public one reads better; they mean the same * thing. * * The message rules are enforced here rather than merely asked for in the * prompt: `none` must carry an empty message, and anything that is actually * delivered must carry a real one. */ export function decisionFromCompletion(delivery: ObservationDelivery, message: string): Decision { if (delivery === "none") { if (message !== "") { throw new Error('complete_observation with delivery "none" requires message to be exactly empty'); } return { action: "noop", reason: "observation completed", message: "" }; } const normalized = message.trim(); if (normalized.length === 0) { throw new Error(`complete_observation with delivery "${delivery}" requires a non-empty message`); } return { action: delivery, reason: "observation completed", message: normalized }; } /** * Adding or removing a head is always reported, because it is a record of what * happened rather than an opinion the head may keep to itself. What changed is * written here so a head cannot misreport it; the head only supplies the * reason. */ export function formatHeadManagementReceipt(operation: HeadOperation, head: string, message: string, lifetime?: string): string { const name = head.trim(); const explanation = message.trim(); if (name.length === 0) { throw new Error("manage_heads requires a non-empty head"); } if (explanation.length === 0) { throw new Error("manage_heads requires a non-empty message explaining the change"); } return `${operation === "add" ? "Added" : "Removed"} ${name}${lifetime ? ` ${lifetime}` : ""} — ${explanation}`; } /** An Anthropic acting head's answer: its decision, and whether it says done. */ export type ParsedDecision = Decision & { done?: true }; function asDecision(value: unknown): ParsedDecision | null { if (typeof value !== "object" || value === null) { return null; } const obj = value as { action?: unknown; reason?: unknown; message?: unknown; done?: unknown }; if (typeof obj.action !== "string" || !(HEAD_ACTIONS as readonly string[]).includes(obj.action)) { return null; } if (obj.done !== undefined && typeof obj.done !== "boolean") { return null; } const done = obj.done === true ? { done: true as const } : {}; const action = obj.action as Action; const reason = typeof obj.reason === "string" ? obj.reason.slice(0, 200) : ""; const message = typeof obj.message === "string" ? obj.message.trim().slice(0, 500) : ""; // A delivery with nothing to deliver is recorded as the noop it is, so // stats never count a delivery that said nothing. if (action !== "noop" && message === "") { return { action: "noop", reason: reason ? `${reason} (empty message)` : "empty message", message: "", ...done }; } return { action, reason, message, ...done }; } function tryParseDecision(text: string): ParsedDecision | null | undefined { try { return asDecision(JSON.parse(text)); } catch (error) { if (error instanceof SyntaxError) return undefined; throw error; } } /** * Anthropic heads hand back a small blob of JSON. OpenAI heads call the hydra * tool instead, so this is not used there. */ export function parseDecision(text: string): ParsedDecision | null { const cleaned = text .replace(/^```(?:json)?\s*\n?/i, "") .replace(/\n?```\s*$/, "") .trim(); const direct = tryParseDecision(cleaned); if (direct !== undefined) return direct; // Models sometimes wrap one decision in prose. Never salvage a nested // decision from an invalid answer, or pick one of several decisions. let start = cleaned.indexOf("{"); if (start === -1) return null; let decision: ParsedDecision | undefined; let depth = 0; let quoted = false; let escaped = false; for (let i = start; i < cleaned.length; i++) { const char = cleaned[i]; if (quoted) { if (escaped) escaped = false; else if (char === "\\") escaped = true; else if (char === '"') quoted = false; } else if (char === '"') { quoted = true; } else if (char === "{") { depth++; } else if (char === "}" && --depth === 0) { const parsed = tryParseDecision(cleaned.slice(start, i + 1)); if (decision === undefined) { if (!parsed) return null; decision = parsed; } else if (parsed !== undefined) { return null; } start = cleaned.indexOf("{", i + 1); if (start === -1) return decision; i = start - 1; } } return decision ?? null; } /** * Record a delivery key, evicting the oldest once the set exceeds max. * Returns false when the key was already delivered. */ export function rememberDelivery(delivered: Set, key: string, max: number): boolean { if (delivered.has(key)) { return false; } delivered.add(key); if (delivered.size > max) { delivered.delete(delivered.values().next().value as string); } return true; } export interface ObservationUsage { input: number; output: number; cacheRead: number; cacheWrite: number; cost: number; } /** * One observation can be several model calls: a judging head makes one, an * acting head one per turn of its loop. * * Costs and tokens add up across all of them. The cache hit rate comes from * the first call alone, because that is the one that should be almost entirely * a cache read. Later calls in a loop are supposed to pay for the work added * since, so including them would hide a real regression in an average. */ export function summarizeLoopUsage(usages: ObservationUsage[]): ObservationUsage & { hitRatio: number } { const total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }; for (const usage of usages) { total.input += usage.input; total.output += usage.output; total.cacheRead += usage.cacheRead; total.cacheWrite += usage.cacheWrite; total.cost += usage.cost; } const first = usages[0]; const readable = first ? first.input + first.cacheRead + first.cacheWrite : 0; return { ...total, hitRatio: readable > 0 ? (first.cacheRead / readable) * 100 : 0 }; } /** Parse a user-supplied head list ("quality,security" or "quality security"). */ export function parseHeadList(value: string): string[] { return [...new Set(value.split(/[\s,]+/).map((name) => name.trim()).filter((name) => name.length > 0))]; } export interface HeadDefinition { name: string; description: string; /** * Which tools the head may run. Undefined means every tool the agent has. * An empty array means none, so the head can only judge. */ tools?: string[]; /** Switches itself on at session start, unless a flag or saved set says otherwise. */ autostart?: boolean; prompt: string; } /** * Written into the session so the active heads come back after a resume or a * branch switch. A --hydra-heads flag wins over what was saved, because what * the user just typed beats what they wanted last time. Heads marked * autostart seed a session that has neither. `lenses` and `lens` are the old * names for the same thing, still read so old sessions load. */ export interface HydraConfig { heads: string[]; /** What the add call said about active heads without a file or with an end condition. */ added?: Record; lenses?: string[]; lens?: string; } export function isValidHeadName(name: string): boolean { return /^[a-z0-9][a-z0-9-]*$/.test(name) && name !== "none"; } /** * A file missing `name:` or `description:` is skipped rather than guessed at, * and the returned error becomes the warning the user sees. * * The head is named by what is inside the file, not by the filename, so * renaming a file does not quietly create a different head. */ export function parseHeadFile(rawContent: string): { head: HeadDefinition } | { error: string } { const content = rawContent.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n"); const frontmatter = content.match(/^---\n([\s\S]*?)\n---\n?/); if (!frontmatter) { return { error: "no frontmatter (name: and description: are required)" }; } let name: string | undefined; let description: string | undefined; let tools: string[] | undefined; let autostart: boolean | undefined; for (const line of frontmatter[1].split("\n")) { if (/^\s*- /.test(line)) { // Written as a bullet list, the line above would read as empty and // the head would silently lose all its tools. Better to complain. return { error: `block-style lists are not supported; write "tools: read, write" on one line` }; } if (line.startsWith("name:")) { name = line.slice("name:".length).trim(); } else if (line.startsWith("description:")) { description = line.slice("description:".length).trim(); } else if (line.startsWith("tools:")) { // Writing "tools:" with nothing after it means no tools at all. // Leaving the line out entirely means every tool. Those are // opposite answers, so they must never be treated as the same. const value = line.slice("tools:".length).trim().replace(/^\[/, "").replace(/\]$/, ""); tools = value === "" ? [] : parseHeadList(value); } else if (line.startsWith("autostart:")) { const value = line.slice("autostart:".length).trim(); if (value !== "true" && value !== "false") { return { error: `invalid autostart "${value}" (expected: true, false)` }; } autostart = value === "true" || undefined; } else if (line.trim() !== "") { // A misspelled or retired key would otherwise change nothing // without anyone noticing. return { error: `unknown key "${line.split(":")[0].trim()}" (allowed: name, description, tools, autostart)` }; } } if (!name) { return { error: "missing name:" }; } if (!isValidHeadName(name)) { return { error: `invalid name "${name}" (lowercase kebab-case, "none" is reserved)` }; } if (!description) { return { error: "missing description:" }; } const prompt = content.slice(frontmatter[0].length).trim(); if (prompt.length === 0) { return { error: "missing instruction body" }; } return { head: { name, description, tools, autostart, prompt } }; } /** Whether a head's tools allowance lets it act: undefined means all tools. */ export function headActs(tools: string[] | undefined): boolean { return tools === undefined || tools.length > 0; } /** * Whether the head's instruction and the rules for answering are sent as two * messages or one (the rules as a developer message), for every head. Decided * by measurement, not taste. * * Splitting them helped on both OpenAI routes: on Codex heads followed * instructions better and answered faster, and with combined messages GPT-6 * heads on Codex and ChatGPT sign-in often took over the main assistant's task * and called its tools instead of answering (docs/providers.md). On Anthropic * splitting made no overall difference and made Sonnet worse, and the ordering * that might have fixed that is not allowed there, so Anthropic keeps them * together. * * ds4 also keeps them together. For DeepSeek V4 Flash its server moves every * system and developer message to the top of the prompt * (render_deepseek_chat_prompt_text in antirez/ds4's ds4_server.c), so a * split head's prompt stops matching the main assistant's right after the * system prompt and re-reads the whole conversation on every check. Split * heads there also called the main assistant's tools far more often * (docs/providers.md#ds4). */ export function usesSplitObservationHandoff(api: string | undefined, provider?: string): boolean { return api !== undefined && api !== "anthropic-messages" && provider !== "ds4"; } /** * Whether a head finishes its check by calling the `hydra` tool. Heads with * tools do on the routes that split the handoff; everywhere else they answer * with JSON (docs/providers.md#completion-channels). */ export function finishesThroughHydraTool(tools: string[] | undefined, api: string | undefined, provider?: string): boolean { return headActs(tools) && usesSplitObservationHandoff(api, provider); } export interface ObservationProtocolOptions { /** Which heads are on. Only shown to a head allowed to change that. */ activeHeads?: readonly string[]; /** What has already been delivered, so a head does not repeat it. */ deliveryContext?: DeliveryContext; /** The condition after which this head ends itself, if it has one. */ endsWhen?: string; } // Only heads with an end condition are told about done; for every other head // the word appears nowhere, so it cannot be mistaken for "this check is over". function endConditionNote(endsWhen: string | undefined, how: string): string { return endsWhen === undefined ? "" : ` This head ends when: ${endsWhen}. If that is true now, ${how}; otherwise leave done out.`; } const STEER_ONLY_DECISION_SHAPE = '{"action":"noop|steer","reason":"≤120 chars","message":"≤240 chars, empty if noop"}'; const ENUMERATED_DECISION_SHAPE = '{"findings":[{"action":"steer","reason":"≤120 chars","message":"≤240 chars"}]}'; const MANAGEMENT_NOTE = "A successful manage_heads change automatically tells the main assistant, with your explanation. Do not repeat it in your final message."; function toolAllowance(tools: string[] | undefined): string { return tools === undefined ? "the available tools" : `only these tools: ${tools.join(", ")}`; } export const OBSERVER_DELIVERY_GUIDANCE = 'Use "steer" when the main assistant needs the feedback, even if it can wait. The message reaches it before its next model request without stopping its work.'; export const OBSERVER_GUIDANCE = "You are reviewing the main assistant's work. You are not the main assistant; it keeps working on its own. Do not continue its task or answer for it. This head's instructions define what to check and how much to report. Follow them. The main assistant may have moved on since this copy of the conversation was taken. Do not repeat its plan or doubts, or suggest work it already plans to do unless the plan itself is the problem. Support each finding with a short quote or exact reference. If evidence is missing, say what is missing; that alone does not prove a problem."; // The messages a head's loop sends to the model. The loop only holds plain // model messages plus Pi's system note with the head's tool list. Anthropic // needs that note: with a subscription login Pi sends Claude Code tool names // ("Edit") and reads the note to map replies back. On Codex it would add a // tool list to the head's request, so it is dropped there. Anything else is // new from Pi: it is dropped too, since Pi forbids throwing here, but reported, // because dropping the note silently once broke every Anthropic head. export function headLoopMessages( messages: readonly T[], keepSystemNote: boolean, onUnexpected: (role: string) => void, ): Message[] { return messages.filter((message): message is T & Message => { if (message.role === "user" || message.role === "assistant" || message.role === "toolResult") return true; if (message.role === "system") return keepSystemNote; onUnexpected(message.role); return false; }); } // Marks the head's own instructions. Without it, a Codex head, which gets // them as a separate message, took them for the user's latest request. export function headInstructions(instruction: string): string { return `HEAD INSTRUCTIONS: ${instruction}`; } export const REPORTING_GUIDANCE = "Report only what the main assistant needs to know or act on, such as a project file you created or changed. Routine work you repeat on every check, such as keeping notes, logs or scores, is not news; don't report it."; function hydraSnapshot(tools: string[] | undefined, activeHeads: readonly string[] | undefined): string { if (activeHeads === undefined || !tools?.includes("hydra")) { return ""; } return ` Active heads when this check started: ${activeHeads.join(", ") || "none"}. If a later hydra tool result differs, use that newer result.`; } export const FOLLOW_UP_GUIDANCE = "Compare feedback about the same issue. Do not repeat feedback still waiting for delivery or a problem that is already fixed. A problem that remains does not prove the feedback was ignored. Follow up only with evidence that the problem still applies after checking the visible response, or with new evidence that changes the finding. Follow this head's rules on repeating feedback too."; /** * What a head is told about an earlier delivery leaves out how it was routed, * and says only who received it. * * Hydra's own note route is never a head's choice. Naming it in a record would * put a choice in front of the model that it cannot make. Naming the recipient * instead tells the head what it needs for a follow-up. */ function enumeratedDeliveryContext(context: DeliveryContext): string { // Deprecated print receipts still describe feedback only the user saw. const recipient = (delivery: Action): "user" | "agent" => (delivery === "print" ? "user" : "agent"); const visible = { lastByThisHead: context.lastByThisHead === null ? null : { recipient: recipient(context.lastByThisHead.delivery), message: context.lastByThisHead.message, }, pending: context.pending.map((item) => ({ head: item.head, recipient: recipient(item.delivery), message: item.message, })), }; return `Earlier feedback: ${JSON.stringify(visible)}. lastByThisHead is this head's last delivered message; recipient says who received it. Messages in pending have not reached the main assistant yet. ${FOLLOW_UP_GUIDANCE}`; } // `deliveryGuidance` says what steer does on the host running the head; // a host whose delivery differs from pi's passes its own so heads are not told otherwise. function enumeratedDecisionProtocol(head: string, deliveryGuidance: string, endsWhen: string | undefined): string { return `Reply with one JSON object, nothing else: ${ENUMERATED_DECISION_SHAPE} Return one entry for each finding you choose to report under this head's instructions, or an empty findings array if there are none.${endConditionNote(endsWhen, 'add "done": true to the JSON object')} ${deliveryGuidance} You cannot use tools, even if their definitions are visible. You get one model call, with no retry or further turn. Do not start message with [pi-hydra ${head}].`; } /** The answering rules plus what has already been delivered, sent separately. */ export function buildEnumeratedJudgeObservationEnvelope( head: string, context: DeliveryContext, deliveryGuidance: string = OBSERVER_DELIVERY_GUIDANCE, endsWhen?: string, ): string { return `${OBSERVER_GUIDANCE} The previous user message contains all instructions for the ${head} head. ${enumeratedDeliveryContext(context)} ${enumeratedDecisionProtocol(head, deliveryGuidance, endsWhen)}`; } /** The same, folded into one message with the instruction. */ export function buildEnumeratedJudgeObservationPrompt( head: string, instruction: string, context: DeliveryContext, deliveryGuidance: string = OBSERVER_DELIVERY_GUIDANCE, endsWhen?: string, ): string { return `${OBSERVER_GUIDANCE} ${headInstructions(instruction)} ${enumeratedDeliveryContext(context)} ${enumeratedDecisionProtocol(head, deliveryGuidance, endsWhen)}`; } export interface EnumeratedDecisionResult { decisions: Decision[] | null; error: string | null; /** The head says its end condition is met. Only heads with ends_when act on it. */ done?: true; } /** * Groups a head's numbered findings for delivery. The deprecated print * grouping remains alongside steer, though heads can no longer select it. * A user-only finding never goes into the agent's context. */ export function parseEnumeratedDecision(text: string): EnumeratedDecisionResult { const fenced = text.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i); let value: unknown; try { value = JSON.parse((fenced ? fenced[1] : text).trim()); } catch { return { decisions: null, error: "completion must be one JSON object" }; } if (typeof value !== "object" || value === null || !Array.isArray((value as { findings?: unknown }).findings)) { return { decisions: null, error: "completion requires a findings array" }; } const doneValue = (value as { done?: unknown }).done; if (doneValue !== undefined && typeof doneValue !== "boolean") { return { decisions: null, error: "done must be true or false" }; } const done = doneValue === true ? { done: true as const } : {}; const findings: Decision[] = []; for (const [index, item] of (value as { findings: unknown[] }).findings.entries()) { if (typeof item !== "object" || item === null) { return { decisions: null, error: `finding ${index + 1} must be an object` }; } const candidate = item as { action?: unknown; reason?: unknown; message?: unknown }; if (typeof candidate.action !== "string" || !(HEAD_DELIVERIES as readonly string[]).includes(candidate.action)) { return { decisions: null, error: `finding ${index + 1} has invalid action ${JSON.stringify(candidate.action)}` }; } const message = typeof candidate.message === "string" ? candidate.message.trim().slice(0, 500) : ""; if (message.length === 0) { return { decisions: null, error: `finding ${index + 1} requires a non-empty message` }; } findings.push({ action: candidate.action as (typeof HEAD_DELIVERIES)[number], reason: typeof candidate.reason === "string" ? candidate.reason.slice(0, 200) : "", message, }); } if (findings.length === 0) { return { decisions: [{ action: "noop", reason: "no findings", message: "" }], error: null, ...done }; } // Deprecated print grouping is retained, though heads cannot select it. const batch = (action: "print" | "steer", selected: Decision[]): Decision => ({ action, reason: selected .map((finding) => finding.reason) .filter(Boolean) .join(" | "), message: selected.map((finding) => finding.message).join(" | "), }); const prints = findings.filter((finding) => finding.action === "print"); const agent = findings.filter((finding) => finding.action === "steer"); const decisions: Decision[] = []; if (prints.length > 0) { decisions.push(batch("print", prints)); } if (agent.length > 0) { decisions.push(batch("steer", agent)); } return { decisions, error: null, ...done, }; } function actingDeliveryContext(context: DeliveryContext | undefined): string { return context === undefined ? "" : ` ${enumeratedDeliveryContext(context)}`; } /** * On Anthropic the head writes its decision as JSON instead of calling a tool. * Tool calls were measured costing noticeably more output and time, even for * heads with no tools to use, while the JSON came back reliably. * * This is only about how the decision comes back. Doing actual work, and * adding or removing heads, still goes through tools. */ export function buildAnthropicObservationPrompt( head: string, instruction: string, tools: string[] | undefined, options: ObservationProtocolOptions = {}, ): string { return `${OBSERVER_GUIDANCE}${hydraSnapshot(tools, options.activeHeads)} You may use ${toolAllowance(tools)} to check facts or do the work this head's instructions ask for. The main assistant does not see your tool calls or their results. manage_heads is available only if hydra is among your allowed tools. ${MANAGEMENT_NOTE} Successfully removing your own head ends this check. ${REPORTING_GUIDANCE}${actingDeliveryContext(options.deliveryContext)} ${headInstructions(instruction)} When finished, reply with one JSON object, nothing else: ${STEER_ONLY_DECISION_SHAPE} Use noop when there is nothing to report.${endConditionNote(options.endsWhen, 'add "done": true to the JSON object')} ${OBSERVER_DELIVERY_GUIDANCE} Do not start message with [pi-hydra ${head}].`; } /** * Sent as a developer message. The head's instructions stay in the adjacent * user message; this message explains tools and how to finish. */ export function buildObservationEnvelope( head: string, tools: string[] | undefined, options: ObservationProtocolOptions = {}, ): string { return `${OBSERVER_GUIDANCE} The previous user message contains all instructions for the ${head} head.${toolCompletionGuidance(head, tools, options)}`; } function toolCompletionGuidance(head: string, tools: string[] | undefined, options: ObservationProtocolOptions): string { return `${hydraSnapshot(tools, options.activeHeads)} You may use ${toolAllowance(tools)} to check facts or do the work this head's instructions ask for. The main assistant does not see your tool calls or their results. The hydra action complete_observation is always available. manage_heads is available only if hydra is among your allowed tools. ${REPORTING_GUIDANCE}${actingDeliveryContext(options.deliveryContext)} ${MANAGEMENT_NOTE} When finished, call hydra exactly once with action "complete_observation", with no other tool calls in that turn. Use delivery "none" and message "" when there is nothing to report. Otherwise, message must contain your feedback; keep it short, ideally under 240 characters.${endConditionNote(options.endsWhen, "also pass done: true")} ${OBSERVER_DELIVERY_GUIDANCE} Do not start message with [pi-hydra ${head}]. Successfully removing your own head ends this check; do not call complete_observation afterward.`; } export interface HeadCatalog { exists(name: string): boolean; isDiagnostic(name: string): boolean; } /** * Cleans up a requested set of heads: unknown names are dropped and duplicates * removed. * * A diagnostic head takes over the whole set on its own. Diagnostics fire once * and then put the previous set back, which only works if there is exactly one * set to put back. */ export function sanitizeHeadSet(requested: string[], catalog: HeadCatalog): { heads: string[]; unknown: string[] } { const known = requested.filter((name) => catalog.exists(name)); const unknown = requested.filter((name) => !catalog.exists(name)); const diagnostic = known.find((name) => catalog.isDiagnostic(name)); return { heads: diagnostic ? [diagnostic] : [...new Set(known)], unknown }; } /** * Reads the saved head list, whichever of the three shapes it is in. `lenses` * and `lens` are what older sessions wrote before the rename. * * An empty list is respected as "the user turned everything off". Null means * nothing was saved at all, which is a different thing and is treated * differently by the caller. */ /** What an add call can carry beyond the head's name. */ export interface AddedHead { withoutFile?: { instructions: string; tools: string[] | undefined }; endsWhen?: string; } // What hydra can execute for a head: the seven standard tools plus its own. // Hydra has no execute for other extensions' tools or MCP. export const EXECUTABLE_TOOL_NAMES = ["read", "bash", "edit", "write", "grep", "find", "ls", "hydra"]; /** What keeps a head from using the tools it needs. */ export interface HeadToolMismatch { /** Tools Hydra could run that the main assistant doesn't have active. */ missing: string[]; /** Listed tools Hydra can never run, active or not. */ unsupported: string[]; /** `codemode.mode: "only"` with codemode active hides every tool. */ hiddenByCodemode: boolean; } /** * A head can only call tools the main assistant's request declares, because * its request replays that one (VISION.md, prompt caching). A tool it knows * only by name it never calls (docs/heads.md#tools). So a head * that needs a tool the main assistant lacks must not run at all. * * Returns null when the head can run. Heads without tools never mismatch. * Heads without a list need nothing listed: they get the main assistant's * tools. Every head that finishes through `hydra` needs it. */ export function headToolMismatch( tools: string[] | undefined, active: readonly string[], options: { finishesThroughHydra: boolean; codemodeOnly: boolean }, ): HeadToolMismatch | null { if (!headActs(tools)) return null; const listed = tools ?? []; const needed = options.finishesThroughHydra && !listed.includes("hydra") ? [...listed, "hydra"] : listed; const unsupported = listed.filter((tool) => !EXECUTABLE_TOOL_NAMES.includes(tool)); const missing = needed.filter((tool) => EXECUTABLE_TOOL_NAMES.includes(tool) && !active.includes(tool)); const hiddenByCodemode = options.codemodeOnly && active.includes("codemode"); if (unsupported.length === 0 && missing.length === 0 && !hiddenByCodemode) return null; return { missing, unsupported, hiddenByCodemode }; } /** * The one message for a blocked head: what it can't use and how to fix it. * `state` is "is off" for a head Hydra turned off, "can't be added" for a * refused add. Callers add the "hydra: " prefix where the user reads it. */ export function headToolBlockMessage(head: string, mismatch: HeadToolMismatch, state: "is off" | "can't be added"): string { const parts = [`head ${head} ${state}`]; if (mismatch.missing.length > 0) { const names = mismatch.missing.join(", "); const plus = mismatch.missing.map((tool) => `"+${tool}"`).join(", "); parts.push( `: the main assistant doesn't have ${names}. To fix: add ${plus} to defaultTools in settings.json and run /reload. If that doesn't help, or you started pi with --tools or --no-tools, add them there and restart pi (pi --continue keeps the conversation).`, ); } else { parts.push(":"); } if (mismatch.hiddenByCodemode) { parts.push(` codemode.mode is "only", which hides all tools from the model; set it to "on".`); } if (mismatch.unsupported.length > 0) { parts.push(` it lists tools Hydra can't run: ${mismatch.unsupported.join(", ")}. Remove them from its tools (usable: ${EXECUTABLE_TOOL_NAMES.join(", ")}).`); } parts.push(state === "is off" ? " Then turn the head back on." : " Then add it again."); return parts.join(""); } /** * The saved `added` record. An entry the add call could not have produced is * damaged: it is not repaired, and its head is not restored at all, not even * from a head file of the same name. Repairing could, for example, turn a * broken tool list into "all tools". */ export function savedAddedHeads(config: { heads?: unknown; added?: unknown }): { added: Record; damaged: string[] } { // A record that is there but not a record says nothing about any saved // head, so none of them can be trusted to be a plain head file. if (config.added !== undefined && plainObject(config.added) === null) { return { added: {}, damaged: savedHeadList(config) ?? [] }; } const added: Record = {}; const damaged: string[] = []; for (const [name, value] of Object.entries(plainObject(config.added) ?? {})) { const head = isValidHeadName(name) ? savedAddedHead(value) : null; if (head === null) damaged.push(name); else added[name] = head; } return { added, damaged }; } function plainObject(value: unknown): Record | null { return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record) : null; } function savedAddedHead(value: unknown): AddedHead | null { const entry = plainObject(value); const text = (value: unknown) => (typeof value === "string" && value.trim().length > 0 ? value : null); if (entry === null) return null; const head: AddedHead = {}; if (entry.endsWhen !== undefined) { const endsWhen = text(entry.endsWhen); if (endsWhen === null) return null; head.endsWhen = endsWhen; } if (entry.withoutFile !== undefined) { const withoutFile = plainObject(entry.withoutFile); const instructions = text(withoutFile?.instructions); const tools = withoutFile?.tools; const toolsValid = tools === undefined || (Array.isArray(tools) && tools.every((tool) => EXECUTABLE_TOOL_NAMES.includes(tool))); // A head without a file always has an end; one without is not something an add call makes. if (instructions === null || !toolsValid || head.endsWhen === undefined) return null; head.withoutFile = { instructions, tools: tools as string[] | undefined }; } return head.withoutFile || head.endsWhen !== undefined ? head : null; } export function savedHeadList(config: { heads?: unknown; lenses?: unknown; lens?: unknown }): string[] | null { if (Array.isArray(config.heads)) { return config.heads.filter((name): name is string => typeof name === "string"); } if (Array.isArray(config.lenses)) { return config.lenses.filter((name): name is string => typeof name === "string"); } if (typeof config.lens === "string") { return [config.lens]; } return null; } export interface FinalAssistantCandidate { role: string; stopReason?: string; errorMessage?: string; content?: unknown; timestamp?: number; } /** * Picks the agent's last message, the one an end-of-run observation has to * carry because nothing else will. * * It has to be the answer to the request that was captured. Any earlier * message is already inside that captured request, so adding it again would * show the head the same text twice. Runs whose last answer was cancelled or * errored fall exactly into that case and produce nothing. * * The two are matched by the timestamp taken when the answer began, not by * comparing clock times. Comparing clocks is a coin toss here, because pi * builds the answer about a millisecond before the request is handed over. */ export function selectFinalAssistant( messages: T[], responseTimestamp: number | null, ): T | null { if (responseTimestamp === null) { return null; } for (let i = messages.length - 1; i >= 0; i--) { const message = messages[i]; if (message.role !== "assistant") { continue; } if (message.stopReason === "error" || message.stopReason === "aborted" || message.errorMessage) { continue; } if (!Array.isArray(message.content) || message.content.length === 0) { continue; } return message.timestamp === responseTimestamp ? message : null; } return null; } /** * Whether the driver sends its whole conversation on every request. * * That is the condition for sharing a cache session with it. A driver that * sends everything never asks the server to continue from an earlier reply, so * there is nothing an observation can knock out from under it. * * Written to accept only known values, because this comes out of a settings * file the user can edit. Anything unrecognized has to count as unsafe. */ export function isFullInputTransport(transport: string): boolean { return transport === "websocket" || transport === "sse"; } /** * The one place that decides whether cache sharing has to stop: null while it * is still safe, otherwise the reason, in words a user can read. * * Kept in one place because that same sentence is also what stops the warning * being printed twice. */ export function classifyCodexShareLoss(transport: string): string | null { return isFullInputTransport(transport) ? null : `pi transport "${transport}" (the driver's delta continuation would break under a shared session)`; } // Matches loosely on purpose, across wording changes and multi-line errors. // Matching something harmless only costs a bit of cache saving, and // hasDriverContinuationError already requires the run to have failed. Missing // a real one costs the user a broken conversation, again and again. const CONTINUATION_ERROR = /previous[ _]?response.*not.*found/is; /** * The one symptom known to mean that observing inside the driver's session has * broken the driver. Whatever reads this stops sharing for good. */ export function hasDriverContinuationError(messages: FinalAssistantCandidate[]): boolean { return messages.some( (message) => message.role === "assistant" && message.stopReason === "error" && CONTINUATION_ERROR.test(message.errorMessage ?? ""), ); } /** Shutdown grace from its raw env value: 0 means "don't wait"; unset or invalid falls back. */ export function parseShutdownGrace(raw: string | undefined, fallback: number): number { const parsed = raw == null || raw.trim() === "" ? Number.NaN : Number(raw); return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback; } // Only the parts of an Anthropic request hydra actually looks at. Described by // shape rather than by importing pi's own type, because the request arrives as // an unknown blob and every field hydra does not recognize has to survive // untouched. export interface CacheControl { type: string; ttl?: string; } export interface PayloadBlock { type: string; text?: string; cache_control?: CacheControl; [key: string]: unknown; } export interface PayloadMessage { role: string; content: string | PayloadBlock[]; [key: string]: unknown; } export interface AnthropicPayload { messages: PayloadMessage[]; [key: string]: unknown; } export function isAnthropicPayload(value: unknown): value is AnthropicPayload { return ( typeof value === "object" && value !== null && Array.isArray((value as { messages?: unknown }).messages) ); } /** Remove every message-level marker in place, returning the deepest one removed. */ function stripMessageMarkers(messages: PayloadMessage[]): CacheControl | undefined { let stripped: CacheControl | undefined; for (const message of messages) { if (!Array.isArray(message.content)) { continue; } for (const block of message.content) { if (block.cache_control !== undefined) { stripped = block.cache_control; delete block.cache_control; } } } return stripped; } // Only text, tool_use and tool_result can carry a cache mark. Putting one on a // thinking block is rejected by the API outright. const MARKABLE_TYPES = ["text", "tool_use", "tool_result"]; function lastMarkableBlock(message: PayloadMessage): PayloadBlock | undefined { if (!Array.isArray(message.content)) { return undefined; } for (let i = message.content.length - 1; i >= 0; i--) { if (MARKABLE_TYPES.includes(message.content[i].type)) { return message.content[i]; } } return undefined; } /** The last block in these messages that is allowed to carry a cache mark. */ function lastMarkableBlockOf(messages: PayloadMessage[]): PayloadBlock | undefined { for (let i = messages.length - 1; i >= 0; i--) { const block = lastMarkableBlock(messages[i]); if (block) { return block; } } return undefined; } const isEffortMessage = (message: PayloadMessage) => message.role === "system" && Array.isArray(message.content) && message.content.length === 0 && "output_config" in message; /** * A head thinks as hard as the driver. On Anthropic models with * mid-conversation effort, pi-ai sets the effort in an empty system message at * the end of each request, and the head's end is written by the head's own * pi-ai call. Whatever effort that call chose, the head's messages take the * effort the driver's request actually ends with: the captured request is the * only record of what the driver sent. */ function adoptDriverEffort(captured: PayloadMessage[], headMessages: PayloadMessage[]): void { const driverEffort = captured.filter(isEffortMessage).at(-1)?.output_config; for (const message of headMessages.filter(isEffortMessage)) { if (driverEffort === undefined) { throw new Error("the head's request sets an effort, but the driver's request does not; the model changed since it was captured"); } message.output_config = structuredClone(driverEffort); } } /** * Where the head's instruction starts: the first user message that is not the * driver's tool results. Everything before it is the driver's last turn, * everything after it is the head's own work. */ function headPromptIndex(tail: PayloadMessage[]): number { const index = tail.findIndex( (message) => message.role === "user" && !(Array.isArray(message.content) && message.content.some((block) => block.type === "tool_result")), ); if (index === -1) { throw new Error("observation tail has no head instruction"); } return index; } /** * Adds the observation's own messages to the end of the driver's captured * request. * * The captured part is replayed exactly as it was, so the observation reads * the driver's cache entry instead of paying to build its own. Anthropic only * writes to the cache where a request marks it, and allows four such marks per * request. The driver has already used all four, so hydra never adds one. It * only moves the last one, and where it moves depends on what is being added: * * - Just the head's instruction. Nothing moves and the instruction is not * cached. It is short and will not be read again. * - The agent's final turn plus the instruction, at the end of a run. The mark * moves onto the end of that turn (its final message, or the results of the * tools it called), so paying to store it also warms up the driver's own * next turn. * - A whole tool loop. The mark moves to the last message of the loop, so each * turn is paid for once and read cheaply afterwards rather than resent as new * text every iteration. This mark deliberately does not carry the driver's * longer lifetime, because loop entries only need to survive until the next * iteration. * * Any marks pi-ai put on the added messages are removed first, so there is only * ever one place deciding where they go. */ export function mergeObservationPayload(captured: AnthropicPayload, tail: PayloadMessage[], envelope?: string): AnthropicPayload { const merged = structuredClone(captured) as AnthropicPayload; // Copy before touching anything: this object belongs to pi-ai and is still // in use. Whatever cache marks pi-ai put on it are then removed, because // the code below is the only thing that decides where they go. const tailMessages = structuredClone(tail) as PayloadMessage[]; stripMessageMarkers(tailMessages); // Decided by the head's instruction, not by counting messages: pi-ai also // adds empty system messages that only carry the thinking effort. const promptIndex = headPromptIndex(tailMessages); adoptDriverEffort(captured.messages, tailMessages.slice(promptIndex + 1)); const loopTurns = tailMessages.slice(promptIndex + 1).some((message) => message.role === "assistant"); const target = loopTurns ? lastMarkableBlockOf(tailMessages) : lastMarkableBlockOf(tailMessages.slice(0, promptIndex)); if (target) { const stripped = stripMessageMarkers(merged.messages); target.cache_control = loopTurns ? { type: "ephemeral" } : (stripped ?? { type: "ephemeral" }); } if (envelope !== undefined) { tailMessages.splice(promptIndex + 1, 0, { role: "system", content: [{ type: "text", text: envelope }], }); } merged.messages = [...merged.messages, ...tailMessages]; return merged; } // OpenAI names the conversation `input` rather than `messages`. Same rule as // above: that is the only field the merge touches and everything else survives // untouched. export interface OpenAIResponsesPayload { input: unknown[]; [key: string]: unknown; } export function isOpenAIResponsesPayload(value: unknown): value is OpenAIResponsesPayload { return ( typeof value === "object" && value !== null && Array.isArray((value as { input?: unknown }).input) ); } /** Remove every explicit cache breakpoint from the items' content blocks in place. */ function stripPromptCacheBreakpoints(items: unknown[]): void { for (const item of items) { const content = (item as { content?: unknown } | null)?.content; if (!Array.isArray(content)) { continue; } for (const block of content) { if (typeof block === "object" && block !== null) { delete (block as { prompt_cache_breakpoint?: unknown }).prompt_cache_breakpoint; } } } } /** * The same job as the Anthropic merge, for OpenAI's request shape. * * The captured part is replayed exactly as it was, down to the cache key and * every other setting. The difference is that nothing has to be marked here: * this backend caches each request's newest message by itself, so every * observation stores its own and the next one reads it. That is the same * arrangement the Anthropic merge has to set up by hand. * * Whether an observation can also read what the driver stored depends on * routing hydra does not control. Running under the driver's own session id * makes it dependable, which is the decision made in index.ts. Measurements * are in the OpenAI section of docs/providers.md. * * There is no explicit Anthropic-style pre-warm here: a cache mark is legal * only on input, never on what the model wrote. Current Codex accounting still * charges a run-end observation for the newest turn plus its own tail; implicit * caching and shared-session routing determine what later requests can reuse. * * Any marks pi-ai might add are removed, since on this provider the right * number of them is none. */ export function mergeOpenAIObservationPayload( captured: OpenAIResponsesPayload, tail: unknown[], envelope?: string, ): OpenAIResponsesPayload { // Copy before stripping, because this object belongs to pi-ai. Only a // shallow copy, unlike the Anthropic merge: nothing here changes the // captured part, so there is no reason to duplicate the whole conversation // on every turn of an acting head's loop. The result therefore shares those // items rather than owning them, which is safe because nothing further down // modifies them. const tailItems = structuredClone(tail) as unknown[]; stripPromptCacheBreakpoints(tailItems); if (envelope !== undefined) { const promptIndex = tailItems.findIndex( (item) => typeof item === "object" && item !== null && (item as { role?: unknown }).role === "user", ); if (promptIndex === -1) { throw new Error("cannot insert observation envelope: tail has no user prompt"); } tailItems.splice(promptIndex + 1, 0, { type: "message", role: "developer", content: [{ type: "input_text", text: envelope }], }); } return { ...captured, input: [...captured.input, ...tailItems] }; }