Skip to content
reaatech

@reaatech/guardrail-chain

npm v0.1.0

Core types, chain orchestration, budget management, and utilities for the Guardrail Chain framework, providing the `Guardrail` interface and `GuardrailChain` orchestrator that every guardrail implementation must satisfy.

@reaatech/guardrail-chain

npm version License: MIT CI

Status: Pre-1.0 — APIs may change in minor versions. Pin to a specific version in production.

Core types, chain orchestration, budget management, and utilities for the Guardrail Chain framework. This package is the foundation for all @reaatech/guardrail-chain-* packages and provides the Guardrail interface that every guardrail implementation must satisfy.

Installation

terminal
npm install @reaatech/guardrail-chain
# or
pnpm add @reaatech/guardrail-chain

Feature Overview

  • Composable guardrail pipeline — chain input and output guardrails with budget-aware scheduling, priority ordering, and short-circuit-on-failure logic.
  • Budget management — track latency and token budgets, skip non-essential guardrails under pressure, and prevent budget overruns.
  • Fluent builder API — construct chains declaratively with ChainBuilder, or wire them programmatically with GuardrailChain.
  • Retry with exponential backoff — transparent retry for transient failures, with configurable predicates, jitter, and caps.
  • Circuit breaker — protect external-service guardrails from cascading failures with CLOSED/OPEN/HALF_OPEN state tracking.
  • LRU cache — TTL-aware cache for guardrail results, with configurable eviction policy.
  • Exported observability getter/setter functionssetLogger, setMetrics, setTracer re-exported from @reaatech/guardrail-chain-observability for single-import convenience.
  • Zero runtime dependencies beyond @reaatech/guardrail-chain-observability — lightweight and tree-shakeable.
  • Dual ESM/CJS output — works with import and require.

Quick Start

typescript
import {
  GuardrailChain,
  ChainBuilder,
  setLogger,
  ConsoleLogger,
  type Guardrail,
  type GuardrailResult,
  type ChainContext,
} from '@reaatech/guardrail-chain';
 
setLogger(new ConsoleLogger());
 
const chain = new ChainBuilder()
  .withBudget({ maxLatencyMs: 500, maxTokens: 4000 })
  .build();
 
const result = await chain.execute('What is the weather today?');
console.log(result.success ? 'Passed' : 'Failed');

Exports

Core Classes

ExportDescription
GuardrailChainMain orchestrator — executes input and output guardrail phases with budget-aware scheduling, timeout handling, retry, and short-circuit logic.
ChainBuilderFluent builder for constructing GuardrailChain instances with a declarative chaining API.
BudgetManagerTracks and enforces latency and token budgets throughout chain execution.

Core Types

ExportDescription
Guardrail<TInput, TOutput>The fundamental guardrail interface — every guardrail must implement id, name, type, enabled, execute(), and optional metadata fields.
GuardrailResult<TOutput>Result of a single guardrail execution — passed, optional output, confidence, metadata, error.
ChainContextState passed between guardrails — correlationId, userId, sessionId, budget, metadata, transformedInput, originalInput.
ChainConfigConfiguration for the chain — budget, observability, errorHandling.
ChainResultResult of a complete chain execution — success, output, error, failedGuardrail, metadata.
ChainResultMetadataWell-known fields on ChainResult.metadatacorrelationId, inputDuration, outputDuration, totalDuration, phase.
ExecutionOptionsPer-run options — userId, sessionId, correlationId overrides.
BudgetConfigBudget constraints — maxLatencyMs, maxTokens, skipSlowGuardrailsUnderPressure.
BudgetStateLive budget tracking — remainingLatency, remainingTokens, usedLatency, usedTokens.
GuardrailConfigPer-guardrail configuration — id, type, enabled, timeout, essential, priority, estimatedCostMs, shortCircuitOnFail.
ObservabilityConfigToggles for observability subsystems.
ErrorHandlingConfigError handling strategy — failOpen, maxRetries, retryDelayMs.

Factory Functions

ExportDescription
createChainContextFactory for ChainContext — initializes budget state from a BudgetConfig and optional overrides.

Error Classes

ClassExtendsCodeWhen
GuardrailErrorErrorBase class for all guardrail errors. Carries type, guardrailId, and recoverable flag.
TimeoutErrorGuardrailErrorTIMEOUTA guardrail exceeded its timeout. Recoverable.
BudgetExceededErrorGuardrailErrorBUDGET_EXCEEDEDLatency or token budget was exceeded during guardrail execution. Recoverable.
ValidationErrorGuardrailErrorVALIDATION_FAILEDConfiguration or input validation failed. Not recoverable.
GuardrailErrorType(enum)Enum of error codes: TIMEOUT, BUDGET_EXCEEDED, VALIDATION_FAILED, EXECUTION_FAILED, CONFIGURATION_ERROR.

Utility Classes

ExportDescription
CircuitBreakerCircuit breaker pattern — CLOSED/OPEN/HALF_OPEN states, configurable failure/success thresholds and reset timeout.
LRUCache<K, V>LRU cache with TTL support — get, set, has, delete, clear, size methods.

Utility Functions

ExportDescription
withRetryExecute an async function with retry logic — exponential backoff, configurable predicate, jitter, and max retries.
generateCorrelationIdGenerate a v4 UUID for correlation IDs — uses crypto.randomUUID() when available.
hashString53-bit string hash using MurmurHash-inspired mixing.

Retry Types & Constants

ExportDescription
RetryConfigConfiguration — maxRetries, initialDelayMs, maxDelayMs, multiplier, jitter.
DEFAULT_RETRY_CONFIGSensible defaults (3 retries, 100ms start, 5s cap, ×2, jitter enabled).
RetryPredicateType for retry decision function — receives (error, attempt) and returns boolean.
defaultRetryPredicateDefault predicate — retries on timeout and transient network errors.

Cache Types & Constants

ExportDescription
CacheConfigConfiguration — maxSize, ttlMs.
DEFAULT_CACHE_CONFIGSensible defaults (1000 entries, 1h TTL).
CacheEntry<T>Internal cache entry — value, expiresAt.

Circuit Breaker Types & Constants

ExportDescription
CircuitBreakerConfigConfiguration — failureThreshold, resetTimeoutMs, successThreshold.
DEFAULT_CIRCUIT_BREAKER_CONFIGSensible defaults (5 failures, 30s reset, 2 successes to close).

Re-exports from observability

For convenience, the following are re-exported from @reaatech/guardrail-chain-observability:

ExportDescription
getLogger / setLoggerGet or set the global logger instance.
ConsoleLoggerLogs to console.debug/info/warn/error.
NoOpLoggerDefault silent logger — used when no logger is set.
getMetrics / setMetricsGet or set the global metrics collector.
getTracer / setTracerGet or set the global tracer instance.
Logger / MetricsCollector / Tracer / SpanObservability interfaces.

Usage Patterns

Building a chain with the fluent builder

typescript
import { ChainBuilder } from '@reaatech/guardrail-chain';
import { PIIRedaction, ToxicityFilter } from '@reaatech/guardrail-chain-guardrails';
 
const chain = new ChainBuilder()
  .withBudget({ maxLatencyMs: 500, maxTokens: 4000 })
  .withGuardrail(new PIIRedaction())
  .withGuardrail(new ToxicityFilter())
  .withSlowGuardrailSkipping(true)
  .withErrorHandling({ maxRetries: 2, retryDelayMs: 200 })
  .build();

Wrapping an external-service guardrail with a circuit breaker

typescript
import { CircuitBreaker, type Guardrail, type GuardrailResult, type ChainContext } from '@reaatech/guardrail-chain';
 
const breaker = new CircuitBreaker('moderation-api', {
  failureThreshold: 5,
  resetTimeoutMs: 30_000,
});
 
class ExternalModerationGuardrail implements Guardrail<string, string> {
  readonly id = 'external-moderation';
  readonly name = 'External Moderation';
  readonly type = 'output' as const;
  enabled = true;
 
  async execute(input: string, context: ChainContext): Promise<GuardrailResult<string>> {
    return breaker.execute(async () => {
      const response = await fetch('https://api.example.com/moderate', {
        method: 'POST',
        body: JSON.stringify({ text: input }),
      });
      const data = await response.json();
      return { passed: data.flagged === false, output: data.sanitized ?? input };
    }).catch(() => {
      return { passed: true, output: input }; // fail-open
    });
  }
}

Caching guardrail results

typescript
import { LRUCache, generateCorrelationId } from '@reaatech/guardrail-chain';
 
const cache = new LRUCache<string, boolean>({ maxSize: 500, ttlMs: 300_000 });
const correlationId = generateCorrelationId();

License

MIT