AIDK API Reference / aidk-kernel / Context
Class: Context ​
Defined in: packages/kernel/src/context.ts:287
Static class for managing execution context via AsyncLocalStorage.
Context flows automatically through all async operations without explicit passing. Use Context.run() to establish context, and Context.get() to access it.
Examples ​
// Create and run with context
const ctx = Context.create({ user: { id: 'user-1' } });
await Context.run(ctx, async () => {
const current = Context.get();
console.log(current.user?.id); // 'user-1'
// Context flows to nested calls
await someAsyncFunction(); // Can access Context.get() inside
});// Each parallel task gets its own context to avoid races
const [a, b] = await Promise.all([
Context.fork({ procedurePid: 'task-1' }, () => doTask1()),
Context.fork({ procedurePid: 'task-2' }, () => doTask2()),
]);// Events go to both global bus and operation handle
Context.emit('progress', { percent: 50 }, 'my-tool');See ​
- KernelContext - The context interface
- context - Brand an object as context for procedure detection
Constructors ​
Constructor ​
new Context(): Context;Returns ​
Context
Methods ​
child() ​
static child(overrides: Partial<KernelContext>): KernelContext;Defined in: packages/kernel/src/context.ts:351
Creates a child context that inherits from the current context (or creates a new root). The child context is a shallow copy - objects like events, procedureGraph, and channels are shared with the parent (intentionally, for coordination).
Scalar values like procedurePid, procedureNode, and origin can be safely overridden in the child without affecting the parent.
Parameters ​
| Parameter | Type | Description |
|---|---|---|
overrides | Partial<KernelContext> | Properties to override in the child context |
Returns ​
A new context object inheriting from the current context
Example ​
// Create child context with new procedure ID
const childCtx = Context.child({ procedurePid: 'new-pid' });
await Context.run(childCtx, async () => {
// This context has its own procedurePid but shares events, graph, etc.
});create() ​
static create(overrides: Partial<Omit<KernelContext, "events">>): KernelContext;Defined in: packages/kernel/src/context.ts:302
Creates a new root context with default values.
Parameters ​
| Parameter | Type | Description |
|---|---|---|
overrides | Partial<Omit<KernelContext, "events">> | Partial context to merge with defaults |
Returns ​
A new KernelContext
Example ​
const ctx = Context.create({
user: { id: 'user-1' },
metadata: { feature: 'chat' }
});emit() ​
static emit(
type: string,
payload: any,
source: string): void;Defined in: packages/kernel/src/context.ts:425
Helper to emit an event on the current context. Events are broadcast to:
- The context's local event bus (ctx.events)
- The operation handle (ctx.executionHandle) if present
- All global subscribers registered via subscribeGlobal()
Parameters ​
| Parameter | Type | Default value |
|---|---|---|
type | string | undefined |
payload | any | undefined |
source | string | "system" |
Returns ​
void
fork() ​
static fork<T>(overrides: Partial<KernelContext>, fn: () => Promise<T>): Promise<T>;Defined in: packages/kernel/src/context.ts:384
Creates a child context and runs a function within it. Convenience method combining child() and run().
This is the safe way to run parallel procedures - each gets its own context object so mutations don't race.
Type Parameters ​
| Type Parameter |
|---|
T |
Parameters ​
| Parameter | Type | Description |
|---|---|---|
overrides | Partial<KernelContext> | Properties to override in the child context |
fn | () => Promise<T> | Function to run within the child context |
Returns ​
Promise<T>
The result of the function
Example ​
// Run parallel procedures safely
const [result1, result2] = await Promise.all([
Context.fork({ procedurePid: 'proc-1' }, async () => doWork1()),
Context.fork({ procedurePid: 'proc-2' }, async () => doWork2()),
]);get() ​
static get(): KernelContext;Defined in: packages/kernel/src/context.ts:392
Gets the current context. Throws if not found.
Returns ​
hasGlobalSubscribers() ​
static hasGlobalSubscribers(): boolean;Defined in: packages/kernel/src/context.ts:498
Check if there are any global subscribers. Useful for conditional event emission to avoid overhead when no one is listening.
Returns ​
boolean
run() ​
static run<T>(context: KernelContext, fn: () => Promise<T>): Promise<T>;Defined in: packages/kernel/src/context.ts:327
Runs a function within the given context. All async operations within fn will have access to this context.
Type Parameters ​
| Type Parameter |
|---|
T |
Parameters ​
| Parameter | Type | Description |
|---|---|---|
context | KernelContext | The context to run within |
fn | () => Promise<T> | Async function to execute |
Returns ​
Promise<T>
The result of the function
setTick() ​
static setTick(tick: number): void;Defined in: packages/kernel/src/context.ts:411
Set the current tick number in the context. Called by the engine at the start of each tick.
Parameters ​
| Parameter | Type |
|---|---|
tick | number |
Returns ​
void
subscribeGlobal() ​
static subscribeGlobal(handler: (event: ExecutionEvent, ctx: KernelContext) => void): () => void;Defined in: packages/kernel/src/context.ts:487
Subscribe to ALL context events globally. This is useful for observability tools like DevTools that need to see all procedure:start/end/error events across all contexts.
Parameters ​
| Parameter | Type | Description |
|---|---|---|
handler | (event: ExecutionEvent, ctx: KernelContext) => void | Callback that receives every event with its context |
Returns ​
Unsubscribe function
(): void;Returns ​
void
Example ​
const unsubscribe = Context.subscribeGlobal((event, ctx) => {
if (event.type === 'procedure:start') {
console.log(`Procedure ${event.payload.name} started`);
}
});
// Later, to stop receiving events:
unsubscribe();tryGet() ​
static tryGet(): KernelContext | undefined;Defined in: packages/kernel/src/context.ts:403
Gets the current context or returns undefined if not found.
Returns ​
KernelContext | undefined