/** * hydra: helpers that check the main assistant's work. * How it works: docs/architecture.md. Provider details: docs/providers.md. * Usage and head instructions: README.md and docs/heads.md. */ import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { runAgentLoop } from "@earendil-works/pi-agent-core"; import type { AgentTool } from "@earendil-works/pi-agent-core"; import { cleanupSessionResources, uuidv7 } from "@earendil-works/pi-ai"; import type { Api, AssistantMessage, Message, Model, ProviderHeaders } from "@earendil-works/pi-ai"; import { createBashTool, createEditTool, createFindTool, createGrepTool, createLsTool, createReadTool, createWriteTool, getAgentDir, SettingsManager, } from "@earendil-works/pi-coding-agent"; import type { AgentEndEvent, ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent"; import { Box, Key, matchesKey, Text, truncateToWidth } from "@earendil-works/pi-tui"; import type { Action, Decision, HydraConfig, ObservationUsage, } from "./utils.ts"; import { consumeDeliveredMessage, DeliveryLedger, routeFeedback } from "./delivery.ts"; import type { DeliveryGateway } from "./delivery.ts"; import { DIAGNOSTIC_PROMPTS, HeadRegistry } from "./heads.ts"; import type { HeadRegistryGateway } from "./heads.ts"; import type { PersistedDelivery } from "./utils.ts"; import { hydraToolDescription, hydraToolParameters, isTerminalHydraAction, validateHydraToolParams, } from "./protocol.ts"; import type { ManageHeadsParams, RawHydraToolParams } from "./protocol.ts"; import { HeadScheduler } from "./scheduler.ts"; import { classifyJudgeResponse, JUDGE_ERROR_DESCRIPTIONS } from "./judge.ts"; import type { JudgeResult } from "./judge.ts"; import { hitBandsFor, parseBranchEntries, StatsLog } from "./stats.ts"; import type { HydraCall, ObserveKind } from "./stats.ts"; import { buildEnumeratedJudgeObservationEnvelope, buildEnumeratedJudgeObservationPrompt, buildObservationEnvelope, buildAnthropicObservationPrompt, classifyCodexShareLoss, decisionFromCompletion, EXECUTABLE_TOOL_NAMES, finishesThroughHydraTool, formatHeadManagementReceipt, hasDriverContinuationError, headActs, headToolBlockMessage, headToolMismatch, headInstructions, headLoopMessages, isAnthropicPayload, isOpenAIResponsesPayload, mergeObservationPayload, mergeOpenAIObservationPayload, parseDecision, parseHeadList, parseShutdownGrace, selectFinalAssistant, summarizeLoopUsage, usesSplitObservationHandoff, } from "./utils.ts"; // Headless runs (`pi -p`) quit as soon as the agent stops, which would cut off // an observation still waiting on a slow model. 0 means quit without waiting. const DEFAULT_SHUTDOWN_GRACE_MS = 5000; // How long a headless run waits at its end for a one-off check it asked for. // Checks have no time limit of their own, so a stuck one must not hold the // run open forever. Longer than the shutdown grace, which only lets // unrequested reviews finish their record. const ONE_OFF_HEADLESS_WAIT_MS = 10 * 60 * 1000; const errorText = (error: unknown): string => (error instanceof Error ? error.message : String(error)); async function isCurrentChatGPTAuth( ctx: ExtensionContext, model: Model, apiKey: string | undefined, headers: ProviderHeaders | undefined, ): Promise { if (!apiKey || [model.headers, headers].some((value) => Object.keys(value ?? {}).some((key) => key.toLowerCase() === "authorization"))) { return false; } // Pi's request-time OAuth resolution reports this source; the availability // snapshot used by isUsingOAuth can lag behind a credential-store change. const current = await ctx.modelRegistry.getProviderAuth("openai"); return current?.source === "OAuth" && current.auth.apiKey === apiKey; } const modelIdentity = (provider: string, id: string): string => `${provider}/${id}`; type ChatGPTCredential = { apiKey: string; headers: ProviderHeaders | undefined }; /** * The credential for one ChatGPT sign-in request, resolved again before every * call: OAuth can expire, or be swapped for an API key, while a check runs. * Never falls back to an earlier token. Callers word the consequence. */ async function currentChatGPTCredential( ctx: ExtensionContext, model: Model, ): Promise<{ credential: ChatGPTCredential } | { reason: string }> { const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model); if (!auth.ok || !auth.apiKey) { return { reason: `hydra: no credentials for ${model.provider}: ${auth.ok ? "no API key" : auth.error}` }; } const baseUrl = (auth as { baseUrl?: unknown }).baseUrl; let signedIn: boolean; try { signedIn = await isCurrentChatGPTAuth(ctx, model, auth.apiKey, auth.headers); } catch (error) { return { reason: `hydra: could not verify ChatGPT sign-in: ${errorText(error)}` }; } if (!signedIn || (baseUrl && baseUrl !== model.baseUrl)) { return { reason: "hydra: ChatGPT sign-in or endpoint changed" }; } return { credential: { apiKey: auth.apiKey, headers: auth.headers } }; } /** Throws, ending the check, unless the ChatGPT sign-in is still the one it started with. */ async function recheckedChatGPTCredential(ctx: ExtensionContext, model: Model): Promise { const current = await currentChatGPTCredential(ctx, model); if ("reason" in current) throw new Error(`${current.reason} during observation; head stopped`); return current.credential; } function plainMessageText(content: unknown): string | null { if (typeof content === "string") return content; if (!Array.isArray(content)) return null; const parts: string[] = []; for (const block of content) { if (typeof block !== "object" || block === null || (block as { type?: unknown }).type !== "text") { return null; } const text = (block as { text?: unknown }).text; if (typeof text !== "string") return null; parts.push(text); } return parts.join(""); } interface ObservationSeed { ctx: ExtensionContext; payload: unknown; assistant: AssistantMessage | null; turnIndex: number; head: string; instruction: string; // frozen at scheduling time; delivery facts are not tools: string[]; // what the head may run: its list, or the main assistant's tools for a head without one; [] = judge-only kind: ObserveKind; // A one-off head is never in the active set: it was asked for one check, // and this seed is that check. oneOff: boolean; // The head's end condition when the check was scheduled, if it has one. endsWhen: string | undefined; branchGeneration: number; // The reviewed run's cancel signal, copied when the review is scheduled: // ctx.signal always returns the current run's. runSignal: AbortSignal | undefined; model: string | null; // provider/id that answered the captured request } interface Observation extends ObservationSeed { prompt: string; // lens is frozen at scheduling; delivery facts resolve when execution starts // On providers where it measured better, the rules for answering are sent // as their own message right after the head's instruction. Undefined means // both go in one message instead. envelope?: string; // How the head is expected to hand back its decision. Judge-only heads use // the numbered JSON form that measured best. Heads that can act keep // whichever way already works on their provider. completionMode?: "tool" | "json" | "enum"; } interface FeedbackDetails { head: string; action: Action; reason: string; // Pre-rename entries persisted `lens`; the renderer falls back to it. lens?: string; } export default function hydraExtension(pi: ExtensionAPI) { pi.registerFlag("hydra-heads", { description: "Initial hydra head set, comma-separated, or `none` (beats the saved session set)", type: "string", }); const userHeadDir = join(getAgentDir(), "hydra"); const registry = new HeadRegistry(userHeadDir); // Headless mode implements ctx.ui.notify as a no-op, and headless runs // are exactly where a silent failure costs the most; warnings and errors // fall back to stderr there. function notifyUser(ctx: ExtensionContext, message: string, level: "warning" | "error") { if (ctx.hasUI) { ctx.ui.notify(message, level); } else { process.stderr.write(`${message}\n`); } } // Discovery and capture run constantly; a standing problem must warn // once, not once per run until it is fixed. const warned = new Set(); function warnOnce(ctx: ExtensionContext, message: string) { if (warned.has(message)) { return; } warned.add(message); notifyUser(ctx, message, "warning"); } function isDirectory(path: string): boolean { try { return statSync(path).isDirectory(); } catch { return false; } } // The registry's pi effects, rebuilt per call so messages carry the // caller's context; mirrors deliveryGateway below. function registryGateway(ctx: ExtensionContext, runSignal?: AbortSignal): HeadRegistryGateway { return { readDir: (dir) => readdirSync(dir), readFile: (path) => readFileSync(path, "utf8"), isDirectory, announce: (message) => ctx.ui.notify(message, "info"), notify: (message, level) => notifyUser(ctx, message, level), // The user must hear of it even when the main assistant can't yet. note: (head, message) => { if (!noteForHead(ctx, head, "head file missing or invalid", message, runSignal)) { notifyUser(ctx, `hydra: head ${head}: ${message}`, "warning"); } }, warnOnce: (message) => warnOnce(ctx, message), persistConfig: (config) => pi.appendEntry("hydra-config", config), onActiveSetChanged: () => { dropHeadsLackingTools(ctx, runSignal); updateFooter(ctx); }, }; } // Judged by the tools the user allowed the main assistant right now: a head // sees only what the main assistant's request declares (utils.ts // headToolMismatch). function toolMismatchFor(ctx: ExtensionContext, tools: string[] | undefined) { return headToolMismatch(tools, pi.getActiveTools(), { // From the tools the head actually gets, as observationHandoffFor decides. finishesThroughHydra: finishesThroughHydraTool(effectiveHeadTools(tools), ctx.model?.api, ctx.model?.provider), codemodeOnly: pi.getSettings().codemode?.mode === "only", }); } // A head without a list gets the main assistant's tools, `hydra` included, // and nothing more. function effectiveHeadTools(tools: string[] | undefined): string[] { if (tools !== undefined) return tools; const active = pi.getActiveTools(); return EXECUTABLE_TOOL_NAMES.filter((tool) => active.includes(tool)); } // Turns off every active head that can't use its tools, with the fix for // the user and a note for the main assistant. Saved like a removal. function dropHeadsLackingTools(ctx: ExtensionContext, runSignal?: AbortSignal) { const blocked = registry.activeSet().flatMap((name) => { const mismatch = toolMismatchFor(ctx, registry.headTools(name)); return mismatch ? [{ name, mismatch }] : []; }); // A one-off waiting for its check counts too: it would run without them. for (const [name, oneOff] of heldOneOffs) { const mismatch = toolMismatchFor(ctx, oneOff.tools); if (mismatch) { heldOneOffs.delete(name); blocked.push({ name, mismatch }); } } if (blocked.length === 0) return; // Saved like a removal: nothing brings these heads back on its own. const gateway = registryGateway(ctx, runSignal); const remaining = registry.activeSet().filter((name) => !blocked.some((head) => head.name === name)); if (remaining.length !== registry.activeSet().length) { if (remaining.length > 0) { registry.setHeadSet(gateway, remaining); } else { registry.clearHeadSet(gateway); } } for (const { name, mismatch } of blocked) { const message = headToolBlockMessage(name, mismatch, "is off"); notifyUser(ctx, `hydra: ${message}`, "warning"); noteForHead(ctx, name, "head lacks tools", message, runSignal); } } // Asked of pi rather than read from the settings file here, so which file // wins, who is allowed to set it, and the old `websockets: true` spelling // all stay pi's problem and keep working as pi changes. Asked fresh every // time: the user can switch transport mid-session and pi points the // running agent at the new one straight away, so a remembered answer // would be wrong in the direction that costs money. Once a session gives // up cache sharing it never takes it back, which covers both ways the // setting can change apart from one unavoidable race, described at // codexShareLostReason. let lastReadTransport: string | null = null; function driverTransport(ctx: ExtensionContext): string { // A read that fails for a moment (a lock, or catching a hand-edit // half-written) must not look like the user changed the setting. // Because giving up cache sharing is permanent, one bad read would // cost the whole session. pi reports a failed load as empty settings // plus a list of errors, so only a clean load is believed; anything // else keeps the last good answer. try { const settings = SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() }); if (settings.drainErrors().length === 0) { lastReadTransport = settings.getTransport(); } } catch { // Environment-level failure: same treatment as an errored load. } return lastReadTransport ?? "auto"; } function observationHandoffFor( ctx: ExtensionContext, name: string, tools: string[], instruction: string, endsWhen: string | undefined, ): Pick { if (name in DIAGNOSTIC_PROMPTS) { return { prompt: DIAGNOSTIC_PROMPTS[name as keyof typeof DIAGNOSTIC_PROMPTS], completionMode: "tool", }; } const deliveryContext = deliveryLedger.contextFor(name); const protocol = { activeHeads: [...registry.activeSet()], deliveryContext, endsWhen }; if (!headActs(tools)) { const split = usesSplitObservationHandoff(ctx.model?.api, ctx.model?.provider); return split ? { prompt: headInstructions(instruction), envelope: buildEnumeratedJudgeObservationEnvelope(name, deliveryContext, undefined, endsWhen), completionMode: "enum", } : { prompt: buildEnumeratedJudgeObservationPrompt(name, instruction, deliveryContext, undefined, endsWhen), completionMode: "enum", }; } return finishesThroughHydraTool(tools, ctx.model?.api, ctx.model?.provider) ? { prompt: headInstructions(instruction), envelope: buildObservationEnvelope(name, tools, protocol), completionMode: "tool", } : { prompt: buildAnthropicObservationPrompt(name, instruction, tools, protocol), completionMode: "json", }; } // The exact request the driver last sent, kept byte for byte so an // observation can replay it and be charged as a cache read instead of as // new input. responseTimestamp identifies the reply that request produced, // which is how the end-of-run trigger tells whether the final message still // has to be appended or is already inside the saved request. let capturedPayload: unknown = null; let responseTimestamp: number | null = null; // The model that answered that request, read from the answer itself: pi // applies a model switch to the selection before a request already being // prepared is sent, so the selection at capture time can be the new model. // A check waiting behind a busy one can start after a switch and must not // replay the old provider's request on the new one. let responseModel: string | null = null; let capturedThisRun = false; let awaitingFirstResponseOfRun = true; let currentTurnIndex = 0; // One-off checks scheduled and not yet finished or skipped. Adding a head // is refused while a check under its name is unfinished, so the name // stands for that one check until it leaves this set. const unfinishedOneOffs = new Set(); const scheduler = new HeadScheduler({ // Waiting reviews of a cancelled run don't start, so nothing new begins // after Escape. That point only gets reviewed if the user writes again. // Nor do reviews whose request a different model answered. A one-off // that cannot start says why. shouldRun: (seed) => { const blocked = seed.branchGeneration !== branchGeneration ? "the conversation switched branches" : seed.runSignal?.aborted ? "its run was cancelled" : seed.ctx.model === undefined || seed.model !== modelIdentity(seed.ctx.model.provider, seed.ctx.model.id) ? "the model was switched" : null; if (blocked !== null && seed.oneOff) { unfinishedOneOffs.delete(seed.head); notifyUser(seed.ctx, `hydra: one-off head "${seed.head}" did not start: ${blocked}`, "warning"); } return blocked === null && (seed.oneOff || registry.isActive(seed.head)); }, observe: async (seed, signal) => { // What has already been delivered is looked up here, not when the // observation was queued. A waiting observation can sit behind one // that delivers feedback, and it should see that rather than a // stale picture. The head's instruction is still fixed at queueing // time. const job: Observation = { ...seed, ...observationHandoffFor(seed.ctx, seed.head, seed.tools, seed.instruction, seed.endsWhen), }; try { await observe(job, signal); } finally { if (seed.oneOff) unfinishedOneOffs.delete(seed.head); } }, onError: (seed, error) => notifyUser(seed.ctx, `hydra: observe error: ${errorText(error)}`, "error"), }); let shuttingDown = false; // The observer's backend session identity for codex observations, one // per extension instance; see the sessionId option in runObservationLoop // for the constraints it satisfies. const observerSessionId = uuidv7(); // Testing only, and genuinely unsafe. Skips the transport check that // normally stops hydra from sharing a cache session with the driver, so the // safety tripwire can be fired on purpose and watched end to end. On the // default transport this breaks the driver's own conversation, which is // exactly what the check exists to prevent, so use a throwaway session. // Recipe in docs/architecture.md under "Verifying the tripwire". const unsafeForceShare = process.env.HYDRA_UNSAFE_FORCE_SHARE === "1"; // Cache sharing with the driver, once given up, is never taken back for the // rest of this session. A new session, a fork or a resume starts over. // // The reason is that the damage only goes one way. After the user switches // transport, the driver can still be holding a reference that a shared // observation has already evicted. Turning sharing back on could hand that // dead reference out again and break the driver's conversation, so off is // the only safe direction to move in. // // Three things can turn it off: the first agent_start, the check before // each observation, and a driver error at the end of a run. One race is // left and accepted. Switching transport while an observation is already // in flight can break the driver's next message once, and the error that // follows then makes the decision permanent. let codexShareLostReason: string | null = null; let initialTransportPinned = false; // Stats and successful delivery facts, rebuilt from the current session // branch on restore. Pending deliveries never cross branch navigation. const stats = new StatsLog(); const deliveryLedger = new DeliveryLedger(); let branchGeneration = 0; // One-off heads asked for since the last review point. They start with the // next one, so their copy of the conversation includes the request itself. const heldOneOffs = new Map(); function dropHeldOneOffs(ctx: ExtensionContext, why: string) { if (heldOneOffs.size === 0) return; notifyUser(ctx, `hydra: one-off ${heldOneOffs.size === 1 ? "head" : "heads"} ${[...heldOneOffs.keys()].join(", ")} did not start: ${why}`, "warning"); heldOneOffs.clear(); } const warnedProviders = new Set(); let debugDir: string | null = null; let debugSeq = 0; function updateFooter(ctx: ExtensionContext) { const activeHeads = registry.activeSet(); const headLabel = activeHeads.length > 0 ? activeHeads.join("+") : "no heads"; const calls = stats.all(); if (calls.length === 0) { ctx.ui.setStatus("hydra", ctx.ui.theme.fg("muted", `hydra: ${headLabel} | (no obs yet)`)); return; } const { cost, meanHit } = stats.cumulative(ctx.model?.api); const lastHit = calls[calls.length - 1].hitRatio; const bands = hitBandsFor(ctx.model?.api); const hitColor = meanHit === null ? "muted" : meanHit >= bands.good ? "success" : meanHit >= bands.fair ? "warning" : "error"; const hitLabel = meanHit === null ? "hit n/a (this model)" : `hit ${meanHit.toFixed(1)}% (last ${lastHit.toFixed(1)}%)`; ctx.ui.setStatus( "hydra", ctx.ui.theme.fg("toolTitle", `hydra:${headLabel}`) + " " + ctx.ui.theme.fg(hitColor, hitLabel) + " " + ctx.ui.theme.fg("dim", `$${cost.toFixed(4)} (${calls.length} obs)`), ); } function restoreFromBranch(ctx: ExtensionContext): boolean { branchGeneration++; dropHeldOneOffs(ctx, "the conversation switched branches"); const { calls: restoredCalls, config, deliveries } = parseBranchEntries(ctx.sessionManager.getBranch()); stats.load(restoredCalls); deliveryLedger.restore(deliveries); registry.resetForBranch(); if (config) { registry.applyConfig(registryGateway(ctx), config); } updateFooter(ctx); return config !== undefined; } // The result of one check. Heads without tools return findings as JSON; // heads with tools use their provider's completion format. interface ObserveOutcome extends JudgeResult { response: AssistantMessage; usages: ObservationUsage[]; iterations: number; toolsUsed: string[]; loopStopReason: ObservationLoopStopReason; } type ObservationLoopStopReason = "share-loss" | "deactivated" | null; interface ObservationToolState { completion: Decision | null; done: boolean; } function clip(text: string, max: number): string { return text.length > max ? `${text.slice(0, max)}…` : text; } function flattenUsage(usage: AssistantMessage["usage"]): ObservationUsage { return { input: usage.input, output: usage.output, cacheRead: usage.cacheRead, cacheWrite: usage.cacheWrite, cost: usage.cost.total, }; } async function observe(job: Observation, signal: AbortSignal) { if (signal.aborted) return; const model = job.ctx.model; if (!model) { warnOnce(job.ctx, "hydra: no model selected; observations skipped"); return; } // Cache replay has been measured on Anthropic, legacy OpenAI Codex, // OpenAI's ChatGPT sign-in and the local ds4 server. Other pairs warn // and stay out: a matching request shape alone does not prove the // provider will read its cache. The OpenAI API-key path remains // unmeasured and disabled. const anthropic = model.provider === "anthropic" && model.api === "anthropic-messages"; const codex = model.provider === "openai-codex" && model.api === "openai-codex-responses"; const chatgpt = model.provider === "openai" && model.api === "openai-responses" && model.baseUrl === "https://api.openai.com/v1" && job.ctx.modelRegistry.isUsingOAuth(model); const ds4 = model.provider === "ds4" && model.api === "openai-responses"; if (!anthropic && !codex && !chatgpt && !ds4) { const pair = `${model.provider}/${model.api}`; if (!warnedProviders.has(pair)) { warnedProviders.add(pair); notifyUser(job.ctx, `hydra: observations disabled for ${pair} (supported: Anthropic, OpenAI Codex, ChatGPT sign-in at OpenAI's API, or ds4)`, "warning"); } return; } // At the end of a run the driver's last message has not been sent // anywhere yet, so the observation has to carry it and let pi-ai turn // it into provider format. Mid-run the saved request already holds // everything. The merging happens in utils.ts. The shape check is also // what stops a request captured on one provider from being merged // under another after the user switches model mid-run. const bindMerge = (guard: (value: unknown) => value is T, merge: (captured: T, built: T) => unknown) => { if (!guard(job.payload)) { return null; } const captured = job.payload; return (built: unknown) => { if (!guard(built)) { throw new Error(`unexpected payload shape from provider ${model.provider}`); } return merge(captured, built); }; }; const mergeBuilt = anthropic ? bindMerge(isAnthropicPayload, (captured, built) => mergeObservationPayload(captured, built.messages, job.envelope)) : bindMerge(isOpenAIResponsesPayload, (captured, built) => mergeOpenAIObservationPayload(captured, built.input, job.envelope), ); if (!mergeBuilt) { warnOnce(job.ctx, `hydra: captured payload does not match ${model.api} (model switched mid-run, or pi changed shape); observation skipped`); return; } // The codex backend keys its cache by session id, so running // observations under the driver's own id is where the saving comes // from: every observation reads what the driver just wrote, about 85% // from the very first one, and the end-of-run write warms up the // driver's next turn. // // It is only safe while the driver sends its full conversation every // turn, which the "websocket" and "sse" transports do. Such a driver // never asks the server to continue from an earlier reply, so there is // nothing an observation can knock out from under it. On the other // transports there is, and knocking it out makes the driver's next // request fail outright. That has been reproduced; the numbers are in // docs/architecture.md. // // The transport is checked again before every observation, because the // user can change it mid-session, and the decision only ever moves // toward hydra using its own separate session, never back. // On the new OpenAI route the session ID also sets a routing header. // Copying the driver's prompt_cache_key without that header measured // zero cache reads; sharing it read the driver's cached prefix. let observationSessionId: string | undefined = chatgpt ? job.ctx.sessionManager.getSessionId() : undefined; if (codex) { if (!unsafeForceShare) { codexShareLostReason ??= classifyCodexShareLoss(driverTransport(job.ctx)); } if (codexShareLostReason === null) { observationSessionId = job.ctx.sessionManager.getSessionId(); } else { observationSessionId = observerSessionId; const advice = codexShareLostReason.startsWith("pi transport") ? ' Full cache sharing needs { "transport": "websocket" } in pi\'s settings.json from session start.' : ""; warnOnce( job.ctx, `hydra: codex observations run in their own cache scope (paying the driver context once, plus re-pays after idle pauses) because of ${codexShareLostReason}.${advice}`, ); } } const onPayload = (built: unknown) => { const merged = mergeBuilt(built); if (debugDir) { // A diagnostic must never kill the observation it diagnoses: // on any write failure, drop the dump dir and keep observing. const stem = `${Date.now()}-${job.head}-${debugSeq++}`; try { writeFileSync(join(debugDir, `hydra-driver-${stem}.json`), JSON.stringify(job.payload, null, 2)); writeFileSync(join(debugDir, `hydra-observation-${stem}.json`), JSON.stringify(merged, null, 2)); } catch (error) { debugDir = null; job.ctx.ui.notify(`hydra: debug dump failed (${errorText(error)}); dumping disabled`, "warning"); } } return merged; }; // ChatGPT sign-in is the one route whose credential hydra checks itself: // the same model signed in with an API key must not observe. Every other // route leaves key, headers and server address to pi, which resolves // them for each request exactly as for the driver's own turns. let credential: ChatGPTCredential | undefined; if (chatgpt) { const current = await currentChatGPTCredential(job.ctx, model); if ("reason" in current) { notifyUser(job.ctx, `${current.reason}; observation skipped`, "warning"); return; } credential = current.credential; } const t0 = Date.now(); const outcome = job.completionMode === "enum" ? await runJudgeObservation(job, model, credential, observationSessionId, onPayload, signal) : await runObservationLoop(job, model, credential, observationSessionId, onPayload, signal); if (!outcome || signal.aborted || job.branchGeneration !== branchGeneration) { return; } const { response, usages, iterations, toolsUsed, decisions: outcomeDecisions, loopStopReason, parseError, errorKind, attemptedTools, } = outcome; const summary = summarizeLoopUsage(usages); // Heads without tools record even empty, zero-usage answers as failures. if (job.completionMode !== "enum" && summary.input + summary.cacheRead + summary.cacheWrite === 0 && response.content.length === 0) { notifyUser(job.ctx, "hydra: head returned no content and zero input usage", "warning"); return; } const text = response.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n"); const thinking = response.content.flatMap((block) => (block.type === "thinking" ? [block.thinking] : [])).join("\n"); let decisions = outcomeDecisions; let done = outcome.done === true; if (errorKind) { const detail = parseError ? ` (${clip(parseError, 200)})` : response.errorMessage ? ` (${clip(response.errorMessage, 500)})` : ""; const tools = attemptedTools.length > 0 ? `; attempted tools: ${attemptedTools.join(", ")}` : ""; notifyUser( job.ctx, `hydra: ${job.head} ${errorKind}: ${JUDGE_ERROR_DESCRIPTIONS[errorKind]}${detail}${tools}; stopReason=${response.stopReason}; recorded as noop`, errorKind === "provider-error" ? "error" : "warning", ); decisions = [{ action: "noop", reason: errorKind, message: "" }]; done = false; } if ((!decisions || decisions.length === 0) && job.completionMode === "json") { const parsed = parseDecision(text); if (parsed) { const { done: saysDone, ...decision } = parsed; decisions = [decision]; done = saysDone === true; } else { decisions = null; } } // Only a head that was given an end condition can end itself. Any other // head saying done keeps running; the record shows it said so. const ends = done && !job.oneOff && job.endsWhen !== undefined && registry.endsWhen(job.head) === job.endsWhen; if ((!decisions || decisions.length === 0) && loopStopReason !== null) { decisions = [{ action: "noop", reason: loopStopReason === "share-loss" ? "codex cache sharing lost mid-observation" : "head deactivated mid-observation", message: "", }]; } if (!decisions || decisions.length === 0) { if (job.completionMode === "enum") throw new Error("classifyJudgeResponse returned neither findings nor an error"); const reason = job.completionMode === "json" ? "unparseable Anthropic decision" : "missing completion tool call"; // Every miss is shown: each one is a separate observation lost, and a // head that keeps missing is the signal the user needs to see. notifyUser( job.ctx, job.completionMode === "json" ? `hydra: ${job.head} answered with an unparseable JSON decision; recorded as noop` : `hydra: ${job.head} ended without complete_observation; recorded as noop`, "warning", ); decisions = [{ action: "noop", reason, message: "" }]; } // Deprecated print ranking is retained with the internal delivery path. const primaryDecision = decisions.reduce((selected, candidate) => { const urgency: Record = { noop: 0, print: 1, note: 2, steer: 3 }; return urgency[candidate.action] > urgency[selected.action] ? candidate : selected; }); const call: HydraCall = { timestamp: Date.now(), turnIndex: job.turnIndex, head: job.head, kind: job.kind, api: model.api, action: primaryDecision.action, actions: decisions.length > 1 ? decisions.map((decision) => decision.action) : undefined, input: summary.input, output: summary.output, cacheRead: summary.cacheRead, cacheWrite: summary.cacheWrite, cost: summary.cost, durationMs: Date.now() - t0, hitRatio: summary.hitRatio, rawResponse: job.completionMode === "enum" ? clip(text, 2000) : outcomeDecisions !== null ? JSON.stringify({ action: "complete_observation", delivery: outcomeDecisions[0].action === "noop" ? "none" : outcomeDecisions[0].action, message: outcomeDecisions[0].message, ...(done ? { done: true } : {}), }) : clip(text, 200), stopReason: response.stopReason, reasoningTokens: response.usage.reasoning, thinking: thinking.length > 0 ? clip(thinking, 2000) : undefined, parseError: parseError ?? undefined, judgeErrorKind: errorKind ?? undefined, attemptedTools: attemptedTools.length ? attemptedTools : undefined, iterations: iterations > 1 ? iterations : undefined, toolsUsed: toolsUsed.length > 0 ? toolsUsed : undefined, doneIgnored: done && !ends ? true : undefined, }; stats.record(call); pi.appendEntry("hydra-call", call); registry.revertDiagnosticAfterFire(registryGateway(job.ctx), job.head); updateFooter(job.ctx); for (const decision of decisions) { routeDecision(job.ctx, decision, job.head, job.runSignal); } if (ends) { registry.removeHead(registryGateway(job.ctx, job.runSignal), job.head); steerForHead(job.ctx, job.head, "head ended", `done, so this head has ended. It was to end when: ${job.endsWhen}`, job.runSignal); } } // Judge-only heads make one call and run no tools. Output that will not // parse is recorded as "did nothing" rather than spending another turn // asking for a correction or guessing at a half-read answer. // // A null header value means "remove this header", not "no value set". The // set is passed through untouched: filtering or defaulting the nulls away // would put back a header pi meant to strip. async function runJudgeObservation( job: Observation, model: Model<"anthropic-messages" | "openai-codex-responses" | "openai-responses">, credential: ChatGPTCredential | undefined, sessionId: string | undefined, onPayload: (built: unknown) => unknown, signal: AbortSignal, ): Promise { const prompt: Message = { role: "user", content: [{ type: "text", text: job.prompt }], timestamp: Date.now(), }; const baseMessages: Message[] = job.assistant ? [job.assistant] : []; const usages: ObservationUsage[] = []; const call = async (messages: Message[]): Promise => { if (signal.aborted) throw new Error("observation aborted"); const current = credential && (await recheckedChatGPTCredential(job.ctx, model)); const options = { apiKey: current?.apiKey, headers: current?.headers, sessionId, transport: model.api === "openai-codex-responses" ? ("websocket" as const) : undefined, onPayload, signal, }; const response = await job.ctx.modelRegistry.streamSimple(model, { systemPrompt: "", messages, tools: [] }, options).result(); usages.push(flattenUsage(response.usage)); return response; }; let response: AssistantMessage; try { response = await call([...baseMessages, prompt]); if (signal.aborted) return null; const classified = classifyJudgeResponse(response); return { response, usages, iterations: 1, toolsUsed: [], ...classified, loopStopReason: null, }; } catch (error) { if (!signal.aborted) { notifyUser(job.ctx, `hydra: observation failed: ${errorText(error)}`, "error"); } return null; } } // Heads that can act run through pi's own agent loop instead of a copy of // it, so checking tool arguments, reporting unknown tools, deciding what // runs in parallel, and handling cancellation all stay pi's code and keep // working as pi changes. // // Every call the loop makes still goes through the same merging as a plain // observation, so the driver's conversation stays a cache read and the // head's own turns are only paid for once. See utils.ts. async function runObservationLoop( job: Observation, model: Model<"anthropic-messages" | "openai-codex-responses" | "openai-responses">, credential: ChatGPTCredential | undefined, sessionId: string | undefined, onPayload: (built: unknown) => unknown, signal: AbortSignal, ): Promise { const prompt: Message = { role: "user", content: [{ type: "text", text: job.prompt }], timestamp: Date.now(), }; const usages: ObservationUsage[] = []; const toolsUsed: string[] = []; let iterations = 0; const toolState: ObservationToolState = { completion: null, done: false }; let loopStopReason: ObservationLoopStopReason = null; // Whether this observation is running inside the driver's own session. // Fixed for the whole loop, and the reason the loop can be stopped by // sharing being given up. const sharedSession = model.api === "openai-codex-responses" && sessionId !== undefined && sessionId !== observerSessionId; let messages: Awaited>; try { messages = await runAgentLoop( [prompt], { messages: job.assistant ? [job.assistant] : [], tools: observationTools(job.ctx, job.tools, job, toolState), }, { model, apiKey: credential?.apiKey, headers: credential?.headers, // ChatGPT only: re-check the sign-in before every turn of the loop. getApiKey: credential ? async () => (signal.aborted ? undefined : (await recheckedChatGPTCredential(job.ctx, model)).apiKey) : undefined, // Codex only. Whether this is the driver's session id or // hydra's own is decided in observe(). // // Always a v7 id: on 2026-07-13 a missing or v4 id was // measured getting routed to a free tier that does not // exist. That did not happen again the next day, but a v7 // id costs nothing and matches what pi generates anyway. // // Always plain websocket, never the default. The default // asks the server to continue from an earlier reply, and // another request in the same session can invalidate that // part-way through the loop. SSE would avoid the same // problem but was measured being refused outright, while // websocket has never misbehaved. sessionId, transport: model.api === "openai-codex-responses" ? "websocket" : undefined, onPayload, convertToLlm: (agentMessages) => headLoopMessages(agentMessages, model.api === "anthropic-messages", (role) => warnOnce(job.ctx, `hydra: a head's loop dropped a "${role}" message it doesn't know; Pi may have changed its loop`), ), // Finishing has to be the only thing the head does in that // turn. Otherwise it could declare a result in the same // breath as an action that then fails, and the failure // would be hidden behind a decision already accepted. beforeToolCall: async ({ assistantMessage, toolCall, args }) => { if (toolCall.name !== "hydra" || !isTerminalHydraAction(args, job.head)) { return undefined; } const calls = assistantMessage.content.filter((block) => block.type === "toolCall"); if (calls.length !== 1) { return { block: true, reason: "Terminal hydra actions must be the only tool call in their turn. Finish the other work, inspect its results, then call the terminal action alone.", }; } return undefined; }, // Cache safety comes before completion or removal. // Count calls for reporting, not as a work limit. finishTurn: () => { iterations++; if (sharedSession && !unsafeForceShare) { codexShareLostReason ??= classifyCodexShareLoss(driverTransport(job.ctx)); } if (sharedSession && codexShareLostReason !== null) { loopStopReason = "share-loss"; } else if (toolState.completion !== null) { return { action: "end" as const }; } else if (!job.oneOff && !registry.isActive(job.head)) { // Also how a head that removed itself finishes: no further // model call, because nobody is left to ask for a decision. loopStopReason = "deactivated"; } return loopStopReason !== null ? { action: "end" as const } : undefined; }, afterToolCall: async (event) => { // Records which tools the head used, for /hydra-stats. if (job.branchGeneration !== branchGeneration) return undefined; const hydraAction = event.toolCall.name === "hydra" && typeof event.toolCall.arguments === "object" && event.toolCall.arguments !== null ? (event.toolCall.arguments as { action?: unknown }).action : undefined; if (hydraAction !== "complete_observation") { toolsUsed.push(event.toolCall.name); } return undefined; }, }, async (event) => { if (event.type === "message_end" && event.message.role === "assistant") { usages.push(flattenUsage((event.message as AssistantMessage).usage)); } }, signal, (streamModel, context, options) => job.ctx.modelRegistry.streamSimple(streamModel, context, options), ); } catch (error) { if (!signal.aborted) { notifyUser( job.ctx, `hydra: observation loop failed: ${errorText(error)}`, "error", ); } return null; } const response = [...messages].reverse().find((message): message is AssistantMessage => message.role === "assistant"); if (!response) { notifyUser(job.ctx, "hydra: observation loop produced no response", "warning"); return null; } if (response.stopReason === "error" || response.stopReason === "aborted") { if (!signal.aborted) { notifyUser( job.ctx, `hydra: observation loop failed: ${response.errorMessage ?? "aborted"}`, "error", ); } return null; } if (loopStopReason === "share-loss" && response.stopReason === "toolUse") { job.ctx.ui.notify( `hydra: ${job.head} wound down after ${iterations} turn${iterations === 1 ? "" : "s"} (codex cache sharing lost mid-loop)`, "warning", ); } return { response, usages, iterations, toolsUsed, decisions: toolState.completion ? [toolState.completion] : null, parseError: null, errorKind: null, attemptedTools: [], loopStopReason, ...(toolState.done && { done: true }), }; } // The head uses pi's own tools, in the driver's working directory. Two // writes to the same file are queued rather than racing, and that queue is // shared with the driver because both end up using the same copy of pi's // code. // // What the model is offered comes from the replayed request, so it always // matches what the driver had. A head file's `tools:` list then narrows // what will actually run. Anything outside it gets pi's ordinary "tool not // found" answer and the head carries on. let standardObservationTools: AgentTool[] | null = null; function observationTools( ctx: ExtensionContext, allowed: string[], job: Observation, state: ObservationToolState, ): AgentTool[] { if (!standardObservationTools) { standardObservationTools = [ createReadTool(ctx.cwd), createBashTool(ctx.cwd), createEditTool(ctx.cwd), createWriteTool(ctx.cwd), createGrepTool(ctx.cwd), createFindTool(ctx.cwd), createLsTool(ctx.cwd), ]; } const workTools = standardObservationTools.filter((tool) => allowed.includes(tool.name)); // Heads with tools get the shared hydra tool. Codex uses it to finish; // Anthropic returns JSON. Each action checks its own permission. // Heads without tools never enter this loop. return [ ...workTools, { name: hydraToolDefinition.name, label: hydraToolDefinition.label, description: hydraToolDefinition.description, parameters: hydraToolDefinition.parameters, execute: (toolCallId, params, toolSignal, _onUpdate) => executeObservationHydra( toolCallId, params as RawHydraToolParams, toolSignal, ctx, job, state, ), } satisfies AgentTool, ]; } // Hydra's own messages go out as the head's steer. The label tells them // apart from the head's findings. function steerForHead(ctx: ExtensionContext, head: string, reason: string, fact: string, runSignal?: AbortSignal) { routeDecision(ctx, { action: "steer", reason, message: `automatic notice: ${fact}` }, head, runSignal); } // Tells the main assistant without starting a turn (safe in // before_agent_start), but never before pi's first system message: // docs/providers.md#anthropic. // Returns whether the note went out. function noteForHead(ctx: ExtensionContext, head: string, reason: string, fact: string, runSignal?: AbortSignal): boolean { const recordsTools = ctx.sessionManager.getBranch().some((entry) => entry.type === "message" && entry.message.role === "system"); if (!recordsTools) return false; routeDecision(ctx, { action: "note", reason, message: `automatic notice: ${fact}` }, head, runSignal); return true; } function deliveryGateway(ctx: ExtensionContext): DeliveryGateway { return { isIdle: () => ctx.isIdle(), notify: (message, level) => (level === "info" ? ctx.ui.notify(message, level) : notifyUser(ctx, message, level)), sendUserMessage: (content, options) => pi.sendUserMessage(content, options), sendMessage: (message, options) => pi.sendMessage(message, options), persist: (entry) => pi.appendEntry("hydra-delivery", entry), }; } function routeDecision(ctx: ExtensionContext, decision: Decision, decisionHead: string, runSignal?: AbortSignal) { // Feedback that would start a driver turn is added without one when: // - the session is shutting down: in a headless run it is already // being torn down, so a new turn would race the teardown; // - the reviewed run was cancelled: a new turn could restart work the // user just stopped. The review itself still finishes and is saved. const holdBack = shuttingDown ? "during shutdown" : runSignal?.aborted ? "after the run was cancelled" : null; const routed = holdBack !== null && decision.action === "steer" ? { ...decision, action: "note" as const, reason: `${decision.reason}; added without a turn ${holdBack}` } : decision; routeFeedback(deliveryLedger, deliveryGateway(ctx), routed, decisionHead); } // One observation per active head, all from the same captured snapshot, // plus the one check of every one-off head asked for since the last point. // One-offs also run on the first response of a run: that response is only // skipped for heads that already reviewed the run before it. function scheduleObservations(ctx: ExtensionContext, kind: ObserveKind, assistant: AssistantMessage | null, includeActive = true) { // A cancelled run gets no new review. Its last message is not a final // answer, and a review now could restart work the user just stopped. if (ctx.signal?.aborted) { dropHeldOneOffs(ctx, "its run was cancelled"); return; } const seed = (head: string, instruction: string, tools: string[], oneOff: boolean) => { if (oneOff) unfinishedOneOffs.add(head); scheduler.schedule({ endsWhen: oneOff ? undefined : registry.endsWhen(head), ctx, payload: capturedPayload, assistant, turnIndex: currentTurnIndex, head, instruction, tools, kind, oneOff, branchGeneration, runSignal: ctx.signal, model: responseModel, }); }; if (includeActive) { for (const name of registry.activeSet()) { seed(name, registry.get(name)?.prompt ?? "", effectiveHeadTools(registry.headTools(name)), false); } } for (const [name, oneOff] of heldOneOffs) { seed(name, oneOff.instruction, effectiveHeadTools(oneOff.tools), true); } heldOneOffs.clear(); } pi.on("session_start", (_event, ctx) => { const gateway = registryGateway(ctx); registry.discover(gateway, ctx.cwd); const restored = restoreFromBranch(ctx); // A flag on this launch beats whatever was saved, because it is what // the user just asked for. if (launchFlag() !== null || !restored) { applyLaunchHeads(ctx); } updateFooter(ctx); }); function launchFlag(): string | null { const flag = pi.getFlag("hydra-heads"); return typeof flag === "string" && flag.length > 0 ? flag : null; } // The heads this launch starts with when no saved set applies: the flag's, // else the autostart heads. A flag-chosen set is saved, since it is the // only way to configure a headless run. Heads that started themselves are // not saved, so a later session reads the files again. function applyLaunchHeads(ctx: ExtensionContext) { const gateway = registryGateway(ctx); const flag = launchFlag(); if (flag === null) { registry.applyAutostart(); } else if (flag.trim() === "none") { registry.clearHeadSet(gateway); } else if (!registry.setHeadSet(gateway, parseHeadList(flag))) { ctx.ui.notify(`hydra: --hydra-heads matched nothing; observing with ${registry.activeSet().join("+") || "no heads"}`, "warning"); } } pi.on("session_tree", (_event, ctx) => { // Branch navigation changes which hydra entries are in scope. A branch // without a saved set gets this launch's starting heads back, not the // heads of the branch just left. if (!restoreFromBranch(ctx)) { applyLaunchHeads(ctx); updateFooter(ctx); } }); pi.on("agent_start", (_event, ctx) => { awaitingFirstResponseOfRun = true; capturedThisRun = false; // The sharing decision is fixed on the first run, which is the closest // an extension can get to the moment pi built the driver from the same // settings. Editing the settings file later does not change the // running driver, so a mid-session switch must not start sharing with // a driver that is still working the old way. An edit made in the gap // before the first prompt can still slip through, which costs at most // one broken message, the same as the race described at // codexShareLostReason. if (!initialTransportPinned) { initialTransportPinned = true; if (!unsafeForceShare) { codexShareLostReason ??= classifyCodexShareLoss(driverTransport(ctx)); } } checkHeadsBeforeRun(ctx); }); // Picks up head edits made since the last run (the in-session tuning loop), // then turns off heads that can't use their tools. Covers autostart, // restored sessions and tree navigation, which change no active set. function checkHeadsBeforeRun(ctx: ExtensionContext) { registry.discover(registryGateway(ctx), ctx.cwd); dropHeadsLackingTools(ctx); updateFooter(ctx); } // Before a prompt's first request; agent_start is one request late // (measured). pi skips this hook for runs started by a message that // triggers a turn and for its own continuations, so agent_start checks // again for those. Running twice changes nothing. pi.on("before_agent_start", (_event, ctx) => checkHeadsBeforeRun(ctx)); pi.on("turn_start", (event) => { currentTurnIndex = event.turnIndex; }); pi.on("before_provider_request", (event) => { if (registry.activeSet().length === 0 && heldOneOffs.size === 0) { // Throw the old snapshot away rather than keeping it. An // observation still running from before must count as out of date, // and a head added part-way through must not treat the old // snapshot as current. capturedPayload = null; responseTimestamp = null; responseModel = null; return; } // Capture the driver's exact bytes; never modify them. Edits made after // this handler (later handlers, transport wrappers) are not in the copy (#43). capturedPayload = structuredClone(event.payload); responseTimestamp = null; responseModel = null; capturedThisRun = true; }); // The driver's answer has started arriving, which on Anthropic is the // moment its request lands in the cache. Replaying it now costs almost // nothing and the head's decision arrives while the answer is still being // written. On OpenAI the timing is looser: the observation reads whatever // is cached so far and pays for the rest, which is slower and dearer but // still works. // // The first request of a run is skipped, because the observation at the // end of the previous run has already looked at everything before it. pi.on("message_start", (event, ctx) => { if (event.message.role === "user") { const content = plainMessageText(event.message.content); if (content !== null) { consumeDeliveredMessage(deliveryLedger, deliveryGateway(ctx), content); } else { deliveryLedger.discardIdleUserDeliveries(); } } if (event.message.role !== "assistant") { return; } // The first reply after a capture is that request's own answer. // Remembering when it arrived is how the end-of-run trigger later // recognizes it. Recorded even when no heads are active, since a head // can be switched on part-way through. if (capturedPayload && responseTimestamp === null) { const answer = event.message as AssistantMessage; responseTimestamp = answer.timestamp ?? null; responseModel = modelIdentity(answer.provider, answer.model); } // Marked even with no heads active: a head added later in this run has // not reviewed the run so far, so its first check must not be skipped. const firstResponse = awaitingFirstResponseOfRun; awaitingFirstResponseOfRun = false; if ((registry.activeSet().length === 0 && heldOneOffs.size === 0) || !capturedPayload) { return; } scheduleObservations(ctx, "piggyback", null, !firstResponse); }); pi.on("agent_settled", (_event, ctx) => { const orphaned = deliveryLedger.settle(); if (orphaned.length > 0) { notifyUser( ctx, `hydra: ${orphaned.length} feedback ${orphaned.length === 1 ? "delivery" : "deliveries"} never reached the driver and was removed from pending context`, "warning", ); } }); // The agent has handed control back to the user, so the last thing it said // will not reach the cache until the user types again. The observation // carries that message itself. Runs that produced nothing worth reviewing, // such as a bare command or an immediate cancel, schedule nothing. // pi -p (print or json mode) ends the session once the main assistant // stops, and a message only gets a turn while agent_end is still running. // So a headless run waits here for the one-off checks still unfinished; // their feedback then wakes the main assistant, as it does in the TUI and // RPC, which stay open anyway. A cancelled run's feedback never starts a // turn, so cancelling also ends the wait. pi.on("agent_end", async (event, ctx) => { scheduleRunEnd(event, ctx); const endsWhenIdle = ctx.mode === "print" || ctx.mode === "json"; const runSignal = ctx.signal; if (!endsWhenIdle || unfinishedOneOffs.size === 0 || runSignal?.aborted) { return; } const oneOffs = [...unfinishedOneOffs]; const finished = await scheduler.settled(oneOffs, ONE_OFF_HEADLESS_WAIT_MS, runSignal); if (!finished && !runSignal?.aborted) { const stuck = oneOffs.filter((head) => unfinishedOneOffs.has(head)); notifyUser(ctx, `hydra: one-off head ${stuck.join(", ")} did not finish within ${ONE_OFF_HEADLESS_WAIT_MS / 60000} minutes; this headless run ends without waiting for its feedback`, "warning"); } }); function scheduleRunEnd(event: AgentEndEvent, ctx: ExtensionContext) { // The one error that is known to mean hydra has broken the driver. // What the backend actually evicts is not visible from here, so any // such error from the driver, whatever caused it, ends session sharing // for the rest of the session. Backing off costs pennies; getting it // wrong a second time costs the user their work. This is recorded even // with no heads active, so that switching one on later is still safe. // The message is only worth showing when heads exist. if (ctx.model?.api === "openai-codex-responses" && codexShareLostReason === null && hasDriverContinuationError(event.messages)) { codexShareLostReason = "a driver continuation error (hydra backed off to keep the driver safe)"; if (registry.activeSet().length > 0) { notifyUser(ctx, "hydra: the driver hit a continuation error; codex observations retreat to their own cache scope for the rest of this session", "warning"); } } // Before the early returns: a cancelled run may end with nothing to // review, and its one-offs must not wait into the next run. if (ctx.signal?.aborted) { dropHeldOneOffs(ctx, "its run was cancelled"); } if ((registry.activeSet().length === 0 && heldOneOffs.size === 0) || !capturedPayload || !capturedThisRun) { return; } // selectFinalAssistant guarantees role "assistant" with block content. const assistant = selectFinalAssistant(event.messages, responseTimestamp) as AssistantMessage | null; if (!assistant) { return; } scheduleObservations(ctx, "run-end", assistant); } pi.on("session_shutdown", async (_event, ctx) => { shuttingDown = true; dropHeldOneOffs(ctx, "the session ended"); await scheduler.shutdown(parseShutdownGrace(process.env.HYDRA_SHUTDOWN_GRACE_MS, DEFAULT_SHUTDOWN_GRACE_MS)); // pi cleans up the driver's own connection. When observations fall back // to hydra's separate session, that connection is hydra's to close. // Leaving it open keeps a headless run alive long after it should have // exited. cleanupSessionResources(observerSessionId); }); pi.registerMessageRenderer("hydra-feedback", (message, { expanded }, theme) => { const details = message.details; const action = details?.action ?? "noop"; const actionColor = action === "steer" ? "accent" : action === "note" ? "warning" : "muted"; let text = theme.fg("accent", "🐍 hydra ") + theme.fg("toolTitle", `[${details?.head ?? details?.lens ?? "?"}]`) + " " + theme.fg(actionColor, `(${action})`) + "\n" + theme.fg("toolOutput", typeof message.content === "string" ? message.content : ""); if (expanded && details) { text += `\n${theme.fg("dim", `reason: ${details.reason || "(none)"}`)}`; } const box = new Box(1, 1, (t) => theme.bg("customMessageBg", t)); box.addChild(new Text(text, 0, 0)); return box; }); // The driver and every head are shown exactly the same tool. They have to // be, or the replayed request would no longer match and the cache saving // would be lost. Who may do what is decided here instead: the driver // manages heads, any head reports a decision, and only a head allowed the // hydra tool may manage heads. function executeHeadManagement(params: ManageHeadsParams, ctx: ExtensionContext, runSignal?: AbortSignal) { const name = params.head.trim(); const lifetimeLabel = params.operation !== "add" ? undefined : params.lifetime.kind === "once" ? "for one check" : params.lifetime.endsWhen !== undefined ? `until ${params.lifetime.endsWhen}` : undefined; const receipt = formatHeadManagementReceipt(params.operation, name, params.message, lifetimeLabel); const gateway = registryGateway(ctx, runSignal); registry.discover(gateway, ctx.cwd); const activeLabel = () => (registry.activeSet().length > 0 ? registry.activeSet().join(", ") : "none"); const reply = (text: string, changed = false) => ({ content: [{ type: "text" as const, text }], details: { action: params.action, operation: params.operation, head: name, heads: [...registry.activeSet()], changed, receipt, }, }); if (params.operation === "add") { const { source, lifetime } = params; if (registry.activeSet().some((active) => active in DIAGNOSTIC_PROMPTS)) { throw new Error("A diagnostic head is running and holds the active set. Add heads after it has fired."); } const plain = source.kind === "file" && lifetime.kind === "ongoing" && lifetime.endsWhen === undefined; if (source.kind === "inline") { if (registry.exists(name)) { throw new Error(`"${name}" is already a head's name. Pick a new name for a head without a file, or omit instructions to use the head file "${name}".`); } } else if (!registry.exists(name)) { throw new Error(`Unknown head "${name}". Available: ${registry.names().join(", ") || "none"}.`); } else if (!registry.get(name) && !plain) { // Diagnostic heads take over the whole set; they have no lifetime. throw new Error(`"${name}" is a diagnostic head and cannot take a lifetime or ends_when.`); } // Discovery above may have just reread a file that now lists a tool // the main assistant lacks. An active head is turned off then. The // error tells the main assistant, so no note on top. const mismatch = toolMismatchFor(ctx, source.kind === "inline" ? source.tools : registry.headTools(name)); if (mismatch) { const active = registry.isActive(name); const message = headToolBlockMessage(name, mismatch, active ? "is off" : "can't be added"); if (active) { registry.removeHead(gateway, name); notifyUser(ctx, `hydra: ${message}`, "warning"); } throw new Error(message); } if (registry.isActive(name)) { if (!plain) { throw new Error(`"${name}" is already active, so it already checks after every response. Remove it first to add it with a different lifetime or ends_when.`); } return reply(`"${name}" is already active. Observing with: ${activeLabel()}.`); } // A check still waiting or running under this name would share its // lane with the new head, and an old answer could act on the new one. if (heldOneOffs.has(name) || scheduler.isBusy(name)) { throw new Error(`"${name}" is still finishing a check. Wait until it has finished, or use a different name.`); } if (lifetime.kind === "once") { // A head may still be checking after the user cancelled the run it // reviews. Its one-off would start in the next run, which the user // never asked for. if (runSignal?.aborted) { throw new Error("The run this check reviews was cancelled, so a one-off head cannot start from it."); } const head = registry.get(name); heldOneOffs.set( name, source.kind === "inline" ? { instruction: source.instructions, tools: source.tools } : { instruction: head?.prompt ?? "", tools: registry.headTools(name) }, ); return reply(`${receipt}\nIt checks once, starting with the next response; its feedback arrives later. Observing with: ${activeLabel()}.`, true); } registry.addHead(gateway, name, { withoutFile: source.kind === "inline" ? { instructions: source.instructions, tools: source.tools } : undefined, endsWhen: lifetime.endsWhen, }); return reply(`${receipt}\nObserving with: ${activeLabel()}.`, true); } if (!registry.isActive(name)) { return reply(`"${name}" is not active. Observing with: ${activeLabel()}.`); } registry.removeHead(gateway, name); return reply(`${receipt}\nObserving with: ${activeLabel()}.`, true); } async function executeObservationHydra( _toolCallId: string, rawParams: RawHydraToolParams, _signal: AbortSignal | undefined, ctx: ExtensionContext, job: Observation, state: ObservationToolState, ) { const params = validateHydraToolParams(rawParams); if (params.action === "complete_observation") { if (state.completion) { throw new Error("complete_observation was already accepted for this observation"); } const decision = decisionFromCompletion(params.delivery, params.message); state.completion = decision; state.done = params.done === true; return { content: [{ type: "text" as const, text: "Observation completed." }], details: { action: params.action, changed: false }, terminate: true, }; } if (!job.tools.includes("hydra")) { throw new Error(`Head "${job.head}" is not allowed to manage heads`); } const result = executeHeadManagement(params, ctx, job.runSignal); if (!result.details.changed) { return result; } const receipt = result.details.receipt; // Observer tool results are hidden from both user and driver, and a // head that removed itself gets no further turn, so Hydra steers the // receipt. Driver-originated calls skip this path because their tool // result is already visible. steerForHead(ctx, job.head, "head set changed", receipt, job.runSignal); return result; } const hydraToolDefinition = { name: "hydra", label: "Hydra", description: hydraToolDescription(userHeadDir), parameters: hydraToolParameters, async execute( _toolCallId: string, rawParams: RawHydraToolParams, _signal: AbortSignal | undefined, _onUpdate: unknown, ctx: ExtensionContext, ) { const params = validateHydraToolParams(rawParams); if (params.action === "complete_observation") { throw new Error("complete_observation is only available while hydra is running a head observation"); } return executeHeadManagement(params, ctx); }, // Hydra's own row, so extensions that redraw tool rows (for example to hide finished ones) can // handle it; pi's generic row is not available to them. Collapsed: what changed. Expanded: every argument. renderCall(args: RawHydraToolParams, theme: Theme, context: { expanded: boolean }) { // While the model is still writing the call, args can be partial. const params = args ?? {}; const summary = [params.operation ?? params.action, params.head].filter((part) => typeof part === "string").join(" "); let text = theme.fg("toolTitle", theme.bold("hydra")) + (summary ? ` ${theme.fg("muted", summary)}` : ""); if (context.expanded) { const lines = Object.entries(params).map(([key, value]) => ` ${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`); if (lines.length > 0) text += `\n${theme.fg("muted", lines.join("\n"))}`; } return new Text(text, 0, 0); }, renderResult(result: { content: { type: string; text?: string }[] }, _options: unknown, theme: Theme) { const output = result.content.filter((block) => block.type === "text").map((block) => block.text ?? "").join("\n").trim(); return new Text(output ? theme.fg("toolOutput", output) : "", 0, 0); }, }; pi.registerTool(hydraToolDefinition); // A checkbox list of every head found. Hand-built because pi's own picker // only allows one choice. Enter applies whatever is ticked, which is the // same "this is the new set" behavior as typing the names out, and escape // cancels. async function openHeadPicker(ctx: ExtensionContext): Promise { const items = registry.list().sort((a, b) => a.name.localeCompare(b.name)); if (items.length === 0) { notifyUser(ctx, `hydra: no heads found. Drop a markdown file into ${userHeadDir} (see docs/heads.md).`, "warning"); return; } const selection = await ctx.ui.custom((tui, theme, _keybindings, done) => { let cursor = 0; const checked = new Set(registry.activeSet().filter((name) => registry.get(name) !== undefined)); function handleInput(data: string) { if (matchesKey(data, Key.escape)) { done(null); return; } if (matchesKey(data, Key.enter)) { done([...checked]); return; } if (matchesKey(data, Key.up)) { cursor = (cursor + items.length - 1) % items.length; } else if (matchesKey(data, Key.down)) { cursor = (cursor + 1) % items.length; } else if (matchesKey(data, Key.space)) { const name = items[cursor].name; if (checked.has(name)) { checked.delete(name); } else { checked.add(name); } } else { return; } tui.requestRender(); } function render(width: number): string[] { const lines: string[] = []; lines.push(theme.fg("accent", "hydra heads")); for (let i = 0; i < items.length; i++) { const item = items[i]; const tags = [ item.source === "project" ? "project" : item.source === "call" ? "no file" : null, registry.endsWhen(item.name) !== undefined ? `until ${registry.endsWhen(item.name)}` : null, item.autostart ? "autostart" : null, headActs(item.tools) ? "tools" : null, ].filter((tag): tag is string => tag !== null); const row = (i === cursor ? theme.fg("accent", "❯ ") : " ") + theme.fg(checked.has(item.name) ? "success" : "muted", checked.has(item.name) ? "[x] " : "[ ] ") + theme.fg(i === cursor ? "accent" : "toolTitle", item.name) + theme.fg("muted", ` ${item.description}`) + (tags.length > 0 ? theme.fg("dim", ` (${tags.join(", ")})`) : ""); lines.push(truncateToWidth(row, width)); } lines.push(theme.fg("dim", " ↑↓ move • space toggle • enter apply • esc cancel")); return lines; } // No render cache to drop, so invalidate has nothing to do. return { render, handleInput, invalidate: () => {} }; }); if (selection === null) { return; } const gateway = registryGateway(ctx); if (selection.length === 0) { registry.clearHeadSet(gateway); ctx.ui.notify("hydra: no heads active", "info"); return; } if (registry.setHeadSet(gateway, selection)) { ctx.ui.notify(`hydra: heads=${registry.activeSet().join("+")}`, "info"); } } pi.registerCommand("hydra-heads", { description: `Pick the active hydra heads: no argument opens the picker, "quality,security" sets them, "none" clears them`, getArgumentCompletions: (prefix: string) => { // Complete the segment after the last separator, so head sets can be // typed as "quality,sec". const split = prefix.match(/^(.*[,\s])?([^,\s]*)$/); const base = split?.[1] ?? ""; const partial = split?.[2] ?? ""; return [...registry.names(), "none"] .filter((name) => name.startsWith(partial)) .map((name) => { const source = registry.get(name)?.source; return { value: base + name, label: source === "project" ? `${name} (project)` : source === "call" ? `${name} (no file)` : name }; }); }, handler: async (args, ctx) => { const gateway = registryGateway(ctx); registry.discover(gateway, ctx.cwd); const trimmed = args.trim(); if (trimmed === "none") { registry.clearHeadSet(gateway); ctx.ui.notify("hydra: no heads active", "info"); return; } if (trimmed.length === 0) { if (ctx.hasUI) { await openHeadPicker(ctx); } else { const roster = registry.list().map((head) => ` ${head.name} (${head.source === "call" ? "no file" : head.source}): ${head.description}`); ctx.ui.notify( [`hydra: active: ${registry.activeSet().join(", ") || "none"}`, ...(roster.length > 0 ? ["available:", ...roster] : [`no heads in ${userHeadDir}`])].join("\n"), "info", ); } return; } if (registry.setHeadSet(gateway, parseHeadList(trimmed))) { ctx.ui.notify(`hydra: heads=${registry.activeSet().join("+")}`, "info"); } }, }); pi.registerCommand("hydra-stats", { description: "Show hydra observation statistics", handler: async (_args, ctx) => { const calls = stats.all(); if (calls.length === 0) { ctx.ui.notify("hydra: no observations yet", "info"); return; } const { cost, read, write, input, meanHit } = stats.cumulative(ctx.model?.api); // Includes deprecated print decisions from saved sessions. const counts: Record = { noop: 0, print: 0, note: 0, steer: 0 }; const failed = new Map(); let totalDuration = 0; for (const call of calls) { for (const action of call.actions?.length ? call.actions : [call.action]) { counts[action]++; } if (call.judgeErrorKind) failed.set(call.judgeErrorKind, (failed.get(call.judgeErrorKind) ?? 0) + 1); totalDuration += call.durationMs; } const failedTotal = [...failed.values()].reduce((sum, n) => sum + n, 0); const failedKinds = [...failed].map(([kind, n]) => `${n} ${kind}`).join(", "); const recent = calls .slice(-10) .map( (call) => ` turn ${call.turnIndex} ${call.head}${call.kind ? ` [${call.kind}]` : ""} ${ call.actions?.length ? call.actions.join("+") : call.action }${ call.iterations ? ` (${call.iterations} turns: ${[...new Set(call.toolsUsed ?? [])].join(",") || "no tools"})` : "" } hit=${call.hitRatio.toFixed(1)}% $${call.cost.toFixed(4)} ${call.durationMs}ms`, ) .join("\n"); ctx.ui.notify( [ `hydra stats (${calls.length} observations):`, ` mean hit: ${meanHit === null ? "n/a (no observations on this model yet)" : `${meanHit.toFixed(2)}%`} ← target: ${hitBandsFor(ctx.model?.api).target}`, ` total cost: $${cost.toFixed(4)}`, ` total cache read: ${read.toLocaleString()} tokens`, ` total cache write: ${write.toLocaleString()} tokens`, ` total input (uncached): ${input.toLocaleString()} tokens`, ` mean duration: ${(totalDuration / calls.length).toFixed(0)}ms`, ` decision groups: ${counts.noop} noop / ${counts.print} print / ${counts.note} note / ${counts.steer} steer`, ` failed checks (counted as noop): ${failedTotal}${failedTotal > 0 ? ` (${failedKinds})` : ""}`, "", `recent (last ${Math.min(10, calls.length)}):`, recent, ].join("\n"), "info", ); }, }); pi.registerCommand("hydra-debug", { description: "Toggle hydra payload dumping for cache debugging", handler: async (_args, ctx) => { if (debugDir) { debugDir = null; ctx.ui.notify("hydra: debug dumping disabled", "info"); return; } const dir = join(tmpdir(), `hydra-debug-${Date.now()}`); try { mkdirSync(dir, { recursive: true }); } catch (error) { notifyUser(ctx, `hydra: failed to create debug dir: ${errorText(error)}`, "error"); return; } debugDir = dir; ctx.ui.notify(`hydra: dumping payloads to ${dir}`, "info"); }, }); }