Skip to content

DCP API Reference

What You'll Learn

This section provides a complete API reference for DCP plugin developers, enabling you to:

  • Understand DCP's plugin entry and hook mechanism
  • Master configuration interfaces and the purpose of all configuration options
  • Learn specifications for discard and extract tools
  • Use state management APIs for session state operations

Core Concepts

DCP plugins are built on the OpenCode Plugin SDK, implementing context pruning functionality by registering hooks, tools, and commands.

Plugin Lifecycle:

1. OpenCode loads plugin

2. Plugin function executes

3. Registers hooks, tools, commands

4. OpenCode calls hooks to process messages

5. Plugin executes pruning logic

6. Returns modified messages

Plugin Entry API

Plugin Function

The main entry function for DCP, returning a plugin configuration object.

Signature:

typescript
import type { Plugin } from "@opencode-ai/plugin"

const plugin: Plugin = (async (ctx) => {
    // Plugin initialization logic
    return {
        // Registered hooks, tools, commands
    }) satisfies Plugin

export default plugin

Parameters:

ParameterTypeDescription
ctxPluginInputOpenCode plugin context, containing client and directory information

Return Value:

Plugin configuration object, containing the following fields:

FieldTypeDescription
experimental.chat.system.transformHandlerSystem prompt injection hook
experimental.chat.messages.transformHandlerMessage transformation hook
chat.messageHandlerMessage capture hook
command.execute.beforeHandlerCommand execution hook
toolRecord<string, Tool>Registered tool mapping
configConfigHandlerConfiguration mutation hook

Source Location: index.ts


Configuration API

PluginConfig Interface

Complete configuration type definition for DCP.

typescript
export interface PluginConfig {
    enabled: boolean
    debug: boolean
    pruneNotification: "off" | "minimal" | "detailed"
    commands: Commands
    turnProtection: TurnProtection
    protectedFilePatterns: string[]
    tools: Tools
    strategies: {
        deduplication: Deduplication
        supersedeWrites: SupersedeWrites
        purgeErrors: PurgeErrors
    }
}

Source Location: lib/config.ts

Configuration Options Details

Top-Level Configuration

OptionTypeDefaultDescription
enabledbooleantrueWhether to enable the plugin
debugbooleanfalseWhether to enable debug logs, logs written to ~/.config/opencode/logs/dcp/
pruneNotification"off" | "minimal" | "detailed""detailed"Notification display mode
protectedFilePatternsstring[][]File protection glob pattern list, matching files will not be pruned

Commands Configuration

typescript
export interface Commands {
    enabled: boolean
    protectedTools: string[]
}
FieldTypeDefaultDescription
enabledbooleantrueWhether to enable /dcp commands
protectedToolsstring[][...DEFAULT_PROTECTED_TOOLS]Command-protected tool list, these tools will not be pruned by /dcp sweep

TurnProtection Configuration

typescript
export interface TurnProtection {
    enabled: boolean
    turns: number
}
FieldTypeDefaultDescription
enabledbooleanfalseWhether to enable turn protection
turnsnumber4Number of turns to protect, tools from the most recent N turns will not be pruned

Tools Configuration

typescript
export interface Tools {
    settings: ToolSettings
    discard: DiscardTool
    extract: ExtractTool
}

ToolSettings:

typescript
export interface ToolSettings {
    nudgeEnabled: boolean
    nudgeFrequency: number
    protectedTools: string[]
}
FieldTypeDefaultDescription
nudgeEnabledbooleantrueWhether to enable AI reminders
nudgeFrequencynumber10Reminder frequency, remind AI to use pruning tools every N tool results
protectedToolsstring[][...DEFAULT_PROTECTED_TOOLS]Tool protection list

DiscardTool:

typescript
export interface DiscardTool {
    enabled: boolean
}
FieldTypeDefaultDescription
enabledbooleantrueWhether to enable discard tool

ExtractTool:

typescript
export interface ExtractTool {
    enabled: boolean
    showDistillation: boolean
}
FieldTypeDefaultDescription
enabledbooleantrueWhether to enable extract tool
showDistillationbooleanfalseWhether to display extracted content in notifications

Strategies Configuration

Deduplication:

typescript
export interface Deduplication {
    enabled: boolean
    protectedTools: string[]
}
FieldTypeDefaultDescription
enabledbooleantrueWhether to enable deduplication strategy
protectedToolsstring[][...DEFAULT_PROTECTED_TOOLS]Tool list not participating in deduplication

SupersedeWrites:

typescript
export interface SupersedeWrites {
    enabled: boolean
}
FieldTypeDefaultDescription
enabledbooleanfalseWhether to enable supersede writes strategy

PurgeErrors:

typescript
export interface PurgeErrors {
    enabled: boolean
    turns: number
    protectedTools: string[]
}
FieldTypeDefaultDescription
enabledbooleantrueWhether to enable error purge strategy
turnsnumber4Error purge threshold (number of turns)
protectedToolsstring[][...DEFAULT_PROTECTED_TOOLS]Tool list not participating in purge

getConfig Function

Load and merge multi-level configurations.

typescript
export function getConfig(ctx: PluginInput): PluginConfig

Parameters:

ParameterTypeDescription
ctxPluginInputOpenCode plugin context

Return Value:

Merged configuration object, priority from high to low:

  1. Project configuration (.opencode/dcp.jsonc)
  2. Environment variable configuration ($OPENCODE_CONFIG_DIR/dcp.jsonc)
  3. Global configuration (~/.config/opencode/dcp.jsonc)
  4. Default configuration (defined in code)

Source Location: lib/config.ts


Tool API

createDiscardTool

Create discard tool for removing completed tasks or noise tool outputs.

typescript
export function createDiscardTool(ctx: PruneToolContext): ReturnType<typeof tool>

Parameters:

ParameterTypeDescription
ctxPruneToolContextTool context, containing client, state, logger, config, workingDirectory

Tool Specification:

FieldTypeDescription
idsstring[]First element is reason ('completion' or 'noise'), followed by numeric IDs

Source Location: lib/strategies/tools.ts

createExtractTool

Create extract tool for extracting key findings and deleting original tool outputs.

typescript
export function createExtractTool(ctx: PruneToolContext): ReturnType<typeof tool>

Parameters:

ParameterTypeDescription
ctxPruneToolContextTool context, containing client, state, logger, config, workingDirectory

Tool Specification:

FieldTypeDescription
idsstring[]Numeric ID array
distillationstring[]Extracted content array, length matches ids

Source Location: lib/strategies/tools.ts


State API

SessionState Interface

Session state object, managing runtime state for a single session.

typescript
export interface SessionState {
    sessionId: string | null
    isSubAgent: boolean
    prune: Prune
    stats: SessionStats
    toolParameters: Map<string, ToolParameterEntry>
    nudgeCounter: number
    lastToolPrune: boolean
    lastCompaction: number
    currentTurn: number
    variant: string | undefined
}

Field Descriptions:

FieldTypeDescription
sessionIdstring | nullOpenCode session ID
isSubAgentbooleanWhether this is a sub-agent session
prunePrunePruning state
statsSessionStatsStatistics data
toolParametersMap<string, ToolParameterEntry>Tool call cache (callID → metadata)
nudgeCounternumberCumulative tool call count (used to trigger reminders)
lastToolPrunebooleanWhether the last operation was a pruning tool
lastCompactionnumberLast context compaction timestamp
currentTurnnumberCurrent turn number
variantstring | undefinedModel variant (e.g., claude-3.5-sonnet)

Source Location: lib/state/types.ts

SessionStats Interface

Session-level token pruning statistics.

typescript
export interface SessionStats {
    pruneTokenCounter: number
    totalPruneTokens: number
}

Field Descriptions:

FieldTypeDescription
pruneTokenCounternumberPruned token count in current session (cumulative)
totalPruneTokensnumberHistorical cumulative pruned token count

Source Location: lib/state/types.ts

Prune Interface

Pruning state object.

typescript
export interface Prune {
    toolIds: string[]
}

Field Descriptions:

FieldTypeDescription
toolIdsstring[]List of tool call IDs marked for pruning

Source Location: lib/state/types.ts

ToolParameterEntry Interface

Metadata cache for a single tool call.

typescript
export interface ToolParameterEntry {
    tool: string
    parameters: any
    status?: ToolStatus
    error?: string
    turn: number
}

Field Descriptions:

FieldTypeDescription
toolstringTool name
parametersanyTool parameters
statusToolStatus | undefinedTool execution status
errorstring | undefinedError message (if any)
turnnumberTurn number when this call was created

ToolStatus Enum:

typescript
export type ToolStatus = "pending" | "running" | "completed" | "error"

Source Location: lib/state/types.ts

createSessionState

Create a new session state object.

typescript
export function createSessionState(): SessionState

Return Value: Initialized SessionState object


Hook API

createSystemPromptHandler

Create system prompt injection hook handler.

typescript
export function createSystemPromptHandler(
    state: SessionState,
    logger: Logger,
    config: PluginConfig,
): Handler

Parameters:

ParameterTypeDescription
stateSessionStateSession state object
loggerLoggerLogger system instance
configPluginConfigConfiguration object

Behavior:

  • Check if this is a sub-agent session, skip if true
  • Check if this is an internal agent (e.g., summary generator), skip if true
  • Load the corresponding prompt template based on configuration (both/discard/extract)
  • Inject pruning tool descriptions into the system prompt

Source Location: lib/hooks.ts

createChatMessageTransformHandler

Create message transformation hook handler, execute automatic pruning logic.

typescript
export function createChatMessageTransformHandler(
    client: any,
    state: SessionState,
    logger: Logger,
    config: PluginConfig,
): Handler

Parameters:

ParameterTypeDescription
clientanyOpenCode client instance
stateSessionStateSession state object
loggerLoggerLogger system instance
configPluginConfigConfiguration object

Processing Flow:

  1. Check session state (whether it's a sub-agent)
  2. Sync tool cache
  3. Execute automatic strategies (deduplication, supersede writes, purge errors)
  4. Prune marked tool contents
  5. Inject <prunable-tools> list
  6. Save context snapshot (if configured)

Source Location: lib/hooks.ts

createCommandExecuteHandler

Create command execution hook handler, handle /dcp series commands.

typescript
export function createCommandExecuteHandler(
    client: any,
    state: SessionState,
    logger: Logger,
    config: PluginConfig,
    workingDirectory: string,
): Handler

Parameters:

ParameterTypeDescription
clientanyOpenCode client instance
stateSessionStateSession state object
loggerLoggerLogger system instance
configPluginConfigConfiguration object
workingDirectorystringWorking directory path

Supported Commands:

  • /dcp - Display help information
  • /dcp context - Display current session token usage analysis
  • /dcp stats - Display cumulative pruning statistics
  • /dcp sweep [n] - Manually prune tools (optionally specify quantity)

Source Location: lib/hooks.ts


Summary

This section provides a complete API reference for the DCP plugin, covering:

  • Plugin entry function and hook registration mechanism
  • Configuration interfaces and detailed descriptions of all configuration options
  • Specifications and creation methods for discard and extract tools
  • Type definitions for session state, statistics, and tool cache
  • Hook handlers for system prompts, message transformation, and command execution

If you need to understand the internal implementation details of DCP, we recommend reading the Architecture Overview and Token Calculation Principles.


Appendix: Source Code Reference

Click to expand source code locations

Last Updated: 2026-01-23

FeatureFile PathLines
Plugin entry functionindex.ts12-102
Configuration interface definitionlib/config.ts7-66
getConfig functionlib/config.ts669-797
Discard tool creationlib/strategies/tools.ts155-181
Extract tool creationlib/strategies/tools.ts183-220
State type definitionslib/state/types.ts1-39
System prompt hooklib/hooks.ts20-53
Message transformation hooklib/hooks.ts55-82
Command execution hooklib/hooks.ts84-156

Key Types:

  • Plugin: OpenCode plugin function signature
  • PluginConfig: DCP configuration interface
  • SessionState: Session state interface
  • ToolStatus: Tool status enum (pending | running | completed | error)

Key Functions:

  • plugin(): Plugin entry function
  • getConfig(): Load and merge configuration
  • createDiscardTool(): Create discard tool
  • createExtractTool(): Create extract tool
  • createSessionState(): Create session state