Skip to content

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 ​

typescript
// 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
});
typescript
// 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()),
]);
typescript
// Events go to both global bus and operation handle
Context.emit('progress', { percent: 50 }, 'my-tool');

See ​

Constructors ​

Constructor ​

ts
new Context(): Context;

Returns ​

Context

Methods ​

child() ​

ts
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 ​

ParameterTypeDescription
overridesPartial<KernelContext>Properties to override in the child context

Returns ​

KernelContext

A new context object inheriting from the current context

Example ​

typescript
// 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() ​

ts
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 ​

ParameterTypeDescription
overridesPartial<Omit<KernelContext, "events">>Partial context to merge with defaults

Returns ​

KernelContext

A new KernelContext

Example ​

typescript
const ctx = Context.create({
  user: { id: 'user-1' },
  metadata: { feature: 'chat' }
});

emit() ​

ts
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:

  1. The context's local event bus (ctx.events)
  2. The operation handle (ctx.executionHandle) if present
  3. All global subscribers registered via subscribeGlobal()

Parameters ​

ParameterTypeDefault value
typestringundefined
payloadanyundefined
sourcestring"system"

Returns ​

void


fork() ​

ts
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 ​

ParameterTypeDescription
overridesPartial<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 ​

typescript
// 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() ​

ts
static get(): KernelContext;

Defined in: packages/kernel/src/context.ts:392

Gets the current context. Throws if not found.

Returns ​

KernelContext


hasGlobalSubscribers() ​

ts
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() ​

ts
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 ​

ParameterTypeDescription
contextKernelContextThe context to run within
fn() => Promise<T>Async function to execute

Returns ​

Promise<T>

The result of the function


setTick() ​

ts
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 ​

ParameterType
ticknumber

Returns ​

void


subscribeGlobal() ​

ts
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 ​

ParameterTypeDescription
handler(event: ExecutionEvent, ctx: KernelContext) => voidCallback that receives every event with its context

Returns ​

Unsubscribe function

ts
(): void;
Returns ​

void

Example ​

typescript
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() ​

ts
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

Released under the MIT License.