Agent Engine Overview
Elftia's Agent system is based on a multi-engine dispatch architecture. EngineDispatcher acts as a unified request dispatcher that routes requests to the corresponding engine implementation based on EngineType. Each engine implements the IEngine interface and encapsulates different backend services.
Architecture Diagram
graph TB
Router["AgentRouter / MagiService"] --> Dispatcher["EngineDispatcher"]
Dispatcher --> TinyElf["TinyElfEngine<br/>tinyelf"]
Dispatcher --> ClaudeSdk["ClaudeSdkEngine<br/>claude-sdk"]
Dispatcher --> CliRunner["CliRunnerEngine<br/>cli"]
Dispatcher --> Chat["ChatEngine<br/>chat"]
Dispatcher --> STChat["STChatEngine<br/>st-chat"]
Dispatcher --> Api["ApiEngine<br/>api"]
TinyElf --> TinyLoop["TinyElfAgentLoop<br/>Tool call loop"]
TinyElf --> ToolReg["ToolRegistry<br/>Tool registry"]
TinyElf --> LLMAdapter["TinyElfLLMAdapter<br/>LLM adapter"]
ClaudeSdk --> AgentSvc["AgentService<br/>Claude Agent SDK"]
ClaudeSdk --> Proxy["AgentProxyServer<br/>HTTP proxy"]
CliRunner --> Supervisor["ProcessSupervisor<br/>Process management"]
Chat --> Pipeline["ChatCompletionPipeline<br/>Chat pipeline"]
IEngine Interface
All engines must implement the IEngine interface:
interface IEngine {
readonly engineType: EngineType;
startSession(ctx: EngineSessionContext): Promise<void>;
resumeSession(ctx: EngineSessionContext): Promise<void>;
interrupt(dbSessionId: string): Promise<boolean>;
isActive(dbSessionId: string): boolean;
reloadMcpForAllActive?(): Promise<void>;
}
| Method | Description |
|---|---|
startSession | Start a new session (save user message, run engine loop) |
resumeSession | Continue conversation on an existing session |
interrupt | Interrupt an active session, return whether successful |
isActive | Check if a session is running |
reloadMcpForAllActive | Hot reload MCP tools for all active sessions (optional) |
EngineSessionContext
All engines share the same session context structure. Each engine uses fields as needed:
interface EngineSessionContext {
dbSessionId: string; // Database session ID
session: ChatSession; // Full session record
sender: WebContents; // Electron IPC sender
prompt: string; // User message
attachments?: Array<...>; // Multimodal attachments
providerId?: string; // LLM provider ID
model?: string; // Model ID (v89+ is bare SDK id)
/**
* v89+: CLI backend binding (from chat_sessions.cliBackend column).
* 'claude-code' goes through ClaudeSdkEngine + AgentProxyServer.passThrough;
* 'codex' / 'gemini-cli' goes through CliRunnerEngine.
*/
cliBackend?: 'claude-code' | 'codex' | 'gemini-cli' | null;
/**
* v89+: 1M-context preference (from chat_sessions.useExtendedContext column).
* Engines / AgentProxyServer / TransformerChainExecutor decide whether to
* inject 'context-1m-2025-08-07' into anthropic_beta based on this.
*/
useExtendedContext?: boolean;
engineConfig?: EngineConfig; // Engine-specific configuration
projectPath?: string; // Project path
agentId?: string; // Agent ID
// Chat engine specific
systemPrompt?: string;
parentId?: string | null;
thinkingLevel?: string;
searchOrchestration?: PipelineSearchConfig;
mcpConfig?: PipelineMcpConfig;
// Magi/Agent engine specific
providerEnv?: Record<string, string>;
onSessionEnd?: () => void;
isOfficialProvider?: boolean;
customAgentOptions?: { ... };
permissionMode?: string;
channelSource?: string;
channelId?: string;
channelSenderId?: string;
channelUserPermissions?: { canUseTool: boolean; requireConfirmation: boolean };
}
EngineDispatcher
EngineDispatcher is the core of engine registration and dispatch:
class EngineDispatcher {
private engines = new Map<EngineType, IEngine>();
registerEngine(engine: IEngine): void;
getEngine(type: EngineType): IEngine;
hasEngine(type: EngineType): boolean;
dispatch(type: EngineType, ctx: EngineSessionContext): Promise<void>;
resume(type: EngineType, ctx: EngineSessionContext): Promise<void>;
interrupt(dbSessionId: string): Promise<boolean>;
reloadMcpForAllActive(): Promise<void>;
getEngineInfos(): EngineInfo[];
}
Engine Registration
Engines are registered in packages/desktop/app/main/index.ts:
const dispatcher = new EngineDispatcher();
dispatcher.registerEngine(new TinyElfEngine(...));
dispatcher.registerEngine(new ClaudeSdkEngine(...));
dispatcher.registerEngine(new CliRunnerEngine(getProcessSupervisor(), db, logger));
dispatcher.registerEngine(new ChatEngine(...));
dispatcher.registerEngine(new STChatEngine(...));
dispatcher.registerEngine(new ApiEngine(...));
Interrupt Mechanism
The interrupt() method iterates through all engines, finds the engine that owns the target session, and interrupts it:
async interrupt(dbSessionId: string): Promise<boolean> {
for (const engine of this.engines.values()) {
if (engine.isActive(dbSessionId)) {
return engine.interrupt(dbSessionId);
}
}
return false;
}
Engine Type Registry
| EngineType | Class | Backend Service | Active Session Tracking |
|---|---|---|---|
tinyelf | TinyElfEngine | Built-in Agent loop | Map<string, ActiveTinyElfSession> |
claude-sdk | ClaudeSdkEngine | AgentService (SDK) | AgentService internal management |
cli | CliRunnerEngine | ProcessSupervisor | Map<string, ActiveCliSession> |
chat | ChatEngine | ChatCompletionPipeline | Internal Map |
st-chat | STChatEngine | CompletionService | Internal Map |
api | ApiEngine | CompletionService | Stateless |
Active Session Tracking
The TinyElf engine uses ActiveTinyElfSession to track the state of each active session:
interface ActiveTinyElfSession {
dbSessionId: string;
projectPath: string;
abortController: AbortController;
parentMessageId?: string;
lastAssistantMessageId?: string;
directMcpConnections?: Array<...>;
hookExecutor?: HookExecutor;
sdkDualWrite?: {
sdkSessionId: string;
lastUuid: string;
seqNum: number;
};
subagentManager?: SubagentManager;
}
IPC Events
Engines send events to the renderer process via sender.send('agent:event', ...):
| Event Type | Payload | Description |
|---|---|---|
init | { sessionId, systemInfo } | Session initialization |
sessionCreated | { sessionId } | Session creation complete |
userMessage | { sessionId, message } | User message saved |
streamDelta | { sessionId, delta } | Streaming text/thinking delta |
toolCallStart | { sessionId, block } | Tool call started |
toolCallEnd | { sessionId, block, status } | Tool call completed |
assistantMessage | { sessionId, message } | Assistant message saved |
permissionRequest | { sessionId, requestId, toolName, input } | Permission confirmation request |
result | { sessionId, stats } | Execution statistics result |
complete | { sessionId } | Session complete |
error | { sessionId, error } | Error event |
retry | { sessionId, retry } | API retry notification |
processing | { sessionId, message } | Processing state |
Key Files
| File | Path | Description |
|---|---|---|
| IEngine interface | services/agent-core/engine/types.ts | Engine interface and context definitions |
| EngineDispatcher | services/agent-core/engine/EngineDispatcher.ts | Engine registration and dispatch |
| Module entry | services/agent-core/engine/index.ts | Export all engines |
| TinyElfEngine | services/agent-core/engine/tinyelf/TinyElfEngine.ts | TinyElf engine implementation |
| ClaudeSdkEngine | services/agent-core/engine/ClaudeSdkEngine.ts | Claude SDK engine |
| CliRunnerEngine | services/agent-core/engine/cli/CliRunnerEngine.ts | CLI engine |
| ChatEngine | services/agent-core/engine/ChatEngine.ts | Chat engine |
| STChatEngine | services/agent-core/engine/STChatEngine.ts | Single-turn chat engine |
| ApiEngine | services/agent-core/engine/ApiEngine.ts | API engine |
| EngineType definition | @shared/contracts/elftia-agent-types.ts | Type definitions |
All paths are relative to packages/desktop/app/main/.
Extension Points
- Add a new engine: Implement
IEngineinterface + register inEngineDispatcher+ addEngineType - Add new IPC events: Send via
sender.send()in engine callbacks - MCP hot reload: Implement
reloadMcpForAllActive()method
Related Modules
| Module | Path | Relationship |
|---|---|---|
| AgentRouter | services/routers/AgentRouter.ts | Receives IPC calls and dispatches |
| MagiService | services/agent-core/magi/MagiService.ts | High-level orchestration, selects engine |
| CompletionService | services/capabilities/llm/completion/CompletionService.ts | LLM API calls |
| AgentService | services/agent-core/agent/AgentService.ts | Claude SDK session management |