@agentforge/core 0.16.69 → 0.16.71

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.cjs CHANGED
@@ -143,6 +143,7 @@ __export(index_exports, {
143
143
  reduce: () => reduce,
144
144
  renderTemplate: () => renderTemplate,
145
145
  retry: () => retry,
146
+ runMockExecution: () => runMockExecution,
146
147
  safeValidateSchemaDescriptions: () => safeValidateSchemaDescriptions,
147
148
  sanitizeValue: () => sanitizeValue,
148
149
  sendMessage: () => sendMessage,
@@ -1947,6 +1948,36 @@ function cache(tool, ttl) {
1947
1948
  };
1948
1949
  }
1949
1950
 
1951
+ // src/tools/testing-runtime.ts
1952
+ function resolveLatency(latency) {
1953
+ if (typeof latency === "function") {
1954
+ return latency();
1955
+ }
1956
+ if (typeof latency === "number") {
1957
+ return latency;
1958
+ }
1959
+ if (latency) {
1960
+ return Math.random() * (latency.max - latency.min) + latency.min;
1961
+ }
1962
+ return 0;
1963
+ }
1964
+ function shouldThrowMockError(shouldError, input) {
1965
+ if (typeof shouldError === "function") {
1966
+ return shouldError(input);
1967
+ }
1968
+ return shouldError ?? false;
1969
+ }
1970
+ async function runMockExecution(input, execute, options = {}) {
1971
+ const delay = resolveLatency(options.latency);
1972
+ if (delay > 0) {
1973
+ await new Promise((resolve) => setTimeout(resolve, delay));
1974
+ }
1975
+ if (shouldThrowMockError(options.shouldError, input)) {
1976
+ throw options.errorFactory?.(input) ?? new Error("Mock tool error");
1977
+ }
1978
+ return Promise.resolve(execute());
1979
+ }
1980
+
1950
1981
  // src/tools/testing.ts
1951
1982
  function matchesMockInput(matcher, input) {
1952
1983
  if (typeof matcher === "function") {
@@ -1969,56 +2000,47 @@ function createMockTool(config) {
1969
2000
  description,
1970
2001
  invoke: async (input) => {
1971
2002
  const startTime = Date.now();
1972
- if (latency) {
1973
- const delay = typeof latency === "number" ? latency : Math.random() * (latency.max - latency.min) + latency.min;
1974
- await new Promise((resolve) => setTimeout(resolve, delay));
1975
- }
1976
- if (errorRate > 0 && Math.random() < errorRate) {
1977
- const error2 = new Error(`Random error from ${name}`);
1978
- invocations.push({
2003
+ try {
2004
+ const result = await runMockExecution(
1979
2005
  input,
1980
- error: error2,
1981
- timestamp: startTime,
1982
- duration: Date.now() - startTime
1983
- });
1984
- throw error2;
1985
- }
1986
- const matchingResponse = responses.find((response) => matchesMockInput(response.input, input));
1987
- if (matchingResponse) {
1988
- if (matchingResponse.error) {
1989
- invocations.push({
1990
- input,
1991
- error: matchingResponse.error,
1992
- timestamp: startTime,
1993
- duration: Date.now() - startTime
1994
- });
1995
- throw matchingResponse.error;
1996
- }
2006
+ () => {
2007
+ const matchingResponse = responses.find(
2008
+ (response) => matchesMockInput(response.input, input)
2009
+ );
2010
+ if (matchingResponse) {
2011
+ if (matchingResponse.error) {
2012
+ throw matchingResponse.error;
2013
+ }
2014
+ return matchingResponse.output;
2015
+ }
2016
+ if (defaultResponse !== void 0) {
2017
+ return defaultResponse;
2018
+ }
2019
+ throw new Error(`No mock response configured for input: ${JSON.stringify(input)}`);
2020
+ },
2021
+ {
2022
+ latency,
2023
+ shouldError: errorRate > 0 ? () => Math.random() < errorRate : false,
2024
+ errorFactory: () => new Error(`Random error from ${name}`)
2025
+ }
2026
+ );
1997
2027
  invocations.push({
1998
2028
  input,
1999
- output: matchingResponse.output,
2029
+ output: result,
2000
2030
  timestamp: startTime,
2001
2031
  duration: Date.now() - startTime
2002
2032
  });
2003
- return matchingResponse.output;
2004
- }
2005
- if (defaultResponse !== void 0) {
2033
+ return result;
2034
+ } catch (error) {
2035
+ const recordedError = error instanceof Error ? error : new Error(String(error));
2006
2036
  invocations.push({
2007
2037
  input,
2008
- output: defaultResponse,
2038
+ error: recordedError,
2009
2039
  timestamp: startTime,
2010
2040
  duration: Date.now() - startTime
2011
2041
  });
2012
- return defaultResponse;
2042
+ throw recordedError;
2013
2043
  }
2014
- const error = new Error(`No mock response configured for input: ${JSON.stringify(input)}`);
2015
- invocations.push({
2016
- input,
2017
- error,
2018
- timestamp: startTime,
2019
- duration: Date.now() - startTime
2020
- });
2021
- throw error;
2022
2044
  },
2023
2045
  getInvocations: () => [...invocations],
2024
2046
  clearInvocations: () => {
@@ -2047,24 +2069,12 @@ function createToolSimulator(config) {
2047
2069
  throw new Error(`Tool ${toolName} not found in simulator`);
2048
2070
  }
2049
2071
  const startTime = Date.now();
2050
- if (latency) {
2051
- const delay = generateLatency();
2052
- await new Promise((resolve) => setTimeout(resolve, delay));
2053
- }
2054
- if (errorRate > 0 && Math.random() < errorRate) {
2055
- const error = new Error(`Simulated error from ${toolName}`);
2056
- if (recordInvocations) {
2057
- invocations.get(toolName).push({
2058
- input,
2059
- error,
2060
- timestamp: startTime,
2061
- duration: Date.now() - startTime
2062
- });
2063
- }
2064
- throw error;
2065
- }
2066
2072
  try {
2067
- const result = await tool.invoke(input);
2073
+ const result = await runMockExecution(input, () => tool.invoke(input), {
2074
+ latency: latency ? generateLatency : void 0,
2075
+ shouldError: errorRate > 0 ? () => Math.random() < errorRate : false,
2076
+ errorFactory: () => new Error(`Simulated error from ${toolName}`)
2077
+ });
2068
2078
  if (recordInvocations) {
2069
2079
  invocations.get(toolName).push({
2070
2080
  input,
@@ -2075,15 +2085,16 @@ function createToolSimulator(config) {
2075
2085
  }
2076
2086
  return result;
2077
2087
  } catch (error) {
2088
+ const recordedError = error instanceof Error ? error : new Error(String(error));
2078
2089
  if (recordInvocations) {
2079
2090
  invocations.get(toolName).push({
2080
2091
  input,
2081
- error,
2092
+ error: recordedError,
2082
2093
  timestamp: startTime,
2083
2094
  duration: Date.now() - startTime
2084
2095
  });
2085
2096
  }
2086
- throw error;
2097
+ throw recordedError;
2087
2098
  }
2088
2099
  },
2089
2100
  getInvocations: (toolName) => {
@@ -5856,6 +5867,7 @@ function loadPrompt(promptName, options = {}, promptsDir) {
5856
5867
  reduce,
5857
5868
  renderTemplate,
5858
5869
  retry,
5870
+ runMockExecution,
5859
5871
  safeValidateSchemaDescriptions,
5860
5872
  sanitizeValue,
5861
5873
  sendMessage,
package/dist/index.d.cts CHANGED
@@ -985,6 +985,16 @@ declare function createToolSimulator<const TTools extends readonly SimulatedTool
985
985
  clearInvocations: (toolName?: ToolName<TTools>) => void;
986
986
  };
987
987
 
988
+ interface MockExecutionRuntimeOptions<TInput> {
989
+ latency?: number | {
990
+ min: number;
991
+ max: number;
992
+ } | (() => number);
993
+ shouldError?: boolean | ((input: TInput) => boolean);
994
+ errorFactory?: (input: TInput) => Error;
995
+ }
996
+ declare function runMockExecution<TInput, TOutput>(input: TInput, execute: () => Promise<TOutput> | TOutput, options?: MockExecutionRuntimeOptions<TInput>): Promise<TOutput>;
997
+
988
998
  /**
989
999
  * LangChain Integration - Tool Converter
990
1000
  *
@@ -4690,4 +4700,4 @@ declare function renderTemplate(template: string, options: RenderTemplateOptions
4690
4700
  */
4691
4701
  declare function loadPrompt(promptName: string, options?: RenderTemplateOptions | PromptVariableMap, promptsDir?: string): string;
4692
4702
 
4693
- 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 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, 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 };
4703
+ 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 };
package/dist/index.d.ts CHANGED
@@ -985,6 +985,16 @@ declare function createToolSimulator<const TTools extends readonly SimulatedTool
985
985
  clearInvocations: (toolName?: ToolName<TTools>) => void;
986
986
  };
987
987
 
988
+ interface MockExecutionRuntimeOptions<TInput> {
989
+ latency?: number | {
990
+ min: number;
991
+ max: number;
992
+ } | (() => number);
993
+ shouldError?: boolean | ((input: TInput) => boolean);
994
+ errorFactory?: (input: TInput) => Error;
995
+ }
996
+ declare function runMockExecution<TInput, TOutput>(input: TInput, execute: () => Promise<TOutput> | TOutput, options?: MockExecutionRuntimeOptions<TInput>): Promise<TOutput>;
997
+
988
998
  /**
989
999
  * LangChain Integration - Tool Converter
990
1000
  *
@@ -4690,4 +4700,4 @@ declare function renderTemplate(template: string, options: RenderTemplateOptions
4690
4700
  */
4691
4701
  declare function loadPrompt(promptName: string, options?: RenderTemplateOptions | PromptVariableMap, promptsDir?: string): string;
4692
4702
 
4693
- 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 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, 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 };
4703
+ 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 };
package/dist/index.js CHANGED
@@ -1772,6 +1772,36 @@ function cache(tool, ttl) {
1772
1772
  };
1773
1773
  }
1774
1774
 
1775
+ // src/tools/testing-runtime.ts
1776
+ function resolveLatency(latency) {
1777
+ if (typeof latency === "function") {
1778
+ return latency();
1779
+ }
1780
+ if (typeof latency === "number") {
1781
+ return latency;
1782
+ }
1783
+ if (latency) {
1784
+ return Math.random() * (latency.max - latency.min) + latency.min;
1785
+ }
1786
+ return 0;
1787
+ }
1788
+ function shouldThrowMockError(shouldError, input) {
1789
+ if (typeof shouldError === "function") {
1790
+ return shouldError(input);
1791
+ }
1792
+ return shouldError ?? false;
1793
+ }
1794
+ async function runMockExecution(input, execute, options = {}) {
1795
+ const delay = resolveLatency(options.latency);
1796
+ if (delay > 0) {
1797
+ await new Promise((resolve) => setTimeout(resolve, delay));
1798
+ }
1799
+ if (shouldThrowMockError(options.shouldError, input)) {
1800
+ throw options.errorFactory?.(input) ?? new Error("Mock tool error");
1801
+ }
1802
+ return Promise.resolve(execute());
1803
+ }
1804
+
1775
1805
  // src/tools/testing.ts
1776
1806
  function matchesMockInput(matcher, input) {
1777
1807
  if (typeof matcher === "function") {
@@ -1794,56 +1824,47 @@ function createMockTool(config) {
1794
1824
  description,
1795
1825
  invoke: async (input) => {
1796
1826
  const startTime = Date.now();
1797
- if (latency) {
1798
- const delay = typeof latency === "number" ? latency : Math.random() * (latency.max - latency.min) + latency.min;
1799
- await new Promise((resolve) => setTimeout(resolve, delay));
1800
- }
1801
- if (errorRate > 0 && Math.random() < errorRate) {
1802
- const error2 = new Error(`Random error from ${name}`);
1803
- invocations.push({
1827
+ try {
1828
+ const result = await runMockExecution(
1804
1829
  input,
1805
- error: error2,
1806
- timestamp: startTime,
1807
- duration: Date.now() - startTime
1808
- });
1809
- throw error2;
1810
- }
1811
- const matchingResponse = responses.find((response) => matchesMockInput(response.input, input));
1812
- if (matchingResponse) {
1813
- if (matchingResponse.error) {
1814
- invocations.push({
1815
- input,
1816
- error: matchingResponse.error,
1817
- timestamp: startTime,
1818
- duration: Date.now() - startTime
1819
- });
1820
- throw matchingResponse.error;
1821
- }
1830
+ () => {
1831
+ const matchingResponse = responses.find(
1832
+ (response) => matchesMockInput(response.input, input)
1833
+ );
1834
+ if (matchingResponse) {
1835
+ if (matchingResponse.error) {
1836
+ throw matchingResponse.error;
1837
+ }
1838
+ return matchingResponse.output;
1839
+ }
1840
+ if (defaultResponse !== void 0) {
1841
+ return defaultResponse;
1842
+ }
1843
+ throw new Error(`No mock response configured for input: ${JSON.stringify(input)}`);
1844
+ },
1845
+ {
1846
+ latency,
1847
+ shouldError: errorRate > 0 ? () => Math.random() < errorRate : false,
1848
+ errorFactory: () => new Error(`Random error from ${name}`)
1849
+ }
1850
+ );
1822
1851
  invocations.push({
1823
1852
  input,
1824
- output: matchingResponse.output,
1853
+ output: result,
1825
1854
  timestamp: startTime,
1826
1855
  duration: Date.now() - startTime
1827
1856
  });
1828
- return matchingResponse.output;
1829
- }
1830
- if (defaultResponse !== void 0) {
1857
+ return result;
1858
+ } catch (error) {
1859
+ const recordedError = error instanceof Error ? error : new Error(String(error));
1831
1860
  invocations.push({
1832
1861
  input,
1833
- output: defaultResponse,
1862
+ error: recordedError,
1834
1863
  timestamp: startTime,
1835
1864
  duration: Date.now() - startTime
1836
1865
  });
1837
- return defaultResponse;
1866
+ throw recordedError;
1838
1867
  }
1839
- const error = new Error(`No mock response configured for input: ${JSON.stringify(input)}`);
1840
- invocations.push({
1841
- input,
1842
- error,
1843
- timestamp: startTime,
1844
- duration: Date.now() - startTime
1845
- });
1846
- throw error;
1847
1868
  },
1848
1869
  getInvocations: () => [...invocations],
1849
1870
  clearInvocations: () => {
@@ -1872,24 +1893,12 @@ function createToolSimulator(config) {
1872
1893
  throw new Error(`Tool ${toolName} not found in simulator`);
1873
1894
  }
1874
1895
  const startTime = Date.now();
1875
- if (latency) {
1876
- const delay = generateLatency();
1877
- await new Promise((resolve) => setTimeout(resolve, delay));
1878
- }
1879
- if (errorRate > 0 && Math.random() < errorRate) {
1880
- const error = new Error(`Simulated error from ${toolName}`);
1881
- if (recordInvocations) {
1882
- invocations.get(toolName).push({
1883
- input,
1884
- error,
1885
- timestamp: startTime,
1886
- duration: Date.now() - startTime
1887
- });
1888
- }
1889
- throw error;
1890
- }
1891
1896
  try {
1892
- const result = await tool.invoke(input);
1897
+ const result = await runMockExecution(input, () => tool.invoke(input), {
1898
+ latency: latency ? generateLatency : void 0,
1899
+ shouldError: errorRate > 0 ? () => Math.random() < errorRate : false,
1900
+ errorFactory: () => new Error(`Simulated error from ${toolName}`)
1901
+ });
1893
1902
  if (recordInvocations) {
1894
1903
  invocations.get(toolName).push({
1895
1904
  input,
@@ -1900,15 +1909,16 @@ function createToolSimulator(config) {
1900
1909
  }
1901
1910
  return result;
1902
1911
  } catch (error) {
1912
+ const recordedError = error instanceof Error ? error : new Error(String(error));
1903
1913
  if (recordInvocations) {
1904
1914
  invocations.get(toolName).push({
1905
1915
  input,
1906
- error,
1916
+ error: recordedError,
1907
1917
  timestamp: startTime,
1908
1918
  duration: Date.now() - startTime
1909
1919
  });
1910
1920
  }
1911
- throw error;
1921
+ throw recordedError;
1912
1922
  }
1913
1923
  },
1914
1924
  getInvocations: (toolName) => {
@@ -5680,6 +5690,7 @@ export {
5680
5690
  reduce,
5681
5691
  renderTemplate,
5682
5692
  retry,
5693
+ runMockExecution,
5683
5694
  safeValidateSchemaDescriptions,
5684
5695
  sanitizeValue,
5685
5696
  sendMessage,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentforge/core",
3
- "version": "0.16.69",
3
+ "version": "0.16.71",
4
4
  "description": "Production-ready TypeScript agent framework built on LangGraph with orchestration, middleware, and typed abstractions.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",