/** * The recorder that turns pi's tool events into Iteration records (ADR-0002). * * The extension cannot see the turn itself, only the events pi emits around it, * so this class keeps the small amount of state those events need: which fire is * still open, in which session. Three rules follow from the event order and are * the whole point of the class: * * - a fire opens a pending iteration; only once its wake is handed to pi does it * bind, and only then does it capture tool calls (ADR-0009); * - `agent_settled` closes the bound iterations, never a pending one; * - a call is recorded into the newest bound iteration of its session, because * the events carry no loop id, so an unbound iteration — a wake still waiting * for an idle agent — must not take the calls of a turn it did not wake; * - `tool_execution_end` pairs by tool call id across every iteration, so a late * result still lands on the call that produced it. * * Opening, binding and recording an iteration is written out at once, because the * record only exists on disk: a reader sees an iteration only after it is written. * Closing one is not written here — a settle closes iterations and their loops' * schedules together, so the caller writes that one record once (ticket #46). * * @author mystery4f <40482524+mystery4f@users.noreply.github.com> */ import type { TaskScope } from "../base/runtime-state.js"; import type { TaskSessions } from "../base/task-sessions.js"; import type { IterationResult, LoopFire } from "./loop-tasks.js"; /** The start event's fields the recorder needs; pi passes the same ones. */ export interface ToolCallStartEvent { readonly toolCallId: string; readonly toolName: string; readonly args: unknown; } /** The end event's fields the recorder needs. */ export interface ToolCallEndEvent { readonly toolCallId: string; readonly toolName: string; readonly result: unknown; readonly isError: boolean; readonly durationMs?: number; } /** * What one provider attempt of the turn in flight looks like from the outside: * the assistant message it ended, and the retry budget the settings allow. * * pi 1.5.2 forwards no retry event to extensions — `auto_retry_start` and * `auto_retry_end` reach public listeners only, and `ExtensionAPI.on` has no * retry event to subscribe to — so the attempt is counted from the message that * carries the failure (`stopReason === "error"`). The attempt after a failure * ends a message too, which is what clears the count. */ export interface ProviderAttemptEvent { readonly role: string; readonly stopReason?: string; /** What the provider said; carries the status code when it gave one. */ readonly errorMessage?: string; /** Retries the settings allow; 0 when pi is not retrying, so nothing is counted. */ readonly maxAttempts: number; } /** * Retries pi makes after a failed attempt when the settings do not say. pi's * `SETTINGS_DEFAULTS` is not exported from the package root, so its default of * three is restated here once instead of being spread over the call sites. */ export declare const DEFAULT_RETRY_BUDGET = 3; /** The retry settings an attempt counter reads; the rest of `Settings` is not its business. */ export interface RetrySettingsLike { readonly enabled?: boolean; readonly maxRetries?: number; } /** * Retries pi is configured to make after a failure. Zero — retries disabled, or a * budget of zero — means the first failure is final, so no attempt is counted: * `retry 1/1` would promise a retry that is never coming. */ export declare function retryBudget(settings: { readonly retry?: RetrySettingsLike; } | undefined): number; export interface IterationsOptions { readonly sessions: TaskSessions; /** Clock seam for tests; defaults to `Date.now`. */ readonly now?: () => number; /** Tool calls kept per iteration; defaults to `ITERATION_CALL_LIMIT`. */ readonly callLimit?: number; /** Iterations kept per loop; defaults to `ITERATION_HISTORY_LIMIT`. */ readonly historyLimit?: number; } /** Both caps are positive counts: a zero would record nothing and say nothing. */ export declare function positiveLimit(value: number | undefined, fallback: number, name: string): number; export declare class Iterations { private readonly sessions; private readonly now; private readonly callLimit; private readonly historyLimit; /** * The last word of the turn in flight, waiting for its settle (ticket #46). * The assistant message is the only place a turn's outcome is visible, and * `settle` is the only event that says the turn is over, so the two facts meet * here rather than in the loop record. */ private turn; constructor(options: IterationsOptions); /** * Open the iteration for one fire and persist it, so a wake that is still * waiting for an idle agent — or a turn that ends before its first tool call — * still leaves a record. The iteration stays pending: it takes no calls until * `bind` marks the wake as sent. */ open(fire: LoopFire): Promise; /** * Bind the iteration to the turn its wake produced: called right after the * wake is handed to pi. From here on the turn's tool calls are its own. */ bind(fire: LoopFire): void; /** * Forget a fire that never woke the model — its loop was paused, completed or * deleted while the wake waited. The iteration goes with it: a pending record * that stays `running` forever would claim a turn that never happened. A bound * iteration is left alone: its wake already left for pi, so the turn is real * and `settle` owns the record from here on. */ drop(fire: LoopFire): Promise; /** Record one tool call's start into the newest open iteration of the session. */ recordStart(scope: TaskScope, start: ToolCallStartEvent): Promise; /** * Record how one tool call ended, found by its id. A call the recorder never * saw is ignored: a turn outside a fire is not an iteration, and its calls * must not appear in this loop's record. */ recordEnd(scope: TaskScope, end: ToolCallEndEvent): Promise; /** * Count one provider attempt of the turn in flight against the iteration that * opened it (ticket #47). A failed attempt has no event of its own — see * `ProviderAttemptEvent` — so it arrives as the assistant message that ended * with `stopReason: "error"`, and the attempt after it is what clears the * count while the turn is still open. * * Nothing is counted when the budget is zero: pi gives up at the first failure * then, so there is no retry to show. */ recordAttempt(scope: TaskScope, attempt: ProviderAttemptEvent): Promise; /** * Close every bound iteration still open in the session, because one run * settles at a time and a bound fire's turn is that run. Calls still running * at that point cannot end any more: `aborted` when the run was aborted, * `interrupted` otherwise. Pending iterations stay pending: their wake has not * produced a turn yet, so this settle is not theirs. * * One turn can be several loops' fire — every loop that came due while the agent * was busy is bound and delivered before the turn starts — so the caller gets one * result per loop that had an iteration closed here, read from that loop's newest * one. A loop with two iterations in the same turn is still one fire to charge. */ settle(scope: TaskScope, aborted: boolean): Promise; /** Drop the oldest iterations until the history cap holds. */ private dropOverflow; /** * The iteration a start belongs to: the newest open iteration its wake already * produced. Read from the session's current records every time, because a loop * update replaces the record object and a deleted loop must stop capturing * calls. A pending iteration is skipped, not pruned: its turn has not begun, * and the current turn belongs to whoever started it. */ private newestOpenIteration; /** * Take the verdict waiting for this session's settle. A verdict from another * session belongs to a turn that has not settled yet, so it stays where it is. */ private takeTurn; private resolve; }