{"meta":{"title":"セッションライフサイクルフック","intro":"セッション ライフサイクル フックを使用すると、セッションの開始イベントと終了イベントに応答できます。 次の場合に使用します。","product":"GitHub Copilot","breadcrumbs":[{"href":"/ja/copilot","title":"GitHub Copilot"},{"href":"/ja/copilot/how-tos","title":"方法"},{"href":"/ja/copilot/how-tos/copilot-sdk","title":"Copilot SDK"},{"href":"/ja/copilot/how-tos/copilot-sdk/hooks","title":"フックを使用する"},{"href":"/ja/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## セッション開始フック {#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### 入力\n\n| フィールド           | タイプ        | 説明                          |\n| --------------- | ---------- | --------------------------- |\n| `timestamp`     | number     | フックがトリガーされたときの Unix タイムスタンプ |\n| `cwd`           | 文字列        | 現在の作業ディレクトリ                 |\n| `source`        |            |                             |\n| `\"startup\"`     |            |                             |\n| \\|              |            |                             |\n| `\"resume\"`      |            |                             |\n| \\|              |            |                             |\n| `\"new\"`         |            |                             |\n| セッションの開始方法      |            |                             |\n| `initialPrompt` | 文字列 \\| 未定義 | 最初のプロンプト (指定されている場合)        |\n\n### アウトプット\n\n| フィールド               | タイプ    | 説明                  |\n| ------------------- | ------ | ------------------- |\n| `additionalContext` | 文字列    | セッション開始時に追加するコンテキスト |\n| `modifiedConfig`    | オブジェクト | セッション構成をオーバーライドする   |\n\n### Examples\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## セッション 終了フック {#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### 入力\n\n| フィールド          | タイプ        | 説明                            |\n| -------------- | ---------- | ----------------------------- |\n| `timestamp`    | number     | フックがトリガーされたときの Unix タイムスタンプ   |\n| `cwd`          | 文字列        | 現在の作業ディレクトリ                   |\n| `reason`       | 文字列        | セッションが終了した理由 (下記参照)           |\n| `finalMessage` | 文字列 \\| 未定義 | セッションからの最後のメッセージ              |\n| `error`        | 文字列 \\| 未定義 | エラーが原因でセッションが終了した場合のエラー メッセージ |\n\n#### 終了の理由\n\n| 理由            | 説明                          |\n| ------------- | --------------------------- |\n| `\"complete\"`  | セッションが正常に完了しました             |\n| `\"error\"`     | エラーが原因でセッションが終了しました         |\n| `\"abort\"`     | ユーザーまたはコードによってセッションが中止されました |\n| `\"timeout\"`   | セッションがタイムアウトしました            |\n| `\"user_exit\"` | ユーザーがセッションを明示的に終了した         |\n\n### アウトプット\n\n| フィールド            | タイプ       | 説明                   |\n| ---------------- | --------- | -------------------- |\n| `suppressOutput` | boolean   | 最後のセッション出力を抑制する      |\n| `cleanupActions` | string\\[] | 実行するクリーンアップ アクションの一覧 |\n| `sessionSummary` | 文字列       | ログ記録/分析のセッションの概要     |\n\n### Examples\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| Language            | ハンドラー            |\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### 入力\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このフックによりすでに続行したエージェントが繰り返しブロックされるのを防ぐため、上記の active-stop member を使用してください。 ランタイムでは、連続したブロック判定にも上限が設けられています。\n\n## ベスト プラクティス\n\n1. \\*\\*\n   `onSessionStart` を高速に保つ\\*\\* - ユーザーはセッションの準備が整うのを待っています。\n\n2. **すべての終了理由を処理する** - セッションが正常に終了することを想定しないでください。エラーと中止を処理します。\n\n3. **リソースのクリーンアップ** - `onSessionEnd` を使用して、セッション中に割り当てられたリソースを解放します。\n\n4. **最小状態を格納** する - セッション データを追跡する場合は、軽量に保ちます。\n\n5. **クリーンアップ処理を冪等にする** - `onSessionEnd` は、プロセスがクラッシュした場合に呼び出されない可能性があります。\n\n## こちらも参照ください\n\n* [フックを使用する](/ja/copilot/how-tos/copilot-sdk/hooks)\n* [エラー処理フック](/ja/copilot/how-tos/copilot-sdk/hooks/error-handling)\n* [デバッグ ガイド](/ja/copilot/how-tos/copilot-sdk/troubleshooting/debugging)"}