import type { AgentMessage } from "@earendil-works/pi-agent-core";
import { type Model, type Tool } from "@earendil-works/pi-ai";
import { type CompactionPreparation, type CompactionResult } from "../../../compaction/index.ts";
import { type WarmAnchorSnapshot } from "../../../compaction/warm-anchor.ts";
import type { ModelRegistry } from "../../../model-registry.ts";
import type { ReadonlySessionManager } from "../../../session-manager.ts";
import type { ApplyCompactionResult, ContextUsage, ProviderRequestPreparation } from "../../types.ts";
import { type MergedCompactionPromptVariant } from "./prompts.ts";
export { createEmergencyPruneLatch, type EmergencyPruneLatch, hardLimitEmergencyPrune, truncateContextMessages, } from "./emergency-prune.ts";
type CompactionProgressCallback = (delta: string) => void;
export interface SpeculativeCompactionContext {
    /** Absolute session directory; subprocess-backed providers (Claude SDK) refuse a summary request without it. */
    cwd: string;
    model: Model<any> | undefined;
    sessionManager: ReadonlySessionManager;
    modelRegistry?: ModelRegistry;
    getContextUsage(): ContextUsage | undefined;
    getCompactionSettings?(): CompactionPreparation["settings"];
    getCompactionModel?(): Model<any> | undefined;
    getMessageRevision(): number;
    getSystemPrompt?(): string;
    getSystemPromptStablePrefix?(): string | undefined;
    prepareProviderRequest?(messages: AgentMessage[]): Promise<ProviderRequestPreparation>;
    isIdle?(): boolean;
    applyCompaction(precomputed: CompactionResult, options: {
        reason: "extension";
        expectedRevision?: number;
        expectedWarmAnchor?: WarmAnchorSnapshot;
        signal?: AbortSignal;
    }): Promise<ApplyCompactionResult>;
}
export interface SpeculativeCompactionSnapshot {
    generation: number;
    expectedRevision: number;
    model: Model<any>;
    contextWindow: number;
    preparation: CompactionPreparation;
    branchEntries?: ReturnType<ReadonlySessionManager["getBranch"]>;
    promptVariant: MergedCompactionPromptVariant;
    origin?: "speculative" | "blocking" | "core-route";
    customInstructions?: string;
    /** Agent system prompt; used to make the summarization request look like normal agent traffic. */
    systemPrompt?: string;
    /** The turn's stable prefix of `systemPrompt`, so the summary request splits it like the turn (senpi#4447). */
    systemPromptStablePrefix?: string;
    /** Agent tool definitions; forwarded so the request shape matches normal agent traffic. */
    tools?: Tool[];
}
export type SpeculativeCompactionResult = ApplyCompactionResult | {
    applied: false;
    reason: "unavailable" | "failed";
};
/**
 * Summary-generation failure with a user-facing diagnosis. Distinct from a
 * user abort (which resolves `undefined`): callers surface `message` on the
 * manual route and degrade to "unavailable" on automatic routes.
 */
/**
 * Provider `error` stop during summarization, carrying the metadata-aware
 * transient classification from the full assistant message. A refusal whose
 * text happens to look retryable must still surface loudly; the message
 * string alone cannot encode that.
 */
export type SummaryRequestFailureKind = "upstream-stream-truncated";
export declare class SummaryRequestError extends Error {
    readonly transient: boolean;
    readonly failureKind?: SummaryRequestFailureKind;
    /**
     * The provider refused the request (refusal/sensitive stop details) rather
     * than failing it. Carried explicitly because the message text cannot encode
     * it, and because a refusal must never authorize destructive context
     * reduction: dropping older detail would not make the model comply.
     */
    readonly refused: boolean;
    constructor(message: string, transient: boolean, failureKind?: SummaryRequestFailureKind, refused?: boolean);
}
/**
 * Only failures with no cheaper recovery earn another billed request.
 *
 * Every class that `classifyRequiredCompactionFallbackFailure` recognizes
 * (watchdog timeouts, the compaction-wide total budget, terminal provider and
 * credential failures, `upstream-stream-truncated`, overflow exhaustion,
 * empty-summary generation failures) already
 * has a deterministic zero-LLM recovery, and context overflow is answered by
 * shrinking the input in the surrounding loop - replaying those would pay for a
 * summarization the fallback can rebuild for free. The classes checked here are
 * mirrored from that classifier rather than imported, because
 * `deterministic-fallback.ts` imports this module.
 */
export declare function isRetryableSummaryAttempt(error: unknown): boolean;
export declare class SummaryGenerationError extends Error {
    readonly kind: "auth" | "empty-summary";
    constructor(kind: "auth" | "empty-summary", message: string);
}
/**
 * Output budget for one summarization request. Adaptive-thinking models emit
 * reasoning tokens before the summary text, so the legacy flat 8192 cap could
 * be consumed entirely by thinking, ending the stream with zero text blocks.
 * Grant generous headroom, clamped to what the model can actually emit and to
 * half the context window: providers that enforce input + output <= window
 * would otherwise reject the request for models advertising contextWindow ==
 * maxTokens (every summarization request also carries conversation input).
 */
export declare function getPromptVariant(options: {
    reason: string;
    preparation: {
        previousSummary?: string;
        isSplitTurn: boolean;
    };
}): MergedCompactionPromptVariant;
export declare function createSpeculativeCompactionSnapshot(context: SpeculativeCompactionContext, options: {
    customInstructions?: string;
    generation: number;
    origin?: "speculative" | "blocking" | "core-route";
    tools?: Tool[];
}): SpeculativeCompactionSnapshot | undefined;
/**
 * Generate a compaction summary for the snapshot. Resolves `undefined` only
 * when the request was aborted (caller signal or an aborted stream); every
 * other failure throws — {@link SummaryGenerationError} for diagnosable
 * generation failures, the raw provider error otherwise. Abort is checked
 * before and after credential resolution so a cancelled request never
 * misreports as an auth failure.
 */
export declare function runExtensionCompaction(context: SpeculativeCompactionContext, snapshot: SpeculativeCompactionSnapshot, signal?: AbortSignal, onProgress?: CompactionProgressCallback): Promise<CompactionResult | undefined>;
export declare function applyGeneratedCompaction(context: SpeculativeCompactionContext, snapshot: SpeculativeCompactionSnapshot | undefined, getCurrentGeneration: () => number, compaction: CompactionResult | undefined, signal?: AbortSignal): Promise<SpeculativeCompactionResult>;
export declare function applySpeculativeCompaction(context: SpeculativeCompactionContext, snapshot: SpeculativeCompactionSnapshot | undefined, getCurrentGeneration: () => number, generate: () => Promise<CompactionResult | undefined>): Promise<SpeculativeCompactionResult>;
//# sourceMappingURL=speculative.d.ts.map