{"meta":{"title":"Enlaces de ciclo de vida de sesión","intro":"Los enlaces de ciclo de vida de la sesión permiten responder a los eventos de inicio y finalización de la sesión. Úselos para:","product":"GitHub Copilot","breadcrumbs":[{"href":"/es/copilot","title":"GitHub Copilot"},{"href":"/es/copilot/how-tos","title":"Procedimientos"},{"href":"/es/copilot/how-tos/copilot-sdk","title":"SDK de Copilot"},{"href":"/es/copilot/how-tos/copilot-sdk/hooks","title":"Uso de enlaces"},{"href":"/es/copilot/how-tos/copilot-sdk/hooks/session-lifecycle","title":"Ciclo de vida de la sesión"}],"documentType":"article"},"body":"# Enlaces de ciclo de vida de sesión\n\nLos enlaces de ciclo de vida de la sesión permiten responder a los eventos de inicio y finalización de la sesión. Úselos para:\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n* Inicialización del contexto cuando comienzan las sesiones\n* Limpieza de recursos cuando finalizan las sesiones\n* Seguimiento de métricas de la sesión y análisis\n* Configuración dinámica del comportamiento de la sesión\n\n## Enlace de inicio de sesión {#session-start}\n\nEl `onSessionStart` hook se llama cuando se inicia una sesión (nueva o reanudada).\n\n### Firma de enlace\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### Entrada\n\n| Campo                    | Tipo                 | Descripción                                             |\n| ------------------------ | -------------------- | ------------------------------------------------------- |\n| `timestamp`              | number               | Marca de tiempo de Unix cuando se desencadenó el enlace |\n| `cwd`                    | string               | Directorio de trabajo actual                            |\n| `source`                 |                      |                                                         |\n| `\"startup\"`              |                      |                                                         |\n| \\|                       |                      |                                                         |\n| `\"resume\"`               |                      |                                                         |\n| \\|                       |                      |                                                         |\n| `\"new\"`                  |                      |                                                         |\n| Cómo se inició la sesión |                      |                                                         |\n| `initialPrompt`          | cadena \\| indefinido | El indicador inicial si se proporciona                  |\n\n### Output\n\n| Campo               | Tipo   | Descripción                                |\n| ------------------- | ------ | ------------------------------------------ |\n| `additionalContext` | string | Contexto a añadir al inicio de la sesión   |\n| `modifiedConfig`    | object | Invalidación de la configuración de sesión |\n\n### Ejemplos\n\n#### Agregar contexto del proyecto al principio\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#### Controlar la reanudación de sesiones\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#### Cargar preferencias de usuario\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## Gancho de fin de sesión {#session-end}\n\nEl `onSessionEnd` hook se llama cuando finaliza una sesión.\n\n### Firma de enlace\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### Entrada\n\n| Campo          | Tipo                 | Descripción                                              |\n| -------------- | -------------------- | -------------------------------------------------------- |\n| `timestamp`    | number               | Marca de tiempo de Unix cuando se desencadenó el enlace  |\n| `cwd`          | string               | Directorio de trabajo actual                             |\n| `reason`       | string               | Por qué finalizó la sesión (consulte a continuación)     |\n| `finalMessage` | cadena \\| indefinido | El último mensaje de la sesión                           |\n| `error`        | cadena \\| indefinido | Mensaje de error si la sesión finalizó debido a un error |\n\n#### Motivos de finalización\n\n| Reason        | Descripción                                  |\n| ------------- | -------------------------------------------- |\n| `\"complete\"`  | La sesión se completó normalmente            |\n| `\"error\"`     | La sesión finalizó debido a un error         |\n| `\"abort\"`     | El usuario o el código anularon la sesión    |\n| `\"timeout\"`   | La sesión ha caducado                        |\n| `\"user_exit\"` | El usuario finalizó explícitamente la sesión |\n\n### Output\n\n| Campo            | Tipo      | Descripción                                                       |\n| ---------------- | --------- | ----------------------------------------------------------------- |\n| `suppressOutput` | boolean   | Suprimir la salida final de la sesión                             |\n| `cleanupActions` | string\\[] | Lista de acciones de limpieza que se van a realizar               |\n| `sessionSummary` | string    | Resumen de la sesión para el registro de eventos o las analíticas |\n\n### Ejemplos\n\n#### Seguimiento de las métricas de sesió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#### Limpieza de recursos\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#### Guardar el estado de sesión para reanudar\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#### Resumen de la sesión de registro\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## Hook de parada del agente {#agent-stop}\n\nEl enlace de parada del agente se ejecuta cuando el agente de nivel superior alcanza naturalmente el final de un turno. Es independiente de `onSessionEnd`: la sesión permanece activa, y el hook puede solicitar una nueva intervención del agente.\n\n| Language           | Controlador      |\n| ------------------ | ---------------- |\n| Node.js/TypeScript | `onAgentStop`    |\n| Python             | `on_agent_stop`  |\n| Go                 | `OnAgentStop`    |\n| .NET               | `OnAgentStop`    |\n| Óxido              | `on_agent_stop`  |\n| Java               | `setOnAgentStop` |\n\n### Entrada\n\nLos nombres de los miembros públicos siguen las convenciones de uso de mayúsculas y minúsculas de sus respectivos idiomas:\n\n| Meaning                                                          | Node.js/Python   | Go/.NET          | Óxido              | Java                  |\n| ---------------------------------------------------------------- | ---------------- | ---------------- | ------------------ | --------------------- |\n| Por qué se detuvo el agente, por ejemplo `end_turn`              | `stopReason`     | `StopReason`     | `stop_reason`      | `getStopReason()`     |\n| Ruta de acceso a la transcripción de sesión en disco             | `transcriptPath` | `TranscriptPath` | `transcript_path`  | `getTranscriptPath()` |\n| Si una decisión de bloque anterior ya obligó a esta continuación | `stopHookActive` | `StopHookActive` | `stop_hook_active` | `getStopHookActive()` |\n\n### Output\n\nNo devuelve ninguna salida para permitir que el agente se detenga. Devuelva una decisión de bloque para poner en cola otro mensaje de usuario y continuar:\n\n```json\n{\n  \"decision\": \"block\",\n  \"reason\": \"Run the final validation and fix any failures.\"\n}\n```\n\nUtilice el miembro `active-stop` mencionado anteriormente para evitar volver a bloquear a un agente que ya ha continuado debido a este gancho. El entorno de ejecución también pone un límite al número de decisiones de bloqueo consecutivas.\n\n## procedimientos recomendados\n\n1. **Mantén `onSessionStart` la rapidez** - Los usuarios están esperando a que la sesión esté lista.\n\n2. **Gestiona todos los motivos de finalización** - No des por hecho que las sesiones finalizan correctamente; gestiona los errores y los abortos.\n\n3. **Limpieza de recursos** : use `onSessionEnd` para liberar los recursos asignados durante la sesión.\n\n4. **Almacene el estado mínimo** - Si realiza un seguimiento de los datos de sesión, manténgalos ligeros.\n\n5. **Convertir la depuración en idempotente** - `onSessionEnd` podría no ejecutarse si el proceso se bloquea.\n\n## Consulte también\n\n* [Uso de enlaces](/es/copilot/how-tos/copilot-sdk/hooks)\n* [Gancho de manejo de errores](/es/copilot/how-tos/copilot-sdk/hooks/error-handling)\n* [Guía de depuración](/es/copilot/how-tos/copilot-sdk/troubleshooting/debugging)"}