Shared from "Merlin Backend" on Inkdown
The orchestration layer is a custom-built, multi-agent tool orchestration system designed for AI assistant interactions. It manages tool execution, agent coordination, streaming responses, and context window optimization - all without relying on external frameworks like LangChain or AutoGPT.
Location: src/server/endpoints/unified/orchestrator/toolOrchestrator.ts
The ToolOrchestrator is the heart of the orchestration system. It's a 1065-line class that manages the entire orchestration lifecycle.
Parameters:
chatCtx: Chat context containing conversation history, model config, and chat stateagentName: Which agent to run (MainThreadAgent, DeepResearchSupervisor, ResearcherAgent)toolRegistry: Registry of available tools for this sessionagentConfig: Configuration object defining agent behaviorcustomToolCallLimit: Optional override for tool call limitschatCtx: Holds conversation state, model config, attachments, etc.registry: Manages which tools are availableagentName: Determines which agent behavior to useagentConfig: Defines how this agent behaves (hooks, limits, policies)usageConfigArray: Tracks token usage across all iterationscurrentToolMetadata: Metadata about tools being executedcurrentExecutingTool: Currently running tool for error reportingrun()The run() method is the main entry point that executes the entire orchestration flow.
executeRequestedTools()This is an async generator that executes tools and yields streaming results.
Stream Chunk Types:
tool:progress: Initial progress event with EventManagertool:start: Tool execution beginstool:stream: Streaming tool result (for tools that return streams)tool:done: Tool execution completed with resulttool:error: Tool execution failedrunSingleTool()Location: src/server/endpoints/unified/tools/toolRegistry.ts
The ToolRegistry manages the lifecycle of tools - registration, retrieval, and filtering.
Default Tools:
memoryRetrievalTool: Retrieve user memoriesmemoryStorageTool: Store information to user memoriescraftTool: Generate code/craftswebSearchTool: Search the webimageGenTool: Generate imagesLocation: src/server/endpoints/unified/orchestrator/configs/
Agent configs define the behavior of different agent types. They use a hook-based pattern for maximum flexibility.
Location: src/server/endpoints/unified/orchestrator/configs/mainThread.config.ts
This is the default, user-facing agent that saves all data and has standard behavior.
Location: src/server/endpoints/unified/orchestrator/configs/deepResearch.config.ts
This agent orchestrates deep research by spawning researcher sub-agents and managing report generation.
Tool Filter for Deep Research:
Location: src/server/endpoints/unified/orchestrator/configs/researcher.config.ts
This is a sub-agent used by the deep research supervisor for individual research tasks.
Tool Filter for Researcher:
Location: src/server/endpoints/unified/orchestrator/helpers/baseUtils.ts
This file contains utility functions used throughout the orchestration system.
When a user sends a request through the unified API:
Tools are registered with the ToolRegistry:
shouldUse() is called if presentexecute() is calledhandleSpecialTools() hookTools can return metadata about their execution:
This metadata controls:
initializeOrchestrationState()initializeAgentState() hook is calledThe orchestration system uses a global streaming index to ensure consistent ordering of streamed content across agents and sub-agents.
The EventManager manages progress events for tool execution:
Agents communicate through:
The researcher_agent_tool is used to spawn researcher sub-agents:
Main agents update global context, sub-agents do not:
This prevents sub-agents from interfering with the main thread's streaming index.
Main Thread Policy (store everything):
Deep Research Policy (only research tools):
Usage is collected at multiple points:
Final usage array is returned and used for billing.
Tools can be executed in parallel:
Parallel execution is controlled by:
useParallelTools: booleanshouldDoParallelToolCallsALWAYS_ALLOW_MULTI_TOOL_CALL_MODELSAgents can force specific tools:
Agents can modify messages based on tool results:
The token engine optimizes context usage:
The engine:
Some models receive few-shot examples:
These examples show the LLM how to use tools correctly.
Some tool results are wrapped to prevent re-generation:
This prevents the LLM from re-generating content already sent to the user.
Agents can have custom tool call limits:
This is used in deep research to allow more iterations.
Agents can override the model:
This allows switching to cheaper models after retries.
The orchestration layer is a sophisticated, custom-built system that provides:
The system is production-ready and handles complex scenarios like deep research with sub-agents, streaming tool execution, and context window optimization - all without relying on external orchestration frameworks.