Session hooks
Withhooks, you can insert logic at each stage of a Copilot session lifecycle.
You can add tool execution control, audit logging, prompt enrichment, and error handling without changing core implementation.
Hook flow
Basic usage
Available hooks
Returning
null keeps default behavior.
Typical use cases
1) Permission control
- Use
onPreToolUsewith allow-list policies. - Require human approval for destructive actions with
permissionDecision: 'ask'. - Use
permissionDecisionReasonfor explicit denial reasons. - See Tools for tool name candidates such as
view,glob, andbash.
2) Auditing and compliance
- Combine lifecycle hooks to collect audit events.
- Persist collected records by session ID.
3) Prompt enrichment
- Add project context in
onSessionStart(language, framework, conventions). - Expand shortcuts such as
/fixand/testinonUserPromptSubmitted.
4) Result filtering
- Mask API keys, tokens, and passwords in
onPostToolUse. - Summarize oversized results and return details only when needed.
5) Error recovery
- Retry only when
errorContextismodel_callandrecoverable=true. - Provide concise user notifications for non-recoverable paths.
6) Session metrics
- Record start time in
onSessionStart. - Update counters in
onPreToolUseandonUserPromptSubmitted. - Emit duration, tool counts, and termination reason in
onSessionEnd.
Hook input and output types
Common input (BaseHookInput)
PreToolUseHookInput
PreToolUseHookOutput
PostToolUseHookInput
PostToolUseHookOutput
UserPromptSubmittedHookInput
UserPromptSubmittedHookOutput
SessionStartHookInput
SessionStartHookOutput
SessionEndHookInput
SessionEndHookOutput
ErrorOccurredHookInput
ErrorOccurredHookOutput
ToolResultObject
Standard object for tool execution results.Best practices
- Avoid heavy sync work inside hooks. Offload when needed.
- Return
nullwhen no customization is required. - Make
permissionDecisionexplicit whenever possible. - Do not over-suppress critical errors. Keep logs and notifications.
- Manage session state by session ID and clean up in
onSessionEnd.
For the latest updates, see the GitHub repository.