aider-desk - docs site docs advanced custom prompts
15099 characters
---
title: "Custom Prompts"
sidebar_label: "Custom Prompts"
---
# Custom Prompts
AiderDesk uses **prompt templates** to control how the AI agent behaves. These templates are written in [Handlebars](https://handlebarsjs.com/) format and can be customized at multiple levels to suit your specific needs.
## Available Prompt Templates
AiderDesk includes the following built-in prompt templates that you can override. You can view the default implementation of each template on GitHub to use as a starting point for your customizations:
| Template | Purpose | Default |
|----------|---------|---------|
| `system-prompt.hbs` | The main system prompt that defines the agent's personality, objectives, and behavior | [View on GitHub](https://github.com/hotovo/aider-desk/blob/main/resources/prompts/system-prompt.hbs) |
| `init-project.hbs` | Instructions for initializing a new project and creating the `AGENTS.md` file | [View on GitHub](https://github.com/hotovo/aider-desk/blob/main/resources/prompts/init-project.hbs) |
| `workflow.hbs` | Agent workflow guidance for task execution | [View on GitHub](https://github.com/hotovo/aider-desk/blob/main/resources/prompts/workflow.hbs) |
| `compact-conversation.hbs` | Instructions for summarizing conversation history | [View on GitHub](https://github.com/hotovo/aider-desk/blob/main/resources/prompts/compact-conversation.hbs) |
| `commit-message.hbs` | Template for generating Git commit messages | [View on GitHub](https://github.com/hotovo/aider-desk/blob/main/resources/prompts/commit-message.hbs) |
| `task-name.hbs` | Template for generating task names from user prompts | [View on GitHub](https://github.com/hotovo/aider-desk/blob/main/resources/prompts/task-name.hbs) |
| `update-task-state.hbs` | Instructions for determining the appropriate task state based on the agent's last response | [View on GitHub](https://github.com/hotovo/aider-desk/blob/main/resources/prompts/update-task-state.hbs) |
| `conflict-resolution-system.hbs` | System prompt for resolving Git merge conflicts | [View on GitHub](https://github.com/hotovo/aider-desk/blob/main/resources/prompts/conflict-resolution-system.hbs) |
| `conflict-resolution.hbs` | Instructions for handling conflict resolution tasks | [View on GitHub](https://github.com/hotovo/aider-desk/blob/main/resources/prompts/conflict-resolution.hbs) |
| `handoff.hbs` | Template for generating focused prompts when using the `/handoff` command | [View on GitHub](https://github.com/hotovo/aider-desk/blob/main/resources/prompts/handoff.hbs) |
| `code-change-requests.hbs` | Template for making focused code changes based on batch inline feedback in the diff viewer | [View on GitHub](https://github.com/hotovo/aider-desk/blob/main/resources/prompts/code-change-requests.hbs) |
## Template Override System
AiderDesk supports a three-level priority system for prompt customization. When a template is requested, the system searches for it in the following order (from highest to lowest priority):
### 1. Project-Specific Prompts (Highest Priority)
**Location:** `$PROJECT_DIR/.aider-desk/prompts/`
Templates placed in your project's `.aider-desk/prompts/` directory will override all other templates for that specific project only.
```
my-project/
├── .aider-desk/
│ └── prompts/
│ ├── system-prompt.hbs
│ ├── init-project.hbs
│ └── workflow.hbs
└── src/
```
Use this level when you want:
- Project-specific behavior customization
- Team-specific prompts for a codebase
- Different prompts for different projects
### 2. Global Prompts (Medium Priority)
**Location:** `~/.aider-desk/prompts/`
Templates placed in your home directory's `.aider-desk/prompts/` folder apply to all projects unless overridden by project-specific templates.
```
~/.aider-desk/prompts/
├── system-prompt.hbs
├── init-project.hbs
└── commit-message.hbs
```
Use this level when you want:
- Personalized prompt preferences across all projects
- Consistent behavior across your entire development workflow
- Global standards that apply to every project
### 3. Default Prompts (Lowest Priority)
**Location:** Bundled with AiderDesk
These are the built-in templates that ship with AiderDesk. They are used when no custom template is found in either the project-specific or global locations. You cannot modify these directly, but you can override them by creating templates at the project or global level.
## Creating Custom Prompts
### Step 1: Choose Your Override Level
Decide whether you want your custom prompts to apply to:
- **One project only** → Use `.aider-desk/prompts/` in your project
- **All projects** → Use `~/.aider-desk/prompts/`
### Step 2: Create the Prompts Directory
```bash
# For project-specific prompts
mkdir -p .aider-desk/prompts
# For global prompts
mkdir -p ~/.aider-desk/prompts
```
### Step 3: Copy and Modify a Template
You can start from the default templates and customize them. Create a file with the same name as the template you want to override.
**Tip:** Browse the default templates on [GitHub](https://github.com/hotovo/aider-desk/tree/main/resources/prompts) to see how they're structured and use them as a reference for your customizations.
Example: Customizing the system prompt for a specific project
```bash
# Copy the default template as a starting point (optional)
# You can also create a new file from scratch
# Create your custom system prompt
cat > .aider-desk/prompts/system-prompt.hbs << 'EOF'
# Custom System Prompt
You are a specialized coding assistant for the {{projectName}} project.
## Project Context
- Language: TypeScript
- Framework: React with Next.js
- Style: Functional components, no classes
## Your Role
Focus on creating maintainable, type-safe code. Always prefer composition over inheritance.
## Guidelines
- Use TypeScript strict mode
- Write tests for all new features
- Follow the existing code patterns
- Keep components under 200 lines
EOF
```
### Step 4: Verify the Template
When you create or modify a template file, AiderDesk will automatically:
1. Detect the change (via file watching)
2. Recompile the template
3. Apply it to new agent sessions
You can verify your changes by starting a new agent task and observing the behavior.
## Available Handlebars Helpers
AiderDesk provides several Handlebars helpers that you can use in your custom templates:
### Conditional Helpers
| Helper | Description |
|--------|-------------|
| `{{equals value1 value2}}` | Check if two values are equal |
| `{{not value}}` | Logical NOT operator |
| `{{assign varName value}}` | Assign a value to a variable in the template scope |
| `{{increment varName}}` | Increment a numeric variable |
### Formatting Helpers
| Helper | Description |
|--------|-------------|
| `{{indent text spaces}}` | Indent each line of text with specified number of spaces |
| `{{cdata text}}` | Wrap text in CDATA sections (for XML-style prompts) |
Example usage in a template:
```handlebars
{{#if toolPermissions.aiderTools}}
You have access to Aider tools.
{{/if}}
{{#if (equals toolPermissions.powerTools.anyEnabled true)}}
Power tools are enabled.
{{/if}}
{{cdata customInstructions}}
```
## Template Variables
Each prompt template has access to different variables depending on its purpose. Here are the key variables available to most templates:
### Common Variables
| Variable | Type | Description |
|----------|------|-------------|
| `projectDir` | string | Absolute path to the project directory |
| `taskDir` | string | Absolute path to the current task directory |
| `osName` | string | Operating system name |
| `currentDate` | string | Current date as a string |
| `customInstructions` | string | Custom instructions from agent profile or additional instructions |
| `rulesFiles` | string | Concatenated content of rule files |
| `toolPermissions` | object | Permissions configuration for various tools |
### System Prompt Variables
The `system-prompt.hbs` template has access to:
```typescript
{
projectDir: string;
taskDir: string;
additionalInstructions?: string;
osName: string;
currentDate: string;
rulesFiles: string;
customInstructions: string;
toolPermissions: {
aiderTools: boolean;
powerTools: { /* ... */ };
todoTools: boolean;
subagents: boolean;
memory: { /* ... */ };
skills: { /* ... */ };
autonomyMode: 'manual' | 'guided' | 'autonomous';
};
workflow: string; // Rendered workflow template
toolConstants: { /* All tool constants */ };
}
```
### Init Project Variables
The `init-project.hbs` template has minimal variables as it's typically static:
```typescript
{
// Additional context can be added in the future
}
```
### Conflict Resolution Variables
The `conflict-resolution.hbs` template receives:
```typescript
{
filePath: string;
basePath?: string;
oursPath?: string;
theirsPath?: string;
}
```
### Handoff Variables
The `handoff.hbs` template receives:
```typescript
{
focus?: string;
contextFiles?: ContextFile[];
}
```
- `focus`: Optional focus parameter provided by the user when running `/handoff`
- `contextFiles`: List of context files that will be transferred to the new task
### Code Change Requests Variables
The `code-change-requests.hbs` template is used when submitting batch inline code change requests from the diff viewer. It receives an array of change requests, allowing multiple comments to be processed in a single prompt:
```typescript
{
requests: {
filename: string;
lineNumber: number;
fileExtension: string;
contextLines: { lineNumber: number; content: string }[];
userComment: string;
}[];
}
```
- `requests`: Array of change request items, each containing:
- `filename`: The path to the file being modified
- `lineNumber`: The specific line number where the change should be made
- `fileExtension`: File extension for proper syntax highlighting in the prompt
- `contextLines`: Array of lines surrounding the target line (provides context for the AI)
- `userComment`: The user's feedback or request for that specific location
Here is the default template:
````handlebars
You are tasked with making specific code changes based on inline feedback. Review all the requested changes and implement them. Focus on the specific areas mentioned and ensure each change integrates well with the surrounding code.
{{#each requests}}
---
File: `{{filename}}`
Target Line: {{lineNumber}}
Context (lines around the target):
```{{fileExtension}}
{{#each contextLines}}
{{lineNumber}}: {{content}}
{{/each}}
```
Requested Change:
{{userComment}}
{{/each}}
````
## Live Reloading
AiderDesk automatically watches for changes to custom prompt templates:
- **File watching**: Any changes to `.hbs` files in the prompt directories are detected
- **Debounced compilation**: Changes are compiled after a 1-second delay to avoid issues with rapid edits
- **Automatic application**: Recompiled templates are used immediately for new agent sessions
- **Error handling**: Invalid templates are logged but won't crash the application
### Monitoring Logs
To monitor template loading and compilation:
```bash
# View logs for template-related events
tail -f ~/.aider-desk/logs/aider-desk.log | grep -i prompt
```
## Example: Custom System Prompt
Here's a complete example of creating a custom system prompt for a TypeScript project:
```bash
# Create the prompts directory
mkdir -p .aider-desk/prompts
# Create a custom system prompt
cat > .aider-desk/prompts/system-prompt.hbs << 'EOF'
# TypeScript Expert Assistant
You are an expert TypeScript developer working on the {{projectDir}} project.
## Your Personality
- Meticulous and detail-oriented
- Type-safety focused
- Performance conscious
- Test-driven development advocate
## Code Style Guidelines
### TypeScript Rules
- Always use `interface` for object shapes, `type` for unions
- Avoid `any` at all costs - use `unknown` when type is truly unknown
- Use `enum` for sets of related constants
- Enable `strict` mode in tsconfig
### React Rules (if applicable)
- Use functional components with hooks
- Define Props as: `type Props = { /* ... */ }`
- Extract event handlers to separate functions
- Import React types directly: `import { MouseEvent } from 'react';`
### General Best Practices
{{#if toolPermissions.memory.enabled}}
- Use memory tools to remember user preferences and patterns
{{/if}}
- Write tests for all new functionality
- Keep functions small and focused
- Add comments only when necessary (complex logic, edge cases)
## Project Context
{{#if rulesFiles}}
The following project rules are defined:
{{rulesFiles}}
{{/if}}
{{#if customInstructions}}
## Additional Instructions
{{customInstructions}}
{{/if}}
EOF
```
## Best Practices
### DO:
- Start by copying the default template as a reference
- Test your custom prompts on a sample task before committing to a project
- Use version control to track prompt changes
- Document any non-obvious template customizations in a README
- Keep templates focused on behavior, not specific implementation details
- Use Handlebars helpers for dynamic content to avoid repetition
### DON'T:
- Create overly complex templates that are hard to maintain
- Include sensitive information in templates (they may be in version control)
- Modify default bundled templates directly (always override)
- Mix concerns - keep system-prompt focused on agent behavior
- Hardcode project-specific values - use template variables when available
## Troubleshooting
### Template Not Being Applied
**Problem:** Your custom template isn't being used.
**Solutions:**
1. Check the file name matches exactly (e.g., `system-prompt.hbs`, not `systemPrompt.hbs`)
2. Verify the file is in the correct directory (`.aider-desk/prompts/` or `~/.aider-desk/prompts/`)
3. Check file permissions - templates must be readable
4. Review logs for compilation errors
### Template Compilation Errors
**Problem:** Template fails to compile.
**Solutions:**
1. Validate Handlebars syntax (balanced braces, proper closing tags)
2. Check helper usage - ensure helper names are correct
3. Verify template variables exist for that template type
4. Test templates with a simple example before complex customization
### Changes Not Taking Effect
**Problem:** Modified template isn't applied to current session.
**Solutions:**
1. Template changes only affect new agent sessions
2. Restart the current task to see changes
3. Verify file watcher is working (check logs)
## Related Features
- **Handoff**: Customize the handoff prompt template to control how conversation context is transferred to new tasks. See [Handoff](../features/handoff.md)
- **Project Rules**: Combine custom prompts with rule files for complete behavior control. See [Project-Specific Rules](../configuration/project-specific-rules.md)
- **Agent Profiles**: Create different agent profiles with different prompts. See [Agent Profiles](../agent-mode/agent-profiles.md)
- **Memory System**: Use memory to store and retrieve user preferences that can inform prompts. See [Memory](../features/memory.md)
aider-desk - docs site docs configuration project specific r...
5264 characters
---
title: "Project-Specific Rules"
sidebar_label: "Project Rules"
---
# Project-Specific Rules
To ensure the AI agent adheres to the specific conventions, architecture, and best practices of your project, you can provide it with custom rule files. This is a powerful feature for tailoring the agent's behavior and improving the quality of its output.
## Rule File Locations
AiderDesk supports multiple levels of rule files that are automatically included in the agent's context:
### 1. Project-Level Rules (`.aider-desk/rules/`)
AiderDesk automatically looks for a directory named `.aider-desk/rules/` in the root of your project. Any markdown files (`.md`) placed in this directory will be automatically read and included in the agent's system prompt as read-only context.
This allows you to create a persistent set of instructions that guide every agent interaction within that project.
### 2. Agent-Specific Rules (`.aider-desk/agents/{profile}/rules/`)
Each agent profile can have its own `rules/` directory containing markdown files with instructions specific to that agent. This allows you to:
- Create specialized rules for different agent profiles
- Override or extend project-level rules for specific agents
- Provide agent-specific guidance while maintaining project-wide standards
### 3. Global Rules (`~/.aider-desk/agents/{profile}/rules/`)
Global agent profiles can also have their own `rules/` directories, which are inherited by project-level profiles with the same ID.
## Rule Precedence
When multiple rule sources exist, they are combined in the following order:
1. **Global agent rules** (from `~/.aider-desk/agents/{profile}/rules/`)
2. **Project-level rules** (from `$projectDir/.aider-desk/rules/`)
3. **Project agent rules** (from `$projectDir/.aider-desk/agents/{profile}/rules/`)
This allows project-level profiles to extend and customize global profiles while maintaining a consistent foundation.
### What to Include in Rule Files
Good candidates for rule files include:
#### Project-Level Rules (`.aider-desk/rules/`)
- **High-level architecture overview**: Describe the main components and how they interact.
- **Coding conventions**: Specify code style, naming conventions, or patterns that are unique to your project.
- **Technology stack**: List the key libraries, frameworks, and tools used.
- **"Do's and Don'ts"**: Provide specific instructions on what the agent should or should not do (e.g., "Always use our custom `useApi` hook for data fetching," "Do not add new dependencies without approval").
#### Agent-Specific Rules (agent `rules/` directories)
- **Agent behavior guidelines**: Define how this specific agent should approach tasks
- **Tool usage preferences**: Specify which tools the agent should prefer for certain tasks
- **Output formatting**: Define expected output formats for this agent
- **Scope limitations**: Define what this agent should and shouldn't do
- **Specialized knowledge**: Include domain-specific information for specialized agents
### Rule File Organization
#### For Project-Level Rules
```
.aider-desk/rules/
├── architecture.md # High-level system design
├── coding-standards.md # Code style and conventions
├── testing-guidelines.md # Testing practices and requirements
└── deployment-rules.md # Deployment-specific instructions
```
#### For Agent-Specific Rules
```
.aider-desk/agents/code-reviewer/rules/
├── review-checklist.md # What to look for during code reviews
└── security-focus.md # Security-specific review guidelines
.aider-desk/agents/refactoring/rules/
├── refactoring-patterns.md # Common refactoring patterns to use
└── backward-compatibility.md # Rules for maintaining compatibility
```
## File-Based Management
### Version Control
Since rule files are stored as regular markdown files, you can:
- **Commit them to version control** to share rules with your team
- **Track changes** to rules over time
- **Branch rules** for different environments or experiments
- **Review rule changes** through pull requests
### Real-time Updates
AiderDesk automatically monitors rule files for changes:
- **Immediate application**: Changes to rule files are applied instantly without restarting
- **File watching**: The system detects additions, modifications, and deletions
- **Error handling**: Malformed rule files are skipped with warnings in the logs
### Sharing and Templates
You can create reusable rule templates:
- **Copy rule directories** between projects
- **Create starter templates** for common project types
- **Share agent profiles** with their custom rules intact
- **Maintain rule libraries** for different technologies or domains
## Best Practices
1. **Keep rules focused**: Each rule file should address a specific aspect of your project
2. **Use clear headings**: Structure rules with markdown headers for better readability
3. **Be specific**: Provide concrete examples and clear "do's and don'ts"
4. **Version control**: Commit your rule files to track changes and share with team
5. **Regular maintenance**: Review and update rules as your project evolves
6. **Test rules**: Verify that rules produce the desired agent behavior
7. **Document exceptions**: Note when rules should be bypassed and why
aider-desk - docs site docs extensions event flow
18436 characters
---
sidebar_position: 4
title: Event Flow Guide
description: Understand when extension events fire during prompt execution and which events to implement for specific use cases
---
# Event Flow Guide
This guide shows you when extension events fire during prompt execution and which events to implement for specific use cases. Use this to understand where your extension can intercept, modify, or enhance the prompt processing flow.
## runPrompt Flow Overview
The following diagram shows the complete flow with all extension events:
```mermaid
sequenceDiagram
autonumber
participant User
participant AiderDesk
participant Extension
participant LLM
User->>AiderDesk: Submit prompt
Note over AiderDesk,Extension: PHASE 1: Prompt Initialization
AiderDesk->>Extension: onPromptStarted
Note right of Extension: Can modify prompt, mode<br/>Can block execution
Extension-->>AiderDesk: Modified or blocked
alt Blocked by extension
AiderDesk-->>User: Prompt blocked
else Not blocked
Note over AiderDesk,Extension: PHASE 2: Agent Execution
AiderDesk->>Extension: onAgentStarted
Note right of Extension: Can modify prompt, files,<br/>system prompt, agent config<br/>Can block execution
Extension-->>AiderDesk: Modified or blocked
alt Blocked by extension
AiderDesk-->>User: Agent blocked
else Not blocked
Note over AiderDesk: Preparing messages for LLM
AiderDesk->>Extension: onOptimizeMessages
Note right of Extension: Can modify optimizedMessages<br/>Cannot block
Extension-->>AiderDesk: Modified messages
Note over AiderDesk,LLM: LLM Processing Loop
loop For each LLM iteration
LLM-->>AiderDesk: Response chunk
AiderDesk->>Extension: onResponseChunk
Note right of Extension: Can modify chunk<br/>Cannot block
Extension-->>AiderDesk: Modified chunk
alt Tool call needed
AiderDesk->>Extension: onToolApproval
Note right of Extension: Can set allowed, blocked<br/>Can block tool execution
Extension-->>AiderDesk: Approval decision
alt Tool approved
AiderDesk->>Extension: onToolCalled
Note right of Extension: Can modify input
Extension-->>AiderDesk: Modified input
alt Not blocked
AiderDesk->>AiderDesk: Execute tool
AiderDesk->>Extension: onToolFinished
Note right of Extension: Can modify output
Extension-->>AiderDesk: Modified output
end
end
end
LLM-->>AiderDesk: Step completed
AiderDesk->>Extension: onAgentStepFinished
Note right of Extension: Can modify finishReason,<br/>responseMessages<br/>Cannot block
Extension-->>AiderDesk: Modified step result
end
Note over AiderDesk,Extension: PHASE 3: Completion
AiderDesk->>Extension: onAgentFinished
Note right of Extension: Can modify resultMessages<br/>Cannot block
Extension-->>AiderDesk: Modified result messages
AiderDesk->>Extension: onPromptFinished
Note right of Extension: Can modify responses<br/>Cannot block
Extension-->>AiderDesk: Final responses
AiderDesk-->>User: Display responses
end
end
```
## Event Details by Phase
### Phase 1: Prompt Initialization
**onPromptStarted** - First event fired when user submits a prompt
- **Can modify**: `prompt`, `mode`, `promptContext`
- **Can block**: ✅ Yes
- **Use for**:
- Filter inappropriate content
- Add prefixes/suffixes to prompts
- Validate prompts before processing
### Phase 2: Agent Execution
**onAgentStarted** - Before the agent begins processing
- **Can modify**: `prompt`, `contextFiles`, `systemPrompt`, `agentProfile`, `providerProfile`, `model`
- **Can block**: ✅ Yes
- **Use for**:
- Inject project-specific context
- Modify system prompts
- Change agent configuration
**onOptimizeMessages** - After messages are optimized for the LLM
- **Can modify**: `optimizedMessages`
- **Can block**: ❌ No
- **Use for**:
- Control token usage
- Remove sensitive data from history
- Add additional context
### Phase 2b: LLM Processing Loop
These events fire during each iteration of the LLM processing:
**onResponseChunk** - For each response chunk
- **Can modify**: `chunk`
- **Can block**: ❌ No
- **Use for**: Real-time response modification
**onToolApproval** - When a tool requires approval
- **Can modify**: `allowed`, `blocked`
- **Can block**: ✅ Yes (via `allowed`)
- **Use for**: Auto-approve safe tools
**onToolCalled** - Before tool execution
- **Can modify**: `input`
- **Can block**: ❌ No (use `onToolApproval` instead)
- **Use for**: Prevent dangerous tool calls, modify inputs
**onToolFinished** - After tool execution
- **Can modify**: `output`
- **Can block**: ❌ No
- **Use for**: Format tool outputs, add metadata
**onAgentStepFinished** - After each LLM step
- **Can modify**: `finishReason`, `responseMessages`
- **Can block**: ❌ No
- **Use for**: Control iteration behavior
### Phase 3: Completion
**onAgentFinished** - After agent completes
- **Can modify**: `resultMessages`
- **Can block**: ❌ No
- **Use for**: Post-process final messages
**onPromptFinished** - Final event before returning to user
- **Can modify**: `responses`
- **Can block**: ❌ No
- **Use for**: Final response processing
## Quick Reference: Which Event Should I Use?
### Want to Modify or Filter Prompts?
| Event | When to Use | Can Block? |
|-------|------------|------------|
| `onPromptStarted` | Modify user's prompt text before processing, filter inappropriate content, add prefixes/suffixes | ✅ Yes |
| `onAgentStarted` | Modify prompt, context files, or system prompt before agent execution | ✅ Yes |
| `onOptimizeMessages` | Modify message history sent to LLM (e.g., remove sensitive data, add context) | ❌ No |
### Want to Customize Prompt Templates?
| Event | When to Use | Can Block? |
|-------|------------|------------|
| `onPromptTemplate` | Customize or override prompt templates (system prompts, init-project, etc.) before they're rendered | ❌ No |
### Want to Control Tool Execution?
| Event | When to Use | Can Block? |
|-------|------------|------------|
| `onToolApproval` | Control which tools require user approval, auto-approve safe tools | ✅ Yes (via `allowed`) |
| `onToolCalled` | Modify tool inputs before execution, prevent specific tool calls | ❌ No |
| `onToolFinished` | Modify tool outputs after execution, add metadata, format results | ❌ No |
### Want to Modify Responses?
| Event | When to Use | Can Block? |
|-------|------------|------------|
| `onResponseChunk` | Modify streaming response chunks in real-time | ❌ No |
| `onAgentStepFinished` | Modify step results, control iteration behavior | ❌ No |
| `onAgentFinished` | Modify final result messages before returning to user | ❌ No |
| `onPromptFinished` | Post-process all responses before display | ❌ No |
### Want to Enhance Context?
| Event | When to Use | Can Block? |
|-------|------------|------------|
| `onFilesAdded` | Filter or add files when user adds them to context | ✅ Yes |
| `onFilesDropped` | Control what files can be dropped into chat | ✅ Yes |
| `onRuleFilesRetrieved` | Modify which rule files (AGENTS.md, etc.) are loaded | ❌ No |
| `onImportantReminders` | Add custom reminders to user messages | ❌ No |
### Want to Handle Task/Project Lifecycle?
| Event | When to Use | Can Block? |
|-------|------------|------------|
| `onTaskCreated` | Initialize task-specific data, validate task creation | ❌ No |
| `onTaskPrepared` | Run setup logic when task is prepared (new or loaded) | ❌ No |
| `onTaskInitialized` | Execute code when task is ready for use | ❌ No |
| `onTaskClosed` | Cleanup when task is closed | ❌ No |
| `onProjectStarted` | Initialize project-level resources | ❌ No |
| `onProjectStopped` | Cleanup project-level resources | ❌ No |
## Common Use Cases with Examples
### 1. Add Custom Context to All Prompts
Implement `onAgentStarted` to inject project-specific context:
```typescript
async onAgentStarted(event: AgentStartedEvent, context: ExtensionContext): Promise<Partial<AgentStartedEvent>> {
// Add project guidelines to system prompt
const guidelines = await loadProjectGuidelines(context.getProjectDir());
return {
systemPrompt: event.systemPrompt + '\n\n' + guidelines
};
}
```
### 2. Prevent Dangerous Operations
Implement `onPromptStarted` to block dangerous commands:
```typescript
async onPromptStarted(event: PromptStartedEvent, context: ExtensionContext): Promise<Partial<PromptStartedEvent>> {
const dangerousPatterns = ['rm -rf', 'DROP TABLE', 'format disk'];
if (dangerousPatterns.some(pattern => event.prompt.includes(pattern))) {
context.log('Blocked dangerous prompt', 'warning');
return { blocked: true };
}
return {};
}
```
### 3. Auto-Approve Safe Tools
Implement `onToolApproval` to auto-approve read-only tools:
```typescript
async onToolApproval(event: ToolApprovalEvent, context: ExtensionContext): Promise<Partial<ToolApprovalEvent>> {
const readOnlyTools = ['file_read', 'semantic_search', 'glob', 'grep'];
if (readOnlyTools.includes(event.toolName)) {
context.log(`Auto-approving safe tool: ${event.toolName}`, 'info');
return { allowed: true };
}
return {};
}
```
### 4. Filter Files Added to Context
Implement `onFilesAdded` to prevent sensitive files from being added:
```typescript
async onFilesAdded(event: FilesAddedEvent, context: ExtensionContext): Promise<Partial<FilesAddedEvent>> {
const filtered = event.files.filter(file =>
!file.path.includes('.env') &&
!file.path.includes('secrets') &&
!file.path.includes('credentials')
);
if (filtered.length !== event.files.length) {
context.log(`Filtered ${event.files.length - filtered.length} sensitive files`, 'info');
}
return { files: filtered };
}
```
### 5. Enhance Tool Outputs
Implement `onToolFinished` to add metadata or format results:
```typescript
async onToolFinished(event: ToolFinishedEvent, context: ExtensionContext): Promise<Partial<ToolFinishedEvent>> {
if (event.toolName === 'file_read' && typeof event.output === 'string') {
// Add line numbers to file contents
const lines = event.output.split('\n');
const numbered = lines.map((line, i) => `${i + 1}|${line}`).join('\n');
return { output: numbered };
}
return {};
}
```
### 6. Add Custom Reminders
Implement `onImportantReminders` to inject custom instructions:
```typescript
async onImportantReminders(event: ImportantRemindersEvent, context: ExtensionContext): Promise<Partial<ImportantRemindersEvent>> {
const customReminders = `
## Project-Specific Rules
- Always use TypeScript strict mode
- Follow the existing code style in each file
- Add unit tests for new functions
`;
return {
remindersContent: event.remindersContent + customReminders
};
}
```
### 7. Optimize Message History
Implement `onOptimizeMessages` to control token usage:
```typescript
async onOptimizeMessages(event: OptimizeMessagesEvent, context: ExtensionContext): Promise<Partial<OptimizeMessagesEvent>> {
// Keep only last 20 messages to reduce tokens
const maxMessages = 20;
const optimized = event.optimizedMessages.slice(-maxMessages);
if (optimized.length < event.optimizedMessages.length) {
context.log(`Trimmed ${event.optimizedMessages.length - optimized.length} old messages`, 'info');
}
return { optimizedMessages: optimized };
}
```
### 8. Validate Task Creation
Implement `onTaskCreated` to enforce naming conventions:
```typescript
async onTaskCreated(event: TaskCreatedEvent, context: ExtensionContext): Promise<Partial<TaskCreatedEvent>> {
const task = event.task;
// Auto-generate task name if missing
if (!task.name || task.name.trim() === '') {
const defaultName = `Task-${Date.now()}`;
return {
task: { ...task, name: defaultName }
};
}
return {};
}
```
### 9. Customize Prompt Templates
Implement `onPromptTemplate` to customize prompt templates before they're rendered:
```typescript
async onPromptTemplate(event: PromptTemplateEvent, context: ExtensionContext): Promise<Partial<PromptTemplateEvent>> {
// Customize the system prompt
if (event.name === 'system-prompt') {
const projectDir = context.getProjectDir();
const customInstructions = `
## Project-Specific Guidelines
- This project uses TypeScript with strict mode
- Always prefer type-safe implementations
- Follow the existing code patterns
`;
return {
prompt: event.prompt + customInstructions
};
}
// Customize the init-project prompt
if (event.name === 'init-project') {
return {
prompt: event.prompt.replace('[DEFAULT INSTRUCTIONS]', '[CUSTOM PROJECT INSTRUCTIONS]')
};
}
return {};
}
```
## Event Execution Order
### During Prompt Execution
```
1. onPromptStarted ← First chance to modify/block prompt
2. onAgentStarted ← Modify agent configuration
3. onOptimizeMessages ← Modify message history
4. [LLM Processing Loop]
4a. onResponseChunk ← Modify each response chunk
4b. onToolApproval ← Control tool execution
4c. onToolCalled ← Modify tool inputs
4d. onToolFinished ← Modify tool outputs
4e. onAgentStepFinished ← Modify step results
5. onAgentFinished ← Modify final messages
6. onPromptFinished ← Last chance to modify responses
```
### During File Operations
```
1. onFilesAdded ← Filter files added via command
2. onFilesDropped ← Filter files dropped in UI
3. onRuleFilesRetrieved ← Modify rule files loaded
```
### During Task Lifecycle
```
1. onTaskCreated ← Task just created
2. onTaskPrepared ← Task prepared (new or loaded)
3. onTaskInitialized ← Task ready for use
4. [Task execution...]
5. onTaskUpdated ← Task data modified
6. onTaskClosed ← Task closing
```
### During Project Lifecycle
```
1. onProjectStarted ← Project opened
2. [Tasks created/used...]
3. onProjectStopped ← Project closed
```
## Blocking vs Non-Blocking Events
### Events That Can Block Execution
These events allow you to prevent an action by returning `{ blocked: true }`:
- ✅ `onPromptStarted` - Block prompt execution
- ✅ `onAgentStarted` - Block agent execution
- ✅ `onToolApproval` - Block tool (by not approving)
- ✅ `onFilesAdded` - Block files from being added (return empty array)
- ✅ `onFilesDropped` - Block files from being dropped (return empty array)
- ✅ `onHandleApproval` - Block approval handling
- ✅ `onSubagentStarted` - Block subagent spawning
- ✅ `onCustomCommandExecuted` - Block custom command
- ✅ `onAiderPromptStarted` - Block Aider prompt
### Events That Cannot Block
These events can only modify data, not prevent execution:
- ❌ `onOptimizeMessages` - Can only modify messages
- ❌ `onResponseChunk` - Can only modify chunks
- ❌ `onAgentStepFinished` - Can only modify step results
- ❌ `onToolFinished` - Can only modify tool output
- ❌ `onAgentFinished` - Can only modify result messages
- ❌ `onPromptFinished` - Can only modify responses
- ❌ All task/project lifecycle events
## Extension Context Capabilities
Your extension receives an `ExtensionContext` object that provides safe access to AiderDesk:
### Available in All Events
```typescript
context.log(message, 'info' | 'error' | 'warn' | 'debug') // Log messages
context.getProjectDir() // Get project path
context.getProjectContext() // Access project operations
context.getModelConfigs() // Get available models
context.getSetting('key.path') // Get setting value
context.updateSettings({ ... }) // Update settings
```
### Available in Task-Related Events
```typescript
const task = context.getTaskContext()
if (task) {
// Read task data
task.data // Task metadata
await task.getContextFiles() // Get context files
await task.getContextMessages() // Get message history
// Modify task
await task.addFile(path, readOnly) // Add file to context
await task.dropFile(path) // Remove file from context
await task.updateTask({ name: '...' }) // Update task data
// Execute operations
await task.runPrompt(prompt, mode) // Run a prompt
await task.runCommand(command) // Execute command
await task.interruptResponse() // Stop current execution
// User interaction
await task.askQuestion('Continue?', {
answers: [{ text: 'Yes', shortkey: 'y' }]
})
task.addLogMessage('info', 'Processing...')
}
```
## Tips for Extension Developers
1. **Use Blocking Sparingly**: Only block when absolutely necessary. Blocking prevents users from completing their work.
2. **Log Your Actions**: Always use `context.log()` to help users understand what your extension is doing.
3. **Handle Errors Gracefully**: Wrap your logic in try-catch and log errors instead of crashing.
4. **Return Empty Objects**: If you don't need to modify an event, return `{}` instead of nothing.
5. **Check Context Availability**: Always check if `getTaskContext()` returns null before using it.
6. **Respect User Intent**: Don't completely rewrite user prompts without good reason.
7. **Test Blocking Logic**: Make sure your blocking conditions are well-tested to avoid false positives.
8. **Document Your Extension**: Clearly document which events your extension uses and why.
## See Also
- [Events Reference](./events.md) - Complete event documentation
- [API Reference](./api-reference.md) - Full type definitions
- [Extensions Gallery](./extensions-gallery.md) - Browse example extensions for inspiration and check out production-ready extensions
- [Creating Extensions](./creating-extensions.md) - Step-by-step tutorial