{"meta":{"title":"Интеграция с Microsoft Agent Framework","intro":"Используйте Copilot SDK в качестве поставщика агентов внутри Microsoft Agent Framework (MAF) для создания многоагентных рабочих процессов вместе с Azure OpenAI, Anthropic и другими провайдерами.","product":"GitHub Copilot","breadcrumbs":[{"href":"/ru/copilot","title":"GitHub Copilot"},{"href":"/ru/copilot/how-tos","title":"Инструкции"},{"href":"/ru/copilot/how-tos/copilot-sdk","title":"Второй пилот SDK"},{"href":"/ru/copilot/how-tos/copilot-sdk/integrations","title":"Integrations"},{"href":"/ru/copilot/how-tos/copilot-sdk/integrations/microsoft-agent-framework","title":"платформа агента Microsoft"}],"documentType":"article"},"body":"# Интеграция с Microsoft Agent Framework\n\nИспользуйте Copilot SDK в качестве поставщика агентов внутри Microsoft Agent Framework (MAF) для создания многоагентных рабочих процессов вместе с Azure OpenAI, Anthropic и другими провайдерами.\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n## Обзор\n\nMicrosoft Agent Framework является унифицированным преемником Semantic Kernel и AutoGen. Он предоставляет стандартный интерфейс для создания, оркестрации и развертывания агентов ИИ. Специализированные интеграционные пакеты позволяют обернуть клиент Copilot SDK как первоклассный MAF-агент — взаимозаменяемый с любым другим поставщиком агентов в фреймворке.\n\n| Концепция                        | Описание                                                                                                 |\n| -------------------------------- | -------------------------------------------------------------------------------------------------------- |\n| **Microsoft Агентный фреймворк** | Открытый фреймворк для оркестрации с одним и несколькими агентами в .NET и Python                        |\n| **Поставщик агентов**            | Бэкенд, который питает агента (Copilot, Azure OpenAI, Anthropic и др.)                                   |\n| **Оркестратор**                  | Компонент MAF, координирующий агентов в последовательных, одновременных или передачных рабочих процессах |\n| **Протокол A2A**                 | Стандарт коммуникации между агентами, поддерживаемый фреймворком                                         |\n\n> \\[!NOTE]\n> Пакеты интеграции MAF доступны для **.NET** и **Python**. Для TypeScript, Go, Java и Rust используйте Copilot SDK напрямую — стандартные SDK API уже обеспечивают вызов инструментов, потоковую передачу и пользовательские агенты.\n\n## Необходимые условия\n\nПрежде чем начать, убедитесь, что у вас есть следующее:\n\n* [Рабочий автозаголовок](/ru/copilot/how-tos/copilot-sdk/getting-started) на выбранном вами языке\n* Подписка на GitHub Copilot (индивидуальная, бизнес-или корпоративная)\n* CLI Copilot, установленный или доступный через комплектный CLI SDK\n\n## Installation\n\nУстановите Copilot SDK вместе с пакетом интеграции MAF для вашего языка:\n\n<div class=\"ghd-codetabs\">\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```shell\ndotnet add package GitHub.Copilot.SDK\ndotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease\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```shell\npip install copilot-sdk agent-framework-github-copilot\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> \\[!NOTE]\n> Java SDK не имеет выделенного пакета интеграции MAF. Используйте стандартный SDK Copilot напрямую — он предоставляет вызов инструментов, потоковую трансляцию и кастомные агенты из коробки.\n\n```xml\n<!-- Maven -->\n<!-- Set copilot.sdk.version to the version published in java/README.md / Maven Central -->\n<dependency>\n    <groupId>com.github</groupId>\n    <artifactId>copilot-sdk-java</artifactId>\n    <version>${copilot.sdk.version}</version>\n</dependency>\n```\n\n</div>\n\n</div>\n\n## Основное использование\n\nОберните клиент Copilot SDK как агент MAF с помощью одного вызова метода. Полученный агент соответствует стандартному интерфейсу фреймворка и может использоваться в любом месте, где ожидается MAF-агент.\n\n<div class=\"ghd-codetabs\">\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\nusing GitHub.Copilot;\nusing Microsoft.Agents.AI;\n\nawait using var copilotClient = new CopilotClient();\nawait copilotClient.StartAsync();\n\n// Wrap as a MAF agent\nAIAgent agent = copilotClient.AsAIAgent();\n\n// Use the standard MAF interface\nstring response = await agent.RunAsync(\"Explain how dependency injection works in ASP.NET Core\");\nConsole.WriteLine(response);\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\nfrom agent_framework.github import GitHubCopilotAgent\n\nasync def main():\n    agent = GitHubCopilotAgent(\n        default_options={\n            \"instructions\": \"You are a helpful coding assistant.\",\n        }\n    )\n\n    async with agent:\n        result = await agent.run(\"Explain how dependency injection works in FastAPI\")\n        print(result)\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.CopilotClient;\nimport com.github.copilot.rpc.*;\n\nvar client = new CopilotClient();\nclient.start().get();\n\nvar session = client.createSession(new SessionConfig()\n    .setModel(\"gpt-5.4\")\n    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)\n).get();\n\nvar response = session.sendAndWait(new MessageOptions()\n    .setPrompt(\"Explain how dependency injection works in Spring Boot\")).get();\nSystem.out.println(response.getData().content());\n\nclient.stop().get();\n```\n\n</div>\n\n</div>\n\n## Добавление пользовательских инструментов\n\nРасширяйте свой агент Copilot с помощью инструментов для индивидуальных функций. Инструменты, определённые через стандартный Copilot SDK, автоматически доступны при работе агента внутри MAF.\n\n<div class=\"ghd-codetabs\">\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\nusing GitHub.Copilot;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Agents.AI;\n\n// Define a custom tool\nAIFunction weatherTool = CopilotTool.DefineTool(\n    (string location) => $\"The weather in {location} is sunny with a high of 25°C.\",\n    factoryOptions: new AIFunctionFactoryOptions\n    {\n        Name = \"GetWeather\",\n        Description = \"Get the current weather for a given location.\",\n    }\n);\n\nawait using var copilotClient = new CopilotClient();\nawait copilotClient.StartAsync();\n\n// Create agent with tools\nAIAgent agent = copilotClient.AsAIAgent(new AIAgentOptions\n{\n    Tools = new[] { weatherTool },\n});\n\nstring response = await agent.RunAsync(\"What's the weather like in Seattle?\");\nConsole.WriteLine(response);\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\nfrom agent_framework.github import GitHubCopilotAgent\n\ndef get_weather(location: str) -> str:\n    \"\"\"Get the current weather for a given location.\"\"\"\n    return f\"The weather in {location} is sunny with a high of 25°C.\"\n\nasync def main():\n    agent = GitHubCopilotAgent(\n        default_options={\n            \"instructions\": \"You are a helpful assistant with access to weather data.\",\n        },\n        tools=[get_weather],\n    )\n\n    async with agent:\n        result = await agent.run(\"What's the weather like in Seattle?\")\n        print(result)\n```\n\n</div>\n\n</div>\n\nВы также можете использовать нативное определение инструмента Copilot SDK вместе с инструментами MAF:\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 } from \"@github/copilot-sdk\";\n\nconst getWeather = defineTool(\"GetWeather\", {\n    description: \"Get the current weather for a given location.\",\n    parameters: {\n        type: \"object\",\n        properties: {\n            location: { type: \"string\", description: \"City name\" },\n        },\n        required: [\"location\"],\n    },\n    handler: async ({ location }: { location: string }) =>\n        `The weather in ${location} is sunny, 25°C.`,\n});\n\nconst client = new CopilotClient();\nconst session = await client.createSession({\n    model: \"gpt-5.4\",\n    tools: [getWeather],\n    onPermissionRequest: async () => ({ kind: \"approve-once\" }),\n});\n\nawait session.sendAndWait({ prompt: \"What's the weather like in Seattle?\" });\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;\nimport java.util.Map;\nimport java.util.concurrent.CompletableFuture;\n\nvar getWeather = ToolDefinition.create(\n    \"GetWeather\",\n    \"Get the current weather for a given location.\",\n    Map.of(\n        \"type\", \"object\",\n        \"properties\", Map.of(\n            \"location\", Map.of(\"type\", \"string\", \"description\", \"City name\")),\n        \"required\", List.of(\"location\")),\n    invocation -> {\n        var location = (String) invocation.getArguments().get(\"location\");\n        return CompletableFuture.completedFuture(\n            \"The weather in \" + location + \" is sunny, 25°C.\");\n    });\n\ntry (var client = new CopilotClient()) {\n    client.start().get();\n\n    var session = client.createSession(new SessionConfig()\n        .setModel(\"gpt-5.4\")\n        .setTools(List.of(getWeather))\n        .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)\n    ).get();\n\n    session.sendAndWait(new MessageOptions()\n        .setPrompt(\"What's the weather like in Seattle?\")).get();\n}\n```\n\n</div>\n\n</div>\n\n## Рабочие процессы с несколькими агентами\n\nОсновное преимущество интеграции MAF — это создание Copilot вместе с другими поставщиками агентов в организованных рабочих процессах. Используйте встроенные оркестраторы фреймворка для создания конвейеров, где разные агенты выполняют разные этапы.\n\n### Последовательный рабочий процесс\n\nЗапускайте агенты один за другим, передавая выходные данные от одного к другому:\n\n<div class=\"ghd-codetabs\">\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\nusing GitHub.Copilot;\nusing Microsoft.Agents.AI;\nusing Microsoft.Agents.AI.Orchestration;\n\nawait using var copilotClient = new CopilotClient();\nawait copilotClient.StartAsync();\n\n// Copilot agent for code review\nAIAgent reviewer = copilotClient.AsAIAgent(new AIAgentOptions\n{\n    Instructions = \"You review code for bugs, security issues, and best practices. Be thorough.\",\n});\n\n// Azure OpenAI agent for generating documentation\nAIAgent documentor = AIAgent.FromOpenAI(new OpenAIAgentOptions\n{\n    Model = \"gpt-5.4\",\n    Instructions = \"You write clear, concise documentation for code changes.\",\n});\n\n// Compose in a sequential pipeline\nvar pipeline = new SequentialOrchestrator(new[] { reviewer, documentor });\n\nstring result = await pipeline.RunAsync(\n    \"Review and document this pull request: added retry logic to the HTTP client\"\n);\nConsole.WriteLine(result);\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\nfrom agent_framework.github import GitHubCopilotAgent\nfrom agent_framework.openai import OpenAIAgent\nfrom agent_framework.orchestration import SequentialOrchestrator\n\nasync def main():\n    # Copilot agent for code review\n    reviewer = GitHubCopilotAgent(\n        default_options={\n            \"instructions\": \"You review code for bugs, security issues, and best practices.\",\n        }\n    )\n\n    # OpenAI agent for documentation\n    documentor = OpenAIAgent(\n        model=\"gpt-5.4\",\n        instructions=\"You write clear, concise documentation for code changes.\",\n    )\n\n    # Compose in a sequential pipeline\n    pipeline = SequentialOrchestrator(agents=[reviewer, documentor])\n\n    async with pipeline:\n        result = await pipeline.run(\n            \"Review and document this PR: added retry logic to the HTTP client\"\n        )\n        print(result)\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.CopilotClient;\nimport com.github.copilot.rpc.*;\n\n// Java uses the standard SDK directly — no MAF orchestrator needed\nvar client = new CopilotClient();\nclient.start().get();\n\n// Step 1: Code review session\nvar reviewer = client.createSession(new SessionConfig()\n    .setModel(\"gpt-5.4\")\n    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)\n).get();\n\nvar review = reviewer.sendAndWait(new MessageOptions()\n    .setPrompt(\"Review this PR for bugs, security issues, and best practices: \"\n        + \"added retry logic to the HTTP client\")).get();\n\n// Step 2: Documentation session using review output\nvar documentor = client.createSession(new SessionConfig()\n    .setModel(\"gpt-5.4\")\n    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)\n).get();\n\nvar docs = documentor.sendAndWait(new MessageOptions()\n    .setPrompt(\"Write documentation for these changes: \" + review.getData().content())).get();\nSystem.out.println(docs.getData().content());\n\nclient.stop().get();\n```\n\n</div>\n\n</div>\n\n### Параллельный рабочий процесс\n\nЗапускайте несколько агентов параллельно и агрегируйте их результаты:\n\n<div class=\"ghd-codetabs\">\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\nusing GitHub.Copilot;\nusing Microsoft.Agents.AI;\nusing Microsoft.Agents.AI.Orchestration;\n\nawait using var copilotClient = new CopilotClient();\nawait copilotClient.StartAsync();\n\nAIAgent securityReviewer = copilotClient.AsAIAgent(new AIAgentOptions\n{\n    Instructions = \"Focus exclusively on security vulnerabilities and risks.\",\n});\n\nAIAgent performanceReviewer = copilotClient.AsAIAgent(new AIAgentOptions\n{\n    Instructions = \"Focus exclusively on performance bottlenecks and optimization opportunities.\",\n});\n\n// Run both reviews concurrently\nvar concurrent = new ConcurrentOrchestrator(new[] { securityReviewer, performanceReviewer });\n\nstring combinedResult = await concurrent.RunAsync(\n    \"Analyze this database query module for issues\"\n);\nConsole.WriteLine(combinedResult);\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.CopilotClient;\nimport com.github.copilot.rpc.*;\nimport java.util.concurrent.CompletableFuture;\n\n// Java uses CompletableFuture for concurrent execution\nvar client = new CopilotClient();\nclient.start().get();\n\nvar securitySession = client.createSession(new SessionConfig()\n    .setModel(\"gpt-5.4\")\n    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)\n).get();\n\nvar perfSession = client.createSession(new SessionConfig()\n    .setModel(\"gpt-5.4\")\n    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)\n).get();\n\n// Run both reviews concurrently\nvar securityFuture = securitySession.sendAndWait(new MessageOptions()\n    .setPrompt(\"Focus on security vulnerabilities in this database query module\"));\nvar perfFuture = perfSession.sendAndWait(new MessageOptions()\n    .setPrompt(\"Focus on performance bottlenecks in this database query module\"));\n\nCompletableFuture.allOf(securityFuture, perfFuture).get();\n\nSystem.out.println(\"Security: \" + securityFuture.get().getData().content());\nSystem.out.println(\"Performance: \" + perfFuture.get().getData().content());\n\nclient.stop().get();\n```\n\n</div>\n\n</div>\n\n## Потоковая передача ответов\n\nПри создании интерактивных приложений отклики агентов подают для отображения выхода в реальном времени. Интеграция MAF сохраняет возможности потокового вещания Copilot SDK.\n\n<div class=\"ghd-codetabs\">\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\nusing GitHub.Copilot;\nusing Microsoft.Agents.AI;\n\nawait using var copilotClient = new CopilotClient();\nawait copilotClient.StartAsync();\n\nAIAgent agent = copilotClient.AsAIAgent(new AIAgentOptions\n{\n    Streaming = true,\n});\n\nawait foreach (var chunk in agent.RunStreamingAsync(\"Write a quicksort implementation in C#\"))\n{\n    Console.Write(chunk);\n}\nConsole.WriteLine();\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\nfrom agent_framework.github import GitHubCopilotAgent\n\nasync def main():\n    agent = GitHubCopilotAgent(\n        default_options={\"streaming\": True}\n    )\n\n    async with agent:\n        async for chunk in agent.run_streaming(\"Write a quicksort in Python\"):\n            print(chunk, end=\"\", flush=True)\n        print()\n```\n\n</div>\n\n</div>\n\nВы также можете транслировать напрямую через Copilot SDK без MAF:\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();\nconst session = await client.createSession({\n    model: \"gpt-5.4\",\n    streaming: true,\n    onPermissionRequest: async () => ({ kind: \"approve-once\" }),\n});\n\nsession.on(\"assistant.message_delta\", (event) => {\n    process.stdout.write(event.data.deltaContent ?? \"\");\n});\n\nawait session.sendAndWait({ prompt: \"Write a quicksort implementation in TypeScript\" });\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.CopilotClient;\nimport com.github.copilot.rpc.*;\n\nvar client = new CopilotClient();\nclient.start().get();\n\nvar session = client.createSession(new SessionConfig()\n    .setModel(\"gpt-5.4\")\n    .setStreaming(true)\n    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)\n).get();\n\nsession.on(AssistantMessageDeltaEvent.class, event -> {\n    System.out.print(event.getData().deltaContent());\n});\n\nsession.sendAndWait(new MessageOptions()\n    .setPrompt(\"Write a quicksort implementation in Java\")).get();\nSystem.out.println();\n\nclient.stop().get();\n```\n\n</div>\n\n</div>\n\n## Справочник по конфигурации\n\n### Опции агентов MAF\n\n| Недвижимость                    | Тип                     | Описание                                                      |\n| ------------------------------- | ----------------------- | ------------------------------------------------------------- |\n| `Instructions` / `instructions` | `string`                | Системный запрос для агента                                   |\n| `Tools` / `tools`               | `AIFunction[]` / `list` | Пользовательские функциональные инструменты, доступные агенту |\n| `Streaming` / `streaming`       | `bool`                  | Включить потоковые ответы                                     |\n| `Model` / `model`               | `string`                | Переопределить модель по умолчанию                            |\n\n### Опции SDK Copilot (прошёл)\n\nВсе стандартные опции [Создайте своё первое приложение на базе Copilot](/ru/copilot/how-tos/copilot-sdk/getting-started) всё ещё доступны при создании базового Copilot-клиента. Обёртка MAF делегирует на SDK под капотом:\n\n| Функция SDK                                                | Поддержка MAF |\n| ---------------------------------------------------------- | ------------- |\n| Кастомные инструменты (`DefineTool` / `AIFunctionFactory`) |               |\n| ✅ Объединение с инструментами MAF                          |               |\n| Серверы MCP                                                |               |\n| ✅ Настроено на клиенте SDK                                 |               |\n| Таможенные агенты / субагенты                              |               |\n| ✅ Доступно внутри агент Copilot                            |               |\n| Бесконечные сессии                                         |               |\n| ✅ Настроено на клиенте SDK                                 |               |\n| Выбор модели                                               |               |\n| ✅ Переопределённое для каждого агента или звонка           |               |\n| Стриминг                                                   |               |\n| ✅ Полная поддержка событий дельта                          |               |\n\n## Лучшие практики\n\n### Выберите правильный уровень интеграции\n\nИспользуйте MAF-обёртку, когда нужно сочинять Copilot вместе с другими провайдерами в организованных рабочих процессах. Если ваше приложение использует только Copilot, отдельный SDK проще и даёт полный контроль:\n\n```typescript\n// Standalone SDK — full control, simpler setup\nimport { CopilotClient } from \"@github/copilot-sdk\";\n\nconst client = new CopilotClient();\nconst session = await client.createSession({\n    model: \"gpt-5.4\",\n    onPermissionRequest: async () => ({ kind: \"approve-once\" }),\n});\nconst response = await session.sendAndWait({ prompt: \"Explain this code\" });\n```\n\n### Держите агентов в фокусе\n\nПри создании рабочих процессов с несколькими агентами дайте каждому агенту конкретную роль с чёткими инструкциями. Избегайте пересечения обязанностей:\n\n```typescript\n// ❌ Too vague — overlapping roles\nconst agents = [\n    { instructions: \"Help with code\" },\n    { instructions: \"Assist with programming\" },\n];\n\n// ✅ Focused — clear separation of concerns\nconst agents = [\n    { instructions: \"Review code for security vulnerabilities. Flag SQL injection, XSS, and auth issues.\" },\n    { instructions: \"Optimize code performance. Focus on algorithmic complexity and memory usage.\" },\n];\n```\n\n### Обработка ошибок на уровне оркестрации\n\nВызовы агентов wrap при обработке ошибок, особенно в рабочих процессах с несколькими агентами, где отказ одного агента не должен блокировать весь конвейер:\n\n<!-- docs-validate: skip -->\n\n```csharp\ntry\n{\n    string result = await pipeline.RunAsync(\"Analyze this module\");\n    Console.WriteLine(result);\n}\ncatch (AgentException ex)\n{\n    Console.Error.WriteLine($\"Agent {ex.AgentName} failed: {ex.Message}\");\n    // Fall back to single-agent mode or retry\n}\n```\n\n## См. также\n\n* [Создайте своё первое приложение на базе Copilot](/ru/copilot/how-tos/copilot-sdk/getting-started): начальная настройка Copilot SDK\n* [Пользовательские агенты и оркестровка субагентов](/ru/copilot/how-tos/copilot-sdk/features/custom-agents): определить специализированные субагенты внутри SDK\n* [Настраиваемые навыки](/ru/copilot/how-tos/copilot-sdk/features/skills): многоразовые модули подсказок\n* [Microsoft документация Agent Framework](https://learn.microsoft.com/en-us/agent-framework/agents/providers/github-copilot): официальная документация MAF для Copilot провайдера\n* [Блог: Создайте AI-агентов с помощью GitHub Copilot SDK и Microsoft Agent Framework](https://devblogs.microsoft.com/semantic-kernel/build-ai-agents-with-github-copilot-sdk-and-microsoft-agent-framework/)"}