{"meta":{"title":"カスタム エージェントとサブエージェント オーケストレーション","intro":"スコープ指定されたツールとプロンプトを使用して特殊なエージェントを定義し、Copilot 1 つのセッション内でサブエージェントとして調整できるようにします。 複数のサブエージェントを並列にディスパッチする場合は、 フリート モード を参照してください。","product":"GitHub Copilot","breadcrumbs":[{"href":"/ja/enterprise-cloud@latest/copilot","title":"GitHub Copilot"},{"href":"/ja/enterprise-cloud@latest/copilot/how-tos","title":"方法"},{"href":"/ja/enterprise-cloud@latest/copilot/how-tos/copilot-sdk","title":"Copilot SDK"},{"href":"/ja/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features","title":"機能"},{"href":"/ja/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/custom-agents","title":"カスタム エージェント"}],"documentType":"article"},"body":"# カスタム エージェントとサブエージェント オーケストレーション\n\nスコープ指定されたツールとプロンプトを使用して特殊なエージェントを定義し、Copilot 1 つのセッション内でサブエージェントとして調整できるようにします。 複数のサブエージェントを並列にディスパッチする場合は、 フリート モード を参照してください。\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n## Overview\n\nカスタム エージェントは、セッションにアタッチする軽量のエージェント定義です。 各エージェントには、独自のシステム プロンプト、ツールの制限、およびオプションの MCP サーバーがあります。 ユーザーの要求がエージェントの専門知識と一致すると、Copilot ランタイムは自動的にそのエージェントに **sub-agent** として委任し、ライフサイクル イベントを親セッションにストリーミングしながら分離されたコンテキストで実行します。\n\n![図: 説明されたプロセスを示すフローチャート。](/assets/images/help/copilot/copilot-sdk/features-custom-agents-diagram-0.png)\n\n| 概念              | Description                                  |\n| --------------- | -------------------------------------------- |\n| **カスタム エージェント** | 独自のプロンプトとツール セットを含む名前付きエージェント構成              |\n| **サブエージェント**    | タスクの一部を処理するためにランタイムによって呼び出されるカスタム エージェント     |\n| **推論**          | ユーザーの意図に基づいてエージェントを自動選択するランタイムの機能            |\n| **親セッション**      | サブエージェントを生成したセッション。は、すべてのライフサイクル イベントを受信します。 |\n\n## カスタム エージェントの定義\n\nセッションの作成時に `customAgents` 渡します。 各エージェントには、少なくとも `name` と `prompt`が必要です。\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\nimport { CopilotClient } from \"@github/copilot-sdk\";\n\nconst client = new CopilotClient();\nawait client.start();\n\nconst session = await client.createSession({\n    model: \"gpt-5.4\",\n    customAgents: [\n        {\n            name: \"researcher\",\n            displayName: \"Research Agent\",\n            description: \"Explores codebases and answers questions using read-only tools\",\n            tools: [\"grep\", \"glob\", \"view\"],\n            prompt: \"You are a research assistant. Analyze code and answer questions. Do not modify any files.\",\n        },\n        {\n            name: \"editor\",\n            displayName: \"Editor Agent\",\n            description: \"Makes targeted code changes\",\n            tools: [\"view\", \"edit\", \"bash\"],\n            prompt: \"You are a code editor. Make minimal, surgical changes to files as requested.\",\n        },\n    ],\n    onPermissionRequest: async () => ({ kind: \"approve-once\" }),\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\nfrom copilot import CopilotClient, PermissionDecisionApproveOnce\n\nclient = CopilotClient()\nawait client.start()\n\nsession = await client.create_session(\n    on_permission_request=lambda req, inv: PermissionDecisionApproveOnce(),\n    model=\"gpt-5.4\",\n    custom_agents=[\n        {\n            \"name\": \"researcher\",\n            \"display_name\": \"Research Agent\",\n            \"description\": \"Explores codebases and answers questions using read-only tools\",\n            \"tools\": [\"grep\", \"glob\", \"view\"],\n            \"prompt\": \"You are a research assistant. Analyze code and answer questions. Do not modify any files.\",\n        },\n        {\n            \"name\": \"editor\",\n            \"display_name\": \"Editor Agent\",\n            \"description\": \"Makes targeted code changes\",\n            \"tools\": [\"view\", \"edit\", \"bash\"],\n            \"prompt\": \"You are a code editor. Make minimal, surgical changes to files as requested.\",\n        },\n    ],\n)\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n```golang\nctx := context.Background()\nclient := copilot.NewClient(nil)\nclient.Start(ctx)\n\nsession, _ := client.CreateSession(ctx, &copilot.SessionConfig{\n    Model: \"gpt-5.4\",\n    CustomAgents: []copilot.CustomAgentConfig{\n        {\n            Name:        \"researcher\",\n            DisplayName: \"Research Agent\",\n            Description: \"Explores codebases and answers questions using read-only tools\",\n            Tools:       []string{\"grep\", \"glob\", \"view\"},\n            Prompt:      \"You are a research assistant. Analyze code and answer questions. Do not modify any files.\",\n        },\n        {\n            Name:        \"editor\",\n            DisplayName: \"Editor Agent\",\n            Description: \"Makes targeted code changes\",\n            Tools:       []string{\"view\", \"edit\", \"bash\"},\n            Prompt:      \"You are a code editor. Make minimal, surgical changes to files as requested.\",\n        },\n    },\n    OnPermissionRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) {\n        return &rpc.PermissionDecisionApproveOnce{}, nil\n    },\n})\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n```csharp\nusing GitHub.Copilot;\nusing GitHub.Copilot.Rpc;\n\nawait using var client = new CopilotClient();\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    Model = \"gpt-5.4\",\n    CustomAgents = new List<CustomAgentConfig>\n    {\n        new()\n        {\n            Name = \"researcher\",\n            DisplayName = \"Research Agent\",\n            Description = \"Explores codebases and answers questions using read-only tools\",\n            Tools = new List<string> { \"grep\", \"glob\", \"view\" },\n            Prompt = \"You are a research assistant. Analyze code and answer questions. Do not modify any files.\",\n        },\n        new()\n        {\n            Name = \"editor\",\n            DisplayName = \"Editor Agent\",\n            Description = \"Makes targeted code changes\",\n            Tools = new List<string> { \"view\", \"edit\", \"bash\" },\n            Prompt = \"You are a code editor. Make minimal, surgical changes to files as requested.\",\n        },\n    },\n    OnPermissionRequest = (req, inv) =>\n        Task.FromResult(PermissionDecision.ApproveOnce()),\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n```java\nimport com.github.copilot.CopilotClient;\nimport com.github.copilot.rpc.*;\nimport java.util.List;\n\ntry (var client = new CopilotClient()) {\n    client.start().get();\n\n    var session = client.createSession(\n        new SessionConfig()\n            .setModel(\"gpt-5.4\")\n            .setCustomAgents(List.of(\n                new CustomAgentConfig()\n                    .setName(\"researcher\")\n                    .setDisplayName(\"Research Agent\")\n                    .setDescription(\"Explores codebases and answers questions using read-only tools\")\n                    .setTools(List.of(\"grep\", \"glob\", \"view\"))\n                    .setPrompt(\"You are a research assistant. Analyze code and answer questions. Do not modify any files.\"),\n                new CustomAgentConfig()\n                    .setName(\"editor\")\n                    .setDisplayName(\"Editor Agent\")\n                    .setDescription(\"Makes targeted code changes\")\n                    .setTools(List.of(\"view\", \"edit\", \"bash\"))\n                    .setPrompt(\"You are a code editor. Make minimal, surgical changes to files as requested.\")\n            ))\n            .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)\n    ).get();\n}\n```\n\n</div>\n\n</div>\n\n## 構成のリファレンス\n\n| 財産                                                                                | タイプ        | 必須 | Description       |\n| --------------------------------------------------------------------------------- | ---------- | -- | ----------------- |\n| `name`                                                                            | `string`   | ✅  | エージェントのユニークID     |\n| `displayName`                                                                     | `string`   |    |                   |\n| イベントに表示される人間が判読できる名前                                                              |            |    |                   |\n| `description`                                                                     | `string`   |    |                   |\n| エージェントが実行すること - ランタイムがエージェントを選択するのを支援します                                          |            |    |                   |\n| `tools`                                                                           |            |    |                   |\n| `string[]` または `null`                                                             |            |    |                   |\n| エージェントが使用できるツール名。                                                                 |            |    |                   |\n| `null` または省略 = すべてのツール                                                            |            |    |                   |\n| `prompt`                                                                          | `string`   | ✅  | エージェントのシステム プロンプト |\n| `mcpServers`                                                                      | `object`   |    |                   |\n| このエージェントに固有の MCP サーバー構成                                                           |            |    |                   |\n| `infer`                                                                           | `boolean`  |    |                   |\n| ランタイムがこのエージェントを自動選択できるかどうか (既定値: `true`)                                          |            |    |                   |\n| `skills`                                                                          | `string[]` |    |                   |\n| 起動時にエージェントのコンテキストにプリロードするスキル名                                                     |            |    |                   |\n| `model`                                                                           | `string`   |    |                   |\n| このエージェントの実行中に使用するモデル識別子                                                           |            |    |                   |\n| `reasoningEffort`                                                                 | `string`   |    |                   |\n| このエージェントの実行中に使用する推論作業。 省略すると、SDK はエージェントごとのオーバーライドを送信せず、ランタイムは作業を解決します (下記の注を参照)。 |            |    |                   |\n\n> \\[!TIP]\n> 適切な `description` は、ランタイムがユーザーの意図を適切なエージェントと照合するのに役立ちます。 エージェントの専門知識と機能について具体的に説明します。\n\nカスタム エージェントの実行中に親セッションのモデル設定をオーバーライドするには、 `model` と `reasoningEffort` を設定します。\n`reasoningEffort`を省略すると、SDK はエージェントごとのオーバーライドを送信せず、ランタイムは、呼び出しごとのクライアント オプション、解決されたモデルの既定値、またはエージェント定義がすべて優先されます。それ以外の場合、サブエージェントが親と同じモデルを実行する場合にのみ、ランタイムは親セッションの作業を継承します。 サブエージェントが別のモデルに解決されると、親の作業を継承するのではなく、そのモデルの既定値にフォールバックします。\n`reasoning_effort`を使用Python、.NETは`ReasoningEffort`を使用し、Go は`ReasoningEffort`を使用し、Javaは`setReasoningEffort`を使用し、Rust は`with_reasoning_effort`を使用します。\n\n上記のエージェントごとの構成に加えて、`agent`自体の\\*\\*\\*\\* を設定して、セッションの開始時にアクティブなカスタム エージェントを事前に選択できます。 以下の [「セッション作成時のエージェントの選択](#selecting-an-agent-at-session-creation) 」を参照してください。\n\n| セッション構成プロパティ                       | タイプ      | Description                      |\n| ---------------------------------- | -------- | -------------------------------- |\n| `agent`                            | `string` | セッションの作成時に事前に選択するカスタム エージェントの名前。 |\n| `name`の`customAgents`と一致する必要があります。 |          |                                  |\n\n## エージェントごとのスキル\n\n`skills` プロパティを使用して、エージェントのコンテキストにスキルを事前に読み込むことができます。 指定すると、リストされている各スキルの **完全なコンテンツ** が起動時にエージェントのコンテキストに熱心に挿入されます。エージェントはスキル ツールを呼び出す必要はありません。手順は既に存在します。 スキルは **オプトイン**です。エージェントは既定でスキルを受け取らず、サブエージェントは親からスキルを継承しません。 スキル名は、セッション レベルの `skillDirectories`から解決されます。\n\n```typescript\nconst session = await client.createSession({\n    skillDirectories: [\"./skills\"],\n    customAgents: [\n        {\n            name: \"security-auditor\",\n            description: \"Security-focused code reviewer\",\n            prompt: \"Focus on OWASP Top 10 vulnerabilities\",\n            skills: [\"security-scan\", \"dependency-check\"],\n        },\n        {\n            name: \"docs-writer\",\n            description: \"Technical documentation writer\",\n            prompt: \"Write clear, concise documentation\",\n            skills: [\"markdown-lint\"],\n        },\n    ],\n    onPermissionRequest: async () => ({ kind: \"approve-once\" }),\n});\n```\n\nこの例では、 `security-auditor` は `security-scan` で始まり、 `dependency-check` はコンテキストに既に挿入されていますが、 `docs-writer` は `markdown-lint`で始まります。\n`skills`フィールドを持たないエージェントは、スキルコンテンツを受け取らない。\n\n## セッション作成時のエージェントの選択\n\nセッション構成で `agent` を渡して、セッションの開始時にアクティブにするカスタム エージェントを事前に選択できます。 この値は、`name`で定義されているいずれかのエージェントの`customAgents`と一致する必要があります。\n\nこれは、作成後に `session.rpc.agent.select()` を呼び出すことと同じですが、追加の API 呼び出しを回避し、最初のプロンプトからエージェントがアクティブになっていることを確認します。\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n<!-- docs-validate: skip -->\n\n```typescript\nconst session = await client.createSession({\n    customAgents: [\n        {\n            name: \"researcher\",\n            prompt: \"You are a research assistant. Analyze code and answer questions.\",\n        },\n        {\n            name: \"editor\",\n            prompt: \"You are a code editor. Make minimal, surgical changes.\",\n        },\n    ],\n    agent: \"researcher\", // Pre-select the researcher agent\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n<!-- docs-validate: skip -->\n\n```python\nsession = await client.create_session(\n    on_permission_request=PermissionHandler.approve_all,\n    custom_agents=[\n        {\n            \"name\": \"researcher\",\n            \"prompt\": \"You are a research assistant. Analyze code and answer questions.\",\n        },\n        {\n            \"name\": \"editor\",\n            \"prompt\": \"You are a code editor. Make minimal, surgical changes.\",\n        },\n    ],\n    agent=\"researcher\",  # Pre-select the researcher agent\n)\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n<!-- docs-validate: skip -->\n\n```golang\nsession, _ := client.CreateSession(ctx, &copilot.SessionConfig{\n    CustomAgents: []copilot.CustomAgentConfig{\n        {\n            Name:   \"researcher\",\n            Prompt: \"You are a research assistant. Analyze code and answer questions.\",\n        },\n        {\n            Name:   \"editor\",\n            Prompt: \"You are a code editor. Make minimal, surgical changes.\",\n        },\n    },\n    Agent: \"researcher\", // Pre-select the researcher agent\n})\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n<!-- docs-validate: skip -->\n\n```csharp\nvar session = await client.CreateSessionAsync(new SessionConfig\n{\n    CustomAgents = new List<CustomAgentConfig>\n    {\n        new() { Name = \"researcher\", Prompt = \"You are a research assistant. Analyze code and answer questions.\" },\n        new() { Name = \"editor\", Prompt = \"You are a code editor. Make minimal, surgical changes.\" },\n    },\n    Agent = \"researcher\", // Pre-select the researcher agent\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nimport com.github.copilot.rpc.*;\nimport java.util.List;\n\nvar session = client.createSession(\n    new SessionConfig()\n        .setCustomAgents(List.of(\n            new CustomAgentConfig()\n                .setName(\"researcher\")\n                .setPrompt(\"You are a research assistant. Analyze code and answer questions.\"),\n            new CustomAgentConfig()\n                .setName(\"editor\")\n                .setPrompt(\"You are a code editor. Make minimal, surgical changes.\")\n        ))\n        .setAgent(\"researcher\") // Pre-select the researcher agent\n        .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)\n).get();\n```\n\n</div>\n\n</div>\n\n## サブエージェントの委任のしくみ\n\nカスタム エージェントとのセッションにプロンプトを送信すると、ランタイムはサブエージェントに委任するかどうかを評価します。\n\n1. **意図の照合** - ランタイムは、ユーザーのプロンプトを各エージェントの`name`および`description`と比較し分析します。\n2. **エージェントの選択** - 一致するものが見つかり、 `infer` が `false`されていない場合、ランタイムはエージェントを選択します。\n3. **分離実行** - サブエージェントは、独自のプロンプトと制限付きツール セットを使用して実行されます\n4. **イベント ストリーミング** - ライフサイクル イベント (`subagent.started`、 `subagent.completed`など) が親セッションにストリームバックされます\n5. **結果の統合** - サブエージェントの出力が親エージェントの応答に組み込まれます\n\n### 推論の制御\n\n既定では、すべてのカスタム エージェントを自動選択 (`infer: true`) で使用できます。\n`infer: false`を設定して、ランタイムがエージェントを自動選択できないようにします。明示的なユーザー要求によってのみ呼び出すエージェントに役立ちます。\n\n```typescript\n{\n    name: \"dangerous-cleanup\",\n    description: \"Deletes unused files and dead code\",\n    tools: [\"bash\", \"edit\", \"view\"],\n    prompt: \"You clean up codebases by removing dead code and unused files.\",\n    infer: false, // Only invoked when user explicitly asks for this agent\n}\n```\n\n## サブエージェント イベントのリッスン\n\nサブエージェントを実行すると、親セッションはライフサイクル イベントを生成します。 これらのイベントをサブスクライブして、エージェント アクティビティを視覚化する UI を構築します。\n\nサブエージェントから発信されたセッション イベントは、親セッション ストリームを共有し、エンベロープ レベルの `agentId`を含めます。 ルート/メイン エージェント イベントとセッション レベルのイベントでは `agentId`が省略されるため、レンダラーはイベント エンベロープを確認することで、親の応答をサブエージェント トレースから分離できます。\n\n### イベントの種類\n\n| イベント                                                                                                               | 次の場合に生成されます                 | データ |\n| ------------------------------------------------------------------------------------------------------------------ | --------------------------- | --- |\n| `subagent.selected`                                                                                                | ランタイムがタスクのエージェントを選択する       |     |\n| `agentName`、`agentDisplayName`、`tools`                                                                             |                             |     |\n| `subagent.started`                                                                                                 | サブエージェントが実行を開始する            |     |\n| `toolCallId`、`agentName`、`agentDisplayName`、`agentDescription`、`model?`                                            |                             |     |\n| `subagent.completed`                                                                                               | サブエージェントが正常に終了する            |     |\n| `toolCallId`､`agentName`、`agentDisplayName`、`model?`、`durationMs?`、`totalTokens?`、`totalToolCalls?`                |                             |     |\n| `subagent.failed`                                                                                                  | サブエージェントでエラーが発生する           |     |\n| `toolCallId`、 `agentName`、 `agentDisplayName`、 `error`、 `model?`、 `durationMs?`、 `totalTokens?`、 `totalToolCalls?` |                             |     |\n| `subagent.deselected`                                                                                              | ランタイムがサブエージェントから他のプロセスに移行する | —   |\n\n### イベントに登録する\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\nsession.on((event) => {\n    switch (event.type) {\n        case \"subagent.started\":\n            console.log(`▶ Sub-agent started: ${event.data.agentDisplayName}`);\n            console.log(`  Description: ${event.data.agentDescription}`);\n            console.log(`  Tool call ID: ${event.data.toolCallId}`);\n            break;\n\n        case \"subagent.completed\":\n            console.log(`✅ Sub-agent completed: ${event.data.agentDisplayName}`);\n            if (event.data.durationMs !== undefined) console.log(`  Duration: ${event.data.durationMs}ms`);\n            if (event.data.totalTokens !== undefined) console.log(`  Tokens: ${event.data.totalTokens}`);\n            if (event.data.totalToolCalls !== undefined) console.log(`  Tool calls: ${event.data.totalToolCalls}`);\n            break;\n\n        case \"subagent.failed\":\n            console.log(`❌ Sub-agent failed: ${event.data.agentDisplayName}`);\n            console.log(`  Error: ${event.data.error}`);\n            if (event.data.durationMs !== undefined) console.log(`  Duration: ${event.data.durationMs}ms`);\n            break;\n\n        case \"subagent.selected\":\n            console.log(`🎯 Agent selected: ${event.data.agentDisplayName}`);\n            console.log(`  Tools: ${event.data.tools?.join(\", \") ?? \"all\"}`);\n            break;\n\n        case \"subagent.deselected\":\n            console.log(\"↩ Agent deselected, returning to parent\");\n            break;\n    }\n});\n\nconst response = await session.sendAndWait({\n    prompt: \"Research how authentication works in this codebase\",\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\ndef handle_event(event):\n    if event.type == \"subagent.started\":\n        print(f\"▶ Sub-agent started: {event.data.agent_display_name}\")\n        print(f\"  Description: {event.data.agent_description}\")\n    elif event.type == \"subagent.completed\":\n        print(f\"✅ Sub-agent completed: {event.data.agent_display_name}\")\n    elif event.type == \"subagent.failed\":\n        print(f\"❌ Sub-agent failed: {event.data.agent_display_name}\")\n        print(f\"  Error: {event.data.error}\")\n    elif event.type == \"subagent.selected\":\n        tools = event.data.tools or \"all\"\n        print(f\"🎯 Agent selected: {event.data.agent_display_name} (tools: {tools})\")\n\nunsubscribe = session.on(handle_event)\n\nresponse = await session.send_and_wait(\"Research how authentication works in this codebase\")\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n```golang\nsession.On(func(event copilot.SessionEvent) {\n    switch d := event.Data.(type) {\n    case *copilot.SubagentStartedData:\n        fmt.Printf(\"▶ Sub-agent started: %s\\n\", d.AgentDisplayName)\n        fmt.Printf(\"  Description: %s\\n\", d.AgentDescription)\n        fmt.Printf(\"  Tool call ID: %s\\n\", d.ToolCallID)\n    case *copilot.SubagentCompletedData:\n        fmt.Printf(\"✅ Sub-agent completed: %s\\n\", d.AgentDisplayName)\n    case *copilot.SubagentFailedData:\n        fmt.Printf(\"❌ Sub-agent failed: %s — %v\\n\", d.AgentDisplayName, d.Error)\n    case *copilot.SubagentSelectedData:\n        fmt.Printf(\"🎯 Agent selected: %s\\n\", d.AgentDisplayName)\n    }\n})\n\n_, err := session.SendAndWait(ctx, copilot.MessageOptions{\n    Prompt: \"Research how authentication works in this codebase\",\n})\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n```csharp\nusing var subscription = session.On<SessionEvent>(evt =>\n{\n    switch (evt)\n    {\n        case SubagentStartedEvent started:\n            Console.WriteLine($\"▶ Sub-agent started: {started.Data.AgentDisplayName}\");\n            Console.WriteLine($\"  Description: {started.Data.AgentDescription}\");\n            Console.WriteLine($\"  Tool call ID: {started.Data.ToolCallId}\");\n            break;\n        case SubagentCompletedEvent completed:\n            Console.WriteLine($\"✅ Sub-agent completed: {completed.Data.AgentDisplayName}\");\n            break;\n        case SubagentFailedEvent failed:\n            Console.WriteLine($\"❌ Sub-agent failed: {failed.Data.AgentDisplayName} — {failed.Data.Error}\");\n            break;\n        case SubagentSelectedEvent selected:\n            Console.WriteLine($\"🎯 Agent selected: {selected.Data.AgentDisplayName}\");\n            break;\n    }\n});\n\nawait session.SendAndWaitAsync(new MessageOptions\n{\n    Prompt = \"Research how authentication works in this codebase\"\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nsession.on(event -> {\n    if (event instanceof SubagentStartedEvent e) {\n        System.out.println(\"▶ Sub-agent started: \" + e.getData().agentDisplayName());\n        System.out.println(\"  Description: \" + e.getData().agentDescription());\n        System.out.println(\"  Tool call ID: \" + e.getData().toolCallId());\n    } else if (event instanceof SubagentCompletedEvent e) {\n        System.out.println(\"✅ Sub-agent completed: \" + e.getData().agentName());\n    } else if (event instanceof SubagentFailedEvent e) {\n        System.out.println(\"❌ Sub-agent failed: \" + e.getData().agentName());\n        System.out.println(\"  Error: \" + e.getData().error());\n    } else if (event instanceof SubagentSelectedEvent e) {\n        System.out.println(\"🎯 Agent selected: \" + e.getData().agentDisplayName());\n    } else if (event instanceof SubagentDeselectedEvent e) {\n        System.out.println(\"↩ Agent deselected, returning to parent\");\n    }\n});\n\nvar response = session.sendAndWait(\n    new MessageOptions().setPrompt(\"Research how authentication works in this codebase\")\n).get();\n```\n\n</div>\n\n</div>\n\n## エージェント ツリー UI の構築\n\nサブエージェント イベントには、実行ツリーを再構築できる `toolCallId` フィールドが含まれます。 エージェント アクティビティを追跡するためのパターンを次に示します。\n\n```typescript\ninterface AgentNode {\n    toolCallId: string;\n    name: string;\n    displayName: string;\n    status: \"running\" | \"completed\" | \"failed\";\n    error?: string;\n    startedAt: Date;\n    completedAt?: Date;\n}\n\nconst agentTree = new Map<string, AgentNode>();\n\nsession.on((event) => {\n    if (event.type === \"subagent.started\") {\n        agentTree.set(event.data.toolCallId, {\n            toolCallId: event.data.toolCallId,\n            name: event.data.agentName,\n            displayName: event.data.agentDisplayName,\n            status: \"running\",\n            startedAt: new Date(event.timestamp),\n        });\n    }\n\n    if (event.type === \"subagent.completed\") {\n        const node = agentTree.get(event.data.toolCallId);\n        if (node) {\n            node.status = \"completed\";\n            node.completedAt = new Date(event.timestamp);\n        }\n    }\n\n    if (event.type === \"subagent.failed\") {\n        const node = agentTree.get(event.data.toolCallId);\n        if (node) {\n            node.status = \"failed\";\n            node.error = event.data.error;\n            node.completedAt = new Date(event.timestamp);\n        }\n    }\n\n    // Render your UI with the updated tree\n    renderAgentTree(agentTree);\n});\n```\n\n## エージェントごとのツールの範囲設定\n\n`tools` プロパティを使用して、エージェントがアクセスできるツールを制限します。 これは、セキュリティとエージェントの集中を維持するために不可欠です。\n\n```typescript\nconst session = await client.createSession({\n    customAgents: [\n        {\n            name: \"reader\",\n            description: \"Read-only exploration of the codebase\",\n            tools: [\"grep\", \"glob\", \"view\"],  // No write access\n            prompt: \"You explore and analyze code. Never suggest modifications directly.\",\n        },\n        {\n            name: \"writer\",\n            description: \"Makes code changes\",\n            tools: [\"view\", \"edit\", \"bash\"],   // Write access\n            prompt: \"You make precise code changes as instructed.\",\n        },\n        {\n            name: \"unrestricted\",\n            description: \"Full access agent for complex tasks\",\n            tools: null,                        // All tools available\n            prompt: \"You handle complex multi-step tasks using any available tools.\",\n        },\n    ],\n});\n```\n\n> \\[!NOTE]\n> `tools`が`null`または省略されると、エージェントはセッションで構成されているすべてのツールへのアクセスを継承します。 明示的なツール リストを使用して、最小限の特権の原則を適用します。\n\n## エージェント専用ツール\n\nセッション構成の `defaultAgent` プロパティを使用して、既定のエージェント (カスタム エージェントが選択されていないときにターンを処理する組み込みエージェント) から特定のツールを非表示にします。 これにより、これらのツールの機能が必要になったときにメイン エージェントがサブエージェントに委任され、メイン エージェントのコンテキストがクリーンな状態が維持されます。\n\nこれは、次の場合に役立ちます。\n\n* 特定のツールは、メイン エージェントを圧倒する大量のコンテキストを生成します\n* メイン エージェントをオーケストレーターとして機能させ、特殊なサブエージェントに重い作業を委任する\n* オーケストレーションと実行を厳密に分離する必要がある\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n```typescript\nimport { CopilotClient, defineTool, approveAll } from \"@github/copilot-sdk\";\nimport { z } from \"zod\";\n\nconst heavyContextTool = defineTool(\"analyze-codebase\", {\n    description: \"Performs deep analysis of the codebase, generating extensive context\",\n    parameters: z.object({ query: z.string() }),\n    handler: async ({ query }) => {\n        // ... expensive analysis that returns lots of data\n        return { analysis: \"...\" };\n    },\n});\n\nconst session = await client.createSession({\n    tools: [heavyContextTool],\n    defaultAgent: {\n        excludedTools: [\"analyze-codebase\"],\n    },\n    customAgents: [\n        {\n            name: \"researcher\",\n            description: \"Deep codebase analysis agent with access to heavy-context tools\",\n            tools: [\"analyze-codebase\"],\n            prompt: \"You perform thorough codebase analysis using the analyze-codebase tool.\",\n        },\n    ],\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n```python\nfrom copilot import CopilotClient\nfrom copilot.tools import Tool\n\nheavy_tool = Tool(\n    name=\"analyze-codebase\",\n    description=\"Performs deep analysis of the codebase\",\n    handler=analyze_handler,\n    parameters={\"type\": \"object\", \"properties\": {\"query\": {\"type\": \"string\"}}},\n)\n\nsession = await client.create_session(\n    tools=[heavy_tool],\n    default_agent={\"excluded_tools\": [\"analyze-codebase\"]},\n    custom_agents=[\n        {\n            \"name\": \"researcher\",\n            \"description\": \"Deep codebase analysis agent\",\n            \"tools\": [\"analyze-codebase\"],\n            \"prompt\": \"You perform thorough codebase analysis.\",\n        },\n    ],\n    on_permission_request=approve_all,\n)\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n<!-- docs-validate: skip -->\n\n```golang\nsession, err := client.CreateSession(ctx, &copilot.SessionConfig{\n    Tools: []copilot.Tool{heavyTool},\n    DefaultAgent: &copilot.DefaultAgentConfig{\n        ExcludedTools: []string{\"analyze-codebase\"},\n    },\n    CustomAgents: []copilot.CustomAgentConfig{\n        {\n            Name:        \"researcher\",\n            Description: \"Deep codebase analysis agent\",\n            Tools:       []string{\"analyze-codebase\"},\n            Prompt:      \"You perform thorough codebase analysis.\",\n        },\n    },\n})\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"csharp\" data-label=\"C#\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">C#</div>\n\n<!-- docs-validate: skip -->\n\n```csharp\nvar session = await client.CreateSessionAsync(new SessionConfig\n{\n    Tools = [analyzeCodebaseTool],\n    DefaultAgent = new DefaultAgentConfig\n    {\n        ExcludedTools = [\"analyze-codebase\"],\n    },\n    CustomAgents =\n    [\n        new CustomAgentConfig\n        {\n            Name = \"researcher\",\n            Description = \"Deep codebase analysis agent\",\n            Tools = [\"analyze-codebase\"],\n            Prompt = \"You perform thorough codebase analysis.\",\n        },\n    ],\n});\n```\n\n</div>\n\n</div>\n\n### どのように機能するのか\n\n`defaultAgent.excludedTools`に一覧表示されているツール:\n\n1. **登録済み**であり、ハンドラーを実行できます\n2. メイン エージェントのツール リストから**非表示**になります。LLM はそれらを直接表示または呼び出しません\n3. それらを\\*\\*\\*\\* 配列に含む任意のカスタム サブエージェントで`tools`\n\n### 他のツールフィルターとの連携\n\n`defaultAgent.excludedTools` はセッション レベルの `availableTools` と `excludedTools`に直交します。\n\n| Filter                       | Scope        | 影響                                           |\n| ---------------------------- | ------------ | -------------------------------------------- |\n| `availableTools`             | セッション全体      | Allowlist - すべてのユーザーに対してこれらのツールのみが存在します      |\n| `excludedTools`              | セッション全体      | ブロックリスト - すべてのユーザーに対してこれらのツールがブロックされます       |\n| `defaultAgent.excludedTools` | メイン エージェントのみ | これらのツールはメイン エージェントには表示されませんが、サブエージェントで使用できます |\n\n優先順位：\n\n1. セッション レベルの `availableTools`/`excludedTools` が最初に適用されます (グローバルに)\n2. `defaultAgent.excludedTools` が上に適用され、メイン エージェントのみがさらに制限されます\n\n> \\[!NOTE]\n> ツールが `excludedTools` (セッション レベル) と `defaultAgent.excludedTools`の両方にある場合、セッション レベルの除外が優先されます。ツールはすべてのユーザーが使用できません。\n\n## エージェントへの MCP サーバーのアタッチ\n\n各カスタム エージェントは独自の MCP (モデル コンテキスト プロトコル) サーバーを持つ可能性があり、特殊なデータ ソースにアクセスできます。\n\n```typescript\nconst session = await client.createSession({\n    customAgents: [\n        {\n            name: \"db-analyst\",\n            description: \"Analyzes database schemas and queries\",\n            prompt: \"You are a database expert. Use the database MCP server to analyze schemas.\",\n            mcpServers: {\n                \"database\": {\n                    command: \"npx\",\n                    args: [\"-y\", \"@modelcontextprotocol/server-postgres\", \"postgresql://localhost/mydb\"],\n                },\n            },\n        },\n    ],\n});\n```\n\n## パターンとベスト プラクティス\n\n### 研究者と編集者のペアリング\n\n一般的なパターンは、読み取り専用の研究者エージェントと書き込み可能なエディター エージェントを定義することです。 ランタイムは探索タスクを研究者に委任し、変更タスクをエディターに委任します。\n\n```typescript\ncustomAgents: [\n    {\n        name: \"researcher\",\n        description: \"Analyzes code structure, finds patterns, and answers questions\",\n        tools: [\"grep\", \"glob\", \"view\"],\n        prompt: \"You are a code analyst. Thoroughly explore the codebase to answer questions.\",\n    },\n    {\n        name: \"implementer\",\n        description: \"Implements code changes based on analysis\",\n        tools: [\"view\", \"edit\", \"bash\"],\n        prompt: \"You make minimal, targeted code changes. Always verify changes compile.\",\n    },\n]\n```\n\n### エージェントの説明を固有に保つ\n\nランタイムは、 `description` を使用してユーザーの意図と一致します。 あいまいな説明は、委任が不適切になります。\n\n```typescript\n// ❌ Too vague — runtime can't distinguish from other agents\n{ description: \"Helps with code\" }\n\n// ✅ Specific — runtime knows when to delegate\n{ description: \"Analyzes Python test coverage and identifies untested code paths\" }\n```\n\n### エラーを適切に処理する\n\nサブエージェントは失敗する可能性があります。 常に `subagent.failed` イベントをリッスンし、アプリケーションで処理します。\n\n```typescript\nsession.on((event) => {\n    if (event.type === \"subagent.failed\") {\n        logger.error(`Agent ${event.data.agentName} failed: ${event.data.error}`);\n        // Show error in UI, retry, or fall back to parent agent\n    }\n});\n```"}