import { z, ZodTypeAny, output, ZodType, ZodTypeDef } from 'zod'; import * as _langchain_core_tools from '@langchain/core/tools'; import { DynamicStructuredTool } from '@langchain/core/tools'; import * as _langchain_langgraph from '@langchain/langgraph'; import { BaseChannel, AnnotationRoot, StateDefinition, UpdateType, StateGraph, END, MemorySaver, BaseCheckpointSaver, CheckpointTuple } from '@langchain/langgraph'; import { RunnableConfig } from '@langchain/core/runnables'; /** * Categories for organizing tools. */ declare enum ToolCategory { FILE_SYSTEM = "file-system", WEB = "web", CODE = "code", DATABASE = "database", API = "api", UTILITY = "utility", CUSTOM = "custom", SKILLS = "skills" } /** * Example usage of a tool to aid documentation and prompt construction. */ interface ToolExample { description: string; input: Record; output?: unknown; explanation?: string; } /** * Relationships between tools to guide ordering and compatibility. */ interface ToolRelations { requires?: string[]; suggests?: string[]; conflicts?: string[]; follows?: string[]; precedes?: string[]; } /** * Rich metadata describing a tool, its examples, and its lifecycle state. */ interface ToolMetadata { name: string; description: string; category: ToolCategory; displayName?: string; tags?: string[]; examples?: ToolExample[]; usageNotes?: string; limitations?: string[]; version?: string; author?: string; deprecated?: boolean; replacedBy?: string; relations?: ToolRelations; } /** * Complete tool contract combining metadata, input schema, and invocation API. */ interface Tool { metadata: ToolMetadata; schema: z.ZodSchema; invoke: (input: TInput) => Promise; /** * @deprecated Use `invoke` instead. */ execute?: (input: TInput) => Promise; } /** * Tool System Schemas * * Zod schemas for runtime validation of tool metadata and configuration. * * Why Zod schemas? * - Runtime validation: Catch errors when tools are created * - Type inference: TypeScript types are automatically inferred * - Great errors: Clear messages when validation fails * - JSON Schema: Can convert to JSON Schema for LangChain */ /** * Schema for ToolCategory * * This validates that a value is one of the valid ToolCategory enum values. * * Example: * ```ts * ToolCategorySchema.parse('file-system'); // ✅ Valid * ToolCategorySchema.parse('invalid'); // ❌ Throws ZodError * ``` */ declare const ToolCategorySchema: z.ZodNativeEnum; /** * Schema for ToolExample * * Validates the structure of tool usage examples. * * Example: * ```ts * ToolExampleSchema.parse({ * description: 'Read a file', * input: { path: './file.txt' }, * output: 'file contents', * explanation: 'Reads and returns file contents' * }); * ``` */ declare const ToolExampleSchema: z.ZodObject<{ /** * Description must be a non-empty string */ description: z.ZodString; /** * Input must be an object (can have any properties) */ input: z.ZodRecord; /** * Output is optional and can be anything */ output: z.ZodOptional; /** * Explanation is optional but must be non-empty if provided */ explanation: z.ZodOptional; }, "strip", z.ZodTypeAny, { description: string; input: Record; output?: unknown; explanation?: string | undefined; }, { description: string; input: Record; output?: unknown; explanation?: string | undefined; }>; /** * Schema for ToolRelations * * Validates tool relationship definitions. * All fields are optional arrays of tool names. * * Example: * ```ts * ToolRelationsSchema.parse({ * requires: ['view-file'], * suggests: ['run-tests', 'format-code'], * conflicts: ['delete-file'], * follows: ['search-codebase'], * precedes: ['run-tests'] * }); * ``` */ declare const ToolRelationsSchema: z.ZodObject<{ /** * Tools that must be called before this tool */ requires: z.ZodOptional>; /** * Tools that work well with this tool */ suggests: z.ZodOptional>; /** * Tools that conflict with this tool */ conflicts: z.ZodOptional>; /** * Tools this typically follows in a workflow */ follows: z.ZodOptional>; /** * Tools this typically precedes in a workflow */ precedes: z.ZodOptional>; }, "strip", z.ZodTypeAny, { requires?: string[] | undefined; suggests?: string[] | undefined; conflicts?: string[] | undefined; follows?: string[] | undefined; precedes?: string[] | undefined; }, { requires?: string[] | undefined; suggests?: string[] | undefined; conflicts?: string[] | undefined; follows?: string[] | undefined; precedes?: string[] | undefined; }>; /** * Schema for tool names * * Tool names must be: * - Lowercase letters, numbers, and hyphens only * - Start with a letter * - Not start or end with a hyphen * - Between 2 and 50 characters * * Valid: 'read-file', 'http-request', 'query-db' * Invalid: 'ReadFile', 'read_file', '-read-file', 'r' */ declare const ToolNameSchema: z.ZodString; /** * Schema for ToolMetadata * * Validates all tool metadata fields with appropriate constraints. * * Example: * ```ts * ToolMetadataSchema.parse({ * name: 'read-file', * description: 'Read a file from the file system', * category: ToolCategory.FILE_SYSTEM, * tags: ['file', 'read'], * examples: [{ description: 'Read README', input: { path: './README.md' } }] * }); * ``` */ declare const ToolMetadataSchema: z.ZodObject<{ /** * Tool name - must be valid kebab-case */ name: z.ZodString; /** * Description - must be meaningful (at least 10 characters) */ description: z.ZodString; /** * Category - must be a valid ToolCategory */ category: z.ZodNativeEnum; /** * Display name - if provided, must be non-empty */ displayName: z.ZodOptional; /** * Tags - array of non-empty strings */ tags: z.ZodOptional>; /** * Examples - array of valid ToolExample objects */ examples: z.ZodOptional; /** * Output is optional and can be anything */ output: z.ZodOptional; /** * Explanation is optional but must be non-empty if provided */ explanation: z.ZodOptional; }, "strip", z.ZodTypeAny, { description: string; input: Record; output?: unknown; explanation?: string | undefined; }, { description: string; input: Record; output?: unknown; explanation?: string | undefined; }>, "many">>; /** * Usage notes - if provided, must be meaningful */ usageNotes: z.ZodOptional; /** * Limitations - array of non-empty strings */ limitations: z.ZodOptional>; /** * Version - if provided, should follow semver format * Examples: '1.0.0', '2.1.3', '0.1.0-beta', '1.0.0-alpha.1' */ version: z.ZodOptional; /** * Author - if provided, must be non-empty */ author: z.ZodOptional; /** * Deprecated flag */ deprecated: z.ZodOptional; /** * Replacement tool name - if provided, must be valid tool name */ replacedBy: z.ZodOptional; /** * Tool relations - defines relationships with other tools */ relations: z.ZodOptional>; /** * Tools that work well with this tool */ suggests: z.ZodOptional>; /** * Tools that conflict with this tool */ conflicts: z.ZodOptional>; /** * Tools this typically follows in a workflow */ follows: z.ZodOptional>; /** * Tools this typically precedes in a workflow */ precedes: z.ZodOptional>; }, "strip", z.ZodTypeAny, { requires?: string[] | undefined; suggests?: string[] | undefined; conflicts?: string[] | undefined; follows?: string[] | undefined; precedes?: string[] | undefined; }, { requires?: string[] | undefined; suggests?: string[] | undefined; conflicts?: string[] | undefined; follows?: string[] | undefined; precedes?: string[] | undefined; }>>; }, "strip", z.ZodTypeAny, { description: string; name: string; category: ToolCategory; displayName?: string | undefined; tags?: string[] | undefined; examples?: { description: string; input: Record; output?: unknown; explanation?: string | undefined; }[] | undefined; usageNotes?: string | undefined; limitations?: string[] | undefined; version?: string | undefined; author?: string | undefined; deprecated?: boolean | undefined; replacedBy?: string | undefined; relations?: { requires?: string[] | undefined; suggests?: string[] | undefined; conflicts?: string[] | undefined; follows?: string[] | undefined; precedes?: string[] | undefined; } | undefined; }, { description: string; name: string; category: ToolCategory; displayName?: string | undefined; tags?: string[] | undefined; examples?: { description: string; input: Record; output?: unknown; explanation?: string | undefined; }[] | undefined; usageNotes?: string | undefined; limitations?: string[] | undefined; version?: string | undefined; author?: string | undefined; deprecated?: boolean | undefined; replacedBy?: string | undefined; relations?: { requires?: string[] | undefined; suggests?: string[] | undefined; conflicts?: string[] | undefined; follows?: string[] | undefined; precedes?: string[] | undefined; } | undefined; }>; /** * Helper function to validate tool metadata * * This is a convenience function that validates metadata and returns * a typed result with helpful error messages. * * Example: * ```ts * const result = validateToolMetadata({ * name: 'read-file', * description: 'Read a file', * category: ToolCategory.FILE_SYSTEM * }); * * if (result.success) { * console.log('Valid metadata:', result.data); * } else { * console.error('Validation errors:', result.error.errors); * } * ``` */ declare function validateToolMetadata(metadata: unknown): z.SafeParseReturnType<{ description: string; name: string; category: ToolCategory; displayName?: string | undefined; tags?: string[] | undefined; examples?: { description: string; input: Record; output?: unknown; explanation?: string | undefined; }[] | undefined; usageNotes?: string | undefined; limitations?: string[] | undefined; version?: string | undefined; author?: string | undefined; deprecated?: boolean | undefined; replacedBy?: string | undefined; relations?: { requires?: string[] | undefined; suggests?: string[] | undefined; conflicts?: string[] | undefined; follows?: string[] | undefined; precedes?: string[] | undefined; } | undefined; }, { description: string; name: string; category: ToolCategory; displayName?: string | undefined; tags?: string[] | undefined; examples?: { description: string; input: Record; output?: unknown; explanation?: string | undefined; }[] | undefined; usageNotes?: string | undefined; limitations?: string[] | undefined; version?: string | undefined; author?: string | undefined; deprecated?: boolean | undefined; replacedBy?: string | undefined; relations?: { requires?: string[] | undefined; suggests?: string[] | undefined; conflicts?: string[] | undefined; follows?: string[] | undefined; precedes?: string[] | undefined; } | undefined; }>; /** * Helper function to validate tool name * * Quick validation for just the tool name. * * Example: * ```ts * validateToolName('read-file'); // ✅ Returns true * validateToolName('ReadFile'); // ❌ Returns false * ``` */ declare function validateToolName(name: string): boolean; /** * Schema Validation Utilities * * Helpers to ensure schemas are properly configured for LLM usage, * including enforcing descriptions on all fields. */ /** * Error thrown when a schema field is missing a description */ declare class MissingDescriptionError extends Error { readonly fieldPath: string[]; readonly fieldType: string; constructor(fieldPath: string[], fieldType: string); } /** * Validates that all fields in a Zod schema have descriptions * * Why enforce descriptions? * - LLMs need context to understand what each parameter does * - Descriptions are converted to JSON Schema for tool calling * - Better descriptions = Better tool selection and usage * * @param schema - The Zod schema to validate * @param fieldPath - Internal: current field path for nested objects * @throws {MissingDescriptionError} If any field lacks a description * * @example * ```ts * // ❌ This will throw - no descriptions * const badSchema = z.object({ * name: z.string(), * age: z.number() * }); * validateSchemaDescriptions(badSchema); // Throws! * * // ✅ This is valid - all fields have descriptions * const goodSchema = z.object({ * name: z.string().describe('User name'), * age: z.number().describe('User age in years') * }); * validateSchemaDescriptions(goodSchema); // OK! * ``` */ declare function validateSchemaDescriptions(schema: z.ZodTypeAny, fieldPath?: string[]): void; /** * Safe version of validateSchemaDescriptions that returns a result * instead of throwing * * @param schema - The Zod schema to validate * @returns Object with success flag and optional error * * @example * ```ts * const result = safeValidateSchemaDescriptions(schema); * if (!result.success) { * console.error('Missing descriptions:', result.error.message); * } * ``` */ declare function safeValidateSchemaDescriptions(schema: z.ZodTypeAny): { success: boolean; error?: MissingDescriptionError; }; /** * Helper to get all missing descriptions from a schema * * @param schema - The Zod schema to check * @returns Array of field paths that are missing descriptions * * @example * ```ts * const missing = getMissingDescriptions(schema); * if (missing.length > 0) { * console.log('Fields missing descriptions:', missing); * } * ``` */ declare function getMissingDescriptions(schema: z.ZodTypeAny): string[]; /** * Tool Creation Helpers * * Utility functions to create tools with automatic validation. */ /** * Create a tool with automatic validation * * This function validates: * 1. Metadata is valid (name, description, category, etc.) * 2. Schema has descriptions on ALL fields (enforced!) * * Why enforce descriptions? * - LLMs need context to understand parameters * - Better descriptions = Better tool usage * - Prevents common mistakes * * @param metadata - Tool metadata * @param schema - Zod schema for input validation (must have descriptions!) * @param invoke - Tool implementation (primary method, industry standard) * @returns Validated tool * @throws {Error} If metadata is invalid or schema is missing descriptions * * @example * ```ts * // ✅ This works - all fields have descriptions * const tool = createTool( * { * name: 'read-file', * description: 'Read a file from the file system', * category: ToolCategory.FILE_SYSTEM, * }, * z.object({ * path: z.string().describe('Path to the file to read'), * }), * async ({ path }) => { * // Implementation * } * ); * * // ❌ This throws - missing description on 'path' * const badTool = createTool( * { name: 'bad', description: 'Bad tool', category: ToolCategory.UTILITY }, * z.object({ * path: z.string(), // No .describe()! * }), * async ({ path }) => {} * ); * ``` */ declare function createTool(metadata: ToolMetadata, schema: z.ZodSchema, invoke: (input: TInput) => Promise): Tool; /** * Create a tool without enforcing schema descriptions * * ⚠️ WARNING: Only use this if you have a good reason to skip description validation. * In most cases, you should use `createTool()` instead. * * This is useful for: * - Migration from existing code * - Tools with dynamic schemas * - Testing * * @param metadata - Tool metadata * @param schema - Zod schema for input validation * @param invoke - Tool implementation (primary method, industry standard) * @returns Tool (without schema validation) */ declare function createToolUnsafe(metadata: ToolMetadata, schema: z.ZodSchema, invoke: (input: TInput) => Promise): Tool; /** * Validate an existing tool * * Checks both metadata and schema descriptions. * * @param tool - The tool to validate * @returns Validation result with success flag and errors * * @example * ```ts * const result = validateTool(myTool); * if (!result.success) { * console.error('Tool validation failed:', result.errors); * } * ``` */ declare function validateTool(tool: Tool): { success: boolean; errors: string[]; }; type ToolInvoke = (this: unknown, input: unknown) => Promise; type SafeToolResult = { success: boolean; data?: T; error?: string; }; declare class ToolBuilder { private metadata; private _schema?; private _invoke?; constructor(metadata?: Partial, _schema?: z.ZodSchema | undefined, _invoke?: ToolInvoke | undefined); name(name: string): this; description(description: string): this; category(category: ToolCategory): this; displayName(displayName: string): this; tags(tags: string[]): this; tag(tag: string): this; example(example: ToolExample): this; usageNotes(notes: string): this; limitations(limitations: string[]): this; limitation(limitation: string): this; version(version: string): this; author(author: string): this; requires(tools: string[]): this; suggests(tools: string[]): this; conflicts(tools: string[]): this; follows(tools: string[]): this; precedes(tools: string[]): this; schema(schema: z.ZodSchema): ToolBuilder; implement(invoke: (input: TInput) => Promise): ToolBuilder; implementSafe(invoke: (input: TInput) => Promise): ToolBuilder>; build(): Tool; } declare function toolBuilder(): ToolBuilder; type RegistryTool = Tool; type RegistryEventHandler = (data: TData) => void; interface RegistryPromptOptions { includeExamples?: boolean; includeNotes?: boolean; includeLimitations?: boolean; includeRelations?: boolean; groupByCategory?: boolean; categories?: ToolCategory[]; maxExamplesPerTool?: number; minimal?: boolean; } declare enum RegistryEvent { TOOL_REGISTERED = "tool:registered", TOOL_REMOVED = "tool:removed", TOOL_UPDATED = "tool:updated", REGISTRY_CLEARED = "registry:cleared" } type EventHandler = RegistryEventHandler; interface PromptOptions extends RegistryPromptOptions { } declare class ToolRegistry { private tools; private eventHandlers; private readonly mutationEvents; private readonly emitMutation; private readonly mutations; private readonly queries; constructor(); register(tool: Tool): void; get(name: string): RegistryTool | undefined; has(name: string): boolean; remove(name: string): boolean; update(name: string, tool: Tool): boolean; getAll(): RegistryTool[]; getByCategory(category: ToolCategory): RegistryTool[]; getByTag(tag: string): RegistryTool[]; search(query: string): RegistryTool[]; registerMany(tools: Iterable>): void; clear(): void; size(): number; getNames(): string[]; on(event: RegistryEvent, handler: EventHandler): void; off(event: RegistryEvent, handler: EventHandler): void; private emit; toLangChainTools(): _langchain_core_tools.DynamicStructuredTool<_langchain_core_tools.ToolSchemaBase, any, any, any, string>[]; generatePrompt(options?: PromptOptions): string; } type Priority$1 = 'low' | 'normal' | 'high' | 'critical'; type BackoffStrategy$1 = 'linear' | 'exponential' | 'fixed'; interface RetryPolicy { maxAttempts: number; backoff: BackoffStrategy$1; initialDelay?: number; maxDelay?: number; retryableErrors?: string[]; } interface ExecutableTool { name?: string; metadata?: { name?: string; }; invoke?: (input: TInput) => Promise; execute?: (input: TInput) => Promise; } interface ToolExecutorConfig { maxConcurrent?: number; timeout?: number; retryPolicy?: RetryPolicy; priorityFn?: (tool: ExecutableTool) => Priority$1; onExecutionStart?: (tool: ExecutableTool, input: unknown) => void; onExecutionComplete?: (tool: ExecutableTool, input: unknown, result: unknown, duration: number) => void; onExecutionError?: (tool: ExecutableTool, input: unknown, error: Error, duration: number) => void; } interface ToolExecution { tool: ExecutableTool; input: unknown; priority?: Priority$1; } interface ExecutionMetrics { totalExecutions: number; successfulExecutions: number; failedExecutions: number; totalDuration: number; averageDuration: number; byPriority: Record; } /** * Tool Executor - Async tool execution with resource management * @module tools/executor */ /** * Create a tool executor with resource management */ declare function createToolExecutor(config?: ToolExecutorConfig): { execute: (tool: ExecutableTool, input: unknown, options?: { priority?: Priority$1; }) => Promise; executeParallel: (executions: ToolExecution[]) => Promise; getMetrics: () => ExecutionMetrics; resetMetrics: () => void; getQueueStatus: () => { queueLength: number; activeExecutions: number; maxConcurrent: number; }; }; /** * Shared JSON-safe payload contracts for observability and monitoring paths. */ type JsonPrimitive = string | number | boolean | null; type JsonValue = JsonPrimitive | JsonObject | JsonValue[]; interface JsonObject { [key: string]: JsonValue; } interface ToolHealthCheckResult { healthy: boolean; error?: string; metadata?: JsonObject; } interface ManagedToolConfigBase { name: string; description: string; initialize?: (this: ManagedTool) => Promise; execute: (this: ManagedTool, input: TInput) => Promise; cleanup?: (this: ManagedTool) => Promise; healthCheck?: (this: ManagedTool) => Promise; autoCleanup?: boolean; healthCheckInterval?: number; } interface ManagedToolConfig extends ManagedToolConfigBase { context?: TContext; } interface ManagedToolStats { initialized: boolean; totalExecutions: number; successfulExecutions: number; failedExecutions: number; lastExecutionTime?: number; lastHealthCheck?: ToolHealthCheckResult; lastHealthCheckTime?: number; } declare class ManagedTool { readonly name: string; readonly description: string; private readonly initializeFn?; private readonly executeFn; private readonly cleanupFn?; private readonly healthCheckFn?; private readonly autoCleanup; private readonly healthCheckInterval?; private readonly state; constructor(config: ManagedToolConfig); get context(): TContext | undefined; set context(value: TContext | undefined); get initialized(): boolean; initialize(): Promise; execute(input: TInput): Promise; cleanup(): Promise; healthCheck(): Promise; getStats(): ManagedToolStats; resetStats(): void; toLangChainTool(): { name: string; description: string; invoke: (input: TInput) => Promise; }; private runPeriodicHealthCheck; private ensureBeforeExitHandler; } declare function createManagedTool(config: ManagedToolConfig): ManagedTool; /** * Tool Composition - Compose tools into higher-level operations * @module tools/composition */ type RetryBackoffStrategy = 'linear' | 'exponential'; interface RetryOptions$1 { maxAttempts?: number; delay?: number; backoff?: RetryBackoffStrategy; } interface ComposedTool { name: string; description: string; invoke(input: TInput): Promise; } interface ConditionalConfig { condition(input: TInput): boolean | Promise; onTrue: ComposedTool; onFalse: ComposedTool; } type ComposedStep = ComposedTool | ComposedTool[] | ConditionalConfig; interface ComposeToolConfig { name: string; description?: string; steps: ComposedStep[]; transformResult?: (result: unknown) => TOutput; } /** * Execute tools sequentially */ declare function sequential(tools: ComposedTool[]): ComposedTool; /** * Execute tools in parallel */ declare function parallel(tools: ComposedTool[]): ComposedTool; /** * Execute tool conditionally */ declare function conditional(config: ConditionalConfig): ComposedTool; /** * Compose tools into a complex workflow */ declare function composeTool(config: ComposeToolConfig): ComposedTool; /** * Create a tool that retries on failure */ declare function retry(tool: ComposedTool, options?: RetryOptions$1): ComposedTool; /** * Create a tool that times out */ declare function timeout(tool: ComposedTool, ms: number): ComposedTool; /** * Create a tool that caches results */ declare function cache(tool: ComposedTool, ttl?: number): ComposedTool; /** * Tool Mocking & Testing - Mock tools for testing * @module tools/testing */ type MockToolMatcher = TInput | ((input: TInput) => boolean); interface MockToolSuccessResponse { input: MockToolMatcher; output: TOutput; error?: never; } interface MockToolErrorResponse { input: MockToolMatcher; output?: never; error: Error; } type MockToolResponse = MockToolSuccessResponse | MockToolErrorResponse; interface MockToolConfig { name: TName; description?: string; responses?: MockToolResponse[]; defaultResponse?: TOutput; latency?: { min: number; max: number; } | number; errorRate?: number; } interface ToolInvocation { input: TInput; output?: TOutput; error?: Error; timestamp: number; duration: number; } interface SimulatedTool { name: TName; invoke(input: TInput): Promise; } type ToolName = TTools[number]['name'] & string; type ToolByName> = Extract; type ToolInputFor> = ToolByName extends SimulatedTool ? TInput : never; type ToolOutputFor> = ToolByName extends SimulatedTool ? TOutput : never; interface ToolSimulatorConfig { tools: TTools; errorRate?: number; latency?: { mean: number; stddev: number; }; recordInvocations?: boolean; } interface MockTool extends SimulatedTool { description: string; getInvocations: () => ToolInvocation[]; clearInvocations: () => void; } /** * Create a mock tool for testing */ declare function createMockTool(config: MockToolConfig): MockTool; /** * Create a tool simulator for testing */ declare function createToolSimulator(config: ToolSimulatorConfig): { execute: >(toolName: TName, input: ToolInputFor) => Promise>; getInvocations: >(toolName: TName) => ToolInvocation, ToolOutputFor>[]; getAllInvocations: () => Partial[]>>; clearInvocations: (toolName?: ToolName) => void; }; interface MockExecutionRuntimeOptions { latency?: number | { min: number; max: number; } | (() => number); shouldError?: boolean | ((input: TInput) => boolean); errorFactory?: (input: TInput) => Error; } declare function runMockExecution(input: TInput, execute: () => Promise | TOutput, options?: MockExecutionRuntimeOptions): Promise; /** * LangChain Integration - Tool Converter * * Converts AgentForge tools to LangChain StructuredTool format. * * @example * ```ts * import { toLangChainTool } from '@agentforge/core'; * * const langchainTool = toLangChainTool(agentforgeTool); * ``` */ type RuntimeSchema = z.ZodSchema; type JsonSchemaObject = Record; interface LangChainConvertibleTool { metadata: ToolMetadata; schema: RuntimeSchema; invoke(input: TInput): Promise; } /** * Convert an AgentForge tool to a LangChain DynamicStructuredTool * * This allows AgentForge tools to be used with LangChain agents and chains. * * @param tool - The AgentForge tool to convert * @returns A LangChain DynamicStructuredTool * * @example * ```ts * const readFileTool = toolBuilder() * .name('read-file') * .description('Read a file from the file system') * .category(ToolCategory.FILE_SYSTEM) * .schema(z.object({ * path: z.string().describe('Path to the file'), * })) * .implement(async ({ path }) => { * return fs.readFileSync(path, 'utf-8'); * }) * .build(); * * // Convert to LangChain tool * const langchainTool = toLangChainTool(readFileTool); * * // Use with LangChain agent * const agent = createAgent({ * model: new ChatOpenAI(), * tools: [langchainTool], * }); * ``` */ declare function toLangChainTool(tool: Tool): DynamicStructuredTool, TInput, TInput, string>; /** * Convert multiple AgentForge tools to LangChain tools * * @param tools - Array of AgentForge tools * @returns Array of LangChain DynamicStructuredTools * * @example * ```ts * const tools = [readFileTool, writeFileTool, searchTool]; * const langchainTools = toLangChainTools(tools); * * const agent = createAgent({ * model: new ChatOpenAI(), * tools: langchainTools, * }); * ``` */ declare function toLangChainTools(tools: readonly LangChainConvertibleTool[]): DynamicStructuredTool[]; /** * Get the JSON Schema representation of a tool's input schema * * This is useful for debugging or for integrations that need the raw JSON Schema. * * @param tool - The AgentForge tool * @returns JSON Schema object * * @example * ```ts * const schema = getToolJsonSchema(readFileTool); * console.log(JSON.stringify(schema, null, 2)); * ``` */ declare function getToolJsonSchema(tool: Tool): JsonSchemaObject; /** * Get tool metadata in a format suitable for LLM prompts * * This creates a human-readable description of the tool including * its metadata, usage notes, limitations, and examples. * * @param tool - The AgentForge tool * @returns Formatted tool description * * @example * ```ts * const description = getToolDescription(readFileTool); * console.log(description); * // Output: * // read-file: Read a file from the file system * // Category: file-system * // Tags: file, read, io * // ... * ``` */ declare function getToolDescription(tool: Tool): string; /** * State channel configuration with optional Zod schema validation */ interface StateChannelConfig { /** * Optional Zod schema for runtime validation */ schema?: ZodType; /** * Optional reducer function for aggregating updates */ reducer?: (left: T, right: U) => T; /** * Optional default value factory */ default?: () => T; /** * Description of this state channel (for documentation) */ description?: string; } type StateChannelConfigLike = { schema?: ZodTypeAny; reducer?: (left: never, right: never) => unknown; default?: () => unknown; description?: string; }; type StateConfigMap = Record; type IsExact = [ TLeft ] extends [TRight] ? ([TRight] extends [TLeft] ? true : false) : false; type HasReducer = TChannel extends { reducer: (left: unknown, right: unknown) => unknown; } ? true : false; type SchemaValue = TChannel extends { schema: infer TSchema extends ZodTypeAny; } ? output : never; type DefaultValue = TChannel extends { default: () => infer TValue; } ? TValue : never; type ReducerValue = TChannel extends { reducer: (left: infer TValue, right: unknown) => infer TResult; } ? IsExact extends true ? TValue : never : never; type ReducerUpdate = TChannel extends { reducer: (left: unknown, right: infer TUpdate) => unknown; } ? TUpdate : never; type ChannelValue = HasReducer extends true ? ReducerValue : [SchemaValue] extends [never] ? [DefaultValue] extends [never] ? unknown : DefaultValue : SchemaValue; type ChannelUpdate = HasReducer extends true ? ReducerUpdate : ChannelValue; type SchemaMatchesValue = [ SchemaValue ] extends [never] ? true : [ChannelValue] extends [SchemaValue] ? true : false; type DefaultMatchesValue = [ DefaultValue ] extends [never] ? true : [DefaultValue] extends [ChannelValue] ? true : false; type ValidStateChannel = HasReducer extends true ? [ChannelValue] extends [never] ? never : SchemaMatchesValue extends true ? DefaultMatchesValue extends true ? TChannel : never : never : TChannel; type ValidStateConfig = { [K in keyof TConfig]: ValidStateChannel; }; type StateShape = { [K in keyof TConfig]: ChannelValue; }; type StateUpdateShape = { [K in keyof TConfig]?: ChannelUpdate; }; type StateChannelDefinition = BaseChannel, ChannelUpdate>; type StateAnnotationDefinition = { [K in keyof TConfig]: StateChannelDefinition; }; type DefaultedKeys = { [K in keyof TConfig]-?: TConfig[K] extends { default: () => ChannelValue; } ? K : never; }[keyof TConfig]; type InputStateKeys = Extract; type ValidatedState>> = { [K in InputStateKeys | DefaultedKeys]: ChannelValue; }; /** * Create a type-safe state annotation with optional Zod validation * * This is a thin wrapper around LangGraph's Annotation.Root that adds: * - Zod schema validation support * - Better TypeScript inference * - Documentation/description support */ declare function createStateAnnotation(config: ValidStateConfig): AnnotationRoot>; /** * Validate state against Zod schemas */ declare function validateState>>(state: TState, config: TConfig): ValidatedState; /** * Merge state updates using configured reducers */ declare function mergeState(currentState: Partial>, update: StateUpdateShape, config: TConfig): Partial>; type SequentialWorkflowState = AnnotationRoot['State']; type SequentialNodeResult = Partial; type SequentialWorkflowGraph = StateGraph, State, Update, string>; /** * Configuration for a node in a sequential workflow */ interface SequentialNode> { /** * Unique name for the node */ name: string; /** * The node function that processes the state */ node: (state: State) => Update | Promise; /** * Optional description of what this node does */ description?: string; } /** * Options for creating a sequential workflow */ interface SequentialWorkflowOptions { /** * Whether to automatically add START and END nodes * @default true */ autoStartEnd?: boolean; /** * Compatibility-only no-op retained to avoid a public type break. * * @deprecated This option is currently unused and will be removed in a future major release. */ name?: string; } /** * Creates a sequential workflow where nodes execute in order. * * This is a convenience function that creates a StateGraph and chains * the provided nodes together with edges. * * @example * ```typescript * const workflow = createSequentialWorkflow(AgentState, [ * { name: 'fetch', node: fetchNode }, * { name: 'process', node: processNode }, * { name: 'save', node: saveNode }, * ]); * * const app = workflow.compile(); * const result = await app.invoke({ input: 'data' }); * ``` * * @param stateSchema - The state annotation for the graph * @param nodes - Array of nodes to execute in sequence * @param options - Optional configuration * @returns A configured StateGraph ready to compile */ declare function createSequentialWorkflow>(stateSchema: AnnotationRoot, nodes: SequentialNode, Update>[], options?: SequentialWorkflowOptions): SequentialWorkflowGraph, Update>; /** * Creates a sequential workflow builder with a fluent API. * * This provides a more flexible way to build sequential workflows * by allowing you to add nodes one at a time. * * @example * ```typescript * const workflow = sequentialBuilder(AgentState) * .addNode('fetch', fetchNode) * .addNode('process', processNode) * .addNode('save', saveNode) * .build(); * * const app = workflow.compile(); * ``` * * @param stateSchema - The state annotation for the graph * @returns A fluent builder for sequential workflows */ declare function sequentialBuilder = UpdateType>(stateSchema: AnnotationRoot): { /** * Add a node to the sequential workflow */ addNode(name: string, node: (state: _langchain_langgraph.StateType) => Update | Promise, description?: string): /*elided*/ any; /** * Set options for the workflow */ options(opts: SequentialWorkflowOptions): /*elided*/ any; /** * Build the StateGraph */ build(): StateGraph, _langchain_langgraph.StateType, Update, string>; }; /** * Parallel Execution Builder * * Provides utilities for building workflows where multiple nodes execute in parallel. * This implements the fan-out/fan-in pattern using LangGraph's native parallel execution. * * @module langgraph/builders/parallel */ type ParallelWorkflowState = AnnotationRoot['State']; type ParallelNodeResult = Partial; /** * Configuration for a parallel node */ interface ParallelNode> { /** * Unique name for the node */ name: string; /** * The node function that processes the state */ node: (state: State) => Update | Promise; /** * Optional description of what this node does */ description?: string; } /** * Configuration for an aggregation node that combines parallel results */ interface AggregateNode> { /** * Name for the aggregation node */ name: string; /** * The aggregation function that combines results from parallel nodes */ node: (state: State) => Update | Promise; /** * Optional description */ description?: string; } /** * Options for creating a parallel workflow */ interface ParallelWorkflowOptions { /** * Whether to automatically add START and END nodes * @default true */ autoStartEnd?: boolean; /** * Compatibility-only no-op retained to avoid a public type break. * * @deprecated This option is currently unused and will be removed in a future major release. */ name?: string; } /** * Configuration for a parallel workflow */ interface ParallelWorkflowConfig> { /** * Nodes that execute in parallel */ parallel: ParallelNode[]; /** * Optional aggregation node that runs after all parallel nodes complete */ aggregate?: AggregateNode; } /** * Creates a parallel workflow where multiple nodes execute concurrently. * * This implements the fan-out/fan-in pattern: * - Fan-out: Multiple nodes execute in parallel * - Fan-in: Optional aggregation node combines results * * @example * ```typescript * const workflow = createParallelWorkflow(AgentState, { * parallel: [ * { name: 'fetch_news', node: fetchNewsNode }, * { name: 'fetch_weather', node: fetchWeatherNode }, * { name: 'fetch_stocks', node: fetchStocksNode }, * ], * aggregate: { name: 'combine', node: combineNode }, * }); * * const app = workflow.compile(); * const result = await app.invoke({ input: 'data' }); * ``` * * @param stateSchema - The state annotation for the graph * @param config - Configuration for parallel nodes and optional aggregation * @param options - Optional configuration * @returns A configured StateGraph ready to compile */ declare function createParallelWorkflow = UpdateType>(stateSchema: AnnotationRoot, config: ParallelWorkflowConfig, Update>, options?: ParallelWorkflowOptions): StateGraph, ParallelWorkflowState, Update, string>; /** * Conditional Routing Utilities * * Provides type-safe utilities for adding conditional edges to LangGraph workflows. * This simplifies the common pattern of routing based on state conditions. * * @module langgraph/builders/conditional */ /** * A route name that can be either a node name or END */ type RouteName = string | typeof END; /** * A mapping of route keys to node names */ type RouteMap = Record; /** * A condition function that determines which route to take */ type RouteCondition = (state: State) => string; /** * Configuration for a conditional router */ interface ConditionalRouterConfig { /** * Map of route keys to node names */ routes: Routes; /** * Condition function that returns a route key */ condition: RouteCondition; /** * Optional description of the routing logic */ description?: string; } /** * A conditional router that can be used with StateGraph.addConditionalEdges */ interface ConditionalRouter { /** * The route map */ routes: Routes; /** * The condition function */ condition: RouteCondition; /** * Optional description */ description?: string; } /** * Creates a type-safe conditional router for LangGraph workflows. * * This provides a cleaner API for conditional routing with better type safety * and validation. * * @example * ```typescript * const router = createConditionalRouter({ * routes: { * 'continue': 'agent', * 'end': END, * 'tools': 'tools', * }, * condition: (state) => { * if (state.shouldEnd) return 'end'; * if (state.needsTools) return 'tools'; * return 'continue'; * }, * }); * * // Use with StateGraph * graph.addConditionalEdges('agent', router.condition, router.routes); * ``` * * @param config - Configuration for the conditional router * @returns A conditional router object */ declare function createConditionalRouter(config: ConditionalRouterConfig): ConditionalRouter; /** * Creates a simple binary router (true/false condition). * * This is a convenience function for the common case of routing based on * a boolean condition. * * @example * ```typescript * const router = createBinaryRouter({ * condition: (state) => state.isComplete, * ifTrue: END, * ifFalse: 'continue', * }); * * graph.addConditionalEdges('check', router.condition, router.routes); * ``` * * @param config - Configuration for the binary router * @returns A conditional router object */ declare function createBinaryRouter(config: { condition: (state: State) => boolean; ifTrue: RouteName; ifFalse: RouteName; description?: string; }): ConditionalRouter; /** * Creates a multi-way router based on a discriminator function. * * This is useful when you have multiple possible routes based on a * state property or computed value. * * @example * ```typescript * const router = createMultiRouter({ * discriminator: (state) => state.status, * routes: { * 'pending': 'process', * 'complete': END, * 'error': 'error_handler', * }, * default: 'unknown', * }); * * graph.addConditionalEdges('check', router.condition, router.routes); * ``` * * @param config - Configuration for the multi-way router * @returns A conditional router object */ declare function createMultiRouter(config: { discriminator: (state: State) => string; routes: Routes; default?: keyof Routes; description?: string; }): ConditionalRouter; /** * Subgraph composition utilities for LangGraph * * Helpers for creating and composing subgraphs. */ /** * Configuration function for building a subgraph */ type SubgraphBuilder = (graph: StateGraph) => StateGraph; /** * Creates a reusable subgraph that can be added as a node to other graphs. * * This is a helper function that creates a StateGraph, applies the builder function, * and returns the compiled graph which can be added as a node to another graph. * * @example * ```typescript * // Create a reusable research subgraph * const researchSubgraph = createSubgraph(ResearchState, (graph) => { * graph.addNode('search', searchNode); * graph.addNode('analyze', analyzeNode); * graph.addEdge('__start__', 'search'); * graph.addEdge('search', 'analyze'); * graph.addEdge('analyze', '__end__'); * return graph; * }); * * // Use in main graph * const mainGraph = new StateGraph(MainState); * mainGraph.addNode('research', researchSubgraph); * ``` * * @param stateSchema - The state annotation for the subgraph * @param builder - Function that configures the subgraph * @returns A compiled graph that can be used as a node */ declare function createSubgraph(stateSchema: any, builder: SubgraphBuilder): ReturnType['compile']>; /** * Options for composing graphs */ interface ComposeGraphsOptions { /** * Name for the subgraph node */ name: string; /** * Optional description for documentation */ description?: string; } /** * Adds a compiled subgraph as a node to a parent graph. * * This is a convenience function that wraps the common pattern of * adding a compiled graph as a node. * * @example * ```typescript * const subgraph = createSubgraph(SubState, (graph) => { * // Configure subgraph * return graph; * }); * * const mainGraph = new StateGraph(MainState); * composeGraphs(mainGraph, subgraph, { name: 'sub_workflow' }); * ``` * * @param parentGraph - The parent graph to add the subgraph to * @param subgraph - The compiled subgraph to add as a node * @param options - Configuration options * @returns The parent graph for chaining */ declare function composeGraphs(parentGraph: StateGraph, subgraph: ReturnType['compile']>, options: ComposeGraphsOptions): StateGraph; /** * Middleware System - Type Definitions * * Core types and interfaces for the middleware system. * All middleware follows a consistent, composable pattern. * * @module langgraph/middleware/types */ /** * A LangGraph node function that processes state. * * Node functions can return: * - Full state (State) * - Partial state update (Partial) * - Promise of either * * @template State - The state type for the node */ type NodeFunction = (state: State) => State | Promise | Partial | Promise>; /** * A middleware function that wraps a node function. * * Middleware takes a node function and options, and returns a new node function * with enhanced behavior (logging, metrics, retry, etc.). * * @template State - The state type for the node * @template Options - Configuration options for the middleware * * @example * ```typescript * const loggingMiddleware: Middleware = (node, options) => { * return async (state) => { * console.log('Before:', state); * const result = await node(state); * console.log('After:', result); * return result; * }; * }; * ``` */ type Middleware = (node: NodeFunction, options: Options) => NodeFunction; /** * A middleware factory that creates middleware with bound options. * * This is useful for creating reusable middleware configurations. * * @template State - The state type for the node * @template Options - Configuration options for the middleware * * @example * ```typescript * const createLogger: MiddlewareFactory = (options) => { * return (node) => { * return async (state) => { * // Logging logic using options * return await node(state); * }; * }; * }; * ``` */ type MiddlewareFactory = (options: Options) => (node: NodeFunction) => NodeFunction; /** * A middleware that doesn't require options. * * @template State - The state type for the node */ type SimpleMiddleware = (node: NodeFunction) => NodeFunction; /** * Configuration for middleware composition. */ interface ComposeOptions { /** * Whether to execute middleware in reverse order. * @default false */ reverse?: boolean; /** * Name for the composed middleware (for debugging). */ name?: string; /** * Whether to catch and handle errors in middleware. * @default true */ catchErrors?: boolean; } /** * Metadata about a middleware function. */ interface MiddlewareMetadata { /** * Name of the middleware */ name: string; /** * Description of what the middleware does */ description?: string; /** * Version of the middleware */ version?: string; /** * Tags for categorizing middleware */ tags?: string[]; } /** * A middleware with attached metadata. */ interface MiddlewareWithMetadata { /** * The middleware function */ middleware: Middleware; /** * Metadata about the middleware */ metadata: MiddlewareMetadata; } /** * Context passed through middleware chain. * * This allows middleware to share information without modifying state. */ interface MiddlewareContext { /** * Unique ID for this execution */ executionId: string; /** * Timestamp when execution started */ startTime: number; /** * Custom data that middleware can read/write */ data: Record; /** * Stack of middleware names that have been applied */ middlewareStack: string[]; } /** * Enhanced node function with middleware context. */ type NodeFunctionWithContext = (state: State, context: MiddlewareContext) => State | Promise | Partial | Promise>; /** * Middleware Composition Utilities * * Functions for composing multiple middleware into a single middleware chain. * * @module langgraph/middleware/compose */ /** * Compose multiple middleware functions into a single middleware. * * Middleware are applied from left to right (first middleware wraps the node, * second middleware wraps the first, etc.). * * @example * ```typescript * const enhanced = compose( * withLogging({ level: 'info' }), * withMetrics({ name: 'my-node' }), * withRetry({ maxAttempts: 3 }) * )(myNode); * ``` * * @param middleware - Middleware functions to compose * @returns A function that takes a node and returns the enhanced node */ declare function compose(...middleware: SimpleMiddleware[]): SimpleMiddleware; /** * Compose middleware with options. * * @example * ```typescript * const enhanced = composeWithOptions( * { reverse: true, name: 'my-chain' }, * withLogging({ level: 'info' }), * withMetrics({ name: 'my-node' }) * )(myNode); * ``` * * @param options - Composition options * @param middleware - Middleware functions to compose * @returns A function that takes a node and returns the enhanced node */ declare function composeWithOptions(options: ComposeOptions, ...middleware: SimpleMiddleware[]): SimpleMiddleware; /** * Create a middleware chain builder for fluent API. * * @example * ```typescript * const enhanced = chain() * .use(withLogging({ level: 'info' })) * .use(withMetrics({ name: 'my-node' })) * .use(withRetry({ maxAttempts: 3 })) * .build(myNode); * ``` */ declare class MiddlewareChain { private middleware; private options; /** * Add middleware to the chain. */ use(middleware: SimpleMiddleware): this; /** * Set composition options. */ withOptions(options: ComposeOptions): this; /** * Build the middleware chain and apply it to a node. */ build(node: NodeFunction): NodeFunction; /** * Get the number of middleware in the chain. */ get length(): number; } /** * Create a new middleware chain builder. * * @example * ```typescript * const enhanced = chain() * .use(withLogging({ level: 'info' })) * .build(myNode); * ``` */ declare function chain(): MiddlewareChain; /** * Create a middleware context for tracking execution. */ declare function createMiddlewareContext(): MiddlewareContext; /** * Structured Logging Utilities * * Provides consistent, structured logging for LangGraph agents. */ /** * Log levels */ declare enum LogLevel { DEBUG = "debug", INFO = "info", WARN = "warn", ERROR = "error" } /** * Logger configuration options */ interface LoggerOptions { /** * Minimum log level to output * @default LogLevel.INFO */ level?: LogLevel; /** * Output format * @default 'pretty' */ format?: 'json' | 'pretty'; /** * Output destination * @default process.stdout */ destination?: NodeJS.WritableStream; /** * Whether to include timestamps * @default true */ includeTimestamp?: boolean; /** * Whether to include context in logs * @default true */ includeContext?: boolean; } /** * Log entry structure */ interface LogEntry { level: LogLevel; name: string; message: string; timestamp?: string; context?: JsonObject; data?: JsonValue; } /** * Logger interface */ interface Logger { /** * Log a debug message */ debug(message: string, data?: JsonValue): void; /** * Log an info message */ info(message: string, data?: JsonValue): void; /** * Log a warning message */ warn(message: string, data?: JsonValue): void; /** * Log an error message */ error(message: string, data?: JsonValue): void; /** * Check if debug logging is enabled * Useful for avoiding expensive computations when debug is disabled */ isDebugEnabled(): boolean; /** * Check if a specific log level is enabled */ isLevelEnabled(level: LogLevel): boolean; /** * Create a child logger with additional context */ withContext(context: JsonObject): Logger; } /** * Create a structured logger. * * @example * Basic usage: * ```typescript * import { createLogger, LogLevel } from '@agentforge/core'; * * const logger = createLogger('my-agent', { * level: LogLevel.INFO, * format: 'json', * }); * * logger.info('Processing request', { userId: 'user-123' }); * logger.error('Request failed', { error: err.message }); * ``` * * @example * Performance optimization with isDebugEnabled: * ```typescript * // Avoid expensive computations when debug is disabled * if (logger.isDebugEnabled()) { * const expensiveData = computeExpensiveDebugInfo(); * logger.debug('Debug info', expensiveData); * } * ``` * * @param name - Logger name (typically the agent or component name) * @param options - Logger configuration options * @returns A logger instance */ declare function createLogger(name: string, options?: LoggerOptions): Logger; /** * Error handler pattern for LangGraph nodes * * Wraps a node function with error handling logic. */ /** * Options for error handling behavior */ interface ErrorHandlerOptions { /** * Callback function to handle errors * Should return a state update to apply when an error occurs */ onError: (error: Error, state: State) => State | Partial | Promise>; /** * Optional callback for logging errors */ logError?: (error: Error, state: State) => void; /** * Whether to rethrow the error after handling * @default false */ rethrow?: boolean; } /** * Wraps a node function with error handling logic. * * @example * ```typescript * const safeNode = withErrorHandler(myNode, { * onError: (error, state) => { * return { ...state, error: error.message, failed: true }; * }, * logError: (error) => { * console.error('Node failed:', error); * }, * }); * * graph.addNode('safe', safeNode); * ``` * * @param node - The node function to wrap * @param options - Error handling configuration options * @returns A wrapped node function with error handling */ declare function withErrorHandler(node: (state: State) => State | Promise | Partial | Promise>, options: ErrorHandlerOptions): (state: State) => Promise>; /** * Retry pattern for LangGraph nodes * * Wraps a node function with retry logic. */ /** * Backoff strategy for retries */ type BackoffStrategy = 'constant' | 'linear' | 'exponential'; /** * Options for retry behavior */ interface RetryOptions { /** * Maximum number of retry attempts * @default 3 */ maxAttempts?: number; /** * Backoff strategy between retries * @default 'exponential' */ backoff?: BackoffStrategy; /** * Initial delay in milliseconds * @default 1000 */ initialDelay?: number; /** * Maximum delay in milliseconds * @default 30000 */ maxDelay?: number; /** * Optional callback when a retry occurs */ onRetry?: (error: Error, attempt: number) => void; /** * Optional predicate to determine if error should be retried * @default () => true (retry all errors) */ shouldRetry?: (error: Error) => boolean; } /** * Wraps a node function with retry logic. * * @example * ```typescript * const robustNode = withRetry(myNode, { * maxAttempts: 3, * backoff: 'exponential', * initialDelay: 1000, * onRetry: (error, attempt) => { * console.log(`Retry attempt ${attempt}: ${error.message}`); * }, * }); * * graph.addNode('robust', robustNode); * ``` * * @param node - The node function to wrap * @param options - Retry configuration options * @returns A wrapped node function with retry logic */ declare function withRetry(node: (state: State) => State | Promise | Partial | Promise>, options?: RetryOptions): (state: State) => Promise>; interface ProductionPresetOptions { nodeName: string; logger?: Logger; enableMetrics?: boolean; enableTracing?: boolean; enableRetry?: boolean; timeout?: number; retryOptions?: Partial; errorOptions?: Partial>; } interface DevelopmentPresetOptions { nodeName: string; verbose?: boolean; logger?: Logger; } interface TestingPresetOptions { nodeName: string; mockResponse?: Partial; simulateError?: Error; delay?: number; trackInvocations?: boolean; } type TestingPresetNode = NodeFunction & { invocations: State[]; }; /** * Production preset with comprehensive error handling, metrics, and tracing. */ declare function production(node: NodeFunction, options: ProductionPresetOptions): NodeFunction; /** * Development preset with verbose logging and debugging. */ declare function development(node: NodeFunction, options: DevelopmentPresetOptions): NodeFunction; /** * Testing preset for unit and integration tests. */ declare function testing(node: NodeFunction, options: TestingPresetOptions): TestingPresetNode; declare const presets: { production: typeof production; development: typeof development; testing: typeof testing; }; /** * Timeout pattern for LangGraph nodes * * Wraps a node function with timeout logic. */ /** * Options for timeout behavior */ interface TimeoutOptions { /** * Timeout duration in milliseconds */ timeout: number; /** * Callback function to handle timeouts * Should return a state update to apply when a timeout occurs */ onTimeout: (state: State) => State | Partial | Promise>; /** * Optional callback for logging timeouts */ logTimeout?: (state: State) => void; /** * Whether to throw an error on timeout * @default false */ throwOnTimeout?: boolean; } /** * Error thrown when a node times out */ declare class TimeoutError extends Error { constructor(timeout: number); } /** * Wraps a node function with timeout logic. * * @example * ```typescript * const timedNode = withTimeout(myNode, { * timeout: 5000, * onTimeout: (state) => ({ * ...state, * timedOut: true, * error: 'Operation timed out', * }), * logTimeout: () => { * console.warn('Node timed out'); * }, * }); * * graph.addNode('timed', timedNode); * ``` * * @param node - The node function to wrap * @param options - Timeout configuration options * @returns A wrapped node function with timeout logic */ declare function withTimeout(node: (state: State) => State | Promise | Partial | Promise>, options: TimeoutOptions): (state: State) => Promise>; /** Metric types supported by the in-memory collector. */ declare enum MetricType { COUNTER = "counter", GAUGE = "gauge", HISTOGRAM = "histogram" } /** A recorded metric sample. */ interface MetricEntry { type: MetricType; name: string; value: number; timestamp: number; labels?: Record; } /** A running duration measurement. */ interface Timer { end(): number; } /** Public metrics collector contract. */ interface Metrics { increment(name: string, value?: number, labels?: Record): void; decrement(name: string, value?: number, labels?: Record): void; gauge(name: string, value: number, labels?: Record): void; histogram(name: string, value: number, labels?: Record): void; startTimer(name: string, labels?: Record): Timer; getMetrics(): MetricEntry[]; clear(): void; } /** Options controlling automatic node instrumentation. */ interface MetricsNodeOptions { /** Name used to identify the instrumented node. */ name: string; /** * Whether to track execution duration. * @default true */ trackDuration?: boolean; /** * Whether to track errors. * @default true */ trackErrors?: boolean; /** * Whether to track invocation count. * @default true */ trackInvocations?: boolean; /** * Metrics collector to use. A new collector is created when omitted. */ metrics?: Metrics; } /** Create an in-memory metrics collector for a namespace. */ declare function createMetrics(name: string): Metrics; /** Wrap a node function with automatic metrics tracking. */ declare function withMetrics(node: (state: State) => State | Promise | Partial | Promise>, options: MetricsNodeOptions): (state: State) => Promise>; /** * LangSmith Integration Utilities * * Helpers for configuring and using LangSmith tracing with LangGraph. */ /** * LangSmith configuration options */ interface LangSmithConfig { /** * LangSmith API key * Can also be set via LANGSMITH_API_KEY environment variable */ apiKey?: string; /** * Project name for organizing traces * Can also be set via LANGSMITH_PROJECT environment variable */ projectName?: string; /** * Whether tracing is enabled * Can also be set via LANGSMITH_TRACING environment variable * @default true if apiKey is provided */ tracingEnabled?: boolean; /** * LangSmith API endpoint * @default 'https://api.smith.langchain.com' */ endpoint?: string; /** * Additional metadata to include in all traces */ metadata?: JsonObject; } /** * Configure LangSmith for tracing. * * This sets environment variables that LangChain/LangGraph use for tracing. * * @example * ```typescript * import { configureLangSmith } from '@agentforge/core'; * * configureLangSmith({ * apiKey: process.env.LANGSMITH_API_KEY, * projectName: 'my-agent', * tracingEnabled: true, * }); * ``` * * @param config - LangSmith configuration */ declare function configureLangSmith(config: LangSmithConfig): void; /** * Get the current LangSmith configuration. * * @returns The current configuration or null if not configured */ declare function getLangSmithConfig(): LangSmithConfig | null; /** * Check if LangSmith tracing is enabled. * * @returns True if tracing is enabled */ declare function isTracingEnabled(): boolean; /** * Options for tracing a node */ interface TracingOptions { /** * Name for the traced operation */ name: string; /** * Additional metadata to include in the trace */ metadata?: JsonObject; /** * Tags to categorize the trace */ tags?: string[]; /** * Run name for the trace */ runName?: string; } /** * Wrap a node function with LangSmith tracing. * * This adds metadata to the execution context that LangSmith can use for tracing. * * @example * ```typescript * import { withTracing } from '@agentforge/core'; * * const tracedNode = withTracing(myNode, { * name: 'research-node', * metadata: { category: 'research' }, * tags: ['research', 'web'], * }); * ``` * * @param node - The node function to wrap * @param options - Tracing options * @returns A wrapped node function with tracing */ declare function withTracing(node: (state: State) => State | Promise | Partial | Promise>, options: TracingOptions): (state: State) => Promise>; /** * Cache key generator function */ type CacheKeyGenerator = (state: State) => string; /** * Cache eviction strategy */ type EvictionStrategy = 'lru' | 'lfu' | 'fifo'; /** * Options for caching middleware */ interface CachingOptions { /** * Time-to-live in milliseconds. * @default 3600000 (1 hour) */ ttl?: number; /** * Maximum number of cache entries. * @default 100 */ maxSize?: number; /** * Eviction strategy when the cache is full. * @default 'lru' */ evictionStrategy?: EvictionStrategy; /** * Custom cache key generator. * @default JSON.stringify with String(...) fallback */ keyGenerator?: CacheKeyGenerator; /** * Whether to cache thrown `Error` results as `{ error: message }`. * @default false */ cacheErrors?: boolean; /** * Optional callback invoked when a fresh cached value is returned. */ onCacheHit?: (key: string, value: State | Partial) => void; /** * Optional callback invoked when no cached value is available. */ onCacheMiss?: (key: string) => void; /** * Optional callback invoked when a stale cached value is evicted. */ onEviction?: (key: string, value: State | Partial) => void; } interface SharedCache { withCache: (node: NodeFunction, keyGenerator?: CacheKeyGenerator) => NodeFunction; clear: () => void; size: () => number; } declare function createSharedCache(options?: Omit, 'keyGenerator'>): SharedCache; /** * Caching Middleware for LangGraph Nodes * * Provides caching capabilities with TTL, LRU eviction, and custom key generation. */ /** * Wraps a node function with caching logic. * * @example * ```typescript * const cachedNode = withCache(expensiveNode, { * ttl: 3600000, * maxSize: 100, * evictionStrategy: 'lru', * keyGenerator: (state) => state.userId, * onCacheHit: (key) => recordCacheHitMetric(key), * }); * * graph.addNode('cached', cachedNode); * ``` * * @param node - The node function to wrap * @param options - Caching configuration options * @returns A wrapped node function with caching */ declare function withCache(node: NodeFunction, options?: CachingOptions): NodeFunction; /** * Rate limiting strategy */ type RateLimitStrategy = 'token-bucket' | 'sliding-window' | 'fixed-window'; /** * Rate limiting options */ interface RateLimitOptions { /** * Maximum number of requests allowed */ maxRequests: number; /** * Time window in milliseconds */ windowMs: number; /** * Rate limiting strategy * @default 'token-bucket' */ strategy?: RateLimitStrategy; /** * Callback when rate limit is exceeded */ onRateLimitExceeded?: (key: string) => void; /** * Callback when rate limit is reset */ onRateLimitReset?: (key: string) => void; /** * Key generator function to identify unique clients/requests * @default Returns a constant key (global rate limit) */ keyGenerator?: (state: State) => string; } /** * Rate limiting middleware */ declare function withRateLimit(node: NodeFunction, options: RateLimitOptions): NodeFunction; /** * Create a shared rate limiter that can be used across multiple nodes */ declare function createSharedRateLimiter(options: Omit): { withRateLimit: (node: NodeFunction, keyGenerator?: (state: State) => string) => NodeFunction; reset: (key?: string) => void; }; /** * Validation mode */ type ValidationMode = 'input' | 'output' | 'both'; /** * Custom validator function */ type ValidatorFunction = (value: T) => boolean | Promise; /** * Validation error handler */ type ValidationErrorHandler = (error: z.ZodError | Error, state: State, mode: 'input' | 'output') => State | Partial | never; /** * Validation options */ interface ValidationOptions { /** * Zod schema for input validation */ inputSchema?: z.ZodSchema; /** * Zod schema for output validation */ outputSchema?: z.ZodSchema>; /** * Custom input validator function */ inputValidator?: ValidatorFunction; /** * Custom output validator function */ outputValidator?: ValidatorFunction>; /** * Validation mode * @default 'both' */ mode?: ValidationMode; /** * Whether to throw on validation error * @default true */ throwOnError?: boolean; /** * Custom error handler */ onValidationError?: ValidationErrorHandler; /** * Callback when validation succeeds */ onValidationSuccess?: (state: State | Partial, mode: 'input' | 'output') => void; /** * Whether to strip unknown properties * @default false */ stripUnknown?: boolean; } /** * Validation middleware */ declare function withValidation(node: NodeFunction, options: ValidationOptions): NodeFunction; /** * Priority level for queued tasks */ type Priority = 'low' | 'normal' | 'high'; /** * Concurrency control options */ interface ConcurrencyOptions { /** * Maximum number of concurrent executions * @default 1 */ maxConcurrent?: number; /** * Maximum queue size (0 = unlimited) * @default 0 */ maxQueueSize?: number; /** * Priority function to determine task priority * @default () => 'normal' */ priorityFn?: (state: State) => Priority; /** * Callback when task is queued */ onQueued?: (queueSize: number, state: State) => void; /** * Callback when task starts executing */ onExecutionStart?: (activeCount: number, state: State) => void; /** * Callback when task completes */ onExecutionComplete?: (activeCount: number, state: State) => void; /** * Callback when queue is full */ onQueueFull?: (state: State) => void; /** * Timeout for queued tasks (ms) * @default 0 (no timeout) */ queueTimeout?: number; } /** * Concurrency control middleware */ declare function withConcurrency(node: NodeFunction, options?: ConcurrencyOptions): NodeFunction; /** * Create a shared concurrency controller */ declare function createSharedConcurrencyController(options?: ConcurrencyOptions): { withConcurrency: (node: NodeFunction) => NodeFunction; getStats: () => { activeCount: number; queueSize: number; }; clear: () => void; }; /** * Logging Middleware * * Provides structured logging for LangGraph nodes with input/output tracking, * duration measurement, and error logging. * * @module langgraph/middleware/logging */ /** * Options for logging middleware */ interface LoggingOptions { /** * Logger instance to use * If not provided, a new logger will be created with the given name */ logger?: Logger; /** * Name for the logger (used if logger is not provided) */ name?: string; /** * Log level * @default 'info' */ level?: LogLevel; /** * Whether to log node inputs * @default true */ logInput?: boolean; /** * Whether to log node outputs * @default true */ logOutput?: boolean; /** * Whether to log execution duration * @default true */ logDuration?: boolean; /** * Whether to log errors * @default true */ logErrors?: boolean; /** * Custom function to extract loggable data from state * Use this to avoid logging sensitive information */ extractData?: (state: State) => Record; /** * Callback when node execution starts */ onStart?: (state: State) => void; /** * Callback when node execution completes */ onComplete?: (state: State, result: State | Partial, duration: number) => void; /** * Callback when node execution fails */ onError?: (error: Error, duration: number) => void; } /** * Create a logging middleware that wraps a node with structured logging. * * @example * ```typescript * import { withLogging } from '@agentforge/core'; * * const loggedNode = withLogging({ * name: 'my-node', * level: 'info', * logInput: true, * logOutput: true, * })(myNode); * ``` * * @param options - Logging configuration options * @returns A middleware function that adds logging to a node */ declare const withLogging: MiddlewareFactory; /** * Checkpointer Factory Functions * * Provides factory functions for creating LangGraph checkpointers with sensible defaults. * * @module langgraph/persistence/checkpointer */ /** * Serializer protocol for checkpoint data */ interface SerializerProtocol { } /** * Common options for all checkpointers */ interface CheckpointerOptions { /** * Custom serializer for checkpoint data * @default undefined (uses default serializer) */ serializer?: SerializerProtocol; } /** * Options for SQLite checkpointer */ interface SqliteCheckpointerOptions extends CheckpointerOptions { /** * Path to the SQLite database file * @default ':memory:' (in-memory database) */ path?: string; /** * Whether to automatically run migrations * @default true */ autoMigrate?: boolean; } /** * Create an in-memory checkpointer for development and testing. * * This checkpointer stores all checkpoints in memory and is lost when the process exits. * Ideal for development, testing, and experimentation. * * @example * ```typescript * import { createMemoryCheckpointer } from '@agentforge/core'; * * const checkpointer = createMemoryCheckpointer(); * * const app = workflow.compile({ checkpointer }); * ``` * * @param options - Optional checkpointer configuration * @returns A MemorySaver instance */ declare function createMemoryCheckpointer(options?: CheckpointerOptions): MemorySaver; /** * Create a SQLite-based checkpointer for local persistence. * * This checkpointer stores checkpoints in a SQLite database file, providing * persistence across process restarts. Ideal for local development and * single-machine deployments. * * Note: Requires `@langchain/langgraph-checkpoint-sqlite` to be installed. * * @example * ```typescript * import { createSqliteCheckpointer } from '@agentforge/core'; * * // Use a file-based database * const checkpointer = await createSqliteCheckpointer({ * path: './checkpoints.db', * autoMigrate: true, * }); * * const app = workflow.compile({ checkpointer }); * ``` * * @param options - SQLite checkpointer configuration * @returns A Promise that resolves to a SqliteSaver instance * @throws Error if @langchain/langgraph-checkpoint-sqlite is not installed */ declare function createSqliteCheckpointer(options?: SqliteCheckpointerOptions): Promise; /** * Type guard to check if a checkpointer is a MemorySaver * * @param checkpointer - The checkpointer to check * @returns True if the checkpointer is a MemorySaver */ declare function isMemoryCheckpointer(checkpointer: BaseCheckpointSaver): checkpointer is MemorySaver; /** * Thread Management Utilities * * Provides utilities for managing conversation threads and configurations. * * @module langgraph/persistence/thread */ /** * Configuration for a thread */ interface ThreadConfig { /** * Unique identifier for the thread */ threadId: string; /** * Optional checkpoint ID to resume from */ checkpointId?: string; /** * Optional checkpoint namespace */ checkpointNamespace?: string; /** * Additional metadata for the thread */ metadata?: JsonObject; } /** * Configuration for a conversation */ interface ConversationConfig { /** * User ID for the conversation */ userId: string; /** * Optional session ID */ sessionId?: string; /** * Additional metadata */ metadata?: JsonObject; } /** * Generate a unique thread ID. * * If a seed is provided, generates a deterministic UUID v5 based on the seed. * Otherwise, generates a random UUID v4. * * @example * ```typescript * import { generateThreadId } from '@agentforge/core'; * * // Random thread ID * const threadId = generateThreadId(); * * // Deterministic thread ID from seed * const threadId2 = generateThreadId('user-123'); * ``` * * @param seed - Optional seed for deterministic ID generation * @returns A unique thread ID */ declare function generateThreadId(seed?: string): string; /** * Create a thread configuration for LangGraph. * * This creates a RunnableConfig object with the thread configuration * that can be passed to graph.invoke() or graph.stream(). * * @example * ```typescript * import { createThreadConfig } from '@agentforge/core'; * * const config = createThreadConfig({ * threadId: 'conversation-1', * metadata: { userId: 'user-123' }, * }); * * const result = await app.invoke(input, config); * ``` * * @param config - Thread configuration * @returns A RunnableConfig object */ declare function createThreadConfig(config?: Partial): RunnableConfig; /** * Create a conversation configuration for LangGraph. * * This is a convenience function that creates a thread configuration * with user and session information, commonly used for chat applications. * * @example * ```typescript * import { createConversationConfig } from '@agentforge/core'; * * const config = createConversationConfig({ * userId: 'user-123', * sessionId: 'session-456', * }); * * const result = await app.invoke(input, config); * ``` * * @param config - Conversation configuration * @returns A RunnableConfig object */ declare function createConversationConfig(config: ConversationConfig): RunnableConfig; /** * Checkpointer Utility Functions * * Provides utility functions for working with LangGraph checkpointers. * * @module langgraph/persistence/utils */ /** * Options for getting checkpoint history */ interface CheckpointHistoryOptions { /** * Thread ID to get history for */ threadId: string; /** * Maximum number of checkpoints to return * @default 10 */ limit?: number; /** * Get checkpoints before this checkpoint ID */ before?: string; } /** * Get the checkpoint history for a thread. * * Returns a list of checkpoints for the specified thread, ordered from * most recent to oldest. * * @example * ```typescript * import { getCheckpointHistory } from '@agentforge/core'; * * const history = await getCheckpointHistory(checkpointer, { * threadId: 'conversation-1', * limit: 10, * }); * * for (const checkpoint of history) { * console.log(checkpoint.checkpoint.id); * } * ``` * * @param checkpointer - The checkpointer to query * @param options - History query options * @returns A promise that resolves to an array of checkpoint tuples */ declare function getCheckpointHistory(checkpointer: BaseCheckpointSaver, options: CheckpointHistoryOptions): Promise; /** * Get the latest checkpoint for a thread. * * Returns the most recent checkpoint for the specified thread, or null * if no checkpoints exist. * * @example * ```typescript * import { getLatestCheckpoint } from '@agentforge/core'; * * const latest = await getLatestCheckpoint(checkpointer, { * threadId: 'conversation-1', * }); * * if (latest) { * console.log('Latest checkpoint:', latest.checkpoint.id); * } * ``` * * @param checkpointer - The checkpointer to query * @param options - Query options * @returns A promise that resolves to the latest checkpoint tuple or null */ declare function getLatestCheckpoint(checkpointer: BaseCheckpointSaver, options: { threadId: string; }): Promise; /** * Clear all checkpoints for a thread. * * Note: This functionality depends on the checkpointer implementation. * Not all checkpointers support deletion. * * @example * ```typescript * import { clearThread } from '@agentforge/core'; * * await clearThread(checkpointer, { * threadId: 'conversation-1', * }); * ``` * * @param checkpointer - The checkpointer to modify * @param options - Clear options * @returns A promise that resolves when the thread is cleared * @throws Error if the checkpointer doesn't support deletion */ declare function clearThread(checkpointer: BaseCheckpointSaver, options: { threadId: string; }): Promise; /** * Enhanced Error Handling Utilities * * Provides enhanced error classes and error reporting for better debugging. */ type SerializedErrorCause = { name: string; message: string; stack?: string; }; type SerializedAgentError = { name: string; message: string; code?: string; node?: string; state?: unknown; metadata?: JsonObject; timestamp: number; stack?: string; cause?: SerializedErrorCause; }; /** * Error context information */ interface ErrorContext { /** * Error code for categorization */ code?: string; /** * Node name where the error occurred */ node?: string; /** * Current state when the error occurred */ state?: unknown; /** * Additional metadata */ metadata?: JsonObject; /** * Original error that caused this error */ cause?: Error; } /** * Enhanced error class for agent errors */ declare class AgentError extends Error { readonly code?: string; readonly node?: string; readonly state?: unknown; readonly metadata?: JsonObject; readonly cause?: Error; readonly timestamp: number; constructor(message: string, context?: ErrorContext); /** * Convert error to JSON for logging/reporting */ toJSON(): SerializedAgentError; /** * Get a human-readable string representation */ toString(): string; } /** * Error reporter configuration */ interface ErrorReporterOptions { /** * Callback function to handle errors */ onError: (error: AgentError) => void | Promise; /** * Whether to include stack traces * @default true */ includeStackTrace?: boolean; /** * Whether to include state in error context * @default false (for security/privacy) */ includeState?: boolean; /** * Whether to rethrow errors after reporting * @default true */ rethrow?: boolean; } /** * Error reporter for tracking and reporting errors */ interface ErrorReporter { /** * Wrap a node function with error reporting */ wrap(node: (state: State) => State | Promise | Partial | Promise>, nodeName?: string): (state: State) => Promise>; /** * Report an error manually */ report(error: Error, context?: ErrorContext): Promise; } /** * Create an error reporter. * * @example * ```typescript * import { createErrorReporter } from '@agentforge/core'; * * const reporter = createErrorReporter({ * onError: (error) => { * console.error('Agent error:', error.toJSON()); * // Send to error tracking service * }, * includeStackTrace: true, * includeState: false, * }); * * const safeNode = reporter.wrap(myNode, 'my-node'); * ``` * * @param options - Error reporter configuration * @returns An error reporter instance */ declare function createErrorReporter(options: ErrorReporterOptions): ErrorReporter; /** * Types for LangGraph interrupt handling * @module langgraph/interrupts/types */ /** * Priority level for human requests */ type HumanRequestPriority = 'low' | 'normal' | 'high' | 'critical'; /** * Status of a human request */ type HumanRequestStatus = 'pending' | 'answered' | 'timeout' | 'cancelled'; /** * Human request stored in state */ interface HumanRequest { /** * Unique ID for this request */ id: string; /** * The question being asked */ question: string; /** * Optional context */ context?: JsonObject; /** * Priority level */ priority: HumanRequestPriority; /** * When the request was created */ createdAt: number; /** * Timeout in milliseconds (0 = no timeout) */ timeout: number; /** * Default response if timeout occurs */ defaultResponse?: string; /** * Suggested responses */ suggestions?: string[]; /** * Current status */ status: HumanRequestStatus; /** * The response (if answered) */ response?: string; /** * When the response was received */ respondedAt?: number; } /** * Interrupt type - identifies what kind of interrupt occurred */ type InterruptType = 'human_request' | 'approval_required' | 'custom'; /** * Shared interrupt metadata contract. */ type InterruptMetadata = JsonObject; /** * JSON-safe payload allowed in generic interrupt and resume flows. */ type InterruptPayload = JsonValue; /** * Interrupt data stored in the checkpoint */ interface InterruptData { /** * Type of interrupt */ type: TType; /** * Unique ID for this interrupt */ id: string; /** * When the interrupt was created */ createdAt: number; /** * The data associated with this interrupt */ data: TData; /** * Optional metadata */ metadata?: TMetadata; } /** * Approval request payload. */ interface ApprovalRequiredData { action: string; description: string; context?: JsonObject; } /** * Human request interrupt data */ type HumanRequestInterrupt = InterruptData<'human_request', HumanRequest>; /** * Approval required interrupt data */ type ApprovalRequiredInterrupt = InterruptData<'approval_required', ApprovalRequiredData>; /** * Custom interrupt data */ type CustomInterrupt = InterruptData<'custom', TData, TMetadata>; /** * Union type of all interrupt types */ type AnyInterrupt = HumanRequestInterrupt | ApprovalRequiredInterrupt | CustomInterrupt; /** * Resume command for continuing after an interrupt */ interface ResumeCommand { /** * The response to the interrupt */ resume: TResume; /** * Optional metadata about the response */ metadata?: TMetadata; } /** * Thread status */ type ThreadStatus = 'running' | 'interrupted' | 'completed' | 'error'; /** * Thread info with interrupt status */ interface ThreadInfo { /** * Thread ID */ threadId: string; /** * Current status */ status: ThreadStatus; /** * Active interrupts (if any) */ interrupts?: AnyInterrupt[]; /** * Last updated timestamp */ updatedAt: number; /** * Optional metadata */ metadata?: InterruptMetadata; } /** * Options for checking interrupt status */ interface CheckInterruptOptions { /** * Thread ID to check */ threadId: string; /** * Filter by interrupt type */ type?: InterruptType; } /** * Options for resuming from an interrupt */ interface ResumeOptions { /** * Thread ID to resume */ threadId: string; /** * Interrupt ID to resume from */ interruptId?: string; /** * The response/value to resume with */ value: InterruptPayload; /** * Optional metadata */ metadata?: InterruptMetadata; } /** * Utilities for working with LangGraph interrupts * @module langgraph/interrupts/utils */ /** * Create a human request interrupt * * @param request - The human request data * @returns A human request interrupt object * * @example * ```typescript * const interrupt = createHumanRequestInterrupt({ * id: 'req-123', * question: 'Should I proceed?', * priority: 'high', * createdAt: Date.now(), * timeout: 0, * status: 'pending', * }); * ``` */ declare function createHumanRequestInterrupt(request: HumanRequest): HumanRequestInterrupt; /** * Create an approval required interrupt * * @param action - The action requiring approval * @param description - Description of the action * @param context - Optional context * @returns An approval required interrupt object * * @example * ```typescript * const interrupt = createApprovalRequiredInterrupt( * 'delete-database', * 'Delete production database', * { database: 'prod-db-1' } * ); * ``` */ declare function createApprovalRequiredInterrupt(action: string, description: string, context?: JsonObject): ApprovalRequiredInterrupt; /** * Create a custom interrupt * * @param id - Unique ID for the interrupt * @param data - Custom data * @param metadata - Optional metadata * @returns A custom interrupt object * * @example * ```typescript * const interrupt = createCustomInterrupt( * 'custom-123', * { type: 'review', content: 'Please review this' } * ); * ``` */ declare function createCustomInterrupt(id: string, data: TData, metadata?: TMetadata): CustomInterrupt; /** * Check if an interrupt is a human request * * @param interrupt - The interrupt to check * @returns True if the interrupt is a human request */ declare function isHumanRequestInterrupt(interrupt: AnyInterrupt): interrupt is HumanRequestInterrupt; /** * Check if an interrupt is an approval request * * @param interrupt - The interrupt to check * @returns True if the interrupt is an approval request */ declare function isApprovalRequiredInterrupt(interrupt: AnyInterrupt): interrupt is ApprovalRequiredInterrupt; /** * Check if an interrupt is a custom interrupt * * @param interrupt - The interrupt to check * @returns True if the interrupt is a custom interrupt */ declare function isCustomInterrupt(interrupt: AnyInterrupt): interrupt is CustomInterrupt; /** * Get the status of a thread based on its state * * @param hasInterrupts - Whether the thread has active interrupts * @param isComplete - Whether the thread has completed * @param hasError - Whether the thread has an error * @returns The thread status */ declare function getThreadStatus(hasInterrupts: boolean, isComplete: boolean, hasError: boolean): ThreadStatus; /** * Streaming utilities for LangGraph applications * @module streaming */ /** * Options for chunk transformer */ interface ChunkOptions { /** Number of items per chunk */ size: number; } /** * Options for batch transformer */ interface BatchOptions { /** Maximum number of items per batch */ maxSize: number; /** Maximum time to wait before emitting a batch (ms) */ maxWait: number; } /** * Options for throttle transformer */ interface ThrottleOptions { /** Maximum number of items to emit */ rate: number; /** Time period for rate limit (ms) */ per: number; } /** * Reducer function for stream aggregation */ type ReducerFunction = (accumulator: R, current: T) => R; /** * Progress information */ interface Progress { /** Current progress value */ current: number; /** Total expected value */ total: number; /** Percentage complete (0-100) */ percentage: number; /** Estimated time to completion (seconds) */ eta: number; /** Start time */ startTime: number; /** Elapsed time (ms) */ elapsed: number; } /** * Progress tracker options */ interface ProgressTrackerOptions { /** Total expected items/steps */ total: number; /** Callback for progress updates */ onProgress?: (progress: Progress) => void; /** Callback for completion */ onComplete?: (progress: Progress) => void; /** Callback for cancellation */ onCancel?: () => void; } /** * Progress tracker interface */ interface ProgressTracker { /** Start tracking */ start(): void; /** Update progress */ update(current: number): void; /** Mark as complete */ complete(): void; /** Cancel tracking */ cancel(): void; /** Get current progress */ getProgress(): Progress; /** Check if cancelled */ isCancelled(): boolean; } /** * SSE event */ interface SSEEvent { /** Event type */ event?: string; /** Event data */ data: string; /** Event ID */ id?: string; /** Retry interval (ms) */ retry?: number; } /** * SSE formatter options */ type SSEEventMapper = (data: TData) => SSEEvent; interface SSEFormatterOptions { /** Event type mappers */ eventTypes?: Record>; /** Heartbeat interval (ms) */ heartbeat?: number; /** Default retry interval (ms) */ retry?: number; } /** * SSE formatter interface */ interface SSEFormatter { /** Format stream as SSE events */ format(stream: AsyncIterable): AsyncIterable; } /** * Binary WebSocket payload */ type WebSocketBinaryData = ArrayBuffer | ArrayBufferView | ReadonlyArray; /** * Raw WebSocket message payload */ type WebSocketRawMessage = string | WebSocketBinaryData; /** * WebSocket close reason payload */ type WebSocketCloseReason = string | WebSocketBinaryData; /** * Minimal WebSocket-like connection contract used by streaming helpers */ type WebSocketEvent = 'pong' | 'message' | 'error' | 'close'; /** * Typed WebSocket event handler */ type WebSocketEventHandler = TEvent extends 'pong' ? () => void : TEvent extends 'message' ? (data: TMessage) => void | Promise : TEvent extends 'error' ? (error: Error) => void : (code?: number, reason?: TCloseReason) => void; interface WebSocketConnection { /** Socket ready state */ readyState: number; /** Register event handler */ on(event: TEvent, handler: WebSocketEventHandler): void; /** Send string data */ send(data: string): void; /** Close gracefully when supported by the implementation */ close?(): void; /** Send ping when heartbeat support is available */ ping?(): void; /** Force terminate socket when supported by the implementation */ terminate?(): void; } type WebSocketConnectionTypeParts = TSocket extends WebSocketConnection ? { message: TMessage; closeReason: TCloseReason; } : { message: WebSocketRawMessage; closeReason: WebSocketCloseReason; }; /** * Extract message payload type from a WebSocket-like connection */ type WebSocketMessageFor = WebSocketConnectionTypeParts['message']; /** * Extract close reason type from a WebSocket-like connection */ type WebSocketCloseReasonFor = WebSocketConnectionTypeParts['closeReason']; /** * Minimal WebSocket-like send target used by send/broadcast helpers */ interface WebSocketSendTarget { /** Socket ready state */ readyState: number; /** Send string data */ send(data: string): void; } /** * WebSocket message */ interface WebSocketMessage { /** Message type */ type: string; /** Message data */ data?: TData; /** Error information */ error?: string; } /** * WebSocket handler options */ interface WebSocketHandlerOptions { /** Connection handler */ onConnect?: (ws: TSocket, req?: TRequest) => void; /** Message handler */ onMessage?: (ws: TSocket, message: unknown) => void | Promise; /** Error handler */ onError?: (ws: TSocket, error: Error) => void; /** Close handler */ onClose?: (ws: TSocket, code?: number, reason?: WebSocketCloseReasonFor) => void; /** Heartbeat interval (ms) */ heartbeat?: number; } /** * Stream transformers for LangGraph applications * @module streaming/transformers */ /** * Transform a stream into chunks of a specified size * * @example * ```typescript * const chunked = chunk(stream, { size: 10 }); * for await (const chunk of chunked) { * console.log(chunk); // Array of 10 items (or fewer for last chunk) * } * ``` */ declare function chunk(stream: AsyncIterable, options: ChunkOptions): AsyncIterable; /** * Batch stream items with size and time constraints * * @example * ```typescript * const batched = batch(stream, { maxSize: 5, maxWait: 100 }); * for await (const batch of batched) { * console.log(batch); // Array of up to 5 items or items collected within 100ms * } * ``` */ declare function batch(stream: AsyncIterable, options: BatchOptions): AsyncIterable; /** * Throttle stream to limit rate of items * * @example * ```typescript * const throttled = throttle(stream, { rate: 10, per: 1000 }); * for await (const item of throttled) { * console.log(item); // Max 10 items per second * } * ``` */ declare function throttle(stream: AsyncIterable, options: ThrottleOptions): AsyncIterable; /** * Stream aggregators for LangGraph applications * @module streaming/aggregators */ /** * Collect all items from a stream into an array * * @example * ```typescript * const items = await collect(stream); * console.log(items); // Array of all items * ``` */ declare function collect(stream: AsyncIterable): Promise; /** * Reduce a stream to a single value * * @example * ```typescript * const sum = await reduce(stream, (acc, val) => acc + val, 0); * console.log(sum); // Sum of all values * ``` */ declare function reduce(stream: AsyncIterable, reducer: ReducerFunction, initialValue: R): Promise; /** * Merge multiple streams into a single stream * * Items are emitted as they arrive from any stream. * * @example * ```typescript * const merged = merge([stream1, stream2, stream3]); * for await (const item of merged) { * console.log(item); // Items from any stream * } * ``` */ declare function merge(streams: AsyncIterable[]): AsyncIterable; /** * Filter stream items based on a predicate * * @example * ```typescript * const filtered = filter(stream, (item) => item.value > 10); * for await (const item of filtered) { * console.log(item); // Only items with value > 10 * } * ``` */ declare function filter(stream: AsyncIterable, predicate: (item: T) => boolean | Promise): AsyncIterable; /** * Map stream items to new values * * @example * ```typescript * const mapped = map(stream, (item) => item.value * 2); * for await (const item of mapped) { * console.log(item); // Transformed items * } * ``` */ declare function map(stream: AsyncIterable, mapper: (item: T) => R | Promise): AsyncIterable; /** * Take only the first N items from a stream * * @example * ```typescript * const first10 = take(stream, 10); * for await (const item of first10) { * console.log(item); // Only first 10 items * } * ``` */ declare function take(stream: AsyncIterable, count: number): AsyncIterable; /** * Progress tracking for long-running operations * @module streaming/progress */ /** * Create a progress tracker for long-running operations * * @example * ```typescript * const tracker = createProgressTracker({ * total: 100, * onProgress: (progress) => { * console.log(`${progress.percentage}% complete (ETA: ${progress.eta}s)`); * }, * }); * * tracker.start(); * for (let i = 0; i < 100; i++) { * await processItem(i); * tracker.update(i + 1); * } * tracker.complete(); * ``` */ declare function createProgressTracker(options: ProgressTrackerOptions): ProgressTracker; /** * Server-Sent Events (SSE) support for streaming * @module streaming/sse */ /** * Create an SSE formatter for streaming data * * @example * ```typescript * const formatter = createSSEFormatter({ * eventTypes: { * token: (data) => ({ event: 'token', data: data.content }), * error: (data) => ({ event: 'error', data: data.message }), * }, * heartbeat: 30000, * retry: 3000, * }); * * // In Express/Fastify handler * res.setHeader('Content-Type', 'text/event-stream'); * res.setHeader('Cache-Control', 'no-cache'); * res.setHeader('Connection', 'keep-alive'); * * for await (const event of formatter.format(stream)) { * res.write(event); * } * res.end(); * ``` */ declare function createSSEFormatter(options?: SSEFormatterOptions): SSEFormatter; /** * Create a heartbeat comment for SSE */ declare function createHeartbeat(): string; /** * Parse SSE event from string * * Useful for testing or client-side parsing */ declare function parseSSEEvent(eventString: string): SSEEvent | null; /** * SSE utilities for human-in-the-loop workflows * @module streaming/human-in-loop */ /** * Human-in-the-loop SSE event types */ type HumanInLoopEventType = 'human_request' | 'human_response' | 'interrupt' | 'resume' | 'agent_waiting' | 'agent_resumed'; /** * Human request SSE event data */ interface HumanRequestEventData { type: 'human_request'; request: HumanRequest; threadId: string; } /** * Human response SSE event data */ interface HumanResponseEventData { type: 'human_response'; requestId: string; response: string; threadId: string; } /** * Interrupt SSE event data */ interface InterruptEventData { type: 'interrupt'; interrupt: AnyInterrupt; threadId: string; } /** * Resume SSE event data */ interface ResumeEventData { type: 'resume'; interruptId: string; value: InterruptPayload; threadId: string; } /** * Agent waiting SSE event data */ interface AgentWaitingEventData { type: 'agent_waiting'; reason: string; threadId: string; } /** * Agent resumed SSE event data */ interface AgentResumedEventData { type: 'agent_resumed'; threadId: string; } /** * Union type of all human-in-the-loop event data */ type HumanInLoopEventData = HumanRequestEventData | HumanResponseEventData | InterruptEventData | ResumeEventData | AgentWaitingEventData | AgentResumedEventData; /** * Format a human request as an SSE event * * @param request - The human request * @param threadId - The thread ID * @returns An SSE event * * @example * ```typescript * const event = formatHumanRequestEvent(humanRequest, 'thread-123'); * // Send to client via SSE * res.write(formatSSEEvent(event)); * ``` */ declare function formatHumanRequestEvent(request: HumanRequest, threadId: string): SSEEvent; /** * Format a human response as an SSE event * * @param requestId - The request ID * @param response - The human's response * @param threadId - The thread ID * @returns An SSE event */ declare function formatHumanResponseEvent(requestId: string, response: string, threadId: string): SSEEvent; /** * Format an interrupt as an SSE event * * @param interrupt - The interrupt data * @param threadId - The thread ID * @returns An SSE event */ declare function formatInterruptEvent(interrupt: AnyInterrupt, threadId: string): SSEEvent; /** * Format a resume event as an SSE event * * @param interruptId - The interrupt ID being resumed * @param value - The resume value * @param threadId - The thread ID * @returns An SSE event */ declare function formatResumeEvent(interruptId: string, value: InterruptPayload, threadId: string): SSEEvent; /** * Format an agent waiting event as an SSE event * * @param reason - Why the agent is waiting * @param threadId - The thread ID * @returns An SSE event */ declare function formatAgentWaitingEvent(reason: string, threadId: string): SSEEvent; /** * Format an agent resumed event as an SSE event * * @param threadId - The thread ID * @returns An SSE event */ declare function formatAgentResumedEvent(threadId: string): SSEEvent; /** * WebSocket support for bidirectional streaming * @module streaming/websocket */ /** * Create a WebSocket handler for bidirectional streaming * * @example * ```typescript * import WebSocket from 'ws'; * * const handler = createWebSocketHandler({ * onConnect: (ws) => { * console.log('Client connected'); * }, * onMessage: async (ws, message) => { * const stream = await agent.stream(message); * for await (const event of stream) { * ws.send(JSON.stringify(event)); * } * }, * onError: (ws, error) => { * ws.send(JSON.stringify({ type: 'error', error: error.message })); * }, * heartbeat: 30000, * }); * * wss.on('connection', handler); * ``` */ declare function createWebSocketHandler(options: WebSocketHandlerOptions): (ws: TSocket, req?: TRequest) => void; /** * Send a message through WebSocket * * Automatically serializes objects to JSON */ declare function sendMessage(ws: WebSocketSendTarget, message: WebSocketMessage): void; /** * Broadcast a message to multiple WebSocket clients */ declare function broadcast(clients: Set, message: WebSocketMessage): void; /** * Create a WebSocket message */ declare function createMessage(type: string, data?: TData, error?: string): WebSocketMessage; interface PoolConfig { min?: number; max?: number; acquireTimeout?: number; idleTimeout?: number; evictionInterval?: number; } interface HealthCheckConfig { enabled?: boolean; interval?: number; timeout?: number; retries?: number; } interface ConnectionPoolOptions { factory: () => Promise; destroyer?: (connection: T) => Promise; validator?: (connection: T) => Promise; pool?: PoolConfig; healthCheck?: HealthCheckConfig; onAcquire?: (connection: T) => void; onRelease?: (connection: T) => void; onDestroy?: (connection: T) => void; onHealthCheckFail?: (error: Error) => void; } interface PoolStats { size: number; available: number; pending: number; acquired: number; created: number; destroyed: number; healthChecksPassed: number; healthChecksFailed: number; } /** * Connection pooling for database and HTTP clients */ declare class ConnectionPool { private readonly runtime; constructor(options: ConnectionPoolOptions); acquire(): Promise; release(connection: T): Promise; drain(): Promise; clear(): Promise; getStats(): PoolStats; } declare function createConnectionPool(options: ConnectionPoolOptions): ConnectionPool; interface DatabaseConfig { host: string; port?: number; database: string; user: string; password: string; ssl?: boolean; connectionTimeout?: number; } type DatabaseQueryParams = readonly unknown[]; type DatabaseQueryResult = unknown; interface DatabaseConnection { query(sql: string, params?: DatabaseQueryParams): Promise; execute(sql: string, params?: DatabaseQueryParams): Promise; close(): Promise; } interface DatabasePoolOptions { config: DatabaseConfig; pool?: PoolConfig; healthCheck?: HealthCheckConfig & { query?: string; }; onConnect?: (connection: DatabaseConnection) => void; onDisconnect?: (connection: DatabaseConnection) => void; } declare class DatabasePool { private options; private pool; constructor(options: DatabasePoolOptions); acquire(): Promise; release(connection: DatabaseConnection): Promise; query(sql: string, params?: DatabaseQueryParams): Promise; execute(sql: string, params?: DatabaseQueryParams): Promise; drain(): Promise; clear(): Promise; getStats(): PoolStats; } declare function createDatabasePool(options: DatabasePoolOptions): DatabasePool; interface HttpConfig { baseURL: string; timeout?: number; headers?: Record; maxRedirects?: number; validateStatus?: (status: number) => boolean; } interface HttpPoolConfig extends PoolConfig { maxSockets?: number; keepAlive?: boolean; keepAliveMsecs?: number; } interface HttpClient { get(url: string, config?: RequestConfig): Promise>; post(url: string, data?: TData, config?: RequestConfig): Promise>; put(url: string, data?: TData, config?: RequestConfig): Promise>; delete(url: string, config?: RequestConfig): Promise>; request(config: RequestConfig): Promise>; close(): Promise; } interface RequestConfig { url?: string; method?: string; headers?: Record; params?: Record; data?: TData; timeout?: number; } interface HttpResponse { data: T; status: number; statusText: string; headers: Record; } interface HttpPoolOptions { config: HttpConfig; pool?: HttpPoolConfig; healthCheck?: HealthCheckConfig & { endpoint?: string; method?: string; }; onConnect?: (client: HttpClient) => void; onDisconnect?: (client: HttpClient) => void; } declare class HttpPool { private options; private pool; constructor(options: HttpPoolOptions); acquire(): Promise; release(client: HttpClient): Promise; request(config: RequestConfig): Promise>; drain(): Promise; clear(): Promise; getStats(): PoolStats; } declare function createHttpPool(options: HttpPoolOptions): HttpPool; /** * Memory management and tracking */ interface MemoryStats { used: number; total: number; percentage: number; heapUsed: number; heapTotal: number; external: number; arrayBuffers: number; } interface MemoryManagerOptions { maxMemory?: number; checkInterval?: number; thresholdPercentage?: number; onThreshold?: (stats: MemoryStats) => void; onLimit?: (stats: MemoryStats) => Promise; onLeak?: (stats: MemoryStats) => void; leakDetection?: { enabled?: boolean; sampleInterval?: number; growthThreshold?: number; }; } type CleanupHandler = () => Promise; declare class MemoryManager { private options; private cleanupHandlers; private checkTimer?; private leakDetectionTimer?; private previousMemory?; private running; constructor(options: MemoryManagerOptions); start(): void; stop(): void; registerCleanup(name: string, handler: CleanupHandler): void; unregisterCleanup(name: string): void; cleanup(name?: string): Promise; getStats(): MemoryStats; forceGC(): void; private checkMemory; private detectLeaks; } declare function createMemoryManager(options: MemoryManagerOptions): MemoryManager; /** * Batch processing for efficient request handling */ interface BatchProcessorOptions { maxBatchSize: number; maxWaitTime: number; processor: (batch: TInput[]) => Promise; onBatchStart?: (batch: TInput[]) => void; onBatchComplete?: (batch: TInput[], results: TOutput[]) => void; onBatchError?: (batch: TInput[], error: Error) => void; onItemError?: (item: TInput, error: Error) => TOutput | undefined; } interface BatchStats { totalBatches: number; totalItems: number; averageBatchSize: number; averageWaitTime: number; successfulBatches: number; failedBatches: number; } declare class BatchProcessor { private options; private pending; private timer?; private processing; private stats; constructor(options: BatchProcessorOptions); add(input: TInput): Promise; flush(): Promise; private processBatch; getStats(): BatchStats; getPendingCount(): number; } declare function createBatchProcessor(options: BatchProcessorOptions): BatchProcessor; /** * Circuit breaker pattern for fault tolerance */ type CircuitState = 'closed' | 'open' | 'half-open'; interface CircuitBreakerOptions { failureThreshold: number; resetTimeout: number; monitoringPeriod?: number; halfOpenRequests?: number; onStateChange?: (state: CircuitState, previousState: CircuitState) => void; onFailure?: (error: Error) => void; onSuccess?: () => void; shouldTrip?: (error: Error) => boolean; } interface CircuitBreakerStats { state: CircuitState; failures: number; successes: number; totalCalls: number; failureRate: number; lastFailureTime?: number; lastSuccessTime?: number; stateChanges: number; } declare class CircuitBreaker { private options; private state; private failures; private successes; private totalCalls; private stateChanges; private lastFailureTime?; private lastSuccessTime?; private resetTimer?; private callHistory; private halfOpenAttempts; constructor(options: CircuitBreakerOptions); execute(fn: () => Promise): Promise; wrap(fn: (...args: TArgs) => Promise): (...args: TArgs) => Promise; private onSuccess; private onFailure; private recordCall; private getRecentFailures; private scheduleReset; private transitionTo; getState(): CircuitState; getStats(): CircuitBreakerStats; reset(): void; } declare function createCircuitBreaker(options: CircuitBreakerOptions): CircuitBreaker; /** * Health check system for production monitoring */ type HealthStatus = 'healthy' | 'unhealthy' | 'degraded'; interface HealthCheckResult { healthy: boolean; status?: HealthStatus; message?: string; error?: string; timestamp?: number; duration?: number; metadata?: JsonObject; } interface HealthCheck { (): Promise; } interface HealthCheckerOptions { checks: Record; timeout?: number; interval?: number; onHealthChange?: (health: HealthReport) => void; onCheckFail?: (name: string, error: Error) => void; } interface HealthReport { healthy: boolean; status: HealthStatus; timestamp: number; checks: Record; uptime: number; } declare class HealthChecker { private options; private checkTimer?; private lastReport?; private startTime; private running; constructor(options: HealthCheckerOptions); start(): void; stop(): void; getHealth(): Promise; getLiveness(): Promise; getReadiness(): Promise; private runChecks; } declare function createHealthChecker(options: HealthCheckerOptions): HealthChecker; /** * Performance profiling for execution monitoring */ interface ProfilerOptions { enabled?: boolean; sampleRate?: number; includeMemory?: boolean; includeStack?: boolean; maxSamples?: number; } interface ProfileSample { timestamp: number; duration: number; memory?: { heapUsed: number; heapTotal: number; external: number; }; stack?: string; } interface ProfileStats { calls: number; totalTime: number; avgTime: number; minTime: number; maxTime: number; p50: number; p95: number; p99: number; memory?: { avgHeapUsed: number; maxHeapUsed: number; minHeapUsed: number; }; samples: ProfileSample[]; } interface ProfileReport { [key: string]: ProfileStats; } declare class Profiler { private profiles; private enabled; private sampleRate; private includeMemory; private includeStack; private maxSamples; constructor(options?: ProfilerOptions); profile(name: string, fn: (...args: TArgs) => Promise): (...args: TArgs) => Promise; wrap(name: string, promise: Promise): Promise; private recordSample; getReport(): ProfileReport; private percentile; reset(name?: string): void; export(path: string): void; } declare function createProfiler(options?: ProfilerOptions): Profiler; type AlertSeverity = 'info' | 'warning' | 'error' | 'critical'; interface Alert { name: string; severity: AlertSeverity; message: string; timestamp?: number; data?: TData; } type BuiltInAlertChannelType = 'email' | 'slack' | 'webhook'; type EmailAlertChannelConfig = JsonObject & { to: string | string[]; }; type SlackAlertChannelConfig = JsonObject & { webhookUrl: string; }; type WebhookAlertChannelConfig = JsonObject & { url: string; }; interface EmailAlertChannel { type: 'email'; config: EmailAlertChannelConfig; } interface SlackAlertChannel { type: 'slack'; config: SlackAlertChannelConfig; } interface WebhookAlertChannel { type: 'webhook'; config: WebhookAlertChannelConfig; } interface GenericAlertChannel { type: TType; config: TConfig; } type CustomAlertChannel = GenericAlertChannel, TConfig>; type AlertChannel = TType extends 'email' ? EmailAlertChannel : TType extends 'slack' ? SlackAlertChannel : TType extends 'webhook' ? WebhookAlertChannel : GenericAlertChannel; type AlertChannelMap = Record; type ValidatedAlertChannels = { [TName in keyof TChannels]: TChannels[TName] extends GenericAlertChannel ? AlertChannel : never; }; type AlertChannelName = keyof ValidatedAlertChannels & string; interface AlertRule { name: string; condition: (metrics: TMetrics) => boolean; severity: AlertSeverity; channels: TChannelName[]; throttle?: number; message?: string; } type AlertCallbackData = JsonObject & { metrics?: TMetrics; }; interface AlertManagerOptions> { channels: ValidatedAlertChannels; rules?: AlertRule>[]; onAlert?: (alert: Alert>) => void | Promise; } declare class AlertManager> { private options; private lastAlertTime; private monitorTimer?; private running; constructor(options: AlertManagerOptions); start(metrics?: () => TMetrics, interval?: number): void; stop(): void; alert(alert: Alert>): Promise; sendToChannel(channelName: keyof TChannels & string, alert: Alert>): Promise; getAlertHistory(_name?: string, _limit?: number): Alert>[]; clearAlertHistory(name?: string): void; } declare function createAlertManager>(options: AlertManagerOptions): AlertManager; /** * Audit logging for compliance and tracking */ interface AuditLogEntry { id?: string; userId: string; action: string; resource: string; timestamp?: number; input?: JsonValue; output?: JsonValue; metadata?: JsonObject; success?: boolean; error?: string; } interface AuditLogQuery { userId?: string; action?: string; resource?: string; startDate?: Date; endDate?: Date; limit?: number; offset?: number; } interface AuditLoggerOptions { storage?: { type: 'memory' | 'database' | 'file'; config?: JsonObject; }; retention?: { days: number; autoCleanup?: boolean; }; fields?: { userId?: boolean; action?: boolean; resource?: boolean; timestamp?: boolean; ip?: boolean; userAgent?: boolean; input?: boolean; output?: boolean; }; onLog?: (entry: AuditLogEntry) => void; } declare class AuditLogger { private options; private logs; private cleanupTimer?; constructor(options?: AuditLoggerOptions); log(entry: AuditLogEntry): Promise; query(query?: AuditLogQuery): Promise; export(path: string, options?: { format?: 'json' | 'csv'; startDate?: Date; endDate?: Date; }): Promise; private convertToCSV; private startCleanup; private cleanup; private generateId; stop(): void; } declare function createAuditLogger(options?: AuditLoggerOptions): AuditLogger; type PromptVariableValue = unknown; type PromptVariableMap = Record; /** Options for rendering templates with trusted and untrusted variables. */ interface RenderTemplateOptions { /** Variables from trusted sources. These values are not sanitized. */ trustedVariables?: PromptVariableMap; /** Variables from untrusted sources. These values are sanitized. */ untrustedVariables?: PromptVariableMap; } /** * Load and render a Markdown prompt template from a custom directory or the * `prompts` directory beneath the current working directory. */ declare function loadPrompt(promptName: string, options?: RenderTemplateOptions | PromptVariableMap, promptsDir?: string): string; /** * Render substitutions and conditional blocks with trusted/untrusted controls. * Trusted values are substituted unchanged, untrusted values are sanitized, * and conditional truthiness is evaluated against the original raw values. * Plain variable maps remain supported as trusted input for compatibility. */ declare function renderTemplate(template: string, options: RenderTemplateOptions | PromptVariableMap): string; /** * Sanitize an untrusted value before prompt substitution. * * Removes Markdown header markers and line breaks, collapses whitespace, * and limits output to 500 characters plus an ellipsis. */ declare function sanitizeValue(value: unknown): string; export { AgentError, type AgentResumedEventData, type AgentWaitingEventData, type AggregateNode, type Alert, type AlertChannel, AlertManager, type AlertManagerOptions, type AlertRule, type AlertSeverity, type AnyInterrupt, type ApprovalRequiredInterrupt, type AuditLogEntry, type AuditLogQuery, AuditLogger, type AuditLoggerOptions, type BackoffStrategy, type BatchOptions, BatchProcessor, type BatchProcessorOptions, type BatchStats, type CacheKeyGenerator, type CachingOptions, type CheckInterruptOptions, type CheckpointHistoryOptions, type CheckpointerOptions, type ChunkOptions, CircuitBreaker, type CircuitBreakerOptions, type CircuitBreakerStats, type CircuitState, type ComposeGraphsOptions, type ComposeOptions, type ComposeToolConfig, type ComposedTool, type ConcurrencyOptions, type ConditionalConfig, type ConditionalRouter, type ConditionalRouterConfig, ConnectionPool, type ConnectionPoolOptions, type ConversationConfig, type CustomAlertChannel, type CustomInterrupt, type DatabaseConfig, type DatabaseConnection, DatabasePool, type DatabasePoolOptions, type DatabaseQueryParams, type DatabaseQueryResult, type DevelopmentPresetOptions, type EmailAlertChannel, type ErrorContext, type ErrorHandlerOptions, type ErrorReporter, type ErrorReporterOptions, type EventHandler, type EvictionStrategy, type ExecutionMetrics, type GenericAlertChannel, type HealthCheck, type HealthCheckConfig, type HealthCheckResult, HealthChecker, type HealthCheckerOptions, type HealthReport, type HealthStatus, type HttpClient, type HttpConfig, HttpPool, type HttpPoolConfig, type HttpPoolOptions, type HttpResponse, type HumanInLoopEventData, type HumanInLoopEventType, type HumanRequest, type HumanRequestEventData, type HumanRequestInterrupt, type HumanRequestPriority, type HumanRequestStatus, type HumanResponseEventData, type InterruptData, type InterruptEventData, type InterruptType, type JsonObject, type JsonPrimitive, type JsonValue, type LangSmithConfig, type LogEntry, LogLevel, type Logger, type LoggerOptions, type LoggingOptions, ManagedTool, type ManagedToolConfig, type ManagedToolStats, MemoryManager, type MemoryManagerOptions, type MemoryStats, type MetricEntry, MetricType, type Metrics, type MetricsNodeOptions, type Middleware, MiddlewareChain, type MiddlewareContext, type MiddlewareFactory, type MiddlewareMetadata, type MiddlewareWithMetadata, MissingDescriptionError, type MockExecutionRuntimeOptions, type MockToolConfig, type MockToolResponse, type NodeFunction, type NodeFunctionWithContext, type ParallelNode, type ParallelWorkflowConfig, type ParallelWorkflowOptions, type PoolConfig, type PoolStats, type Priority$1 as Priority, type ProductionPresetOptions, type ProfileReport, type ProfileSample, type ProfileStats, Profiler, type ProfilerOptions, type Progress, type ProgressTracker, type ProgressTrackerOptions, type PromptOptions, type PromptVariableMap, type PromptVariableValue, type RateLimitOptions, type RateLimitStrategy, type ReducerFunction, RegistryEvent, type RenderTemplateOptions, type RequestConfig, type ResumeCommand, type ResumeEventData, type ResumeOptions, type RetryOptions, type RetryPolicy, type RouteCondition, type RouteMap, type RouteName, type SSEEvent, type SSEFormatter, type SSEFormatterOptions, type SequentialNode, type SequentialWorkflowOptions, type SimpleMiddleware, type SlackAlertChannel, type SqliteCheckpointerOptions, type StateChannelConfig, type SubgraphBuilder, type TestingPresetOptions, type ThreadConfig, type ThreadInfo, type ThreadStatus, type ThrottleOptions, TimeoutError, type TimeoutOptions, type Timer, type Tool, type BackoffStrategy$1 as ToolBackoffStrategy, ToolBuilder, ToolCategory, ToolCategorySchema, type ToolExample, ToolExampleSchema, type ToolExecution, type ToolExecutorConfig, type ToolHealthCheckResult, type ToolInvocation, type ToolMetadata, ToolMetadataSchema, ToolNameSchema, ToolRegistry, type ToolRelations, ToolRelationsSchema, type ToolSimulatorConfig, type TracingOptions, type ValidationErrorHandler, type ValidationMode, type ValidationOptions, type ValidatorFunction, type WebSocketBinaryData, type WebSocketCloseReason, type WebSocketCloseReasonFor, type WebSocketConnection, type WebSocketEvent, type WebSocketEventHandler, type WebSocketHandlerOptions, type WebSocketMessage, type WebSocketMessageFor, type WebSocketRawMessage, type WebSocketSendTarget, type WebhookAlertChannel, batch, broadcast, cache, chain, chunk, clearThread, collect, compose, composeGraphs, composeTool, composeWithOptions, conditional, configureLangSmith, createAlertManager, createApprovalRequiredInterrupt, createAuditLogger, createBatchProcessor, createBinaryRouter, createCircuitBreaker, createConditionalRouter, createConnectionPool, createConversationConfig, createCustomInterrupt, createDatabasePool, createErrorReporter, createHealthChecker, createHeartbeat, createHttpPool, createHumanRequestInterrupt, createLogger, createManagedTool, createMemoryCheckpointer, createMemoryManager, createMessage, createMetrics, createMiddlewareContext, createMockTool, createMultiRouter, createParallelWorkflow, createProfiler, createProgressTracker, createSSEFormatter, createSequentialWorkflow, createSharedCache, createSharedConcurrencyController, createSharedRateLimiter, createSqliteCheckpointer, createStateAnnotation, createSubgraph, createThreadConfig, createTool, createToolExecutor, createToolSimulator, createToolUnsafe, createWebSocketHandler, development, filter, formatAgentResumedEvent, formatAgentWaitingEvent, formatHumanRequestEvent, formatHumanResponseEvent, formatInterruptEvent, formatResumeEvent, generateThreadId, getCheckpointHistory, getLangSmithConfig, getLatestCheckpoint, getMissingDescriptions, getThreadStatus, getToolDescription, getToolJsonSchema, isApprovalRequiredInterrupt, isCustomInterrupt, isHumanRequestInterrupt, isMemoryCheckpointer, isTracingEnabled, loadPrompt, map, merge, mergeState, parallel, parseSSEEvent, presets, production, reduce, renderTemplate, retry, runMockExecution, safeValidateSchemaDescriptions, sanitizeValue, sendMessage, sequential, sequentialBuilder, take, testing, throttle, timeout, toLangChainTool, toLangChainTools, toolBuilder, validateSchemaDescriptions, validateState, validateTool, validateToolMetadata, validateToolName, withCache, withConcurrency, withErrorHandler, withLogging, withMetrics, withRateLimit, withRetry, withTimeout, withTracing, withValidation };