# Крючки жизненного цикла сессии

Крючки жизненного цикла сессии позволяют реагировать на события начала и окончания сессии. Используйте их для:

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

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

* Инициализация контекста при начале сессий
* Очищайте ресурсы после окончания сессий
* Отслеживайте метрики сессий и аналитику
* Динамическая настройка поведения сессии

## Hook Session start {#session-start}

`onSessionStart` Крюк вызывается при начале сессии (новой или возобновлённой).

### Сигнатура крюка

<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
type SessionStartHandler = (
  input: SessionStartHookInput,
  invocation: HookInvocation
) => Promise<SessionStartHookOutput | null | undefined>;
```

</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
SessionStartHandler = Callable[
    [SessionStartHookInput, dict[str, str]],
    Awaitable[SessionStartHookOutput | None]
]
```

</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
type SessionStartHandler func(
    input SessionStartHookInput,
    invocation HookInvocation,
) (*SessionStartHookOutput, error)
```

</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
public delegate Task<SessionStartHookOutput?> SessionStartHandler(
    SessionStartHookInput input,
    HookInvocation invocation);
```

</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
@FunctionalInterface
public interface SessionStartHandler {
    CompletableFuture<SessionStartHookOutput> handle(
        SessionStartHookInput input,
        HookInvocation invocation);
}
```

</div>

</div>

### Input

| Поле                | Тип                    | Description                                  |
| ------------------- | ---------------------- | -------------------------------------------- |
| `timestamp`         | number                 | Временная метка Unix, когда срабатывал крюк  |
| `cwd`               | string                 | Текущий рабочий справочник                   |
| `source`            |                        |                                              |
| `"startup"`         |                        |                                              |
| \|                  |                        |                                              |
| `"resume"`          |                        |                                              |
| \|                  |                        |                                              |
| `"new"`             |                        |                                              |
| Как началась сессия |                        |                                              |
| `initialPrompt`     | Строка \| неопределена | Первоначальный запрос, если был предоставлен |

### Выходные данные

| Поле                | Тип    | Description                               |
| ------------------- | ------ | ----------------------------------------- |
| `additionalContext` | string | Контекст для добавления при начале сессии |
| `modifiedConfig`    | object | Конфигурация сессии переопределения       |

### Примеры

#### Добавьте контекст проекта в начале

<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
const session = await client.createSession({
  hooks: {
    onSessionStart: async (input, invocation) => {
      console.log(`Session ${invocation.sessionId} started (${input.source})`);
      
      const projectInfo = await detectProjectType(input.cwd);
      
      return {
        additionalContext: `
This is a ${projectInfo.type} project.
Main language: ${projectInfo.language}
Package manager: ${projectInfo.packageManager}
        `.trim(),
      };
    },
  },
});
```

</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.session import PermissionHandler

async def on_session_start(input_data, invocation):
    print(f"Session {invocation['session_id']} started ({input_data['source']})")
    
    project_info = await detect_project_type(input_data["cwd"])
    
    return {
        "additionalContext": f"""
This is a {project_info['type']} project.
Main language: {project_info['language']}
Package manager: {project_info['packageManager']}
        """.strip()
    }

session = await client.create_session(on_permission_request=PermissionHandler.approve_all, hooks={"on_session_start": on_session_start})
```

</div>

</div>

#### Обработка возобновления сессии

```typescript
const session = await client.createSession({
  hooks: {
    onSessionStart: async (input, invocation) => {
      if (input.source === "resume") {
        // Load previous session state
        const previousState = await loadSessionState(invocation.sessionId);
        
        return {
          additionalContext: `
Session resumed. Previous context:
- Last topic: ${previousState.lastTopic}
- Open files: ${previousState.openFiles.join(", ")}
          `.trim(),
        };
      }
      return null;
    },
  },
});
```

#### Загрузка пользовательских предпочтений

```typescript
const session = await client.createSession({
  hooks: {
    onSessionStart: async () => {
      const preferences = await loadUserPreferences();
      
      const contextParts = [];
      
      if (preferences.language) {
        contextParts.push(`Preferred language: ${preferences.language}`);
      }
      if (preferences.codeStyle) {
        contextParts.push(`Code style: ${preferences.codeStyle}`);
      }
      if (preferences.verbosity === "concise") {
        contextParts.push("Keep responses brief and to the point.");
      }
      
      return {
        additionalContext: contextParts.join("\n"),
      };
    },
  },
});
```

## Hook end session {#session-end}

`onSessionEnd` Крюк вызывается, когда сессия заканчивается.

### Сигнатура крюка

<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
type SessionEndHandler = (
  input: SessionEndHookInput,
  invocation: HookInvocation
) => Promise<SessionEndHookOutput | null | undefined>;
```

</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
SessionEndHandler = Callable[
    [SessionEndHookInput, dict[str, str]],
    Awaitable[SessionEndHookOutput | None]
]
```

</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
type SessionEndHandler func(
    input SessionEndHookInput,
    invocation HookInvocation,
) (*SessionEndHookOutput, error)
```

</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
public delegate Task<SessionEndHookOutput?> SessionEndHandler(
    SessionEndHookInput input,
    HookInvocation invocation);
```

</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
@FunctionalInterface
public interface SessionEndHandler {
    CompletableFuture<SessionEndHookOutput> handle(
        SessionEndHookInput input,
        HookInvocation invocation);
}
```

</div>

</div>

### Input

| Поле           | Тип                    | Description                                               |
| -------------- | ---------------------- | --------------------------------------------------------- |
| `timestamp`    | number                 | Временная метка Unix, когда срабатывал крюк               |
| `cwd`          | string                 | Текущий рабочий справочник                                |
| `reason`       | string                 | Почему сессия закончилась (см. ниже)                      |
| `finalMessage` | Строка \| неопределена | Последнее сообщение с сессии                              |
| `error`        | Строка \| неопределена | Сообщение об ошибке, если сессия завершилась из-за ошибки |

#### Конечные причины

| Reason        | Description                                  |
| ------------- | -------------------------------------------- |
| `"complete"`  | Сессия прошла нормально                      |
| `"error"`     | Сессия завершилась из-за ошибки              |
| `"abort"`     | Сессия была прервана пользователем или кодом |
| `"timeout"`   | Время сессии окончено                        |
| `"user_exit"` | Пользователь явно завершил сессию            |

### Выходные данные

| Поле             | Тип       | Description                                        |
| ---------------- | --------- | -------------------------------------------------- |
| `suppressOutput` | boolean   | Подавить итоговый выход сессии                     |
| `cleanupActions` | string\[] | Список действий по очистке                         |
| `sessionSummary` | string    | Краткое содержание сессии по логированию/аналитике |

### Примеры

#### Метрики трековых сессий

<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
const sessionStartTimes = new Map<string, number>();

const session = await client.createSession({
  hooks: {
    onSessionStart: async (input, invocation) => {
      sessionStartTimes.set(invocation.sessionId, input.timestamp);
      return null;
    },
    onSessionEnd: async (input, invocation) => {
      const startTime = sessionStartTimes.get(invocation.sessionId);
      const duration = startTime ? input.timestamp - startTime : 0;
      
      await recordMetrics({
        sessionId: invocation.sessionId,
        duration,
        endReason: input.reason,
      });
      
      sessionStartTimes.delete(invocation.sessionId);
      return null;
    },
  },
});
```

</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.session import PermissionHandler

session_start_times = {}

async def on_session_start(input_data, invocation):
    session_start_times[invocation["session_id"]] = input_data["timestamp"]
    return None

async def on_session_end(input_data, invocation):
    start_time = session_start_times.get(invocation["session_id"])
    duration = input_data["timestamp"] - start_time if start_time else 0
    
    await record_metrics({
        "session_id": invocation["session_id"],
        "duration": duration,
        "end_reason": input_data["reason"],
    })
    
    session_start_times.pop(invocation["session_id"], None)
    return None

session = await client.create_session(on_permission_request=PermissionHandler.approve_all, hooks={
        "on_session_start": on_session_start,
        "on_session_end": on_session_end,
    })
```

</div>

</div>

#### Очистите ресурсы

```typescript
const sessionResources = new Map<string, { tempFiles: string[] }>();

const session = await client.createSession({
  hooks: {
    onSessionStart: async (input, invocation) => {
      sessionResources.set(invocation.sessionId, { tempFiles: [] });
      return null;
    },
    onSessionEnd: async (input, invocation) => {
      const resources = sessionResources.get(invocation.sessionId);
      
      if (resources) {
        // Clean up temp files
        for (const file of resources.tempFiles) {
          await fs.unlink(file).catch(() => {});
        }
        sessionResources.delete(invocation.sessionId);
      }
      
      console.log(`Session ${invocation.sessionId} ended: ${input.reason}`);
      return null;
    },
  },
});
```

#### Сохранить состояние сессии для резюме

```typescript
const session = await client.createSession({
  hooks: {
    onSessionEnd: async (input, invocation) => {
      if (input.reason !== "error") {
        // Save state for potential resume
        await saveSessionState(invocation.sessionId, {
          endTime: input.timestamp,
          cwd: input.cwd,
          reason: input.reason,
        });
      }
      return null;
    },
  },
});
```

#### Краткое описание сессии журнала

```typescript
const sessionData: Record<string, { prompts: number; tools: number; startTime: number }> = {};

const session = await client.createSession({
  hooks: {
    onSessionStart: async (input, invocation) => {
      sessionData[invocation.sessionId] = { 
        prompts: 0, 
        tools: 0, 
        startTime: input.timestamp 
      };
      return null;
    },
    onUserPromptSubmitted: async (_, invocation) => {
      sessionData[invocation.sessionId].prompts++;
      return null;
    },
    onPreToolUse: async (_, invocation) => {
      sessionData[invocation.sessionId].tools++;
      return { permissionDecision: "allow" };
    },
    onSessionEnd: async (input, invocation) => {
      const data = sessionData[invocation.sessionId];
      console.log(`
Session Summary:
  ID: ${invocation.sessionId}
  Duration: ${(input.timestamp - data.startTime) / 1000}s
  Prompts: ${data.prompts}
  Tool calls: ${data.tools}
  End reason: ${input.reason}
      `.trim());
      
      delete sessionData[invocation.sessionId];
      return null;
    },
  },
});
```

## Остановка агента {#agent-stop}

Перехватчик агента запускается, когда агент верхнего уровня естественно достигает конца поворота. Он отличается от `onSessionEnd`: сеанс остается активным, и перехватчик может запросить другой поворот агента.

| Язык                 | Обработчик       |
| -------------------- | ---------------- |
| Node.js / TypeScript | `onAgentStop`    |
| Python               | `on_agent_stop`  |
| Go                   | `OnAgentStop`    |
| .NET                 | `OnAgentStop`    |
| Rust                 | `on_agent_stop`  |
| Java                 | `setOnAgentStop` |

### Input

Имена общедоступных членов следуют соглашениям о регистре каждого языка:

| Значение                                                      | Node.js / Python | Go / .NET        | Rust               | Java                  |
| ------------------------------------------------------------- | ---------------- | ---------------- | ------------------ | --------------------- |
| Почему агент остановлен, например `end_turn`                  | `stopReason`     | `StopReason`     | `stop_reason`      | `getStopReason()`     |
| Путь к транскрибированию сеанса на диске                      | `transcriptPath` | `TranscriptPath` | `transcript_path`  | `getTranscriptPath()` |
| Если предыдущее решение о блоке уже заставило это продолжение | `stopHookActive` | `StopHookActive` | `stop_hook_active` | `getStopHookActive()` |

### Выходные данные

Не возвращайте выходные данные, чтобы разрешить агенту остановиться. Верните блокное решение, чтобы заквещать другое сообщение пользователя и продолжить:

```json
{
  "decision": "block",
  "reason": "Run the final validation and fix any failures."
}
```

Используйте элемент активной остановки, указанный выше, чтобы избежать многократной блокировки агента, который уже продолжался из-за этого перехватчика. Среда выполнения также блокирует последовательные решения блокировок.

## Лучшие практики

1. **Будьте `onSessionStart` быстрыми** — пользователи ждут, пока сессия будет готова.

2. **Решайте все конечные причины** — не предполагайте, что сессии заканчиваются чисто; Обрабатывайте ошибки и отмены.

3. **Очистка ресурсов** — используйте `onSessionEnd` для освобождения выделенных ресурсов во время сессии.

4. **Сохраняйте минимальное состояние** — если отслеживаете данные сессии, держите его лёгким.

5. **Сделайте очистку идемпотентной** - `onSessionEnd` Если процесс вылетит, может не вызвать.

## См. также

* [Используйте крючки](/ru/copilot/how-tos/copilot-sdk/hooks)
* [Крюк для обработки ошибок](/ru/copilot/how-tos/copilot-sdk/hooks/error-handling)
* [Руководство по отладке](/ru/copilot/how-tos/copilot-sdk/troubleshooting/debugging)