Module Development Guide
PilotDeck Agent Series
This article introduces the design philosophy and interface conventions of each core module of PilotDeck to help you quickly get started with the development of a certain module.
Overall Principle
- modular boundaries: Each module passes
index.tsDefine public API, internal implementation details are not exposed to the outside world - dependency injection: Dependencies are injected between modules through construction parameters and interfaces to facilitate testing and replacement.
- Protocol takes precedence: All modules have well-defined Protocol types located in
protocol/subdirectory - Testability: Each module should be independently testable, using fake/stub instead of external dependencies
Gateway Module
Directory: src/gateway/
Core Object
| object | Responsibilities |
|---|---|
Gateway | Interface definition, contract implemented by all Gateways |
InProcessGateway | In-Process implementation, runs directly in the current process |
SessionRouter | Manage Session creation, search, and life cycle |
GatewayWsClient | WebSocket client encapsulation |
RemoteGateway | Client proxy for remote gateway |
GatewayElicitationBus | Handle the tool's question to the user (ask_user_question) |
Development Points
// Standard way to create a Gateway
import { createGateway } from "../gateway/index.js";
const gateway = createGateway({
agent: { /* AgentSession creation options */ },
projectStorage: { projectRoot, pilotHome },
idleSessionTimeoutMs: 30 * 60 * 1000,
});
// Gateway interface
interface Gateway {
submitTurn(input: GatewaySubmitTurnInput): AsyncIterable<GatewayEvent>;
abortTurn(input: { sessionKey: string }): Promise<void>;
newSession(input: NewSessionInput): Promise<{ sessionKey: string }>;
listSessions(input: ListSessionsInput): Promise<ListSessionsResult>;
// ...
}
If you need to add a new Gateway method, remember to update it at the same time:
protocol/types.tsinGatewayinterfaceInProcessGatewayrealizeRemoteGatewayclient proxyGatewayServerWebSocket handler
Router Module
Directory: src/router/
Internal Structure
src/router/
├── RouterRuntime.ts # Main entrance: createRouterRuntime()
├── config/
│ └── schema.ts # Configuration type definition
├── scenario/
│ ├── decideScenario.ts # Scenario decision logic
│ └── subagentDetector.ts # Sub-Agent detection
├── tokenSaver/
│ └── classifyAndRoute.ts # TokenSaver classification and routing
├── fallback/
│ └── runFallbackChain.ts # Fallback chain planning and execution
├── retry/
│ └── zeroUsageRetry.ts # Empty response retry
├── orchestrate/
│ └── applyOrchestration.ts # Auto-Orchestrate orchestration
├── customRouter/
│ └── customRouter.ts # Custom router interface
├── session/
│ ├── SessionRouterStore.ts # Session level routing status
│ └── sessionUsageCache.ts # Token usage cache
├── stats/
│ └── TokenStatsCollector.ts # Statistics collector
├── protocol/
│ ├── decision.ts # Decision type
│ ├── events.ts # Event type
│ └── errors.ts # Error type
└── utils/
└── countTokens.ts # Token counting tool
Extend TokenSaver Tier
Modifications are required when adding a new downgrade tier:
- Configure Schema (
config/schema.ts): add tier definition - Classification logic (
tokenSaver/classifyAndRoute.ts): Update judgment rules - test: Add the corresponding single test scenario
Custom Router
realize PilotDeckCustomRouter interface to create a custom router:
interface PilotDeckCustomRouter {
decide(input: CustomRouterDecideInput): Promise<Partial<RouterDecision> | undefined>;
}
Context Module
Directory: src/context/
Core Components
| components | File | Responsibilities |
|---|---|---|
| PromptAssembler | prompt/PromptAssembler.ts | Assembling a complete System Prompt |
| MessageProjector | projection/MessageProjector.ts | Projection and clipping history messages |
| TokenBudgetManager | budget/TokenBudgetManager.ts | Token budget management and early warning |
| CompactionEngine | compaction/CompactionEngine.ts | Historical message compression |
| MemoryResolver | memory/MemoryResolver.ts | Long-term memory retrieval interface |
| InstructionDiscovery | instructions/InstructionDiscovery.ts | Project command discovery |
| AttachmentResolver | attachments/AttachmentResolver.ts | Attachment (file/picture) processing |
Compaction (Context Compression)
When the conversation history is too long, the Context module provides a multi-layer compression strategy:
AutoCompactionPolicy
│
├── MicroCompaction #Micro compression: truncate large tool output
│
├── SnipEngine # Slicing: mark compression boundaries and discard old messages
│
├── CompactionEngine # Main compression: Use model to summarize old messages
│
└── ContextOverflowRecovery # Emergency cover: forced truncation when exceeding the limit
Add New Memory Provider
realize MemoryResolver Interface:
interface MemoryResolver {
retrieve(input: MemoryRetrieveInput): Promise<MemoryRetrieveResult>;
captureTurn?(input: MemoryCaptureTurnInput): void;
}
Model Module
Directory: src/model/
Canonical Protocol
All Provider requests and responses are converted to a unified Canonical format:
// Unified request
interface CanonicalModelRequest {
provider: string;
model: string;
messages: CanonicalMessage[];
tools?: CanonicalToolSchema[];
systemPrompt?: string;
// ...
}
// Unify streaming events
type CanonicalModelEvent =
| { type: "message_start"; ... }
| { type: "text_delta"; text: string }
| { type: "thinking_delta"; text: string }
| { type: "tool_call_start"; ... }
| { type: "tool_call_delta"; ... }
| { type: "tool_call_end"; ... }
| { type: "message_end"; finishReason: CanonicalFinishReason }
| { type: "error"; error: CanonicalModelError };
Add New Provider
- in
providers/Create a new Provider adapter under - Implement request conversion (Canonical → Provider format)
- Implement response conversion (Provider streaming event → Canonical event)
- in
ModelProviderRegistryRegister in
Tool Module
Directory: src/tool/
Add Built-in Tools
- in
builtin/Create tool files under - Define the input schema for the tool
- realize
PilotDeckToolDefinitioninterface - in
createBuiltinRegistryRegister in
// Tool definition structure
interface PilotDeckToolDefinition {
name: string;
description: string;
inputSchema: PilotDeckToolInputSchema;
execute(
call: PilotDeckToolCall,
context: PilotDeckToolRuntimeContext,
): Promise<PilotDeckToolResult>;
}
Tool Scheduling
The tool scheduler determines how multiple tool calls are executed:
ConcurrentToolScheduler: Parallel execution, suitable for independent read operationsSequentialToolScheduler: Sequential execution, suitable for write operations with dependencies
Always-On Module
Directory: src/always-on/
Core Components
| components | Responsibilities |
|---|---|
AlwaysOnManager | Top-level manager, bound to Gateway |
AlwaysOnRuntime | Discovery runtime |
DiscoveryScheduler | Scheduler, checks Gate and triggers Discovery |
DiscoveryFire | Execute a single Discovery |
SignalWatcher | File change signal monitoring |
WorkspaceProviderRegistry | Workspace provider (git-worktree/snapshot-copy) |
Development Considerations
- Always-On Passed
bindGateway()Bind to Gateway - It injects additional tools (Discovery Plan Tool, Report Tool) into Gateway
- It provides SessionConfigOverrides that affect the configuration of Discovery sessions