# セッション フック

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

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

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

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

## 使用可能なフック

| フック                                                                                      | Trigger           | ユースケース(事例)                |
| ---------------------------------------------------------------------------------------- | ----------------- | ------------------------- |
| [ツール使用前のフック](/ja/copilot/how-tos/copilot-sdk/hooks/pre-tool-use)                         | ツールの実行前           | アクセス許可の制御、引数の検証           |
| [ツール使用後フック](/ja/copilot/how-tos/copilot-sdk/hooks/post-tool-use)                         | ツールの実行後 (成功のみ)    | 結果変換、ログ記録                 |
| [ツール使用後フック](/ja/copilot/how-tos/copilot-sdk/hooks/post-tool-use#failure-variant)         | 結果が失敗したツールの実行後    | 再試行のガイダンスを挿入し、エラーをログに記録する |
| [ユーザー プロンプト送信後フック](/ja/copilot/how-tos/copilot-sdk/hooks/user-prompt-submitted)          | ユーザーがメッセージを送信する場合 | プロンプトの変更、フィルター処理          |
| [セッションライフサイクルフック](/ja/copilot/how-tos/copilot-sdk/hooks/session-lifecycle#session-start) | セッションの開始          | コンテキストの追加、セッションの構成        |
| [セッションライフサイクルフック](/ja/copilot/how-tos/copilot-sdk/hooks/session-lifecycle#session-end)   | セッションの終了          | クリーンアップ、分析                |
| [エラー処理フック](/ja/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` パラメーターを受け取ります。

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

## フックガイド

* **[ツール使用前のフック](/ja/copilot/how-tos/copilot-sdk/hooks/pre-tool-use)** - コントロール ツールの実行アクセス許可
* **[ツール使用後フック](/ja/copilot/how-tos/copilot-sdk/hooks/post-tool-use)** - 変換ツールの結果
* **[ユーザー プロンプト送信後フック](/ja/copilot/how-tos/copilot-sdk/hooks/user-prompt-submitted)** - ユーザー プロンプトを変更する
* **[セッションライフサイクルフック](/ja/copilot/how-tos/copilot-sdk/hooks/session-lifecycle)** - セッションの開始と終了
* **[エラー処理フック](/ja/copilot/how-tos/copilot-sdk/hooks/error-handling)** - カスタム エラー処理

## こちらも参照ください

* [初めてのCopilot搭載アプリを構築する](/ja/copilot/how-tos/copilot-sdk/getting-started)
* [初めてのCopilot搭載アプリを構築する](/ja/copilot/how-tos/copilot-sdk/getting-started#step-4-add-a-custom-tool)
* [デバッグ ガイド](/ja/copilot/how-tos/copilot-sdk/troubleshooting/debugging)