Skip to content

Documentation / @agentick/kernel / Context

Class: Context ​

Defined in: kernel/src/context.ts:346

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 ​

new Context(): Context

Returns ​

Context

Methods ​

brand() ​

static brand(ctx): KernelContext

Defined in: kernel/src/context.ts:384

Parameters ​

ctx ​

Partial<KernelContext>

Returns ​

KernelContext


child() ​

static child(overrides?): KernelContext

Defined in: kernel/src/context.ts:423

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 ​

overrides? ​

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

static create(overrides?): KernelContext

Defined in: kernel/src/context.ts:361

Creates a new root context with default values.

Parameters ​

overrides? ​

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

static emit(type, payload, source?): void

Defined in: kernel/src/context.ts:530

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 ​

type ​

string

payload ​

any

source? ​

string = "system"

Returns ​

void


fork() ​

static fork<T>(overrides, fn): Promise<T>

Defined in: kernel/src/context.ts:456

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 ​

T ​

T

Parameters ​

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 ​

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

static get(): KernelContext

Defined in: kernel/src/context.ts:497

Gets the current context. Throws if not found.

Returns ​

KernelContext


hasGlobalSubscribers() ​

static hasGlobalSubscribers(): boolean

Defined in: kernel/src/context.ts:603

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>(ctx, fn): Promise<T>

Defined in: kernel/src/context.ts:399

Runs a function within the given context. All async operations within fn will have access to this context.

Type Parameters ​

T ​

T

Parameters ​

ctx ​

Partial<KernelContext>

fn ​

() => Promise<T>

Async function to execute

Returns ​

Promise<T>

The result of the function


setTick() ​

static setTick(tick): void

Defined in: kernel/src/context.ts:516

Set the current tick number in the context. Called by the engine at the start of each tick.

Parameters ​

tick ​

number

Returns ​

void


subscribeGlobal() ​

static subscribeGlobal(handler): () => void

Defined in: kernel/src/context.ts:592

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 ​

handler ​

(event, ctx) => void

Callback that receives every event with its context

Returns ​

Unsubscribe function

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

static tryGet(): KernelContext | undefined

Defined in: kernel/src/context.ts:508

Gets the current context or returns undefined if not found.

Returns ​

KernelContext | undefined


withBaggage() ​

static withBaggage(attrs): void

Defined in: kernel/src/context.ts:488

Merge attrs onto the current ALS context's baggage. If no baggage is set yet, this initializes it. Mutates via reassignment of the baggage slot, not in-place mutation of the existing object — siblings or parents that captured a prior reference are unaffected.

Scoping is the ALS layer's responsibility: any Context.fork / Context.run you're already inside bounds the mutation. To get scoped baggage that restores on exit, fork first:

typescript
await Context.fork({}, async () => {
  Context.withBaggage({ "app.location": "ernesto" });
  await runAgent();
});
// outside the fork, baggage is whatever it was before

Inside the same context (no fork), repeated calls layer — last writer wins per key. No-op when called outside any context.

Naming follows the with* convention used by procedures (proc.withBaggage, proc.withMetadata, proc.withContext). Both surfaces describe the same action: "for this scope, apply these values."

Parameters ​

attrs ​

Record<string, AttributeValue>

Baggage keys to merge onto the current context

Returns ​

void

Released under the ISC License.