Skip to main content
Back

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

objectResponsibilities
GatewayInterface definition, contract implemented by all Gateways
InProcessGatewayIn-Process implementation, runs directly in the current process
SessionRouterManage Session creation, search, and life cycle
GatewayWsClientWebSocket client encapsulation
RemoteGatewayClient proxy for remote gateway
GatewayElicitationBusHandle the tool's question to the user (ask_user_question)

Development Points​

Typescript
// 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>;
// ...
}
Note · Note

If you need to add a new Gateway method, remember to update it at the same time:

  1. protocol/types.ts in Gateway interface
  2. InProcessGateway realize
  3. RemoteGateway client proxy
  4. GatewayServer WebSocket handler

Router Module​

Directory: src/router/

Internal Structure​

Plain Text
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:

  1. Configure Schema (config/schema.ts): add tier definition
  2. Classification logic (tokenSaver/classifyAndRoute.ts): Update judgment rules
  3. test: Add the corresponding single test scenario

Custom Router​

realize PilotDeckCustomRouter interface to create a custom router:

Typescript
interface PilotDeckCustomRouter {
decide(input: CustomRouterDecideInput): Promise<Partial<RouterDecision> | undefined>;
}

Context Module​

Directory: src/context/

Core Components​

componentsFileResponsibilities
PromptAssemblerprompt/PromptAssembler.tsAssembling a complete System Prompt
MessageProjectorprojection/MessageProjector.tsProjection and clipping history messages
TokenBudgetManagerbudget/TokenBudgetManager.tsToken budget management and early warning
CompactionEnginecompaction/CompactionEngine.tsHistorical message compression
MemoryResolvermemory/MemoryResolver.tsLong-term memory retrieval interface
InstructionDiscoveryinstructions/InstructionDiscovery.tsProject command discovery
AttachmentResolverattachments/AttachmentResolver.tsAttachment (file/picture) processing

Compaction (Context Compression)​

When the conversation history is too long, the Context module provides a multi-layer compression strategy:

Plain Text
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:

Typescript
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:

Typescript
// 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​

  1. in providers/ Create a new Provider adapter under
  2. Implement request conversion (Canonical → Provider format)
  3. Implement response conversion (Provider streaming event → Canonical event)
  4. in ModelProviderRegistry Register in

Tool Module​

Directory: src/tool/

Add Built-in Tools​

  1. in builtin/ Create tool files under
  2. Define the input schema for the tool
  3. realize PilotDeckToolDefinition interface
  4. in createBuiltinRegistry Register in
Typescript
// 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 operations
  • SequentialToolScheduler: Sequential execution, suitable for write operations with dependencies

Always-On Module​

Directory: src/always-on/

Core Components​

componentsResponsibilities
AlwaysOnManagerTop-level manager, bound to Gateway
AlwaysOnRuntimeDiscovery runtime
DiscoverySchedulerScheduler, checks Gate and triggers Discovery
DiscoveryFireExecute a single Discovery
SignalWatcherFile change signal monitoring
WorkspaceProviderRegistryWorkspace 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

Developer Showcase

View all →