> ## Documentation Index
> Fetch the complete documentation index at: https://docs.enconvo.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 掛鉤

> 當代理程式啟動、使用工具或完成時，自動執行 shell 指令或傳送 webhook。

掛鉤會在 Enconvo 中發生某些事情時執行 shell 指令或傳送 HTTP 請求，例如代理程式啟動、完成、失敗或使用工具。你在 JSON 檔案中設定它們，因此不必開發擴充功能，就能加入通知、記錄、本機自動化或整合。

> [!NOTE]
>
> 大多數掛鉤都是觸發後不管：它們在背景執行，不會阻擋 Enconvo。在代理程式執行期間，`PreToolUse`、`Stop` 和 `SubagentStop` 是例外。代理程式會等待它們，因此它們可以封鎖工具呼叫，或讓代理程式回頭繼續工作。請參閱[封鎖型掛鉤](#封鎖型掛鉤)。

## 快速開始

**1. 建立掛鉤資料夾**

```bash theme={null}
mkdir -p ~/.enconvo
```

**2. 建立 \~/.enconvo/hooks.json**

```json theme={null}
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "echo 'Agent status changed' >> /tmp/enconvo-hooks.log"
          }
        ]
      }
    ]
  }
}
```

**3. 觸發代理程式**

啟動任何代理程式或聊天指令。當它的狀態改變時，Enconvo 會執行
設定的指令，並在 `/tmp/enconvo-hooks.log` 中附加一行。

## 設定檔

掛鉤存放在：

```text theme={null}
~/.enconvo/hooks.json
```

當新檔案不存在時，Enconvo 也會讀取位於 `~/.config/enconvo/hooks.json` 的舊檔案。如果兩個檔案都存在，則以 `~/.enconvo/hooks.json` 為準。

每次事件觸發時都會重新讀取該檔案，因此你可以在 Enconvo 執行時編輯掛鉤，不需要重新啟動。

## 在設定中管理掛鉤

開啟 **設定 → 掛鉤**，即可看到 `~/.enconvo/hooks.json` 中依事件分組的掛鉤。用開關開啟或關閉某個項目，或點一下 **開啟 hooks.json** 來編輯檔案。關閉或開啟項目時，會在該項目上寫入 `enabled: false` 或 `enabled: true`，而不會更動它的指令或 webhook。

## 來自外掛程式的掛鉤

Claude Code 和 Codex 外掛程式，例如 context-mode，可以帶有它們自己的掛鉤。在你允許之後，它們的運作方式與在 Claude Code 中相同：在聊天開始時、每則訊息、工具呼叫和壓縮前後，以及回覆失敗或代理程式完成時執行。

1. 從 **外掛程式** 安裝該外掛程式，或在聊天中給代理程式該外掛程式的 GitHub 儲存庫、Git 位址、zip 或 npm 套件。它會提供該外掛程式的安裝卡片。
2. 安裝前先勾選 **允許執行它的掛鉤**。未勾選就安裝的外掛程式會顯示它的掛鉤已關閉；之後可以在它上面點一下 **允許掛鉤** 來開啟。

如果外掛程式更新時更動了它的掛鉤，這些掛鉤會停止執行，直到你檢查並再次允許為止。Enconvo 無法執行的掛鉤，會在卡片上列為未在 Enconvo 中執行。

## 掛鉤如何運作

當事件觸發時，Enconvo 會：

1. 載入 `~/.enconvo/hooks.json`。
2. 只有在新檔案不存在時，才改用 `~/.config/enconvo/hooks.json`。
3. 在最上層的 `hooks` 物件中，找出鍵與事件名稱相符的項目。
4. 套用選用的 `matcher` 正規表示式。
5. 略過 `enabled` 為 `false` 的項目。
6. 同時執行所有已設定的掛鉤。

掛鉤事件名稱遵循 Claude Code 和 Codex 的生命週期集合：`SessionStart`、`UserPromptSubmit`、`PreToolUse`、`PermissionRequest`、`PostToolUse`、`Stop` 和 `SubagentStop`。舊的 Enconvo 事件名稱和舊的扁平 JSON 結構在既有安裝上仍然有效，但新寫入的內容會使用包裝過的 Codex 風格格式。

## 設定參考

```json theme={null}
{
  "hooks": {
    "event_name": [
      {
        "matcher": "optional_regex_filter",
        "enabled": true,
        "hooks": [
          { "type": "command", "command": "..." },
          { "type": "http", "url": "..." }
        ]
      }
    ]
  }
}
```

| 欄位 | 類型 | 必填 | 說明 |
| - | - | - | - |
| `hooks` | object | 是 | 以事件名稱為鍵的事件對應表。 |
| `event_name` | string | 是 | 要監聽的事件。在 `hooks` 內把它當作鍵使用。 |
| `matcher` | string | 否 | 正規表示式篩選器。對工具事件，它比對 `toolName`、`toolTitle` 或 `path`；對其他事件，它比對掛鉤事件名稱。 |
| `enabled` | boolean | 否 | 設為 `false` 可在設定中保留該項目但略過執行。預設為 `true`。 |
| `hooks` | array | 是 | 要執行的指令和 HTTP 掛鉤。 |

### 指令掛鉤

指令掛鉤會執行 shell 指令。Enconvo 會把事件酬載以 JSON 寫入指令的 stdin。

```json theme={null}
{
  "type": "command",
  "command": "bash ~/.enconvo/hooks/on-status-change.sh",
  "timeout": 30000
}
```

| 欄位 | 類型 | 預設 | 說明 |
| - | - | - | - |
| `type` | `"command"` | - | 必填的掛鉤類型。 |
| `command` | string | - | 要執行的 shell 指令。 |
| `timeout` | number | `30000` | 逾時時間，單位為毫秒。 |

### HTTP 掛鉤

HTTP 掛鉤會把事件酬載作為 JSON 請求本文傳送。

```json theme={null}
{
  "type": "http",
  "url": "https://example.com/webhook",
  "method": "POST",
  "headers": {
    "Authorization": "Bearer your-token"
  },
  "timeout": 30000
}
```

| 欄位 | 類型 | 預設 | 說明 |
| - | - | - | - |
| `type` | `"http"` | - | 必填的掛鉤類型。 |
| `url` | string | - | HTTP 端點 URL。 |
| `method` | string | `"POST"` | HTTP 方法。 |
| `headers` | object | `{}` | 額外的請求標頭。 |
| `timeout` | number | `30000` | 逾時時間，單位為毫秒。 |

## 封鎖型掛鉤

在代理程式或機器人執行期間，有三個事件會以封鎖型掛鉤執行。代理程式會等待每個相符的掛鉤（它們平行執行）完成才繼續，並以與 Claude Code 和 Codex 相同的方式讀取它們的結果。

| 事件 | 時機 | 掛鉤可以做什麼 |
| - | - | - |
| `PreToolUse` | 工具呼叫執行之前。`matcher` 會與工具名稱、標題和路由路徑比對。 | 封鎖該呼叫，或改寫它的輸入。 |
| `Stop` | 代理程式以答案結束它的回合之前。 | 以一道指示讓代理程式回頭繼續工作。 |
| `SubagentStop` | 子代理完成之前。 | 以一道指示讓子代理回頭繼續工作。 |

掛鉤用兩種方式之一做出決定：

* **結束碼 2** 會封鎖。指令寫到 stderr 的文字就是原因。
* **結束碼 0，且 stdout 上有 JSON。** 任何其他輸出、結束碼、錯誤或逾時都不會做出任何決定，執行會繼續，就像沒有這個掛鉤一樣。

```json theme={null}
{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Writing outside the project is not allowed."
  }
}
```

| JSON 輸出 | 效果 |
| - | - |
| `hookSpecificOutput.permissionDecision: "deny"` | `PreToolUse`：該呼叫不會執行。模型會把 `permissionDecisionReason` 當作工具結果看到，並可以選擇其他做法。 |
| `hookSpecificOutput.permissionDecision: "ask"` | 視同 `deny`。Enconvo 目前還沒有針對掛鉤的確認提示。 |
| `hookSpecificOutput.permissionDecision: "allow"` | `PreToolUse`：該呼叫會執行。 |
| `hookSpecificOutput.updatedInput` | `PreToolUse`：該呼叫會以這個輸入而非模型的輸入執行。 |
| `{ "decision": "block", "reason": "..." }` | `Stop` / `SubagentStop`：代理程式繼續工作，並以 `reason` 作為它的下一道指示。在 `PreToolUse` 上，它會封鎖該呼叫。 |
| `{ "decision": "approve" }` | 與 `allow` 相同。 |

HTTP 掛鉤以 2xx 回應做出決定，其本文就是相同的 JSON。

當多個掛鉤相符時，deny 優先於 ask，ask 又優先於 allow。各個原因會被合併，並使用最後一個 `updatedInput`。

一個 `Stop` 掛鉤在一個回合中最多可以讓代理程式回頭 5 次。在第二次及之後的檢查中，`stop_hook_active` 為 `true`，因此掛鉤可以在指示被遵循後讓代理程式停止。`Stop` 封鎖只在代理程式正常完成時適用；失敗或被停止的執行仍會在背景觸發 `Stop`。

> [!TIP]
>
> 代理程式會等待封鎖型掛鉤，因此緩慢的 `PreToolUse` 掛鉤會拖慢每個工具呼叫，緩慢的 `Stop` 掛鉤則會延後回合的結束。請讓它們保持快速、設定較短的 `timeout`，或把耗時的工作放到背景執行（`command &`）。

封鎖型掛鉤會收到一般的[事件酬載](#事件酬載)，並在最上層加上 Claude Code 的欄位：

```json theme={null}
{
  "hook_event_name": "PreToolUse",
  "session_id": "Qx2...",
  "cwd": "/Users/you/project",
  "tool_name": "bash",
  "tool_input": { "command": "rm -rf build" },
  "tool_use_id": "call_1",
  "event": "PreToolUse",
  "sourceEvent": "agent_tool_step_changed",
  "params": { "toolName": "bash", "status": "running", "sessionId": "Qx2..." },
  "timestamp": 1742313600000
}
```

`Stop` 和 `SubagentStop` 收到的是 `stop_hook_active` 和 `last_assistant_message`，而不是工具欄位。指令掛鉤在代理程式的工作目錄中執行。

### 封鎖危險指令

```bash theme={null}
#!/bin/bash
# ~/.enconvo/hooks/guard.sh
COMMAND=$(jq -r '.tool_input.command // empty')
if echo "$COMMAND" | grep -q 'rm -rf /'; then
  echo "Deleting from the filesystem root is not allowed." >&2
  exit 2
fi
```

```json theme={null}
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "bash",
        "hooks": [{ "type": "command", "command": "bash ~/.enconvo/hooks/guard.sh", "timeout": 5000 }]
      }
    ]
  }
}
```

### 讓代理程式在完成前先執行測試

```bash theme={null}
#!/bin/bash
# ~/.enconvo/hooks/require-tests.sh
[ "$(jq -r '.stop_hook_active')" = "true" ] && exit 0
echo '{"decision":"block","reason":"Run the test suite and fix any failures before you finish."}'
```

## 事件酬載

指令掛鉤會在 stdin 收到這份 JSON。HTTP 掛鉤則收到相同的 JSON 作為請求本文。

```json theme={null}
{
  "event": "UserPromptSubmit",
  "fullEvent": "event-UserPromptSubmit",
  "sourceEvent": "run_status_changed",
  "sourceFullEvent": "event-run_status_changed",
  "params": {
    "commandKey": "agent|main",
    "runStatus": "running"
  },
  "timestamp": 1742313600000
}
```

| 欄位 | 說明 |
| - | - |
| `event` | 簡短的事件名稱。 |
| `fullEvent` | 帶有 `event-` 前綴的內部事件名稱。 |
| `sourceEvent` | 產生此掛鉤事件的原始 Enconvo 事件，在該事件為了與 Codex 相容而被對應時提供。 |
| `sourceFullEvent` | 帶有 `event-` 前綴的原始內部事件名稱。 |
| `params` | 各事件專屬的酬載。 |
| `timestamp` | 以毫秒為單位的 Unix 時間戳記。 |

背景掛鉤也會收到 Claude Code 的欄位：`hook_event_name`、事件有 `session_id` 時的 `session_id`，以及對工具事件而言的 `tool_name`、`tool_input` 和 `tool_use_id`。

## 可用的事件

| 事件 | 參數 | 時機 |
| - | - | - |
| `SessionStart` | `{ command, commandKey }` | 建立新的聊天工作階段時。 |
| `UserPromptSubmit` | `{ commandKey, runStatus, status?, sessionId? }` | 代理程式、聊天或機器人的執行由使用者輸入啟動時。 |
| `PreToolUse` | `{ toolCallId, toolName, toolTitle?, status, sessionId?, commandKey? }` | 工具呼叫開始時。在代理程式執行期間為封鎖型。 |
| `PermissionRequest` | `{ toolCallId, toolName, toolTitle?, status, sessionId?, commandKey? }` | 工具呼叫進入權限或被拒絕的狀態時。 |
| `PostToolUse` | `{ toolCallId, toolName, toolTitle?, status, sessionId?, commandKey? }` | 工具呼叫成功、失敗、完成或被拒絕時。 |
| `Stop` | `{ commandKey, runStatus, status?, sessionId? }` | 代理程式、聊天或機器人的執行到達最終狀態時。在代理程式正常完成時為封鎖型。 |
| `SubagentStop` | `{ commandKey, runStatus, status?, sessionId? }` | 子代理即將完成時。封鎖型。子代理不會觸發 `Stop`。 |

`run_status_changed` 和 `agent_tool_step_changed` 等舊版 Enconvo 名稱仍然有效，因此既有的掛鉤檔案不需要立刻遷移。

## 範例

### 代理程式失敗時顯示 macOS 通知

```json theme={null}
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "STATUS=$(cat | jq -r '.params.runStatus // .params.status') && [ \"$STATUS\" = \"failed\" ] && osascript -e 'display notification \"An agent failed\" with title \"EnConvo\"'"
          }
        ]
      }
    ]
  }
}
```

### 記錄代理程式的狀態變更

```json theme={null}
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "jq -c '{time: (.timestamp / 1000 | strftime(\"%Y-%m-%d %H:%M:%S\")), agent: .params.commandKey, status: (.params.runStatus // .params.status)}' >> ~/.enconvo/agent-status.log"
          }
        ]
      }
    ]
  }
}
```

### 記錄代理程式的工具呼叫

```json theme={null}
{
  "hooks": {
    "PostToolUse": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.params | \"\\(.status) \\(.toolName) \\(.toolCallId)\"' >> ~/.enconvo/agent-tools.log"
          }
        ]
      }
    ]
  }
}
```

### 傳送到 Slack

```json theme={null}
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "http",
            "url": "https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
          }
        ]
      }
    ]
  }
}
```

### 自訂指令碼

建立一個從 stdin 讀取事件酬載的指令碼：

```bash theme={null}
#!/bin/bash
# ~/.enconvo/hooks/on-status-change.sh
INPUT=$(cat)
STATUS=$(echo "$INPUT" | jq -r '.params.runStatus // .params.status')
AGENT=$(echo "$INPUT" | jq -r '.params.commandKey')

echo "[$(date)] $AGENT -> $STATUS" >> /tmp/enconvo-hooks.log

if [ "$STATUS" = "failed" ]; then
  osascript -e "display notification \"$AGENT failed\" with title \"EnConvo\""
fi
```

在 `~/.enconvo/hooks.json` 中引用它：

```json theme={null}
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "bash ~/.enconvo/hooks/on-status-change.sh"
          }
        ]
      }
    ]
  }
}
```

讓指令碼可以執行：

```bash theme={null}
chmod +x ~/.enconvo/hooks/on-status-change.sh
```

## 疑難排解

| 問題 | 解決方法 |
| - | - |
| 掛鉤沒有執行 | 檢查 `~/.enconvo/hooks.json` 是否為有效的 JSON、最上層的鍵是否與事件名稱相符，以及你自己執行該指令時是否可行。如果你仍有 `~/.config/enconvo/hooks.json`，在新檔案存在期間它會被忽略。 |
| 不確定掛鉤是否會阻擋 Enconvo | 只有 `PreToolUse`、`Stop` 和 `SubagentStop` 會在代理程式執行期間封鎖。其他所有掛鉤都是觸發後不管。如果任何掛鉤失敗或逾時，Enconvo 會記錄該失敗，並繼續執行，就像沒有這個掛鉤一樣。 |
| 外掛程式的掛鉤沒有執行 | 開啟該外掛程式，點一下 **允許掛鉤**。在更新更動了它們之後，請檢查並再次允許。 |
| 指令找不到指令碼或執行檔 | 請使用絕對路徑。當指令透過 shell 執行時，shell 的 `~` 展開可以運作，但絕對路徑更容易除錯。 |

### 手動測試指令碼

把範例酬載用管線傳給指令碼：

```bash theme={null}
echo '{"event":"Stop","params":{"commandKey":"agent|main","runStatus":"failed"},"timestamp":1742313600000}' | bash ~/.enconvo/hooks/on-status-change.sh
```

## 相關內容

> [card] [代理程式](https://docs.enconvo.ai/zh-hant/ai/agents.md)
>
> 了解 Enconvo 代理程式和自訂機器人

> [card] [擴充功能 API 參考](https://docs.enconvo.ai/extensions/extension-api-reference.md)
>
> 開發會發出或監聽事件的擴充功能


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.