parseExtensionsHeader(headerValue)
Parse A2A-Extensions header value into URI array. Signature
Returns — Array of trimmed extension URI strings
Example
negotiateExtensions(requestedUris, agentExtensions)
Negotiate extensions between client-requested and agent-declared sets. Signature
Returns — Negotiation result with activated, unsupported, and missing required sets
Example
formatExtensionsHeader(activatedUris)
Format activated extension URIs into header value. Signature
Returns — Comma-separated header value string
Example
buildLafsExtension(options)
Build an A2A AgentExtension object declaring LAFS support. Signature
Returns — A2A AgentExtension object ready for inclusion in an Agent Card
Example
buildExtension(options)
Build a generic A2A AgentExtension object. Signature
Returns — A2A AgentExtension object
Example
isValidExtensionKind(kind)
Check whether a string is a valid extension kind. Signature
Returns — True if the value is a recognized ExtensionKind
Example
validateExtensionDeclaration(extension)
Validate an A2A extension declaration for correctness. Signature
Returns — Object with
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
Returns — Express RequestHandler that performs extension negotiation
Example
discoveryMiddleware(config, options)
Create Express middleware for serving A2A Agent Card. Signature
Returns — Express RequestHandler that serves the Agent Card
Example
discoveryFastifyPlugin(fastify, options)
Fastify plugin for A2A Agent Card discovery. Signature
Returns — Promise that resolves when the plugin is registered
Example
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
Returns — Estimated token count
Example
estimateTokensJSON(json, options)
Convenience function to estimate tokens from a JSON string. Signature
Returns — Estimated token count
Example
isMVILevel(value)
Type guard that checks whether an unknown value is a validMVILevel.
Signature
Returns —
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
Returns —
true if value is one of the recognised agent action strings.
Example
applyBudgetEnforcement(envelope, budget, options)
Apply budget enforcement to an envelope. Signature
Returns — Enforcement result with the (possibly modified) envelope, budget status, and token estimates
Example
withBudget(budget, options)
Create a budget enforcement middleware function. Signature
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
Returns — Object with
exceeded flag, estimated token count, and remaining budget
Example
withBudgetSync(budget, options)
Synchronous version of withBudget for non-async contexts. Signature
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
Returns — Wrapped handler with budget enforcement
Example
composeMiddleware(middlewares)
Compose multiple middleware functions into a single middleware. Signature
Returns — A single middleware function that chains all provided middlewares
Example
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
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
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. SignatureisRegisteredErrorCode(code)
Checks whether a given error code exists in the LAFS error registry. Signature
Returns —
true if the code is registered, false otherwise.
Example
getRegistryCode(code)
Retrieves the full registry entry for a given error code. Signature
Returns — The matching
RegistryCode or undefined if not found.
Example
getAgentAction(code)
Returns the default agent action for a given error code. Signature
Returns — The
LAFSAgentAction or undefined if unavailable.
Example
getTypeUri(code)
Returns the RFC 9457 type URI for a given error code. Signature
Returns — The type URI string or
undefined if unavailable.
Example
getDocUrl(code)
Returns the documentation URL for a given error code. Signature
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
Returns — A
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
Returns — The resolved format, its source layer, and quiet mode status
Throws
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
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
Returns — The input cast to
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
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
Returns — A
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
Returns — A
ComplianceResult with the aggregate pass/fail status and per-stage reports.
Example
assertCompliance(input, options)
Validates input and throwsComplianceError on any failure.
Signature
Returns — The validated
LAFSEnvelope when all stages pass.
Throws
ComplianceErrorWhen any compliance stage fails.
withCompliance(producer, options)
Wraps an envelope-producing function with automatic compliance enforcement. Signature
Returns — An async function with the same signature that enforces compliance on every call.
Example
createComplianceMiddleware(options)
Creates aComplianceMiddleware that enforces LAFS compliance on the next handler’s output.
Signature
Returns — A middleware function that validates the downstream envelope.
Example
getDeprecationRegistry()
Retrieve all registered deprecation entries. SignatureDeprecationEntry rules in the registry
Example
detectDeprecatedEnvelopeFields(envelope)
Detect deprecated field usage in a LAFS envelope. Signature
Returns — Array of
Warning objects for each detected deprecation
Example
emitDeprecationWarnings(envelope)
Emit deprecation warnings by attaching them to the envelope metadata. Signature
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
Returns — A complete
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
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
requireRegisteredErrorCodeistrueand the code is unregistered.
resolveFieldExtraction(input)
Resolve field extraction flags into a validated configuration. Signature
Returns — The resolved extraction configuration with mvi level and source
Throws
LAFSFlagErrorWhen bothfieldFlagandfieldsFlagare set.
extractFieldFromResult(result, field)
Extract a named field from a LAFS result object. Signature
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
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
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
Returns — The unified resolution containing format, fields, and any cross-layer warnings
Throws
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
Returns — A2A Artifact containing the envelope as a DataPart
Example
createTextArtifact(text, name)
Create a text artifact. Signature
Returns — A2A Artifact containing the text as a TextPart
Example
createFileArtifact(fileUrl, mediaType, filename)
Create a file artifact. Signature
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
Returns — True if the extension is declared as required
Example
getExtensionParams(agentCard, extensionUri)
Get extension parameters from an Agent Card. Signature
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
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
Returns — True if the state is terminal
Example
isInterruptedState(state)
Check if a state is interrupted (paused awaiting input). Signature
Returns — True if the state indicates the task is waiting for external input
Example
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
Returns — Deep clone of the updated task with the new artifact
Example
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
Returns — Async generator yielding task stream events
Example
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
Returns — A fully formed
JsonRpcRequest object
Example
createJsonRpcResponse(id, result)
Create a JSON-RPC 2.0 success response. Signature
Returns — A fully formed
JsonRpcResponse object
Example
createJsonRpcErrorResponse(id, code, message, data)
Create a JSON-RPC 2.0 error response. Signature
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
Returns — A fully formed
JsonRpcErrorResponse with the resolved A2A error code
Example
validateJsonRpcRequest(input)
Validate the structure of a JSON-RPC request. Signature
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
Returns —
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
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
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
Returns — A
ProblemDetails object with LAFS extension fields
Example
buildUrl(endpoint, params)
Build a URL by substituting path parameters. Signature
Returns — The resolved URL path string with parameters substituted
Example
parseListTasksQuery(query)
Parse camelCase query parameters for the ListTasks endpoint. Signature
Returns — A typed
ListTasksQueryParams object with coerced values
Example
getErrorCodeMapping(errorType)
Get the complete error code mapping for a given A2A error type. Signature
Returns — The
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
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
Returns — The negotiated version string, or
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
Returns — An Express-compatible middleware function
Example
healthCheck(config)
Health check middleware for Express applications. Signature
Returns — An Express-compatible middleware function that serves the health endpoint
Example
createDatabaseHealthCheck(config, , )
Create a health check function that verifies database connectivity. Signature
Returns — A
HealthCheckFunction suitable for use in HealthCheckConfig.checks
Example
createExternalServiceHealthCheck(config, , , )
Create a health check function that probes an external HTTP service. Signature
Returns — A
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
Returns — An Express-compatible async middleware function
Example
projectEnvelope(envelope, mviLevel)
Project an envelope to the declared MVI verbosity level. Signature
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
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
Returns — An RFC 9457-compliant
LafsProblemDetails object
Example
gracefulShutdown(server, config)
Enable graceful shutdown for an HTTP server. Signature
Example
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
Example