# SDK Session Management

> **Version Requirement**: This document is for CodeBuddy Agent SDK v0.1.0 and above.

This document explains how to manage sessions in the SDK, including obtaining session IDs, resuming sessions, forking sessions, and multi-turn conversations.

## Table of Contents

- [Overview](#overview)
- [Obtaining Session ID](#obtaining-session-id)
- [Resuming Sessions](#resuming-sessions)
- [Multi-turn Conversations](#multi-turn-conversations)
- [Related Documentation](#related-documentation)

## Overview

Session is a core concept in CodeBuddy, used for:

- **Maintaining conversation context**: AI can remember previous content in multi-turn conversations
- **Supporting session resumption**: Can continue from where you left off
- **Supporting session forking**: Create branches from a certain point to explore different directions

Each session has a unique `session_id` that can be used for subsequent resumption.

## Obtaining Session ID

When a session starts, the SDK returns an initialization message of type `system` containing the `session_id`.

### Using query API

::: code-group

```typescript [TypeScript]
import { query } from '@tencent-ai/agent-sdk';

let sessionId: string | undefined;

const q = query({
  prompt: 'Help me build a web application',
  options: {
    model: 'deepseek-v3.1'
  }
});

for await (const message of q) {
  // Get session_id from initialization message
  if (message.type === 'system' && message.subtype === 'init') {
    sessionId = message.session_id;
    console.log(`Session ID: ${sessionId}`);
    // Save sessionId for later resumption
  }

  console.log(message);
}

// sessionId can be saved to database or file
```

```python [Python]
import asyncio
from codebuddy_agent_sdk import query, CodeBuddyAgentOptions, SystemMessage

session_id = None

async def main():
    global session_id

    options = CodeBuddyAgentOptions(model="deepseek-v3.1")

    async for message in query(prompt="Help me build a web application", options=options):
        # Get session_id from initialization message
        if isinstance(message, SystemMessage):
            session_id = message.data.get("session_id")
            print(f"Session ID: {session_id}")
            # Save session_id for later resumption

        print(message)

asyncio.run(main())
# session_id can be saved to database or file
```

:::

### Using v2 Session API (TypeScript)

```typescript
import { unstable_v2_createSession } from '@tencent-ai/agent-sdk';

const session = unstable_v2_createSession({
  model: 'deepseek-v3.1'
});

await session.send('Help me build a web application');

for await (const message of session.stream()) {
  if (message.type === 'system' && message.subtype === 'init') {
    console.log(`Session ID: ${message.session_id}`);
  }
  console.log(message);
}

// Use session.sessionId to get (available after initialization)
console.log(`Session ID: ${session.sessionId}`);

session.close();
```

### Using Client API (Python)

```python
from codebuddy_agent_sdk import CodeBuddySDKClient, CodeBuddyAgentOptions

async def main():
    options = CodeBuddyAgentOptions(model="deepseek-v3.1")

    async with CodeBuddySDKClient(options=options) as client:
        await client.query("Help me build a web application")

        async for message in client.receive_response():
            if isinstance(message, SystemMessage):
                print(f"Session ID: {message.data.get('session_id')}")
            print(message)
```

## Resuming Sessions

Using a previously saved `session_id` allows you to resume a session and continue the previous conversation.

### Using resume option

::: code-group

```typescript [TypeScript - query API]
import { query } from '@tencent-ai/agent-sdk';

// Use previously saved session_id
const savedSessionId = 'abc123-xyz789';

const q = query({
  prompt: 'Continue our previous work',
  options: {
    model: 'deepseek-v3.1',
    resume: savedSessionId  // Resume specified session
  }
});

for await (const message of q) {
  console.log(message);
}
```

```typescript [TypeScript - v2 API]
import { unstable_v2_resumeSession } from '@tencent-ai/agent-sdk';

// Use previously saved session_id
const savedSessionId = 'abc123-xyz789';

const session = unstable_v2_resumeSession(savedSessionId, {
  model: 'deepseek-v3.1'
});

await session.send('Continue our previous work');

for await (const message of session.stream()) {
  console.log(message);
}

session.close();
```

```python [Python]
from codebuddy_agent_sdk import query, CodeBuddyAgentOptions

# Use previously saved session_id
saved_session_id = "abc123-xyz789"

options = CodeBuddyAgentOptions(
    model="deepseek-v3.1",
    resume=saved_session_id  # Resume specified session
)

async for message in query(prompt="Continue our previous work", options=options):
    print(message)
```

:::

### Continuing the most recent session

Using the `continue` / `continue_conversation` option automatically continues the most recent session:

::: code-group

```typescript [TypeScript]
const q = query({
  prompt: 'Continue',
  options: {
    model: 'deepseek-v3.1',
    continue: true  // Continue most recent session
  }
});
```

```python [Python]
options = CodeBuddyAgentOptions(
    model="deepseek-v3.1",
    continue_conversation=True  # Continue most recent session
)
```

:::

## Multi-turn Conversations

Multi-turn conversations allow multiple interactions within the same session while maintaining context coherence.

### TypeScript: Using query API

Each new query call uses `resume` to resume the session:

```typescript
import { query } from '@tencent-ai/agent-sdk';

async function multiTurnWithQuery() {
  let sessionId: string;

  // First turn
  const q1 = query({
    prompt: 'Help me create a React project',
    options: { model: 'deepseek-v3.1' }
  });

  for await (const msg of q1) {
    if (msg.type === 'system' && msg.subtype === 'init') {
      sessionId = msg.session_id;
    }
    if (msg.type === 'result') {
      console.log('First turn completed');
    }
  }

  // Second turn (resume session)
  const q2 = query({
    prompt: 'Add a user login page',
    options: {
      model: 'deepseek-v3.1',
      resume: sessionId
    }
  });

  for await (const msg of q2) {
    if (msg.type === 'result') {
      console.log('Second turn completed');
    }
  }

  // Third turn
  const q3 = query({
    prompt: 'Add form validation',
    options: {
      model: 'deepseek-v3.1',
      resume: sessionId
    }
  });

  for await (const msg of q3) {
    console.log(msg);
  }
}
```

### TypeScript: Using v2 Session API

v2 API provides a more concise multi-turn conversation experience:

```typescript
import { unstable_v2_createSession } from '@tencent-ai/agent-sdk';

async function multiTurnWithSession() {
  const session = unstable_v2_createSession({
    model: 'deepseek-v3.1'
  });

  try {
    // First turn
    await session.send('Help me create a React project');
    for await (const msg of session.stream()) {
      console.log(msg);
    }

    // Second turn (automatically maintains context)
    await session.send('Add a user login page');
    for await (const msg of session.stream()) {
      console.log(msg);
    }

    // Third turn
    await session.send('Add form validation');
    for await (const msg of session.stream()) {
      console.log(msg);
    }

  } finally {
    session.close();
  }
}
```

### Python: Using CodeBuddySDKClient

```python
from codebuddy_agent_sdk import CodeBuddySDKClient, CodeBuddyAgentOptions

async def multi_turn_conversation():
    options = CodeBuddyAgentOptions(model="deepseek-v3.1")

    async with CodeBuddySDKClient(options=options) as client:
        # First turn
        await client.query("Help me create a React project")
        async for msg in client.receive_response():
            print(msg)

        # Second turn (automatically maintains context)
        await client.query("Add a user login page")
        async for msg in client.receive_response():
            print(msg)

        # Third turn
        await client.query("Add form validation")
        async for msg in client.receive_response():
            print(msg)
```

## Related Documentation

- [SDK Overview](sdk.md) - Quick start and usage examples
- [SDK Permission Control](sdk-permissions.md) - Permission modes and canUseTool
- [TypeScript SDK Reference](sdk-typescript.md) - Complete API reference
- [Python SDK Reference](sdk-python.md) - Complete API reference
