# 会话挂钩

钩子允许你在对话生命周期的关键节点拦截并自定义 Copilot 会话的行为。 使用挂钩可以：

<!-- markdownlint-disable GHD046 GHD005 -->

<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->

* **控制工具执行** - 批准、拒绝或修改工具调用
* **转换结果** - 在处理结果之前修改工具输出
* **添加上下文** - 在会话开始时注入其他信息
* **处理错误** - 实现自定义错误处理
* **审核和记录** - 跟踪符合性的所有交互

## 可用挂钩

| 挂钩                                                                                | Trigger      | 用例            |
| --------------------------------------------------------------------------------- | ------------ | ------------- |
| [工具使用前挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/pre-tool-use)                     | 在工具执行之前      | 权限控制，参数验证     |
| [工具使用后挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/post-tool-use)                    | 工具执行后（仅在成功时） | 结果转换，日志记录     |
| [工具使用后挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/post-tool-use#failure-variant)    | 在工具执行结果为失败之后 | 添加重试指引，记录失败日志 |
| [用户提示提交挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/user-prompt-submitted)           | 当用户发送消息时     | 提示修改、筛选       |
| [会话生命周期挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/session-lifecycle#session-start) | 会话开始         | 添加上下文，配置会话    |
| [会话生命周期挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/session-lifecycle#session-end)   | 会话结束         | 清理、分析         |
| [错误处理挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/error-handling)                    | 发生错误         | 自定义错误处理       |

## 快速入门

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();

const session = await client.createSession({
  hooks: {
    onPreToolUse: async (input) => {
      console.log(`Tool called: ${input.toolName}`);
      // Allow all tools
      return { permissionDecision: "allow" };
    },
    onPostToolUse: async (input) => {
      console.log(`Tool result: ${JSON.stringify(input.toolResult)}`);
      return null; // No modifications
    },
    onSessionStart: async (input) => {
      return { additionalContext: "User prefers concise answers." };
    },
  },
});
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```python
from copilot import CopilotClient
from copilot.session import PermissionHandler

async def main():
    client = CopilotClient()
    await client.start()

    async def on_pre_tool_use(input_data, invocation):
        print(f"Tool called: {input_data['toolName']}")
        return {"permissionDecision": "allow"}

    async def on_post_tool_use(input_data, invocation):
        print(f"Tool result: {input_data['toolResult']}")
        return None

    async def on_session_start(input_data, invocation):
        return {"additionalContext": "User prefers concise answers."}

    session = await client.create_session(on_permission_request=PermissionHandler.approve_all, hooks={
            "on_pre_tool_use": on_pre_tool_use,
            "on_post_tool_use": on_post_tool_use,
            "on_session_start": on_session_start,
        })
```

</div>

<div class="ghd-codetab" data-lang="go" data-label="Go"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Go</div>

```golang
package main

import (
    "context"
    "fmt"
    copilot "github.com/github/copilot-sdk/go"
)

func main() {
    client := copilot.NewClient(nil)

    session, _ := client.CreateSession(context.Background(), &copilot.SessionConfig{
        Hooks: &copilot.SessionHooks{
            OnPreToolUse: func(input copilot.PreToolUseHookInput, inv copilot.HookInvocation) (*copilot.PreToolUseHookOutput, error) {
                fmt.Printf("Tool called: %s\n", input.ToolName)
                return &copilot.PreToolUseHookOutput{
                    PermissionDecision: "allow",
                }, nil
            },
            OnPostToolUse: func(input copilot.PostToolUseHookInput, inv copilot.HookInvocation) (*copilot.PostToolUseHookOutput, error) {
                fmt.Printf("Tool result: %v\n", input.ToolResult)
                return nil, nil
            },
            OnSessionStart: func(input copilot.SessionStartHookInput, inv copilot.HookInvocation) (*copilot.SessionStartHookOutput, error) {
                return &copilot.SessionStartHookOutput{
                    AdditionalContext: "User prefers concise answers.",
                }, nil
            },
        },
    })
    _ = session
}
```

</div>

<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```csharp
using GitHub.Copilot;

var client = new CopilotClient();

var session = await client.CreateSessionAsync(new SessionConfig
{
    Hooks = new SessionHooks
    {
        OnPreToolUse = (input, invocation) =>
        {
            Console.WriteLine($"Tool called: {input.ToolName}");
            return Task.FromResult<PreToolUseHookOutput?>(
                new PreToolUseHookOutput { PermissionDecision = "allow" }
            );
        },
        OnPostToolUse = (input, invocation) =>
        {
            Console.WriteLine($"Tool result: {input.ToolResult}");
            return Task.FromResult<PostToolUseHookOutput?>(null);
        },
        OnSessionStart = (input, invocation) =>
        {
            return Task.FromResult<SessionStartHookOutput?>(
                new SessionStartHookOutput { AdditionalContext = "User prefers concise answers." }
            );
        },
    },
});
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

```java
import com.github.copilot.*;
import com.github.copilot.rpc.*;
import java.util.concurrent.CompletableFuture;

try (var client = new CopilotClient()) {
    client.start().get();

    var hooks = new SessionHooks()
        .setOnPreToolUse((input, invocation) -> {
            System.out.println("Tool called: " + input.getToolName());
            return CompletableFuture.completedFuture(PreToolUseHookOutput.allow());
        })
        .setOnPostToolUse((input, invocation) -> {
            System.out.println("Tool result: " + input.getToolResult());
            return CompletableFuture.completedFuture(null);
        })
        .setOnSessionStart((input, invocation) -> {
            return CompletableFuture.completedFuture(
                new SessionStartHookOutput("User prefers concise answers.", null)
            );
        });

    var session = client.createSession(
        new SessionConfig()
            .setHooks(hooks)
            .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
    ).get();
}
```

</div>

</div>

## 挂钩调用上下文

每个挂钩接收一个 `invocation` 参数，其中包含有关当前会话的上下文：

| 领域          | 类型  | 说明       |
| ----------- | --- | -------- |
| `sessionId` | 字符串 | 当前会话的 ID |

这允许钩子维护状态或执行会话特定的逻辑。

## 常见模式

### 记录所有工具调用

```typescript
const session = await client.createSession({
  hooks: {
    onPreToolUse: async (input) => {
      console.log(`[${new Date().toISOString()}] Tool: ${input.toolName}, Args: ${JSON.stringify(input.toolArgs)}`);
      return { permissionDecision: "allow" };
    },
    onPostToolUse: async (input) => {
      console.log(`[${new Date().toISOString()}] Result: ${JSON.stringify(input.toolResult)}`);
      return null;
    },
  },
});
```

### 阻止危险工具

```typescript
const BLOCKED_TOOLS = ["shell", "bash", "exec"];

const session = await client.createSession({
  hooks: {
    onPreToolUse: async (input) => {
      if (BLOCKED_TOOLS.includes(input.toolName)) {
        return {
          permissionDecision: "deny",
          permissionDecisionReason: "Shell access is not permitted",
        };
      }
      return { permissionDecision: "allow" };
    },
  },
});
```

### 添加用户上下文

```typescript
const session = await client.createSession({
  hooks: {
    onSessionStart: async () => {
      const userPrefs = await loadUserPreferences();
      return {
        additionalContext: `User preferences: ${JSON.stringify(userPrefs)}`,
      };
    },
  },
});
```

## 挂钩指南

* **[工具使用前挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/pre-tool-use)** - 控制工具执行权限
* **[工具使用后挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/post-tool-use)** - 转换工具结果
* **[用户提示提交挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/user-prompt-submitted)** - 修改用户提示
* **[会话生命周期挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/session-lifecycle)** - 会话开始和结束
* **[错误处理挂钩](/zh/copilot/how-tos/copilot-sdk/hooks/error-handling)** - 自定义错误处理

## 另见

* [构建你的第一个由 Copilot 提供支持的应用](/zh/copilot/how-tos/copilot-sdk/getting-started)
* [构建你的第一个由 Copilot 提供支持的应用](/zh/copilot/how-tos/copilot-sdk/getting-started#step-4-add-a-custom-tool)
* [调试指南](/zh/copilot/how-tos/copilot-sdk/troubleshooting/debugging)