parseExtensionsHeader(headerValue)
Parse A2A-Extensions header value into URI array. Signature| Name | Type | Description |
|---|---|---|
headerValue | string | undefined | Raw header value string, or undefined if absent |
negotiateExtensions(requestedUris, agentExtensions)
Negotiate extensions between client-requested and agent-declared sets. Signature| Name | Type | Description |
|---|---|---|
requestedUris | string[] | Extension URIs requested by the client |
agentExtensions | AgentExtension[] | Extensions declared in the agent’s Agent Card |
formatExtensionsHeader(activatedUris)
Format activated extension URIs into header value. Signature| Name | Type | Description |
|---|---|---|
activatedUris | string[] | Extension URIs that were successfully negotiated |
buildLafsExtension(options)
Build an A2A AgentExtension object declaring LAFS support. Signature| Name | Type | Description |
|---|---|---|
options | : BuildLafsExtensionOptions | Configuration options for the LAFS extension declaration |
buildExtension(options)
Build a generic A2A AgentExtension object. Signature| Name | Type | Description |
|---|---|---|
options | BuildExtensionOptions | Configuration for the extension declaration |
isValidExtensionKind(kind)
Check whether a string is a valid extension kind. Signature| Name | Type | Description |
|---|---|---|
kind | string | String value to validate |
validateExtensionDeclaration(extension)
Validate an A2A extension declaration for correctness. Signature| Name | Type | Description |
|---|---|---|
extension | AgentExtension | The AgentExtension to validate |
valid boolean and optional error message
Example
ExtensionSupportRequiredError
Error thrown when required A2A extensions are not supported by the client. SignaturetoJSONRPCError()
Convert to JSON-RPC error object.toProblemDetails()
Convert to RFC 9457 Problem Details object with agent-actionable fields.toLafsError()
Convert to a LAFSError-compatible object.extensionNegotiationMiddleware(options)
Express middleware for A2A extension negotiation. Signature| Name | Type | Description |
|---|---|---|
options | ExtensionNegotiationMiddlewareOptions | Middleware configuration with extensions and enforcement settings |
discoveryMiddleware(config, options)
Create Express middleware for serving A2A Agent Card. Signature| Name | Type | Description |
|---|---|---|
config | DiscoveryConfig | Discovery configuration (A2A v1.0 format) |
options | : DiscoveryMiddlewareOptions | Middleware options for path routing and caching |
discoveryFastifyPlugin(fastify, options)
Fastify plugin for A2A Agent Card discovery. Signature| Name | Type | Description |
|---|---|---|
fastify | unknown | Fastify instance |
options | { config: DiscoveryConfig; path?: string; } | Plugin options containing config and optional path |
TokenEstimator
Character-based token estimator for JSON payloads. Signatureestimate()
Estimate tokens for any JavaScript value. Handles circular references, nested objects, arrays, and Unicode.estimateJSON()
Estimate tokens from a JSON string. More efficient if you already have the JSON string.estimateWithTracking()
Internal recursive estimation with circular reference tracking.estimateArray()
Estimate tokens for an array.estimateObject()
Estimate tokens for a plain object.canSerialize()
Check if a value can be safely serialized (no circular refs).safeStringify()
Serialize a value to JSON with circular reference handling.safeCopy()
Create a deep copy of a value with circular refs replaced by"[Circular]".
estimateTokens(value, options)
Convenience function to estimate tokens for a value. Signature| Name | Type | Description |
|---|---|---|
value | unknown | Any JavaScript value to estimate |
options | : TokenEstimatorOptions | Optional estimator configuration overrides |
estimateTokensJSON(json, options)
Convenience function to estimate tokens from a JSON string. Signature| Name | Type | Description |
|---|---|---|
json | string | Pre-serialized JSON string |
options | : TokenEstimatorOptions | Optional estimator configuration overrides |
isMVILevel(value)
Type guard that checks whether an unknown value is a validMVILevel.
Signature
| Name | Type | Description |
|---|---|---|
value | unknown | The value to test. |
true if value is one of the recognised MVI level strings.
Example
isAgentAction(value)
Type guard that checks whether an unknown value is a validLAFSAgentAction.
Signature
| Name | Type | Description |
|---|---|---|
value | unknown | The value to test. |
true if value is one of the recognised agent action strings.
Example
applyBudgetEnforcement(envelope, budget, options)
Apply budget enforcement to an envelope. Signature| Name | Type | Description |
|---|---|---|
envelope | LAFSEnvelope | The LAFS envelope to check |
budget | number | Maximum allowed token count |
options | : BudgetEnforcementOptions | Budget enforcement options (truncation, callbacks) |
withBudget(budget, options)
Create a budget enforcement middleware function. Signature| Name | Type | Description |
|---|---|---|
budget | number | Maximum allowed token count for the response |
options | : BudgetEnforcementOptions | Budget enforcement options (truncation, callbacks) |
checkBudget(envelope, budget)
Check if an envelope has exceeded its budget without modifying it. Signature| Name | Type | Description |
|---|---|---|
envelope | LAFSEnvelope | The LAFS envelope to check |
budget | number | Maximum allowed token count |
exceeded flag, estimated token count, and remaining budget
Example
withBudgetSync(budget, options)
Synchronous version of withBudget for non-async contexts. Signature| Name | Type | Description |
|---|---|---|
budget | number | Maximum allowed token count for the response |
options | : BudgetEnforcementOptions | Budget enforcement options (truncation, callbacks) |
wrapWithBudget(handler, handler, budget, options)
Higher-order function that wraps a handler with budget enforcement. Signature| Name | Type | Description |
|---|---|---|
handler | (...args: TArgs | The handler function to wrap |
handler | (...args: TArgs | The handler function to wrap with budget enforcement |
budget | number | Maximum allowed tokens |
options | : BudgetEnforcementOptions | Budget enforcement options |
composeMiddleware(middlewares)
Compose multiple middleware functions into a single middleware. Signature| Name | Type | Description |
|---|---|---|
middlewares | EnvelopeMiddleware[] | Middleware functions to compose (executed left to right) |
getConformanceProfiles()
Loads the conformance profiles from the bundled JSON schema. SignatureConformanceProfiles object.
Example
getChecksForTier(tier)
Returns the list of check names that belong to the given conformance tier. Signature| Name | Type | Description |
|---|---|---|
tier | ConformanceTier | The conformance tier to retrieve checks for. |
validateConformanceProfiles(availableChecks)
Validates that the conformance profiles are internally consistent and reference only known checks. Signature| Name | Type | Description |
|---|---|---|
availableChecks | string[] | The full list of check names implemented by the conformance runner. |
valid (true when no errors) and an errors array of diagnostic strings.
Example
getErrorRegistry()
Loads the full LAFS error registry from the bundled JSON. SignatureisRegisteredErrorCode(code)
Checks whether a given error code exists in the LAFS error registry. Signature| Name | Type | Description |
|---|---|---|
code | string | The error code string to look up (e.g., "E_FORMAT_CONFLICT"). |
true if the code is registered, false otherwise.
Example
getRegistryCode(code)
Retrieves the full registry entry for a given error code. Signature| Name | Type | Description |
|---|---|---|
code | string | The error code string to look up. |
RegistryCode or undefined if not found.
Example
getAgentAction(code)
Returns the default agent action for a given error code. Signature| Name | Type | Description |
|---|---|---|
code | string | The error code string to look up. |
LAFSAgentAction or undefined if unavailable.
Example
getTypeUri(code)
Returns the RFC 9457 type URI for a given error code. Signature| Name | Type | Description |
|---|---|---|
code | string | The error code string to look up. |
undefined if unavailable.
Example
getDocUrl(code)
Returns the documentation URL for a given error code. Signature| Name | Type | Description |
|---|---|---|
code | string | The error code string to look up. |
undefined if unavailable.
Example
getTransportMapping(code, transport)
Resolves the transport-specific status value for a given error code and transport. Signature| Name | Type | Description |
|---|---|---|
code | string | The error code string to look up. |
transport | "http" | "grpc" | "cli" | The transport protocol to resolve a mapping for. |
TransportMapping or null if the code is unregistered.
Example
LAFSFlagError
Error thrown when LAFS flag validation fails. SignatureresolveOutputFormat(input)
Resolve the output format from flag inputs using the LAFS precedence chain. Signature| Name | Type | Description |
|---|---|---|
input | FlagInput | The flag inputs including explicit flags, project/user defaults, and TTY state |
LAFSFlagErrorWhenhumanFlagandjsonFlagare both truthy.
isNativeAvailable()
Check if the native addon is available. Signaturetrue if the native Rust binding was loaded successfully.
getNativeModule()
Get the native module, ornull if unavailable.
Signature
null for AJV fallback.
validateEnvelope(input)
Validates an unknown input against the LAFS envelope JSON Schema (Draft-07). Signature| Name | Type | Description |
|---|---|---|
input | unknown | The raw value to validate. |
EnvelopeValidationResult with validity status and any errors.
Example
assertEnvelope(input)
Validates input and throws on schema failure, returning a typed envelope on success. Signature| Name | Type | Description |
|---|---|---|
input | unknown | The raw value to validate as a LAFS envelope. |
LAFSEnvelope when schema validation passes.
Throws
- Error When the input does not conform to the envelope schema.
runEnvelopeConformance(envelope, options)
Runs the full suite of LAFS envelope conformance checks. Signature| Name | Type | Description |
|---|---|---|
envelope | unknown | The raw value to validate as a LAFS envelope. |
options | : EnvelopeConformanceOptions | Optional tier filter for the conformance checks. |
ConformanceReport with individual check results and an overall pass/fail.
Example
runFlagConformance(flags)
Runs LAFS flag-semantics conformance checks against a set of flag inputs. Signature| Name | Type | Description |
|---|---|---|
flags | FlagInput | The flag input to validate. |
ConformanceReport with individual check results and an overall pass/fail.
Example
ComplianceError
Error thrown whenassertCompliance or withCompliance detects failures.
Signature
enforceCompliance(input, options)
Runs the full LAFS compliance pipeline against an unknown input value. Signature| Name | Type | Description |
|---|---|---|
input | unknown | The raw value to validate as a LAFS envelope. |
options | : EnforceComplianceOptions | Controls which optional stages execute. |
ComplianceResult with the aggregate pass/fail status and per-stage reports.
Example
assertCompliance(input, options)
Validates input and throwsComplianceError on any failure.
Signature
| Name | Type | Description |
|---|---|---|
input | unknown | The raw value to validate as a LAFS envelope. |
options | : EnforceComplianceOptions | Controls which optional stages execute. |
LAFSEnvelope when all stages pass.
Throws
ComplianceErrorWhen any compliance stage fails.
withCompliance(producer, options)
Wraps an envelope-producing function with automatic compliance enforcement. Signature| Name | Type | Description |
|---|---|---|
producer | (...args: TArgs | A sync or async function that produces a LAFS envelope. |
options | : EnforceComplianceOptions | Compliance options forwarded to assertCompliance. |
createComplianceMiddleware(options)
Creates aComplianceMiddleware that enforces LAFS compliance on the next handler’s output.
Signature
| Name | Type | Description |
|---|---|---|
options | : EnforceComplianceOptions | Compliance options forwarded to assertCompliance. |
getDeprecationRegistry()
Retrieve all registered deprecation entries. SignatureDeprecationEntry rules in the registry
Example
detectDeprecatedEnvelopeFields(envelope)
Detect deprecated field usage in a LAFS envelope. Signature| Name | Type | Description |
|---|---|---|
envelope | LAFSEnvelope | The LAFS envelope to inspect |
Warning objects for each detected deprecation
Example
emitDeprecationWarnings(envelope)
Emit deprecation warnings by attaching them to the envelope metadata. Signature| Name | Type | Description |
|---|---|---|
envelope | LAFSEnvelope | The LAFS envelope to augment |
_meta.warnings
Example
createEnvelope(input)
Create a fully validated LAFS envelope from a success or error input. Signature| Name | Type | Description |
|---|---|---|
input | CreateEnvelopeInput | Discriminated union of success or error input data. |
LAFSEnvelope ready for serialization.
Example
LafsError
Error subclass that carries the fullLAFSError payload.
Signature
parseLafsResponse(input, options)
Parse and unwrap a raw LAFS envelope, returning the result or throwing on error. Signature| Name | Type | Description |
|---|---|---|
input | unknown | Raw value expected to be a valid LAFSEnvelope. |
options | : ParseLafsResponseOptions | Parsing options controlling error-code validation. |
result field of the envelope cast to T.
Throws
- LafsError When the envelope indicates failure (
success=false). - Error When the envelope is structurally invalid or
requireRegisteredErrorCodeistrueand the code is unregistered.
resolveFieldExtraction(input)
Resolve field extraction flags into a validated configuration. Signature| Name | Type | Description |
|---|---|---|
input | FieldExtractionInput | The field extraction flag inputs |
LAFSFlagErrorWhen bothfieldFlagandfieldsFlagare set.
extractFieldFromResult(result, field)
Extract a named field from a LAFS result object. Signature| Name | Type | Description |
|---|---|---|
result | LAFSEnvelope["result"] | The envelope result value (object, array, or null) |
field | string | The field name to extract |
undefined if not found at any level
Example
extractFieldFromEnvelope(envelope, field)
Extract a named field from an envelope’s result. Signature| Name | Type | Description |
|---|---|---|
envelope | LAFSEnvelope | The LAFS envelope to extract from |
field | string | The field name to extract |
undefined if not found
Example
applyFieldFilter(envelope, fields)
Filter result fields in a LAFS envelope to the requested subset. Signature| Name | Type | Description |
|---|---|---|
envelope | LAFSEnvelope | The LAFS envelope whose result will be filtered |
fields | string[] | Array of field names to retain in the result |
_meta.mvi set to 'custom'
Example
resolveFlags(input)
Resolve all flags across both layers and validate cross-layer semantics. Signature| Name | Type | Description |
|---|---|---|
input | UnifiedFlagInput | Combined format and field extraction flags |
LAFSFlagErrorWhen format or field layer flags conflict.
LafsA2AResult
Wrapper for A2A responses with LAFS envelope support. SignaturegetA2AResult()
Get the raw A2A response.isError()
Check if the result is an error response.getError()
Get error details if the result is an error.getSuccess()
Get the success result.getTask()
Extract a Task from the response (if present).getMessage()
Extract a Message from the response (if present).hasLafsEnvelope()
Check if the response contains a LAFS envelope.getLafsEnvelope()
Extract a LAFS envelope from A2A artifact.getTokenEstimate()
Get token estimate from LAFS envelope.getTaskStatus()
Get the task status.getTaskState()
Get the task state.isTerminal()
Check if the task is in a terminal state.isInputRequired()
Check if the task requires user input.isAuthRequired()
Check if the task requires authentication.getArtifacts()
Get all artifacts from the task.isDataPart()
Type guard: checks whether a Part is a DataPart by inspecting itskind field.
isLafsEnvelope()
Heuristic check: returns true if the data object looks like a LAFS envelope (has$schema, _meta, success).
createLafsArtifact(envelope)
Create a LAFS envelope artifact for A2A. Signature| Name | Type | Description |
|---|---|---|
envelope | LAFSEnvelope | LAFS envelope to wrap as an artifact |
createTextArtifact(text, name)
Create a text artifact. Signature| Name | Type | Description |
|---|---|---|
text | string | Text content for the artifact |
name | : string | Display name for the artifact |
createFileArtifact(fileUrl, mediaType, filename)
Create a file artifact. Signature| Name | Type | Description |
|---|---|---|
fileUrl | string | URI pointing to the file resource |
mediaType | string | MIME type of the file (e.g., application/pdf) |
filename | : string | Optional display filename for the artifact |
isExtensionRequired(agentCard, extensionUri)
Check if an extension is required in an Agent Card. Signature| Name | Type | Description |
|---|---|---|
agentCard | AgentCard | Agent Card to inspect |
extensionUri | string | URI of the extension to check |
getExtensionParams(agentCard, extensionUri)
Get extension parameters from an Agent Card. Signature| Name | Type | Description |
|---|---|---|
agentCard | AgentCard | Agent Card to inspect |
extensionUri | string | URI of the extension to look up |
isValidTransition(from, to)
Check if a transition from one state to another is valid. Signature| Name | Type | Description |
|---|---|---|
from | TaskState | Current task state |
to | TaskState | Desired target state |
isTerminalState(state)
Check if a state is terminal (no further transitions allowed). Signature| Name | Type | Description |
|---|---|---|
state | TaskState | Task state to check |
isInterruptedState(state)
Check if a state is interrupted (paused awaiting input). Signature| Name | Type | Description |
|---|---|---|
state | TaskState | Task state to check |
InvalidStateTransitionError
Thrown when attempting an invalid state transition. SignatureTaskImmutabilityError
Thrown when attempting to modify a task in a terminal state. SignatureTaskNotFoundError
Thrown when a task is not found. SignatureTaskRefinementError
Thrown when a refinement/follow-up task references invalid parent tasks. SignatureTaskManager
In-memory task manager implementing A2A task lifecycle. SignaturecreateTask()
Create a new task in the submitted state.createRefinedTask()
Create a refinement/follow-up task referencing existing task(s).getTask()
Get a task by ID.listTasks()
List tasks with optional filtering and pagination.updateTaskStatus()
Update task status. Enforces valid transitions and terminal state immutability.addArtifact()
Add an artifact to a task.addHistory()
Add a message to task history.cancelTask()
Cancel a task by transitioning to canceled state.getTasksByContext()
Get all tasks in a given context.isTerminal()
Check if a task is in a terminal state.resolveContextForReferenceTasks()
Derive a contextId from the first referenced task, if any reference tasks are provided.validateReferenceTasks()
Validate that all referenced tasks exist and share the same contextId.attachLafsEnvelope(manager, taskId, envelope)
Attach a LAFS envelope as an artifact to an A2A task. Signature| Name | Type | Description |
|---|---|---|
manager | TaskManager | TaskManager instance managing the task |
taskId | string | ID of the task to attach the envelope to |
envelope | LAFSEnvelope | LAFS envelope to attach as an artifact |
TaskEventBus
In-memory event bus for task lifecycle streaming events. SignaturepublishStatusUpdate()
Publish a task status update event.publishArtifactUpdate()
Publish a task artifact update event.publish()
Publish a task stream event to all listeners and history.subscribe()
Subscribe to events for a specific task.getHistory()
Get the full event history for a task.streamTaskEvents(bus, taskId, options)
Build an async iterator for real-time task stream events. Signature| Name | Type | Description |
|---|---|---|
bus | TaskEventBus | TaskEventBus to subscribe to |
taskId | string | ID of the task to stream events for |
options | : StreamIteratorOptions | Iterator options including timeout |
PushNotificationConfigStore
In-memory manager for async push-notification configs. Signatureset()
Store a push-notification config for a task.get()
Retrieve a push-notification config by task and config ID.list()
List all push-notification configs for a task.delete()
Delete a push-notification config.PushNotificationDispatcher
Deliver task updates to registered push-notification webhooks. Signaturedispatch()
Dispatch a task event to all registered webhooks for the task.buildHeaders()
Build HTTP headers for push notification delivery including auth tokens.TaskArtifactAssembler
Applies append/lastChunk artifact deltas into task-local snapshots. SignatureapplyUpdate()
Apply an artifact update event to the assembled snapshot.get()
Get a specific assembled artifact by task and artifact ID.list()
List all assembled artifacts for a task.mergeArtifact()
Merge a new artifact update event into an existing artifact snapshot, handling append semantics.withLastChunk()
Inject thea2a:last_chunk marker into artifact metadata.
createJsonRpcRequest(id, method, params)
Create a JSON-RPC 2.0 request object. Signature| Name | Type | Description |
|---|---|---|
id | string | number | Client-assigned request identifier |
method | string | The RPC method name to invoke |
params | : Record<string | Optional named parameters for the method call |
JsonRpcRequest object
Example
createJsonRpcResponse(id, result)
Create a JSON-RPC 2.0 success response. Signature| Name | Type | Description |
|---|---|---|
id | string | number | null | Identifier matching the originating request, or null for notifications |
result | unknown | The return value of the invoked method |
JsonRpcResponse object
Example
createJsonRpcErrorResponse(id, code, message, data)
Create a JSON-RPC 2.0 error response. Signature| Name | Type | Description |
|---|---|---|
id | string | number | null | Identifier matching the originating request, or null for notifications |
code | number | Numeric error code (standard or A2A-specific) |
message | string | Short human-readable description of the error |
data | : Record<string | Optional additional structured error data |
JsonRpcErrorResponse object
Example
createA2AErrorResponse(id, errorType, message, data)
Create an A2A-specific JSON-RPC error response by error type name. Signature| Name | Type | Description |
|---|---|---|
id | string | number | null | Identifier matching the originating request, or null for notifications |
errorType | A2AErrorType | The A2A error type name (e.g. "TaskNotFound") |
message | string | Short human-readable description of the error |
data | : Record<string | Optional additional structured error data |
JsonRpcErrorResponse with the resolved A2A error code
Example
validateJsonRpcRequest(input)
Validate the structure of a JSON-RPC request. Signature| Name | Type | Description |
|---|---|---|
input | unknown | The unknown value to validate |
valid indicating success and errors listing any violations
Example
isA2AError(code)
Check if a numeric error code is an A2A-specific error. Signature| Name | Type | Description |
|---|---|---|
code | number | The numeric JSON-RPC error code to check |
true if the code falls within the A2A error range
Example
createGrpcStatus(errorType, message, metadata)
Create a gRPC Status object for an A2A error type. Signature| Name | Type | Description |
|---|---|---|
errorType | A2AErrorType | The A2A error type name (e.g. "TaskNotFound") |
message | string | Human-readable error message |
metadata | : Record<string | Optional key-value metadata to include in the ErrorInfo detail |
GrpcStatus object with ErrorInfo details
Example
createProblemDetails(errorType, detail, extensions)
Create an RFC 9457 Problem Details object for an A2A error. Signature| Name | Type | Description |
|---|---|---|
errorType | A2AErrorType | The A2A error type name (e.g. "TaskNotFound") |
detail | string | Human-readable explanation specific to this occurrence |
extensions | : Record<string | Optional additional members to include in the response |
ProblemDetails object
Example
createLafsProblemDetails(errorType, lafsError, requestId)
Create an RFC 9457 Problem Details object bridging A2A error types with LAFS error data. Signature| Name | Type | Description |
|---|---|---|
errorType | A2AErrorType | The A2A error type name (e.g. "InvalidAgentResponse") |
lafsError | LAFSError | The LAFS error object to extract extension fields from |
requestId | : string | Optional request identifier used as the instance field |
ProblemDetails object with LAFS extension fields
Example
buildUrl(endpoint, params)
Build a URL by substituting path parameters. Signature| Name | Type | Description |
|---|---|---|
endpoint | HttpEndpoint | HTTP endpoint definition from HTTP_ENDPOINTS |
params | : Record<string | Path parameter values keyed by name (without leading colon) |
parseListTasksQuery(query)
Parse camelCase query parameters for the ListTasks endpoint. Signature| Name | Type | Description |
|---|---|---|
query | Record<string | Raw query parameter map from the HTTP request |
ListTasksQueryParams object with coerced values
Example
getErrorCodeMapping(errorType)
Get the complete error code mapping for a given A2A error type. Signature| Name | Type | Description |
|---|---|---|
errorType | A2AErrorType | The A2A error type name (e.g. "TaskNotFound") |
ErrorCodeMapping with JSON-RPC, HTTP, and gRPC codes
Throws
- Error if the error type is not a known A2A error type
parseA2AVersionHeader(headerValue)
Parse thea2a-version header into an array of version strings.
Signature
| Name | Type | Description |
|---|---|---|
headerValue | string | undefined | The raw a2a-version header value, or undefined if absent |
negotiateA2AVersion(requestedVersions)
Negotiate an A2A protocol version from the client’s requested versions. Signature| Name | Type | Description |
|---|---|---|
requestedVersions | string[] | Array of version strings requested by the client |
null if no common version exists
Example
CircuitBreakerError
Error thrown when a circuit breaker rejects a call. SignatureCircuitBreaker
Circuit breaker for protecting against cascading failures. Signatureexecute()
Execute a function with circuit breaker protection.getState()
Get the current circuit breaker state.getMetrics()
Get a snapshot of the circuit breaker’s runtime metrics.forceOpen()
Manually open the circuit breaker, rejecting all subsequent calls.forceClose()
Manually close the circuit breaker and reset all counters.onSuccess()
Records a successful call and may transition from HALF_OPEN to CLOSED.onFailure()
Records a failed call and may trip the circuit to OPEN.transitionTo()
Transitions the circuit to the given state, resetting HALF_OPEN call count when entering HALF_OPEN.shouldAttemptReset()
Returnstrue if enough time has elapsed since the last failure to attempt a reset.
scheduleReset()
Schedules a timer to transition from OPEN to HALF_OPEN after the configured reset timeout.reset()
Resets all failure/success counters and clears the pending reset timer.CircuitBreakerRegistry
Registry for managing multiple named circuit breakers. Signatureadd()
Register a new circuit breaker with the given name and configuration.get()
Retrieve a circuit breaker by name.getOrCreate()
Retrieve an existing circuit breaker or create one if it does not exist.getAllMetrics()
Collect metrics from all registered circuit breakers.resetAll()
Force-close all registered circuit breakers, resetting their counters.circuitBreakerMiddleware(config)
Create an Express middleware that wraps downstream handlers with a circuit breaker. Signature| Name | Type | Description |
|---|---|---|
config | CircuitBreakerConfig | Circuit breaker configuration for the middleware instance |
healthCheck(config)
Health check middleware for Express applications. Signature| Name | Type | Description |
|---|---|---|
config | : HealthCheckConfig | Optional health check configuration |
createDatabaseHealthCheck(config, , )
Create a health check function that verifies database connectivity. Signature| Name | Type | Description |
|---|---|---|
config | { checkConnection: ( | Database check configuration |
| “ | { checkConnection: ( | config.checkConnection - Async function returning true if the database is reachable |
| “ | { checkConnection: ( | config.name - Display name for this check in health output |
HealthCheckFunction suitable for use in HealthCheckConfig.checks
Example
createExternalServiceHealthCheck(config, , , )
Create a health check function that probes an external HTTP service. Signature| Name | Type | Description |
|---|---|---|
config | { name: string; url: string; timeout?: number; } | External service check configuration |
| “ | { name: string; url: string; timeout?: number; } | config.name - Display name for this check in health output |
| “ | { name: string; url: string; timeout?: number; } | config.url - URL to probe for health status |
| “ | { name: string; url: string; timeout?: number; } | config.timeout - Request timeout in milliseconds |
HealthCheckFunction suitable for use in HealthCheckConfig.checks
Example
livenessProbe()
Liveness probe — a minimal check confirming the process is running. SignaturereadinessProbe(config)
Readiness probe — verifies the service can accept traffic. Signature| Name | Type | Description |
|---|---|---|
config | : { checks?: HealthCheckFunction[]; } | Optional configuration with custom health check functions |
projectEnvelope(envelope, mviLevel)
Project an envelope to the declared MVI verbosity level. Signature| Name | Type | Description |
|---|---|---|
envelope | LAFSEnvelope | The full LAFS envelope to project |
mviLevel | : MVILevel | Override MVI level; falls back to envelope._meta.mvi, then 'standard' |
estimateProjectedTokens(projected)
Estimate token count for a projected envelope. Signature| Name | Type | Description |
|---|---|---|
projected | Record<string | The projected envelope object to estimate |
lafsErrorToProblemDetails(error, requestId)
Convert a LAFSError to an RFC 9457 Problem Details object. Signature| Name | Type | Description |
|---|---|---|
error | LAFSError | The LAFS error to convert |
requestId | : string | Optional request ID to set as the instance field |
LafsProblemDetails object
Example
gracefulShutdown(server, config)
Enable graceful shutdown for an HTTP server. Signature| Name | Type | Description |
|---|---|---|
server | Server | The Node.js HTTP server to manage |
config | : GracefulShutdownConfig | Optional shutdown configuration |
isShuttingDown()
Check whether a shutdown sequence is currently in progress. Signaturetrue if the server is shutting down, false otherwise
Example
getShutdownState()
Get a snapshot of the current shutdown state. SignatureShutdownState
Example
forceShutdown(exitCode)
Terminate the process immediately without waiting for connections to drain. Signature| Name | Type | Description |
|---|---|---|
exitCode | : number | Process exit code |