{"meta":{"title":"Session Lifecycle Hooks","intro":"Mit Sitzungslebenszyklus-Hooks können Sie auf Start- und Endereignisse der Sitzung reagieren. Verwenden Sie sie für:","product":"GitHub Copilot","breadcrumbs":[{"href":"/de/enterprise-cloud@latest/copilot","title":"GitHub Copilot"},{"href":"/de/enterprise-cloud@latest/copilot/how-tos","title":"Vorgehensweisen"},{"href":"/de/enterprise-cloud@latest/copilot/how-tos/copilot-sdk","title":"Copilot SDK"},{"href":"/de/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/hooks","title":"Verwenden Sie Hooks"},{"href":"/de/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/hooks/session-lifecycle","title":"Sitzungslebenszyklus"}],"documentType":"article"},"body":"# Session Lifecycle Hooks\n\nMit Sitzungslebenszyklus-Hooks können Sie auf Start- und Endereignisse der Sitzung reagieren. Verwenden Sie sie für:\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n* Initialisieren des Kontexts, wenn Sitzungen beginnen\n* Bereinigen von Ressourcen beim Beenden von Sitzungen\n* Sitzungsmetriken und Analysen nachverfolgen\n* Dynamisches Konfigurieren des Sitzungsverhaltens\n\n## Sitzungsstart-Hook {#session-start}\n\nDer `onSessionStart` Hook wird aufgerufen, wenn eine Sitzung beginnt (neu oder fortgesetzt).\n\n### Hook-Signatur\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### Eingabe\n\n| Feld                            | Typ                         | Beschreibung                                         |\n| ------------------------------- | --------------------------- | ---------------------------------------------------- |\n| `timestamp`                     | number                      | Unix-Zeitstempel, zu dem der Hook ausgelöst wurde    |\n| `cwd`                           | string                      | Aktuelles Arbeitsverzeichnis                         |\n| `source`                        |                             |                                                      |\n| `\"startup\"`                     |                             |                                                      |\n| \\|                              |                             |                                                      |\n| `\"resume\"`                      |                             |                                                      |\n| \\|                              |                             |                                                      |\n| `\"new\"`                         |                             |                                                      |\n| Wie die Sitzung gestartet wurde |                             |                                                      |\n| `initialPrompt`                 | Zeichenfolge \\| undefiniert | Die anfängliche Eingabeaufforderung, falls angegeben |\n\n### Output\n\n| Feld                | Typ    | Beschreibung                             |\n| ------------------- | ------ | ---------------------------------------- |\n| `additionalContext` | string | Kontext zum Hinzufügen am Sitzungsstart  |\n| `modifiedConfig`    | Objekt | Sitzungskonfiguration außer Kraft setzen |\n\n### Beispiele\n\n#### Projektkontext zu Beginn hinzufügen\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#### Verwaltung der Sitzungswiederaufnahme\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#### Laden von Benutzereinstellungen\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 für das Sitzungsende {#session-end}\n\nDer `onSessionEnd` Hook wird aufgerufen, wenn eine Sitzung endet.\n\n### Hook-Signatur\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### Eingabe\n\n| Feld           | Typ                         | Beschreibung                                                         |\n| -------------- | --------------------------- | -------------------------------------------------------------------- |\n| `timestamp`    | number                      | Unix-Zeitstempel, zu dem der Hook ausgelöst wurde                    |\n| `cwd`          | string                      | Aktuelles Arbeitsverzeichnis                                         |\n| `reason`       | string                      | Warum die Sitzung beendet wurde (siehe unten)                        |\n| `finalMessage` | Zeichenfolge \\| undefiniert | Die letzte Nachricht aus der Sitzung                                 |\n| `error`        | Zeichenfolge \\| undefiniert | Fehlermeldung, wenn die Sitzung aufgrund eines Fehlers beendet wurde |\n\n#### Endgründe\n\n| Grund         | Beschreibung                                                      |\n| ------------- | ----------------------------------------------------------------- |\n| `\"complete\"`  | Die Sitzung wurde normal abgeschlossen.                           |\n| `\"error\"`     | Sitzung aufgrund eines Fehlers beendet                            |\n| `\"abort\"`     | Die Sitzung wurde durch den Benutzer oder durch Code abgebrochen. |\n| `\"timeout\"`   | Timeout für die Sitzung                                           |\n| `\"user_exit\"` | Der Benutzer hat die Sitzung explizit beendet.                    |\n\n### Output\n\n| Feld             | Typ       | Beschreibung                                            |\n| ---------------- | --------- | ------------------------------------------------------- |\n| `suppressOutput` | boolean   | Endgültige Sitzungsausgabe unterdrücken                 |\n| `cleanupActions` | string\\[] | Liste der auszuführenden Bereinigungsaktionen           |\n| `sessionSummary` | string    | Zusammenfassung der Sitzung für Protokollierung/Analyse |\n\n### Beispiele\n\n#### Nachverfolgen von Sitzungsmetriken\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#### Bereinigen von Ressourcen\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#### Sitzungsstatus zum Fortsetzen speichern\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#### Protokollsitzungszusammenfassung\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-Stopp-Hook {#agent-stop}\n\nDer Agent-Stopp-Hook wird ausgeführt, wenn der Agent der obersten Ebene auf natürliche Weise das Ende einer Interaktion erreicht. Er ist getrennt von `onSessionEnd`: Die Sitzung bleibt aktiv, und der Hook kann einen weiteren Agent-Turn anfordern.\n\n| Sprache              | Handler          |\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### Eingabe\n\nDie Namen der öffentlichen Mitglieder folgen den Groß-/Kleinschreibungskonventionen der einzelnen Sprachen:\n\n| Bedeutung                                                                          | Node.js/Python   | Gehe zu /.NET    | Rust               | Java                  |\n| ---------------------------------------------------------------------------------- | ---------------- | ---------------- | ------------------ | --------------------- |\n| Warum der Agent gestoppt wurde, z. B. `end_turn`                                   | `stopReason`     | `StopReason`     | `stop_reason`      | `getStopReason()`     |\n| Pfad zum Transkript der On-Disk-Sitzung                                            | `transcriptPath` | `TranscriptPath` | `transcript_path`  | `getTranscriptPath()` |\n| Gibt an, ob eine frühere Blockentscheidung diese Fortsetzung bereits erzwungen hat | `stopHookActive` | `StopHookActive` | `stop_hook_active` | `getStopHookActive()` |\n\n### Output\n\nGibt keine Ausgabe zurück, damit der Agent beendet werden kann. Geben Sie eine Blockierentscheidung zurück, um eine weitere Benutzernachricht in die Warteschlange zu stellen und fortzufahren:\n\n```json\n{\n  \"decision\": \"block\",\n  \"reason\": \"Run the final validation and fix any failures.\"\n}\n```\n\nVerwenden Sie das oben angegebene Active-Stop-Element, um zu vermeiden, dass ein Agent, der aufgrund dieses Hooks bereits weitergelaufen ist, erneut blockiert wird. Die Laufzeit begrenzt auch aufeinander folgende Blockierungsentscheidungen.\n\n## Bewährte Methoden\n\n1. **Sorgen Sie dafür, dass `onSessionStart` schnell bleibt** – Die Benutzer warten darauf, dass die Sitzung einsatzbereit ist.\n\n2. **Berücksichtigen Sie alle Gründe für die Beendigung** – Gehen Sie nicht davon aus, dass Sitzungen immer ordnungsgemäß beendet werden; behandeln Sie auch Fehler und Abbrüche.\n\n3. **Ressourcen freigeben** – Verwenden Sie `onSessionEnd`, um alle während der Sitzung zugewiesenen Ressourcen freizugeben.\n\n4. **Speichern Sie so wenig Status wie möglich** - Wenn Sie Sitzungsdaten verfolgen, halten Sie sie so schlank wie möglich.\n\n5. **Machen Sie die Bereinigung idempotent** - `onSessionEnd` wird möglicherweise nicht aufgerufen, wenn der Prozess abstürzt.\n\n## Siehe auch\n\n* [Verwenden Sie Hooks](/de/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/hooks)\n* [Fehlerbehandlung Hook](/de/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/hooks/error-handling)\n* [Debughandbuch](/de/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/troubleshooting/debugging)"}