Skip to content

Commit 3cbfe9f

Browse files
authored
Merge pull request #42417 from github/repo-sync
Repo sync
2 parents 1a5d8d0 + 0c3a153 commit 3cbfe9f

File tree

8 files changed

+835
-0
lines changed

8 files changed

+835
-0
lines changed

content/copilot/concepts/agents/about-copilot-cli.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,10 @@ You can customize {% data variables.copilot.copilot_cli %} in a number of ways:
149149
* **Custom instructions**: Custom instructions allow you to give {% data variables.product.prodname_copilot_short %} additional context on your project and how to build, test and validate its changes. For more information, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/use-copilot-cli#use-custom-instructions).
150150
* **Model Context Protocol (MCP) servers**: MCP servers allow you to give {% data variables.product.prodname_copilot_short %} access to different data sources and tools. For more information, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/use-copilot-cli#add-an-mcp-server).
151151
* **{% data variables.copilot.custom_agents_caps_short %}**: {% data variables.copilot.custom_agents_caps_short %} allow you to create different specialized versions of {% data variables.product.prodname_copilot_short %} for different tasks. For example, you could customize {% data variables.product.prodname_copilot_short %} to be an expert frontend engineer following your team's guidelines. {% data variables.copilot.copilot_cli %} includes specialized {% data variables.copilot.custom_agents_short %} that it automatically delegates common tasks to. For more information, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/use-copilot-cli#use-custom-agents).
152+
* **Hooks**: Hooks allow you to execute custom shell commands at key points during agent execution, enabling you to add validation, logging, security scanning, or workflow automation. See [AUTOTITLE](/copilot/concepts/agents/coding-agent/about-hooks).
152153
* **Skills**: Skills allow you to enhance the ability of {% data variables.product.prodname_copilot_short %} to perform specialized tasks with instructions, scripts, and resources. For more information, see [AUTOTITLE](/copilot/concepts/agents/about-agent-skills).
153154

155+
154156
## Security considerations
155157

156158
When you use {% data variables.copilot.copilot_cli_short %}, {% data variables.product.prodname_copilot_short %} can perform tasks on your behalf, such as executing or modifying files, or running shell commands.

content/copilot/concepts/agents/coding-agent/about-coding-agent.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ You can customize {% data variables.copilot.copilot_coding_agent %} in a number
118118
* **Custom instructions**: Custom instructions allow you to give {% data variables.product.prodname_copilot_short %} additional context on your project and how to build, test and validate its changes. For more information, see [AUTOTITLE](/copilot/how-tos/configure-custom-instructions/add-repository-instructions).
119119
* **Model Context Protocol (MCP) servers**: MCP servers allow you to give {% data variables.product.prodname_copilot_short %} access to different data sources and tools. For more information, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/coding-agent/extend-coding-agent-with-mcp).
120120
* **{% data variables.copilot.custom_agents_caps_short %}**: {% data variables.copilot.custom_agents_caps_short %} allow you to create different specialized versions of {% data variables.product.prodname_copilot_short %} for different tasks. For example, you could customize {% data variables.product.prodname_copilot_short %} to be an expert frontend engineer following your team's guidelines. For more information, see [AUTOTITLE](/copilot/concepts/agents/coding-agent/about-custom-agents).
121+
* **Hooks**: Hooks allow you to execute custom shell commands at key points during agent execution, enabling you to add validation, logging, security scanning, or workflow automation. For more information, see [AUTOTITLE](/copilot/concepts/agents/coding-agent/about-hooks).
121122
* **Skills**: Skills allow you to enhance the ability of {% data variables.product.prodname_copilot_short %} to perform specialized tasks with instructions, scripts, and resources. For more information, see [AUTOTITLE](/copilot/concepts/agents/about-agent-skills).
122123

123124
## Built-in security protections
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
---
2+
title: About hooks
3+
shortTitle: Hooks
4+
intro: 'Extend and customize {% data variables.product.prodname_copilot %} agent behavior by executing custom shell commands at key points during agent execution.'
5+
product: '{% data reusables.gated-features.copilot-coding-agent %}<br><a href="https://github.com/features/copilot/plans?ref_product=copilot&ref_type=purchase&ref_style=button" target="_blank" class="btn btn-primary mt-3 mr-3 no-underline"><span>Sign up for {% data variables.product.prodname_copilot_short %}</span> {% octicon "link-external" height:16 %}</a>'
6+
versions:
7+
feature: copilot
8+
topics:
9+
- Copilot
10+
contentType: concepts
11+
category:
12+
- Configure Copilot
13+
---
14+
15+
## About hooks
16+
17+
Hooks enable you to execute custom shell commands at strategic points in an agent's workflow, such as when an agent session starts or ends, or before and after a prompt is entered or a tool is called.
18+
19+
Hooks receive detailed information about agent actions via JSON input, enabling context-aware automation. For example, you can use hooks to:
20+
21+
* Programmatically approve or deny tool executions.
22+
* Utilize built-in security features like secret scanning to prevent credential leaks.
23+
* Implement custom validation rules and audit logging for compliance.
24+
25+
{% data variables.product.prodname_copilot_short %} agents support hooks stored in JSON files in your repository at `.github/hooks/*.json`.
26+
27+
Hooks are available for use with:
28+
29+
* {% data variables.copilot.copilot_coding_agent %} on {% data variables.product.github %}
30+
* {% data variables.copilot.copilot_cli %} in the terminal
31+
32+
## Types of hooks
33+
34+
The following types of hooks are available:
35+
36+
* **sessionStart**: Executed when a new agent session begins or when resuming an existing session. Can be used to initialize environments, log session starts for auditing, validate project state, and set up temporary resources.
37+
* **sessionEnd**: Executed when the agent session completes or is terminated. Can be used to cleanup temporary resources, generate and archive session reports and logs, or send notifications about session completion.
38+
* **userPromptSubmitted**: Executed when the user submits a prompt to the agent. Can be used to log user requests for auditing and usage analysis.
39+
* **preToolUse**: Executed before the agent uses any tool (such as `bash`, `edit`, `view`). This is the most powerful hook as it can **approve or deny tool executions**. Use this hook to block dangerous commands, enforce security policies and coding standards, require approval for sensitive operations, or log tool usage for compliance.
40+
* **postToolUse**: Executed after a tool completes execution (whether successful or failed). Can be used to log execution results, track usage statistics, generate audit trails, monitor performance metrics, and send failure alerts.
41+
* **errorOccurred**: Executed when an error occurs during agent execution. Can be used to log errors for debugging, send notifications, track error patterns, and generate reports.
42+
43+
To see a complete reference of hook types with example use cases, best practices, and advanced patterns, see [AUTOTITLE](/copilot/reference/hooks-configuration).
44+
45+
## Hook configuration format
46+
47+
You configure hooks using a special JSON format. The JSON must contain a `version` field with a value of `1` and a `hooks` object containing arrays of hook definitions.
48+
49+
```json copy
50+
{
51+
"version": 1,
52+
"hooks": {
53+
"sessionStart": [
54+
{
55+
"type": "command",
56+
"bash": "string (optional)",
57+
"powershell": "string (optional)",
58+
"cwd": "string (optional)",
59+
"env": { "KEY": "value" },
60+
"timeoutSec": 30
61+
}
62+
],
63+
}
64+
}
65+
```
66+
67+
The hook object can contain the following keys:
68+
69+
| Property | Required | Description |
70+
| --- | --- | --- |
71+
| `type` | Yes | Must be `"command"` |
72+
| `bash` | Yes (on Unix systems) | Path to the bash script to execute |
73+
| `powershell` | Yes (on Windows) | Path to the PowerShell script to execute |
74+
| `cwd` | No | Working directory for the script (relative to repository root) |
75+
| `env` | No | Additional environment variables that are merged with the existing environment |
76+
| `timeoutSec` | No | Maximum execution time in seconds (default: 30) |
77+
78+
## Example hook configuration file
79+
80+
This is an example configuration file that lives in `~/.github/hooks/project-hooks.json` within a repository.
81+
82+
```json copy
83+
{
84+
"version": 1,
85+
"hooks": {
86+
"sessionStart": [
87+
{
88+
"type": "command",
89+
"bash": "echo \"Session started: $(date)\" >> logs/session.log",
90+
"powershell": "Add-Content -Path logs/session.log -Value \"Session started: $(Get-Date)\"",
91+
"cwd": ".",
92+
"timeoutSec": 10
93+
}
94+
],
95+
"userPromptSubmitted": [
96+
{
97+
"type": "command",
98+
"bash": "./scripts/log-prompt.sh",
99+
"powershell": "./scripts/log-prompt.ps1",
100+
"cwd": "scripts",
101+
"env": {
102+
"LOG_LEVEL": "INFO"
103+
}
104+
}
105+
],
106+
"preToolUse": [
107+
{
108+
"type": "command",
109+
"bash": "./scripts/security-check.sh",
110+
"powershell": "./scripts/security-check.ps1",
111+
"cwd": "scripts",
112+
"timeoutSec": 15
113+
},
114+
{
115+
"type": "command",
116+
"bash": "./scripts/log-tool-use.sh",
117+
"powershell": "./scripts/log-tool-use.ps1",
118+
"cwd": "scripts"
119+
}
120+
],
121+
"postToolUse": [
122+
{
123+
"type": "command",
124+
"bash": "cat >> logs/tool-results.jsonl",
125+
"powershell": "$input | Add-Content -Path logs/tool-results.jsonl"
126+
}
127+
],
128+
"sessionEnd": [
129+
{
130+
"type": "command",
131+
"bash": "./scripts/cleanup.sh",
132+
"powershell": "./scripts/cleanup.ps1",
133+
"cwd": "scripts",
134+
"timeoutSec": 60
135+
}
136+
]
137+
}
138+
}
139+
```
140+
141+
## Performance considerations
142+
143+
Hooks run synchronously and block agent execution. To ensure a responsive experience, keep the following considerations in mind:
144+
145+
* **Minimize execution time**: Keep hook execution time under 5 seconds when possible.
146+
* **Optimize logging**: Use asynchronous logging, like appending to files, rather than synchronous I/O.
147+
* **Use background processing**: For expensive operations, consider background processing.
148+
* **Cache results**: Cache expensive computations when possible.
149+
150+
## Security considerations
151+
152+
To ensure security is maintained when using hooks, keep the following considerations in mind:
153+
154+
* **Always validate and sanitize the input processed by hooks**. Untrusted input could lead to unexpected behavior.
155+
* **Use proper shell escaping when constructing commands**. This prevents command injection vulnerabilities.
156+
* **Never log sensitive data, such as tokens or passwords**.
157+
* **Ensure hook scripts and logs have the appropriate permissions**.
158+
* **Be cautious with hooks that make external network calls**. These can introduce latency, failures, or expose data to third parties.
159+
* **Set appropriate timeouts to prevent resource exhaustion**. Long-running hooks can block agent execution and degrade performance.
160+
161+
## Next steps
162+
163+
To start creating hooks, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/coding-agent/use-hooks).
164+

content/copilot/concepts/agents/coding-agent/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ children:
1111
- /about-coding-agent
1212
- /agent-management
1313
- /about-custom-agents
14+
- /about-hooks
1415
- /access-management
1516
- /mcp-and-coding-agent
1617
contentType: concepts

content/copilot/how-tos/use-copilot-agents/coding-agent/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ children:
2020
- /changing-the-ai-model
2121
- /customize-the-agent-environment
2222
- /customize-the-agent-firewall
23+
- /use-hooks
2324
- /troubleshoot-coding-agent
2425
redirect_from:
2526
- /copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
---
2+
title: Using hooks with GitHub Copilot agents
3+
shortTitle: Use hooks
4+
intro: 'Learn how to extend and customize {% data variables.product.prodname_copilot %} agent behavior by executing custom shell commands at key points during agent execution.'
5+
versions:
6+
feature: copilot
7+
topics:
8+
- Copilot
9+
contentType: how-tos
10+
category:
11+
- Configure Copilot
12+
---
13+
14+
Hooks allow you to extend and customize the behavior of {% data variables.product.prodname_copilot %} agents by executing custom shell commands at key points during agent execution. For a conceptual overview of hooks, see [AUTOTITLE](/copilot/concepts/agents/coding-agent/about-hooks).
15+
16+
## Creating a hook in a repository on {% data variables.product.github %}
17+
18+
1. Create a new `hooks.json` file with the name of your choice in the `.github/hooks/` folder of your repository. The hooks configuration file **must be present** on your repository's default branch to be used by {% data variables.copilot.copilot_coding_agent %}. For {% data variables.copilot.copilot_cli %}, hooks are loaded from your current working directory.
19+
20+
1. In your text editor, copy and paste the following hook template. Remove any hooks you don't plan on using from the `hooks` array.
21+
22+
```json copy
23+
{
24+
"version": 1,
25+
"hooks": {
26+
"sessionStart": [...],
27+
"sessionEnd": [...],
28+
"userPromptSubmitted": [...],
29+
"preToolUse": [...],
30+
"postToolUse": [...],
31+
"errorOccurred": [...]
32+
}
33+
}
34+
```
35+
36+
1. Configure your hook syntax under the `bash` or `powershell` keys, or directly reference script files you have created.
37+
38+
* This example runs a script that outputs the start date of the session to a log file using the `sessionStart` hook:
39+
40+
```json copy
41+
"sessionStart": [
42+
{
43+
"type": "command",
44+
"bash": "echo \"Session started: $(date)\" >> logs/session.log",
45+
"powershell": "Add-Content -Path logs/session.log -Value \"Session started: $(Get-Date)\"",
46+
"cwd": ".",
47+
"timeoutSec": 10
48+
}
49+
],
50+
```
51+
52+
* This example calls out to an external `log-prompt` script:
53+
54+
```json copy
55+
"userPromptSubmitted": [
56+
{
57+
"type": "command",
58+
"bash": "./scripts/log-prompt.sh",
59+
"powershell": "./scripts/log-prompt.ps1",
60+
"cwd": "scripts",
61+
"env": {
62+
"LOG_LEVEL": "INFO"
63+
}
64+
}
65+
],
66+
```
67+
68+
For a full reference on the input JSON from agent sessions along with sample scripts, see [AUTOTITLE](/copilot/reference/hooks-configuration).
69+
70+
1. Commit the file to the repository and merge it into the default branch. Your hooks will now run during agent sessions.
71+
72+
## Troubleshooting
73+
74+
If you run into problems using hooks, use the following table to troubleshoot.
75+
76+
| Issue | Action |
77+
| --- | --- |
78+
| Hooks are not executing | <ul><li>Verify the JSON file is in the `.github/hooks/` directory.</li><li>Check for valid JSON syntax (for example, `jq . hooks.json`).</li><li>Ensure `version: 1` is specified in your `hooks.json` file.</li><li>Verify the script you are calling from your hook is executable (`chmod +x script.sh`)</li><li>Check that the script has a proper shebang (for example, `#!/bin/bash`)</li></ul> |
79+
| Hooks are timing out | <ul><li>The default timeout is 30 seconds. Increase `timeoutSec` in the configuration if needed.</li><li>Optimize script performance by avoiding unnecessary operations.</li> |
80+
| Invalid JSON output | <ul><li>Ensure the output is on a single line.</li><li>On Unix, use `jq -c` to compact and validate the JSON output.</li><li>On Windows, use the `ConvertTo-Json -Compress` command in PowerShell to do the same.</li></ul> |
81+
82+
## Debugging
83+
84+
You can debug hooks using the following methods:
85+
86+
* **Enable verbose logging** in the script to inspect the input data and trace script execution.
87+
88+
```shell copy
89+
#!/bin/bash
90+
set -x # Enable bash debug mode
91+
INPUT=$(cat)
92+
echo "DEBUG: Received input" >&2
93+
echo "$INPUT" >&2
94+
# ... rest of script
95+
```
96+
97+
* **Test hooks locally** by piping test input into your hook to validate its behavior:
98+
99+
```shell copy
100+
# Create test input
101+
echo '{"timestamp":1704614400000,"cwd":"/tmp","toolName":"bash","toolArgs":"{\"command\":\"ls\"}"}' | ./my-hook.sh
102+
103+
# Check exit code
104+
echo $?
105+
106+
# Validate output is valid JSON
107+
./my-hook.sh | jq .
108+
```
109+
110+
## Further reading
111+
112+
* For more information about configuring hooks, see [AUTOTITLE](/copilot/reference/hooks-configuration)
113+
* For more information about {% data variables.copilot.copilot_coding_agent %}, see [AUTOTITLE](/copilot/concepts/agents/coding-agent/about-coding-agent)
114+
* For more information about {% data variables.copilot.copilot_cli %}, see [AUTOTITLE](/copilot/concepts/agents/about-copilot-cli)
115+
* For information about customizing the agent environment, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/coding-agent/customize-the-agent-environment)

0 commit comments

Comments
 (0)