@agentforge/core 0.15.8 → 0.15.9

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
@@ -946,7 +946,7 @@ var LoggerImpl = class _LoggerImpl {
946
946
  if (this.options.includeContext && Object.keys(this.context).length > 0) {
947
947
  entry.context = this.context;
948
948
  }
949
- if (data) {
949
+ if (data !== void 0) {
950
950
  entry.data = data;
951
951
  }
952
952
  const output = this.format(entry);
@@ -966,7 +966,7 @@ var LoggerImpl = class _LoggerImpl {
966
966
  if (entry.context) {
967
967
  parts.push(`context=${JSON.stringify(entry.context)}`);
968
968
  }
969
- if (entry.data) {
969
+ if (entry.data !== void 0) {
970
970
  parts.push(`data=${JSON.stringify(entry.data)}`);
971
971
  }
972
972
  return parts.join(" ");
@@ -1299,7 +1299,7 @@ var ToolRegistry = class {
1299
1299
  logger.error("Event handler error", {
1300
1300
  event,
1301
1301
  error: error instanceof Error ? error.message : String(error),
1302
- stack: error instanceof Error ? error.stack : void 0
1302
+ ...error instanceof Error && error.stack ? { stack: error.stack } : {}
1303
1303
  });
1304
1304
  }
1305
1305
  });
@@ -1766,7 +1766,7 @@ var ManagedTool = class {
1766
1766
  (err) => logger3.error("Cleanup failed", {
1767
1767
  toolName: this.name,
1768
1768
  error: err instanceof Error ? err.message : String(err),
1769
- stack: err instanceof Error ? err.stack : void 0
1769
+ ...err instanceof Error && err.stack ? { stack: err.stack } : {}
1770
1770
  })
1771
1771
  );
1772
1772
  });
@@ -2826,7 +2826,7 @@ var withLogging = (options) => {
2826
2826
  if (logErrors) {
2827
2827
  logger5.error(`Node execution failed (${duration}ms)`, {
2828
2828
  error: err.message,
2829
- stack: err.stack
2829
+ ...err.stack ? { stack: err.stack } : {}
2830
2830
  });
2831
2831
  }
2832
2832
  if (onError) {
@@ -5274,6 +5274,40 @@ function createProfiler(options) {
5274
5274
 
5275
5275
  // src/monitoring/alerts.ts
5276
5276
  var logger4 = createLogger("agentforge:core:monitoring:alerts", { level: "info" /* INFO */ });
5277
+ function toAlertSummary(alert) {
5278
+ return {
5279
+ name: alert.name,
5280
+ severity: alert.severity,
5281
+ message: alert.message
5282
+ };
5283
+ }
5284
+ function toRuleErrorPayload(ruleName, error) {
5285
+ return {
5286
+ ruleName,
5287
+ error: error instanceof Error ? error.message : String(error),
5288
+ ...error instanceof Error && error.stack ? { stack: error.stack } : {}
5289
+ };
5290
+ }
5291
+ function toAlertDispatchErrorPayload(ruleName, error) {
5292
+ return {
5293
+ stage: "alert-dispatch",
5294
+ ...toRuleErrorPayload(ruleName, error)
5295
+ };
5296
+ }
5297
+ function toAlertCallbackErrorPayload(error) {
5298
+ return {
5299
+ stage: "alert-callback",
5300
+ error: error instanceof Error ? error.message : String(error),
5301
+ ...error instanceof Error && error.stack ? { stack: error.stack } : {}
5302
+ };
5303
+ }
5304
+ function toMetricsProviderErrorPayload(error) {
5305
+ return {
5306
+ stage: "metrics-provider",
5307
+ error: error instanceof Error ? error.message : String(error),
5308
+ ...error instanceof Error && error.stack ? { stack: error.stack } : {}
5309
+ };
5310
+ }
5277
5311
  var AlertManager = class {
5278
5312
  constructor(options) {
5279
5313
  this.options = options;
@@ -5287,8 +5321,12 @@ var AlertManager = class {
5287
5321
  }
5288
5322
  this.running = true;
5289
5323
  this.monitorTimer = setInterval(() => {
5290
- const currentMetrics = metrics();
5291
- this.checkRules(currentMetrics);
5324
+ try {
5325
+ const currentMetrics = metrics();
5326
+ this.checkRules(currentMetrics);
5327
+ } catch (error) {
5328
+ logger4.error("Metrics collection failed", toMetricsProviderErrorPayload(error));
5329
+ }
5292
5330
  }, interval);
5293
5331
  }
5294
5332
  stop() {
@@ -5304,18 +5342,22 @@ var AlertManager = class {
5304
5342
  async alert(alert) {
5305
5343
  const fullAlert = {
5306
5344
  ...alert,
5307
- timestamp: alert.timestamp || Date.now()
5345
+ timestamp: alert.timestamp ?? Date.now()
5308
5346
  };
5309
5347
  if (this.isThrottled(alert.name)) {
5310
5348
  return;
5311
5349
  }
5312
5350
  this.lastAlertTime.set(alert.name, Date.now());
5313
- this.options.onAlert?.(fullAlert);
5351
+ try {
5352
+ await this.options.onAlert?.(fullAlert);
5353
+ } catch (error) {
5354
+ logger4.error("Alert callback failed", toAlertCallbackErrorPayload(error));
5355
+ }
5314
5356
  logger4.warn("Alert triggered", {
5315
5357
  name: alert.name,
5316
5358
  severity: alert.severity,
5317
5359
  message: alert.message,
5318
- data: alert.data
5360
+ ...alert.data ? { data: alert.data } : {}
5319
5361
  });
5320
5362
  }
5321
5363
  checkRules(metrics) {
@@ -5325,19 +5367,17 @@ var AlertManager = class {
5325
5367
  for (const rule of this.options.rules) {
5326
5368
  try {
5327
5369
  if (rule.condition(metrics)) {
5328
- this.alert({
5370
+ void this.alert({
5329
5371
  name: rule.name,
5330
5372
  severity: rule.severity,
5331
5373
  message: rule.message || `Alert triggered: ${rule.name}`,
5332
5374
  data: { metrics }
5375
+ }).catch((error) => {
5376
+ logger4.error("Alert dispatch failed", toAlertDispatchErrorPayload(rule.name, error));
5333
5377
  });
5334
5378
  }
5335
5379
  } catch (error) {
5336
- logger4.error("Rule check failed", {
5337
- ruleName: rule.name,
5338
- error: error instanceof Error ? error.message : String(error),
5339
- stack: error instanceof Error ? error.stack : void 0
5340
- });
5380
+ logger4.error("Rule check failed", toRuleErrorPayload(rule.name, error));
5341
5381
  }
5342
5382
  }
5343
5383
  }
@@ -5362,32 +5402,32 @@ var AlertManager = class {
5362
5402
  logger4.info("Alert sent to email", {
5363
5403
  channel: channelName,
5364
5404
  to: channel.config.to,
5365
- alert: { name: alert.name, severity: alert.severity, message: alert.message }
5405
+ alert: toAlertSummary(alert)
5366
5406
  });
5367
5407
  break;
5368
5408
  case "slack":
5369
5409
  logger4.info("Alert sent to Slack", {
5370
5410
  channel: channelName,
5371
5411
  webhookUrl: channel.config.webhookUrl,
5372
- alert: { name: alert.name, severity: alert.severity, message: alert.message }
5412
+ alert: toAlertSummary(alert)
5373
5413
  });
5374
5414
  break;
5375
5415
  case "webhook":
5376
5416
  logger4.info("Alert sent to webhook", {
5377
5417
  channel: channelName,
5378
5418
  url: channel.config.url,
5379
- alert: { name: alert.name, severity: alert.severity, message: alert.message }
5419
+ alert: toAlertSummary(alert)
5380
5420
  });
5381
5421
  break;
5382
5422
  default:
5383
5423
  logger4.info("Alert sent", {
5384
5424
  channel: channelName,
5385
5425
  channelType: channel.type,
5386
- alert: { name: alert.name, severity: alert.severity, message: alert.message }
5426
+ alert: toAlertSummary(alert)
5387
5427
  });
5388
5428
  }
5389
5429
  }
5390
- getAlertHistory(name, limit = 100) {
5430
+ getAlertHistory(_name, _limit = 100) {
5391
5431
  return [];
5392
5432
  }
5393
5433
  clearAlertHistory(name) {
package/dist/index.d.cts CHANGED
@@ -2816,11 +2816,21 @@ interface ErrorHandlerOptions<State> {
2816
2816
  */
2817
2817
  declare function withErrorHandler<State>(node: (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>, options: ErrorHandlerOptions<State>): (state: State) => Promise<State | Partial<State>>;
2818
2818
 
2819
+ /**
2820
+ * Shared JSON-safe payload contracts for observability and monitoring paths.
2821
+ */
2822
+ type JsonPrimitive = string | number | boolean | null;
2823
+ type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
2824
+ interface JsonObject {
2825
+ [key: string]: JsonValue;
2826
+ }
2827
+
2819
2828
  /**
2820
2829
  * Structured Logging Utilities
2821
2830
  *
2822
2831
  * Provides consistent, structured logging for LangGraph agents.
2823
2832
  */
2833
+
2824
2834
  /**
2825
2835
  * Log levels
2826
2836
  */
@@ -2868,8 +2878,8 @@ interface LogEntry {
2868
2878
  name: string;
2869
2879
  message: string;
2870
2880
  timestamp?: string;
2871
- context?: Record<string, any>;
2872
- data?: Record<string, any>;
2881
+ context?: JsonObject;
2882
+ data?: JsonValue;
2873
2883
  }
2874
2884
  /**
2875
2885
  * Logger interface
@@ -2878,19 +2888,19 @@ interface Logger {
2878
2888
  /**
2879
2889
  * Log a debug message
2880
2890
  */
2881
- debug(message: string, data?: Record<string, any>): void;
2891
+ debug(message: string, data?: JsonValue): void;
2882
2892
  /**
2883
2893
  * Log an info message
2884
2894
  */
2885
- info(message: string, data?: Record<string, any>): void;
2895
+ info(message: string, data?: JsonValue): void;
2886
2896
  /**
2887
2897
  * Log a warning message
2888
2898
  */
2889
- warn(message: string, data?: Record<string, any>): void;
2899
+ warn(message: string, data?: JsonValue): void;
2890
2900
  /**
2891
2901
  * Log an error message
2892
2902
  */
2893
- error(message: string, data?: Record<string, any>): void;
2903
+ error(message: string, data?: JsonValue): void;
2894
2904
  /**
2895
2905
  * Check if debug logging is enabled
2896
2906
  * Useful for avoiding expensive computations when debug is disabled
@@ -2903,7 +2913,7 @@ interface Logger {
2903
2913
  /**
2904
2914
  * Create a child logger with additional context
2905
2915
  */
2906
- withContext(context: Record<string, any>): Logger;
2916
+ withContext(context: JsonObject): Logger;
2907
2917
  }
2908
2918
  /**
2909
2919
  * Create a structured logger.
@@ -5334,47 +5344,80 @@ declare function createProfiler(options?: ProfilerOptions): Profiler;
5334
5344
  /**
5335
5345
  * Alert system for production monitoring
5336
5346
  */
5347
+
5337
5348
  type AlertSeverity = 'info' | 'warning' | 'error' | 'critical';
5338
- interface Alert {
5349
+ interface Alert<TData extends JsonObject = JsonObject> {
5339
5350
  name: string;
5340
5351
  severity: AlertSeverity;
5341
5352
  message: string;
5342
5353
  timestamp?: number;
5343
- data?: Record<string, any>;
5344
- }
5345
- interface AlertChannel {
5346
- type: string;
5347
- config: Record<string, any>;
5354
+ data?: TData;
5348
5355
  }
5349
- interface AlertRule {
5356
+ type BuiltInAlertChannelType = 'email' | 'slack' | 'webhook';
5357
+ type EmailAlertChannelConfig = JsonObject & {
5358
+ to: string | string[];
5359
+ };
5360
+ type SlackAlertChannelConfig = JsonObject & {
5361
+ webhookUrl: string;
5362
+ };
5363
+ type WebhookAlertChannelConfig = JsonObject & {
5364
+ url: string;
5365
+ };
5366
+ interface EmailAlertChannel {
5367
+ type: 'email';
5368
+ config: EmailAlertChannelConfig;
5369
+ }
5370
+ interface SlackAlertChannel {
5371
+ type: 'slack';
5372
+ config: SlackAlertChannelConfig;
5373
+ }
5374
+ interface WebhookAlertChannel {
5375
+ type: 'webhook';
5376
+ config: WebhookAlertChannelConfig;
5377
+ }
5378
+ interface GenericAlertChannel<TType extends string = string, TConfig extends JsonObject = JsonObject> {
5379
+ type: TType;
5380
+ config: TConfig;
5381
+ }
5382
+ type CustomAlertChannel<TType extends string = string, TConfig extends JsonObject = JsonObject> = GenericAlertChannel<Exclude<TType, BuiltInAlertChannelType>, TConfig>;
5383
+ type AlertChannel<TType extends string = string, TConfig extends JsonObject = JsonObject> = TType extends 'email' ? EmailAlertChannel : TType extends 'slack' ? SlackAlertChannel : TType extends 'webhook' ? WebhookAlertChannel : GenericAlertChannel<TType, TConfig>;
5384
+ type AlertChannelMap = Record<string, GenericAlertChannel>;
5385
+ type ValidatedAlertChannels<TChannels extends AlertChannelMap> = {
5386
+ [TName in keyof TChannels]: TChannels[TName] extends GenericAlertChannel<infer TType, infer TConfig> ? AlertChannel<TType, TConfig> : never;
5387
+ };
5388
+ type AlertChannelName<TChannels extends AlertChannelMap> = keyof ValidatedAlertChannels<TChannels> & string;
5389
+ interface AlertRule<TMetrics extends JsonObject = JsonObject, TChannelName extends string = string> {
5350
5390
  name: string;
5351
- condition: (metrics: any) => boolean;
5391
+ condition: (metrics: TMetrics) => boolean;
5352
5392
  severity: AlertSeverity;
5353
- channels: string[];
5393
+ channels: TChannelName[];
5354
5394
  throttle?: number;
5355
5395
  message?: string;
5356
5396
  }
5357
- interface AlertManagerOptions {
5358
- channels: Record<string, AlertChannel>;
5359
- rules?: AlertRule[];
5360
- onAlert?: (alert: Alert) => void;
5397
+ type AlertCallbackData<TMetrics extends JsonObject> = JsonObject & {
5398
+ metrics?: TMetrics;
5399
+ };
5400
+ interface AlertManagerOptions<TMetrics extends JsonObject = JsonObject, TChannels extends AlertChannelMap = Record<string, GenericAlertChannel>> {
5401
+ channels: ValidatedAlertChannels<TChannels>;
5402
+ rules?: AlertRule<TMetrics, AlertChannelName<TChannels>>[];
5403
+ onAlert?: (alert: Alert<AlertCallbackData<TMetrics>>) => void | Promise<void>;
5361
5404
  }
5362
- declare class AlertManager {
5405
+ declare class AlertManager<TMetrics extends JsonObject = JsonObject, TChannels extends AlertChannelMap = Record<string, GenericAlertChannel>> {
5363
5406
  private options;
5364
5407
  private lastAlertTime;
5365
5408
  private monitorTimer?;
5366
5409
  private running;
5367
- constructor(options: AlertManagerOptions);
5368
- start(metrics?: () => any, interval?: number): void;
5410
+ constructor(options: AlertManagerOptions<TMetrics, TChannels>);
5411
+ start(metrics?: () => TMetrics, interval?: number): void;
5369
5412
  stop(): void;
5370
- alert(alert: Alert): Promise<void>;
5413
+ alert(alert: Alert<AlertCallbackData<TMetrics>>): Promise<void>;
5371
5414
  private checkRules;
5372
5415
  private isThrottled;
5373
- sendToChannel(channelName: string, alert: Alert): Promise<void>;
5374
- getAlertHistory(name?: string, limit?: number): Alert[];
5416
+ sendToChannel(channelName: keyof TChannels & string, alert: Alert<AlertCallbackData<TMetrics>>): Promise<void>;
5417
+ getAlertHistory(_name?: string, _limit?: number): Alert<AlertCallbackData<TMetrics>>[];
5375
5418
  clearAlertHistory(name?: string): void;
5376
5419
  }
5377
- declare function createAlertManager(options: AlertManagerOptions): AlertManager;
5420
+ declare function createAlertManager<TMetrics extends JsonObject = JsonObject, TChannels extends AlertChannelMap = Record<string, GenericAlertChannel>>(options: AlertManagerOptions<TMetrics, TChannels>): AlertManager<TMetrics, TChannels>;
5378
5421
 
5379
5422
  /**
5380
5423
  * Audit logging for compliance and tracking
@@ -5548,4 +5591,4 @@ declare function renderTemplate(template: string, options: RenderTemplateOptions
5548
5591
  */
5549
5592
  declare function loadPrompt(promptName: string, options?: RenderTemplateOptions | Record<string, any>, promptsDir?: string): string;
5550
5593
 
5551
- 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 CustomInterrupt, type DatabaseConfig, type DatabaseConnection, DatabasePool, type DatabasePoolOptions, type DevelopmentPresetOptions, type ErrorContext, type ErrorHandlerOptions, type ErrorReporter, type ErrorReporterOptions, type EventHandler, type EvictionStrategy, type ExecutionMetrics, 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 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 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 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 WebSocketHandlerOptions, type WebSocketMessage, 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 };
5594
+ 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 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 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 WebSocketHandlerOptions, type WebSocketMessage, 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 };
package/dist/index.d.ts CHANGED
@@ -2816,11 +2816,21 @@ interface ErrorHandlerOptions<State> {
2816
2816
  */
2817
2817
  declare function withErrorHandler<State>(node: (state: State) => State | Promise<State> | Partial<State> | Promise<Partial<State>>, options: ErrorHandlerOptions<State>): (state: State) => Promise<State | Partial<State>>;
2818
2818
 
2819
+ /**
2820
+ * Shared JSON-safe payload contracts for observability and monitoring paths.
2821
+ */
2822
+ type JsonPrimitive = string | number | boolean | null;
2823
+ type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
2824
+ interface JsonObject {
2825
+ [key: string]: JsonValue;
2826
+ }
2827
+
2819
2828
  /**
2820
2829
  * Structured Logging Utilities
2821
2830
  *
2822
2831
  * Provides consistent, structured logging for LangGraph agents.
2823
2832
  */
2833
+
2824
2834
  /**
2825
2835
  * Log levels
2826
2836
  */
@@ -2868,8 +2878,8 @@ interface LogEntry {
2868
2878
  name: string;
2869
2879
  message: string;
2870
2880
  timestamp?: string;
2871
- context?: Record<string, any>;
2872
- data?: Record<string, any>;
2881
+ context?: JsonObject;
2882
+ data?: JsonValue;
2873
2883
  }
2874
2884
  /**
2875
2885
  * Logger interface
@@ -2878,19 +2888,19 @@ interface Logger {
2878
2888
  /**
2879
2889
  * Log a debug message
2880
2890
  */
2881
- debug(message: string, data?: Record<string, any>): void;
2891
+ debug(message: string, data?: JsonValue): void;
2882
2892
  /**
2883
2893
  * Log an info message
2884
2894
  */
2885
- info(message: string, data?: Record<string, any>): void;
2895
+ info(message: string, data?: JsonValue): void;
2886
2896
  /**
2887
2897
  * Log a warning message
2888
2898
  */
2889
- warn(message: string, data?: Record<string, any>): void;
2899
+ warn(message: string, data?: JsonValue): void;
2890
2900
  /**
2891
2901
  * Log an error message
2892
2902
  */
2893
- error(message: string, data?: Record<string, any>): void;
2903
+ error(message: string, data?: JsonValue): void;
2894
2904
  /**
2895
2905
  * Check if debug logging is enabled
2896
2906
  * Useful for avoiding expensive computations when debug is disabled
@@ -2903,7 +2913,7 @@ interface Logger {
2903
2913
  /**
2904
2914
  * Create a child logger with additional context
2905
2915
  */
2906
- withContext(context: Record<string, any>): Logger;
2916
+ withContext(context: JsonObject): Logger;
2907
2917
  }
2908
2918
  /**
2909
2919
  * Create a structured logger.
@@ -5334,47 +5344,80 @@ declare function createProfiler(options?: ProfilerOptions): Profiler;
5334
5344
  /**
5335
5345
  * Alert system for production monitoring
5336
5346
  */
5347
+
5337
5348
  type AlertSeverity = 'info' | 'warning' | 'error' | 'critical';
5338
- interface Alert {
5349
+ interface Alert<TData extends JsonObject = JsonObject> {
5339
5350
  name: string;
5340
5351
  severity: AlertSeverity;
5341
5352
  message: string;
5342
5353
  timestamp?: number;
5343
- data?: Record<string, any>;
5344
- }
5345
- interface AlertChannel {
5346
- type: string;
5347
- config: Record<string, any>;
5354
+ data?: TData;
5348
5355
  }
5349
- interface AlertRule {
5356
+ type BuiltInAlertChannelType = 'email' | 'slack' | 'webhook';
5357
+ type EmailAlertChannelConfig = JsonObject & {
5358
+ to: string | string[];
5359
+ };
5360
+ type SlackAlertChannelConfig = JsonObject & {
5361
+ webhookUrl: string;
5362
+ };
5363
+ type WebhookAlertChannelConfig = JsonObject & {
5364
+ url: string;
5365
+ };
5366
+ interface EmailAlertChannel {
5367
+ type: 'email';
5368
+ config: EmailAlertChannelConfig;
5369
+ }
5370
+ interface SlackAlertChannel {
5371
+ type: 'slack';
5372
+ config: SlackAlertChannelConfig;
5373
+ }
5374
+ interface WebhookAlertChannel {
5375
+ type: 'webhook';
5376
+ config: WebhookAlertChannelConfig;
5377
+ }
5378
+ interface GenericAlertChannel<TType extends string = string, TConfig extends JsonObject = JsonObject> {
5379
+ type: TType;
5380
+ config: TConfig;
5381
+ }
5382
+ type CustomAlertChannel<TType extends string = string, TConfig extends JsonObject = JsonObject> = GenericAlertChannel<Exclude<TType, BuiltInAlertChannelType>, TConfig>;
5383
+ type AlertChannel<TType extends string = string, TConfig extends JsonObject = JsonObject> = TType extends 'email' ? EmailAlertChannel : TType extends 'slack' ? SlackAlertChannel : TType extends 'webhook' ? WebhookAlertChannel : GenericAlertChannel<TType, TConfig>;
5384
+ type AlertChannelMap = Record<string, GenericAlertChannel>;
5385
+ type ValidatedAlertChannels<TChannels extends AlertChannelMap> = {
5386
+ [TName in keyof TChannels]: TChannels[TName] extends GenericAlertChannel<infer TType, infer TConfig> ? AlertChannel<TType, TConfig> : never;
5387
+ };
5388
+ type AlertChannelName<TChannels extends AlertChannelMap> = keyof ValidatedAlertChannels<TChannels> & string;
5389
+ interface AlertRule<TMetrics extends JsonObject = JsonObject, TChannelName extends string = string> {
5350
5390
  name: string;
5351
- condition: (metrics: any) => boolean;
5391
+ condition: (metrics: TMetrics) => boolean;
5352
5392
  severity: AlertSeverity;
5353
- channels: string[];
5393
+ channels: TChannelName[];
5354
5394
  throttle?: number;
5355
5395
  message?: string;
5356
5396
  }
5357
- interface AlertManagerOptions {
5358
- channels: Record<string, AlertChannel>;
5359
- rules?: AlertRule[];
5360
- onAlert?: (alert: Alert) => void;
5397
+ type AlertCallbackData<TMetrics extends JsonObject> = JsonObject & {
5398
+ metrics?: TMetrics;
5399
+ };
5400
+ interface AlertManagerOptions<TMetrics extends JsonObject = JsonObject, TChannels extends AlertChannelMap = Record<string, GenericAlertChannel>> {
5401
+ channels: ValidatedAlertChannels<TChannels>;
5402
+ rules?: AlertRule<TMetrics, AlertChannelName<TChannels>>[];
5403
+ onAlert?: (alert: Alert<AlertCallbackData<TMetrics>>) => void | Promise<void>;
5361
5404
  }
5362
- declare class AlertManager {
5405
+ declare class AlertManager<TMetrics extends JsonObject = JsonObject, TChannels extends AlertChannelMap = Record<string, GenericAlertChannel>> {
5363
5406
  private options;
5364
5407
  private lastAlertTime;
5365
5408
  private monitorTimer?;
5366
5409
  private running;
5367
- constructor(options: AlertManagerOptions);
5368
- start(metrics?: () => any, interval?: number): void;
5410
+ constructor(options: AlertManagerOptions<TMetrics, TChannels>);
5411
+ start(metrics?: () => TMetrics, interval?: number): void;
5369
5412
  stop(): void;
5370
- alert(alert: Alert): Promise<void>;
5413
+ alert(alert: Alert<AlertCallbackData<TMetrics>>): Promise<void>;
5371
5414
  private checkRules;
5372
5415
  private isThrottled;
5373
- sendToChannel(channelName: string, alert: Alert): Promise<void>;
5374
- getAlertHistory(name?: string, limit?: number): Alert[];
5416
+ sendToChannel(channelName: keyof TChannels & string, alert: Alert<AlertCallbackData<TMetrics>>): Promise<void>;
5417
+ getAlertHistory(_name?: string, _limit?: number): Alert<AlertCallbackData<TMetrics>>[];
5375
5418
  clearAlertHistory(name?: string): void;
5376
5419
  }
5377
- declare function createAlertManager(options: AlertManagerOptions): AlertManager;
5420
+ declare function createAlertManager<TMetrics extends JsonObject = JsonObject, TChannels extends AlertChannelMap = Record<string, GenericAlertChannel>>(options: AlertManagerOptions<TMetrics, TChannels>): AlertManager<TMetrics, TChannels>;
5378
5421
 
5379
5422
  /**
5380
5423
  * Audit logging for compliance and tracking
@@ -5548,4 +5591,4 @@ declare function renderTemplate(template: string, options: RenderTemplateOptions
5548
5591
  */
5549
5592
  declare function loadPrompt(promptName: string, options?: RenderTemplateOptions | Record<string, any>, promptsDir?: string): string;
5550
5593
 
5551
- 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 CustomInterrupt, type DatabaseConfig, type DatabaseConnection, DatabasePool, type DatabasePoolOptions, type DevelopmentPresetOptions, type ErrorContext, type ErrorHandlerOptions, type ErrorReporter, type ErrorReporterOptions, type EventHandler, type EvictionStrategy, type ExecutionMetrics, 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 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 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 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 WebSocketHandlerOptions, type WebSocketMessage, 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 };
5594
+ 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 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 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 WebSocketHandlerOptions, type WebSocketMessage, 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 };
package/dist/index.js CHANGED
@@ -771,7 +771,7 @@ var LoggerImpl = class _LoggerImpl {
771
771
  if (this.options.includeContext && Object.keys(this.context).length > 0) {
772
772
  entry.context = this.context;
773
773
  }
774
- if (data) {
774
+ if (data !== void 0) {
775
775
  entry.data = data;
776
776
  }
777
777
  const output = this.format(entry);
@@ -791,7 +791,7 @@ var LoggerImpl = class _LoggerImpl {
791
791
  if (entry.context) {
792
792
  parts.push(`context=${JSON.stringify(entry.context)}`);
793
793
  }
794
- if (entry.data) {
794
+ if (entry.data !== void 0) {
795
795
  parts.push(`data=${JSON.stringify(entry.data)}`);
796
796
  }
797
797
  return parts.join(" ");
@@ -1124,7 +1124,7 @@ var ToolRegistry = class {
1124
1124
  logger.error("Event handler error", {
1125
1125
  event,
1126
1126
  error: error instanceof Error ? error.message : String(error),
1127
- stack: error instanceof Error ? error.stack : void 0
1127
+ ...error instanceof Error && error.stack ? { stack: error.stack } : {}
1128
1128
  });
1129
1129
  }
1130
1130
  });
@@ -1591,7 +1591,7 @@ var ManagedTool = class {
1591
1591
  (err) => logger3.error("Cleanup failed", {
1592
1592
  toolName: this.name,
1593
1593
  error: err instanceof Error ? err.message : String(err),
1594
- stack: err instanceof Error ? err.stack : void 0
1594
+ ...err instanceof Error && err.stack ? { stack: err.stack } : {}
1595
1595
  })
1596
1596
  );
1597
1597
  });
@@ -2651,7 +2651,7 @@ var withLogging = (options) => {
2651
2651
  if (logErrors) {
2652
2652
  logger5.error(`Node execution failed (${duration}ms)`, {
2653
2653
  error: err.message,
2654
- stack: err.stack
2654
+ ...err.stack ? { stack: err.stack } : {}
2655
2655
  });
2656
2656
  }
2657
2657
  if (onError) {
@@ -5099,6 +5099,40 @@ function createProfiler(options) {
5099
5099
 
5100
5100
  // src/monitoring/alerts.ts
5101
5101
  var logger4 = createLogger("agentforge:core:monitoring:alerts", { level: "info" /* INFO */ });
5102
+ function toAlertSummary(alert) {
5103
+ return {
5104
+ name: alert.name,
5105
+ severity: alert.severity,
5106
+ message: alert.message
5107
+ };
5108
+ }
5109
+ function toRuleErrorPayload(ruleName, error) {
5110
+ return {
5111
+ ruleName,
5112
+ error: error instanceof Error ? error.message : String(error),
5113
+ ...error instanceof Error && error.stack ? { stack: error.stack } : {}
5114
+ };
5115
+ }
5116
+ function toAlertDispatchErrorPayload(ruleName, error) {
5117
+ return {
5118
+ stage: "alert-dispatch",
5119
+ ...toRuleErrorPayload(ruleName, error)
5120
+ };
5121
+ }
5122
+ function toAlertCallbackErrorPayload(error) {
5123
+ return {
5124
+ stage: "alert-callback",
5125
+ error: error instanceof Error ? error.message : String(error),
5126
+ ...error instanceof Error && error.stack ? { stack: error.stack } : {}
5127
+ };
5128
+ }
5129
+ function toMetricsProviderErrorPayload(error) {
5130
+ return {
5131
+ stage: "metrics-provider",
5132
+ error: error instanceof Error ? error.message : String(error),
5133
+ ...error instanceof Error && error.stack ? { stack: error.stack } : {}
5134
+ };
5135
+ }
5102
5136
  var AlertManager = class {
5103
5137
  constructor(options) {
5104
5138
  this.options = options;
@@ -5112,8 +5146,12 @@ var AlertManager = class {
5112
5146
  }
5113
5147
  this.running = true;
5114
5148
  this.monitorTimer = setInterval(() => {
5115
- const currentMetrics = metrics();
5116
- this.checkRules(currentMetrics);
5149
+ try {
5150
+ const currentMetrics = metrics();
5151
+ this.checkRules(currentMetrics);
5152
+ } catch (error) {
5153
+ logger4.error("Metrics collection failed", toMetricsProviderErrorPayload(error));
5154
+ }
5117
5155
  }, interval);
5118
5156
  }
5119
5157
  stop() {
@@ -5129,18 +5167,22 @@ var AlertManager = class {
5129
5167
  async alert(alert) {
5130
5168
  const fullAlert = {
5131
5169
  ...alert,
5132
- timestamp: alert.timestamp || Date.now()
5170
+ timestamp: alert.timestamp ?? Date.now()
5133
5171
  };
5134
5172
  if (this.isThrottled(alert.name)) {
5135
5173
  return;
5136
5174
  }
5137
5175
  this.lastAlertTime.set(alert.name, Date.now());
5138
- this.options.onAlert?.(fullAlert);
5176
+ try {
5177
+ await this.options.onAlert?.(fullAlert);
5178
+ } catch (error) {
5179
+ logger4.error("Alert callback failed", toAlertCallbackErrorPayload(error));
5180
+ }
5139
5181
  logger4.warn("Alert triggered", {
5140
5182
  name: alert.name,
5141
5183
  severity: alert.severity,
5142
5184
  message: alert.message,
5143
- data: alert.data
5185
+ ...alert.data ? { data: alert.data } : {}
5144
5186
  });
5145
5187
  }
5146
5188
  checkRules(metrics) {
@@ -5150,19 +5192,17 @@ var AlertManager = class {
5150
5192
  for (const rule of this.options.rules) {
5151
5193
  try {
5152
5194
  if (rule.condition(metrics)) {
5153
- this.alert({
5195
+ void this.alert({
5154
5196
  name: rule.name,
5155
5197
  severity: rule.severity,
5156
5198
  message: rule.message || `Alert triggered: ${rule.name}`,
5157
5199
  data: { metrics }
5200
+ }).catch((error) => {
5201
+ logger4.error("Alert dispatch failed", toAlertDispatchErrorPayload(rule.name, error));
5158
5202
  });
5159
5203
  }
5160
5204
  } catch (error) {
5161
- logger4.error("Rule check failed", {
5162
- ruleName: rule.name,
5163
- error: error instanceof Error ? error.message : String(error),
5164
- stack: error instanceof Error ? error.stack : void 0
5165
- });
5205
+ logger4.error("Rule check failed", toRuleErrorPayload(rule.name, error));
5166
5206
  }
5167
5207
  }
5168
5208
  }
@@ -5187,32 +5227,32 @@ var AlertManager = class {
5187
5227
  logger4.info("Alert sent to email", {
5188
5228
  channel: channelName,
5189
5229
  to: channel.config.to,
5190
- alert: { name: alert.name, severity: alert.severity, message: alert.message }
5230
+ alert: toAlertSummary(alert)
5191
5231
  });
5192
5232
  break;
5193
5233
  case "slack":
5194
5234
  logger4.info("Alert sent to Slack", {
5195
5235
  channel: channelName,
5196
5236
  webhookUrl: channel.config.webhookUrl,
5197
- alert: { name: alert.name, severity: alert.severity, message: alert.message }
5237
+ alert: toAlertSummary(alert)
5198
5238
  });
5199
5239
  break;
5200
5240
  case "webhook":
5201
5241
  logger4.info("Alert sent to webhook", {
5202
5242
  channel: channelName,
5203
5243
  url: channel.config.url,
5204
- alert: { name: alert.name, severity: alert.severity, message: alert.message }
5244
+ alert: toAlertSummary(alert)
5205
5245
  });
5206
5246
  break;
5207
5247
  default:
5208
5248
  logger4.info("Alert sent", {
5209
5249
  channel: channelName,
5210
5250
  channelType: channel.type,
5211
- alert: { name: alert.name, severity: alert.severity, message: alert.message }
5251
+ alert: toAlertSummary(alert)
5212
5252
  });
5213
5253
  }
5214
5254
  }
5215
- getAlertHistory(name, limit = 100) {
5255
+ getAlertHistory(_name, _limit = 100) {
5216
5256
  return [];
5217
5257
  }
5218
5258
  clearAlertHistory(name) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentforge/core",
3
- "version": "0.15.8",
3
+ "version": "0.15.9",
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",