Skip to main content
Functions and classes exported by this package.

parseExtensionsHeader(headerValue)

Parse A2A-Extensions header value into URI array. Signature
Parameters Returns — Array of trimmed extension URI strings Example

negotiateExtensions(requestedUris, agentExtensions)

Negotiate extensions between client-requested and agent-declared sets. Signature
Parameters Returns — Negotiation result with activated, unsupported, and missing required sets Example

formatExtensionsHeader(activatedUris)

Format activated extension URIs into header value. Signature
Parameters Returns — Comma-separated header value string Example

buildLafsExtension(options)

Build an A2A AgentExtension object declaring LAFS support. Signature
Parameters Returns — A2A AgentExtension object ready for inclusion in an Agent Card Example

buildExtension(options)

Build a generic A2A AgentExtension object. Signature
Parameters Returns — A2A AgentExtension object Example

isValidExtensionKind(kind)

Check whether a string is a valid extension kind. Signature
Parameters Returns — True if the value is a recognized ExtensionKind Example

validateExtensionDeclaration(extension)

Validate an A2A extension declaration for correctness. Signature
Parameters Returns — Object with valid boolean and optional error message Example

ExtensionSupportRequiredError

Error thrown when required A2A extensions are not supported by the client. Signature
Methods

toJSONRPCError()

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
Parameters Returns — Express RequestHandler that performs extension negotiation Example

discoveryMiddleware(config, options)

Create Express middleware for serving A2A Agent Card. Signature
Parameters Returns — Express RequestHandler that serves the Agent Card Example

discoveryFastifyPlugin(fastify, options)

Fastify plugin for A2A Agent Card discovery. Signature
Parameters Returns — Promise that resolves when the plugin is registered Example

TokenEstimator

Character-based token estimator for JSON payloads. Signature
Example
Methods

estimate()

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
Parameters Returns — Estimated token count Example

estimateTokensJSON(json, options)

Convenience function to estimate tokens from a JSON string. Signature
Parameters Returns — Estimated token count Example

isMVILevel(value)

Type guard that checks whether an unknown value is a valid MVILevel. Signature
Parameters Returnstrue if value is one of the recognised MVI level strings. Example

isAgentAction(value)

Type guard that checks whether an unknown value is a valid LAFSAgentAction. Signature
Parameters Returnstrue if value is one of the recognised agent action strings. Example

applyBudgetEnforcement(envelope, budget, options)

Apply budget enforcement to an envelope. Signature
Parameters Returns — Enforcement result with the (possibly modified) envelope, budget status, and token estimates Example

withBudget(budget, options)

Create a budget enforcement middleware function. Signature
Parameters Returns — Async middleware function that enforces the token budget Example

checkBudget(envelope, budget)

Check if an envelope has exceeded its budget without modifying it. Signature
Parameters Returns — Object with exceeded flag, estimated token count, and remaining budget Example

withBudgetSync(budget, options)

Synchronous version of withBudget for non-async contexts. Signature
Parameters Returns — Synchronous middleware function that enforces the token budget Example

wrapWithBudget(handler, handler, budget, options)

Higher-order function that wraps a handler with budget enforcement. Signature
Parameters Returns — Wrapped handler with budget enforcement Example

composeMiddleware(middlewares)

Compose multiple middleware functions into a single middleware. Signature
Parameters Returns — A single middleware function that chains all provided middlewares Example

getConformanceProfiles()

Loads the conformance profiles from the bundled JSON schema. Signature
Returns — The full ConformanceProfiles object. Example

getChecksForTier(tier)

Returns the list of check names that belong to the given conformance tier. Signature
Parameters Returns — An array of check name strings for the specified tier. Example

validateConformanceProfiles(availableChecks)

Validates that the conformance profiles are internally consistent and reference only known checks. Signature
Parameters Returns — An object with valid (true when no errors) and an errors array of diagnostic strings. Example

getErrorRegistry()

Loads the full LAFS error registry from the bundled JSON. Signature
Returns — The complete error registry with version and all registered codes. Example

isRegisteredErrorCode(code)

Checks whether a given error code exists in the LAFS error registry. Signature
Parameters Returnstrue if the code is registered, false otherwise. Example

getRegistryCode(code)

Retrieves the full registry entry for a given error code. Signature
Parameters Returns — The matching RegistryCode or undefined if not found. Example

getAgentAction(code)

Returns the default agent action for a given error code. Signature
Parameters Returns — The LAFSAgentAction or undefined if unavailable. Example

getTypeUri(code)

Returns the RFC 9457 type URI for a given error code. Signature
Parameters Returns — The type URI string or undefined if unavailable. Example

getDocUrl(code)

Returns the documentation URL for a given error code. Signature
Parameters Returns — The documentation URL string or undefined if unavailable. Example

getTransportMapping(code, transport)

Resolves the transport-specific status value for a given error code and transport. Signature
Parameters Returns — A TransportMapping or null if the code is unregistered. Example

LAFSFlagError

Error thrown when LAFS flag validation fails. Signature

resolveOutputFormat(input)

Resolve the output format from flag inputs using the LAFS precedence chain. Signature
Parameters Returns — The resolved format, its source layer, and quiet mode status Throws
  • LAFSFlagError When humanFlag and jsonFlag are both truthy.
Example

isNativeAvailable()

Check if the native addon is available. Signature
Returnstrue if the native Rust binding was loaded successfully.

getNativeModule()

Get the native module, or null if unavailable. Signature
Returns — The loaded native module, or null for AJV fallback.

validateEnvelope(input)

Validates an unknown input against the LAFS envelope JSON Schema (Draft-07). Signature
Parameters Returns — An EnvelopeValidationResult with validity status and any errors. Example

assertEnvelope(input)

Validates input and throws on schema failure, returning a typed envelope on success. Signature
Parameters Returns — The input cast to LAFSEnvelope when schema validation passes. Throws
  • Error When the input does not conform to the envelope schema.
Example

runEnvelopeConformance(envelope, options)

Runs the full suite of LAFS envelope conformance checks. Signature
Parameters Returns — A 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
Parameters Returns — A ConformanceReport with individual check results and an overall pass/fail. Example

ComplianceError

Error thrown when assertCompliance or withCompliance detects failures. Signature
Example

enforceCompliance(input, options)

Runs the full LAFS compliance pipeline against an unknown input value. Signature
Parameters Returns — A ComplianceResult with the aggregate pass/fail status and per-stage reports. Example

assertCompliance(input, options)

Validates input and throws ComplianceError on any failure. Signature
Parameters Returns — The validated LAFSEnvelope when all stages pass. Throws
  • ComplianceError When any compliance stage fails.
Example

withCompliance(producer, options)

Wraps an envelope-producing function with automatic compliance enforcement. Signature
Parameters Returns — An async function with the same signature that enforces compliance on every call. Example

createComplianceMiddleware(options)

Creates a ComplianceMiddleware that enforces LAFS compliance on the next handler’s output. Signature
Parameters Returns — A middleware function that validates the downstream envelope. Example

getDeprecationRegistry()

Retrieve all registered deprecation entries. Signature
Returns — Array of all DeprecationEntry rules in the registry Example

detectDeprecatedEnvelopeFields(envelope)

Detect deprecated field usage in a LAFS envelope. Signature
Parameters Returns — Array of Warning objects for each detected deprecation Example

emitDeprecationWarnings(envelope)

Emit deprecation warnings by attaching them to the envelope metadata. Signature
Parameters Returns — A new envelope with deprecation warnings appended to _meta.warnings Example

createEnvelope(input)

Create a fully validated LAFS envelope from a success or error input. Signature
Parameters Returns — A complete LAFSEnvelope ready for serialization. Example

LafsError

Error subclass that carries the full LAFSError payload. Signature
Example

parseLafsResponse(input, options)

Parse and unwrap a raw LAFS envelope, returning the result or throwing on error. Signature
Parameters Returns — The 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 requireRegisteredErrorCode is true and the code is unregistered.
Example

resolveFieldExtraction(input)

Resolve field extraction flags into a validated configuration. Signature
Parameters Returns — The resolved extraction configuration with mvi level and source Throws
  • LAFSFlagError When both fieldFlag and fieldsFlag are set.
Example

extractFieldFromResult(result, field)

Extract a named field from a LAFS result object. Signature
Parameters Returns — The extracted value, or undefined if not found at any level Example

extractFieldFromEnvelope(envelope, field)

Extract a named field from an envelope’s result. Signature
Parameters Returns — The extracted value, or undefined if not found Example

applyFieldFilter(envelope, fields)

Filter result fields in a LAFS envelope to the requested subset. Signature
Parameters Returns — A new envelope with the filtered result and _meta.mvi set to 'custom' Example

resolveFlags(input)

Resolve all flags across both layers and validate cross-layer semantics. Signature
Parameters Returns — The unified resolution containing format, fields, and any cross-layer warnings Throws
  • LAFSFlagError When format or field layer flags conflict.
Example

LafsA2AResult

Wrapper for A2A responses with LAFS envelope support. Signature
Methods

getA2AResult()

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 its kind 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
Parameters Returns — A2A Artifact containing the envelope as a DataPart Example

createTextArtifact(text, name)

Create a text artifact. Signature
Parameters Returns — A2A Artifact containing the text as a TextPart Example

createFileArtifact(fileUrl, mediaType, filename)

Create a file artifact. Signature
Parameters Returns — A2A Artifact containing the file reference as a FilePart Example

isExtensionRequired(agentCard, extensionUri)

Check if an extension is required in an Agent Card. Signature
Parameters Returns — True if the extension is declared as required Example

getExtensionParams(agentCard, extensionUri)

Get extension parameters from an Agent Card. Signature
Parameters Returns — The extension’s params object, or undefined if not found Example

isValidTransition(from, to)

Check if a transition from one state to another is valid. Signature
Parameters Returns — True if the transition is allowed by the state machine Example

isTerminalState(state)

Check if a state is terminal (no further transitions allowed). Signature
Parameters Returns — True if the state is terminal Example

isInterruptedState(state)

Check if a state is interrupted (paused awaiting input). Signature
Parameters Returns — True if the state indicates the task is waiting for external input Example

InvalidStateTransitionError

Thrown when attempting an invalid state transition. Signature

TaskImmutabilityError

Thrown when attempting to modify a task in a terminal state. Signature

TaskNotFoundError

Thrown when a task is not found. Signature

TaskRefinementError

Thrown when a refinement/follow-up task references invalid parent tasks. Signature

TaskManager

In-memory task manager implementing A2A task lifecycle. Signature
Methods

createTask()

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
Parameters Returns — Deep clone of the updated task with the new artifact Example

TaskEventBus

In-memory event bus for task lifecycle streaming events. Signature
Methods

publishStatusUpdate()

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
Parameters Returns — Async generator yielding task stream events Example

PushNotificationConfigStore

In-memory manager for async push-notification configs. Signature
Methods

set()

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. Signature
Methods

dispatch()

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. Signature
Methods

applyUpdate()

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 the a2a:last_chunk marker into artifact metadata.

createJsonRpcRequest(id, method, params)

Create a JSON-RPC 2.0 request object. Signature
Parameters Returns — A fully formed JsonRpcRequest object Example

createJsonRpcResponse(id, result)

Create a JSON-RPC 2.0 success response. Signature
Parameters Returns — A fully formed JsonRpcResponse object Example

createJsonRpcErrorResponse(id, code, message, data)

Create a JSON-RPC 2.0 error response. Signature
Parameters Returns — A fully formed JsonRpcErrorResponse object Example

createA2AErrorResponse(id, errorType, message, data)

Create an A2A-specific JSON-RPC error response by error type name. Signature
Parameters Returns — A fully formed JsonRpcErrorResponse with the resolved A2A error code Example

validateJsonRpcRequest(input)

Validate the structure of a JSON-RPC request. Signature
Parameters Returns — An object with valid indicating success and errors listing any violations Example

isA2AError(code)

Check if a numeric error code is an A2A-specific error. Signature
Parameters Returnstrue 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
Parameters Returns — A fully formed GrpcStatus object with ErrorInfo details Example

createProblemDetails(errorType, detail, extensions)

Create an RFC 9457 Problem Details object for an A2A error. Signature
Parameters Returns — A fully formed ProblemDetails object Example

createLafsProblemDetails(errorType, lafsError, requestId)

Create an RFC 9457 Problem Details object bridging A2A error types with LAFS error data. Signature
Parameters Returns — A ProblemDetails object with LAFS extension fields Example

buildUrl(endpoint, params)

Build a URL by substituting path parameters. Signature
Parameters Returns — The resolved URL path string with parameters substituted Example

parseListTasksQuery(query)

Parse camelCase query parameters for the ListTasks endpoint. Signature
Parameters Returns — A typed ListTasksQueryParams object with coerced values Example

getErrorCodeMapping(errorType)

Get the complete error code mapping for a given A2A error type. Signature
Parameters Returns — The ErrorCodeMapping with JSON-RPC, HTTP, and gRPC codes Throws
  • Error if the error type is not a known A2A error type
Example

parseA2AVersionHeader(headerValue)

Parse the a2a-version header into an array of version strings. Signature
Parameters Returns — An array of version strings extracted from the header Example

negotiateA2AVersion(requestedVersions)

Negotiate an A2A protocol version from the client’s requested versions. Signature
Parameters Returns — The negotiated version string, or null if no common version exists Example

CircuitBreakerError

Error thrown when a circuit breaker rejects a call. Signature
Example

CircuitBreaker

Circuit breaker for protecting against cascading failures. Signature
Example
Methods

execute()

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()

Returns true 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. Signature
Example
Methods

add()

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
Parameters Returns — An Express-compatible middleware function Example

healthCheck(config)

Health check middleware for Express applications. Signature
Parameters Returns — An Express-compatible middleware function that serves the health endpoint Example

createDatabaseHealthCheck(config, , )

Create a health check function that verifies database connectivity. Signature
Parameters Returns — A HealthCheckFunction suitable for use in HealthCheckConfig.checks Example

createExternalServiceHealthCheck(config, , , )

Create a health check function that probes an external HTTP service. Signature
Parameters Returns — A HealthCheckFunction suitable for use in HealthCheckConfig.checks Example

livenessProbe()

Liveness probe — a minimal check confirming the process is running. Signature
Returns — An Express-compatible middleware function Example

readinessProbe(config)

Readiness probe — verifies the service can accept traffic. Signature
Parameters Returns — An Express-compatible async middleware function Example

projectEnvelope(envelope, mviLevel)

Project an envelope to the declared MVI verbosity level. Signature
Parameters Returns — A plain object containing only the fields appropriate for the resolved MVI level Example

estimateProjectedTokens(projected)

Estimate token count for a projected envelope. Signature
Parameters Returns — The estimated token count based on JSON serialization length Example

lafsErrorToProblemDetails(error, requestId)

Convert a LAFSError to an RFC 9457 Problem Details object. Signature
Parameters Returns — An RFC 9457-compliant LafsProblemDetails object Example

gracefulShutdown(server, config)

Enable graceful shutdown for an HTTP server. Signature
Parameters Example

isShuttingDown()

Check whether a shutdown sequence is currently in progress. Signature
Returnstrue if the server is shutting down, false otherwise Example

getShutdownState()

Get a snapshot of the current shutdown state. Signature
Returns — A copy of the current ShutdownState Example

forceShutdown(exitCode)

Terminate the process immediately without waiting for connections to drain. Signature
Parameters Example

shutdownMiddleware()

Express middleware that rejects requests with 503 while the server is shutting down. Signature
Returns — An Express-compatible middleware function Example

waitForShutdown()

Wait until a shutdown sequence begins. Signature
Returns — A promise that resolves when shutdown has started Example