Skip to content

AIDK API Reference / aidk-kernel

aidk-kernel ​

AIDK Kernel ​

Low-level execution primitives for the AIDK framework. The kernel provides the foundational infrastructure that all other AIDK packages build upon.

Core Primitives ​

  • Procedures - Async function wrappers with middleware, context, and telemetry
  • Context - Request-scoped state with automatic propagation
  • Channels - Async generators for streaming with backpressure
  • Telemetry - Execution tracking, spans, and metrics
  • Logger - Structured logging with configurable levels

When to Use Kernel Directly ​

Most applications should use the higher-level aidk package. Use kernel directly when:

  • Building custom execution infrastructure
  • Creating new AIDK adapters or integrations
  • Need fine-grained control over procedure execution

Example ​

typescript
import { procedure, Telemetry, Context } from 'aidk-kernel';

const myProcedure = procedure('my-operation', async (ctx, input: string) => {
  ctx.logger.info('Processing', { input });
  return { result: input.toUpperCase() };
});

const result = await myProcedure.run(ctx, 'hello');

See ​

Classes ​

ClassDescription
ChannelCore Channel primitive. Works standalone in any Node environment. Uses EventEmitter internally for pub/sub.
ChannelSessionChannel session manages a collection of channels. Sessions persist across multiple engine executions.
ContextStatic class for managing execution context via AsyncLocalStorage.
ContextProvider-
ExecutionTrackerUnified execution tracker for procedures and hooks. Handles automatic telemetry, metrics tracking, and propagation.
ProcedureBase-
ProcedureGraphProcedure graph for tracking parent-child relationships
ProcedureNodeProcedure node stored in the graph
TelemetryGlobal telemetry service for tracing, spans, and metrics.

Interfaces ​

InterfaceDescription
ChannelEventNormalized channel event structure. Loosely structured but normalized for consistency.
ChannelServiceInterfaceKernel-level interface for channel service access. This allows KernelContext to reference channels without creating a circular dependency between kernel and engine packages.
ChannelTargetTarget specification for event routing. Used by transports to determine which connections receive the event.
ContextMetadataExtensible metadata storage within the context.
ContextMetricsMetrics accumulated during procedure execution.
CounterA counter metric that only increases (e.g., request count, error count).
ExecutionEventEvent emitted during procedure execution.
ExecutionHandleHandle for monitoring and controlling a running procedure execution.
ExecutionTrackerOptions-
HistogramA histogram metric for recording distributions (e.g., latency, sizes).
KernelContextExecution context that flows through all async operations via AsyncLocalStorage.
KernelLoggerKernel logger interface with structured logging and context injection.
LoggerConfig-
LogMethodLog method signature supporting both message-first and object-first forms.
MetricAttributesAttributes for metrics, used for filtering and grouping.
MiddlewarePipelineA reusable bundle of middleware that can be applied to procedures.
ProcedureA callable function wrapper with middleware, validation, and execution control.
ProcedureEnvelopeMetadata envelope passed to middleware containing execution context.
ProcedureOptionsConfiguration options for creating a procedure.
SpanA span represents a unit of work or operation within a trace. Spans track timing, attributes, and errors for observability.
StaticMiddlewareStatic middleware configuration for a class. Maps procedure names to middleware arrays or pipelines.
StreamTagTagged stream item from mergeStreams when using a Record input.
TelemetryProviderInterface for telemetry providers (e.g., OpenTelemetry, DataDog).
UserContextUser information associated with the current execution context.

Type Aliases ​

Type AliasDescription
AsProcedureHelper type to transform a method signature to Procedure type. Extracts args and return type, then creates Procedure<TArgs, TOutput>.
BrandedContextType for branded context objects
ContextFieldsExtractorFunction to extract fields from KernelContext for logging. Return an object with fields to include in every log entry.
ExecutionBoundaryConfigExecution boundary behavior configuration.
ExtractArgsHelper type to extract argument types from a function signature. Handles functions with this parameters and generator functions.
ExtractReturnHelper type to extract return type from a function signature. Handles both Promise and direct returns, and unwraps Promise. Preserves AsyncIterable as-is.
HandleFactoryFactory function for creating custom execution handles.
LogLevelLog levels supported by the kernel logger.
MiddlewareMiddleware function that can intercept and transform procedure execution.
ProcedureStatusProcedure status
ProcedureWithHandleA procedure variant that returns an execution handle along with the result.
WithProceduresHelper type to transform all methods in a class to Procedures.

Variables ​

VariableDescription
defaultContextFieldsThe default context fields extractor. Exports core KernelContext fields only. Use with composeContextFields to extend.
KERNEL_CONTEXT_SYMBOLSymbol used to brand context objects for deterministic detection. This allows procedures to distinguish context from regular arguments.
LoggerLogger singleton for AIDK applications.

Functions ​

FunctionDescription
addMetricAdd a metric value (accumulates). Supports dot notation for nested paths: 'usage.inputTokens'
addUsageMetricsAdd usage metrics from a usage object. Converts nested structure to flat dot-notation keys.
applyMiddlewareType-safe helper to apply middleware to a Procedure while preserving types.
applyRegistryMiddlewareType-safe helper to apply middleware from a registry/hook system.
composeContextFieldsCompose multiple context field extractors into one. Later extractors override earlier ones for the same keys.
contextBrand a context object with a Symbol for deterministic detection. This allows procedures to deterministically identify context vs regular args.
createHookCreate a Hook Procedure from a function.
createPipelineCreate a reusable middleware pipeline.
createProcedureCreate a Procedure from a function (for use in class property initializers).
generatorProcedure-
getChannelGet a channel from the current context.
getMetricGet a metric value. Supports dot notation for nested paths: 'usage.inputTokens'
getUsageMetricsGet usage metrics as an object. Converts flat dot-notation keys back to nested structure.
hookDecorator-
isAsyncIterableType guard to check if an object is an async iterable.
isKernelContextCheck if an object is a branded context (deterministic check via Symbol). This is 100% reliable - no heuristics needed.
mapStreamTransform items in an async stream using a mapper function.
mergeStreamsMerge multiple async streams into a single stream, yielding items as they arrive.
pipePipe multiple procedures together, passing the output of each to the next.
procedureDecorator-
publishChannelPublish an event to a channel using the current context.
setMetricSet a metric value (overwrites). Supports dot notation for nested paths: 'usage.inputTokens'
subscribeChannelSubscribe to events on a channel using the current context.
tapStreamPerform side effects on each stream item without modifying the stream.
tryGetChannelTry to get a channel from the current context (returns undefined if not available).
waitForChannelResponseWait for a response on a channel using the current context.
wrapHook-
wrapProcedure-

References ​

getExecutionInfo ​

Re-exports getExecutionInfo


getOriginName ​

Re-exports getOriginName


getOriginNode ​

Re-exports getOriginNode


getParentNode ​

Re-exports getParentNode


getParentPid ​

Re-exports getParentPid


getRootPid ​

Re-exports getRootPid


hasAncestorMatching ​

Re-exports hasAncestorMatching


hasAncestorNamed ​

Re-exports hasAncestorNamed


hook ​

Renames and re-exports hookDecorator


isNestedExecution ​

Re-exports isNestedExecution


isStandaloneExecution ​

Re-exports isStandaloneExecution


isWithinEngine ​

Re-exports isWithinEngine


procedure ​

Renames and re-exports procedureDecorator


withExecution ​

Re-exports withExecution


WithExecutionOptions ​

Re-exports WithExecutionOptions

Released under the MIT License.