@agentforge/core 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -2379,6 +2379,247 @@ interface ComposeGraphsOptions {
2379
2379
  */
2380
2380
  declare function composeGraphs<ParentState, SubState>(parentGraph: StateGraph<ParentState>, subgraph: ReturnType<StateGraph<SubState>['compile']>, options: ComposeGraphsOptions): StateGraph<ParentState>;
2381
2381
 
2382
+ /**
2383
+ * Middleware System - Type Definitions
2384
+ *
2385
+ * Core types and interfaces for the middleware system.
2386
+ * All middleware follows a consistent, composable pattern.
2387
+ *
2388
+ * @module langgraph/middleware/types
2389
+ */
2390
+ /**
2391
+ * A LangGraph node function that processes state.
2392
+ *
2393
+ * Node functions can return:
2394
+ * - Full state (State)
2395
+ * - Partial state update (Partial<State>)
2396
+ * - Promise of either
2397
+ *
2398
+ * @template State - The state type for the node
2399
+ */
2400
+ type NodeFunction<State> = (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>;
2401
+ /**
2402
+ * A middleware function that wraps a node function.
2403
+ *
2404
+ * Middleware takes a node function and options, and returns a new node function
2405
+ * with enhanced behavior (logging, metrics, retry, etc.).
2406
+ *
2407
+ * @template State - The state type for the node
2408
+ * @template Options - Configuration options for the middleware
2409
+ *
2410
+ * @example
2411
+ * ```typescript
2412
+ * const loggingMiddleware: Middleware<MyState, LoggingOptions> = (node, options) => {
2413
+ * return async (state) => {
2414
+ * console.log('Before:', state);
2415
+ * const result = await node(state);
2416
+ * console.log('After:', result);
2417
+ * return result;
2418
+ * };
2419
+ * };
2420
+ * ```
2421
+ */
2422
+ type Middleware<State, Options = unknown> = (node: NodeFunction<State>, options: Options) => NodeFunction<State>;
2423
+ /**
2424
+ * A middleware factory that creates middleware with bound options.
2425
+ *
2426
+ * This is useful for creating reusable middleware configurations.
2427
+ *
2428
+ * @template State - The state type for the node
2429
+ * @template Options - Configuration options for the middleware
2430
+ *
2431
+ * @example
2432
+ * ```typescript
2433
+ * const createLogger: MiddlewareFactory<MyState, LoggingOptions> = (options) => {
2434
+ * return (node) => {
2435
+ * return async (state) => {
2436
+ * // Logging logic using options
2437
+ * return await node(state);
2438
+ * };
2439
+ * };
2440
+ * };
2441
+ * ```
2442
+ */
2443
+ type MiddlewareFactory<State, Options = unknown> = (options: Options) => (node: NodeFunction<State>) => NodeFunction<State>;
2444
+ /**
2445
+ * A middleware that doesn't require options.
2446
+ *
2447
+ * @template State - The state type for the node
2448
+ */
2449
+ type SimpleMiddleware<State> = (node: NodeFunction<State>) => NodeFunction<State>;
2450
+ /**
2451
+ * Configuration for middleware composition.
2452
+ */
2453
+ interface ComposeOptions {
2454
+ /**
2455
+ * Whether to execute middleware in reverse order.
2456
+ * @default false
2457
+ */
2458
+ reverse?: boolean;
2459
+ /**
2460
+ * Name for the composed middleware (for debugging).
2461
+ */
2462
+ name?: string;
2463
+ /**
2464
+ * Whether to catch and handle errors in middleware.
2465
+ * @default true
2466
+ */
2467
+ catchErrors?: boolean;
2468
+ }
2469
+ /**
2470
+ * Metadata about a middleware function.
2471
+ */
2472
+ interface MiddlewareMetadata {
2473
+ /**
2474
+ * Name of the middleware
2475
+ */
2476
+ name: string;
2477
+ /**
2478
+ * Description of what the middleware does
2479
+ */
2480
+ description?: string;
2481
+ /**
2482
+ * Version of the middleware
2483
+ */
2484
+ version?: string;
2485
+ /**
2486
+ * Tags for categorizing middleware
2487
+ */
2488
+ tags?: string[];
2489
+ }
2490
+ /**
2491
+ * A middleware with attached metadata.
2492
+ */
2493
+ interface MiddlewareWithMetadata<State, Options = unknown> {
2494
+ /**
2495
+ * The middleware function
2496
+ */
2497
+ middleware: Middleware<State, Options>;
2498
+ /**
2499
+ * Metadata about the middleware
2500
+ */
2501
+ metadata: MiddlewareMetadata;
2502
+ }
2503
+ /**
2504
+ * Context passed through middleware chain.
2505
+ *
2506
+ * This allows middleware to share information without modifying state.
2507
+ */
2508
+ interface MiddlewareContext {
2509
+ /**
2510
+ * Unique ID for this execution
2511
+ */
2512
+ executionId: string;
2513
+ /**
2514
+ * Timestamp when execution started
2515
+ */
2516
+ startTime: number;
2517
+ /**
2518
+ * Custom data that middleware can read/write
2519
+ */
2520
+ data: Record<string, unknown>;
2521
+ /**
2522
+ * Stack of middleware names that have been applied
2523
+ */
2524
+ middlewareStack: string[];
2525
+ }
2526
+ /**
2527
+ * Enhanced node function with middleware context.
2528
+ */
2529
+ type NodeFunctionWithContext<State> = (state: State, context: MiddlewareContext) => State | Promise<State> | Partial<State> | Promise<Partial<State>>;
2530
+
2531
+ /**
2532
+ * Middleware Composition Utilities
2533
+ *
2534
+ * Functions for composing multiple middleware into a single middleware chain.
2535
+ *
2536
+ * @module langgraph/middleware/compose
2537
+ */
2538
+
2539
+ /**
2540
+ * Compose multiple middleware functions into a single middleware.
2541
+ *
2542
+ * Middleware are applied from left to right (first middleware wraps the node,
2543
+ * second middleware wraps the first, etc.).
2544
+ *
2545
+ * @example
2546
+ * ```typescript
2547
+ * const enhanced = compose(
2548
+ * withLogging({ level: 'info' }),
2549
+ * withMetrics({ name: 'my-node' }),
2550
+ * withRetry({ maxAttempts: 3 })
2551
+ * )(myNode);
2552
+ * ```
2553
+ *
2554
+ * @param middleware - Middleware functions to compose
2555
+ * @returns A function that takes a node and returns the enhanced node
2556
+ */
2557
+ declare function compose<State>(...middleware: SimpleMiddleware<State>[]): SimpleMiddleware<State>;
2558
+ /**
2559
+ * Compose middleware with options.
2560
+ *
2561
+ * @example
2562
+ * ```typescript
2563
+ * const enhanced = composeWithOptions(
2564
+ * { reverse: true, name: 'my-chain' },
2565
+ * withLogging({ level: 'info' }),
2566
+ * withMetrics({ name: 'my-node' })
2567
+ * )(myNode);
2568
+ * ```
2569
+ *
2570
+ * @param options - Composition options
2571
+ * @param middleware - Middleware functions to compose
2572
+ * @returns A function that takes a node and returns the enhanced node
2573
+ */
2574
+ declare function composeWithOptions<State>(options: ComposeOptions, ...middleware: SimpleMiddleware<State>[]): SimpleMiddleware<State>;
2575
+ /**
2576
+ * Create a middleware chain builder for fluent API.
2577
+ *
2578
+ * @example
2579
+ * ```typescript
2580
+ * const enhanced = chain<MyState>()
2581
+ * .use(withLogging({ level: 'info' }))
2582
+ * .use(withMetrics({ name: 'my-node' }))
2583
+ * .use(withRetry({ maxAttempts: 3 }))
2584
+ * .build(myNode);
2585
+ * ```
2586
+ */
2587
+ declare class MiddlewareChain<State> {
2588
+ private middleware;
2589
+ private options;
2590
+ /**
2591
+ * Add middleware to the chain.
2592
+ */
2593
+ use(middleware: SimpleMiddleware<State>): this;
2594
+ /**
2595
+ * Set composition options.
2596
+ */
2597
+ withOptions(options: ComposeOptions): this;
2598
+ /**
2599
+ * Build the middleware chain and apply it to a node.
2600
+ */
2601
+ build(node: NodeFunction<State>): NodeFunction<State>;
2602
+ /**
2603
+ * Get the number of middleware in the chain.
2604
+ */
2605
+ get length(): number;
2606
+ }
2607
+ /**
2608
+ * Create a new middleware chain builder.
2609
+ *
2610
+ * @example
2611
+ * ```typescript
2612
+ * const enhanced = chain<MyState>()
2613
+ * .use(withLogging({ level: 'info' }))
2614
+ * .build(myNode);
2615
+ * ```
2616
+ */
2617
+ declare function chain<State>(): MiddlewareChain<State>;
2618
+ /**
2619
+ * Create a middleware context for tracking execution.
2620
+ */
2621
+ declare function createMiddlewareContext(): MiddlewareContext;
2622
+
2382
2623
  /**
2383
2624
  * Retry pattern for LangGraph nodes
2384
2625
  *
@@ -2493,486 +2734,12 @@ interface ErrorHandlerOptions<State> {
2493
2734
  declare function withErrorHandler<State>(node: (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>, options: ErrorHandlerOptions<State>): (state: State) => Promise<State | Partial<State>>;
2494
2735
 
2495
2736
  /**
2496
- * Timeout pattern for LangGraph nodes
2737
+ * Structured Logging Utilities
2497
2738
  *
2498
- * Wraps a node function with timeout logic.
2739
+ * Provides consistent, structured logging for LangGraph agents.
2499
2740
  */
2500
2741
  /**
2501
- * Options for timeout behavior
2502
- */
2503
- interface TimeoutOptions<State> {
2504
- /**
2505
- * Timeout duration in milliseconds
2506
- */
2507
- timeout: number;
2508
- /**
2509
- * Callback function to handle timeouts
2510
- * Should return a state update to apply when a timeout occurs
2511
- */
2512
- onTimeout: (state: State) => State | Partial<State> | Promise<State | Partial<State>>;
2513
- /**
2514
- * Optional callback for logging timeouts
2515
- */
2516
- logTimeout?: (state: State) => void;
2517
- /**
2518
- * Whether to throw an error on timeout
2519
- * @default false
2520
- */
2521
- throwOnTimeout?: boolean;
2522
- }
2523
- /**
2524
- * Error thrown when a node times out
2525
- */
2526
- declare class TimeoutError extends Error {
2527
- constructor(timeout: number);
2528
- }
2529
- /**
2530
- * Wraps a node function with timeout logic.
2531
- *
2532
- * @example
2533
- * ```typescript
2534
- * const timedNode = withTimeout(myNode, {
2535
- * timeout: 5000,
2536
- * onTimeout: (state) => ({
2537
- * ...state,
2538
- * timedOut: true,
2539
- * error: 'Operation timed out',
2540
- * }),
2541
- * logTimeout: () => {
2542
- * console.warn('Node timed out');
2543
- * },
2544
- * });
2545
- *
2546
- * graph.addNode('timed', timedNode);
2547
- * ```
2548
- *
2549
- * @param node - The node function to wrap
2550
- * @param options - Timeout configuration options
2551
- * @returns A wrapped node function with timeout logic
2552
- */
2553
- declare function withTimeout<State>(node: (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>, options: TimeoutOptions<State>): (state: State) => Promise<State | Partial<State>>;
2554
-
2555
- /**
2556
- * Checkpointer Factory Functions
2557
- *
2558
- * Provides factory functions for creating LangGraph checkpointers with sensible defaults.
2559
- *
2560
- * @module langgraph/persistence/checkpointer
2561
- */
2562
-
2563
- /**
2564
- * Serializer protocol for checkpoint data
2565
- */
2566
- interface SerializerProtocol {
2567
- }
2568
- /**
2569
- * Common options for all checkpointers
2570
- */
2571
- interface CheckpointerOptions {
2572
- /**
2573
- * Custom serializer for checkpoint data
2574
- * @default undefined (uses default serializer)
2575
- */
2576
- serializer?: SerializerProtocol;
2577
- }
2578
- /**
2579
- * Options for SQLite checkpointer
2580
- */
2581
- interface SqliteCheckpointerOptions extends CheckpointerOptions {
2582
- /**
2583
- * Path to the SQLite database file
2584
- * @default ':memory:' (in-memory database)
2585
- */
2586
- path?: string;
2587
- /**
2588
- * Whether to automatically run migrations
2589
- * @default true
2590
- */
2591
- autoMigrate?: boolean;
2592
- }
2593
- /**
2594
- * Create an in-memory checkpointer for development and testing.
2595
- *
2596
- * This checkpointer stores all checkpoints in memory and is lost when the process exits.
2597
- * Ideal for development, testing, and experimentation.
2598
- *
2599
- * @example
2600
- * ```typescript
2601
- * import { createMemoryCheckpointer } from '@agentforge/core';
2602
- *
2603
- * const checkpointer = createMemoryCheckpointer();
2604
- *
2605
- * const app = workflow.compile({ checkpointer });
2606
- * ```
2607
- *
2608
- * @param options - Optional checkpointer configuration
2609
- * @returns A MemorySaver instance
2610
- */
2611
- declare function createMemoryCheckpointer(options?: CheckpointerOptions): MemorySaver;
2612
- /**
2613
- * Create a SQLite-based checkpointer for local persistence.
2614
- *
2615
- * This checkpointer stores checkpoints in a SQLite database file, providing
2616
- * persistence across process restarts. Ideal for local development and
2617
- * single-machine deployments.
2618
- *
2619
- * Note: Requires `@langchain/langgraph-checkpoint-sqlite` to be installed.
2620
- *
2621
- * @example
2622
- * ```typescript
2623
- * import { createSqliteCheckpointer } from '@agentforge/core';
2624
- *
2625
- * // Use a file-based database
2626
- * const checkpointer = await createSqliteCheckpointer({
2627
- * path: './checkpoints.db',
2628
- * autoMigrate: true,
2629
- * });
2630
- *
2631
- * const app = workflow.compile({ checkpointer });
2632
- * ```
2633
- *
2634
- * @param options - SQLite checkpointer configuration
2635
- * @returns A Promise that resolves to a SqliteSaver instance
2636
- * @throws Error if @langchain/langgraph-checkpoint-sqlite is not installed
2637
- */
2638
- declare function createSqliteCheckpointer(options?: SqliteCheckpointerOptions): Promise<BaseCheckpointSaver>;
2639
- /**
2640
- * Type guard to check if a checkpointer is a MemorySaver
2641
- *
2642
- * @param checkpointer - The checkpointer to check
2643
- * @returns True if the checkpointer is a MemorySaver
2644
- */
2645
- declare function isMemoryCheckpointer(checkpointer: BaseCheckpointSaver): checkpointer is MemorySaver;
2646
-
2647
- /**
2648
- * Thread Management Utilities
2649
- *
2650
- * Provides utilities for managing conversation threads and configurations.
2651
- *
2652
- * @module langgraph/persistence/thread
2653
- */
2654
-
2655
- /**
2656
- * Configuration for a thread
2657
- */
2658
- interface ThreadConfig {
2659
- /**
2660
- * Unique identifier for the thread
2661
- */
2662
- threadId: string;
2663
- /**
2664
- * Optional checkpoint ID to resume from
2665
- */
2666
- checkpointId?: string;
2667
- /**
2668
- * Optional checkpoint namespace
2669
- */
2670
- checkpointNamespace?: string;
2671
- /**
2672
- * Additional metadata for the thread
2673
- */
2674
- metadata?: Record<string, any>;
2675
- }
2676
- /**
2677
- * Configuration for a conversation
2678
- */
2679
- interface ConversationConfig {
2680
- /**
2681
- * User ID for the conversation
2682
- */
2683
- userId: string;
2684
- /**
2685
- * Optional session ID
2686
- */
2687
- sessionId?: string;
2688
- /**
2689
- * Additional metadata
2690
- */
2691
- metadata?: Record<string, any>;
2692
- }
2693
- /**
2694
- * Generate a unique thread ID.
2695
- *
2696
- * If a seed is provided, generates a deterministic UUID v5 based on the seed.
2697
- * Otherwise, generates a random UUID v4.
2698
- *
2699
- * @example
2700
- * ```typescript
2701
- * import { generateThreadId } from '@agentforge/core';
2702
- *
2703
- * // Random thread ID
2704
- * const threadId = generateThreadId();
2705
- *
2706
- * // Deterministic thread ID from seed
2707
- * const threadId2 = generateThreadId('user-123');
2708
- * ```
2709
- *
2710
- * @param seed - Optional seed for deterministic ID generation
2711
- * @returns A unique thread ID
2712
- */
2713
- declare function generateThreadId(seed?: string): string;
2714
- /**
2715
- * Create a thread configuration for LangGraph.
2716
- *
2717
- * This creates a RunnableConfig object with the thread configuration
2718
- * that can be passed to graph.invoke() or graph.stream().
2719
- *
2720
- * @example
2721
- * ```typescript
2722
- * import { createThreadConfig } from '@agentforge/core';
2723
- *
2724
- * const config = createThreadConfig({
2725
- * threadId: 'conversation-1',
2726
- * metadata: { userId: 'user-123' },
2727
- * });
2728
- *
2729
- * const result = await app.invoke(input, config);
2730
- * ```
2731
- *
2732
- * @param config - Thread configuration
2733
- * @returns A RunnableConfig object
2734
- */
2735
- declare function createThreadConfig(config?: Partial<ThreadConfig>): RunnableConfig;
2736
- /**
2737
- * Create a conversation configuration for LangGraph.
2738
- *
2739
- * This is a convenience function that creates a thread configuration
2740
- * with user and session information, commonly used for chat applications.
2741
- *
2742
- * @example
2743
- * ```typescript
2744
- * import { createConversationConfig } from '@agentforge/core';
2745
- *
2746
- * const config = createConversationConfig({
2747
- * userId: 'user-123',
2748
- * sessionId: 'session-456',
2749
- * });
2750
- *
2751
- * const result = await app.invoke(input, config);
2752
- * ```
2753
- *
2754
- * @param config - Conversation configuration
2755
- * @returns A RunnableConfig object
2756
- */
2757
- declare function createConversationConfig(config: ConversationConfig): RunnableConfig;
2758
-
2759
- /**
2760
- * Checkpointer Utility Functions
2761
- *
2762
- * Provides utility functions for working with LangGraph checkpointers.
2763
- *
2764
- * @module langgraph/persistence/utils
2765
- */
2766
-
2767
- /**
2768
- * Options for getting checkpoint history
2769
- */
2770
- interface CheckpointHistoryOptions {
2771
- /**
2772
- * Thread ID to get history for
2773
- */
2774
- threadId: string;
2775
- /**
2776
- * Maximum number of checkpoints to return
2777
- * @default 10
2778
- */
2779
- limit?: number;
2780
- /**
2781
- * Get checkpoints before this checkpoint ID
2782
- */
2783
- before?: string;
2784
- }
2785
- /**
2786
- * Get the checkpoint history for a thread.
2787
- *
2788
- * Returns a list of checkpoints for the specified thread, ordered from
2789
- * most recent to oldest.
2790
- *
2791
- * @example
2792
- * ```typescript
2793
- * import { getCheckpointHistory } from '@agentforge/core';
2794
- *
2795
- * const history = await getCheckpointHistory(checkpointer, {
2796
- * threadId: 'conversation-1',
2797
- * limit: 10,
2798
- * });
2799
- *
2800
- * for (const checkpoint of history) {
2801
- * console.log(checkpoint.checkpoint.id);
2802
- * }
2803
- * ```
2804
- *
2805
- * @param checkpointer - The checkpointer to query
2806
- * @param options - History query options
2807
- * @returns A promise that resolves to an array of checkpoint tuples
2808
- */
2809
- declare function getCheckpointHistory(checkpointer: BaseCheckpointSaver, options: CheckpointHistoryOptions): Promise<CheckpointTuple[]>;
2810
- /**
2811
- * Get the latest checkpoint for a thread.
2812
- *
2813
- * Returns the most recent checkpoint for the specified thread, or null
2814
- * if no checkpoints exist.
2815
- *
2816
- * @example
2817
- * ```typescript
2818
- * import { getLatestCheckpoint } from '@agentforge/core';
2819
- *
2820
- * const latest = await getLatestCheckpoint(checkpointer, {
2821
- * threadId: 'conversation-1',
2822
- * });
2823
- *
2824
- * if (latest) {
2825
- * console.log('Latest checkpoint:', latest.checkpoint.id);
2826
- * }
2827
- * ```
2828
- *
2829
- * @param checkpointer - The checkpointer to query
2830
- * @param options - Query options
2831
- * @returns A promise that resolves to the latest checkpoint tuple or null
2832
- */
2833
- declare function getLatestCheckpoint(checkpointer: BaseCheckpointSaver, options: {
2834
- threadId: string;
2835
- }): Promise<CheckpointTuple | null>;
2836
- /**
2837
- * Clear all checkpoints for a thread.
2838
- *
2839
- * Note: This functionality depends on the checkpointer implementation.
2840
- * Not all checkpointers support deletion.
2841
- *
2842
- * @example
2843
- * ```typescript
2844
- * import { clearThread } from '@agentforge/core';
2845
- *
2846
- * await clearThread(checkpointer, {
2847
- * threadId: 'conversation-1',
2848
- * });
2849
- * ```
2850
- *
2851
- * @param checkpointer - The checkpointer to modify
2852
- * @param options - Clear options
2853
- * @returns A promise that resolves when the thread is cleared
2854
- * @throws Error if the checkpointer doesn't support deletion
2855
- */
2856
- declare function clearThread(checkpointer: BaseCheckpointSaver, options: {
2857
- threadId: string;
2858
- }): Promise<void>;
2859
-
2860
- /**
2861
- * LangSmith Integration Utilities
2862
- *
2863
- * Helpers for configuring and using LangSmith tracing with LangGraph.
2864
- */
2865
- /**
2866
- * LangSmith configuration options
2867
- */
2868
- interface LangSmithConfig {
2869
- /**
2870
- * LangSmith API key
2871
- * Can also be set via LANGSMITH_API_KEY environment variable
2872
- */
2873
- apiKey?: string;
2874
- /**
2875
- * Project name for organizing traces
2876
- * Can also be set via LANGSMITH_PROJECT environment variable
2877
- */
2878
- projectName?: string;
2879
- /**
2880
- * Whether tracing is enabled
2881
- * Can also be set via LANGSMITH_TRACING environment variable
2882
- * @default true if apiKey is provided
2883
- */
2884
- tracingEnabled?: boolean;
2885
- /**
2886
- * LangSmith API endpoint
2887
- * @default 'https://api.smith.langchain.com'
2888
- */
2889
- endpoint?: string;
2890
- /**
2891
- * Additional metadata to include in all traces
2892
- */
2893
- metadata?: Record<string, any>;
2894
- }
2895
- /**
2896
- * Configure LangSmith for tracing.
2897
- *
2898
- * This sets environment variables that LangChain/LangGraph use for tracing.
2899
- *
2900
- * @example
2901
- * ```typescript
2902
- * import { configureLangSmith } from '@agentforge/core';
2903
- *
2904
- * configureLangSmith({
2905
- * apiKey: process.env.LANGSMITH_API_KEY,
2906
- * projectName: 'my-agent',
2907
- * tracingEnabled: true,
2908
- * });
2909
- * ```
2910
- *
2911
- * @param config - LangSmith configuration
2912
- */
2913
- declare function configureLangSmith(config: LangSmithConfig): void;
2914
- /**
2915
- * Get the current LangSmith configuration.
2916
- *
2917
- * @returns The current configuration or null if not configured
2918
- */
2919
- declare function getLangSmithConfig(): LangSmithConfig | null;
2920
- /**
2921
- * Check if LangSmith tracing is enabled.
2922
- *
2923
- * @returns True if tracing is enabled
2924
- */
2925
- declare function isTracingEnabled(): boolean;
2926
- /**
2927
- * Options for tracing a node
2928
- */
2929
- interface TracingOptions {
2930
- /**
2931
- * Name for the traced operation
2932
- */
2933
- name: string;
2934
- /**
2935
- * Additional metadata to include in the trace
2936
- */
2937
- metadata?: Record<string, any>;
2938
- /**
2939
- * Tags to categorize the trace
2940
- */
2941
- tags?: string[];
2942
- /**
2943
- * Run name for the trace
2944
- */
2945
- runName?: string;
2946
- }
2947
- /**
2948
- * Wrap a node function with LangSmith tracing.
2949
- *
2950
- * This adds metadata to the execution context that LangSmith can use for tracing.
2951
- *
2952
- * @example
2953
- * ```typescript
2954
- * import { withTracing } from '@agentforge/core';
2955
- *
2956
- * const tracedNode = withTracing(myNode, {
2957
- * name: 'research-node',
2958
- * metadata: { category: 'research' },
2959
- * tags: ['research', 'web'],
2960
- * });
2961
- * ```
2962
- *
2963
- * @param node - The node function to wrap
2964
- * @param options - Tracing options
2965
- * @returns A wrapped node function with tracing
2966
- */
2967
- declare function withTracing<State>(node: (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>, options: TracingOptions): (state: State) => Promise<State | Partial<State>>;
2968
-
2969
- /**
2970
- * Structured Logging Utilities
2971
- *
2972
- * Provides consistent, structured logging for LangGraph agents.
2973
- */
2974
- /**
2975
- * Log levels
2742
+ * Log levels
2976
2743
  */
2977
2744
  declare enum LogLevel {
2978
2745
  DEBUG = "debug",
@@ -3042,51 +2809,270 @@ interface Logger {
3042
2809
  */
3043
2810
  error(message: string, data?: Record<string, any>): void;
3044
2811
  /**
3045
- * Check if debug logging is enabled
3046
- * Useful for avoiding expensive computations when debug is disabled
2812
+ * Check if debug logging is enabled
2813
+ * Useful for avoiding expensive computations when debug is disabled
2814
+ */
2815
+ isDebugEnabled(): boolean;
2816
+ /**
2817
+ * Check if a specific log level is enabled
2818
+ */
2819
+ isLevelEnabled(level: LogLevel): boolean;
2820
+ /**
2821
+ * Create a child logger with additional context
2822
+ */
2823
+ withContext(context: Record<string, any>): Logger;
2824
+ }
2825
+ /**
2826
+ * Create a structured logger.
2827
+ *
2828
+ * @example
2829
+ * Basic usage:
2830
+ * ```typescript
2831
+ * import { createLogger, LogLevel } from '@agentforge/core';
2832
+ *
2833
+ * const logger = createLogger('my-agent', {
2834
+ * level: LogLevel.INFO,
2835
+ * format: 'json',
2836
+ * });
2837
+ *
2838
+ * logger.info('Processing request', { userId: 'user-123' });
2839
+ * logger.error('Request failed', { error: err.message });
2840
+ * ```
2841
+ *
2842
+ * @example
2843
+ * Performance optimization with isDebugEnabled:
2844
+ * ```typescript
2845
+ * // Avoid expensive computations when debug is disabled
2846
+ * if (logger.isDebugEnabled()) {
2847
+ * const expensiveData = computeExpensiveDebugInfo();
2848
+ * logger.debug('Debug info', expensiveData);
2849
+ * }
2850
+ * ```
2851
+ *
2852
+ * @param name - Logger name (typically the agent or component name)
2853
+ * @param options - Logger configuration options
2854
+ * @returns A logger instance
2855
+ */
2856
+ declare function createLogger(name: string, options?: LoggerOptions): Logger;
2857
+
2858
+ /**
2859
+ * Middleware Presets
2860
+ *
2861
+ * Pre-configured middleware combinations for common use cases.
2862
+ *
2863
+ * @module langgraph/middleware/presets
2864
+ */
2865
+
2866
+ /**
2867
+ * Options for the production preset.
2868
+ */
2869
+ interface ProductionPresetOptions<State> {
2870
+ /**
2871
+ * Name of the node (for logging and metrics)
2872
+ */
2873
+ nodeName: string;
2874
+ /**
2875
+ * Logger instance
2876
+ */
2877
+ logger?: Logger;
2878
+ /**
2879
+ * Enable metrics tracking
2880
+ * @default true
2881
+ */
2882
+ enableMetrics?: boolean;
2883
+ /**
2884
+ * Enable tracing
2885
+ * @default true
2886
+ */
2887
+ enableTracing?: boolean;
2888
+ /**
2889
+ * Enable retry logic
2890
+ * @default true
2891
+ */
2892
+ enableRetry?: boolean;
2893
+ /**
2894
+ * Timeout in milliseconds
2895
+ * @default 30000 (30 seconds)
2896
+ */
2897
+ timeout?: number;
2898
+ /**
2899
+ * Custom retry options
2900
+ */
2901
+ retryOptions?: Partial<RetryOptions>;
2902
+ /**
2903
+ * Custom error handler options
2904
+ */
2905
+ errorOptions?: Partial<ErrorHandlerOptions<State>>;
2906
+ }
2907
+ /**
2908
+ * Production preset with comprehensive error handling, metrics, and tracing.
2909
+ *
2910
+ * Includes:
2911
+ * - Error handling with fallback
2912
+ * - Retry logic with exponential backoff
2913
+ * - Timeout protection
2914
+ * - Metrics tracking
2915
+ * - Distributed tracing
2916
+ *
2917
+ * @example
2918
+ * ```typescript
2919
+ * const productionNode = presets.production(myNode, {
2920
+ * nodeName: 'my-node',
2921
+ * logger: createLogger({ level: LogLevel.INFO }),
2922
+ * });
2923
+ * ```
2924
+ */
2925
+ declare function production<State>(node: NodeFunction<State>, options: ProductionPresetOptions<State>): NodeFunction<State>;
2926
+ /**
2927
+ * Options for the development preset.
2928
+ */
2929
+ interface DevelopmentPresetOptions {
2930
+ /**
2931
+ * Name of the node
2932
+ */
2933
+ nodeName: string;
2934
+ /**
2935
+ * Enable verbose logging
2936
+ * @default true
2937
+ */
2938
+ verbose?: boolean;
2939
+ /**
2940
+ * Logger instance
2941
+ */
2942
+ logger?: Logger;
2943
+ }
2944
+ /**
2945
+ * Development preset with verbose logging and debugging.
2946
+ *
2947
+ * Includes:
2948
+ * - Verbose logging
2949
+ * - Error details
2950
+ * - No retry (fail fast)
2951
+ * - Extended timeout
2952
+ *
2953
+ * @example
2954
+ * ```typescript
2955
+ * const devNode = presets.development(myNode, {
2956
+ * nodeName: 'my-node',
2957
+ * verbose: true,
2958
+ * });
2959
+ * ```
2960
+ */
2961
+ declare function development<State>(node: NodeFunction<State>, options: DevelopmentPresetOptions): NodeFunction<State>;
2962
+ /**
2963
+ * Options for the testing preset.
2964
+ */
2965
+ interface TestingPresetOptions<State> {
2966
+ /**
2967
+ * Name of the node
2968
+ */
2969
+ nodeName: string;
2970
+ /**
2971
+ * Mock responses for testing
2972
+ */
2973
+ mockResponse?: Partial<State>;
2974
+ /**
2975
+ * Simulate errors for testing
2976
+ */
2977
+ simulateError?: Error;
2978
+ /**
2979
+ * Delay in milliseconds for testing async behavior
2980
+ */
2981
+ delay?: number;
2982
+ /**
2983
+ * Track invocations for assertions
2984
+ */
2985
+ trackInvocations?: boolean;
2986
+ }
2987
+ /**
2988
+ * Testing preset for unit and integration tests.
2989
+ *
2990
+ * Includes:
2991
+ * - Mock responses
2992
+ * - Error simulation
2993
+ * - Invocation tracking
2994
+ * - Configurable delays
2995
+ *
2996
+ * @example
2997
+ * ```typescript
2998
+ * const testNode = presets.testing(myNode, {
2999
+ * nodeName: 'my-node',
3000
+ * mockResponse: { result: 'mocked' },
3001
+ * trackInvocations: true,
3002
+ * });
3003
+ * ```
3004
+ */
3005
+ declare function testing<State>(node: NodeFunction<State>, options: TestingPresetOptions<State>): NodeFunction<State> & {
3006
+ invocations: State[];
3007
+ };
3008
+ /**
3009
+ * Preset collection for easy access.
3010
+ */
3011
+ declare const presets: {
3012
+ production: typeof production;
3013
+ development: typeof development;
3014
+ testing: typeof testing;
3015
+ };
3016
+
3017
+ /**
3018
+ * Timeout pattern for LangGraph nodes
3019
+ *
3020
+ * Wraps a node function with timeout logic.
3021
+ */
3022
+ /**
3023
+ * Options for timeout behavior
3024
+ */
3025
+ interface TimeoutOptions<State> {
3026
+ /**
3027
+ * Timeout duration in milliseconds
3028
+ */
3029
+ timeout: number;
3030
+ /**
3031
+ * Callback function to handle timeouts
3032
+ * Should return a state update to apply when a timeout occurs
3047
3033
  */
3048
- isDebugEnabled(): boolean;
3034
+ onTimeout: (state: State) => State | Partial<State> | Promise<State | Partial<State>>;
3049
3035
  /**
3050
- * Check if a specific log level is enabled
3036
+ * Optional callback for logging timeouts
3051
3037
  */
3052
- isLevelEnabled(level: LogLevel): boolean;
3038
+ logTimeout?: (state: State) => void;
3053
3039
  /**
3054
- * Create a child logger with additional context
3040
+ * Whether to throw an error on timeout
3041
+ * @default false
3055
3042
  */
3056
- withContext(context: Record<string, any>): Logger;
3043
+ throwOnTimeout?: boolean;
3057
3044
  }
3058
3045
  /**
3059
- * Create a structured logger.
3046
+ * Error thrown when a node times out
3047
+ */
3048
+ declare class TimeoutError extends Error {
3049
+ constructor(timeout: number);
3050
+ }
3051
+ /**
3052
+ * Wraps a node function with timeout logic.
3060
3053
  *
3061
3054
  * @example
3062
- * Basic usage:
3063
3055
  * ```typescript
3064
- * import { createLogger, LogLevel } from '@agentforge/core';
3065
- *
3066
- * const logger = createLogger('my-agent', {
3067
- * level: LogLevel.INFO,
3068
- * format: 'json',
3056
+ * const timedNode = withTimeout(myNode, {
3057
+ * timeout: 5000,
3058
+ * onTimeout: (state) => ({
3059
+ * ...state,
3060
+ * timedOut: true,
3061
+ * error: 'Operation timed out',
3062
+ * }),
3063
+ * logTimeout: () => {
3064
+ * console.warn('Node timed out');
3065
+ * },
3069
3066
  * });
3070
3067
  *
3071
- * logger.info('Processing request', { userId: 'user-123' });
3072
- * logger.error('Request failed', { error: err.message });
3073
- * ```
3074
- *
3075
- * @example
3076
- * Performance optimization with isDebugEnabled:
3077
- * ```typescript
3078
- * // Avoid expensive computations when debug is disabled
3079
- * if (logger.isDebugEnabled()) {
3080
- * const expensiveData = computeExpensiveDebugInfo();
3081
- * logger.debug('Debug info', expensiveData);
3082
- * }
3068
+ * graph.addNode('timed', timedNode);
3083
3069
  * ```
3084
3070
  *
3085
- * @param name - Logger name (typically the agent or component name)
3086
- * @param options - Logger configuration options
3087
- * @returns A logger instance
3071
+ * @param node - The node function to wrap
3072
+ * @param options - Timeout configuration options
3073
+ * @returns A wrapped node function with timeout logic
3088
3074
  */
3089
- declare function createLogger(name: string, options?: LoggerOptions): Logger;
3075
+ declare function withTimeout<State>(node: (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>, options: TimeoutOptions<State>): (state: State) => Promise<State | Partial<State>>;
3090
3076
 
3091
3077
  /**
3092
3078
  * Metrics Collection Utilities
@@ -3233,515 +3219,529 @@ interface MetricsNodeOptions {
3233
3219
  declare function withMetrics<State>(node: (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>, options: MetricsNodeOptions): (state: State) => Promise<State | Partial<State>>;
3234
3220
 
3235
3221
  /**
3236
- * Enhanced Error Handling Utilities
3222
+ * LangSmith Integration Utilities
3237
3223
  *
3238
- * Provides enhanced error classes and error reporting for better debugging.
3224
+ * Helpers for configuring and using LangSmith tracing with LangGraph.
3239
3225
  */
3240
3226
  /**
3241
- * Error context information
3227
+ * LangSmith configuration options
3242
3228
  */
3243
- interface ErrorContext {
3229
+ interface LangSmithConfig {
3244
3230
  /**
3245
- * Error code for categorization
3231
+ * LangSmith API key
3232
+ * Can also be set via LANGSMITH_API_KEY environment variable
3246
3233
  */
3247
- code?: string;
3234
+ apiKey?: string;
3248
3235
  /**
3249
- * Node name where the error occurred
3236
+ * Project name for organizing traces
3237
+ * Can also be set via LANGSMITH_PROJECT environment variable
3250
3238
  */
3251
- node?: string;
3239
+ projectName?: string;
3252
3240
  /**
3253
- * Current state when the error occurred
3241
+ * Whether tracing is enabled
3242
+ * Can also be set via LANGSMITH_TRACING environment variable
3243
+ * @default true if apiKey is provided
3254
3244
  */
3255
- state?: any;
3245
+ tracingEnabled?: boolean;
3256
3246
  /**
3257
- * Additional metadata
3247
+ * LangSmith API endpoint
3248
+ * @default 'https://api.smith.langchain.com'
3258
3249
  */
3259
- metadata?: Record<string, any>;
3250
+ endpoint?: string;
3260
3251
  /**
3261
- * Original error that caused this error
3252
+ * Additional metadata to include in all traces
3262
3253
  */
3263
- cause?: Error;
3254
+ metadata?: Record<string, any>;
3264
3255
  }
3265
3256
  /**
3266
- * Enhanced error class for agent errors
3257
+ * Configure LangSmith for tracing.
3258
+ *
3259
+ * This sets environment variables that LangChain/LangGraph use for tracing.
3260
+ *
3261
+ * @example
3262
+ * ```typescript
3263
+ * import { configureLangSmith } from '@agentforge/core';
3264
+ *
3265
+ * configureLangSmith({
3266
+ * apiKey: process.env.LANGSMITH_API_KEY,
3267
+ * projectName: 'my-agent',
3268
+ * tracingEnabled: true,
3269
+ * });
3270
+ * ```
3271
+ *
3272
+ * @param config - LangSmith configuration
3267
3273
  */
3268
- declare class AgentError extends Error {
3269
- readonly code?: string;
3270
- readonly node?: string;
3271
- readonly state?: any;
3272
- readonly metadata?: Record<string, any>;
3273
- readonly cause?: Error;
3274
- readonly timestamp: number;
3275
- constructor(message: string, context?: ErrorContext);
3276
- /**
3277
- * Convert error to JSON for logging/reporting
3278
- */
3279
- toJSON(): Record<string, any>;
3280
- /**
3281
- * Get a human-readable string representation
3282
- */
3283
- toString(): string;
3284
- }
3274
+ declare function configureLangSmith(config: LangSmithConfig): void;
3285
3275
  /**
3286
- * Error reporter configuration
3276
+ * Get the current LangSmith configuration.
3277
+ *
3278
+ * @returns The current configuration or null if not configured
3287
3279
  */
3288
- interface ErrorReporterOptions {
3289
- /**
3290
- * Callback function to handle errors
3291
- */
3292
- onError: (error: AgentError) => void | Promise<void>;
3293
- /**
3294
- * Whether to include stack traces
3295
- * @default true
3296
- */
3297
- includeStackTrace?: boolean;
3280
+ declare function getLangSmithConfig(): LangSmithConfig | null;
3281
+ /**
3282
+ * Check if LangSmith tracing is enabled.
3283
+ *
3284
+ * @returns True if tracing is enabled
3285
+ */
3286
+ declare function isTracingEnabled(): boolean;
3287
+ /**
3288
+ * Options for tracing a node
3289
+ */
3290
+ interface TracingOptions {
3298
3291
  /**
3299
- * Whether to include state in error context
3300
- * @default false (for security/privacy)
3292
+ * Name for the traced operation
3301
3293
  */
3302
- includeState?: boolean;
3294
+ name: string;
3303
3295
  /**
3304
- * Whether to rethrow errors after reporting
3305
- * @default true
3296
+ * Additional metadata to include in the trace
3306
3297
  */
3307
- rethrow?: boolean;
3308
- }
3309
- /**
3310
- * Error reporter for tracking and reporting errors
3311
- */
3312
- interface ErrorReporter {
3298
+ metadata?: Record<string, any>;
3313
3299
  /**
3314
- * Wrap a node function with error reporting
3300
+ * Tags to categorize the trace
3315
3301
  */
3316
- wrap<State>(node: (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>, nodeName?: string): (state: State) => Promise<State | Partial<State>>;
3302
+ tags?: string[];
3317
3303
  /**
3318
- * Report an error manually
3304
+ * Run name for the trace
3319
3305
  */
3320
- report(error: Error, context?: ErrorContext): Promise<void>;
3306
+ runName?: string;
3321
3307
  }
3322
3308
  /**
3323
- * Create an error reporter.
3309
+ * Wrap a node function with LangSmith tracing.
3310
+ *
3311
+ * This adds metadata to the execution context that LangSmith can use for tracing.
3324
3312
  *
3325
3313
  * @example
3326
3314
  * ```typescript
3327
- * import { createErrorReporter } from '@agentforge/core';
3315
+ * import { withTracing } from '@agentforge/core';
3328
3316
  *
3329
- * const reporter = createErrorReporter({
3330
- * onError: (error) => {
3331
- * console.error('Agent error:', error.toJSON());
3332
- * // Send to error tracking service
3333
- * },
3334
- * includeStackTrace: true,
3335
- * includeState: false,
3317
+ * const tracedNode = withTracing(myNode, {
3318
+ * name: 'research-node',
3319
+ * metadata: { category: 'research' },
3320
+ * tags: ['research', 'web'],
3336
3321
  * });
3337
- *
3338
- * const safeNode = reporter.wrap(myNode, 'my-node');
3339
3322
  * ```
3340
3323
  *
3341
- * @param options - Error reporter configuration
3342
- * @returns An error reporter instance
3324
+ * @param node - The node function to wrap
3325
+ * @param options - Tracing options
3326
+ * @returns A wrapped node function with tracing
3343
3327
  */
3344
- declare function createErrorReporter(options: ErrorReporterOptions): ErrorReporter;
3328
+ declare function withTracing<State>(node: (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>, options: TracingOptions): (state: State) => Promise<State | Partial<State>>;
3345
3329
 
3346
3330
  /**
3347
- * Middleware System - Type Definitions
3331
+ * Checkpointer Factory Functions
3348
3332
  *
3349
- * Core types and interfaces for the middleware system.
3350
- * All middleware follows a consistent, composable pattern.
3333
+ * Provides factory functions for creating LangGraph checkpointers with sensible defaults.
3351
3334
  *
3352
- * @module langgraph/middleware/types
3335
+ * @module langgraph/persistence/checkpointer
3353
3336
  */
3337
+
3354
3338
  /**
3355
- * A LangGraph node function that processes state.
3356
- *
3357
- * Node functions can return:
3358
- * - Full state (State)
3359
- * - Partial state update (Partial<State>)
3360
- * - Promise of either
3361
- *
3362
- * @template State - The state type for the node
3339
+ * Serializer protocol for checkpoint data
3363
3340
  */
3364
- type NodeFunction<State> = (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>;
3341
+ interface SerializerProtocol {
3342
+ }
3365
3343
  /**
3366
- * A middleware function that wraps a node function.
3367
- *
3368
- * Middleware takes a node function and options, and returns a new node function
3369
- * with enhanced behavior (logging, metrics, retry, etc.).
3344
+ * Common options for all checkpointers
3345
+ */
3346
+ interface CheckpointerOptions {
3347
+ /**
3348
+ * Custom serializer for checkpoint data
3349
+ * @default undefined (uses default serializer)
3350
+ */
3351
+ serializer?: SerializerProtocol;
3352
+ }
3353
+ /**
3354
+ * Options for SQLite checkpointer
3355
+ */
3356
+ interface SqliteCheckpointerOptions extends CheckpointerOptions {
3357
+ /**
3358
+ * Path to the SQLite database file
3359
+ * @default ':memory:' (in-memory database)
3360
+ */
3361
+ path?: string;
3362
+ /**
3363
+ * Whether to automatically run migrations
3364
+ * @default true
3365
+ */
3366
+ autoMigrate?: boolean;
3367
+ }
3368
+ /**
3369
+ * Create an in-memory checkpointer for development and testing.
3370
3370
  *
3371
- * @template State - The state type for the node
3372
- * @template Options - Configuration options for the middleware
3371
+ * This checkpointer stores all checkpoints in memory and is lost when the process exits.
3372
+ * Ideal for development, testing, and experimentation.
3373
3373
  *
3374
3374
  * @example
3375
3375
  * ```typescript
3376
- * const loggingMiddleware: Middleware<MyState, LoggingOptions> = (node, options) => {
3377
- * return async (state) => {
3378
- * console.log('Before:', state);
3379
- * const result = await node(state);
3380
- * console.log('After:', result);
3381
- * return result;
3382
- * };
3383
- * };
3376
+ * import { createMemoryCheckpointer } from '@agentforge/core';
3377
+ *
3378
+ * const checkpointer = createMemoryCheckpointer();
3379
+ *
3380
+ * const app = workflow.compile({ checkpointer });
3384
3381
  * ```
3382
+ *
3383
+ * @param options - Optional checkpointer configuration
3384
+ * @returns A MemorySaver instance
3385
3385
  */
3386
- type Middleware<State, Options = unknown> = (node: NodeFunction<State>, options: Options) => NodeFunction<State>;
3386
+ declare function createMemoryCheckpointer(options?: CheckpointerOptions): MemorySaver;
3387
3387
  /**
3388
- * A middleware factory that creates middleware with bound options.
3388
+ * Create a SQLite-based checkpointer for local persistence.
3389
3389
  *
3390
- * This is useful for creating reusable middleware configurations.
3390
+ * This checkpointer stores checkpoints in a SQLite database file, providing
3391
+ * persistence across process restarts. Ideal for local development and
3392
+ * single-machine deployments.
3391
3393
  *
3392
- * @template State - The state type for the node
3393
- * @template Options - Configuration options for the middleware
3394
+ * Note: Requires `@langchain/langgraph-checkpoint-sqlite` to be installed.
3394
3395
  *
3395
3396
  * @example
3396
3397
  * ```typescript
3397
- * const createLogger: MiddlewareFactory<MyState, LoggingOptions> = (options) => {
3398
- * return (node) => {
3399
- * return async (state) => {
3400
- * // Logging logic using options
3401
- * return await node(state);
3402
- * };
3403
- * };
3404
- * };
3398
+ * import { createSqliteCheckpointer } from '@agentforge/core';
3399
+ *
3400
+ * // Use a file-based database
3401
+ * const checkpointer = await createSqliteCheckpointer({
3402
+ * path: './checkpoints.db',
3403
+ * autoMigrate: true,
3404
+ * });
3405
+ *
3406
+ * const app = workflow.compile({ checkpointer });
3405
3407
  * ```
3408
+ *
3409
+ * @param options - SQLite checkpointer configuration
3410
+ * @returns A Promise that resolves to a SqliteSaver instance
3411
+ * @throws Error if @langchain/langgraph-checkpoint-sqlite is not installed
3406
3412
  */
3407
- type MiddlewareFactory<State, Options = unknown> = (options: Options) => (node: NodeFunction<State>) => NodeFunction<State>;
3413
+ declare function createSqliteCheckpointer(options?: SqliteCheckpointerOptions): Promise<BaseCheckpointSaver>;
3408
3414
  /**
3409
- * A middleware that doesn't require options.
3415
+ * Type guard to check if a checkpointer is a MemorySaver
3410
3416
  *
3411
- * @template State - The state type for the node
3417
+ * @param checkpointer - The checkpointer to check
3418
+ * @returns True if the checkpointer is a MemorySaver
3412
3419
  */
3413
- type SimpleMiddleware<State> = (node: NodeFunction<State>) => NodeFunction<State>;
3420
+ declare function isMemoryCheckpointer(checkpointer: BaseCheckpointSaver): checkpointer is MemorySaver;
3421
+
3414
3422
  /**
3415
- * Configuration for middleware composition.
3423
+ * Thread Management Utilities
3424
+ *
3425
+ * Provides utilities for managing conversation threads and configurations.
3426
+ *
3427
+ * @module langgraph/persistence/thread
3416
3428
  */
3417
- interface ComposeOptions {
3418
- /**
3419
- * Whether to execute middleware in reverse order.
3420
- * @default false
3421
- */
3422
- reverse?: boolean;
3423
- /**
3424
- * Name for the composed middleware (for debugging).
3425
- */
3426
- name?: string;
3427
- /**
3428
- * Whether to catch and handle errors in middleware.
3429
- * @default true
3430
- */
3431
- catchErrors?: boolean;
3432
- }
3429
+
3433
3430
  /**
3434
- * Metadata about a middleware function.
3431
+ * Configuration for a thread
3435
3432
  */
3436
- interface MiddlewareMetadata {
3437
- /**
3438
- * Name of the middleware
3439
- */
3440
- name: string;
3441
- /**
3442
- * Description of what the middleware does
3443
- */
3444
- description?: string;
3433
+ interface ThreadConfig {
3445
3434
  /**
3446
- * Version of the middleware
3435
+ * Unique identifier for the thread
3447
3436
  */
3448
- version?: string;
3437
+ threadId: string;
3449
3438
  /**
3450
- * Tags for categorizing middleware
3439
+ * Optional checkpoint ID to resume from
3451
3440
  */
3452
- tags?: string[];
3453
- }
3454
- /**
3455
- * A middleware with attached metadata.
3456
- */
3457
- interface MiddlewareWithMetadata<State, Options = unknown> {
3441
+ checkpointId?: string;
3458
3442
  /**
3459
- * The middleware function
3443
+ * Optional checkpoint namespace
3460
3444
  */
3461
- middleware: Middleware<State, Options>;
3445
+ checkpointNamespace?: string;
3462
3446
  /**
3463
- * Metadata about the middleware
3447
+ * Additional metadata for the thread
3464
3448
  */
3465
- metadata: MiddlewareMetadata;
3449
+ metadata?: Record<string, any>;
3466
3450
  }
3467
3451
  /**
3468
- * Context passed through middleware chain.
3469
- *
3470
- * This allows middleware to share information without modifying state.
3452
+ * Configuration for a conversation
3471
3453
  */
3472
- interface MiddlewareContext {
3473
- /**
3474
- * Unique ID for this execution
3475
- */
3476
- executionId: string;
3454
+ interface ConversationConfig {
3477
3455
  /**
3478
- * Timestamp when execution started
3456
+ * User ID for the conversation
3479
3457
  */
3480
- startTime: number;
3458
+ userId: string;
3481
3459
  /**
3482
- * Custom data that middleware can read/write
3460
+ * Optional session ID
3483
3461
  */
3484
- data: Record<string, unknown>;
3462
+ sessionId?: string;
3485
3463
  /**
3486
- * Stack of middleware names that have been applied
3464
+ * Additional metadata
3487
3465
  */
3488
- middlewareStack: string[];
3466
+ metadata?: Record<string, any>;
3489
3467
  }
3490
3468
  /**
3491
- * Enhanced node function with middleware context.
3469
+ * Generate a unique thread ID.
3470
+ *
3471
+ * If a seed is provided, generates a deterministic UUID v5 based on the seed.
3472
+ * Otherwise, generates a random UUID v4.
3473
+ *
3474
+ * @example
3475
+ * ```typescript
3476
+ * import { generateThreadId } from '@agentforge/core';
3477
+ *
3478
+ * // Random thread ID
3479
+ * const threadId = generateThreadId();
3480
+ *
3481
+ * // Deterministic thread ID from seed
3482
+ * const threadId2 = generateThreadId('user-123');
3483
+ * ```
3484
+ *
3485
+ * @param seed - Optional seed for deterministic ID generation
3486
+ * @returns A unique thread ID
3492
3487
  */
3493
- type NodeFunctionWithContext<State> = (state: State, context: MiddlewareContext) => State | Promise<State> | Partial<State> | Promise<Partial<State>>;
3494
-
3488
+ declare function generateThreadId(seed?: string): string;
3495
3489
  /**
3496
- * Middleware Composition Utilities
3490
+ * Create a thread configuration for LangGraph.
3497
3491
  *
3498
- * Functions for composing multiple middleware into a single middleware chain.
3492
+ * This creates a RunnableConfig object with the thread configuration
3493
+ * that can be passed to graph.invoke() or graph.stream().
3499
3494
  *
3500
- * @module langgraph/middleware/compose
3495
+ * @example
3496
+ * ```typescript
3497
+ * import { createThreadConfig } from '@agentforge/core';
3498
+ *
3499
+ * const config = createThreadConfig({
3500
+ * threadId: 'conversation-1',
3501
+ * metadata: { userId: 'user-123' },
3502
+ * });
3503
+ *
3504
+ * const result = await app.invoke(input, config);
3505
+ * ```
3506
+ *
3507
+ * @param config - Thread configuration
3508
+ * @returns A RunnableConfig object
3501
3509
  */
3502
-
3510
+ declare function createThreadConfig(config?: Partial<ThreadConfig>): RunnableConfig;
3503
3511
  /**
3504
- * Compose multiple middleware functions into a single middleware.
3512
+ * Create a conversation configuration for LangGraph.
3505
3513
  *
3506
- * Middleware are applied from left to right (first middleware wraps the node,
3507
- * second middleware wraps the first, etc.).
3514
+ * This is a convenience function that creates a thread configuration
3515
+ * with user and session information, commonly used for chat applications.
3508
3516
  *
3509
3517
  * @example
3510
3518
  * ```typescript
3511
- * const enhanced = compose(
3512
- * withLogging({ level: 'info' }),
3513
- * withMetrics({ name: 'my-node' }),
3514
- * withRetry({ maxAttempts: 3 })
3515
- * )(myNode);
3519
+ * import { createConversationConfig } from '@agentforge/core';
3520
+ *
3521
+ * const config = createConversationConfig({
3522
+ * userId: 'user-123',
3523
+ * sessionId: 'session-456',
3524
+ * });
3525
+ *
3526
+ * const result = await app.invoke(input, config);
3516
3527
  * ```
3517
3528
  *
3518
- * @param middleware - Middleware functions to compose
3519
- * @returns A function that takes a node and returns the enhanced node
3529
+ * @param config - Conversation configuration
3530
+ * @returns A RunnableConfig object
3520
3531
  */
3521
- declare function compose<State>(...middleware: SimpleMiddleware<State>[]): SimpleMiddleware<State>;
3532
+ declare function createConversationConfig(config: ConversationConfig): RunnableConfig;
3533
+
3522
3534
  /**
3523
- * Compose middleware with options.
3535
+ * Checkpointer Utility Functions
3536
+ *
3537
+ * Provides utility functions for working with LangGraph checkpointers.
3538
+ *
3539
+ * @module langgraph/persistence/utils
3540
+ */
3541
+
3542
+ /**
3543
+ * Options for getting checkpoint history
3544
+ */
3545
+ interface CheckpointHistoryOptions {
3546
+ /**
3547
+ * Thread ID to get history for
3548
+ */
3549
+ threadId: string;
3550
+ /**
3551
+ * Maximum number of checkpoints to return
3552
+ * @default 10
3553
+ */
3554
+ limit?: number;
3555
+ /**
3556
+ * Get checkpoints before this checkpoint ID
3557
+ */
3558
+ before?: string;
3559
+ }
3560
+ /**
3561
+ * Get the checkpoint history for a thread.
3562
+ *
3563
+ * Returns a list of checkpoints for the specified thread, ordered from
3564
+ * most recent to oldest.
3524
3565
  *
3525
3566
  * @example
3526
3567
  * ```typescript
3527
- * const enhanced = composeWithOptions(
3528
- * { reverse: true, name: 'my-chain' },
3529
- * withLogging({ level: 'info' }),
3530
- * withMetrics({ name: 'my-node' })
3531
- * )(myNode);
3568
+ * import { getCheckpointHistory } from '@agentforge/core';
3569
+ *
3570
+ * const history = await getCheckpointHistory(checkpointer, {
3571
+ * threadId: 'conversation-1',
3572
+ * limit: 10,
3573
+ * });
3574
+ *
3575
+ * for (const checkpoint of history) {
3576
+ * console.log(checkpoint.checkpoint.id);
3577
+ * }
3532
3578
  * ```
3533
3579
  *
3534
- * @param options - Composition options
3535
- * @param middleware - Middleware functions to compose
3536
- * @returns A function that takes a node and returns the enhanced node
3580
+ * @param checkpointer - The checkpointer to query
3581
+ * @param options - History query options
3582
+ * @returns A promise that resolves to an array of checkpoint tuples
3537
3583
  */
3538
- declare function composeWithOptions<State>(options: ComposeOptions, ...middleware: SimpleMiddleware<State>[]): SimpleMiddleware<State>;
3584
+ declare function getCheckpointHistory(checkpointer: BaseCheckpointSaver, options: CheckpointHistoryOptions): Promise<CheckpointTuple[]>;
3539
3585
  /**
3540
- * Create a middleware chain builder for fluent API.
3586
+ * Get the latest checkpoint for a thread.
3587
+ *
3588
+ * Returns the most recent checkpoint for the specified thread, or null
3589
+ * if no checkpoints exist.
3541
3590
  *
3542
3591
  * @example
3543
3592
  * ```typescript
3544
- * const enhanced = chain<MyState>()
3545
- * .use(withLogging({ level: 'info' }))
3546
- * .use(withMetrics({ name: 'my-node' }))
3547
- * .use(withRetry({ maxAttempts: 3 }))
3548
- * .build(myNode);
3593
+ * import { getLatestCheckpoint } from '@agentforge/core';
3594
+ *
3595
+ * const latest = await getLatestCheckpoint(checkpointer, {
3596
+ * threadId: 'conversation-1',
3597
+ * });
3598
+ *
3599
+ * if (latest) {
3600
+ * console.log('Latest checkpoint:', latest.checkpoint.id);
3601
+ * }
3549
3602
  * ```
3603
+ *
3604
+ * @param checkpointer - The checkpointer to query
3605
+ * @param options - Query options
3606
+ * @returns A promise that resolves to the latest checkpoint tuple or null
3550
3607
  */
3551
- declare class MiddlewareChain<State> {
3552
- private middleware;
3553
- private options;
3554
- /**
3555
- * Add middleware to the chain.
3556
- */
3557
- use(middleware: SimpleMiddleware<State>): this;
3558
- /**
3559
- * Set composition options.
3560
- */
3561
- withOptions(options: ComposeOptions): this;
3562
- /**
3563
- * Build the middleware chain and apply it to a node.
3564
- */
3565
- build(node: NodeFunction<State>): NodeFunction<State>;
3566
- /**
3567
- * Get the number of middleware in the chain.
3568
- */
3569
- get length(): number;
3570
- }
3608
+ declare function getLatestCheckpoint(checkpointer: BaseCheckpointSaver, options: {
3609
+ threadId: string;
3610
+ }): Promise<CheckpointTuple | null>;
3571
3611
  /**
3572
- * Create a new middleware chain builder.
3612
+ * Clear all checkpoints for a thread.
3613
+ *
3614
+ * Note: This functionality depends on the checkpointer implementation.
3615
+ * Not all checkpointers support deletion.
3573
3616
  *
3574
3617
  * @example
3575
3618
  * ```typescript
3576
- * const enhanced = chain<MyState>()
3577
- * .use(withLogging({ level: 'info' }))
3578
- * .build(myNode);
3619
+ * import { clearThread } from '@agentforge/core';
3620
+ *
3621
+ * await clearThread(checkpointer, {
3622
+ * threadId: 'conversation-1',
3623
+ * });
3579
3624
  * ```
3625
+ *
3626
+ * @param checkpointer - The checkpointer to modify
3627
+ * @param options - Clear options
3628
+ * @returns A promise that resolves when the thread is cleared
3629
+ * @throws Error if the checkpointer doesn't support deletion
3580
3630
  */
3581
- declare function chain<State>(): MiddlewareChain<State>;
3582
- /**
3583
- * Create a middleware context for tracking execution.
3584
- */
3585
- declare function createMiddlewareContext(): MiddlewareContext;
3631
+ declare function clearThread(checkpointer: BaseCheckpointSaver, options: {
3632
+ threadId: string;
3633
+ }): Promise<void>;
3586
3634
 
3587
3635
  /**
3588
- * Middleware Presets
3589
- *
3590
- * Pre-configured middleware combinations for common use cases.
3636
+ * Enhanced Error Handling Utilities
3591
3637
  *
3592
- * @module langgraph/middleware/presets
3638
+ * Provides enhanced error classes and error reporting for better debugging.
3593
3639
  */
3594
-
3595
3640
  /**
3596
- * Options for the production preset.
3641
+ * Error context information
3597
3642
  */
3598
- interface ProductionPresetOptions<State> {
3599
- /**
3600
- * Name of the node (for logging and metrics)
3601
- */
3602
- nodeName: string;
3643
+ interface ErrorContext {
3603
3644
  /**
3604
- * Logger instance
3645
+ * Error code for categorization
3605
3646
  */
3606
- logger?: Logger;
3647
+ code?: string;
3607
3648
  /**
3608
- * Enable metrics tracking
3609
- * @default true
3649
+ * Node name where the error occurred
3610
3650
  */
3611
- enableMetrics?: boolean;
3651
+ node?: string;
3612
3652
  /**
3613
- * Enable tracing
3614
- * @default true
3653
+ * Current state when the error occurred
3615
3654
  */
3616
- enableTracing?: boolean;
3655
+ state?: any;
3617
3656
  /**
3618
- * Enable retry logic
3619
- * @default true
3657
+ * Additional metadata
3620
3658
  */
3621
- enableRetry?: boolean;
3659
+ metadata?: Record<string, any>;
3622
3660
  /**
3623
- * Timeout in milliseconds
3624
- * @default 30000 (30 seconds)
3661
+ * Original error that caused this error
3625
3662
  */
3626
- timeout?: number;
3663
+ cause?: Error;
3664
+ }
3665
+ /**
3666
+ * Enhanced error class for agent errors
3667
+ */
3668
+ declare class AgentError extends Error {
3669
+ readonly code?: string;
3670
+ readonly node?: string;
3671
+ readonly state?: any;
3672
+ readonly metadata?: Record<string, any>;
3673
+ readonly cause?: Error;
3674
+ readonly timestamp: number;
3675
+ constructor(message: string, context?: ErrorContext);
3627
3676
  /**
3628
- * Custom retry options
3677
+ * Convert error to JSON for logging/reporting
3629
3678
  */
3630
- retryOptions?: Partial<RetryOptions>;
3679
+ toJSON(): Record<string, any>;
3631
3680
  /**
3632
- * Custom error handler options
3681
+ * Get a human-readable string representation
3633
3682
  */
3634
- errorOptions?: Partial<ErrorHandlerOptions<State>>;
3683
+ toString(): string;
3635
3684
  }
3636
3685
  /**
3637
- * Production preset with comprehensive error handling, metrics, and tracing.
3638
- *
3639
- * Includes:
3640
- * - Error handling with fallback
3641
- * - Retry logic with exponential backoff
3642
- * - Timeout protection
3643
- * - Metrics tracking
3644
- * - Distributed tracing
3645
- *
3646
- * @example
3647
- * ```typescript
3648
- * const productionNode = presets.production(myNode, {
3649
- * nodeName: 'my-node',
3650
- * logger: createLogger({ level: LogLevel.INFO }),
3651
- * });
3652
- * ```
3653
- */
3654
- declare function production<State>(node: NodeFunction<State>, options: ProductionPresetOptions<State>): NodeFunction<State>;
3655
- /**
3656
- * Options for the development preset.
3686
+ * Error reporter configuration
3657
3687
  */
3658
- interface DevelopmentPresetOptions {
3688
+ interface ErrorReporterOptions {
3659
3689
  /**
3660
- * Name of the node
3690
+ * Callback function to handle errors
3661
3691
  */
3662
- nodeName: string;
3692
+ onError: (error: AgentError) => void | Promise<void>;
3663
3693
  /**
3664
- * Enable verbose logging
3694
+ * Whether to include stack traces
3665
3695
  * @default true
3666
3696
  */
3667
- verbose?: boolean;
3697
+ includeStackTrace?: boolean;
3668
3698
  /**
3669
- * Logger instance
3699
+ * Whether to include state in error context
3700
+ * @default false (for security/privacy)
3670
3701
  */
3671
- logger?: Logger;
3702
+ includeState?: boolean;
3703
+ /**
3704
+ * Whether to rethrow errors after reporting
3705
+ * @default true
3706
+ */
3707
+ rethrow?: boolean;
3672
3708
  }
3673
3709
  /**
3674
- * Development preset with verbose logging and debugging.
3675
- *
3676
- * Includes:
3677
- * - Verbose logging
3678
- * - Error details
3679
- * - No retry (fail fast)
3680
- * - Extended timeout
3681
- *
3682
- * @example
3683
- * ```typescript
3684
- * const devNode = presets.development(myNode, {
3685
- * nodeName: 'my-node',
3686
- * verbose: true,
3687
- * });
3688
- * ```
3689
- */
3690
- declare function development<State>(node: NodeFunction<State>, options: DevelopmentPresetOptions): NodeFunction<State>;
3691
- /**
3692
- * Options for the testing preset.
3710
+ * Error reporter for tracking and reporting errors
3693
3711
  */
3694
- interface TestingPresetOptions<State> {
3695
- /**
3696
- * Name of the node
3697
- */
3698
- nodeName: string;
3699
- /**
3700
- * Mock responses for testing
3701
- */
3702
- mockResponse?: Partial<State>;
3703
- /**
3704
- * Simulate errors for testing
3705
- */
3706
- simulateError?: Error;
3712
+ interface ErrorReporter {
3707
3713
  /**
3708
- * Delay in milliseconds for testing async behavior
3714
+ * Wrap a node function with error reporting
3709
3715
  */
3710
- delay?: number;
3716
+ wrap<State>(node: (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>, nodeName?: string): (state: State) => Promise<State | Partial<State>>;
3711
3717
  /**
3712
- * Track invocations for assertions
3718
+ * Report an error manually
3713
3719
  */
3714
- trackInvocations?: boolean;
3720
+ report(error: Error, context?: ErrorContext): Promise<void>;
3715
3721
  }
3716
3722
  /**
3717
- * Testing preset for unit and integration tests.
3718
- *
3719
- * Includes:
3720
- * - Mock responses
3721
- * - Error simulation
3722
- * - Invocation tracking
3723
- * - Configurable delays
3723
+ * Create an error reporter.
3724
3724
  *
3725
3725
  * @example
3726
3726
  * ```typescript
3727
- * const testNode = presets.testing(myNode, {
3728
- * nodeName: 'my-node',
3729
- * mockResponse: { result: 'mocked' },
3730
- * trackInvocations: true,
3727
+ * import { createErrorReporter } from '@agentforge/core';
3728
+ *
3729
+ * const reporter = createErrorReporter({
3730
+ * onError: (error) => {
3731
+ * console.error('Agent error:', error.toJSON());
3732
+ * // Send to error tracking service
3733
+ * },
3734
+ * includeStackTrace: true,
3735
+ * includeState: false,
3731
3736
  * });
3737
+ *
3738
+ * const safeNode = reporter.wrap(myNode, 'my-node');
3732
3739
  * ```
3740
+ *
3741
+ * @param options - Error reporter configuration
3742
+ * @returns An error reporter instance
3733
3743
  */
3734
- declare function testing<State>(node: NodeFunction<State>, options: TestingPresetOptions<State>): NodeFunction<State> & {
3735
- invocations: State[];
3736
- };
3737
- /**
3738
- * Preset collection for easy access.
3739
- */
3740
- declare const presets: {
3741
- production: typeof production;
3742
- development: typeof development;
3743
- testing: typeof testing;
3744
- };
3744
+ declare function createErrorReporter(options: ErrorReporterOptions): ErrorReporter;
3745
3745
 
3746
3746
  /**
3747
3747
  * Types for LangGraph interrupt handling