AIDK API Reference / aidk/utils / CompileJSXService
Class: CompileJSXService ​
Defined in: packages/core/src/utils/compile-jsx-service.ts:1214
Comprehensive compilation service for JSX elements.
This service provides all the setup and compilation logic that Engine needs before and after calling the model. Engine can delegate compilation and state management to this service to simplify the tick loop.
Features:
- Component hooks (for component lifecycle)
- Lifecycle hooks (onTickStart, onAfterCompile, onTickEnd)
- Tool registration and MCP server initialization
- Model-based renderer resolution
- Process methods support (fork/spawn abstraction)
- Session-based API for multi-tick execution
- Post-model state ingestion and component lifecycle hooks
- Tick control resolution
Separation of Concerns:
- Service handles: component hooks, lifecycle hooks, compilation, state management
- Engine handles: model hooks, tool hooks, engine hooks, model/tool execution
Examples ​
const service = new CompileJSXService({
tools: [MyTool],
modelGetter: (com) => myModel,
});
const session = await service.createSession({
input: { timeline: [], sections: {} },
rootElement: <MyAgent />,
});
while (session.shouldContinue() && session.tick <= 10) {
// Pre-model: compile and get input
const { formatted, model, tools } = await session.compileTick();
// Model execution (caller's responsibility)
const response = await model.generate(formatted);
// Tool execution (caller's responsibility)
const toolResults = await executeTools(response.toolCalls, tools);
// Post-model: ingest results and run component lifecycle
await session.ingestTickResult({ response, toolResults });
// Advance to next tick
session.advanceTick();
}
const finalState = await session.complete();const result = await service.compile(<MyComponent />, {
timeline: [],
sections: {}
});
console.log(result.formatted);// Engine creates service with only the registries the service needs
// (component and lifecycle hooks are service concerns)
const compileService = new CompileJSXService({
tools: this.getTools(),
hookRegistries: {
components: this.componentHooksRegistry,
lifecycle: this.lifecycleHooksRegistry,
},
modelGetter: (com) => this.getRawModel(com),
processMethods: { fork: ..., spawn: ..., ... }, // For fork/spawn support
});
const session = await compileService.createSession({ input, rootElement });
// Engine's tick loop is now much simpler:
// (Model, tool, and engine hooks are handled by Engine separately)
while (session.shouldContinue()) {
const { model, modelInput, tools } = await session.compileTick();
const response = await this.executeModel(model, modelInput);
const toolResults = await this.executeTools(response.toolCalls, tools);
await session.ingestTickResult({ response, toolResults });
session.advanceTick();
}Constructors ​
Constructor ​
new CompileJSXService(config: CompileJSXServiceConfig): CompileJSXService;Defined in: packages/core/src/utils/compile-jsx-service.ts:1223
Parameters ​
| Parameter | Type |
|---|---|
config | CompileJSXServiceConfig |
Returns ​
CompileJSXService
Properties ​
| Property | Modifier | Type | Description | Defined in |
|---|---|---|---|---|
componentHooksRegistry | readonly | ComponentHookRegistry | - | packages/core/src/utils/compile-jsx-service.ts:1215 |
lifecycleHooksRegistry | readonly | EngineLifecycleHookRegistry | - | packages/core/src/utils/compile-jsx-service.ts:1216 |
run | public | Procedure<(config: CompileSessionConfig, fn: (compiled: CompileTickResult) => Promise<TickResultInput>) => Promise<COMInput>> | - | packages/core/src/utils/compile-jsx-service.ts:1719 |
runStream | public | Procedure<<TChunk>(config: CompileSessionConfig, executorOrCallbacks: | TickExecutor<TChunk> | RunStreamCallbacks<TChunk>) => AsyncGenerator<SessionStreamEvent<TChunk>>> | Streaming execution as a Procedure. Supports context injection and middleware. Example const events = await service.runStream .withContext({ userId: 'abc' }) .run(config, executeTick); for await (const event of events) { // handle events } | packages/core/src/utils/compile-jsx-service.ts:1866 |
Accessors ​
hooks ​
Get Signature ​
get hooks(): {
components: ComponentHookRegistry;
lifecycle: EngineLifecycleHookRegistry;
};Defined in: packages/core/src/utils/compile-jsx-service.ts:2143
Get hook registries for dynamic hook registration.
Note: Only component and lifecycle hooks are service concerns. Model, tool, and engine hooks are Engine concerns.
Returns ​
{
components: ComponentHookRegistry;
lifecycle: EngineLifecycleHookRegistry;
}| Name | Type | Defined in |
|---|---|---|
components | ComponentHookRegistry | packages/core/src/utils/compile-jsx-service.ts:2145 |
lifecycle | EngineLifecycleHookRegistry | packages/core/src/utils/compile-jsx-service.ts:2146 |
Methods ​
_run() ​
_run(config: CompileSessionConfig, fn: (compiled: CompileTickResult) => Promise<TickResultInput>): Promise<COMInput>;Defined in: packages/core/src/utils/compile-jsx-service.ts:1703
Execute a program using a CompileSession.
Parameters ​
| Parameter | Type | Description |
|---|---|---|
config | CompileSessionConfig | Session configuration |
fn | (compiled: CompileTickResult) => Promise<TickResultInput> | Function to execute for each tick |
Returns ​
Promise<COMInput>
Final COM input
_runStream() ​
_runStream<TChunk>(config: CompileSessionConfig, executorOrCallbacks:
| TickExecutor<TChunk>
| RunStreamCallbacks<TChunk>): AsyncGenerator<SessionStreamEvent<TChunk>>;Defined in: packages/core/src/utils/compile-jsx-service.ts:1775
Execute a program with streaming support.
Supports two overloaded forms:
- Simple function:
runStream(config, executeTick) - Callbacks object:
runStream(config, callbacks)
When executeTick (or callbacks.onTick) returns an AsyncIterable:
- Chunks are yielded as
{ type: 'chunk', tick, chunk }events finalizeChunksMUST be provided to convert chunks to TickResultInput
When it returns a Promise<TickResultInput>:
- No chunks are yielded, result is used directly
Type Parameters ​
| Type Parameter | Default type |
|---|---|
TChunk | unknown |
Parameters ​
| Parameter | Type |
|---|---|
config | CompileSessionConfig |
executorOrCallbacks | | TickExecutor<TChunk> | RunStreamCallbacks<TChunk> |
Returns ​
AsyncGenerator<SessionStreamEvent<TChunk>>
Examples ​
for await (const event of service.runStream(config, async (compiled) => {
const response = await model.generate(compiled.formatted);
return { response };
})) {
console.log(event.type);
}for await (const event of service.runStream(config, {
onTick: async function* (compiled) {
for await (const chunk of model.stream(compiled.formatted)) {
yield chunk;
}
},
finalizeChunks: (chunks) => {
const response = mergeChunks(chunks);
return { response };
},
})) {
if (event.type === 'chunk') {
process.stdout.write(event.chunk.text);
}
}addRenderer() ​
addRenderer(name: string, renderer: ContentRenderer): void;Defined in: packages/core/src/utils/compile-jsx-service.ts:2153
Add a renderer.
Parameters ​
| Parameter | Type |
|---|---|
name | string |
renderer | ContentRenderer |
Returns ​
void
callLifecycleHooks() ​
callLifecycleHooks<T>(hookName: T, args: EngineLifecycleHookArgs<T>): Promise<void>;Defined in: packages/core/src/utils/compile-jsx-service.ts:1356
Call lifecycle hooks.
Type Parameters ​
| Type Parameter |
|---|
T extends EngineLifecycleHookName |
Parameters ​
| Parameter | Type |
|---|---|
hookName | T |
args | EngineLifecycleHookArgs<T> |
Returns ​
Promise<void>
checkAbort() ​
checkAbort(): void;Defined in: packages/core/src/utils/compile-jsx-service.ts:1590
Check if compilation should be aborted and throw if so. Called before and after compilation (not during).
Returns ​
void
clearAndReRegisterTools() ​
clearAndReRegisterTools(com: ContextObjectModel): void;Defined in: packages/core/src/utils/compile-jsx-service.ts:1578
Clear COM ephemeral state and re-register tools. Called before each tick compilation to reset timeline/sections.
Parameters ​
| Parameter | Type | Description |
|---|---|---|
com | ContextObjectModel | COM instance to clear |
Returns ​
void
compile() ​
compile(
jsx: ComponentDefinition,
input: Partial<EngineInput>,
handle?: ExecutionHandle): Promise<CompileJSXResult>;Defined in: packages/core/src/utils/compile-jsx-service.ts:1898
Compile JSX with full setup (convenience method).
This performs all the setup that Engine does before calling the model:
- Creates COM with proper metadata and services
- Initializes MCP servers and discovers tools
- Registers tools
- Sets up compiler with hooks
- Creates structure renderer
- Resolves renderer from model capabilities
- Calls lifecycle hooks
- Compiles until stable
- Applies and formats the result
Parameters ​
| Parameter | Type | Description |
|---|---|---|
jsx | ComponentDefinition | The JSX element or component definition to compile |
input | Partial<EngineInput> | Initial COM input (timeline, sections, metadata, etc.) |
handle? | ExecutionHandle | Optional execution handle |
Returns ​
Promise<CompileJSXResult>
Compilation result with compiled structure, formatted output, and metadata
compileTick() ​
compileTick(
com: ContextObjectModel,
compiler: FiberCompiler,
structureRenderer: StructureRenderer,
rootElement: Element,
tick: number,
previous?: COMInput,
current?: COMOutput,
stopReason?: string,
shouldContinue?: boolean,
handle?: ExecutionHandle): Promise<{
compiled: CompiledStructure;
formatted: COMInput;
model?: ModelInstance;
modelInput?: ModelInput;
stopReason?: string;
tickControl: COMTickDecision;
tickState: TickState;
}>;Defined in: packages/core/src/utils/compile-jsx-service.ts:2009
Compile a single tick (for use in Engine's tick loop).
This method handles the full compilation flow for a single tick:
- Clears COM and re-registers tools
- Prepares tick state
- Compiles until stable
- Waits for forks/spawns and re-compiles if needed
- Applies structures
- Resolves tick control
- Returns formatted input and control decisions
Parameters ​
| Parameter | Type | Default value | Description |
|---|---|---|---|
com | ContextObjectModel | undefined | COM instance |
compiler | FiberCompiler | undefined | FiberCompiler instance |
structureRenderer | StructureRenderer | undefined | StructureRenderer instance |
rootElement | Element | undefined | Root JSX element |
tick | number | undefined | Tick number |
previous? | COMInput | undefined | Previous tick's state (undefined for tick 1) |
current? | COMOutput | undefined | Current tick's state (userInput for tick 1, model output for tick 2+) |
stopReason? | string | undefined | Stop reason from TickState.stop() callback (if any) |
shouldContinue? | boolean | true | Whether execution should continue (for tick control resolution) |
handle? | ExecutionHandle | undefined | Optional execution handle |
Returns ​
Promise<{ compiled: CompiledStructure; formatted: COMInput; model?: ModelInstance; modelInput?: ModelInput; stopReason?: string; tickControl: COMTickDecision; tickState: TickState; }>
Compilation result with formatted input and tick control
createSession() ​
createSession(config: CompileSessionConfig): Promise<CompileSession>;Defined in: packages/core/src/utils/compile-jsx-service.ts:1506
Create a long-lived compilation session for multi-tick execution.
The session maintains state across ticks and provides a clean API for:
- Pre-model compilation (compileTick)
- Post-model state ingestion (ingestTickResult)
- Component lifecycle hooks (notifyTickEnd, notifyComplete)
- Tick control resolution (shouldContinue)
Parameters ​
| Parameter | Type | Description |
|---|---|---|
config | CompileSessionConfig | Session configuration |
Returns ​
Promise<CompileSession>
A long-lived CompileSession instance
Example ​
const session = await service.createSession({
input: engineInput,
rootElement: <MyAgent />,
});
while (session.shouldContinue() && session.tick <= maxTicks) {
const { formatted, model, tools } = await session.compileTick();
// Engine executes model and tools
const response = await model.generate(formatted);
const toolResults = await executeTools(response.toolCalls, tools);
// Session ingests results and handles component lifecycle
await session.ingestTickResult({ response, toolResults });
// Engine calls its own lifecycle hooks, yields events, etc.
session.advanceTick();
}
const finalState = await session.complete();getChannelService() ​
getChannelService():
| ChannelService
| undefined;Defined in: packages/core/src/utils/compile-jsx-service.ts:2181
Get channel service (if initialized).
Returns ​
| ChannelService | undefined
getMCPClient() ​
getMCPClient(): MCPClient | undefined;Defined in: packages/core/src/utils/compile-jsx-service.ts:2167
Get MCP client (if initialized).
Returns ​
MCPClient | undefined
getMCPService() ​
getMCPService(): MCPService | undefined;Defined in: packages/core/src/utils/compile-jsx-service.ts:2174
Get MCP service (if initialized).
Returns ​
MCPService | undefined
getRenderers() ​
getRenderers(): {
[key: string]: ContentRenderer;
};Defined in: packages/core/src/utils/compile-jsx-service.ts:2160
Get all renderers.
Returns ​
{
[key: string]: ContentRenderer;
}getTools() ​
getTools(): (
| ToolClass<any>
| ExecutableTool<(input: any) =>
| ContentBlock[]
| Promise<ContentBlock[]>>)[];Defined in: packages/core/src/utils/compile-jsx-service.ts:1317
Get resolved tools (cached).
Returns ​
( | ToolClass<any> | ExecutableTool<(input: any) => | ContentBlock[] | Promise<ContentBlock[]>>)[]
prepareTickState() ​
prepareTickState(
com: ContextObjectModel,
tick: number,
previous?: COMInput,
current?: COMOutput): TickState;Defined in: packages/core/src/utils/compile-jsx-service.ts:1547
Prepare tick state for a given tick number. Handles state semantics correctly (previous, current).
Parameters ​
| Parameter | Type | Description |
|---|---|---|
com | ContextObjectModel | COM instance |
tick | number | Tick number (1-based) |
previous? | COMInput | Previous tick's state (undefined for tick 1) |
current? | COMOutput | Current tick's state (userInput for tick 1, model output for tick 2+) |
Returns ​
TickState ready for compilation
registerMCPTools() ​
registerMCPTools(com: ContextObjectModel): Promise<void>;Defined in: packages/core/src/utils/compile-jsx-service.ts:1334
Initialize MCP servers and discover their tools.
Parameters ​
| Parameter | Type |
|---|---|
com | ContextObjectModel |
Returns ​
Promise<void>
registerTools() ​
registerTools(com: ContextObjectModel): void;Defined in: packages/core/src/utils/compile-jsx-service.ts:1325
Register tools with COM. Called during setup and after COM.clear() for multi-tick scenarios.
Parameters ​
| Parameter | Type |
|---|---|
com | ContextObjectModel |
Returns ​
void
setup() ​
setup(
input: EngineInput,
rootElement: Element,
handle?: ExecutionHandle): Promise<{
com: ContextObjectModel;
compiler: FiberCompiler;
structureRenderer: StructureRenderer;
}>;Defined in: packages/core/src/utils/compile-jsx-service.ts:1381
Setup compilation infrastructure (COM, FiberCompiler, StructureRenderer). This is the core setup that Engine needs before compilation.
Parameters ​
| Parameter | Type | Description |
|---|---|---|
input | EngineInput | Initial COM input |
rootElement | Element | Root JSX element to compile |
handle? | ExecutionHandle | Optional execution handle (for setting COM instance) |
Returns ​
Promise<{ com: ContextObjectModel; compiler: FiberCompiler; structureRenderer: StructureRenderer; }>
Setup result with com, compiler, and structureRenderer exposed
waitForForksAndRecompile() ​
waitForForksAndRecompile(
com: ContextObjectModel,
compiler: FiberCompiler,
rootElement: Element,
tickState: TickState,
compiled: CompiledStructure,
handle?: ExecutionHandle): Promise<{
compiled: CompiledStructure;
hadWaitingForks: boolean;
recompiled: boolean;
}>;Defined in: packages/core/src/utils/compile-jsx-service.ts:1615
Wait for forks/spawns to complete and re-compile if needed.
This is part of the compilation phase - after compilation completes, we check if any forks/spawns are waiting. If they complete, their onComplete callbacks may modify COM state, so we re-compile to allow components to see the fork results.
This happens BEFORE applying structures so fork results are included in the compiled structure that gets applied.
Parameters ​
| Parameter | Type | Description |
|---|---|---|
com | ContextObjectModel | COM instance |
compiler | FiberCompiler | FiberCompiler instance |
rootElement | Element | Root JSX element |
tickState | TickState | Current tick state |
compiled | CompiledStructure | Initial compiled structure |
handle? | ExecutionHandle | Optional execution handle (for lifecycle hooks) |
Returns ​
Promise<{ compiled: CompiledStructure; hadWaitingForks: boolean; recompiled: boolean; }>
Final compiled structure (possibly recompiled) and metadata