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

parseExtensionsHeader(headerValue)

Parse A2A-Extensions header value into URI array. Signature
(headerValue: string | undefined) => string[]
Parameters
NameTypeDescription
headerValuestring | undefinedRaw header value string, or undefined if absent
Returns — Array of trimmed extension URI strings Example
const uris = parseExtensionsHeader('https://lafs.dev/ext/v1, https://example.com/ext');
// => ['https://lafs.dev/ext/v1', 'https://example.com/ext']

negotiateExtensions(requestedUris, agentExtensions)

Negotiate extensions between client-requested and agent-declared sets. Signature
(requestedUris: string[], agentExtensions: AgentExtension[]) => ExtensionNegotiationResult
Parameters
NameTypeDescription
requestedUrisstring[]Extension URIs requested by the client
agentExtensionsAgentExtension[]Extensions declared in the agent’s Agent Card
Returns — Negotiation result with activated, unsupported, and missing required sets Example
const result = negotiateExtensions(
  ['https://lafs.dev/extensions/envelope/v1'],
  agentCard.capabilities.extensions,
);
if (result.missingRequired.length > 0) {
  throw new ExtensionSupportRequiredError(result.missingRequired);
}

formatExtensionsHeader(activatedUris)

Format activated extension URIs into header value. Signature
(activatedUris: string[]) => string
Parameters
NameTypeDescription
activatedUrisstring[]Extension URIs that were successfully negotiated
Returns — Comma-separated header value string Example
res.setHeader('A2A-Extensions', formatExtensionsHeader(result.activated));

buildLafsExtension(options)

Build an A2A AgentExtension object declaring LAFS support. Signature
(options?: BuildLafsExtensionOptions) => AgentExtension
Parameters
NameTypeDescription
options: BuildLafsExtensionOptionsConfiguration options for the LAFS extension declaration
Returns — A2A AgentExtension object ready for inclusion in an Agent Card Example
const ext = buildLafsExtension({ required: true, supportsTokenBudgets: true });
agentCard.capabilities.extensions.push(ext);

buildExtension(options)

Build a generic A2A AgentExtension object. Signature
(options: BuildExtensionOptions) => AgentExtension
Parameters
NameTypeDescription
optionsBuildExtensionOptionsConfiguration for the extension declaration
Returns — A2A AgentExtension object Example
const ext = buildExtension({
  uri: 'https://example.com/ext/v1',
  description: 'Custom extension',
  kind: 'data-only',
});

isValidExtensionKind(kind)

Check whether a string is a valid extension kind. Signature
(kind: string) => kind is ExtensionKind
Parameters
NameTypeDescription
kindstringString value to validate
Returns — True if the value is a recognized ExtensionKind Example
if (isValidExtensionKind(userInput)) {
  // userInput is now typed as ExtensionKind
}

validateExtensionDeclaration(extension)

Validate an A2A extension declaration for correctness. Signature
(extension: AgentExtension) => { valid: boolean; error?: string; }
Parameters
NameTypeDescription
extensionAgentExtensionThe AgentExtension to validate
Returns — Object with valid boolean and optional error message Example
const { valid, error } = validateExtensionDeclaration(ext);
if (!valid) {
  console.error('Invalid extension:', error);
}

ExtensionSupportRequiredError

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

toJSONRPCError()

Convert to JSON-RPC error object.
() => { code: number; message: string; data: Record<string, unknown>; }

toProblemDetails()

Convert to RFC 9457 Problem Details object with agent-actionable fields.
() => Record<string, unknown> & { agentAction: string; }

toLafsError()

Convert to a LAFSError-compatible object.
() => { code: string; message: string; category: "CONTRACT"; retryable: boolean; retryAfterMs: null; details: Record<string, unknown>; }

extensionNegotiationMiddleware(options)

Express middleware for A2A extension negotiation. Signature
(options: ExtensionNegotiationMiddlewareOptions) => RequestHandler
Parameters
NameTypeDescription
optionsExtensionNegotiationMiddlewareOptionsMiddleware configuration with extensions and enforcement settings
Returns — Express RequestHandler that performs extension negotiation Example
app.use(extensionNegotiationMiddleware({
  extensions: agentCard.capabilities.extensions,
  enforceRequired: true,
}));

discoveryMiddleware(config, options)

Create Express middleware for serving A2A Agent Card. Signature
(config: DiscoveryConfig, options?: DiscoveryMiddlewareOptions) => RequestHandler
Parameters
NameTypeDescription
configDiscoveryConfigDiscovery configuration (A2A v1.0 format)
options: DiscoveryMiddlewareOptionsMiddleware options for path routing and caching
Returns — Express RequestHandler that serves the Agent Card Example
import express from "express";
import { discoveryMiddleware } from "@cleocode/lafs/discovery";

const app = express();

app.use(discoveryMiddleware({
  agent: {
    name: "my-lafs-agent",
    description: "A LAFS-compliant agent with A2A support",
    version: "1.0.0",
    url: "https://api.example.com",
    capabilities: {
      streaming: true,
      pushNotifications: false,
      extensions: []
    },
    defaultInputModes: ["application/json", "text/plain"],
    defaultOutputModes: ["application/json"],
    skills: [
      {
        id: "envelope-processor",
        name: "Envelope Processor",
        description: "Process LAFS envelopes",
        tags: ["lafs", "envelope", "validation"],
        examples: ["Validate this envelope", "Process envelope data"]
      }
    ]
  }
}));

discoveryFastifyPlugin(fastify, options)

Fastify plugin for A2A Agent Card discovery. Signature
(fastify: unknown, options: { config: DiscoveryConfig; path?: string; }) => Promise<void>
Parameters
NameTypeDescription
fastifyunknownFastify instance
options{ config: DiscoveryConfig; path?: string; }Plugin options containing config and optional path
Returns — Promise that resolves when the plugin is registered Example
import Fastify from "fastify";
import { discoveryFastifyPlugin } from "@cleocode/lafs/discovery";

const app = Fastify();
app.register(discoveryFastifyPlugin, {
  config: { agent: { name: "my-agent", ... } },
});

TokenEstimator

Character-based token estimator for JSON payloads. Signature
typeof TokenEstimator
Example
const estimator = new TokenEstimator({ charsPerToken: 4 });
const tokens = estimator.estimate({ name: "hello", items: [1, 2, 3] });
Methods

estimate()

Estimate tokens for any JavaScript value. Handles circular references, nested objects, arrays, and Unicode.
(value: unknown) => number

estimateJSON()

Estimate tokens from a JSON string. More efficient if you already have the JSON string.
(json: string) => number

estimateWithTracking()

Internal recursive estimation with circular reference tracking.
(value: unknown, seen: WeakSet<object>, depth: number) => number

estimateArray()

Estimate tokens for an array.
(arr: unknown[], seen: WeakSet<object>, depth: number) => number

estimateObject()

Estimate tokens for a plain object.
(obj: Record<string, unknown>, seen: WeakSet<object>, depth: number) => number

canSerialize()

Check if a value can be safely serialized (no circular refs).
(value: unknown) => boolean

safeStringify()

Serialize a value to JSON with circular reference handling.
(value: unknown) => string

safeCopy()

Create a deep copy of a value with circular refs replaced by "[Circular]".
<T>(value: T) => T

estimateTokens(value, options)

Convenience function to estimate tokens for a value. Signature
(value: unknown, options?: TokenEstimatorOptions) => number
Parameters
NameTypeDescription
valueunknownAny JavaScript value to estimate
options: TokenEstimatorOptionsOptional estimator configuration overrides
Returns — Estimated token count Example
const tokens = estimateTokens({ data: [1, 2, 3] });

estimateTokensJSON(json, options)

Convenience function to estimate tokens from a JSON string. Signature
(json: string, options?: TokenEstimatorOptions) => number
Parameters
NameTypeDescription
jsonstringPre-serialized JSON string
options: TokenEstimatorOptionsOptional estimator configuration overrides
Returns — Estimated token count Example
const tokens = estimateTokensJSON('{"key": "value"}');

isMVILevel(value)

Type guard that checks whether an unknown value is a valid MVILevel. Signature
(value: unknown) => value is MVILevel
Parameters
NameTypeDescription
valueunknownThe value to test.
Returnstrue if value is one of the recognised MVI level strings. Example
const level: unknown = 'minimal';
if (isMVILevel(level)) {
  // level is narrowed to MVILevel
}

isAgentAction(value)

Type guard that checks whether an unknown value is a valid LAFSAgentAction. Signature
(value: unknown) => value is LAFSAgentAction
Parameters
NameTypeDescription
valueunknownThe value to test.
Returnstrue if value is one of the recognised agent action strings. Example
const action: unknown = 'retry';
if (isAgentAction(action)) {
  // action is narrowed to LAFSAgentAction
}

applyBudgetEnforcement(envelope, budget, options)

Apply budget enforcement to an envelope. Signature
(envelope: LAFSEnvelope, budget: number, options?: BudgetEnforcementOptions) => BudgetEnforcementResult
Parameters
NameTypeDescription
envelopeLAFSEnvelopeThe LAFS envelope to check
budgetnumberMaximum allowed token count
options: BudgetEnforcementOptionsBudget enforcement options (truncation, callbacks)
Returns — Enforcement result with the (possibly modified) envelope, budget status, and token estimates Example
const result = applyBudgetEnforcement(envelope, 1000, { truncateOnExceed: true });
if (!result.withinBudget) {
  console.warn("Budget exceeded:", result.estimatedTokens);
}

withBudget(budget, options)

Create a budget enforcement middleware function. Signature
(budget: number, options?: BudgetEnforcementOptions) => EnvelopeMiddleware
Parameters
NameTypeDescription
budgetnumberMaximum allowed token count for the response
options: BudgetEnforcementOptionsBudget enforcement options (truncation, callbacks)
Returns — Async middleware function that enforces the token budget Example
const middleware = withBudget(1000, { truncateOnExceed: true });
const result = await middleware(envelope, async () => nextEnvelope);

checkBudget(envelope, budget)

Check if an envelope has exceeded its budget without modifying it. Signature
(envelope: LAFSEnvelope, budget: number) => { exceeded: boolean; estimated: number; remaining: number; }
Parameters
NameTypeDescription
envelopeLAFSEnvelopeThe LAFS envelope to check
budgetnumberMaximum allowed token count
Returns — Object with exceeded flag, estimated token count, and remaining budget Example
const { exceeded, estimated, remaining } = checkBudget(envelope, 500);
if (exceeded) {
  console.warn(`Over budget by ${estimated - 500} tokens`);
}

withBudgetSync(budget, options)

Synchronous version of withBudget for non-async contexts. Signature
(budget: number, options?: BudgetEnforcementOptions) => (envelope: LAFSEnvelope, next: () => LAFSEnvelope) => LAFSEnvelope
Parameters
NameTypeDescription
budgetnumberMaximum allowed token count for the response
options: BudgetEnforcementOptionsBudget enforcement options (truncation, callbacks)
Returns — Synchronous middleware function that enforces the token budget Example
const middleware = withBudgetSync(500);
const result = middleware(envelope, () => nextEnvelope);

wrapWithBudget(handler, handler, budget, options)

Higher-order function that wraps a handler with budget enforcement. Signature
<TArgs extends unknown[], TResult extends LAFSEnvelope>(handler: (...args: TArgs) => TResult | Promise<TResult>, budget: number, options?: BudgetEnforcementOptions) => (...args: TArgs) => Promise<LAFSEnvelope>
Parameters
NameTypeDescription
handler(...args: TArgsThe handler function to wrap
handler(...args: TArgsThe handler function to wrap with budget enforcement
budgetnumberMaximum allowed tokens
options: BudgetEnforcementOptionsBudget enforcement options
Returns — Wrapped handler with budget enforcement Example
const myHandler = async (request: Request) => ({ success: true, result: { data } });
const budgetedHandler = wrapWithBudget(myHandler, 1000, { truncateOnExceed: true });
const result = await budgetedHandler(request);

composeMiddleware(middlewares)

Compose multiple middleware functions into a single middleware. Signature
(...middlewares: EnvelopeMiddleware[]) => EnvelopeMiddleware
Parameters
NameTypeDescription
middlewaresEnvelopeMiddleware[]Middleware functions to compose (executed left to right)
Returns — A single middleware function that chains all provided middlewares Example
const pipeline = composeMiddleware(
  withBudget(1000),
  loggingMiddleware,
);
const result = await pipeline(envelope, () => finalEnvelope);

getConformanceProfiles()

Loads the conformance profiles from the bundled JSON schema. Signature
() => ConformanceProfiles
Returns — The full ConformanceProfiles object. Example
const profiles = getConformanceProfiles();
console.log(profiles.tiers.core);

getChecksForTier(tier)

Returns the list of check names that belong to the given conformance tier. Signature
(tier: ConformanceTier) => string[]
Parameters
NameTypeDescription
tierConformanceTierThe conformance tier to retrieve checks for.
Returns — An array of check name strings for the specified tier. Example
const coreChecks = getChecksForTier('core');

validateConformanceProfiles(availableChecks)

Validates that the conformance profiles are internally consistent and reference only known checks. Signature
(availableChecks: string[]) => { valid: boolean; errors: string[]; }
Parameters
NameTypeDescription
availableChecksstring[]The full list of check names implemented by the conformance runner.
Returns — An object with valid (true when no errors) and an errors array of diagnostic strings. Example
const result = validateConformanceProfiles(['envelope_schema_valid', 'envelope_invariants']);
if (!result.valid) {
  console.error(result.errors);
}

getErrorRegistry()

Loads the full LAFS error registry from the bundled JSON. Signature
() => ErrorRegistry
Returns — The complete error registry with version and all registered codes. Example
const registry = getErrorRegistry();
console.log(registry.version, registry.codes.length);

isRegisteredErrorCode(code)

Checks whether a given error code exists in the LAFS error registry. Signature
(code: string) => boolean
Parameters
NameTypeDescription
codestringThe error code string to look up (e.g., "E_FORMAT_CONFLICT").
Returnstrue if the code is registered, false otherwise. Example
isRegisteredErrorCode('E_FORMAT_CONFLICT'); // true
isRegisteredErrorCode('E_UNKNOWN');         // false

getRegistryCode(code)

Retrieves the full registry entry for a given error code. Signature
(code: string) => RegistryCode | undefined
Parameters
NameTypeDescription
codestringThe error code string to look up.
Returns — The matching RegistryCode or undefined if not found. Example
const entry = getRegistryCode('E_FORMAT_CONFLICT');
if (entry) {
  console.log(entry.httpStatus); // 409
}

getAgentAction(code)

Returns the default agent action for a given error code. Signature
(code: string) => LAFSAgentAction | undefined
Parameters
NameTypeDescription
codestringThe error code string to look up.
Returns — The LAFSAgentAction or undefined if unavailable. Example
const action = getAgentAction('E_RATE_LIMIT');
console.log(action); // "retry"

getTypeUri(code)

Returns the RFC 9457 type URI for a given error code. Signature
(code: string) => string | undefined
Parameters
NameTypeDescription
codestringThe error code string to look up.
Returns — The type URI string or undefined if unavailable. Example
const uri = getTypeUri('E_VALIDATION');
// "https://lafs.dev/errors/E_VALIDATION"

getDocUrl(code)

Returns the documentation URL for a given error code. Signature
(code: string) => string | undefined
Parameters
NameTypeDescription
codestringThe error code string to look up.
Returns — The documentation URL string or undefined if unavailable. Example
const url = getDocUrl('E_VALIDATION');
// "https://lafs.dev/docs/errors/E_VALIDATION"

getTransportMapping(code, transport)

Resolves the transport-specific status value for a given error code and transport. Signature
(code: string, transport: "http" | "grpc" | "cli") => TransportMapping | null
Parameters
NameTypeDescription
codestringThe error code string to look up.
transport"http" | "grpc" | "cli"The transport protocol to resolve a mapping for.
Returns — A TransportMapping or null if the code is unregistered. Example
const mapping = getTransportMapping('E_NOT_FOUND', 'http');
console.log(mapping); // { transport: 'http', value: 404 }

LAFSFlagError

Error thrown when LAFS flag validation fails. Signature
typeof LAFSFlagError

resolveOutputFormat(input)

Resolve the output format from flag inputs using the LAFS precedence chain. Signature
(input: FlagInput) => FlagResolution
Parameters
NameTypeDescription
inputFlagInputThe flag inputs including explicit flags, project/user defaults, and TTY state
Returns — The resolved format, its source layer, and quiet mode status Throws
  • LAFSFlagError When humanFlag and jsonFlag are both truthy.
Example
const resolution = resolveOutputFormat({ humanFlag: true });
// => { format: 'human', source: 'flag', quiet: false }

isNativeAvailable()

Check if the native addon is available. Signature
() => boolean
Returnstrue if the native Rust binding was loaded successfully.

getNativeModule()

Get the native module, or null if unavailable. Signature
() => LafsNativeModule | null
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
(input: unknown) => EnvelopeValidationResult
Parameters
NameTypeDescription
inputunknownThe raw value to validate.
Returns — An EnvelopeValidationResult with validity status and any errors. Example
const result = validateEnvelope(JSON.parse(rawJson));
if (!result.valid) {
  console.error(result.errors);
}

assertEnvelope(input)

Validates input and throws on schema failure, returning a typed envelope on success. Signature
(input: unknown) => LAFSEnvelope
Parameters
NameTypeDescription
inputunknownThe raw value to validate as a LAFS envelope.
Returns — The input cast to LAFSEnvelope when schema validation passes. Throws
  • Error When the input does not conform to the envelope schema.
Example
const envelope = assertEnvelope(parsed);
console.log(envelope.success);

runEnvelopeConformance(envelope, options)

Runs the full suite of LAFS envelope conformance checks. Signature
(envelope: unknown, options?: EnvelopeConformanceOptions) => ConformanceReport
Parameters
NameTypeDescription
envelopeunknownThe raw value to validate as a LAFS envelope.
options: EnvelopeConformanceOptionsOptional tier filter for the conformance checks.
Returns — A ConformanceReport with individual check results and an overall pass/fail. Example
const report = runEnvelopeConformance(parsedJson, { tier: 'core' });
if (!report.ok) {
  console.error(report.checks.filter(c => !c.pass));
}

runFlagConformance(flags)

Runs LAFS flag-semantics conformance checks against a set of flag inputs. Signature
(flags: FlagInput) => ConformanceReport
Parameters
NameTypeDescription
flagsFlagInputThe flag input to validate.
Returns — A ConformanceReport with individual check results and an overall pass/fail. Example
const report = runFlagConformance({ humanFlag: true, jsonFlag: false });
console.log(report.ok); // true

ComplianceError

Error thrown when assertCompliance or withCompliance detects failures. Signature
typeof ComplianceError
Example
try {
  assertCompliance(envelope);
} catch (err) {
  if (err instanceof ComplianceError) {
    console.log(err.issues);
  }
}

enforceCompliance(input, options)

Runs the full LAFS compliance pipeline against an unknown input value. Signature
(input: unknown, options?: EnforceComplianceOptions) => ComplianceResult
Parameters
NameTypeDescription
inputunknownThe raw value to validate as a LAFS envelope.
options: EnforceComplianceOptionsControls which optional stages execute.
Returns — A ComplianceResult with the aggregate pass/fail status and per-stage reports. Example
const result = enforceCompliance(rawJson, { checkFlags: true, flags: { jsonFlag: true } });
if (!result.ok) {
  console.error(result.issues);
}

assertCompliance(input, options)

Validates input and throws ComplianceError on any failure. Signature
(input: unknown, options?: EnforceComplianceOptions) => LAFSEnvelope
Parameters
NameTypeDescription
inputunknownThe raw value to validate as a LAFS envelope.
options: EnforceComplianceOptionsControls which optional stages execute.
Returns — The validated LAFSEnvelope when all stages pass. Throws
  • ComplianceError When any compliance stage fails.
Example
const envelope = assertCompliance(rawJson);

withCompliance(producer, options)

Wraps an envelope-producing function with automatic compliance enforcement. Signature
<TArgs extends unknown[], TResult extends LAFSEnvelope>(producer: (...args: TArgs) => TResult | Promise<TResult>, options?: EnforceComplianceOptions) => (...args: TArgs) => Promise<LAFSEnvelope>
Parameters
NameTypeDescription
producer(...args: TArgsA sync or async function that produces a LAFS envelope.
options: EnforceComplianceOptionsCompliance options forwarded to assertCompliance.
Returns — An async function with the same signature that enforces compliance on every call. Example
const safeFetch = withCompliance(fetchEnvelope, { checkConformance: true });
const envelope = await safeFetch('/api/data');

createComplianceMiddleware(options)

Creates a ComplianceMiddleware that enforces LAFS compliance on the next handler’s output. Signature
(options?: EnforceComplianceOptions) => ComplianceMiddleware
Parameters
NameTypeDescription
options: EnforceComplianceOptionsCompliance options forwarded to assertCompliance.
Returns — A middleware function that validates the downstream envelope. Example
const mw = createComplianceMiddleware({ checkConformance: true });
const result = await mw(currentEnvelope, () => produceEnvelope());

getDeprecationRegistry()

Retrieve all registered deprecation entries. Signature
() => DeprecationEntry[]
Returns — Array of all DeprecationEntry rules in the registry Example
const entries = getDeprecationRegistry();
console.log(entries.length); // number of registered deprecations

detectDeprecatedEnvelopeFields(envelope)

Detect deprecated field usage in a LAFS envelope. Signature
(envelope: LAFSEnvelope) => Warning[]
Parameters
NameTypeDescription
envelopeLAFSEnvelopeThe LAFS envelope to inspect
Returns — Array of Warning objects for each detected deprecation Example
const warnings = detectDeprecatedEnvelopeFields(envelope);
for (const w of warnings) {
  console.warn(`${w.code}: ${w.message}`);
}

emitDeprecationWarnings(envelope)

Emit deprecation warnings by attaching them to the envelope metadata. Signature
(envelope: LAFSEnvelope) => LAFSEnvelope
Parameters
NameTypeDescription
envelopeLAFSEnvelopeThe LAFS envelope to augment
Returns — A new envelope with deprecation warnings appended to _meta.warnings Example
const enriched = emitDeprecationWarnings(envelope);
console.log(enriched._meta.warnings); // includes any deprecation warnings

createEnvelope(input)

Create a fully validated LAFS envelope from a success or error input. Signature
(input: CreateEnvelopeInput) => LAFSEnvelope
Parameters
NameTypeDescription
inputCreateEnvelopeInputDiscriminated union of success or error input data.
Returns — A complete LAFSEnvelope ready for serialization. Example
import { createEnvelope } from '@cleocode/lafs';

const envelope = createEnvelope({
  success: true,
  result: { items: [] },
  meta: { operation: 'tasks.list', requestId: 'req-1' },
});

LafsError

Error subclass that carries the full LAFSError payload. Signature
typeof LafsError
Example
try {
  parseLafsResponse(envelope);
} catch (err) {
  if (err instanceof LafsError) {
    console.log(err.code, err.agentAction);
  }
}

parseLafsResponse(input, options)

Parse and unwrap a raw LAFS envelope, returning the result or throwing on error. Signature
<T = unknown>(input: unknown, options?: ParseLafsResponseOptions) => T
Parameters
NameTypeDescription
inputunknownRaw value expected to be a valid LAFSEnvelope.
options: ParseLafsResponseOptionsParsing options controlling error-code validation.
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
import { parseLafsResponse } from '@cleocode/lafs';

interface TaskList { items: Task[] }
const tasks = parseLafsResponse<TaskList>(rawEnvelope);

resolveFieldExtraction(input)

Resolve field extraction flags into a validated configuration. Signature
(input: FieldExtractionInput) => FieldExtractionResolution
Parameters
NameTypeDescription
inputFieldExtractionInputThe field extraction flag inputs
Returns — The resolved extraction configuration with mvi level and source Throws
  • LAFSFlagError When both fieldFlag and fieldsFlag are set.
Example
const resolution = resolveFieldExtraction({ fieldsFlag: 'id,title' });
// => { fields: ['id', 'title'], mvi: 'minimal', mviSource: 'default', expectsCustomMvi: true }

extractFieldFromResult(result, field)

Extract a named field from a LAFS result object. Signature
(result: LAFSEnvelope["result"], field: string) => unknown
Parameters
NameTypeDescription
resultLAFSEnvelope["result"]The envelope result value (object, array, or null)
fieldstringThe field name to extract
Returns — The extracted value, or undefined if not found at any level Example
const result = { task: { id: 'T1', title: 'Fix bug' } };
extractFieldFromResult(result, 'title'); // => 'Fix bug'

extractFieldFromEnvelope(envelope, field)

Extract a named field from an envelope’s result. Signature
(envelope: LAFSEnvelope, field: string) => unknown
Parameters
NameTypeDescription
envelopeLAFSEnvelopeThe LAFS envelope to extract from
fieldstringThe field name to extract
Returns — The extracted value, or undefined if not found Example
const value = extractFieldFromEnvelope(envelope, 'title');

applyFieldFilter(envelope, fields)

Filter result fields in a LAFS envelope to the requested subset. Signature
(envelope: LAFSEnvelope, fields: string[]) => LAFSEnvelope
Parameters
NameTypeDescription
envelopeLAFSEnvelopeThe LAFS envelope whose result will be filtered
fieldsstring[]Array of field names to retain in the result
Returns — A new envelope with the filtered result and _meta.mvi set to 'custom' Example
const filtered = applyFieldFilter(envelope, ['id', 'title']);
// filtered.result contains only 'id' and 'title' fields
// filtered._meta.mvi === 'custom'

resolveFlags(input)

Resolve all flags across both layers and validate cross-layer semantics. Signature
(input: UnifiedFlagInput) => UnifiedFlagResolution
Parameters
NameTypeDescription
inputUnifiedFlagInputCombined format and field extraction flags
Returns — The unified resolution containing format, fields, and any cross-layer warnings Throws
  • LAFSFlagError When format or field layer flags conflict.
Example
const result = resolveFlags({ human: true, field: 'title' });
// result.format => { format: 'human', source: 'flag', quiet: false }
// result.fields => { field: 'title', mvi: 'minimal', ... }
// result.warnings => ['Cross-layer: --human + --field "title". ...']

LafsA2AResult

Wrapper for A2A responses with LAFS envelope support. Signature
typeof LafsA2AResult
Methods

getA2AResult()

Get the raw A2A response.
() => SendMessageResponse

isError()

Check if the result is an error response.
() => boolean

getError()

Get error details if the result is an error.
() => JSONRPCErrorResponse | null

getSuccess()

Get the success result.
() => SendMessageSuccessResponse | null

getTask()

Extract a Task from the response (if present).
() => Task | null

getMessage()

Extract a Message from the response (if present).
() => Message | null

hasLafsEnvelope()

Check if the response contains a LAFS envelope.
() => boolean

getLafsEnvelope()

Extract a LAFS envelope from A2A artifact.
() => LAFSEnvelope | null

getTokenEstimate()

Get token estimate from LAFS envelope.
() => { estimated: number; budget?: number; truncated?: boolean; } | null

getTaskStatus()

Get the task status.
() => TaskStatus | null

getTaskState()

Get the task state.
() => TaskState | null

isTerminal()

Check if the task is in a terminal state.
() => boolean

isInputRequired()

Check if the task requires user input.
() => boolean

isAuthRequired()

Check if the task requires authentication.
() => boolean

getArtifacts()

Get all artifacts from the task.
() => Artifact[]

isDataPart()

Type guard: checks whether a Part is a DataPart by inspecting its kind field.
(part: Part) => part is DataPart

isLafsEnvelope()

Heuristic check: returns true if the data object looks like a LAFS envelope (has $schema, _meta, success).
(data: unknown) => boolean

createLafsArtifact(envelope)

Create a LAFS envelope artifact for A2A. Signature
(envelope: LAFSEnvelope) => Artifact
Parameters
NameTypeDescription
envelopeLAFSEnvelopeLAFS envelope to wrap as an artifact
Returns — A2A Artifact containing the envelope as a DataPart Example
const envelope = createEnvelope({
  success: true,
  result: { data: '...' },
  meta: { operation: 'analysis.run' }
});

const artifact = createLafsArtifact(envelope);
task.artifacts.push(artifact);

createTextArtifact(text, name)

Create a text artifact. Signature
(text: string, name?: string) => Artifact
Parameters
NameTypeDescription
textstringText content for the artifact
name: stringDisplay name for the artifact
Returns — A2A Artifact containing the text as a TextPart Example
const artifact = createTextArtifact('Hello, world!', 'greeting');

createFileArtifact(fileUrl, mediaType, filename)

Create a file artifact. Signature
(fileUrl: string, mediaType: string, filename?: string) => Artifact
Parameters
NameTypeDescription
fileUrlstringURI pointing to the file resource
mediaTypestringMIME type of the file (e.g., application/pdf)
filename: stringOptional display filename for the artifact
Returns — A2A Artifact containing the file reference as a FilePart Example
const artifact = createFileArtifact(
  'https://example.com/report.pdf',
  'application/pdf',
  'report.pdf',
);

isExtensionRequired(agentCard, extensionUri)

Check if an extension is required in an Agent Card. Signature
(agentCard: AgentCard, extensionUri: string) => boolean
Parameters
NameTypeDescription
agentCardAgentCardAgent Card to inspect
extensionUristringURI of the extension to check
Returns — True if the extension is declared as required Example
if (isExtensionRequired(agentCard, LAFS_EXTENSION_URI)) {
  console.log('LAFS extension is mandatory for this agent');
}

getExtensionParams(agentCard, extensionUri)

Get extension parameters from an Agent Card. Signature
(agentCard: AgentCard, extensionUri: string) => Record<string, unknown> | undefined
Parameters
NameTypeDescription
agentCardAgentCardAgent Card to inspect
extensionUristringURI of the extension to look up
Returns — The extension’s params object, or undefined if not found Example
const params = getExtensionParams(agentCard, LAFS_EXTENSION_URI);
if (params?.supportsTokenBudgets) {
  // Enable budget tracking
}

isValidTransition(from, to)

Check if a transition from one state to another is valid. Signature
(from: TaskState, to: TaskState) => boolean
Parameters
NameTypeDescription
fromTaskStateCurrent task state
toTaskStateDesired target state
Returns — True if the transition is allowed by the state machine Example
if (!isValidTransition('submitted', 'completed')) {
  throw new Error('Cannot go directly from submitted to completed');
}

isTerminalState(state)

Check if a state is terminal (no further transitions allowed). Signature
(state: TaskState) => boolean
Parameters
NameTypeDescription
stateTaskStateTask state to check
Returns — True if the state is terminal Example
if (isTerminalState(task.status.state)) {
  console.log('Task has reached a final state');
}

isInterruptedState(state)

Check if a state is interrupted (paused awaiting input). Signature
(state: TaskState) => boolean
Parameters
NameTypeDescription
stateTaskStateTask state to check
Returns — True if the state indicates the task is waiting for external input Example
if (isInterruptedState(task.status.state)) {
  promptUserForInput(task);
}

InvalidStateTransitionError

Thrown when attempting an invalid state transition. Signature
typeof InvalidStateTransitionError

TaskImmutabilityError

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

TaskNotFoundError

Thrown when a task is not found. Signature
typeof TaskNotFoundError

TaskRefinementError

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

TaskManager

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

createTask()

Create a new task in the submitted state.
(options?: CreateTaskOptions) => Task

createRefinedTask()

Create a refinement/follow-up task referencing existing task(s).
(referenceTaskIds: string[], options?: Omit<CreateTaskOptions, "referenceTaskIds">) => Task

getTask()

Get a task by ID.
(taskId: string) => Task

listTasks()

List tasks with optional filtering and pagination.
(options?: ListTasksOptions) => ListTasksResult

updateTaskStatus()

Update task status. Enforces valid transitions and terminal state immutability.
(taskId: string, state: TaskState, message?: Message) => Task

addArtifact()

Add an artifact to a task.
(taskId: string, artifact: Artifact) => Task

addHistory()

Add a message to task history.
(taskId: string, message: Message) => Task

cancelTask()

Cancel a task by transitioning to canceled state.
(taskId: string) => Task

getTasksByContext()

Get all tasks in a given context.
(contextId: string) => Task[]

isTerminal()

Check if a task is in a terminal state.
(taskId: string) => boolean

resolveContextForReferenceTasks()

Derive a contextId from the first referenced task, if any reference tasks are provided.
(referenceTaskIds: string[] | undefined) => string | undefined

validateReferenceTasks()

Validate that all referenced tasks exist and share the same contextId.
(referenceTaskIds: string[], contextId: string) => void

attachLafsEnvelope(manager, taskId, envelope)

Attach a LAFS envelope as an artifact to an A2A task. Signature
(manager: TaskManager, taskId: string, envelope: LAFSEnvelope) => Task
Parameters
NameTypeDescription
managerTaskManagerTaskManager instance managing the task
taskIdstringID of the task to attach the envelope to
envelopeLAFSEnvelopeLAFS envelope to attach as an artifact
Returns — Deep clone of the updated task with the new artifact Example
const envelope: LAFSEnvelope = { success: true, result: { data: 'ok' }, error: null, _meta: meta };
const updated = attachLafsEnvelope(manager, 'task-1', envelope);

TaskEventBus

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

publishStatusUpdate()

Publish a task status update event.
(event: TaskStatusUpdateEvent) => void

publishArtifactUpdate()

Publish a task artifact update event.
(event: TaskArtifactUpdateEvent) => void

publish()

Publish a task stream event to all listeners and history.
(event: TaskStreamEvent) => void

subscribe()

Subscribe to events for a specific task.
(taskId: string, listener: StreamListener) => () => void

getHistory()

Get the full event history for a task.
(taskId: string) => TaskStreamEvent[]

streamTaskEvents(bus, taskId, options)

Build an async iterator for real-time task stream events. Signature
(bus: TaskEventBus, taskId: string, options?: StreamIteratorOptions) => AsyncGenerator<TaskStreamEvent>
Parameters
NameTypeDescription
busTaskEventBusTaskEventBus to subscribe to
taskIdstringID of the task to stream events for
options: StreamIteratorOptionsIterator options including timeout
Returns — Async generator yielding task stream events Example
for await (const event of streamTaskEvents(bus, 'task-1', { timeoutMs: 5000 })) {
  console.log('Received:', event);
}

PushNotificationConfigStore

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

set()

Store a push-notification config for a task.
(taskId: string, configId: string, config: PushNotificationConfig) => void

get()

Retrieve a push-notification config by task and config ID.
(taskId: string, configId: string) => PushNotificationConfig | undefined

list()

List all push-notification configs for a task.
(taskId: string) => PushNotificationConfig[]

delete()

Delete a push-notification config.
(taskId: string, configId: string) => boolean

PushNotificationDispatcher

Deliver task updates to registered push-notification webhooks. Signature
typeof PushNotificationDispatcher
Methods

dispatch()

Dispatch a task event to all registered webhooks for the task.
(taskId: string, event: TaskStreamEvent) => Promise<PushNotificationDeliveryResult[]>

buildHeaders()

Build HTTP headers for push notification delivery including auth tokens.
(config: PushNotificationConfig) => Record<string, string>

TaskArtifactAssembler

Applies append/lastChunk artifact deltas into task-local snapshots. Signature
typeof TaskArtifactAssembler
Methods

applyUpdate()

Apply an artifact update event to the assembled snapshot.
(event: TaskArtifactUpdateEvent) => Artifact

get()

Get a specific assembled artifact by task and artifact ID.
(taskId: string, artifactId: string) => Artifact | undefined

list()

List all assembled artifacts for a task.
(taskId: string) => Artifact[]

mergeArtifact()

Merge a new artifact update event into an existing artifact snapshot, handling append semantics.
(prior: Artifact | undefined, event: TaskArtifactUpdateEvent) => Artifact

withLastChunk()

Inject the a2a:last_chunk marker into artifact metadata.
(metadata: Record<string, unknown> | undefined, lastChunk: boolean) => Record<string, unknown>

createJsonRpcRequest(id, method, params)

Create a JSON-RPC 2.0 request object. Signature
(id: string | number, method: string, params?: Record<string, unknown>) => JsonRpcRequest
Parameters
NameTypeDescription
idstring | numberClient-assigned request identifier
methodstringThe RPC method name to invoke
params: Record<stringOptional named parameters for the method call
Returns — A fully formed JsonRpcRequest object Example
const req = createJsonRpcRequest(1, 'tasks/get', { id: 'abc' });
// { jsonrpc: '2.0', id: 1, method: 'tasks/get', params: { id: 'abc' } }

createJsonRpcResponse(id, result)

Create a JSON-RPC 2.0 success response. Signature
(id: string | number | null, result: unknown) => JsonRpcResponse
Parameters
NameTypeDescription
idstring | number | nullIdentifier matching the originating request, or null for notifications
resultunknownThe return value of the invoked method
Returns — A fully formed JsonRpcResponse object Example
const res = createJsonRpcResponse(1, { status: 'ok' });
// { jsonrpc: '2.0', id: 1, result: { status: 'ok' } }

createJsonRpcErrorResponse(id, code, message, data)

Create a JSON-RPC 2.0 error response. Signature
(id: string | number | null, code: number, message: string, data?: Record<string, unknown>) => JsonRpcErrorResponse
Parameters
NameTypeDescription
idstring | number | nullIdentifier matching the originating request, or null for notifications
codenumberNumeric error code (standard or A2A-specific)
messagestringShort human-readable description of the error
data: Record<stringOptional additional structured error data
Returns — A fully formed JsonRpcErrorResponse object Example
const err = createJsonRpcErrorResponse(1, -32001, 'Task not found');
// { jsonrpc: '2.0', id: 1, error: { code: -32001, message: 'Task not found' } }

createA2AErrorResponse(id, errorType, message, data)

Create an A2A-specific JSON-RPC error response by error type name. Signature
(id: string | number | null, errorType: A2AErrorType, message: string, data?: Record<string, unknown>) => JsonRpcErrorResponse
Parameters
NameTypeDescription
idstring | number | nullIdentifier matching the originating request, or null for notifications
errorTypeA2AErrorTypeThe A2A error type name (e.g. "TaskNotFound")
messagestringShort human-readable description of the error
data: Record<stringOptional additional structured error data
Returns — A fully formed JsonRpcErrorResponse with the resolved A2A error code Example
const err = createA2AErrorResponse(1, 'TaskNotFound', 'No task with id xyz');
// error.code === -32001

validateJsonRpcRequest(input)

Validate the structure of a JSON-RPC request. Signature
(input: unknown) => { valid: boolean; errors: string[]; }
Parameters
NameTypeDescription
inputunknownThe unknown value to validate
Returns — An object with valid indicating success and errors listing any violations Example
const { valid, errors } = validateJsonRpcRequest({ jsonrpc: '2.0', id: 1, method: 'tasks/get' });
// valid === true, errors === []

isA2AError(code)

Check if a numeric error code is an A2A-specific error. Signature
(code: number) => boolean
Parameters
NameTypeDescription
codenumberThe numeric JSON-RPC error code to check
Returnstrue if the code falls within the A2A error range Example
isA2AError(-32001); // true  (TaskNotFound)
isA2AError(-32700); // false (standard ParseError)

createGrpcStatus(errorType, message, metadata)

Create a gRPC Status object for an A2A error type. Signature
(errorType: A2AErrorType, message: string, metadata?: Record<string, string>) => GrpcStatus
Parameters
NameTypeDescription
errorTypeA2AErrorTypeThe A2A error type name (e.g. "TaskNotFound")
messagestringHuman-readable error message
metadata: Record<stringOptional key-value metadata to include in the ErrorInfo detail
Returns — A fully formed GrpcStatus object with ErrorInfo details Example
const status = createGrpcStatus('TaskNotFound', 'No task with id xyz');
// { code: 5, message: '...', details: [{ reason: 'TASK_NOT_FOUND', domain: 'a2a-protocol.org' }] }

createProblemDetails(errorType, detail, extensions)

Create an RFC 9457 Problem Details object for an A2A error. Signature
(errorType: A2AErrorType, detail: string, extensions?: Record<string, unknown>) => ProblemDetails
Parameters
NameTypeDescription
errorTypeA2AErrorTypeThe A2A error type name (e.g. "TaskNotFound")
detailstringHuman-readable explanation specific to this occurrence
extensions: Record<stringOptional additional members to include in the response
Returns — A fully formed ProblemDetails object Example
const problem = createProblemDetails('TaskNotFound', 'No task with id xyz');
// { type: 'https://a2a-protocol.org/errors/task-not-found', title: 'Task Not Found', status: 404, detail: '...' }

createLafsProblemDetails(errorType, lafsError, requestId)

Create an RFC 9457 Problem Details object bridging A2A error types with LAFS error data. Signature
(errorType: A2AErrorType, lafsError: LAFSError, requestId?: string) => ProblemDetails
Parameters
NameTypeDescription
errorTypeA2AErrorTypeThe A2A error type name (e.g. "InvalidAgentResponse")
lafsErrorLAFSErrorThe LAFS error object to extract extension fields from
requestId: stringOptional request identifier used as the instance field
Returns — A ProblemDetails object with LAFS extension fields Example
const problem = createLafsProblemDetails('InvalidAgentResponse', {
  code: 'E_AGENT_RESPONSE',
  message: 'Upstream agent returned invalid JSON',
  retryable: true,
  retryAfterMs: 5000,
}, 'req-123');

buildUrl(endpoint, params)

Build a URL by substituting path parameters. Signature
(endpoint: HttpEndpoint, params?: Record<string, string>) => string
Parameters
NameTypeDescription
endpointHttpEndpointHTTP endpoint definition from HTTP_ENDPOINTS
params: Record<stringPath parameter values keyed by name (without leading colon)
Returns — The resolved URL path string with parameters substituted Example
const url = buildUrl(HTTP_ENDPOINTS.GetTask, { id: 'task-42' });
// '/tasks/task-42'

parseListTasksQuery(query)

Parse camelCase query parameters for the ListTasks endpoint. Signature
(query: Record<string, string | undefined>) => ListTasksQueryParams
Parameters
NameTypeDescription
queryRecord<stringRaw query parameter map from the HTTP request
Returns — A typed ListTasksQueryParams object with coerced values Example
const params = parseListTasksQuery({ contextId: 'ctx-1', limit: '10' });
// { contextId: 'ctx-1', limit: 10 }

getErrorCodeMapping(errorType)

Get the complete error code mapping for a given A2A error type. Signature
(errorType: A2AErrorType) => ErrorCodeMapping
Parameters
NameTypeDescription
errorTypeA2AErrorTypeThe A2A error type name (e.g. "TaskNotFound")
Returns — The ErrorCodeMapping with JSON-RPC, HTTP, and gRPC codes Throws
  • Error if the error type is not a known A2A error type
Example
const mapping = getErrorCodeMapping('TaskNotFound');
// { jsonRpcCode: -32001, httpStatus: 404, httpTypeUri: '...', grpcStatus: 'NOT_FOUND', grpcCode: 5 }

parseA2AVersionHeader(headerValue)

Parse the a2a-version header into an array of version strings. Signature
(headerValue: string | undefined) => string[]
Parameters
NameTypeDescription
headerValuestring | undefinedThe raw a2a-version header value, or undefined if absent
Returns — An array of version strings extracted from the header Example
parseA2AVersionHeader('1.0, 2.0'); // ['1.0', '2.0']
parseA2AVersionHeader(undefined);   // []

negotiateA2AVersion(requestedVersions)

Negotiate an A2A protocol version from the client’s requested versions. Signature
(requestedVersions: string[]) => string | null
Parameters
NameTypeDescription
requestedVersionsstring[]Array of version strings requested by the client
Returns — The negotiated version string, or null if no common version exists Example
negotiateA2AVersion(['1.0', '2.0']); // '1.0'
negotiateA2AVersion([]);              // '1.0' (default)
negotiateA2AVersion(['3.0']);          // null

CircuitBreakerError

Error thrown when a circuit breaker rejects a call. Signature
typeof CircuitBreakerError
Example
try {
  await breaker.execute(() => fetch('/api'));
} catch (err) {
  if (err instanceof CircuitBreakerError) {
    console.log('Circuit open, using fallback');
  }
}

CircuitBreaker

Circuit breaker for protecting against cascading failures. Signature
typeof CircuitBreaker
Example
import { CircuitBreaker } from '@cleocode/lafs/circuit-breaker';

const breaker = new CircuitBreaker({
  name: 'external-api',
  failureThreshold: 5,
  resetTimeout: 30000
});

try {
  const result = await breaker.execute(async () => {
    return await externalApi.call();
  });
} catch (error) {
  if (error instanceof CircuitBreakerError) {
    console.log('Circuit breaker is open');
  }
}
Methods

execute()

Execute a function with circuit breaker protection.
<T>(fn: () => Promise<T>) => Promise<T>

getState()

Get the current circuit breaker state.
() => CircuitState

getMetrics()

Get a snapshot of the circuit breaker’s runtime metrics.
() => CircuitBreakerMetrics

forceOpen()

Manually open the circuit breaker, rejecting all subsequent calls.
() => void

forceClose()

Manually close the circuit breaker and reset all counters.
() => void

onSuccess()

Records a successful call and may transition from HALF_OPEN to CLOSED.
() => void

onFailure()

Records a failed call and may trip the circuit to OPEN.
() => void

transitionTo()

Transitions the circuit to the given state, resetting HALF_OPEN call count when entering HALF_OPEN.
(newState: CircuitState) => void

shouldAttemptReset()

Returns true if enough time has elapsed since the last failure to attempt a reset.
() => boolean

scheduleReset()

Schedules a timer to transition from OPEN to HALF_OPEN after the configured reset timeout.
() => void

reset()

Resets all failure/success counters and clears the pending reset timer.
() => void

CircuitBreakerRegistry

Registry for managing multiple named circuit breakers. Signature
typeof CircuitBreakerRegistry
Example
const registry = new CircuitBreakerRegistry();

registry.add('payment-api', {
  failureThreshold: 3,
  resetTimeout: 60000
});

const paymentBreaker = registry.get('payment-api');
Methods

add()

Register a new circuit breaker with the given name and configuration.
(name: string, config: Omit<CircuitBreakerConfig, "name">) => CircuitBreaker

get()

Retrieve a circuit breaker by name.
(name: string) => CircuitBreaker | undefined

getOrCreate()

Retrieve an existing circuit breaker or create one if it does not exist.
(name: string, config: Omit<CircuitBreakerConfig, "name">) => CircuitBreaker

getAllMetrics()

Collect metrics from all registered circuit breakers.
() => Record<string, CircuitBreakerMetrics>

resetAll()

Force-close all registered circuit breakers, resetting their counters.
() => void

circuitBreakerMiddleware(config)

Create an Express middleware that wraps downstream handlers with a circuit breaker. Signature
(config: CircuitBreakerConfig) => (_req: unknown, res: { status: (code: number) => { json: (body: unknown) => void; }; }, next: () => void) => Promise<void>
Parameters
NameTypeDescription
configCircuitBreakerConfigCircuit breaker configuration for the middleware instance
Returns — An Express-compatible middleware function Example
app.use('/external-api', circuitBreakerMiddleware({
  name: 'external-api',
  failureThreshold: 5
}));

healthCheck(config)

Health check middleware for Express applications. Signature
(config?: HealthCheckConfig) => (_req: unknown, res: { status: (code: number) => { json: (body: unknown) => void; }; }) => Promise<void>
Parameters
NameTypeDescription
config: HealthCheckConfigOptional health check configuration
Returns — An Express-compatible middleware function that serves the health endpoint Example
import express from 'express';
import { healthCheck } from '@cleocode/lafs/health';

const app = express();

// Basic health check
app.use('/health', healthCheck());

// Custom health checks
app.use('/health', healthCheck({
  checks: [
    async () => ({
      name: 'database',
      status: await checkDatabase() ? 'ok' : 'error'
    })
  ]
}));

createDatabaseHealthCheck(config, , )

Create a health check function that verifies database connectivity. Signature
(config: { checkConnection: () => Promise<boolean>; name?: string; }) => HealthCheckFunction
Parameters
NameTypeDescription
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
Returns — A HealthCheckFunction suitable for use in HealthCheckConfig.checks Example
const dbCheck = createDatabaseHealthCheck({
  checkConnection: async () => await db.ping()
});

app.use('/health', healthCheck({
  checks: [dbCheck]
}));

createExternalServiceHealthCheck(config, , , )

Create a health check function that probes an external HTTP service. Signature
(config: { name: string; url: string; timeout?: number; }) => HealthCheckFunction
Parameters
NameTypeDescription
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
Returns — A HealthCheckFunction suitable for use in HealthCheckConfig.checks Example
const apiCheck = createExternalServiceHealthCheck({
  name: 'payment-api',
  url: 'https://api.payment.com/health',
  timeout: 5000
});

livenessProbe()

Liveness probe — a minimal check confirming the process is running. Signature
() => (_req: unknown, res: { status: (code: number) => { json: (body: unknown) => void; }; }) => void
Returns — An Express-compatible middleware function Example
app.get('/health/live', livenessProbe());

readinessProbe(config)

Readiness probe — verifies the service can accept traffic. Signature
(config?: { checks?: HealthCheckFunction[]; }) => (_req: unknown, res: { status: (code: number) => { json: (body: unknown) => void; }; }) => Promise<void>
Parameters
NameTypeDescription
config: { checks?: HealthCheckFunction[]; }Optional configuration with custom health check functions
Returns — An Express-compatible async middleware function Example
app.get('/health/ready', readinessProbe({
  checks: [dbCheck, cacheCheck]
}));

projectEnvelope(envelope, mviLevel)

Project an envelope to the declared MVI verbosity level. Signature
(envelope: LAFSEnvelope, mviLevel?: MVILevel) => Record<string, unknown>
Parameters
NameTypeDescription
envelopeLAFSEnvelopeThe full LAFS envelope to project
mviLevel: MVILevelOverride MVI level; falls back to envelope._meta.mvi, then 'standard'
Returns — A plain object containing only the fields appropriate for the resolved MVI level Example
const minimal = projectEnvelope(envelope, 'minimal');
// minimal contains only: success, _meta (requestId, contextVersion), result/error

estimateProjectedTokens(projected)

Estimate token count for a projected envelope. Signature
(projected: Record<string, unknown>) => number
Parameters
NameTypeDescription
projectedRecord<stringThe projected envelope object to estimate
Returns — The estimated token count based on JSON serialization length Example
const tokens = estimateProjectedTokens(projectEnvelope(envelope, 'minimal'));
// tokens ~= Math.ceil(JSON.stringify(projected).length / 4)

lafsErrorToProblemDetails(error, requestId)

Convert a LAFSError to an RFC 9457 Problem Details object. Signature
(error: LAFSError, requestId?: string) => LafsProblemDetails
Parameters
NameTypeDescription
errorLAFSErrorThe LAFS error to convert
requestId: stringOptional request ID to set as the instance field
Returns — An RFC 9457-compliant LafsProblemDetails object Example
import { lafsErrorToProblemDetails } from "@cleocode/lafs";

const pd = lafsErrorToProblemDetails(envelope.error!, envelope._meta.requestId);
// pd.status === 400, pd.type === "https://lafs.dev/errors/v1/E_VALIDATION"

gracefulShutdown(server, config)

Enable graceful shutdown for an HTTP server. Signature
(server: Server, config?: GracefulShutdownConfig) => void
Parameters
NameTypeDescription
serverServerThe Node.js HTTP server to manage
config: GracefulShutdownConfigOptional shutdown configuration
Example
import express from 'express';
import { gracefulShutdown } from '@cleocode/lafs/shutdown';

const app = express();
const server = app.listen(3000);

gracefulShutdown(server, {
  timeout: 30000,
  signals: ['SIGTERM', 'SIGINT'],
  onShutdown: async () => {
    console.log('Shutting down...');
    await db.close();
  }
});

isShuttingDown()

Check whether a shutdown sequence is currently in progress. Signature
() => boolean
Returnstrue if the server is shutting down, false otherwise Example
if (isShuttingDown()) {
  return; // skip expensive work
}

getShutdownState()

Get a snapshot of the current shutdown state. Signature
() => ShutdownState
Returns — A copy of the current ShutdownState Example
const state = getShutdownState();
console.log(`Connections: ${state.activeConnections}`);

forceShutdown(exitCode)

Terminate the process immediately without waiting for connections to drain. Signature
(exitCode?: number) => void
Parameters
NameTypeDescription
exitCode: numberProcess exit code
Example
forceShutdown(1);

shutdownMiddleware()

Express middleware that rejects requests with 503 while the server is shutting down. Signature
() => (_req: unknown, res: { status: (code: number) => { json: (body: unknown) => void; }; }, next: () => void) => void
Returns — An Express-compatible middleware function Example
app.use(shutdownMiddleware());

waitForShutdown()

Wait until a shutdown sequence begins. Signature
() => Promise<void>
Returns — A promise that resolves when shutdown has started Example
await waitForShutdown();