Documentation / @agentick/core / SessionImpl
Class: SessionImpl<P> ​
Defined in: core/src/app/session.ts:163
Session implementation.
A session manages the execution lifecycle: compile JSX, call model, execute tools. Component state (hooks, signals) persists across ticks within a session.
Extends ​
EventEmitter
Type Parameters ​
P ​
P = { }
Implements ​
Session<P>
Constructors ​
Constructor ​
new SessionImpl<
P>(Component,appOptions,sessionOptions?):SessionImpl<P>
Defined in: core/src/app/session.ts:273
Parameters ​
Component ​
appOptions ​
sessionOptions? ​
SessionOptions = {}
Returns ​
SessionImpl<P>
Overrides ​
EventEmitter.constructor
Properties ​
dispatch ​
dispatch:
Procedure<(name,input) =>Promise<ContentBlock[]>,true>
Defined in: core/src/app/session.ts:415
Dispatch a tool by name (or alias) from the user side. Works on any registered tool regardless of audience. Ensures tree is mounted before dispatch. Validates input against the tool's schema before calling the handler.
Known limitation: If called concurrently with render(), ctx.clear() during compilation briefly removes tools. Both operations are client-initiated so this race doesn't occur in single-user practice.
Implementation of ​
id ​
readonlyid:string
Defined in: core/src/app/session.ts:164
Unique session ID
Implementation of ​
queue ​
queue:
Procedure<(message) =>Promise<void>,true>
Defined in: core/src/app/session.ts:404
Queue a message to be included in the next tick.
Queues the message and notifies onMessage hooks if components are mounted. Does NOT trigger execution - use send() if you want to trigger render().
This is a procedure (without execution boundary) so you can use:
session.queue.withContext({ userId }).exec(message)session.queue.use(middleware).exec(message)
Implementation of ​
render ​
render:
Procedure<(props,options?) =>SessionExecutionHandle,true>
Defined in: core/src/app/session.ts:406
Run the component with props, execute tick loop.
Returns SessionExecutionHandle (AsyncIterable, not PromiseLike). If already running, returns the existing handle (hot-update support).
Note: If called with no props (or empty props) and no queued messages, returns an empty handle and does not run a tick.
Example ​
const handle = await session.render(props);
handle.queueMessage({ role: "user", content: [...] });
const result = await handle.result;Implementation of ​
send ​
send:
Procedure<(input) =>SessionExecutionHandle,true>
Defined in: core/src/app/session.ts:405
Send messages and/or update props.
Returns SessionExecutionHandle (AsyncIterable, not PromiseLike):
await handle.result→ SendResult when execution completesfor await (const event of handle)→ stream events
Concurrent calls return THE SAME handle - messages queue, handle resolves when the tick loop settles.
Example ​
// Await Procedure to get handle, then stream events
const handle = await session.send({ messages: [...] });
for await (const event of handle) {
console.log(event);
}
// Or get the result directly via ProcedurePromise chaining
const result = await session.send({ messages: [...] }).result;Implementation of ​
spawn ​
spawn:
Procedure<(component,input?,options?) =>SessionExecutionHandle,true>
Defined in: core/src/app/session.ts:407
Spawn a child session with a different agent/component.
Creates an ephemeral child session, runs it to completion, and returns the same SessionExecutionHandle as session.send().
The child session is NOT registered in the App's session registry. Parent abort propagates to child. Max spawn depth is 10.
By default, child inherits parent's structural options (model, tools, runner, maxTicks). Use options to override any of these.
Param ​
ComponentFunction or JSX element
Param ​
Optional SendInput for the child session
Param ​
Optional overrides for the child's structural options
Example ​
// Basic spawn
const handle = await session.spawn(ResearchAgent, { messages });
// Spawn with different runner
const handle = await session.spawn(CodeAgent, { messages }, {
runner: replRunner,
});Implementation of ​
Accessors ​
children ​
Get Signature ​
get children(): readonly
Session<{ }>[]
Defined in: core/src/app/session.ts:369
Active child sessions (currently running spawns).
Returns ​
readonly Session<{ }>[]
Active child sessions (currently running spawns).
Implementation of ​
currentTick ​
Get Signature ​
get currentTick():
number
Defined in: core/src/app/session.ts:349
Current tick number
Returns ​
number
Current tick number
Implementation of ​
isAborted ​
Get Signature ​
get isAborted():
boolean
Defined in: core/src/app/session.ts:353
Whether the session has been aborted
Returns ​
boolean
Whether the session has been aborted
Implementation of ​
isTerminal ​
Get Signature ​
get isTerminal():
boolean
Defined in: core/src/app/session.ts:340
Whether the session is in a terminal state (closed).
Returns ​
boolean
Whether the session is in a terminal state (closed).
Implementation of ​
metadata ​
Get Signature ​
get metadata():
Readonly<Record<string,unknown>>
Defined in: core/src/app/session.ts:365
Immutable identity labels set at creation time.
Returns ​
Readonly<Record<string, unknown>>
Immutable identity labels set at creation time.
Implementation of ​
parent ​
Get Signature ​
get parent():
Session<{ }> |null
Defined in: core/src/app/session.ts:357
Parent session, or null for root sessions.
Returns ​
Session<{ }> | null
Parent session, or null for root sessions.
Implementation of ​
parentSessionId ​
Get Signature ​
get parentSessionId():
string|null
Defined in: core/src/app/session.ts:361
Parent session ID as a string. Survives persistence/restore.
- Ephemeral spawn children have both
parent(live ref) andparentSessionId. - Persistent children (delegation) have only
parentSessionId.
Returns ​
string | null
Parent session ID as a string. Survives persistence/restore.
- Ephemeral spawn children have both
parent(live ref) andparentSessionId. - Persistent children (delegation) have only
parentSessionId.
Implementation of ​
queuedMessages ​
Get Signature ​
get queuedMessages(): readonly
Message[]
Defined in: core/src/app/session.ts:373
Messages queued for the next tick (read-only view)
Returns ​
readonly Message[]
Messages queued for the next tick (read-only view)
Implementation of ​
schedulerState ​
Get Signature ​
get schedulerState():
SchedulerState|null
Defined in: core/src/app/session.ts:396
Observable scheduler state for DevTools.
Returns a Signal containing the scheduler's current state, including status, pending reasons, and reconciliation metrics.
Returns null if the session hasn't been initialized yet.
Example ​
// In DevTools
effect(() => {
const state = session.schedulerState?.();
if (state) {
console.log(`Status: ${state.status}, reconciles: ${state.reconcileCount}`);
}
});Returns ​
SchedulerState | null
Current scheduler state for DevTools.
Returns the scheduler's current state, including status, pending reasons, and reconciliation metrics.
Returns null if the session hasn't been initialized yet.
Implementation of ​
status ​
Get Signature ​
get status():
SessionStatus
Defined in: core/src/app/session.ts:335
Current session status
Returns ​
Current session status
Implementation of ​
Methods ​
channel() ​
channel(
name):Channel
Defined in: core/src/app/session.ts:1039
Get a named channel for pub/sub communication.
Channels allow external code to communicate with running components and vice versa. Components can subscribe to channels using useChannel().
Built-in channels:
- 'messages': Message queue updates
- 'tool_confirmation': Tool confirmation requests/responses
Parameters ​
name ​
string
Channel name
Returns ​
The channel instance
Example ​
// External code publishes to session
session.channel('custom').publish({ action: 'refresh' });
// Component subscribes
const channel = useChannel('custom');
useEffect(() => channel.subscribe(handleEvent), []);Implementation of ​
clearAbort() ​
clearAbort():
void
Defined in: core/src/app/session.ts:1084
Clear the aborted state flag, allowing the session to continue.
Returns ​
void
Implementation of ​
close() ​
close():
Promise<void>
Defined in: core/src/app/session.ts:1899
Close the session and release resources. Awaits runner cleanup (onDestroy) and child session teardown.
Returns ​
Promise<void>
Implementation of ​
events() ​
events():
AsyncIterable<StreamEvent>
Defined in: core/src/app/session.ts:1194
Convert EventEmitter to AsyncIterable for the current/next execution.
Call this before send() to capture events as an AsyncIterable. The iterable completes when the execution finishes.
Returns ​
AsyncIterable<StreamEvent>
Implementation of ​
getRecording() ​
getRecording():
SessionRecording|null
Defined in: core/src/app/session.ts:1513
Get the session recording.
Returns null if recording was never started.
Returns ​
SessionRecording | null
Example ​
const session = app.session({ recording: 'full' });
await session.render({ query: "Hello!" });
const recording = session.getRecording();
console.log(recording?.snapshots.length); // 1
console.log(recording?.summary.totalUsage);Implementation of ​
getSnapshotAt() ​
getSnapshotAt(
tick):TickSnapshot|null
Defined in: core/src/app/session.ts:1522
Get a specific tick's snapshot.
Parameters ​
tick ​
number
Tick number (1-indexed)
Returns ​
TickSnapshot | null
The snapshot, or null if not found or recording not enabled
Example ​
const snapshot = session.getSnapshotAt(2);
if (snapshot) {
console.log(snapshot.model.output.content);
console.log(snapshot.tools.calls);
}Implementation of ​
getToolDefinitions() ​
getToolDefinitions():
Promise<ToolDefinition[]>
Defined in: core/src/app/session.ts:1105
Get tool definitions for all registered tools.
Returns the provider-compatible ToolDefinition[] (with JSON Schema). Includes ALL tools (model + user + all audience), with audience field set. Mounts the component tree if not already mounted.
Returns ​
Promise<ToolDefinition[]>
Implementation of ​
inspect() ​
inspect():
SessionInspection
Defined in: core/src/app/session.ts:1410
Inspect the current session state for debugging.
Returns a snapshot of live status, last outputs, aggregated usage, and component/hook summaries. Useful for DevTools integration and debugging mid-execution.
Returns ​
Example ​
const session = app.session();
await session.render({ query: "Hello!" });
const info = session.inspect();
console.log('Tick:', info.currentTick);
console.log('Components:', info.components.names);
console.log('Total tokens:', info.totalUsage.totalTokens);Implementation of ​
interrupt() ​
interrupt(
message?,reason?):void
Defined in: core/src/app/session.ts:1064
Interrupt the current execution, optionally with a message.
If the session is running:
- Aborts the current execution
- Queues the message (if provided)
If the session is idle:
- Queues the message (if provided)
Parameters ​
message? ​
Optional message to queue
reason? ​
string
Optional abort reason
Returns ​
void
Implementation of ​
mount() ​
mount():
Promise<void>
Defined in: core/src/app/session.ts:1088
Mount the component tree without calling the model. Makes tools and commands available for dispatch. No-op if already mounted.
Returns ​
Promise<void>
Implementation of ​
notifyParent() ​
notifyParent(
message):Promise<void>
Defined in: core/src/app/session.ts:1885
Deliver a message to this session's parent inbox.
Uses parentSessionId to write directly to the inbox storage. Throws if no parentSessionId is set or inbox storage is unavailable.
Parameters ​
message ​
Returns ​
Promise<void>
Implementation of ​
processInboxMessages() ​
processInboxMessages():
Promise<void>
Defined in: core/src/app/session.ts:1351
Internal
Process all pending inbox messages. Called by App.processInbox().
Returns ​
Promise<void>
pushEvent() ​
pushEvent(
event):void
Defined in: core/src/app/session.ts:1228
Push an event into this session's event stream.
The event goes through the full enrichment pipeline (id, tick, timestamp, sequence, devtools forwarding) and is delivered to all consumers: onEvent callbacks, EventEmitter listeners, and AsyncIterable readers.
Use this to inject external events (e.g. forwarding confirmations from child sessions that aren't connected via spawn).
Parameters ​
event ​
Record<string, unknown> & object
Returns ​
void
Implementation of ​
setInboxStorage() ​
setInboxStorage(
storage):void
Defined in: core/src/app/session.ts:1334
Internal
Connect this session to an inbox storage backend. Subscribes to notifications and drains any pre-existing pending messages.
Parameters ​
storage ​
Returns ​
void
setPersistCallback() ​
setPersistCallback(
callback):void
Defined in: core/src/app/session.ts:1325
Internal
Set the auto-persist callback. Called by the App when a store is configured.
Parameters ​
callback ​
(snapshot) => Promise<void>
Returns ​
void
setSnapshotForResolve() ​
setSnapshotForResolve(
snapshot):void
Defined in: core/src/app/session.ts:1402
Internal
Set a snapshot to be applied/resolved when compilation infrastructure is created.
Parameters ​
snapshot ​
Returns ​
void
snapshot() ​
snapshot():
SessionSnapshot
Defined in: core/src/app/session.ts:1303
Export session state for persistence.
Returns ​
Implementation of ​
startRecording() ​
startRecording(
mode):void
Defined in: core/src/app/session.ts:1478
Start recording tick snapshots.
If already recording, changes the mode.
Parameters ​
mode ​
Recording mode ('full' or 'lightweight')
Returns ​
void
Example ​
const session = app.session();
session.startRecording('full');
await session.render({ query: "Hello!" });
const recording = session.getRecording();Implementation of ​
stopRecording() ​
stopRecording():
void
Defined in: core/src/app/session.ts:1502
Stop recording tick snapshots.
The recording is preserved and can still be retrieved with getRecording().
Returns ​
void
Implementation of ​
submitToolResult() ​
submitToolResult(
toolUseId,response):void
Defined in: core/src/app/session.ts:1048
Submit tool confirmation result out-of-band. Used when client sends tool confirmation outside of execution handle.
Parameters ​
toolUseId ​
string
response ​
approved ​
boolean
modifiedArguments? ​
Record<string, unknown>
reason? ​
string
Returns ​
void