{"meta":{"title":"Session resume and persistence","intro":"This guide walks you through the SDK's session persistence capabilities—how to pause work, resume it later, and manage sessions in production environments.","product":"GitHub Copilot","breadcrumbs":[{"href":"/en/copilot","title":"GitHub Copilot"},{"href":"/en/copilot/how-tos","title":"How-tos"},{"href":"/en/copilot/how-tos/copilot-sdk","title":"Copilot SDK"},{"href":"/en/copilot/how-tos/copilot-sdk/features","title":"Features"},{"href":"/en/copilot/how-tos/copilot-sdk/features/session-persistence","title":"Session Persistence"}],"documentType":"article"},"body":"# Session resume and persistence\n\nThis guide walks you through the SDK's session persistence capabilities—how to pause work, resume it later, and manage sessions in production environments.\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n## How sessions work\n\nWhen you create a session, the Copilot CLI maintains conversation history, tool state, and planning context. By default, this state lives in memory and disappears when the session ends. With persistence enabled, you can resume sessions across restarts, container migrations, or even different client instances.\n\n![Diagram: Flowchart showing the described process.](/assets/images/help/copilot/copilot-sdk/features-session-persistence-diagram-0.png)\n\n| State      | What happens                        |\n| ---------- | ----------------------------------- |\n| **Create** | `session_id` assigned               |\n| **Active** | Send prompts, tool calls, responses |\n| **Paused** | State saved to disk                 |\n| **Resume** | State loaded from disk              |\n\n## Quick start: creating a resumable session\n\nThe key to resumable sessions is providing your own `session_id`. Without one, the SDK generates a random ID and the session can't be resumed later.\n\n### TypeScript\n\n```typescript\nimport { CopilotClient } from \"@github/copilot-sdk\";\n\nconst client = new CopilotClient();\n\n// Create a session with a meaningful ID\nconst session = await client.createSession({\n  sessionId: \"user-123-task-456\",\n  model: \"gpt-5.2-codex\",\n});\n\n// Do some work...\nawait session.sendAndWait({ prompt: \"Analyze my codebase\" });\n\n// Session state is automatically persisted\n// You can safely close the client\n```\n\n### Python\n\n```python\nfrom copilot import CopilotClient\nfrom copilot.session import PermissionHandler\n\nclient = CopilotClient()\nawait client.start()\n\n# Create a session with a meaningful ID\nsession = await client.create_session(on_permission_request=PermissionHandler.approve_all, model=\"gpt-5.2-codex\", session_id=\"user-123-task-456\")\n\n# Do some work...\nawait session.send_and_wait(\"Analyze my codebase\")\n\n# Session state is automatically persisted\n```\n\n### Go\n\n```golang\nctx := context.Background()\nclient := copilot.NewClient(nil)\n\n// Create a session with a meaningful ID\nsession, _ := client.CreateSession(ctx, &copilot.SessionConfig{\n    SessionID: \"user-123-task-456\",\n    Model:     \"gpt-5.2-codex\",\n})\n\n// Do some work...\nsession.SendAndWait(ctx, copilot.MessageOptions{Prompt: \"Analyze my codebase\"})\n\n// Session state is automatically persisted\n```\n\n### C# (.NET)\n\n```csharp\nusing GitHub.Copilot;\n\nvar client = new CopilotClient();\n\n// Create a session with a meaningful ID\nvar session = await client.CreateSessionAsync(new SessionConfig\n{\n    SessionId = \"user-123-task-456\",\n    Model = \"gpt-5.2-codex\",\n});\n\n// Do some work...\nawait session.SendAndWaitAsync(new MessageOptions { Prompt = \"Analyze my codebase\" });\n\n// Session state is automatically persisted\n```\n\n## Resuming a session\n\nLater—minutes, hours, or even days—you can resume the session from where you left off.\n\n![Diagram: Flowchart showing the described process.](/assets/images/help/copilot/copilot-sdk/features-session-persistence-diagram-1.png)\n\n### TypeScript\n\n```typescript\n// Resume from a different client instance (or after restart)\nconst session = await client.resumeSession(\"user-123-task-456\");\n\n// Continue where you left off\nawait session.sendAndWait({ prompt: \"What did we discuss earlier?\" });\n```\n\n### Python\n\n```python\n# Resume from a different client instance (or after restart)\nsession = await client.resume_session(\"user-123-task-456\", on_permission_request=PermissionHandler.approve_all)\n\n# Continue where you left off\nawait session.send_and_wait(\"What did we discuss earlier?\")\n```\n\n### Go\n\n```golang\nctx := context.Background()\n\n// Resume from a different client instance (or after restart)\nsession, _ := client.ResumeSession(ctx, \"user-123-task-456\", nil)\n\n// Continue where you left off\nsession.SendAndWait(ctx, copilot.MessageOptions{Prompt: \"What did we discuss earlier?\"})\n```\n\n### C# (.NET)\n\n```csharp\n// Resume from a different client instance (or after restart)\nvar session = await client.ResumeSessionAsync(\"user-123-task-456\");\n\n// Continue where you left off\nawait session.SendAndWaitAsync(new MessageOptions { Prompt = \"What did we discuss earlier?\" });\n```\n\n## Resume options\n\nWhen resuming a session, you can optionally reconfigure many settings. This is useful when you need to change the model, update tool configurations, or modify behavior.\n\n| Option             | Description                                              |\n| ------------------ | -------------------------------------------------------- |\n| `model`            | Change the model for the resumed session                 |\n| `systemMessage`    | Override or extend the system prompt                     |\n| `availableTools`   | Restrict which tools are available                       |\n| `excludedTools`    | Disable specific tools                                   |\n| `provider`         | Re-provide BYOK credentials (required for BYOK sessions) |\n| `reasoningEffort`  | Adjust reasoning effort level                            |\n| `streaming`        | Enable/disable streaming responses                       |\n| `workingDirectory` | Change the working directory                             |\n| `configDir`        | Override configuration directory                         |\n| `mcpServers`       | Configure MCP servers                                    |\n| `customAgents`     | Configure custom agents                                  |\n| `agent`            | Pre-select a custom agent by name                        |\n| `skillDirectories` | Directories to load skills from                          |\n| `disabledSkills`   | Skills to disable                                        |\n| `infiniteSessions` | Configure infinite session behavior                      |\n\n### Example: changing model on resume\n\n```typescript\n// Resume with a different model\nconst session = await client.resumeSession(\"user-123-task-456\", {\n  model: \"claude-sonnet-4\",  // Switch to a different model\n  reasoningEffort: \"high\",   // Increase reasoning effort\n});\n```\n\n## Using BYOK (bring your own key) with resumed sessions\n\nWhen using your own API keys, you must re-provide the provider configuration when resuming. API keys are never persisted to disk for security reasons.\n\n```typescript\n// Original session with BYOK\nconst session = await client.createSession({\n  sessionId: \"user-123-task-456\",\n  model: \"gpt-5.2-codex\",\n  provider: {\n    type: \"azure\",\n    endpoint: \"https://my-resource.openai.azure.com\",\n    apiKey: process.env.AZURE_OPENAI_KEY,\n    deploymentId: \"my-gpt-deployment\",\n  },\n});\n\n// When resuming, you MUST re-provide the provider config\nconst resumed = await client.resumeSession(\"user-123-task-456\", {\n  provider: {\n    type: \"azure\",\n    endpoint: \"https://my-resource.openai.azure.com\",\n    apiKey: process.env.AZURE_OPENAI_KEY,  // Required again\n    deploymentId: \"my-gpt-deployment\",\n  },\n});\n```\n\n## What gets persisted?\n\nSession state is saved to `~/.copilot/session-state/{sessionId}/`:\n\n```text\n~/.copilot/session-state/\n└── user-123-task-456/\n    ├── checkpoints/           # Conversation history snapshots\n    │   ├── 001.json          # Initial state\n    │   ├── 002.json          # After first interaction\n    │   └── ...               # Incremental checkpoints\n    ├── plan.md               # Agent's planning state (if any)\n    └── files/                # Session artifacts\n        ├── analysis.md       # Files the agent created\n        └── notes.txt         # Working documents\n```\n\n| Data                 | Persisted? | Notes                     |\n| -------------------- | ---------- | ------------------------- |\n| Conversation history | ✅ Yes      | Full message thread       |\n| Tool call results    | ✅ Yes      | Cached for context        |\n| Agent planning state | ✅ Yes      | `plan.md` file            |\n| Session artifacts    | ✅ Yes      | In `files/` directory     |\n| Provider/API keys    | ❌ No       | Security: must re-provide |\n| In-memory tool state | ❌ No       | Tools should be stateless |\n\n## Session ID best practices\n\nChoose session IDs that encode ownership and purpose. This makes auditing and cleanup much easier.\n\n| Pattern                           | Example                   | Use Case                         |\n| --------------------------------- | ------------------------- | -------------------------------- |\n| ❌ `abc123`                        | Random IDs                | Hard to audit, no ownership info |\n| ✅ `user-{userId}-{taskId}`        | `user-alice-pr-review-42` | Multi-user apps                  |\n| ✅ `tenant-{tenantId}-{workflow}`  | `tenant-acme-onboarding`  | Multi-tenant SaaS                |\n| ✅ `{userId}-{taskId}-{timestamp}` | `alice-deploy-1706932800` | Time-based cleanup               |\n\n**Benefits of structured IDs:**\n\n* Easy to audit: \"Show all sessions for user alice\"\n* Easy to clean up: \"Delete all sessions older than X\"\n* Natural access control: Parse user ID from session ID\n\n### Example: generating session IDs\n\n```typescript\nfunction createSessionId(userId: string, taskType: string): string {\n  const timestamp = Date.now();\n  return `${userId}-${taskType}-${timestamp}`;\n}\n\nconst sessionId = createSessionId(\"alice\", \"code-review\");\n// → \"alice-code-review-1706932800000\"\n```\n\n```python\nimport time\n\ndef create_session_id(user_id: str, task_type: str) -> str:\n    timestamp = int(time.time())\n    return f\"{user_id}-{task_type}-{timestamp}\"\n\nsession_id = create_session_id(\"alice\", \"code-review\")\n# → \"alice-code-review-1706932800\"\n```\n\n## Managing session lifecycle\n\n### Listing active sessions\n\n```typescript\n// List all sessions\nconst sessions = await client.listSessions();\nconsole.log(`Found ${sessions.length} sessions`);\n\nfor (const session of sessions) {\n  console.log(`- ${session.sessionId} (created: ${session.createdAt})`);\n}\n\n// Filter sessions by repository\nconst repoSessions = await client.listSessions({ repository: \"owner/repo\" });\n```\n\n### Cleaning up old sessions\n\n```typescript\nasync function cleanupExpiredSessions(maxAgeMs: number) {\n  const sessions = await client.listSessions();\n  const now = Date.now();\n  \n  for (const session of sessions) {\n    const age = now - new Date(session.createdAt).getTime();\n    if (age > maxAgeMs) {\n      await client.deleteSession(session.sessionId);\n      console.log(`Deleted expired session: ${session.sessionId}`);\n    }\n  }\n}\n\n// Clean up sessions older than 24 hours\nawait cleanupExpiredSessions(24 * 60 * 60 * 1000);\n```\n\n### Disconnecting from a session (`disconnect`)\n\nWhen a task completes, disconnect from the session explicitly rather than waiting for timeouts. This releases in-memory resources but **preserves session data on disk**, so the session can still be resumed later:\n\n```typescript\ntry {\n  // Do work...\n  await session.sendAndWait({ prompt: \"Complete the task\" });\n  \n  // Task complete — release in-memory resources (session can be resumed later)\n  await session.disconnect();\n} catch (error) {\n  // Clean up even on error\n  await session.disconnect();\n  throw error;\n}\n```\n\nEach SDK also provides idiomatic automatic cleanup patterns:\n\n| Language       | Pattern                      | Example                                                                             |\n| -------------- | ---------------------------- | ----------------------------------------------------------------------------------- |\n| **TypeScript** | `Symbol.asyncDispose`        | `await using session = await client.createSession(config);`                         |\n| **Python**     | `async with` context manager | `async with await client.create_session(on_permission_request=handler) as session:` |\n| **C#**         | `IAsyncDisposable`           | `await using var session = await client.CreateSessionAsync(config);`                |\n| **Go**         | `defer`                      | `defer session.Disconnect()`                                                        |\n\n> \\[!NOTE]\n> `destroy()` is deprecated in favor of `disconnect()`. Existing code using `destroy()` will continue to work but should be migrated.\n\n### Permanently deleting a session (`deleteSession`)\n\nTo permanently remove a session and all its data from disk (conversation history, planning state, artifacts), use `deleteSession`. This is irreversible—the session **cannot** be resumed after deletion:\n\n```typescript\n// Permanently remove session data\nawait client.deleteSession(\"user-123-task-456\");\n```\n\n> **`disconnect()` vs `deleteSession()`:** `disconnect()` releases in-memory resources but keeps session data on disk for later resumption. `deleteSession()` permanently removes everything, including files on disk.\n\n## Automatic cleanup: idle timeout\n\nBy default, sessions have **no idle timeout** and live indefinitely until explicitly disconnected or deleted. You can optionally configure a server-wide idle timeout via `CopilotClientOptions.sessionIdleTimeoutSeconds`:\n\n```typescript\nconst client = new CopilotClient({\n  sessionIdleTimeoutSeconds: 30 * 60, // 30 minutes\n});\n```\n\nWhen a timeout is configured, sessions without activity for that duration are automatically cleaned up. Set to `0` or omit to disable.\n\n> \\[!NOTE]\n> This option only applies when the SDK spawns the runtime process. When connecting to an existing server via `cliUrl`, the server's own timeout configuration applies.\n\n![Diagram: Flowchart showing the described process.](/assets/images/help/copilot/copilot-sdk/features-session-persistence-diagram-2.png)\n\nSessions with active work (running commands, background agents) are always protected from idle cleanup, regardless of the timeout setting.\n\nListen for idle events to react to session inactivity:\n\n```typescript\nsession.on(\"session.idle\", (event) => {\n  console.log(`Session idle for ${event.idleDurationMs}ms`);\n});\n```\n\n## Deployment patterns\n\n### Pattern 1: one CLI server per user (recommended)\n\nBest for: Strong isolation, multi-tenant environments, Azure Dynamic Sessions.\n\n![Diagram: Flowchart showing the described process.](/assets/images/help/copilot/copilot-sdk/features-session-persistence-diagram-3.png)\n\n**Benefits:** ✅ Complete isolation | ✅ Simple security | ✅ Easy scaling\n\n### Pattern 2: shared CLI server (resource efficient)\n\nBest for: Internal tools, trusted environments, resource-constrained setups.\n\n![Diagram: Flowchart showing the described process.](/assets/images/help/copilot/copilot-sdk/features-session-persistence-diagram-4.png)\n\n**Requirements:**\n\n* ⚠️ Unique session IDs per user\n* ⚠️ Application-level access control\n* ⚠️ Session ID validation before operations\n\n```typescript\n// Application-level access control for shared CLI\nasync function resumeSessionWithAuth(\n  client: CopilotClient,\n  sessionId: string,\n  currentUserId: string\n): Promise<Session> {\n  // Parse user from session ID\n  const [sessionUserId] = sessionId.split(\"-\");\n  \n  if (sessionUserId !== currentUserId) {\n    throw new Error(\"Access denied: session belongs to another user\");\n  }\n  \n  return client.resumeSession(sessionId);\n}\n```\n\n## Azure dynamic sessions\n\nFor serverless/container deployments where containers can restart or migrate:\n\n### Mount persistent storage\n\nThe session state directory must be mounted to persistent storage:\n\n```yaml\n# Azure Container Instance example\ncontainers:\n  - name: copilot-agent\n    image: my-agent:latest\n    volumeMounts:\n      - name: session-storage\n        mountPath: /home/app/.copilot/session-state\n\nvolumes:\n  - name: session-storage\n    azureFile:\n      shareName: copilot-sessions\n      storageAccountName: myaccount\n```\n\n![Diagram: Flowchart showing the described process.](/assets/images/help/copilot/copilot-sdk/features-session-persistence-diagram-5.png)\n\n**Session survives container restarts!**\n\n## Infinite sessions for long-running workflows\n\nFor workflows that might exceed context limits, enable infinite sessions with automatic compaction:\n\n```typescript\nconst session = await client.createSession({\n  sessionId: \"long-workflow-123\",\n  infiniteSessions: {\n    enabled: true,\n    backgroundCompactionThreshold: 0.80,  // Start compaction at 80% context\n    bufferExhaustionThreshold: 0.95,      // Block at 95% if needed\n  },\n});\n```\n\n> \\[!NOTE]\n> Thresholds are context utilization ratios (0.0-1.0), not absolute token counts. See the [SDK and CLI compatibility](/en/copilot/how-tos/copilot-sdk/troubleshooting/compatibility) for details.\n\n## Limitations and considerations\n\n| Limitation                   | Description                                    | Mitigation                                              |\n| ---------------------------- | ---------------------------------------------- | ------------------------------------------------------- |\n| **BYOK re-authentication**   | API keys aren't persisted                      | Store keys in your secret manager; provide on resume    |\n| **Writable storage**         | `~/.copilot/session-state/` must be writable   | Mount persistent volume in containers                   |\n| **No session locking**       | Concurrent access to same session is undefined | Implement application-level locking or queue            |\n| **Tool state not persisted** | In-memory tool state is lost                   | Design tools to be stateless or persist their own state |\n\n### Handling concurrent access\n\nThe SDK doesn't provide built-in session locking. If multiple clients might access the same session:\n\n```typescript\n// Option 1: Application-level locking with Redis\nimport Redis from \"ioredis\";\n\nconst redis = new Redis();\n\nasync function withSessionLock<T>(\n  sessionId: string,\n  fn: () => Promise<T>\n): Promise<T> {\n  const lockKey = `session-lock:${sessionId}`;\n  const acquired = await redis.set(lockKey, \"locked\", \"NX\", \"EX\", 300);\n  \n  if (!acquired) {\n    throw new Error(\"Session is in use by another client\");\n  }\n  \n  try {\n    return await fn();\n  } finally {\n    await redis.del(lockKey);\n  }\n}\n\n// Usage\nawait withSessionLock(\"user-123-task-456\", async () => {\n  const session = await client.resumeSession(\"user-123-task-456\");\n  await session.sendAndWait({ prompt: \"Continue the task\" });\n});\n```\n\n## Summary\n\n| Feature                            | How to Use                                                                                            |\n| ---------------------------------- | ----------------------------------------------------------------------------------------------------- |\n| **Create resumable session**       | Provide your own `sessionId`                                                                          |\n| **Resume session**                 | `client.resumeSession(sessionId)`                                                                     |\n| **BYOK resume**                    | Re-provide `provider` config                                                                          |\n| **List sessions**                  | `client.listSessions(filter?)`                                                                        |\n| **Disconnect from active session** | `session.disconnect()`—releases in-memory resources; session data on disk is preserved for resumption |\n| **Delete session permanently**     | `client.deleteSession(sessionId)`—permanently removes all session data from disk; cannot be resumed   |\n| **Containerized deployment**       | Mount `~/.copilot/session-state/` to persistent storage                                               |\n\n## Next steps\n\n* [Session hooks](/en/copilot/how-tos/copilot-sdk/hooks/hooks-overview) - Customize session behavior with hooks\n* [SDK and CLI compatibility](/en/copilot/how-tos/copilot-sdk/troubleshooting/compatibility) - SDK vs CLI feature comparison\n* [Debugging guide](/en/copilot/how-tos/copilot-sdk/troubleshooting/debugging) - Troubleshoot session issues"}