{"meta":{"title":"GitHub Copilot hooks reference","intro":"Find hook events, configuration formats, and input payloads for hooks in Copilot CLI and Copilot cloud agent.","product":"GitHub Copilot","breadcrumbs":[{"href":"/en/enterprise-cloud@latest/copilot","title":"GitHub Copilot"},{"href":"/en/enterprise-cloud@latest/copilot/reference","title":"Reference"},{"href":"/en/enterprise-cloud@latest/copilot/reference/hooks-reference","title":"Hooks reference"}],"documentType":"article"},"body":"# GitHub Copilot hooks reference\n\nFind hook events, configuration formats, and input payloads for hooks in Copilot CLI and Copilot cloud agent.\n\n## Introduction\n\nHooks are external commands that execute at specific lifecycle points during a session, enabling custom automation, security controls, and integrations.\n\nHooks are supported in two Copilot surfaces: Copilot CLI and Copilot cloud agent. Most of the configuration format and event payloads are identical, but the execution environment and the set of events that can fire differ.\n\nThroughout this article, behavior that differs between the two surfaces is called out in \"CLI only\" and \"Cloud agent only\" notes. Anything not marked applies to both.\n\n## Hooks locations\n\nThe locations where hooks run, and where you can store hook configuration files, depend on the surface:\n\n* **Copilot CLI** — hooks run on the developer's local machine in the same shell as the CLI. All hook events described in this article are supported by the CLI.\n\n  Hooks are loaded from the following sources in order (policy, then user, then project, then plugins) and combined. When the same event appears in multiple sources, all hook entries from all sources are run.\n\n  * **Policy-level hook files** — JSON files in the platform-appropriate policy directory, loaded in alphabetical order. Policy hooks are machine-wide and load before all other hooks. They cannot be disabled by `disableAllHooks` and are available regardless of folder trust state. See [Policy hooks](#policy-hooks) below.\n  * **Repository-level hook files** — `.github/hooks/*.json` in the repository root.\n  * **User-level hook files** — `*.json` files in the user-level hooks directory. By default this is `~/.copilot/hooks/` on macOS and Linux, or `%USERPROFILE%\\.copilot\\hooks\\` on Windows. If `COPILOT_HOME` is set, it is `$COPILOT_HOME/hooks/`.\n  * **Inline `hooks` block in repository settings** — the `hooks` field at the top level of `.github/copilot/settings.json` (Git committed) or `.github/copilot/settings.local.json` (typically gitignored and user specific) in the repository. Cross-tool `.claude/settings.json` and `.claude/settings.local.json` files in the repository are also read.\n  * **Inline `hooks` block in user-level config** — the `hooks` field at the top level of `~/.copilot/settings.json`.\n  * **Hooks contributed by installed plugins** — declared by each plugin in its own `hooks.json` (or under `hooks/hooks.json`) inside the plugin's installation directory.\n\n* **Copilot cloud agent** — hooks run inside the ephemeral Linux sandbox that cloud agent provisions for each job. The sandbox is non-interactive, has a constrained network, and is destroyed when the job ends. A subset of events fires, and only `bash` (or `command`) entries are honored.\n\n  Hook configuration is loaded from `.github/hooks/*.json` files in the cloned repository.\n\n### Policy hooks\n\n> \\[!NOTE]\n> **Copilot CLI only.** Policy hooks are not supported under Copilot cloud agent.\n\nPolicy hooks are machine-wide hooks loaded by administrators. They load before all other hooks and cannot be disabled by `disableAllHooks`.\n\nPolicy hooks are discovered from two sources:\n\n* **Filesystem**: JSON files in the platform-appropriate policy directory, loaded in alphabetical order:\n  * Linux/macOS: `/etc/github-copilot/policy.d/*.json`\n  * Windows: `C:\\ProgramData\\GitHub\\Copilot\\policy.d\\*.json`\n* **Windows Registry**: Values under `HKLM\\Software\\Policies\\GitHub\\Copilot` (each subkey holds a `Policy` REG\\_SZ value containing a JSON policy document).\n\nPolicy hook files use the same hook configuration format as user and project hooks (`{ \"version\": 1, \"hooks\": { ... } }`). On POSIX systems, policy files must be owned by root and must not be group- or world-writable.\n\nPolicy hooks are intended for use by enterprise IT administrators and require elevated privileges to install. End users cannot modify them.\n\n## Cloud agent execution environment\n\nThis section applies to **Copilot cloud agent only**. It describes constraints that affect how you write hook scripts and configure hook entries for cloud agent jobs.\n\n| Property                        | Value                                                                                                                                                                                                                                                                                      |\n| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| Operating system                | Linux. Only the `bash` field on command hooks is honored; `powershell` entries are ignored. The cross-platform `command` field is honored as a fallback.                                                                                                                                   |\n| Working directory               | `/workspace` when a repository is cloned, otherwise `/root`. Use this path when setting `cwd` on a hook entry or when referencing files from a script.                                                                                                                                     |\n| Filesystem                      | Ephemeral. Files written by hooks (logs, CSVs, transcripts) are discarded when the job ends. To retain hook output, send it via an `http` hook entry.                                                                                                                                      |\n| Outbound network                | Restricted by the cloud agent firewall. By default only GitHub and Copilot hostnames are reachable; reaching any other host (for example `https://hooks.example.com`) requires an admin-configured firewall allow rule.                                                                    |\n| Available environment variables | `GITHUB_COPILOT_API_TOKEN` and `GITHUB_COPILOT_GIT_TOKEN` are set in the sandbox. `COPILOT_AGENT_PROMPT` holds the prompt the job was invoked with. `HOME` is set to `/root`, so any hook script that resolves `~/...` paths writes into the ephemeral sandbox. `GITHUB_TOKEN` is not set. |\n| Interactivity                   | Fully non-interactive. The agent runs with all tool permissions pre-granted, so no permission dialogs are shown and no notifications are surfaced to a user.                                                                                                                               |\n| Configuration discovery         | In a cloud agent job, the only hook configuration that exists by default is `.github/hooks/*.json` inside the cloned repository. The sandbox does not ship with user-level hook files, `settings.json`, `config.json`, or installed plugins.                                               |\n\n## Hook configuration format\n\nHook configuration files use JSON format with version `1`.\n\n> \\[!NOTE]\n> If a hook configuration file loaded from a directory (for example, `.github/hooks/`) contains a malformed hook item, only that item is dropped and logged—valid sibling hooks in the same file still load. Structural errors (invalid JSON, a bad `version`, or a non-array event list) still reject the entire file. Hooks defined inline in `settings.json` remain strict: any item-level validation error rejects the whole `hooks` field. Other configuration files always load independently.\n\n### Command hooks\n\nCommand hooks run shell scripts or executables and are supported on all hook types.\n\n> \\[!NOTE]\n> **Cloud agent only.** Cloud agent runs hooks in a Linux sandbox. Only the `bash` field is honored; `powershell` entries are ignored. The cross-platform `command` field is honored as a fallback.\n\n```json\n{\n  \"version\": 1,\n  \"hooks\": {\n    \"preToolUse\": [\n      {\n        \"type\": \"command\",\n        \"bash\": \"YOUR_BASH_COMMAND\",\n        \"powershell\": \"YOUR_POWERSHELL_COMMAND\",\n        \"cwd\": \"OPTIONAL/WORKING/DIRECTORY\",\n        \"env\": { \"VAR\": \"VALUE\" },\n        \"timeoutSec\": 30\n      }\n    ]\n  }\n}\n```\n\nIn Copilot CLI, you can use `exec` and `args` to run an executable directly instead of using a shell:\n\n```json\n{\n  \"version\": 1,\n  \"hooks\": {\n    \"preToolUse\": [\n      {\n        \"type\": \"command\",\n        \"exec\": \"YOUR_EXECUTABLE\",\n        \"args\": [\"YOUR_ARGUMENT\"],\n        \"cwd\": \"OPTIONAL/WORKING/DIRECTORY\",\n        \"env\": { \"VAR\": \"VALUE\" },\n        \"timeoutSec\": 30\n      }\n    ]\n  }\n}\n```\n\nReplace `YOUR_EXECUTABLE` with the executable name or path and `YOUR_ARGUMENT` with an argument to pass to it. You can include additional arguments in the `args` array.\n\nDo not combine `exec` with `bash`, `powershell`, or `command`. Arguments are passed directly to the executable without shell interpretation, so shell features such as pipes, redirection, and glob expansion are not available.\n\n| Field        | Type             | Required                                                              | Description                                                                                                                                                                          |\n| ------------ | ---------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `args`       | array of strings | No                                                                    | Arguments passed directly to `exec`. Only supported in Copilot CLI.                                                                                                                  |\n| `bash`       | string           | One of `bash`, `powershell`, or `command`, unless `exec` is specified | Shell command for Unix.                                                                                                                                                              |\n| `command`    | string           | One of `bash`, `powershell`, or `command`, unless `exec` is specified | Cross-platform fallback. Copied to both `bash` and `powershell` when those fields are absent; explicit `bash` or `powershell` entries take precedence on their respective platforms. |\n| `cwd`        | string           | No                                                                    | Working directory for the command (relative to repository root or absolute).                                                                                                         |\n| `env`        | object           | No                                                                    | Environment variables to set (supports variable expansion).                                                                                                                          |\n| `exec`       | string           | Instead of `bash`, `powershell`, and `command`                        | Executable name or path. Runs the executable directly without a shell. Only supported in Copilot CLI.                                                                                |\n| `powershell` | string           | One of `bash`, `powershell`, or `command`, unless `exec` is specified | Shell command for Windows.                                                                                                                                                           |\n| `timeout`    | number           | No                                                                    | Alias for `timeoutSec`, in seconds. Used only when `timeoutSec` is absent; `timeoutSec` takes precedence when both are present.                                                      |\n| `timeoutSec` | number           | No                                                                    | Timeout in seconds. Default: `30`.                                                                                                                                                   |\n| `type`       | `\"command\"`      | No                                                                    | Hook type. Defaults to `\"command\"` when omitted.                                                                                                                                     |\n\n#### Progress messages\n\nCommand hooks can emit progress status lines to the CLI timeline while executing. Write a `{\"type\": \"progress\", \"message\": \"...\"}` JSON object to stdout before writing the final output:\n\n```bash\necho '{\"type\": \"progress\", \"message\": \"Checking policy...\"}'\n# ... perform work ...\necho '{\"permissionDecision\": \"allow\"}'\n```\n\nSet `\"temporary\": true` to emit a transient status line. A transient line replaces the previous transient line and is cleared when the assistant responds, instead of accumulating in the timeline:\n\n```bash\necho '{\"type\": \"progress\", \"message\": \"Routing...\", \"temporary\": true}'\necho '{\"type\": \"progress\", \"message\": \"Thinking...\", \"temporary\": true}'\n# ... perform work ...\necho '{\"permissionDecision\": \"allow\"}'\n```\n\nProgress messages are display-only and do not affect hook output or decision logic.\n\n**How stdout is parsed when progress messages are mixed in.** — The CLI scans stdout line-by-line as the hook runs. Any line that, after trimming, is a single complete JSON object with `\"type\": \"progress\"` is consumed as a progress event and **removed from the hook's output stream**. Every other line—blank lines, plain text, and JSON objects that are not progress messages—is preserved verbatim. When the hook exits, the preserved lines are concatenated, trimmed, and parsed with a single `JSON.parse` call: that result is the hook's output (the \"hook output JSON\" referenced elsewhere in this article). This means:\n\n* Emitting progress lines alongside a final decision object (as in the examples above) is safe and is the intended pattern—the progress lines never reach the JSON parser.\n* Each progress message must be on its own line and must be valid JSON on that single line. Multi-line / pretty-printed progress objects are not recognized as progress and will be left in the output stream, where they will likely cause the final `JSON.parse` to fail.\n* The final decision object, by contrast, may span multiple lines—only progress *recognition* is line-oriented; what remains after progress stripping is parsed as one JSON document, not as line-delimited JSON.\n* If the leftover output is empty, or fails to parse as JSON, the hook is treated as having produced no output and falls through to default behavior. Two or more non-progress JSON objects on stdout (for example, two `echo '{\"permissionDecision\": ...}'` calls) will therefore concatenate into invalid JSON and be ignored—emit exactly one final decision object.\n\n### HTTP hooks\n\nHTTP hooks send the input payload as a JSON `POST` to a URL.\n\n> \\[!NOTE]\n>\n> * By default, only `https://` URLs are allowed. Non-TLS `http://` requests are rejected, except for `http://localhost`, `http://127.*`, and `http://[::1]` when `COPILOT_HOOK_ALLOW_LOCALHOST=1` is set.\n> * **Cloud agent only.** Outbound network from the sandbox is restricted by the cloud agent firewall, so `url` must target an allow-listed host.\n\n```json\n{\n  \"version\": 1,\n  \"hooks\": {\n    \"postToolUse\": [\n      {\n        \"type\": \"http\",\n        \"url\": \"https://hooks.example.com/copilot\",\n        \"headers\": { \"X-Source\": \"copilot-cli\" },\n        \"allowedEnvVars\": [\"GITHUB_TOKEN\"],\n        \"timeoutSec\": 30\n      }\n    ]\n  }\n}\n```\n\n| Field            | Type      | Required | Description                                                                                                                                              |\n| ---------------- | --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `allowedEnvVars` | string\\[] | No       | Environment variable names that may be expanded inside `headers` values. When set, `url` must use `https://`.                                            |\n| `headers`        | object    | No       | Request headers to include.                                                                                                                              |\n| `timeout`        | number    | No       | Alias for `timeoutSec`, in seconds. Used only when `timeoutSec` is absent; `timeoutSec` takes precedence when both are present.                          |\n| `timeoutSec`     | number    | No       | Timeout in seconds. Default: `30`.                                                                                                                       |\n| `type`           | `\"http\"`  | Yes      | Must be `\"http\"`.                                                                                                                                        |\n| `url`            | string    | Yes      | Target URL. Must use `http:` or `https:`. For `preToolUse` and `permissionRequest`, must use `https://` because the response can grant tool permissions. |\n\n### Prompt hooks\n\nPrompt hooks auto-submit text as if the user typed it. They are only supported on `sessionStart`. The text can be a natural language prompt or a slash command.\n\n> \\[!NOTE]\n> **Copilot CLI only.** Prompt hooks fire only for **new interactive sessions**. They do not fire on resume, and they do not fire in non-interactive prompt mode (`-p`).\n\n> \\[!NOTE]\n> **Cloud agent.** Cloud agent jobs run non-interactively (similar to `-p`), so `prompt` hook entries may not fire. Confirm the behavior in your environment before relying on them.\n\n```json\n{\n  \"version\": 1,\n  \"hooks\": {\n    \"sessionStart\": [\n      {\n        \"type\": \"prompt\",\n        \"prompt\": \"YOUR_PROMPT_TEXT_OR_SLASH_COMMAND\"\n      }\n    ]\n  }\n}\n```\n\n| Field    | Type       | Required | Description                                                          |\n| -------- | ---------- | -------- | -------------------------------------------------------------------- |\n| `type`   | `\"prompt\"` | Yes      | Must be `\"prompt\"`.                                                  |\n| `prompt` | string     | Yes      | Text to submit—can be a natural language message or a slash command. |\n\n## Hook events\n\nThe table below lists every supported event. The **Cloud agent** column shows whether the event fires under cloud agent and notes any behavior differences.\n\n| Event                   | Fires when                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | Output processed                                                                                 | Cloud agent                                                                                                                                                   |\n| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `agentStop`             | The main agent finishes a turn.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Yes — can block and force continuation.                                                          | Fires. `decision: \"block\"` forces another turn, which still counts against the job's timeout.                                                                 |\n| `errorOccurred`         | An error occurs during execution.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | No                                                                                               | Fires.                                                                                                                                                        |\n| `notification`          | Fires asynchronously when the CLI emits a system notification (shell completion, agent completion or idle, permission prompts, elicitation dialogs). Fire-and-forget: never blocks the session. Supports a `matcher` regex pattern (the value of the `matcher` field) on `notification_type`.                                                                                                                                                                                                                                                                                                         | Optional — can inject `additionalContext` into the session.                                      | **Does not fire.** Cloud agent does not surface notifications to a user (see the **Interactivity** row in the Cloud agent execution environment table above). |\n| `permissionRequest`     | Fires before the permission service runs (rules engine, session approvals, auto-allow/auto-deny, and user prompting). If the merged hook output returns `behavior: \"allow\"` or `\"deny\"`, that decision short-circuits the normal permission flow—except for a sandbox-bypass request (`requestSandboxBypass: true`), where an `allow` does not pre-approve the escape and only `deny` propagates (see the [`permissionRequest` decision control](#permissionrequest-decision-control) sandbox-bypass exception). Supports a `matcher` regex pattern (the value of the `matcher` field) on `toolName`. | Yes — can allow or deny programmatically.                                                        | Tool calls are pre-approved, so this hook either does not fire or has no effect. Use `preToolUse` to make permission decisions instead.                       |\n| `postToolUse`           | After each tool completes successfully.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               | Yes — can modify the tool result or inject additional context for the model.                     | Fires.                                                                                                                                                        |\n| `postToolUseFailure`    | After a tool completes with a failure.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | Yes — can provide recovery guidance via `additionalContext` (exit code `2` for command hooks).   | Fires.                                                                                                                                                        |\n| `preCompact`            | Context compaction is about to begin (manual or automatic). Supports a `matcher` regex pattern (the value of the `matcher` field) to filter by trigger (`\"manual\"` or `\"auto\"`).                                                                                                                                                                                                                                                                                                                                                                                                                      | No — notification only.                                                                          | Fires only with `trigger: \"auto\"`. There is no user to request manual compaction.                                                                             |\n| `preToolUse`            | Before each tool executes.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | Yes — can allow, deny, or modify.                                                                | Fires. A decision of `\"ask\"` is treated as `\"deny\"` because no user is available to answer.                                                                   |\n| `sessionEnd`            | The session terminates.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               | No                                                                                               | Fires once per job. `reason` is typically `\"complete\"`, `\"error\"`, or `\"timeout\"`; `\"abort\"` and `\"user_exit\"` are not expected because there is no user.     |\n| `sessionStart`          | A new or resumed session begins.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Optional — can inject `additionalContext` into the session.                                      | Fires once per job, as a new session (not a resume). See the Prompt hooks note above for the behavior of `prompt` entries under cloud agent.                  |\n| `subagentStart`         | A subagent is spawned (before it runs). Supports a `matcher` regex pattern (the value of the `matcher` field) to filter by agent name.                                                                                                                                                                                                                                                                                                                                                                                                                                                                | Optional — cannot block creation, but `additionalContext` is prepended to the subagent's prompt. | Fires.                                                                                                                                                        |\n| `subagentStop`          | A subagent completes.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | Yes — can block and force continuation.                                                          | Fires.                                                                                                                                                        |\n| `userPromptSubmitted`   | The user submits a prompt.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | Optional—`modifiedPrompt` is honored only by SDK programmatic hooks.                             | Fires at most once, for the prompt supplied to the job. There is no follow-up user input.                                                                     |\n| `userPromptTransformed` | Fires after the runtime transforms a submitted prompt into its model-facing content, just before that content is emitted and persisted to session history. Runs for the primary message and for every preceding message in a batched submission. Mutation-only — it can rewrite the content the model receives, but not block or handle the turn. System notifications never trigger it.                                                                                                                                                                                                              | Yes — can rewrite the model-facing content.                                                      | Fires.                                                                                                                                                        |\n\n## Hook event input payloads\n\nEach hook event delivers a JSON payload to the hook handler. Two payload formats are supported, selected by the event name used in the hook configuration:\n\n* **camelCase format** — Configure the event name in camelCase (for example, `sessionStart`). Fields use camelCase.\n* **VS Code compatible format** — Configure the event name in PascalCase (for example, `SessionStart`). Fields use snake\\_case to match the VS Code Copilot extension format.\n\n### `sessionStart` / `SessionStart`\n\n**camelCase input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;      // Unix timestamp in milliseconds\n    cwd: string;\n    source: \"startup\" | \"resume\" | \"new\";\n    initialPrompt?: string;\n}\n```\n\n**VS Code compatible input:**\n\n```typescript\n{\n    hook_event_name: \"SessionStart\";\n    session_id: string;\n    timestamp: string;      // ISO 8601 timestamp\n    cwd: string;\n    source: \"startup\" | \"resume\" | \"new\";\n    initial_prompt?: string;\n}\n```\n\n### `sessionEnd` / `SessionEnd`\n\n**camelCase input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;\n    cwd: string;\n    reason: \"complete\" | \"error\" | \"abort\" | \"timeout\" | \"user_exit\";\n}\n```\n\n**VS Code compatible input:**\n\n```typescript\n{\n    hook_event_name: \"SessionEnd\";\n    session_id: string;\n    timestamp: string;      // ISO 8601 timestamp\n    cwd: string;\n    reason: \"complete\" | \"error\" | \"abort\" | \"timeout\" | \"user_exit\";\n}\n```\n\n### `userPromptSubmitted` / `UserPromptSubmit`\n\n**camelCase input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;\n    cwd: string;\n    prompt: string;\n}\n```\n\n**VS Code compatible input:**\n\n```typescript\n{\n    hook_event_name: \"UserPromptSubmit\";\n    session_id: string;\n    timestamp: string;      // ISO 8601 timestamp\n    cwd: string;\n    prompt: string;\n}\n```\n\n**Output:**\n\n```typescript\n{\n    modifiedPrompt?: string; // Replaces the prompt for the rest of the turn (SDK programmatic hooks only)\n}\n```\n\nReturn `{}` or empty to leave the prompt unchanged.\n\n> \\[!NOTE]\n>\n> * `modifiedPrompt` is only honored by SDK programmatic hooks. Command and HTTP config-file `userPromptSubmitted` hooks have their output dropped, including `modifiedPrompt`. The lighter hooks-processing runtime used by hosted or steering Copilot cloud agent sessions also ignores it. This is the same runtime split as `preToolUse`.\n> * A non-string `modifiedPrompt`, `modifiedTransformedPrompt`, or a handled `responseContent` value is ignored rather than corrupting the session—a type warning naming the field is logged and emitted as a `session.warning` event. An empty-string override is rejected instead of blanking the model-facing content. A `null` `additionalContext` value is treated as absent instead of being injected as the literal text `null`. Hook output (stdout for command hooks, the response body for HTTP hooks) is bounded at 10 MiB per invocation—a larger response is truncated rather than exhausting memory.\n\n### `userPromptTransformed`\n\nFires after the runtime transforms a submitted prompt into its model-facing content, just before that content is emitted and persisted to session history. Runs for the primary message and for every preceding message in a batched submission. Mutation-only—it can rewrite the content the model receives, but not block or handle the turn. System notifications never trigger it.\n\n**Input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;         // epoch-ms integer\n    cwd: string;\n    prompt: string;            // user prompt after userPromptSubmitted hooks have run\n    transformedPrompt: string; // runtime-transformed content the model will receive\n}\n```\n\n**Output:**\n\n```typescript\n{\n    modifiedTransformedPrompt?: string; // Replaces the model-facing content\n}\n```\n\nReturn `{}` or empty to leave the transformed content unchanged. `modifiedTransformedPrompt` replaces only the content sent to the model and stored in session history—the prompt displayed in the timeline is unaffected—and the replacement is replayed unchanged if the session is resumed.\n\n### `preToolUse` / `PreToolUse`\n\n**camelCase input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;\n    cwd: string;\n    toolName: string;\n    toolArgs: unknown;\n}\n```\n\n**VS Code compatible input:**\n\nWhen configured with the PascalCase event name `PreToolUse`, the payload uses snake\\_case field names to match the VS Code Copilot extension format:\n\n```typescript\n{\n    hook_event_name: \"PreToolUse\";\n    session_id: string;\n    timestamp: string;      // ISO 8601 timestamp\n    cwd: string;\n    tool_name: string;\n    tool_input: unknown;    // Tool arguments (parsed from JSON string when possible)\n}\n```\n\n**Claude-format matchers (PascalCase `PreToolUse`):** Hooks configured with the PascalCase event name `PreToolUse`—as used in Claude Code plugins and the Open Plugins format—apply Claude's matcher semantics instead of the native regex rule:\n\n* `*`, `**`, or an empty `matcher` value fires for every tool.\n* A literal name or `|`-separated alternation (for example, `Bash` or `Edit|Write`) fires when any token equals the runtime tool name or its Claude tool name from the table below.\n* Any other value is treated as a case-sensitive regex anchored as `^(?:PATTERN)$` tested against the Claude tool name (or the runtime name for tools with no Claude equivalent).\n\nPayloads for PascalCase `PreToolUse` report `tool_name` as the Claude tool name (for example, `Bash`, not `bash`).\n\n| Runtime tool                                | Claude tool name                              |\n| ------------------------------------------- | --------------------------------------------- |\n| `bash`, `powershell`                        | `Bash`                                        |\n| `view`                                      | `Read`                                        |\n| `create`                                    | `Write`                                       |\n| `edit`, `str_replace_editor`, `apply_patch` | `Edit`                                        |\n| `grep`, `rg`                                | `Grep`                                        |\n| `glob`                                      | `Glob`                                        |\n| `web_fetch`                                 | `WebFetch`                                    |\n| `web_search`                                | `WebSearch`                                   |\n| `ask_user`                                  | `AskUserQuestion`                             |\n| `update_todo`                               | `TodoWrite`                                   |\n| `task`                                      | `Agent` (the literal `Task` is also accepted) |\n\nTools with no Claude equivalent keep their runtime names.\n\n> \\[!IMPORTANT]\n> **Command vs HTTP fail behavior for `preToolUse`:** Command `preToolUse` hooks are **fail-closed** on errors—a crash or non-zero exit (including exit `2`) denies the tool call, even if the hook's stdout JSON reports `permissionDecision: \"allow\"`. Command hook **timeouts are always fail-open, even for `preToolUse` and admin-deployed policy hooks**—a timed-out hook surfaces a warning and lets the tool call proceed through the normal permission flow instead of denying it. HTTP `preToolUse` hooks are **fail-open**—a network error, timeout, or non-2xx response falls through to the default permission flow. Choose the variant that matches your security requirements.\n\n### `postToolUse` / `PostToolUse`\n\n**camelCase input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;\n    cwd: string;\n    toolName: string;\n    toolArgs: unknown;\n    toolResult: {\n        resultType: \"success\";\n        textResultForLlm: string;\n    }\n}\n```\n\n**VS Code compatible input:**\n\n```typescript\n{\n    hook_event_name: \"PostToolUse\";\n    session_id: string;\n    timestamp: string;      // ISO 8601 timestamp\n    cwd: string;\n    tool_name: string;\n    tool_input: unknown;\n    tool_result: {\n        result_type: \"success\";\n        text_result_for_llm: string;\n    }\n}\n```\n\n### `postToolUseFailure` / `PostToolUseFailure`\n\n**camelCase input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;\n    cwd: string;\n    toolName: string;\n    toolArgs: unknown;\n    error: string;\n}\n```\n\n**VS Code compatible input:**\n\n```typescript\n{\n    hook_event_name: \"PostToolUseFailure\";\n    session_id: string;\n    timestamp: string;      // ISO 8601 timestamp\n    cwd: string;\n    tool_name: string;\n    tool_input: unknown;\n    error: string;\n}\n```\n\n### `agentStop` / `Stop`\n\n**camelCase input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;\n    cwd: string;\n    transcriptPath: string;\n    stopReason: \"end_turn\";\n    stop_hook_active: boolean; // true when this turn was already forced to continue by a prior \"block\" decision from this hook\n}\n```\n\n**VS Code compatible input:**\n\n```typescript\n{\n    hook_event_name: \"Stop\";\n    session_id: string;\n    timestamp: string;      // ISO 8601 timestamp\n    cwd: string;\n    transcript_path: string;\n    stop_reason: \"end_turn\";\n    stop_hook_active: boolean;\n}\n```\n\n### `subagentStart`\n\n> \\[!NOTE]\n> The built-in `general-purpose` agent does not emit `subagentStart` or `subagentStop` events. All other built-in YAML-based agents—including `explore`, `task`, `code-review`, `rubber-duck`, `research`, and `security-review`—and user-defined custom agents emit these events.\n\n**Input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;\n    cwd: string;\n    transcriptPath: string;\n    agentName: string;\n    agentDisplayName?: string;\n    agentDescription?: string;\n}\n```\n\n### `subagentStop` / `SubagentStop`\n\nFires when a subagent completes normally, before returning results to the parent. `stopReason` is currently always `\"end_turn\"`. This hook fires before large-response spill handling, so `response` (or `last_assistant_message` in the VS Code compatible format) carries the full final subagent response text.\n\n**camelCase input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;\n    cwd: string;\n    transcriptPath: string;\n    agentId: string;\n    agentType: string;\n    agentName: string;\n    agentDisplayName?: string;\n    response: string;       // Full final subagent response text\n    stopReason: \"end_turn\";\n}\n```\n\n**VS Code compatible input:**\n\n```typescript\n{\n    hook_event_name: \"SubagentStop\";\n    session_id: string;\n    timestamp: string;      // ISO 8601 timestamp\n    cwd: string;\n    transcript_path: string;\n    agent_id: string;\n    agent_type: string;\n    agent_name: string;\n    agent_display_name?: string;\n    last_assistant_message: string; // The `response` text\n    stop_reason: \"end_turn\";\n}\n```\n\n### `errorOccurred` / `ErrorOccurred`\n\n**camelCase input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;\n    cwd: string;\n    error: {\n        message: string;\n        name: string;\n        stack?: string;\n    };\n    errorContext: \"model_call\" | \"tool_execution\" | \"system\" | \"user_input\";\n    recoverable: boolean;\n}\n```\n\n**VS Code compatible input:**\n\n```typescript\n{\n    hook_event_name: \"ErrorOccurred\";\n    session_id: string;\n    timestamp: string;      // ISO 8601 timestamp\n    cwd: string;\n    error: {\n        message: string;\n        name: string;\n        stack?: string;\n    };\n    error_context: \"model_call\" | \"tool_execution\" | \"system\" | \"user_input\";\n    recoverable: boolean;\n}\n```\n\n### `preCompact` / `PreCompact`\n\n**camelCase input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;\n    cwd: string;\n    transcriptPath: string;\n    trigger: \"manual\" | \"auto\";\n    customInstructions: string;\n}\n```\n\n**VS Code compatible input:**\n\n```typescript\n{\n    hook_event_name: \"PreCompact\";\n    session_id: string;\n    timestamp: string;      // ISO 8601 timestamp\n    cwd: string;\n    transcript_path: string;\n    trigger: \"manual\" | \"auto\";\n    custom_instructions: string;\n}\n```\n\n## `preToolUse` decision control\n\nThe `preToolUse` hook can control tool execution by writing a JSON object to stdout.\n\n| Field                      | Values                       | Description                                                                                                                                              |\n| -------------------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `permissionDecision`       | `\"allow\"`, `\"deny\"`, `\"ask\"` | Whether the tool executes. Empty output uses default behavior. Under cloud agent, `\"ask\"` is treated as `\"deny\"` because no user is available to answer. |\n| `permissionDecisionReason` | string                       | Reason shown to the agent. Required when decision is `\"deny\"`.                                                                                           |\n| `modifiedArgs`             | object                       | Substitute tool arguments to use instead of the originals.                                                                                               |\n\nWhen Copilot CLI can show the hook-permission prompt, the user can type optional feedback along with a denial. That feedback is appended to the message the agent receives: `Denied by user via preToolUse hook prompt: <permissionDecisionReason>. The user provided the following feedback: <feedback>`.\n\n## `agentStop` / `subagentStop` decision control\n\n| Field              | Values               | Description                                                                                                                                                                                         |\n| ------------------ | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `decision`         | `\"block\"`, `\"allow\"` | `\"block\"` forces another agent turn using `reason` as the prompt.                                                                                                                                   |\n| `reason`           | string               | Prompt for the next turn when `decision` is `\"block\"`.                                                                                                                                              |\n| `modifiedResponse` | string               | **`subagentStop` only.** Replaces the response returned to the parent when the subagent is allowed to complete—useful for redacting or reformatting subagent output. Not applicable to `agentStop`. |\n\n`decision` and `reason` behave the same for both `agentStop` and `subagentStop`. `modifiedResponse` applies only to `subagentStop`:\n\n* A valid `block` decision wins over `modifiedResponse`: if a hook returns both, the subagent continues and the rewrite is discarded.\n* Rewrites do not compose across multiple matching hooks. Every hook receives the same original `response`, and the last hook to return `modifiedResponse` wins—chaining a redactor and a formatter does not feed the redacted text into the formatter.\n* The output field names (`decision`, `reason`, `modifiedResponse`) are the same for both the camelCase and VS Code compatible configs.\n\n> \\[!NOTE]\n> **Runaway guard.** After 8 consecutive `block` continuations, the CLI overrides the hook and ends the turn anyway, to prevent an unbounded loop. Use the `stop_hook_active` input field on `agentStop` to detect that this turn was already forced to continue, and self-limit before hitting the cap.\n\n## `postToolUse` output\n\nThe `postToolUse` hook can modify the tool result or inject additional context for the model by writing a JSON object to stdout.\n\n```typescript\n{\n    modifiedResult?: {\n        resultType: \"success\";\n        textResultForLlm: string;\n    };\n    additionalContext?: string;\n}\n```\n\n| Field               | Type   | Description                                                                                                                                                                                                                       |\n| ------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `modifiedResult`    | object | Replacement tool result. Must have `resultType: \"success\"`. If returned with `resultType: \"failure\"`, the failure routes downstream and `postToolUseFailure` fires next.                                                          |\n| `additionalContext` | string | Additional guidance appended to `textResultForLlm` so the model sees it after the tool output on the same turn. When multiple hooks return `additionalContext`, the results are joined with a double newline and capped at 10 KB. |\n\nReturn `{}` or empty output to keep the original successful result.\n\n> \\[!NOTE]\n> `modifiedResult` is honored by both SDK programmatic hooks and command/HTTP config-file `postToolUse` hooks.\n\n**Matcher:** Optional regex tested against `toolName`. The regex pattern is the value of the `matcher` field, compiled as `^(?:PATTERN)$`, and must match the entire tool name. If the pattern is not a valid regular expression, the hook is skipped. Omit `matcher` to receive results from all tools.\n\n```json\n{\n    \"type\": \"command\",\n    \"matcher\": \"bash|edit\",\n    \"bash\": \"./scripts/log-tool.sh\"\n}\n```\n\n## `permissionRequest` decision control\n\n> \\[!NOTE]\n> **Copilot CLI only.** The `permissionRequest` hook does not apply under Copilot cloud agent—tool calls there are pre-approved (see the **Interactivity** row in the Cloud agent execution environment table). Use `preToolUse` to make permission decisions in cloud agent.\n\nThe `permissionRequest` hook fires before the permission service runs—before rule checks, session approvals, auto-allow/auto-deny, and user prompting. If hooks return `behavior: \"allow\"` or `\"deny\"`, that decision short-circuits the normal permission flow. Returning nothing falls through to normal permission handling. Use it to approve or deny tool calls programmatically—especially useful in CLI pipe mode (`-p`) and other CLI CI usages where no interactive prompt is available. It does not apply to cloud agent.\n\nAll configured `permissionRequest` hooks run for each request (except `read` and `hook` permission kinds, which short-circuit before hooks). Hook outputs are merged with later hook outputs overriding earlier ones.\n\n**Sandbox-bypass exception:** for any request that asks to escape the sandbox (`requestSandboxBypass: true` in `toolInput`), a hook `allow` does not pre-approve the request or short-circuit the user prompt—leaving the sandbox is a privilege escalation the user must always confirm interactively. This covers a shell command asking to run outside the sandbox and a `web_fetch` whose URL the sandbox network policy denies. Only `deny` still propagates (so a policy hook can block the escape); an `allow` (or no decision) falls through to the normal prompt.\n\n**Matcher:** Optional regex tested against `toolName`. The regex pattern is the value of the `matcher` field, anchored as `^(?:PATTERN)$`, and must match the full tool name. When set, the hook fires only for matching tool names.\n\n> \\[!NOTE]\n> **Claude-format matchers (PascalCase `PermissionRequest`):** Hooks configured with the PascalCase event name `PermissionRequest` use the same Claude matcher semantics as `PreToolUse`. See [Claude-format matchers (PascalCase PreToolUse)](#claude-format-matchers-pascalcase-pretooluse) for the matcher rules and tool name table.\n\nOutput JSON to stdout to control the permission decision:\n\n| Field       | Values              | Description                                                   |\n| ----------- | ------------------- | ------------------------------------------------------------- |\n| `behavior`  | `\"allow\"`, `\"deny\"` | Whether to approve or deny the tool call.                     |\n| `message`   | string              | Reason fed back to the LLM when denying.                      |\n| `interrupt` | boolean             | When `true` combined with `\"deny\"`, stops the agent entirely. |\n\nReturn empty output or `{}` to fall through to the normal permission flow. For command hooks, exit code `2` is treated as a deny; stdout JSON (if any) is merged with `{\"behavior\":\"deny\"}`, and stderr is ignored.\n\n## `notification` hook\n\n> \\[!NOTE]\n> **Copilot CLI only.** The `notification` hook does not fire under Copilot cloud agent.\n\nThe `notification` hook fires asynchronously when the CLI emits a system notification. These hooks are fire-and-forget: they never block the session, and any errors are logged and skipped.\n\n**Input:**\n\n```typescript\n{\n    sessionId: string;\n    timestamp: number;\n    cwd: string;\n    hook_event_name: \"Notification\";\n    message: string;           // Human-readable notification text\n    title?: string;            // Short title (e.g., \"Permission needed\", \"Shell completed\")\n    notification_type: string; // One of the types listed below\n}\n```\n\n**Notification types:**\n\n| Type                       | When it fires                                                                        |\n| -------------------------- | ------------------------------------------------------------------------------------ |\n| `shell_completed`          | A background (async) shell command finishes                                          |\n| `shell_detached_completed` | A detached shell session completes                                                   |\n| `agent_completed`          | A background subagent finishes (completed or failed)                                 |\n| `agent_idle`               | A background agent finishes a turn and enters idle state (waiting for `write_agent`) |\n| `permission_prompt`        | The agent requests permission to execute a tool                                      |\n| `elicitation_dialog`       | The agent requests additional information from the user                              |\n\n**Output:**\n\n```typescript\n{\n    additionalContext?: string; // Injected into the session as a user message\n}\n```\n\nIf `additionalContext` is returned, the text is injected into the session as a prepended user message. This can trigger further agent processing if the session is idle. Return `{}` or empty output to take no action.\n\n**Matcher:** Optional regex on `notification_type`. The regex pattern is the value of the `matcher` field, anchored as `^(?:PATTERN)$`. Omit `matcher` to receive all notification types.\n\n## Matcher filtering\n\nSeveral events accept an optional `matcher` regex on each hook entry that filters which invocations the hook fires for. It is compiled as `^(?:PATTERN)$` and must match the full value. Invalid regexes cause the hook entry to be skipped.\n\n| Event               | `matcher` is matched against       |\n| ------------------- | ---------------------------------- |\n| `notification`      | `notification_type`                |\n| `permissionRequest` | `toolName`                         |\n| `postToolUse`       | `toolName`                         |\n| `preCompact`        | `trigger` (`\"manual\"` or `\"auto\"`) |\n| `preToolUse`        | `toolName`                         |\n| `subagentStart`     | `agentName`                        |\n\n## Tool names for hook matching\n\n| Tool name    | Description                                                                                                             |\n| ------------ | ----------------------------------------------------------------------------------------------------------------------- |\n| `ask_user`   | Ask the user a clarifying question. Under cloud agent there is no user, so `ask_user` does not produce a useful result. |\n| `bash`       | Execute shell commands (Unix).                                                                                          |\n| `create`     | Create new files.                                                                                                       |\n| `edit`       | Modify file contents.                                                                                                   |\n| `glob`       | Find files by pattern.                                                                                                  |\n| `grep`       | Search file contents.                                                                                                   |\n| `powershell` | Execute shell commands (Windows). Does not appear under cloud agent (Linux sandbox).                                    |\n| `task`       | Run subagent tasks.                                                                                                     |\n| `view`       | Read file contents.                                                                                                     |\n| `web_fetch`  | Fetch web pages.                                                                                                        |\n\nIf multiple hooks of the same type are configured, they execute in order. For `preToolUse`, if any hook returns `\"deny\"`, the tool is blocked. For most events, hook failures (non-zero exit codes other than `2`, or timeouts) are logged and skipped. **Exception: `preToolUse` command hooks are fail-closed on exit `2` and on non-timeout errors**—exit `2`, a crash, or any other non-zero exit (other than a timeout) denies the tool call, even if the hook's stdout JSON reports `permissionDecision: \"allow\"`. **Timeouts are always fail-open, including for `preToolUse` and admin-deployed policy hooks**: a warning is surfaced and the tool call proceeds through the normal permission flow rather than being denied.\n\n## Exit codes for command hooks\n\n| Exit code      | Meaning                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |\n| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `0`            | Success. `stdout` is parsed as the hook output JSON if present.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |\n| `2`            | Treated as a warning by default. `stderr` is surfaced to the user but the run continues. For `permissionRequest` and `preToolUse`, exit `2` is treated as a deny: any `stdout` JSON is merged with the deny decision and the tool call is denied even if that JSON reports `permissionDecision: \"allow\"`. For `postToolUseFailure`, exit `2` is treated as `additionalContext` and `stdout` is appended to the failure shown to the agent.                                                                                                                                                                                                                                         |\n| Other non-zero | Logged as a hook failure. The run continues (fail-open). **Exception: `preToolUse` is fail-closed**—a non-zero exit (other than exit 2) denies the tool call with `\"Denied by preToolUse hook (hook errored)\"`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |\n| Timeout        | Killed after `timeoutSec`. Error logged, execution continues. **Timeouts are fail-open for every event, including `preToolUse` and admin-deployed policy hooks**—a warning is surfaced and processing proceeds as if the hook had not run. For `preToolUse`, the tool call proceeds through the normal permission flow rather than being denied. A crashed or explicitly-denying hook still fails-closed; only timeouts are exempt. The logged message includes the command that timed out, for example `Hook command timed out after 30 seconds: my-validation-script.sh` (the bash/PowerShell script text, or `program arg1 arg2 …` for exec hooks), truncated to 80 characters. |\n\nFor most events, non-zero exits and timeouts are logged and skipped—agent execution continues. For `preToolUse` command hooks, exit 2, crashes, and other non-zero exits all fail-closed and deny the tool call—exit 2 always denies, even if the hook's `stdout` JSON reports `permissionDecision: \"allow\"`—but **timeouts always fail-open**—a slow or unreachable hook must not silently block tool calls or work, even when the hook was deployed by an administrator as policy.\n\n## Disable all hooks\n\nUse `disableAllHooks` when you want to keep your hook configuration on disk but stop it from running—for example:\n\n* Debugging an issue and you want to confirm a hook is the cause without deleting your config.\n* Pausing automation during a sensitive task (a code review, a release branch, working with secrets) without losing the setup. (**Copilot CLI only.**)\n* Shipping a hooks file in source control that contributors can opt out of locally by setting the option in their repository `settings.json`. (**Copilot CLI only.**)\n* Temporarily silencing slow or noisy hooks during an interactive session. (**Copilot CLI only.**)\n\nSet `disableAllHooks` to `true` at the top level to skip every hook in the file without deleting it.\n\n```json\n{\n  \"version\": 1,\n  \"disableAllHooks\": false,\n  \"hooks\": {\n    \"preToolUse\": [ /* hook entries */ ]\n  }\n}\n```\n\nBehavior depends on where you set the flag:\n\n* **Inside a single `.github/hooks/*.json` file** — only the hooks declared in that file are skipped. Honored by both Copilot CLI and Copilot cloud agent.\n* **At the top level of repository `settings.json`** — **Copilot CLI only.** Every hook from every source (repository files, user files, plugins, and inline hook blocks) is skipped for sessions in that repository. Policy hooks are not affected and continue to run. Cloud agent does not load `settings.json`.\n\n## Further reading\n\n* [Using hooks with GitHub Copilot CLI](/en/enterprise-cloud@latest/copilot/how-tos/copilot-cli/customize-copilot/use-hooks)\n* [GitHub Copilot hooks reference](/en/enterprise-cloud@latest/copilot/reference/hooks-reference)\n* [GitHub Copilot CLI command reference](/en/enterprise-cloud@latest/copilot/reference/copilot-cli-reference/cli-command-reference)\n* [Concepts for GitHub Copilot cloud agent](/en/enterprise-cloud@latest/copilot/concepts/agents/cloud-agent)"}