import { AgentMiddleware } from "./types.cjs";
import { BaseMessage } from "@langchain/core/messages";

//#region src/agents/middleware/contextEditing.d.ts

/**
 * Function type for counting tokens in a sequence of messages.
 */
type TokenCounter = (messages: BaseMessage[]) => number | Promise<number>;
/**
 * Protocol describing a context editing strategy.
 *
 * Implement this interface to create custom strategies for managing
 * conversation context size. The `apply` method should modify the
 * messages array in-place and return the updated token count.
 *
 * @example
 * ```ts
 * import { SystemMessage } from "langchain";
 *
 * class RemoveOldSystemMessages implements ContextEdit {
 *   async apply({ tokens, messages, countTokens }) {
 *     // Remove old system messages if over limit
 *     if (tokens > 50000) {
 *       messages = messages.filter(SystemMessage.isInstance);
 *       return await countTokens(messages);
 *     }
 *     return tokens;
 *   }
 * }
 * ```
 */
interface ContextEdit {
  /**
   * Apply an edit to the message list, returning the new token count.
   *
   * This method should:
   * 1. Check if editing is needed based on `tokens` parameter
   * 2. Modify the `messages` array in-place (if needed)
   * 3. Return the new token count after modifications
   *
   * @param params - Parameters for the editing operation
   * @returns The updated token count after applying edits
   */
  apply(params: {
    /**
     * Current token count of all messages
     */
    tokens: number;
    /**
     * Array of messages to potentially edit (modify in-place)
     */
    messages: BaseMessage[];
    /**
     * Function to count tokens in a message array
     */
    countTokens: TokenCounter;
  }): number | Promise<number>;
}
/**
 * Configuration for clearing tool outputs when token limits are exceeded.
 */
interface ClearToolUsesEditConfig {
  /**
   * Token count that triggers the edit.
   * @default 100000
   */
  triggerTokens?: number;
  /**
   * Minimum number of tokens to reclaim when the edit runs.
   * @default 0
   */
  clearAtLeast?: number;
  /**
   * Number of most recent tool results that must be preserved.
   * @default 3
   */
  keep?: number;
  /**
   * Whether to clear the originating tool call parameters on the AI message.
   * @default false
   */
  clearToolInputs?: boolean;
  /**
   * List of tool names to exclude from clearing.
   * @default []
   */
  excludeTools?: string[];
  /**
   * Placeholder text inserted for cleared tool outputs.
   * @default "[cleared]"
   */
  placeholder?: string;
}
/**
 * Strategy for clearing tool outputs when token limits are exceeded.
 *
 * This strategy mirrors Anthropic's `clear_tool_uses_20250919` behavior by
 * replacing older tool results with a placeholder text when the conversation
 * grows too large. It preserves the most recent tool results and can exclude
 * specific tools from being cleared.
 *
 * @example
 * ```ts
 * import { ClearToolUsesEdit } from "langchain";
 *
 * const edit = new ClearToolUsesEdit({
 *   triggerTokens: 100000,       // Start clearing at 100K tokens
 *   clearAtLeast: 0,             // Clear as much as needed
 *   keep: 3,                     // Always keep 3 most recent results
 *   excludeTools: ["important"], // Never clear "important" tool
 *   clearToolInputs: false,      // Keep tool call arguments
 *   placeholder: "[cleared]",    // Replacement text
 * });
 * ```
 */
declare class ClearToolUsesEdit implements ContextEdit {
  #private;
  triggerTokens: number;
  clearAtLeast: number;
  keep: number;
  clearToolInputs: boolean;
  excludeTools: Set<string>;
  placeholder: string;
  constructor(config?: ClearToolUsesEditConfig);
  apply(params: {
    tokens: number;
    messages: BaseMessage[];
    countTokens: TokenCounter;
  }): Promise<number>;
}
/**
 * Configuration for the Context Editing Middleware.
 */
interface ContextEditingMiddlewareConfig {
  /**
   * Sequence of edit strategies to apply. Defaults to a single
   * ClearToolUsesEdit mirroring Anthropic defaults.
   */
  edits?: ContextEdit[];
  /**
   * Whether to use approximate token counting (faster, less accurate)
   * or exact counting implemented by the chat model (potentially slower, more accurate).
   * Currently only OpenAI models support exact counting.
   * @default "approx"
   */
  tokenCountMethod?: "approx" | "model";
}
/**
 * Middleware that automatically prunes tool results to manage context size.
 *
 * This middleware applies a sequence of edits when the total input token count
 * exceeds configured thresholds. By default, it uses the `ClearToolUsesEdit` strategy
 * which mirrors Anthropic's `clear_tool_uses_20250919` behaviour by clearing older
 * tool results once the conversation exceeds 100,000 tokens.
 *
 * ## Basic Usage
 *
 * Use the middleware with default settings to automatically manage context:
 *
 * @example Basic usage with defaults
 * ```ts
 * import { contextEditingMiddleware } from "langchain";
 * import { createAgent } from "langchain";
 *
 * const agent = createAgent({
 *   model: "anthropic:claude-3-5-sonnet",
 *   tools: [searchTool, calculatorTool],
 *   middleware: [
 *     contextEditingMiddleware(),
 *   ],
 * });
 * ```
 *
 * The default configuration:
 * - Triggers when context exceeds **100,000 tokens**
 * - Keeps the **3 most recent** tool results
 * - Uses **approximate token counting** (fast)
 * - Does not clear tool call arguments
 *
 * ## Custom Configuration
 *
 * Customize the clearing behavior with `ClearToolUsesEdit`:
 *
 * @example Custom ClearToolUsesEdit configuration
 * ```ts
 * import { contextEditingMiddleware, ClearToolUsesEdit } from "langchain";
 *
 * const agent = createAgent({
 *   model: "anthropic:claude-3-5-sonnet",
 *   tools: [searchTool, calculatorTool],
 *   middleware: [
 *     contextEditingMiddleware({
 *       edits: [
 *         new ClearToolUsesEdit({
 *           triggerTokens: 50000,      // Clear when exceeding 50K tokens
 *           clearAtLeast: 1000,         // Reclaim at least 1K tokens
 *           keep: 5,                    // Keep 5 most recent tool results
 *           excludeTools: ["search"],   // Never clear search results
 *           clearToolInputs: true,      // Also clear tool call arguments
 *         }),
 *       ],
 *       tokenCountMethod: "approx",     // Use approximate counting (or "model")
 *     }),
 *   ],
 * });
 * ```
 *
 * ## Custom Editing Strategies
 *
 * Implement your own context editing strategy by creating a class that
 * implements the `ContextEdit` interface:
 *
 * @example Custom editing strategy
 * ```ts
 * import { contextEditingMiddleware, type ContextEdit, type TokenCounter } from "langchain";
 * import type { BaseMessage } from "@langchain/core/messages";
 *
 * class CustomEdit implements ContextEdit {
 *   async apply(params: {
 *     tokens: number;
 *     messages: BaseMessage[];
 *     countTokens: TokenCounter;
 *   }): Promise<number> {
 *     // Implement your custom editing logic here
 *     // and apply it to the messages array, then
 *     // return the new token count after edits
 *     return countTokens(messages);
 *   }
 * }
 * ```
 *
 * @param config - Configuration options for the middleware
 * @returns A middleware instance that can be used with `createAgent`
 */
declare function contextEditingMiddleware(config?: ContextEditingMiddlewareConfig): AgentMiddleware<undefined, undefined, any>;
//#endregion
export { ClearToolUsesEdit, ClearToolUsesEditConfig, ContextEdit, ContextEditingMiddlewareConfig, TokenCounter, contextEditingMiddleware };
//# sourceMappingURL=contextEditing.d.cts.map