跳至主要内容

Hooks 快速入门

开始使用 Copilot SDK 中的 hooks,以控制工具执行、转换结果、添加上下文、处理错误并审计交互。

谁可以使用此功能?

GitHub Copilot SDK 在所有 Copilot 计划中均可使用。

注意

Copilot SDK 目前处于公开预览阶段。功能和可用性可能会更改。

Hooks 允许您在对话生命周期的关键节点拦截并自定义 Copilot SDK 会话的行为。使用 hooks 可

  • 控制工具执行—批准、拒绝或修改工具调用
  • 转换结果—在处理之前修改工具输出
  • 添加上下文—在会话开始时注入额外信息
  • 处理错误—实现自定义错误处理
  • 审计和日志记录—跟踪所有交互以满足合规要求

可用的 hooks

钩子触发条件使用场景
onPreToolUse工具执行前权限控制、参数验证
onPostToolUse工具执行后结果转换、日志记录
onUserPromptSubmitted用户发送消息时提示修改、过滤
onSessionStart会话开始添加上下文、配置会话
onSessionEnd会话结束清理、分析
onErrorOccurred错误发生时自定义错误处理

快速入门

以下示例演示了在 Node.js/TypeScript 中创建会话时如何注册 hooks。

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.",
      };
    },
  },
});

有关 Python、Go 和 .NET 的示例,请参阅 github/copilot-sdk 仓库。Java 示例请参阅 github/copilot-sdk-java 仓库

Hook 调用上下文

每个 hook 都会接收一个包含当前会话上下文的 invocation 参数。

字段类型描述
sessionIdstring当前会话的 ID

这使得 hook 能够维护状态或执行特定于会话的逻辑。

常见模式

记录所有工具调用

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;
    },
  },
});

阻止危险工具

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" };
    },
  },
});

添加用户上下文

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

后续步骤

© . This site is unofficial and not affiliated with GitHub, Inc.