Thanks to visit codestin.com
Credit goes to docs.github.com

Skip to main content

挂钩快速入门

在Copilot SDK中开始使用挂钩来控制工具执行、转换结果、添加上下文、处理错误以及监控和审核交互。

谁可以使用此功能?

GitHub Copilot SDK 适用于所有 Copilot 计划。

注意

          Copilot SDK 当前处于 公共预览版. 功能和可用性可能会发生更改。

挂钩允许您在会话生命周期的关键点截获和自定义 Copilot SDK 会话的行为。 使用挂钩可以:

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

可用挂钩

挂钩Trigger用例
onPreToolUse在工具执行之前权限控制,参数验证
onPostToolUse工具执行完毕后结果转换,日志记录
onUserPromptSubmitted当用户发送消息时提示修改、筛选
onSessionStart会话开始添加上下文,配置会话
onSessionEnd会话结束清理、分析
onErrorOccurred发生错误自定义错误处理

快速入门

以下示例演示如何在 Node.js/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.",
      };
    },
  },
});

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

挂钩调用上下文

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

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

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

常见模式

记录所有工具调用

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

后续步骤