---
schema_version: "1"
id: c9a8c1b055b3be96c3a22afdab4d5fe0e7d11e3c87795997c8c47c5125ee6fee
title: Hooks for Agentforce Vibes
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/salesforcedx/einsteinfordevs/guides/files/hooks.md
canonical_url: https://developer.salesforce.com/docs/platform/einstein-for-devs/guide/hooks.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: 7f0524f82f3b0fe4597ee3cf05026bd23fce08dfb1438e04f6314fb2da035ad4
products:
  - Agentforce Vibes Developer Guide (Deprecated)
  - salesforcedx
---
# Hooks for Agentforce Vibes

## Overview

Hooks let you inject custom logic into Agentforce Vibes workflows to validate operations and shape the agent's decisions. Hooks are scripts that run at key moments in the task lifecycle. Because they run at defined points with consistent inputs and outputs, hooks add determinism to AI models by enforcing guardrails, validations, and context injection. You can validate operations before they run, monitor tool usage, and influence how Agentforce Vibes makes decisions.

When using AI-powered features, you assume responsibility for reviewing outputs and ensuring they match your requirements. Hooks help you enforce policies programmatically, but always review hook logic before enabling it.

**note:** Hooks are currently unavailable on Windows.

## What You Can Build

- Stop operations before they cause problems, such as creating `.js` files in a TypeScript project.
- Run linters or custom validators before files get saved.
- Prevent operations that violate security policies.
- Track everything for analytics or compliance.
- Trigger external tools or services at the right moments.
- Add context to the conversation based on what the agent is doing.

## Hook Types

Agentforce Vibes supports eight hook types that run at different points in the task lifecycle:

| Hook Type          | When It Runs                                    |
| ------------------ | ----------------------------------------------- |
| `TaskStart`        | When you start a new task                       |
| `TaskResume`       | When you resume an interrupted task             |
| `TaskCancel`       | When you cancel a running task                  |
| `TaskComplete`     | When a task finishes successfully               |
| `PreToolUse`       | Before the agent runs a tool                    |
| `PostToolUse`      | After a tool execution completes                |
| `UserPromptSubmit` | When you submit a message to the agent          |
| `PreCompact`       | Before the agent truncates conversation history |

## Hook Lifecycle

The hook lifecycle follows the conversation flow:

1. When you start a task, either `TaskStart` (new task) or `TaskResume` (interrupted task) runs first.
2. Each time you make a request, `UserPromptSubmit` runs, then the agent processes your request.
3. When the agent decides to use a tool, `PreToolUse` runs first. If allowed, the tool executes, then `PostToolUse` runs.
4. If the conversation approaches context limits, `PreCompact` runs before truncation.
5. The task ends with either `TaskComplete` (success) or `TaskCancel` (user cancellation).

The cycle repeats as you continue the conversation.

## Hook Locations

Hooks are either global or in a project workspace, and are located in these directories:

- **Global hooks**: `~/Library/ApplicationSupport/Code/User/globalStorage/salesforce.salesforcedx-einstein-gpt/Hooks/`
- **Project hooks**: `.a4drules/hooks/` in your repo (can be committed to version control)

When both global and workspace hooks exist for the same hook type, both run. Global hooks execute first, then workspace hooks. If either returns `cancel: true`, the operation stops.

## Get Started

To create and enable your first hook:

1. Click the `⚖️`icon at the bottom of the Agentforce Vibes panel, to the left of the model selector.
2. Click the Hooks tab.
3. Click the "New hook…" dropdown and select a hook type (for example, `PreToolUse`, `TaskStart`).
4. Click the pencil icon to open and edit the hook script. Agentforce Vibes generates a template with examples to get you started.
5. Toggle the switch to activate the hook after you understand what it does.

**important:** Always review a hook's code before enabling it. Hooks execute automatically during your workflow and can block operations or run shell commands.

## How Hooks Work

Hooks are executable scripts that receive JSON input via stdin and return JSON output via stdout.

### Input Structure

Every hook receives a JSON object with common fields plus hook-specific data:

```json
{
  "taskId": "abc123",
  "hookName": "PreToolUse",
  "agentforceVersion": "3.17.0",
  "timestamp": "1736654400000",
  "workspaceRoots": ["/path/to/project"]
  "preToolUse": {
    "tool": "write_to_file",
    "parameters": {
      "path": "src/config.ts",
      "content": "..."
    }
  }
}
```

The hook-specific field name matches the hook type in camelCase:

- `taskStart`, `taskResume`, `taskCancel`, `taskComplete` – contain `{ task: string }`
- `preToolUse` – contains `{ tool: string, parameters: object }`
- `postToolUse` – contains `{ tool: string, parameters: object, result: string, success: boolean, durationMs: number }`
- `userPromptSubmit` – contains `{ prompt: string }`
- `preCompact` – contains `{ conversationLength: number, estimatedTokens: number }`

### Output Structure

Hooks return a JSON object to stdout:

```json
{
  "cancel": false,
  "contextModification": "Optional text to add to the conversation",
  "errorMessage": ""
}
```

| Field                 | Type    | Description                                                                  |
| --------------------- | ------- | ---------------------------------------------------------------------------- |
| `cancel`              | boolean | If true, stops the operation (blocks the tool, cancels the task start, etc.) |
| `contextModification` | string  | Optional text injected into the conversation as context for the agent        |
| `errorMessage`        | string  | Shown to the user if cancel is true                                          |

### Context Modification

The `contextModification` field lets hooks inject information into the conversation. Use it for:

- Adding project-specific context when a task starts.
- Providing validation results that the agent should consider.
- Injecting environment information before tool execution.

For example, a `PreToolUse` hook could add: "Note: This file is auto-generated. Edits may be overwritten."

## Implementation Examples

### TypeScript Enforcement

Block creation of `.js` files in a TypeScript project:

```bash
#!/bin/bash
# PreToolUse hook

INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.preToolUse.tool')
FILE_PATH=$(echo "$INPUT" | jq -r '.preToolUse.parameters.path // empty')

if [[ "$TOOL" == "write_to_file" && "$FILE_PATH" == *.js ]]; then
  echo '{"cancel":true,"errorMessage":"Use .ts files instead of .js in this TypeScript project"}'
  exit 0
fi

echo '{"cancel":false}'
```

### Tool Usage Logging

Log all tool executions to a file:

```bash
#!/bin/bash
# PostToolUse hook

INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.postToolUse.tool')
SUCCESS=$(echo "$INPUT" | jq -r '.postToolUse.success')
DURATION=$(echo "$INPUT" | jq -r '.postToolUse.durationMs')

echo "$(date -Iseconds) | $TOOL | success=$SUCCESS | ${DURATION}ms" >> ~/.agentforce-tool-log.txt

echo '{"cancel":false}'
```

### Add Project Context on Task Start

Inject project-specific information when a task begins:

```bash
#!/bin/bash
# TaskStart hook

INPUT=$(cat)
WORKSPACE=$(echo "$INPUT" | jq -r '.workspaceRoots[0] // empty')

# Read project info if available
if [[ -f "$WORKSPACE/.project-context" ]]; then
  CONTEXT=$(cat "$WORKSPACE/.project-context")
  echo "{\"cancel\":false,\"contextModification\":\"Project context: $CONTEXT\"}"
else
  echo '{"cancel":false}'
fi
```

## Troubleshooting

**Hook not running?**

- Check that the file is executable (`chmod +x hookname`).
- Ensure that the hook file uses extensionless `<HookName>` naming (for example, `PreToolUse`).
- Verify that the hook is enabled (toggle is on in the Hooks tab).
- Check that Hooks are enabled globally in Settings.

**Hook output not parsed?**

- Ensure that output is valid JSON on a single-line to stdout.
- Use stderr (`>&2`) for debug logging, not stdout.
- Check for trailing characters or newlines before the JSON.

**Hook blocking unexpectedly?**

- Review the hook's logic and test with sample input.
- Check both global and workspace hooks (both run if they exist).

## Considerations and Limitations

- Hooks execute automatically during your workflow. Review the hook code before enabling to avoid unintended blocking or side effects.
- `PostToolUse` hooks can return `cancel: true` to stop the task, but they can’t undo the tool execution that already happened.
- When both global and workspace hooks exist, both run. If either returns `cancel: true`, the operation stops.
- Hooks run with the permissions of the user running Agentforce Vibes. Ensure that hooks don’t expose sensitive data or execute untrusted commands.

## See Also

- [Rules](https://developer.salesforce.com/docs/platform/einstein-for-devs/guide/devagent-rules.md)
- [Checkpoints](https://developer.salesforce.com/docs/platform/einstein-for-devs/guide/checkpoints.md)
- [Abilities](https://developer.salesforce.com/docs/platform/einstein-for-devs/guide/abilities.md)
