@agentforge/core 0.16.6 → 0.16.8

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
@@ -4229,24 +4229,68 @@ function formatAgentResumedEvent(threadId) {
4229
4229
  }
4230
4230
 
4231
4231
  // src/streaming/websocket.ts
4232
+ var WEBSOCKET_OPEN = 1;
4233
+ function parseWebSocketMessage(data) {
4234
+ if (typeof data !== "string") {
4235
+ return data;
4236
+ }
4237
+ try {
4238
+ return JSON.parse(data);
4239
+ } catch {
4240
+ return data;
4241
+ }
4242
+ }
4243
+ function normalizeThrownError(error) {
4244
+ return error instanceof Error ? error : new Error(String(error));
4245
+ }
4246
+ function createHeartbeatCapabilityError() {
4247
+ return new Error(
4248
+ "WebSocket heartbeat requires ping() and terminate() support on the provided socket"
4249
+ );
4250
+ }
4251
+ function closeIncompatibleHeartbeatSocket(socket) {
4252
+ if (typeof socket.close === "function") {
4253
+ try {
4254
+ socket.close();
4255
+ return;
4256
+ } catch {
4257
+ }
4258
+ }
4259
+ if (typeof socket.terminate === "function") {
4260
+ try {
4261
+ socket.terminate();
4262
+ } catch {
4263
+ }
4264
+ }
4265
+ }
4232
4266
  function createWebSocketHandler(options) {
4233
4267
  const { onConnect, onMessage, onError, onClose, heartbeat = 0 } = options;
4234
4268
  return function handler(ws, req) {
4269
+ const socket = ws;
4235
4270
  let heartbeatInterval = null;
4236
4271
  let isAlive = true;
4237
4272
  if (heartbeat > 0) {
4273
+ if (typeof ws.ping !== "function" || typeof ws.terminate !== "function") {
4274
+ if (onError) {
4275
+ onError(ws, createHeartbeatCapabilityError());
4276
+ }
4277
+ closeIncompatibleHeartbeatSocket(socket);
4278
+ return;
4279
+ }
4280
+ const ping = ws.ping.bind(ws);
4281
+ const terminate = ws.terminate.bind(ws);
4238
4282
  heartbeatInterval = setInterval(() => {
4239
4283
  if (!isAlive) {
4240
4284
  if (heartbeatInterval) {
4241
4285
  clearInterval(heartbeatInterval);
4242
4286
  }
4243
- ws.terminate();
4287
+ terminate();
4244
4288
  return;
4245
4289
  }
4246
4290
  isAlive = false;
4247
- ws.ping();
4291
+ ping();
4248
4292
  }, heartbeat);
4249
- ws.on("pong", () => {
4293
+ socket.on("pong", () => {
4250
4294
  isAlive = true;
4251
4295
  });
4252
4296
  }
@@ -4255,37 +4299,28 @@ function createWebSocketHandler(options) {
4255
4299
  onConnect(ws, req);
4256
4300
  } catch (error) {
4257
4301
  if (onError) {
4258
- onError(ws, error);
4302
+ onError(ws, normalizeThrownError(error));
4259
4303
  }
4260
4304
  }
4261
4305
  }
4262
- ws.on("message", async (data) => {
4306
+ socket.on("message", async (data) => {
4263
4307
  try {
4264
- let message;
4265
- if (typeof data === "string") {
4266
- try {
4267
- message = JSON.parse(data);
4268
- } catch {
4269
- message = data;
4270
- }
4271
- } else {
4272
- message = data;
4273
- }
4308
+ const message = parseWebSocketMessage(data);
4274
4309
  if (onMessage) {
4275
4310
  await onMessage(ws, message);
4276
4311
  }
4277
4312
  } catch (error) {
4278
4313
  if (onError) {
4279
- onError(ws, error);
4314
+ onError(ws, normalizeThrownError(error));
4280
4315
  }
4281
4316
  }
4282
4317
  });
4283
- ws.on("error", (error) => {
4318
+ socket.on("error", (error) => {
4284
4319
  if (onError) {
4285
4320
  onError(ws, error);
4286
4321
  }
4287
4322
  });
4288
- ws.on("close", (code, reason) => {
4323
+ socket.on("close", (code, reason) => {
4289
4324
  if (heartbeatInterval) {
4290
4325
  clearInterval(heartbeatInterval);
4291
4326
  }
@@ -4296,14 +4331,14 @@ function createWebSocketHandler(options) {
4296
4331
  };
4297
4332
  }
4298
4333
  function sendMessage(ws, message) {
4299
- if (ws.readyState === 1) {
4334
+ if (ws.readyState === WEBSOCKET_OPEN) {
4300
4335
  ws.send(JSON.stringify(message));
4301
4336
  }
4302
4337
  }
4303
4338
  function broadcast(clients, message) {
4304
4339
  const data = JSON.stringify(message);
4305
4340
  for (const client of clients) {
4306
- if (client.readyState === 1) {
4341
+ if (client.readyState === WEBSOCKET_OPEN) {
4307
4342
  client.send(data);
4308
4343
  }
4309
4344
  }
@@ -5585,6 +5620,35 @@ function createAuditLogger(options) {
5585
5620
  var import_fs = require("fs");
5586
5621
  var import_path = require("path");
5587
5622
  var MAX_VARIABLE_LENGTH = 500;
5623
+ function createPromptVariableMap() {
5624
+ return /* @__PURE__ */ Object.create(null);
5625
+ }
5626
+ function isPromptVariableMap(value) {
5627
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5628
+ }
5629
+ function isRenderTemplateOptions(value) {
5630
+ return isPromptVariableMap(value) && (Object.prototype.hasOwnProperty.call(value, "trustedVariables") || Object.prototype.hasOwnProperty.call(value, "untrustedVariables"));
5631
+ }
5632
+ function normalizeVariableMap(value) {
5633
+ if (!isPromptVariableMap(value)) {
5634
+ return createPromptVariableMap();
5635
+ }
5636
+ return Object.assign(createPromptVariableMap(), value);
5637
+ }
5638
+ function sanitizeVariableMap(variables) {
5639
+ const sanitizedVariables = createPromptVariableMap();
5640
+ for (const [key, value] of Object.entries(variables)) {
5641
+ sanitizedVariables[key] = sanitizeValue(value);
5642
+ }
5643
+ return sanitizedVariables;
5644
+ }
5645
+ function mergeVariableMaps(baseVariables, overrideVariables) {
5646
+ return Object.assign(
5647
+ createPromptVariableMap(),
5648
+ baseVariables,
5649
+ overrideVariables
5650
+ );
5651
+ }
5588
5652
  function sanitizeValue(value) {
5589
5653
  if (value === void 0 || value === null) return "";
5590
5654
  let sanitized = String(value);
@@ -5599,25 +5663,17 @@ function sanitizeValue(value) {
5599
5663
  function renderTemplate(template, options) {
5600
5664
  let rawVariables;
5601
5665
  let sanitizedVariables;
5602
- if ("trustedVariables" in options || "untrustedVariables" in options) {
5603
- const opts = options;
5604
- rawVariables = {
5605
- ...opts.trustedVariables,
5606
- ...opts.untrustedVariables
5607
- };
5608
- const sanitizedUntrusted = {};
5609
- if (opts.untrustedVariables) {
5610
- for (const [key, value] of Object.entries(opts.untrustedVariables)) {
5611
- sanitizedUntrusted[key] = sanitizeValue(value);
5612
- }
5613
- }
5614
- sanitizedVariables = {
5615
- ...opts.trustedVariables,
5616
- ...sanitizedUntrusted
5617
- };
5666
+ if (isRenderTemplateOptions(options)) {
5667
+ const trustedVariables = normalizeVariableMap(options.trustedVariables);
5668
+ const untrustedVariables = normalizeVariableMap(options.untrustedVariables);
5669
+ rawVariables = mergeVariableMaps(trustedVariables, untrustedVariables);
5670
+ sanitizedVariables = mergeVariableMaps(
5671
+ trustedVariables,
5672
+ sanitizeVariableMap(untrustedVariables)
5673
+ );
5618
5674
  } else {
5619
- rawVariables = options;
5620
- sanitizedVariables = options;
5675
+ rawVariables = normalizeVariableMap(options);
5676
+ sanitizedVariables = rawVariables;
5621
5677
  }
5622
5678
  let result = template;
5623
5679
  result = result.replace(/\{\{#if\s+(\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g, (_, varName, content) => {
package/dist/index.d.cts CHANGED
@@ -4573,29 +4573,87 @@ interface SSEFormatter<T = any> {
4573
4573
  /** Format stream as SSE events */
4574
4574
  format(stream: AsyncIterable<T>): AsyncIterable<string>;
4575
4575
  }
4576
+ /**
4577
+ * Binary WebSocket payload
4578
+ */
4579
+ type WebSocketBinaryData = ArrayBuffer | ArrayBufferView | ReadonlyArray<ArrayBufferView>;
4580
+ /**
4581
+ * Raw WebSocket message payload
4582
+ */
4583
+ type WebSocketRawMessage = string | WebSocketBinaryData;
4584
+ /**
4585
+ * WebSocket close reason payload
4586
+ */
4587
+ type WebSocketCloseReason = string | WebSocketBinaryData;
4588
+ /**
4589
+ * Minimal WebSocket-like connection contract used by streaming helpers
4590
+ */
4591
+ type WebSocketEvent = 'pong' | 'message' | 'error' | 'close';
4592
+ /**
4593
+ * Typed WebSocket event handler
4594
+ */
4595
+ type WebSocketEventHandler<TEvent extends WebSocketEvent, TMessage, TCloseReason> = TEvent extends 'pong' ? () => void : TEvent extends 'message' ? (data: TMessage) => void | Promise<void> : TEvent extends 'error' ? (error: Error) => void : (code?: number, reason?: TCloseReason) => void;
4596
+ interface WebSocketConnection<TMessage = WebSocketRawMessage, TCloseReason = WebSocketCloseReason> {
4597
+ /** Socket ready state */
4598
+ readyState: number;
4599
+ /** Register event handler */
4600
+ on<TEvent extends WebSocketEvent>(event: TEvent, handler: WebSocketEventHandler<TEvent, TMessage, TCloseReason>): void;
4601
+ /** Send string data */
4602
+ send(data: string): void;
4603
+ /** Close gracefully when supported by the implementation */
4604
+ close?(): void;
4605
+ /** Send ping when heartbeat support is available */
4606
+ ping?(): void;
4607
+ /** Force terminate socket when supported by the implementation */
4608
+ terminate?(): void;
4609
+ }
4610
+ type WebSocketConnectionTypeParts<TSocket extends WebSocketConnection> = TSocket extends WebSocketConnection<infer TMessage, infer TCloseReason> ? {
4611
+ message: TMessage;
4612
+ closeReason: TCloseReason;
4613
+ } : {
4614
+ message: WebSocketRawMessage;
4615
+ closeReason: WebSocketCloseReason;
4616
+ };
4617
+ /**
4618
+ * Extract message payload type from a WebSocket-like connection
4619
+ */
4620
+ type WebSocketMessageFor<TSocket extends WebSocketConnection> = WebSocketConnectionTypeParts<TSocket>['message'];
4621
+ /**
4622
+ * Extract close reason type from a WebSocket-like connection
4623
+ */
4624
+ type WebSocketCloseReasonFor<TSocket extends WebSocketConnection> = WebSocketConnectionTypeParts<TSocket>['closeReason'];
4625
+ /**
4626
+ * Minimal WebSocket-like send target used by send/broadcast helpers
4627
+ */
4628
+ interface WebSocketSendTarget {
4629
+ /** Socket ready state */
4630
+ readyState: number;
4631
+ /** Send string data */
4632
+ send(data: string): void;
4633
+ }
4576
4634
  /**
4577
4635
  * WebSocket message
4578
4636
  */
4579
- interface WebSocketMessage {
4637
+ interface WebSocketMessage<TData = unknown> {
4580
4638
  /** Message type */
4581
4639
  type: string;
4582
4640
  /** Message data */
4583
- data?: any;
4641
+ data?: TData;
4584
4642
  /** Error information */
4585
4643
  error?: string;
4586
4644
  }
4587
4645
  /**
4588
4646
  * WebSocket handler options
4589
4647
  */
4590
- interface WebSocketHandlerOptions {
4648
+ interface WebSocketHandlerOptions<TSocket extends WebSocketConnection = WebSocketConnection, TRequest = unknown> {
4591
4649
  /** Connection handler */
4592
- onConnect?: (ws: any, req?: any) => void;
4650
+ onConnect?: (ws: TSocket, req?: TRequest) => void;
4593
4651
  /** Message handler */
4594
- onMessage?: (ws: any, message: any) => Promise<void>;
4652
+ onMessage?: (ws: TSocket, message: unknown) => void | Promise<void>;
4595
4653
  /** Error handler */
4596
- onError?: (ws: any, error: Error) => void;
4654
+ onError?: (ws: TSocket, error: Error) => void;
4597
4655
  /** Close handler */
4598
- onClose?: (ws: any, code?: number, reason?: string) => void;
4656
+ onClose?: (ws: TSocket, code?: number, reason?: WebSocketCloseReasonFor<TSocket>) => void;
4599
4657
  /** Heartbeat interval (ms) */
4600
4658
  heartbeat?: number;
4601
4659
  }
@@ -4937,21 +4995,21 @@ declare function formatAgentResumedEvent(threadId: string): SSEEvent;
4937
4995
  * wss.on('connection', handler);
4938
4996
  * ```
4939
4997
  */
4940
- declare function createWebSocketHandler(options: WebSocketHandlerOptions): (ws: any, req?: any) => void;
4998
+ declare function createWebSocketHandler<TSocket extends WebSocketConnection = WebSocketConnection, TRequest = unknown>(options: WebSocketHandlerOptions<TSocket, TRequest>): (ws: TSocket, req?: TRequest) => void;
4941
4999
  /**
4942
5000
  * Send a message through WebSocket
4943
5001
  *
4944
5002
  * Automatically serializes objects to JSON
4945
5003
  */
4946
- declare function sendMessage(ws: any, message: WebSocketMessage): void;
5004
+ declare function sendMessage<TData = unknown>(ws: WebSocketSendTarget, message: WebSocketMessage<TData>): void;
4947
5005
  /**
4948
5006
  * Broadcast a message to multiple WebSocket clients
4949
5007
  */
4950
- declare function broadcast(clients: Set<any>, message: WebSocketMessage): void;
5008
+ declare function broadcast<TData = unknown, TSocket extends WebSocketSendTarget = WebSocketSendTarget>(clients: Set<TSocket>, message: WebSocketMessage<TData>): void;
4951
5009
  /**
4952
5010
  * Create a WebSocket message
4953
5011
  */
4954
- declare function createMessage(type: string, data?: any, error?: string): WebSocketMessage;
5012
+ declare function createMessage<TData = unknown>(type: string, data?: TData, error?: string): WebSocketMessage<TData>;
4955
5013
 
4956
5014
  /**
4957
5015
  * Connection pooling for database and HTTP clients
@@ -5495,6 +5553,8 @@ declare function createAuditLogger(options?: AuditLoggerOptions): AuditLogger;
5495
5553
  * SECURITY: This module includes protection against prompt injection attacks
5496
5554
  * by sanitizing variable values before substitution.
5497
5555
  */
5556
+ type PromptVariableValue = unknown;
5557
+ type PromptVariableMap = Record<string, PromptVariableValue>;
5498
5558
  /**
5499
5559
  * Options for rendering templates with security controls
5500
5560
  */
@@ -5503,12 +5563,12 @@ interface RenderTemplateOptions {
5503
5563
  * Variables from trusted sources (config files, hardcoded values)
5504
5564
  * These will NOT be sanitized
5505
5565
  */
5506
- trustedVariables?: Record<string, any>;
5566
+ trustedVariables?: PromptVariableMap;
5507
5567
  /**
5508
5568
  * Variables from untrusted sources (user input, API calls, databases)
5509
5569
  * These WILL be sanitized to prevent prompt injection
5510
5570
  */
5511
- untrustedVariables?: Record<string, any>;
5571
+ untrustedVariables?: PromptVariableMap;
5512
5572
  }
5513
5573
  /**
5514
5574
  * Sanitize a value to prevent prompt injection attacks
@@ -5521,7 +5581,7 @@ interface RenderTemplateOptions {
5521
5581
  * @param value - The value to sanitize
5522
5582
  * @returns Sanitized string safe for use in prompts
5523
5583
  */
5524
- declare function sanitizeValue(value: any): string;
5584
+ declare function sanitizeValue(value: unknown): string;
5525
5585
  /**
5526
5586
  * Render a template string with variable substitution
5527
5587
  *
@@ -5532,6 +5592,8 @@ declare function sanitizeValue(value: any): string;
5532
5592
  * SECURITY: Distinguishes between trusted and untrusted variables.
5533
5593
  * - Trusted variables (from config) are used as-is
5534
5594
  * - Untrusted variables (from user input) are sanitized
5595
+ * - Only own enumerable properties are considered from provided variable maps
5596
+ * or backwards-compatible plain objects
5535
5597
  *
5536
5598
  * @param template - Template string with {{variable}} placeholders
5537
5599
  * @param options - Variables and security options
@@ -5565,7 +5627,7 @@ declare function sanitizeValue(value: any): string;
5565
5627
  * });
5566
5628
  * ```
5567
5629
  */
5568
- declare function renderTemplate(template: string, options: RenderTemplateOptions | Record<string, any>): string;
5630
+ declare function renderTemplate(template: string, options: RenderTemplateOptions | PromptVariableMap): string;
5569
5631
  /**
5570
5632
  * Load and render a prompt template from a .md file
5571
5633
  *
@@ -5591,6 +5653,6 @@ declare function renderTemplate(template: string, options: RenderTemplateOptions
5591
5653
  * loadPrompt('system', { companyName: 'Acme' }, '/path/to/prompts');
5592
5654
  * ```
5593
5655
  */
5594
- declare function loadPrompt(promptName: string, options?: RenderTemplateOptions | Record<string, any>, promptsDir?: string): string;
5656
+ declare function loadPrompt(promptName: string, options?: RenderTemplateOptions | PromptVariableMap, promptsDir?: string): string;
5595
5657
 
5596
- 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 };
5658
+ 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 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 };
package/dist/index.d.ts CHANGED
@@ -4573,29 +4573,87 @@ interface SSEFormatter<T = any> {
4573
4573
  /** Format stream as SSE events */
4574
4574
  format(stream: AsyncIterable<T>): AsyncIterable<string>;
4575
4575
  }
4576
+ /**
4577
+ * Binary WebSocket payload
4578
+ */
4579
+ type WebSocketBinaryData = ArrayBuffer | ArrayBufferView | ReadonlyArray<ArrayBufferView>;
4580
+ /**
4581
+ * Raw WebSocket message payload
4582
+ */
4583
+ type WebSocketRawMessage = string | WebSocketBinaryData;
4584
+ /**
4585
+ * WebSocket close reason payload
4586
+ */
4587
+ type WebSocketCloseReason = string | WebSocketBinaryData;
4588
+ /**
4589
+ * Minimal WebSocket-like connection contract used by streaming helpers
4590
+ */
4591
+ type WebSocketEvent = 'pong' | 'message' | 'error' | 'close';
4592
+ /**
4593
+ * Typed WebSocket event handler
4594
+ */
4595
+ type WebSocketEventHandler<TEvent extends WebSocketEvent, TMessage, TCloseReason> = TEvent extends 'pong' ? () => void : TEvent extends 'message' ? (data: TMessage) => void | Promise<void> : TEvent extends 'error' ? (error: Error) => void : (code?: number, reason?: TCloseReason) => void;
4596
+ interface WebSocketConnection<TMessage = WebSocketRawMessage, TCloseReason = WebSocketCloseReason> {
4597
+ /** Socket ready state */
4598
+ readyState: number;
4599
+ /** Register event handler */
4600
+ on<TEvent extends WebSocketEvent>(event: TEvent, handler: WebSocketEventHandler<TEvent, TMessage, TCloseReason>): void;
4601
+ /** Send string data */
4602
+ send(data: string): void;
4603
+ /** Close gracefully when supported by the implementation */
4604
+ close?(): void;
4605
+ /** Send ping when heartbeat support is available */
4606
+ ping?(): void;
4607
+ /** Force terminate socket when supported by the implementation */
4608
+ terminate?(): void;
4609
+ }
4610
+ type WebSocketConnectionTypeParts<TSocket extends WebSocketConnection> = TSocket extends WebSocketConnection<infer TMessage, infer TCloseReason> ? {
4611
+ message: TMessage;
4612
+ closeReason: TCloseReason;
4613
+ } : {
4614
+ message: WebSocketRawMessage;
4615
+ closeReason: WebSocketCloseReason;
4616
+ };
4617
+ /**
4618
+ * Extract message payload type from a WebSocket-like connection
4619
+ */
4620
+ type WebSocketMessageFor<TSocket extends WebSocketConnection> = WebSocketConnectionTypeParts<TSocket>['message'];
4621
+ /**
4622
+ * Extract close reason type from a WebSocket-like connection
4623
+ */
4624
+ type WebSocketCloseReasonFor<TSocket extends WebSocketConnection> = WebSocketConnectionTypeParts<TSocket>['closeReason'];
4625
+ /**
4626
+ * Minimal WebSocket-like send target used by send/broadcast helpers
4627
+ */
4628
+ interface WebSocketSendTarget {
4629
+ /** Socket ready state */
4630
+ readyState: number;
4631
+ /** Send string data */
4632
+ send(data: string): void;
4633
+ }
4576
4634
  /**
4577
4635
  * WebSocket message
4578
4636
  */
4579
- interface WebSocketMessage {
4637
+ interface WebSocketMessage<TData = unknown> {
4580
4638
  /** Message type */
4581
4639
  type: string;
4582
4640
  /** Message data */
4583
- data?: any;
4641
+ data?: TData;
4584
4642
  /** Error information */
4585
4643
  error?: string;
4586
4644
  }
4587
4645
  /**
4588
4646
  * WebSocket handler options
4589
4647
  */
4590
- interface WebSocketHandlerOptions {
4648
+ interface WebSocketHandlerOptions<TSocket extends WebSocketConnection = WebSocketConnection, TRequest = unknown> {
4591
4649
  /** Connection handler */
4592
- onConnect?: (ws: any, req?: any) => void;
4650
+ onConnect?: (ws: TSocket, req?: TRequest) => void;
4593
4651
  /** Message handler */
4594
- onMessage?: (ws: any, message: any) => Promise<void>;
4652
+ onMessage?: (ws: TSocket, message: unknown) => void | Promise<void>;
4595
4653
  /** Error handler */
4596
- onError?: (ws: any, error: Error) => void;
4654
+ onError?: (ws: TSocket, error: Error) => void;
4597
4655
  /** Close handler */
4598
- onClose?: (ws: any, code?: number, reason?: string) => void;
4656
+ onClose?: (ws: TSocket, code?: number, reason?: WebSocketCloseReasonFor<TSocket>) => void;
4599
4657
  /** Heartbeat interval (ms) */
4600
4658
  heartbeat?: number;
4601
4659
  }
@@ -4937,21 +4995,21 @@ declare function formatAgentResumedEvent(threadId: string): SSEEvent;
4937
4995
  * wss.on('connection', handler);
4938
4996
  * ```
4939
4997
  */
4940
- declare function createWebSocketHandler(options: WebSocketHandlerOptions): (ws: any, req?: any) => void;
4998
+ declare function createWebSocketHandler<TSocket extends WebSocketConnection = WebSocketConnection, TRequest = unknown>(options: WebSocketHandlerOptions<TSocket, TRequest>): (ws: TSocket, req?: TRequest) => void;
4941
4999
  /**
4942
5000
  * Send a message through WebSocket
4943
5001
  *
4944
5002
  * Automatically serializes objects to JSON
4945
5003
  */
4946
- declare function sendMessage(ws: any, message: WebSocketMessage): void;
5004
+ declare function sendMessage<TData = unknown>(ws: WebSocketSendTarget, message: WebSocketMessage<TData>): void;
4947
5005
  /**
4948
5006
  * Broadcast a message to multiple WebSocket clients
4949
5007
  */
4950
- declare function broadcast(clients: Set<any>, message: WebSocketMessage): void;
5008
+ declare function broadcast<TData = unknown, TSocket extends WebSocketSendTarget = WebSocketSendTarget>(clients: Set<TSocket>, message: WebSocketMessage<TData>): void;
4951
5009
  /**
4952
5010
  * Create a WebSocket message
4953
5011
  */
4954
- declare function createMessage(type: string, data?: any, error?: string): WebSocketMessage;
5012
+ declare function createMessage<TData = unknown>(type: string, data?: TData, error?: string): WebSocketMessage<TData>;
4955
5013
 
4956
5014
  /**
4957
5015
  * Connection pooling for database and HTTP clients
@@ -5495,6 +5553,8 @@ declare function createAuditLogger(options?: AuditLoggerOptions): AuditLogger;
5495
5553
  * SECURITY: This module includes protection against prompt injection attacks
5496
5554
  * by sanitizing variable values before substitution.
5497
5555
  */
5556
+ type PromptVariableValue = unknown;
5557
+ type PromptVariableMap = Record<string, PromptVariableValue>;
5498
5558
  /**
5499
5559
  * Options for rendering templates with security controls
5500
5560
  */
@@ -5503,12 +5563,12 @@ interface RenderTemplateOptions {
5503
5563
  * Variables from trusted sources (config files, hardcoded values)
5504
5564
  * These will NOT be sanitized
5505
5565
  */
5506
- trustedVariables?: Record<string, any>;
5566
+ trustedVariables?: PromptVariableMap;
5507
5567
  /**
5508
5568
  * Variables from untrusted sources (user input, API calls, databases)
5509
5569
  * These WILL be sanitized to prevent prompt injection
5510
5570
  */
5511
- untrustedVariables?: Record<string, any>;
5571
+ untrustedVariables?: PromptVariableMap;
5512
5572
  }
5513
5573
  /**
5514
5574
  * Sanitize a value to prevent prompt injection attacks
@@ -5521,7 +5581,7 @@ interface RenderTemplateOptions {
5521
5581
  * @param value - The value to sanitize
5522
5582
  * @returns Sanitized string safe for use in prompts
5523
5583
  */
5524
- declare function sanitizeValue(value: any): string;
5584
+ declare function sanitizeValue(value: unknown): string;
5525
5585
  /**
5526
5586
  * Render a template string with variable substitution
5527
5587
  *
@@ -5532,6 +5592,8 @@ declare function sanitizeValue(value: any): string;
5532
5592
  * SECURITY: Distinguishes between trusted and untrusted variables.
5533
5593
  * - Trusted variables (from config) are used as-is
5534
5594
  * - Untrusted variables (from user input) are sanitized
5595
+ * - Only own enumerable properties are considered from provided variable maps
5596
+ * or backwards-compatible plain objects
5535
5597
  *
5536
5598
  * @param template - Template string with {{variable}} placeholders
5537
5599
  * @param options - Variables and security options
@@ -5565,7 +5627,7 @@ declare function sanitizeValue(value: any): string;
5565
5627
  * });
5566
5628
  * ```
5567
5629
  */
5568
- declare function renderTemplate(template: string, options: RenderTemplateOptions | Record<string, any>): string;
5630
+ declare function renderTemplate(template: string, options: RenderTemplateOptions | PromptVariableMap): string;
5569
5631
  /**
5570
5632
  * Load and render a prompt template from a .md file
5571
5633
  *
@@ -5591,6 +5653,6 @@ declare function renderTemplate(template: string, options: RenderTemplateOptions
5591
5653
  * loadPrompt('system', { companyName: 'Acme' }, '/path/to/prompts');
5592
5654
  * ```
5593
5655
  */
5594
- declare function loadPrompt(promptName: string, options?: RenderTemplateOptions | Record<string, any>, promptsDir?: string): string;
5656
+ declare function loadPrompt(promptName: string, options?: RenderTemplateOptions | PromptVariableMap, promptsDir?: string): string;
5595
5657
 
5596
- 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 };
5658
+ 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 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 };
package/dist/index.js CHANGED
@@ -4054,24 +4054,68 @@ function formatAgentResumedEvent(threadId) {
4054
4054
  }
4055
4055
 
4056
4056
  // src/streaming/websocket.ts
4057
+ var WEBSOCKET_OPEN = 1;
4058
+ function parseWebSocketMessage(data) {
4059
+ if (typeof data !== "string") {
4060
+ return data;
4061
+ }
4062
+ try {
4063
+ return JSON.parse(data);
4064
+ } catch {
4065
+ return data;
4066
+ }
4067
+ }
4068
+ function normalizeThrownError(error) {
4069
+ return error instanceof Error ? error : new Error(String(error));
4070
+ }
4071
+ function createHeartbeatCapabilityError() {
4072
+ return new Error(
4073
+ "WebSocket heartbeat requires ping() and terminate() support on the provided socket"
4074
+ );
4075
+ }
4076
+ function closeIncompatibleHeartbeatSocket(socket) {
4077
+ if (typeof socket.close === "function") {
4078
+ try {
4079
+ socket.close();
4080
+ return;
4081
+ } catch {
4082
+ }
4083
+ }
4084
+ if (typeof socket.terminate === "function") {
4085
+ try {
4086
+ socket.terminate();
4087
+ } catch {
4088
+ }
4089
+ }
4090
+ }
4057
4091
  function createWebSocketHandler(options) {
4058
4092
  const { onConnect, onMessage, onError, onClose, heartbeat = 0 } = options;
4059
4093
  return function handler(ws, req) {
4094
+ const socket = ws;
4060
4095
  let heartbeatInterval = null;
4061
4096
  let isAlive = true;
4062
4097
  if (heartbeat > 0) {
4098
+ if (typeof ws.ping !== "function" || typeof ws.terminate !== "function") {
4099
+ if (onError) {
4100
+ onError(ws, createHeartbeatCapabilityError());
4101
+ }
4102
+ closeIncompatibleHeartbeatSocket(socket);
4103
+ return;
4104
+ }
4105
+ const ping = ws.ping.bind(ws);
4106
+ const terminate = ws.terminate.bind(ws);
4063
4107
  heartbeatInterval = setInterval(() => {
4064
4108
  if (!isAlive) {
4065
4109
  if (heartbeatInterval) {
4066
4110
  clearInterval(heartbeatInterval);
4067
4111
  }
4068
- ws.terminate();
4112
+ terminate();
4069
4113
  return;
4070
4114
  }
4071
4115
  isAlive = false;
4072
- ws.ping();
4116
+ ping();
4073
4117
  }, heartbeat);
4074
- ws.on("pong", () => {
4118
+ socket.on("pong", () => {
4075
4119
  isAlive = true;
4076
4120
  });
4077
4121
  }
@@ -4080,37 +4124,28 @@ function createWebSocketHandler(options) {
4080
4124
  onConnect(ws, req);
4081
4125
  } catch (error) {
4082
4126
  if (onError) {
4083
- onError(ws, error);
4127
+ onError(ws, normalizeThrownError(error));
4084
4128
  }
4085
4129
  }
4086
4130
  }
4087
- ws.on("message", async (data) => {
4131
+ socket.on("message", async (data) => {
4088
4132
  try {
4089
- let message;
4090
- if (typeof data === "string") {
4091
- try {
4092
- message = JSON.parse(data);
4093
- } catch {
4094
- message = data;
4095
- }
4096
- } else {
4097
- message = data;
4098
- }
4133
+ const message = parseWebSocketMessage(data);
4099
4134
  if (onMessage) {
4100
4135
  await onMessage(ws, message);
4101
4136
  }
4102
4137
  } catch (error) {
4103
4138
  if (onError) {
4104
- onError(ws, error);
4139
+ onError(ws, normalizeThrownError(error));
4105
4140
  }
4106
4141
  }
4107
4142
  });
4108
- ws.on("error", (error) => {
4143
+ socket.on("error", (error) => {
4109
4144
  if (onError) {
4110
4145
  onError(ws, error);
4111
4146
  }
4112
4147
  });
4113
- ws.on("close", (code, reason) => {
4148
+ socket.on("close", (code, reason) => {
4114
4149
  if (heartbeatInterval) {
4115
4150
  clearInterval(heartbeatInterval);
4116
4151
  }
@@ -4121,14 +4156,14 @@ function createWebSocketHandler(options) {
4121
4156
  };
4122
4157
  }
4123
4158
  function sendMessage(ws, message) {
4124
- if (ws.readyState === 1) {
4159
+ if (ws.readyState === WEBSOCKET_OPEN) {
4125
4160
  ws.send(JSON.stringify(message));
4126
4161
  }
4127
4162
  }
4128
4163
  function broadcast(clients, message) {
4129
4164
  const data = JSON.stringify(message);
4130
4165
  for (const client of clients) {
4131
- if (client.readyState === 1) {
4166
+ if (client.readyState === WEBSOCKET_OPEN) {
4132
4167
  client.send(data);
4133
4168
  }
4134
4169
  }
@@ -5410,6 +5445,35 @@ function createAuditLogger(options) {
5410
5445
  import { readFileSync } from "fs";
5411
5446
  import { join } from "path";
5412
5447
  var MAX_VARIABLE_LENGTH = 500;
5448
+ function createPromptVariableMap() {
5449
+ return /* @__PURE__ */ Object.create(null);
5450
+ }
5451
+ function isPromptVariableMap(value) {
5452
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5453
+ }
5454
+ function isRenderTemplateOptions(value) {
5455
+ return isPromptVariableMap(value) && (Object.prototype.hasOwnProperty.call(value, "trustedVariables") || Object.prototype.hasOwnProperty.call(value, "untrustedVariables"));
5456
+ }
5457
+ function normalizeVariableMap(value) {
5458
+ if (!isPromptVariableMap(value)) {
5459
+ return createPromptVariableMap();
5460
+ }
5461
+ return Object.assign(createPromptVariableMap(), value);
5462
+ }
5463
+ function sanitizeVariableMap(variables) {
5464
+ const sanitizedVariables = createPromptVariableMap();
5465
+ for (const [key, value] of Object.entries(variables)) {
5466
+ sanitizedVariables[key] = sanitizeValue(value);
5467
+ }
5468
+ return sanitizedVariables;
5469
+ }
5470
+ function mergeVariableMaps(baseVariables, overrideVariables) {
5471
+ return Object.assign(
5472
+ createPromptVariableMap(),
5473
+ baseVariables,
5474
+ overrideVariables
5475
+ );
5476
+ }
5413
5477
  function sanitizeValue(value) {
5414
5478
  if (value === void 0 || value === null) return "";
5415
5479
  let sanitized = String(value);
@@ -5424,25 +5488,17 @@ function sanitizeValue(value) {
5424
5488
  function renderTemplate(template, options) {
5425
5489
  let rawVariables;
5426
5490
  let sanitizedVariables;
5427
- if ("trustedVariables" in options || "untrustedVariables" in options) {
5428
- const opts = options;
5429
- rawVariables = {
5430
- ...opts.trustedVariables,
5431
- ...opts.untrustedVariables
5432
- };
5433
- const sanitizedUntrusted = {};
5434
- if (opts.untrustedVariables) {
5435
- for (const [key, value] of Object.entries(opts.untrustedVariables)) {
5436
- sanitizedUntrusted[key] = sanitizeValue(value);
5437
- }
5438
- }
5439
- sanitizedVariables = {
5440
- ...opts.trustedVariables,
5441
- ...sanitizedUntrusted
5442
- };
5491
+ if (isRenderTemplateOptions(options)) {
5492
+ const trustedVariables = normalizeVariableMap(options.trustedVariables);
5493
+ const untrustedVariables = normalizeVariableMap(options.untrustedVariables);
5494
+ rawVariables = mergeVariableMaps(trustedVariables, untrustedVariables);
5495
+ sanitizedVariables = mergeVariableMaps(
5496
+ trustedVariables,
5497
+ sanitizeVariableMap(untrustedVariables)
5498
+ );
5443
5499
  } else {
5444
- rawVariables = options;
5445
- sanitizedVariables = options;
5500
+ rawVariables = normalizeVariableMap(options);
5501
+ sanitizedVariables = rawVariables;
5446
5502
  }
5447
5503
  let result = template;
5448
5504
  result = result.replace(/\{\{#if\s+(\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g, (_, varName, content) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentforge/core",
3
- "version": "0.16.6",
3
+ "version": "0.16.8",
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",