Hook Tiers
Hooks are organized into tiers based on their execution context:| Tier | Count | Purpose | Composition File |
|---|---|---|---|
| Session | 23 | Session lifecycle, model selection, error recovery | create-session-hooks.ts |
| Tool Guard | 10 | Pre/post tool execution validation | create-tool-guard-hooks.ts |
| Transform | 4 | Message content transformation | create-transform-hooks.ts |
| Continuation | 7 | Session continuation logic | create-continuation-hooks.ts |
| Skill | 2 | Skill-based reminders and commands | create-skill-hooks.ts |
src/plugin/hooks/ directory
Hook Events
Hooks respond to OpenCode plugin events:Factory Pattern
All hooks follow thecreateXXXHook(deps) → HookFunction factory pattern.
Basic Hook Structure
Hook Types and Signatures
chat.params Hook
Modify API request parameters before sending:src/hooks/anthropic-effort/hook.ts:35
tool.execute.before Hook
Intercept tool calls before execution:tool.execute.after Hook
Modify tool results after execution:event Hook
Respond to session lifecycle events:experimental.chat.messages.transform Hook
Transform message arrays before API submission:Hook Registration
Register hooks in tier-specific composition files:import type { PluginContext } from "../../plugin/types"
export function createMyHook(ctx: PluginContext) {
return {
"chat.params": async (input, output) => {
// Implementation
}
}
}
import { createMyHook } from "../../hooks/my-hook"
export type SessionHooks = {
// ... existing hooks
myHook: ReturnType<typeof createMyHook> | null
}
export function createSessionHooks(args) {
const myHook = isHookEnabled("my-hook")
? safeHook("my-hook", () => createMyHook(ctx))
: null
return {
// ... existing hooks
myHook
}
}
Hook Composition
Tier composition files aggregate hooks:src/plugin/hooks/create-core-hooks.ts:8
Safe Hook Creation
ThesafeCreateHook wrapper prevents individual hook failures from breaking the plugin:
- Catches exceptions during hook creation
- Logs errors without crashing
- Returns
nullon failure
Hook Examples
Model Fallback Hook
Automatically switch models on API errors:Comment Checker Hook
Block AI-generated comment patterns:src/hooks/comment-checker/index.ts
Hook Dependencies
Hooks can receive dependencies via factory arguments:Disabling Hooks
Disable hooks via configuration:isHookEnabled check prevents disabled hooks from being created.
Testing Hooks
Test hooks in isolation:describe blocks.
Related Files
- Hook Composition:
src/plugin/hooks/create-*-hooks.ts - Hook Aggregation:
src/create-hooks.ts - Plugin Interface:
src/plugin-interface.ts - Safe Hook Creation:
src/shared/safe-create-hook.ts - Hook Schema:
src/config/schema/hooks.ts