Skip to content

JavaScript/TypeScript Core API

@nnrp/core contains runtime-neutral types and helpers shared by the JavaScript role and transport packages.

Constants

NameTypeValue
NNRP_PROTOCOL_NAME"NNRP"Protocol name.
NNRP_PROTOCOL_VERSION"1.0.0"Protocol version.
NNRP_STANDARD_INPUT_PROFILESreadonly tupletensor, token, structured_event, tool_delta.

createCapabilityManifest

Creates a build-mode-specific capability manifest.

ParameterTypeRequiredDescription
optionsNnrpCapabilityManifestOptionsYesBuild mode, transports, and capability claims.
Returns
NnrpCapabilityManifest
ts
import { createCapabilityManifest } from "@nnrp/core";

const manifest = createCapabilityManifest({
  buildMode: "backend-native",
  transports: ["tcp", "quic"],
  capabilities: ["client.session"],
});

createBackendNativeManifest

Creates the default backend native capability manifest.

ParameterTypeRequiredDescription
capabilitiesreadonly NnrpCapability[]NoExtra capability claims.
Returns
NnrpCapabilityManifest

createBrowserWasmManifest

Creates the default browser WASM capability manifest.

ParameterTypeRequiredDescription
capabilitiesreadonly NnrpCapability[]NoExtra capability claims.
Returns
NnrpCapabilityManifest

selectTransport

Builds, filters, and orders provider candidates with the frozen transport comparator, then selects rank 0. When no provider is selectable it throws NnrpTransportSelectionError, whose candidates retain the complete ordered diagnostic list.

ParameterTypeRequiredDescription
providersreadonly NnrpTransportProviderDescriptor[]YesInstalled provider descriptors.
optionsNnrpTransportSelectionOptionsYesPeer support, policy, limits, readiness, and probe data.
Returns
NnrpTransportSelection

createTransportCandidates

Builds transport candidates from provider descriptors and frozen selection evidence without choosing one.

ParameterTypeRequiredDescription
providersreadonly NnrpTransportProviderDescriptor[]YesInstalled provider descriptors.
optionsNnrpTransportSelectionOptionsYesPeer support, policy, limits, readiness, and probe data.
Returns
readonly NnrpTransportCandidate[]

createTransportSelectionSummary

Creates a compact selection summary for diagnostics, conformance, and benchmarks.

ParameterTypeRequiredDescription
selectionNnrpTransportSelectionYesFull selection object.
Returns
NnrpTransportSelectionSummary

parseApplicationEndpoint

Parses and validates the public application endpoint. The function accepts only nnrp:// and nnrps:// and returns a URL, preserving the authority, path, query, and security intent.

ParameterTypeRequiredDescription
endpointstring | URLYesPublic NNRP application endpoint.
ReturnsThrows
URLNnrpProtocolError for empty, malformed, or provider-local endpoints.

resolveProviderEndpoint

Resolves the carrier-local endpoint after provider selection. TCP and QUIC derive host:port from the application authority and use port 4433 when it is omitted. IPC and WebSocket require an explicit matching provider endpoint.

ParameterTypeRequiredDescription
endpointstring | URLYesPublic nnrp:// or nnrps:// endpoint.
transportNnrpTransportKindYesSelected carrier.
providerEndpointstring | URLNoExplicit carrier-local endpoint.
ReturnsThrows
stringNnrpTransportError when the selected carrier cannot resolve the supplied locator.

normalizeSubmitRequest

Validates and normalizes submit payloads.

ParameterTypeRequiredDescription
requestNnrpSubmitRequestYesSubmit request.
optionsNormalizeSubmitRequestOptionsNoPayload copy and strict profile options.
ReturnsThrows
NnrpNormalizedSubmitRequestNnrpProtocolError for invalid frame, payload, cache, schema, or profile fields.

Cache and Schema Helpers

FunctionParametersReturnsDescription
createCacheKeykind: NnrpCacheObjectKind, key: bigint | number | string, namespaceId?: numberNnrpCacheKeyCreates the canonical 128-bit cache identity used by submit and cache operations.
createSchemaDescriptordescriptor: NnrpSchemaDescriptorNnrpSchemaDescriptorValidates and snapshots a schema descriptor.
normalizeCachePutRequestrequest: NnrpCachePutRequestNnrpCachePutRequestValidates cache identity, lease, payload, and metadata fields.
normalizeCacheInvalidateRequestrequest: NnrpCacheInvalidateRequestNnrpCacheInvalidateRequestValidates an explicit cache invalidation request.
isStandardInputProfileprofile: stringprofile is NnrpInputProfileTests membership in NNRP_STANDARD_INPUT_PROFILES.

Recovery and Session Helpers

FunctionParametersReturnsDescription
createRecoveryTokentoken: string | NnrpBinaryPayload, metadata?: Readonly<Record<string, string>>NnrpRecoveryTokenCreates an owned recovery token and metadata snapshot.
normalizeSessionMigrationRequestrequest: NnrpSessionMigrationRequestNnrpSessionMigrationRequestValidates the destination and recovery token for session migration.
throwIfResultDropevent: NnrpRuntimeEventvoidThrows NnrpResultDropError when the event records a dropped result.
validateSessionMetadataoptions?: NnrpSessionMetadataOptionsvoidValidates profile, cadence, quality, and metadata fields.
normalizeSessionPatchRequestrequest: NnrpSessionPatchRequestNnrpSessionPatchRequestValidates and snapshots a session metadata or flow-control patch.

NnrpSessionRecoveryTicket

NnrpSessionRecoveryTicket is the opaque runtime-issued value used by resumeSession. Applications may persist it, but cannot construct or mutate its resume token.

MemberParametersReturnsDescription
toBytes()NoneUint8ArrayEncodes the canonical little-endian NRTK version 1 envelope.
NnrpSessionRecoveryTicket.fromBytes(encoded)encoded: Uint8ArrayNnrpSessionRecoveryTicketValidates and decodes one exact NRTK envelope.

The readonly semantic fields are sessionId, a defensive-copy resumeToken, optional resumeFromOperationId, and resumeWindowMillis. Decoding rejects wrong magic or version, reserved flags, zero session id, an empty token, truncation, and trailing bytes.

validateEventPollOptions

Validates event polling options.

ParameterTypeRequiredDescription
optionsNnrpEventPollOptionsNoTimeout options.
ReturnsThrows
voidNnrpProtocolError for invalid timeout values.

Data Types

Capability and Transport

TypeDescription
NnrpBuildMode"backend-native" | "browser-wasm".
NnrpTransportKind"tcp" | "quic" | "ipc" | "websocket".
NnrpTransportPolicy"auto", "prefer-quic", "prefer-tcp", "prefer-ipc", "prefer-websocket", and the four corresponding force-* values.
NnrpCapabilityCapability claim such as client.session, server.session, native.loader, wasm.loader, cache, schema, or recovery.
NnrpCapabilityManifestProtocol name/version, build mode, transports, and capabilities.
NnrpTransportProviderCostFrozen provider modelId and units.
NnrpTransportProviderLimitsFrozen provider maxFrameBytes.
NnrpTransportProviderLimitationUnion of the seven registered limitation strings.
NnrpTransportProviderMetadataProvider id, cost, preference rank, limits, and registered limitations.
NnrpTransportProviderDescriptorProvider name/version, transport identity, implementation kind, availability, metadata, and optional native library path or diagnostic.
NnrpTransportCandidateReadinessProvider identity, route/security readiness, and optional diagnostic.
NnrpTransportProbeState"not-run" | "succeeded" | "failed" | "missing".
NnrpTransportProbeMetricsSample/success counts, median throughput, and median RTT.
NnrpTransportProbeObservationProvider identity, succeeded/failed state, optional metrics, and optional diagnostic.
NnrpTransportRejectionReasonUnion of the eight registered rejection strings.
NnrpTransportCandidateProvider metadata, availability, peer/limit eligibility, probe state/metrics, selection rank, rejection reason, and diagnostic.
NnrpTransportSelectionSummarySelected transport plus rejected candidates.
NnrpTransportSelectionErrorTyped error with code, string diagnostic, optional policy / transportId, and ordered candidates; forced failures identify their transport.

NnrpTransportCandidate uses camelCase forms of the canonical fields frozen in Transport Strategy and Probing: transportId, provider, localAvailable, peerSupported, withinLimits, probeState, optional probe, optional selectionRank, optional rejectionReason, and optional diagnostic. The public type has no opaque score field.

ts
type NnrpTransportProviderLimitation =
  | "requires-udp"
  | "requires-tcp"
  | "local-host-only"
  | "native-host-only"
  | "browser-host-only"
  | "unix-domain-socket"
  | "windows-named-pipe";
type NnrpTransportProbeState = "not-run" | "succeeded" | "failed" | "missing";
type NnrpTransportRejectionReason =
  | "policy-disallowed"
  | "local-unavailable"
  | "peer-unsupported"
  | "limit-exceeded"
  | "route-unresolved"
  | "security-unsatisfied"
  | "probe-missing"
  | "probe-failed";

interface NnrpTransportProviderCost {
  readonly modelId: number;
  readonly units: bigint;
}
interface NnrpTransportProviderLimits {
  readonly maxFrameBytes: bigint;
}
interface NnrpTransportProviderMetadata {
  readonly id: string;
  readonly cost: NnrpTransportProviderCost;
  readonly preferenceRank: number;
  readonly limits: NnrpTransportProviderLimits;
  readonly limitations: readonly NnrpTransportProviderLimitation[];
}
type NnrpTransportProviderKind = "pure-rust" | "native-dynamic" | "wasm";
interface NnrpTransportProviderDescriptor {
  readonly name: string;
  readonly version: string;
  readonly transportId: NnrpTransportKind;
  readonly kind: NnrpTransportProviderKind;
  readonly available: boolean;
  readonly libraryPath?: string;
  readonly metadata: NnrpTransportProviderMetadata;
  readonly diagnostic?: string;
}
interface NnrpTransportCandidateReadiness {
  readonly transportId: NnrpTransportKind;
  readonly providerId: string;
  readonly routeResolved: boolean;
  readonly securitySatisfied: boolean;
  readonly diagnostic?: string;
}
interface NnrpTransportProbeMetrics {
  readonly sampleCount: number;
  readonly successCount: number;
  readonly medianThroughputBytesPerSecond: bigint;
  readonly medianRttMicroseconds: bigint;
}
interface NnrpTransportProbeObservation {
  readonly transportId: NnrpTransportKind;
  readonly providerId: string;
  readonly state: "succeeded" | "failed";
  readonly metrics?: NnrpTransportProbeMetrics;
  readonly diagnostic?: string;
}
interface NnrpTransportCandidate {
  readonly transportId: NnrpTransportKind;
  readonly provider: NnrpTransportProviderMetadata;
  readonly localAvailable: boolean;
  readonly peerSupported: boolean;
  readonly withinLimits: boolean;
  readonly probeState: NnrpTransportProbeState;
  readonly probe?: NnrpTransportProbeMetrics;
  readonly selectionRank?: number;
  readonly rejectionReason?: NnrpTransportRejectionReason;
  readonly diagnostic?: string;
}
interface NnrpTransportSelectionOptions {
  readonly peerSupportedTransports: readonly NnrpTransportKind[];
  readonly policy: NnrpTransportPolicy;
  readonly requestedMaxFrameBytes?: bigint;
  readonly candidateReadiness: readonly NnrpTransportCandidateReadiness[];
  readonly probeObservations: readonly NnrpTransportProbeObservation[];
}
interface NnrpTransportSelection {
  readonly selectedProvider: NnrpTransportProviderDescriptor;
  readonly candidates: readonly NnrpTransportCandidate[];
  readonly policy: NnrpTransportPolicy;
  readonly diagnostic?: string;
}

NnrpTransportProviderDescriptor.name is the provider-owned package or display name. Selection, readiness, route lookup, and reporting use transportId as the canonical carrier identity and never infer it from name.

peerSupportedTransports has set semantics, so duplicates and array order do not affect selection. requestedMaxFrameBytes: 0n is valid and remains distinct from an omitted property.

Provider descriptors must have unique (transportId, provider.metadata.id) identities. Readiness is required for every provider. Readiness and probe observations are matched by (transportId, providerId); duplicate or unmatched evidence is a contract error. Missing probe observations remain distinguishable from observations whose state is "failed".

Submit, Result, and Events

TypeDescription
NnrpInputProfileOne of the standard profiles: tensor, token, structured_event, or tool_delta.
NnrpSubmitMode"inline" | "object-reference".
NnrpSubmitRequestNon-zero operationId: bigint, independent frameId, payload/tensors, profile, submit mode, cache key, descriptor, and metadata.
NnrpResultNon-zero operation id, canonical terminal state, and closed runtime-or-lifecycle evidence.
NnrpRuntimeEventComplete wire header, typed metadata union, and semantic tail.
NnrpClientEventClosed client union containing one runtime or lifecycle event.
NnrpEventPollOptionsOptional timeoutMillis.
ts
interface NnrpResult {
  readonly operationId: bigint;
  readonly terminalState: NnrpResultTerminalState;
  readonly event: NnrpTerminalEvent;
}

type NnrpTerminalEvent =
  | { readonly type: "runtime"; readonly event: NnrpRuntimeEvent }
  | { readonly type: "lifecycle"; readonly event: NnrpOperationLifecycleEvent };

type NnrpClientEvent =
  | { readonly type: "runtime"; readonly event: NnrpRuntimeEvent }
  | { readonly type: "lifecycle"; readonly event: NnrpOperationLifecycleEvent };

interface NnrpOperationLifecycleEvent {
  readonly operationId: bigint;
  readonly state: NnrpOperationState;
}

NnrpResultTerminalState is "success" | "cancelled" | "dropped" | "error". NnrpOperationState is "accepted" | "running" | "partial" | "waiting-tool" | "superseded" | "cancelled" | "failed" | "completed". Successful results preserve RESULT_PUSH; non-success results preserve the exact wire or local lifecycle event. An NnrpOperationLifecycleEvent is local role state and never carries a fabricated NnrpRuntimeFrameHeader. NnrpTerminalEvent always contains exactly one variant; nullable parallel runtime and lifecycle fields are not part of the API.

Additional public types used by these contracts:

TypeDescription
NnrpOperationIdNon-zero operation identity represented as bigint.
NnrpOperationStateCanonical eight-state operation lifecycle listed above.
NnrpSubmitCapacityPolicy"reject" | "await" behavior when local submit credit is exhausted.
NnrpBinaryPayloadUint8Array | ArrayBufferView.
NnrpTensorSection, NnrpNormalizedTensorSectionTensor byte section before and after request normalization.
NnrpPayloadDescriptorOptional schema id, content type, and encoding for a payload.
NnrpSchemaFlag, NnrpSchemaDescriptorRegistered schema flags and the validated schema contract.
NnrpCacheKey, NnrpCacheMetadataCanonical cache identity and caller metadata.
NnrpCacheOperationStatusaccepted, stored, invalidated, miss, or rejected.
NnrpCachePutRequest, NnrpCachePutResultExplicit cache put request and result.
NnrpCacheInvalidateRequest, NnrpCacheInvalidateResultExplicit invalidation request and result.
NnrpRecoveryToken, NnrpSessionMigrationEventRecovery token and typed migration lifecycle events.
NnrpSessionMetadataOptions, NnrpSessionFlowControlOptionsReusable session metadata and credit-window options.
NnrpFlowUpdateMetadata, NnrpResultHintMetadataStructured flow update and result-hint payloads.
NnrpAbortSignalLikeRuntime-neutral abort signal accepted by asynchronous SDK methods.

Errors

ClassDescription
NnrpErrorBase error with structured diagnostic.
NnrpCapabilityErrorCapability, manifest, or unsupported runtime error.
NnrpTransportErrorTransport error.
NnrpTimeoutErrorTimeout error.
NnrpProtocolErrorRequest shape or protocol validation error.
NnrpResultDropErrorTyped terminal evidence for a dropped result.
NnrpRecoveryErrorRecovery or migration capability failure.

NnrpDiagnosticSource identifies the producing layer as core, native, wasm, transport, protocol, or runtime.

NNRP Documentation