{"meta":{"title":"Крючки жизненного цикла сессии","intro":"Крючки жизненного цикла сессии позволяют реагировать на события начала и окончания сессии. Используйте их для:","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/hooks","title":"Используйте крючки"},{"href":"/ru/copilot/how-tos/copilot-sdk/hooks/session-lifecycle","title":"Жизненный цикл сессии"}],"documentType":"article"},"body":"# Крючки жизненного цикла сессии\n\nКрючки жизненного цикла сессии позволяют реагировать на события начала и окончания сессии. Используйте их для:\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n* Инициализация контекста при начале сессий\n* Очищайте ресурсы после окончания сессий\n* Отслеживайте метрики сессий и аналитику\n* Динамическая настройка поведения сессии\n\n## Hook Session start {#session-start}\n\n`onSessionStart` Крюк вызывается при начале сессии (новой или возобновлённой).\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\ntype SessionStartHandler = (\n  input: SessionStartHookInput,\n  invocation: HookInvocation\n) => Promise<SessionStartHookOutput | null | undefined>;\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\nSessionStartHandler = Callable[\n    [SessionStartHookInput, dict[str, str]],\n    Awaitable[SessionStartHookOutput | None]\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\ntype SessionStartHandler func(\n    input SessionStartHookInput,\n    invocation HookInvocation,\n) (*SessionStartHookOutput, error)\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\npublic delegate Task<SessionStartHookOutput?> SessionStartHandler(\n    SessionStartHookInput input,\n    HookInvocation invocation);\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\n@FunctionalInterface\npublic interface SessionStartHandler {\n    CompletableFuture<SessionStartHookOutput> handle(\n        SessionStartHookInput input,\n        HookInvocation invocation);\n}\n```\n\n</div>\n\n</div>\n\n### Input\n\n| Поле                | Тип                    | Description                                  |\n| ------------------- | ---------------------- | -------------------------------------------- |\n| `timestamp`         | number                 | Временная метка Unix, когда срабатывал крюк  |\n| `cwd`               | string                 | Текущий рабочий справочник                   |\n| `source`            |                        |                                              |\n| `\"startup\"`         |                        |                                              |\n| \\|                  |                        |                                              |\n| `\"resume\"`          |                        |                                              |\n| \\|                  |                        |                                              |\n| `\"new\"`             |                        |                                              |\n| Как началась сессия |                        |                                              |\n| `initialPrompt`     | Строка \\| неопределена | Первоначальный запрос, если был предоставлен |\n\n### Выходные данные\n\n| Поле                | Тип    | Description                               |\n| ------------------- | ------ | ----------------------------------------- |\n| `additionalContext` | string | Контекст для добавления при начале сессии |\n| `modifiedConfig`    | object | Конфигурация сессии переопределения       |\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\nconst session = await client.createSession({\n  hooks: {\n    onSessionStart: async (input, invocation) => {\n      console.log(`Session ${invocation.sessionId} started (${input.source})`);\n      \n      const projectInfo = await detectProjectType(input.cwd);\n      \n      return {\n        additionalContext: `\nThis is a ${projectInfo.type} project.\nMain language: ${projectInfo.language}\nPackage manager: ${projectInfo.packageManager}\n        `.trim(),\n      };\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.session import PermissionHandler\n\nasync def on_session_start(input_data, invocation):\n    print(f\"Session {invocation['session_id']} started ({input_data['source']})\")\n    \n    project_info = await detect_project_type(input_data[\"cwd\"])\n    \n    return {\n        \"additionalContext\": f\"\"\"\nThis is a {project_info['type']} project.\nMain language: {project_info['language']}\nPackage manager: {project_info['packageManager']}\n        \"\"\".strip()\n    }\n\nsession = await client.create_session(on_permission_request=PermissionHandler.approve_all, hooks={\"on_session_start\": on_session_start})\n```\n\n</div>\n\n</div>\n\n#### Обработка возобновления сессии\n\n```typescript\nconst session = await client.createSession({\n  hooks: {\n    onSessionStart: async (input, invocation) => {\n      if (input.source === \"resume\") {\n        // Load previous session state\n        const previousState = await loadSessionState(invocation.sessionId);\n        \n        return {\n          additionalContext: `\nSession resumed. Previous context:\n- Last topic: ${previousState.lastTopic}\n- Open files: ${previousState.openFiles.join(\", \")}\n          `.trim(),\n        };\n      }\n      return null;\n    },\n  },\n});\n```\n\n#### Загрузка пользовательских предпочтений\n\n```typescript\nconst session = await client.createSession({\n  hooks: {\n    onSessionStart: async () => {\n      const preferences = await loadUserPreferences();\n      \n      const contextParts = [];\n      \n      if (preferences.language) {\n        contextParts.push(`Preferred language: ${preferences.language}`);\n      }\n      if (preferences.codeStyle) {\n        contextParts.push(`Code style: ${preferences.codeStyle}`);\n      }\n      if (preferences.verbosity === \"concise\") {\n        contextParts.push(\"Keep responses brief and to the point.\");\n      }\n      \n      return {\n        additionalContext: contextParts.join(\"\\n\"),\n      };\n    },\n  },\n});\n```\n\n## Hook end session {#session-end}\n\n`onSessionEnd` Крюк вызывается, когда сессия заканчивается.\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\ntype SessionEndHandler = (\n  input: SessionEndHookInput,\n  invocation: HookInvocation\n) => Promise<SessionEndHookOutput | null | undefined>;\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\nSessionEndHandler = Callable[\n    [SessionEndHookInput, dict[str, str]],\n    Awaitable[SessionEndHookOutput | None]\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\ntype SessionEndHandler func(\n    input SessionEndHookInput,\n    invocation HookInvocation,\n) (*SessionEndHookOutput, error)\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\npublic delegate Task<SessionEndHookOutput?> SessionEndHandler(\n    SessionEndHookInput input,\n    HookInvocation invocation);\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\n@FunctionalInterface\npublic interface SessionEndHandler {\n    CompletableFuture<SessionEndHookOutput> handle(\n        SessionEndHookInput input,\n        HookInvocation invocation);\n}\n```\n\n</div>\n\n</div>\n\n### Input\n\n| Поле           | Тип                    | Description                                               |\n| -------------- | ---------------------- | --------------------------------------------------------- |\n| `timestamp`    | number                 | Временная метка Unix, когда срабатывал крюк               |\n| `cwd`          | string                 | Текущий рабочий справочник                                |\n| `reason`       | string                 | Почему сессия закончилась (см. ниже)                      |\n| `finalMessage` | Строка \\| неопределена | Последнее сообщение с сессии                              |\n| `error`        | Строка \\| неопределена | Сообщение об ошибке, если сессия завершилась из-за ошибки |\n\n#### Конечные причины\n\n| Reason        | Description                                  |\n| ------------- | -------------------------------------------- |\n| `\"complete\"`  | Сессия прошла нормально                      |\n| `\"error\"`     | Сессия завершилась из-за ошибки              |\n| `\"abort\"`     | Сессия была прервана пользователем или кодом |\n| `\"timeout\"`   | Время сессии окончено                        |\n| `\"user_exit\"` | Пользователь явно завершил сессию            |\n\n### Выходные данные\n\n| Поле             | Тип       | Description                                        |\n| ---------------- | --------- | -------------------------------------------------- |\n| `suppressOutput` | boolean   | Подавить итоговый выход сессии                     |\n| `cleanupActions` | string\\[] | Список действий по очистке                         |\n| `sessionSummary` | string    | Краткое содержание сессии по логированию/аналитике |\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\nconst sessionStartTimes = new Map<string, number>();\n\nconst session = await client.createSession({\n  hooks: {\n    onSessionStart: async (input, invocation) => {\n      sessionStartTimes.set(invocation.sessionId, input.timestamp);\n      return null;\n    },\n    onSessionEnd: async (input, invocation) => {\n      const startTime = sessionStartTimes.get(invocation.sessionId);\n      const duration = startTime ? input.timestamp - startTime : 0;\n      \n      await recordMetrics({\n        sessionId: invocation.sessionId,\n        duration,\n        endReason: input.reason,\n      });\n      \n      sessionStartTimes.delete(invocation.sessionId);\n      return null;\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.session import PermissionHandler\n\nsession_start_times = {}\n\nasync def on_session_start(input_data, invocation):\n    session_start_times[invocation[\"session_id\"]] = input_data[\"timestamp\"]\n    return None\n\nasync def on_session_end(input_data, invocation):\n    start_time = session_start_times.get(invocation[\"session_id\"])\n    duration = input_data[\"timestamp\"] - start_time if start_time else 0\n    \n    await record_metrics({\n        \"session_id\": invocation[\"session_id\"],\n        \"duration\": duration,\n        \"end_reason\": input_data[\"reason\"],\n    })\n    \n    session_start_times.pop(invocation[\"session_id\"], None)\n    return None\n\nsession = await client.create_session(on_permission_request=PermissionHandler.approve_all, hooks={\n        \"on_session_start\": on_session_start,\n        \"on_session_end\": on_session_end,\n    })\n```\n\n</div>\n\n</div>\n\n#### Очистите ресурсы\n\n```typescript\nconst sessionResources = new Map<string, { tempFiles: string[] }>();\n\nconst session = await client.createSession({\n  hooks: {\n    onSessionStart: async (input, invocation) => {\n      sessionResources.set(invocation.sessionId, { tempFiles: [] });\n      return null;\n    },\n    onSessionEnd: async (input, invocation) => {\n      const resources = sessionResources.get(invocation.sessionId);\n      \n      if (resources) {\n        // Clean up temp files\n        for (const file of resources.tempFiles) {\n          await fs.unlink(file).catch(() => {});\n        }\n        sessionResources.delete(invocation.sessionId);\n      }\n      \n      console.log(`Session ${invocation.sessionId} ended: ${input.reason}`);\n      return null;\n    },\n  },\n});\n```\n\n#### Сохранить состояние сессии для резюме\n\n```typescript\nconst session = await client.createSession({\n  hooks: {\n    onSessionEnd: async (input, invocation) => {\n      if (input.reason !== \"error\") {\n        // Save state for potential resume\n        await saveSessionState(invocation.sessionId, {\n          endTime: input.timestamp,\n          cwd: input.cwd,\n          reason: input.reason,\n        });\n      }\n      return null;\n    },\n  },\n});\n```\n\n#### Краткое описание сессии журнала\n\n```typescript\nconst sessionData: Record<string, { prompts: number; tools: number; startTime: number }> = {};\n\nconst session = await client.createSession({\n  hooks: {\n    onSessionStart: async (input, invocation) => {\n      sessionData[invocation.sessionId] = { \n        prompts: 0, \n        tools: 0, \n        startTime: input.timestamp \n      };\n      return null;\n    },\n    onUserPromptSubmitted: async (_, invocation) => {\n      sessionData[invocation.sessionId].prompts++;\n      return null;\n    },\n    onPreToolUse: async (_, invocation) => {\n      sessionData[invocation.sessionId].tools++;\n      return { permissionDecision: \"allow\" };\n    },\n    onSessionEnd: async (input, invocation) => {\n      const data = sessionData[invocation.sessionId];\n      console.log(`\nSession Summary:\n  ID: ${invocation.sessionId}\n  Duration: ${(input.timestamp - data.startTime) / 1000}s\n  Prompts: ${data.prompts}\n  Tool calls: ${data.tools}\n  End reason: ${input.reason}\n      `.trim());\n      \n      delete sessionData[invocation.sessionId];\n      return null;\n    },\n  },\n});\n```\n\n## Остановка агента {#agent-stop}\n\nПерехватчик агента запускается, когда агент верхнего уровня естественно достигает конца поворота. Он отличается от `onSessionEnd`: сеанс остается активным, и перехватчик может запросить другой поворот агента.\n\n| Язык                 | Обработчик       |\n| -------------------- | ---------------- |\n| Node.js / TypeScript | `onAgentStop`    |\n| Python               | `on_agent_stop`  |\n| Go                   | `OnAgentStop`    |\n| .NET                 | `OnAgentStop`    |\n| Rust                 | `on_agent_stop`  |\n| Java                 | `setOnAgentStop` |\n\n### Input\n\nИмена общедоступных членов следуют соглашениям о регистре каждого языка:\n\n| Значение                                                      | Node.js / Python | Go / .NET        | Rust               | Java                  |\n| ------------------------------------------------------------- | ---------------- | ---------------- | ------------------ | --------------------- |\n| Почему агент остановлен, например `end_turn`                  | `stopReason`     | `StopReason`     | `stop_reason`      | `getStopReason()`     |\n| Путь к транскрибированию сеанса на диске                      | `transcriptPath` | `TranscriptPath` | `transcript_path`  | `getTranscriptPath()` |\n| Если предыдущее решение о блоке уже заставило это продолжение | `stopHookActive` | `StopHookActive` | `stop_hook_active` | `getStopHookActive()` |\n\n### Выходные данные\n\nНе возвращайте выходные данные, чтобы разрешить агенту остановиться. Верните блокное решение, чтобы заквещать другое сообщение пользователя и продолжить:\n\n```json\n{\n  \"decision\": \"block\",\n  \"reason\": \"Run the final validation and fix any failures.\"\n}\n```\n\nИспользуйте элемент активной остановки, указанный выше, чтобы избежать многократной блокировки агента, который уже продолжался из-за этого перехватчика. Среда выполнения также блокирует последовательные решения блокировок.\n\n## Лучшие практики\n\n1. **Будьте `onSessionStart` быстрыми** — пользователи ждут, пока сессия будет готова.\n\n2. **Решайте все конечные причины** — не предполагайте, что сессии заканчиваются чисто; Обрабатывайте ошибки и отмены.\n\n3. **Очистка ресурсов** — используйте `onSessionEnd` для освобождения выделенных ресурсов во время сессии.\n\n4. **Сохраняйте минимальное состояние** — если отслеживаете данные сессии, держите его лёгким.\n\n5. **Сделайте очистку идемпотентной** - `onSessionEnd` Если процесс вылетит, может не вызвать.\n\n## См. также\n\n* [Используйте крючки](/ru/copilot/how-tos/copilot-sdk/hooks)\n* [Крюк для обработки ошибок](/ru/copilot/how-tos/copilot-sdk/hooks/error-handling)\n* [Руководство по отладке](/ru/copilot/how-tos/copilot-sdk/troubleshooting/debugging)"}