Skip to content

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 ​

typescript
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();
typescript
const result = await service.compile(<MyComponent />, {
  timeline: [],
  sections: {}
});
console.log(result.formatted);
typescript
// 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 ​

ts
new CompileJSXService(config: CompileJSXServiceConfig): CompileJSXService;

Defined in: packages/core/src/utils/compile-jsx-service.ts:1223

Parameters ​

ParameterType
configCompileJSXServiceConfig

Returns ​

CompileJSXService

Properties ​

PropertyModifierTypeDescriptionDefined in
componentHooksRegistryreadonlyComponentHookRegistry-packages/core/src/utils/compile-jsx-service.ts:1215
lifecycleHooksRegistryreadonlyEngineLifecycleHookRegistry-packages/core/src/utils/compile-jsx-service.ts:1216
runpublicProcedure<(config: CompileSessionConfig, fn: (compiled: CompileTickResult) => Promise<TickResultInput>) => Promise<COMInput>>-packages/core/src/utils/compile-jsx-service.ts:1719
runStreampublicProcedure<<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 ​

ts
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 ​
ts
{
  components: ComponentHookRegistry;
  lifecycle: EngineLifecycleHookRegistry;
}
NameTypeDefined in
componentsComponentHookRegistrypackages/core/src/utils/compile-jsx-service.ts:2145
lifecycleEngineLifecycleHookRegistrypackages/core/src/utils/compile-jsx-service.ts:2146

Methods ​

_run() ​

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

ParameterTypeDescription
configCompileSessionConfigSession configuration
fn(compiled: CompileTickResult) => Promise<TickResultInput>Function to execute for each tick

Returns ​

Promise<COMInput>

Final COM input


_runStream() ​

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

  1. Simple function: runStream(config, executeTick)
  2. Callbacks object: runStream(config, callbacks)

When executeTick (or callbacks.onTick) returns an AsyncIterable:

  • Chunks are yielded as { type: 'chunk', tick, chunk } events
  • finalizeChunks MUST be provided to convert chunks to TickResultInput

When it returns a Promise&lt;TickResultInput&gt;:

  • No chunks are yielded, result is used directly

Type Parameters ​

Type ParameterDefault type
TChunkunknown

Parameters ​

ParameterType
configCompileSessionConfig
executorOrCallbacks| TickExecutor<TChunk> | RunStreamCallbacks<TChunk>

Returns ​

AsyncGenerator<SessionStreamEvent<TChunk>>

Examples ​

typescript
for await (const event of service.runStream(config, async (compiled) => {
  const response = await model.generate(compiled.formatted);
  return { response };
})) {
  console.log(event.type);
}
typescript
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() ​

ts
addRenderer(name: string, renderer: ContentRenderer): void;

Defined in: packages/core/src/utils/compile-jsx-service.ts:2153

Add a renderer.

Parameters ​

ParameterType
namestring
rendererContentRenderer

Returns ​

void


callLifecycleHooks() ​

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

ParameterType
hookNameT
argsEngineLifecycleHookArgs<T>

Returns ​

Promise<void>


checkAbort() ​

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

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

ParameterTypeDescription
comContextObjectModelCOM instance to clear

Returns ​

void


compile() ​

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

ParameterTypeDescription
jsxComponentDefinitionThe JSX element or component definition to compile
inputPartial<EngineInput>Initial COM input (timeline, sections, metadata, etc.)
handle?ExecutionHandleOptional execution handle

Returns ​

Promise<CompileJSXResult>

Compilation result with compiled structure, formatted output, and metadata


compileTick() ​

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

ParameterTypeDefault valueDescription
comContextObjectModelundefinedCOM instance
compilerFiberCompilerundefinedFiberCompiler instance
structureRendererStructureRendererundefinedStructureRenderer instance
rootElementElementundefinedRoot JSX element
ticknumberundefinedTick number
previous?COMInputundefinedPrevious tick's state (undefined for tick 1)
current?COMOutputundefinedCurrent tick's state (userInput for tick 1, model output for tick 2+)
stopReason?stringundefinedStop reason from TickState.stop() callback (if any)
shouldContinue?booleantrueWhether execution should continue (for tick control resolution)
handle?ExecutionHandleundefinedOptional 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() ​

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

ParameterTypeDescription
configCompileSessionConfigSession configuration

Returns ​

Promise<CompileSession>

A long-lived CompileSession instance

Example ​

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

ts
getChannelService(): 
  | ChannelService
  | undefined;

Defined in: packages/core/src/utils/compile-jsx-service.ts:2181

Get channel service (if initialized).

Returns ​

| ChannelService | undefined


getMCPClient() ​

ts
getMCPClient(): MCPClient | undefined;

Defined in: packages/core/src/utils/compile-jsx-service.ts:2167

Get MCP client (if initialized).

Returns ​

MCPClient | undefined


getMCPService() ​

ts
getMCPService(): MCPService | undefined;

Defined in: packages/core/src/utils/compile-jsx-service.ts:2174

Get MCP service (if initialized).

Returns ​

MCPService | undefined


getRenderers() ​

ts
getRenderers(): {
[key: string]: ContentRenderer;
};

Defined in: packages/core/src/utils/compile-jsx-service.ts:2160

Get all renderers.

Returns ​

ts
{
[key: string]: ContentRenderer;
}

getTools() ​

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

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

ParameterTypeDescription
comContextObjectModelCOM instance
ticknumberTick number (1-based)
previous?COMInputPrevious tick's state (undefined for tick 1)
current?COMOutputCurrent tick's state (userInput for tick 1, model output for tick 2+)

Returns ​

TickState

TickState ready for compilation


registerMCPTools() ​

ts
registerMCPTools(com: ContextObjectModel): Promise<void>;

Defined in: packages/core/src/utils/compile-jsx-service.ts:1334

Initialize MCP servers and discover their tools.

Parameters ​

ParameterType
comContextObjectModel

Returns ​

Promise<void>


registerTools() ​

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

ParameterType
comContextObjectModel

Returns ​

void


setup() ​

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

ParameterTypeDescription
inputEngineInputInitial COM input
rootElementElementRoot JSX element to compile
handle?ExecutionHandleOptional execution handle (for setting COM instance)

Returns ​

Promise<{ com: ContextObjectModel; compiler: FiberCompiler; structureRenderer: StructureRenderer; }>

Setup result with com, compiler, and structureRenderer exposed


waitForForksAndRecompile() ​

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

ParameterTypeDescription
comContextObjectModelCOM instance
compilerFiberCompilerFiberCompiler instance
rootElementElementRoot JSX element
tickStateTickStateCurrent tick state
compiledCompiledStructureInitial compiled structure
handle?ExecutionHandleOptional execution handle (for lifecycle hooks)

Returns ​

Promise<{ compiled: CompiledStructure; hadWaitingForks: boolean; recompiled: boolean; }>

Final compiled structure (possibly recompiled) and metadata

Released under the MIT License.