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 ​
- Procedure - The core procedure abstraction
- KernelContext - Request-scoped context
- Channel - Streaming primitive
- Telemetry - Execution tracking
Classes ​
| Class | Description |
|---|---|
| Channel | Core Channel primitive. Works standalone in any Node environment. Uses EventEmitter internally for pub/sub. |
| ChannelSession | Channel session manages a collection of channels. Sessions persist across multiple engine executions. |
| Context | Static class for managing execution context via AsyncLocalStorage. |
| ContextProvider | - |
| ExecutionTracker | Unified execution tracker for procedures and hooks. Handles automatic telemetry, metrics tracking, and propagation. |
| ProcedureBase | - |
| ProcedureGraph | Procedure graph for tracking parent-child relationships |
| ProcedureNode | Procedure node stored in the graph |
| Telemetry | Global telemetry service for tracing, spans, and metrics. |
Interfaces ​
| Interface | Description |
|---|---|
| ChannelEvent | Normalized channel event structure. Loosely structured but normalized for consistency. |
| ChannelServiceInterface | Kernel-level interface for channel service access. This allows KernelContext to reference channels without creating a circular dependency between kernel and engine packages. |
| ChannelTarget | Target specification for event routing. Used by transports to determine which connections receive the event. |
| ContextMetadata | Extensible metadata storage within the context. |
| ContextMetrics | Metrics accumulated during procedure execution. |
| Counter | A counter metric that only increases (e.g., request count, error count). |
| ExecutionEvent | Event emitted during procedure execution. |
| ExecutionHandle | Handle for monitoring and controlling a running procedure execution. |
| ExecutionTrackerOptions | - |
| Histogram | A histogram metric for recording distributions (e.g., latency, sizes). |
| KernelContext | Execution context that flows through all async operations via AsyncLocalStorage. |
| KernelLogger | Kernel logger interface with structured logging and context injection. |
| LoggerConfig | - |
| LogMethod | Log method signature supporting both message-first and object-first forms. |
| MetricAttributes | Attributes for metrics, used for filtering and grouping. |
| MiddlewarePipeline | A reusable bundle of middleware that can be applied to procedures. |
| Procedure | A callable function wrapper with middleware, validation, and execution control. |
| ProcedureEnvelope | Metadata envelope passed to middleware containing execution context. |
| ProcedureOptions | Configuration options for creating a procedure. |
| Span | A span represents a unit of work or operation within a trace. Spans track timing, attributes, and errors for observability. |
| StaticMiddleware | Static middleware configuration for a class. Maps procedure names to middleware arrays or pipelines. |
| StreamTag | Tagged stream item from mergeStreams when using a Record input. |
| TelemetryProvider | Interface for telemetry providers (e.g., OpenTelemetry, DataDog). |
| UserContext | User information associated with the current execution context. |
Type Aliases ​
| Type Alias | Description |
|---|---|
| AsProcedure | Helper type to transform a method signature to Procedure type. Extracts args and return type, then creates Procedure<TArgs, TOutput>. |
| BrandedContext | Type for branded context objects |
| ContextFieldsExtractor | Function to extract fields from KernelContext for logging. Return an object with fields to include in every log entry. |
| ExecutionBoundaryConfig | Execution boundary behavior configuration. |
| ExtractArgs | Helper type to extract argument types from a function signature. Handles functions with this parameters and generator functions. |
| ExtractReturn | Helper type to extract return type from a function signature. Handles both Promise and direct returns, and unwraps Promise. Preserves AsyncIterable as-is. |
| HandleFactory | Factory function for creating custom execution handles. |
| LogLevel | Log levels supported by the kernel logger. |
| Middleware | Middleware function that can intercept and transform procedure execution. |
| ProcedureStatus | Procedure status |
| ProcedureWithHandle | A procedure variant that returns an execution handle along with the result. |
| WithProcedures | Helper type to transform all methods in a class to Procedures. |
Variables ​
| Variable | Description |
|---|---|
| defaultContextFields | The default context fields extractor. Exports core KernelContext fields only. Use with composeContextFields to extend. |
| KERNEL_CONTEXT_SYMBOL | Symbol used to brand context objects for deterministic detection. This allows procedures to distinguish context from regular arguments. |
| Logger | Logger singleton for AIDK applications. |
Functions ​
| Function | Description |
|---|---|
| addMetric | Add a metric value (accumulates). Supports dot notation for nested paths: 'usage.inputTokens' |
| addUsageMetrics | Add usage metrics from a usage object. Converts nested structure to flat dot-notation keys. |
| applyMiddleware | Type-safe helper to apply middleware to a Procedure while preserving types. |
| applyRegistryMiddleware | Type-safe helper to apply middleware from a registry/hook system. |
| composeContextFields | Compose multiple context field extractors into one. Later extractors override earlier ones for the same keys. |
| context | Brand a context object with a Symbol for deterministic detection. This allows procedures to deterministically identify context vs regular args. |
| createHook | Create a Hook Procedure from a function. |
| createPipeline | Create a reusable middleware pipeline. |
| createProcedure | Create a Procedure from a function (for use in class property initializers). |
| generatorProcedure | - |
| getChannel | Get a channel from the current context. |
| getMetric | Get a metric value. Supports dot notation for nested paths: 'usage.inputTokens' |
| getUsageMetrics | Get usage metrics as an object. Converts flat dot-notation keys back to nested structure. |
| hookDecorator | - |
| isAsyncIterable | Type guard to check if an object is an async iterable. |
| isKernelContext | Check if an object is a branded context (deterministic check via Symbol). This is 100% reliable - no heuristics needed. |
| mapStream | Transform items in an async stream using a mapper function. |
| mergeStreams | Merge multiple async streams into a single stream, yielding items as they arrive. |
| pipe | Pipe multiple procedures together, passing the output of each to the next. |
| procedureDecorator | - |
| publishChannel | Publish an event to a channel using the current context. |
| setMetric | Set a metric value (overwrites). Supports dot notation for nested paths: 'usage.inputTokens' |
| subscribeChannel | Subscribe to events on a channel using the current context. |
| tapStream | Perform side effects on each stream item without modifying the stream. |
| tryGetChannel | Try to get a channel from the current context (returns undefined if not available). |
| waitForChannelResponse | Wait 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