Skip to main content

セッション フック

フックを使用すると、会話ライフサイクルの重要なポイントでCopilotセッションの動作をインターセプトしてカスタマイズできます。 フックを使用して以下を行います。

  • ツールの実行を制御 する - ツール呼び出しの承認、拒否、または変更
  • 変換結果 - 処理前にツールの出力を変更する
  • コンテキストの追加 - セッション開始時に追加情報を挿入する
  • エラーの処理 - カスタム エラー処理を実装する
  • 監査とログ - コンプライアンスのすべての対話を追跡する

使用可能なフック

フックTriggerユースケース(事例)
ツール使用前のフックツールの実行前アクセス許可の制御、引数の検証
ツール使用後フックツールの実行後 (成功のみ)結果変換、ログ記録
ツール使用後フック結果が失敗したツールの実行後再試行のガイダンスを挿入し、エラーをログに記録する
ユーザー プロンプト送信後フックユーザーがメッセージを送信する場合プロンプトの変更、フィルター処理
セッションライフサイクルフックセッションの開始コンテキストの追加、セッションの構成
セッションライフサイクルフックセッションの終了クリーンアップ、分析
エラー処理フックエラーが発生するカスタム エラー処理

簡単スタート

コード言語 navigation

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

フック呼び出しコンテキスト

すべてのフックは、現在のセッションに関するコンテキストを持つ invocation パラメーターを受け取ります。

フィールドタイプDescription
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)}`,
      };
    },
  },
});

フックガイド

こちらも参照ください