> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/block/goose/llms.txt
> Use this file to discover all available pages before exploring further.

# Session

> Session management and persistence in Goose

The Session system provides SQLite-backed persistence for conversations, extensions, and metadata in Goose.

## Overview

Sessions store:

* Conversation history (messages)
* Extension states (enabled MCP servers)
* Token usage metrics
* Working directory and metadata
* Recipe configurations

## Core Types

### Session

Represents a Goose conversation session.

```rust theme={null}
pub struct Session {
    pub id: String,
    pub working_dir: PathBuf,
    pub name: String,
    pub user_set_name: bool,
    pub session_type: SessionType,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub extension_data: ExtensionData,
    pub total_tokens: Option<i32>,
    pub input_tokens: Option<i32>,
    pub output_tokens: Option<i32>,
    pub accumulated_total_tokens: Option<i32>,
    pub accumulated_input_tokens: Option<i32>,
    pub accumulated_output_tokens: Option<i32>,
    pub schedule_id: Option<String>,
    pub recipe: Option<Recipe>,
    pub user_recipe_values: Option<HashMap<String, String>>,
    pub conversation: Option<Conversation>,
    pub message_count: usize,
    pub provider_name: Option<String>,
    pub model_config: Option<ModelConfig>,
}
```

**Source:** `crates/goose/src/session/session_manager.rs:70-96`

<ResponseField name="id" type="String" required>
  Unique session identifier (format: `YYYYMMDD_N`)
</ResponseField>

<ResponseField name="working_dir" type="PathBuf" required>
  Directory where session tools execute
</ResponseField>

<ResponseField name="name" type="String" required>
  Human-readable session name
</ResponseField>

<ResponseField name="user_set_name" type="bool" required>
  Whether name was set by user (vs auto-generated)
</ResponseField>

<ResponseField name="session_type" type="SessionType" required>
  Type of session (User, Scheduled, SubAgent, Hidden, Terminal, Gateway)
</ResponseField>

<ResponseField name="extension_data" type="ExtensionData" required>
  JSON blob storing extension states
</ResponseField>

<ResponseField name="conversation" type="Option<Conversation>">
  Full message history (only loaded with `include_messages=true`)
</ResponseField>

<ResponseField name="total_tokens" type="Option<i32>">
  Tokens used in the last LLM call
</ResponseField>

<ResponseField name="accumulated_total_tokens" type="Option<i32>">
  Total tokens used across all LLM calls in this session
</ResponseField>

### SessionType

```rust theme={null}
pub enum SessionType {
    User,       // Standard user session
    Scheduled,  // Scheduled task session
    SubAgent,   // Sub-agent spawned session
    Hidden,     // Hidden from UI
    Terminal,   // Terminal-only session
    Gateway,    // Gateway session
}
```

**Source:** `crates/goose/src/session/session_manager.rs:25-35`

## SessionManager

Manages session lifecycle and persistence.

```rust theme={null}
pub struct SessionManager {
    storage: Arc<SessionStorage>,
}
```

**Source:** `crates/goose/src/session/session_manager.rs:246-248`

### Constructor

#### instance()

Get the global SessionManager singleton.

```rust theme={null}
pub fn instance() -> Self
```

**Returns:** Shared SessionManager instance

**Source:** `crates/goose/src/session/session_manager.rs:257-261`

**Example:**

```rust theme={null}
let session_manager = SessionManager::instance();
```

#### new()

Create a SessionManager with custom data directory.

```rust theme={null}
pub fn new(data_dir: PathBuf) -> Self
```

<ParamField path="data_dir" type="PathBuf" required>
  Directory for session database
</ParamField>

**Source:** `crates/goose/src/session/session_manager.rs:251-255`

## CRUD Operations

### create\_session()

Create a new session.

```rust theme={null}
pub async fn create_session(
    &self,
    working_dir: PathBuf,
    name: String,
    session_type: SessionType,
) -> Result<Session>
```

<ParamField path="working_dir" type="PathBuf" required>
  Initial working directory for tools
</ParamField>

<ParamField path="name" type="String" required>
  Initial session name
</ParamField>

<ParamField path="session_type" type="SessionType" required>
  Type of session to create
</ParamField>

**Returns:** Newly created Session

**Source:** `crates/goose/src/session/session_manager.rs:267-276`

**Example:**

```rust theme={null}
let session = session_manager.create_session(
    PathBuf::from("/home/user/project"),
    "My Project".to_string(),
    SessionType::User,
).await?;
```

### get\_session()

Retrieve a session by ID.

```rust theme={null}
pub async fn get_session(&self, id: &str, include_messages: bool) -> Result<Session>
```

<ParamField path="id" type="&str" required>
  Session ID to retrieve
</ParamField>

<ParamField path="include_messages" type="bool" required>
  Whether to load full conversation history
</ParamField>

**Returns:** Session with optional conversation

**Source:** `crates/goose/src/session/session_manager.rs:278-280`

**Example:**

```rust theme={null}
// Get session without messages (faster)
let session = session_manager.get_session("20260304_1", false).await?;

// Get session with full conversation
let session = session_manager.get_session("20260304_1", true).await?;
if let Some(conversation) = session.conversation {
    println!("Messages: {}", conversation.len());
}
```

### list\_sessions()

List all user and scheduled sessions.

```rust theme={null}
pub async fn list_sessions(&self) -> Result<Vec<Session>>
```

**Returns:** Vector of sessions sorted by updated\_at descending

**Source:** `crates/goose/src/session/session_manager.rs:298-300`

### list\_sessions\_by\_types()

List sessions filtered by type.

```rust theme={null}
pub async fn list_sessions_by_types(&self, types: &[SessionType]) -> Result<Vec<Session>>
```

<ParamField path="types" type="&[SessionType]" required>
  Session types to include
</ParamField>

**Source:** `crates/goose/src/session/session_manager.rs:302-304`

**Example:**

```rust theme={null}
let sessions = session_manager.list_sessions_by_types(&[
    SessionType::User,
    SessionType::SubAgent,
]).await?;
```

### delete\_session()

Delete a session and all its messages.

```rust theme={null}
pub async fn delete_session(&self, id: &str) -> Result<()>
```

<ParamField path="id" type="&str" required>
  Session ID to delete
</ParamField>

**Source:** `crates/goose/src/session/session_manager.rs:306-308`

## Message Management

### add\_message()

Append a message to a session.

```rust theme={null}
pub async fn add_message(&self, id: &str, message: &Message) -> Result<()>
```

<ParamField path="id" type="&str" required>
  Session ID
</ParamField>

<ParamField path="message" type="&Message" required>
  Message to append
</ParamField>

**Source:** `crates/goose/src/session/session_manager.rs:290-292`

**Example:**

```rust theme={null}
let message = Message::user().with_text("Hello, Goose!");
session_manager.add_message("20260304_1", &message).await?;
```

### replace\_conversation()

Replace entire conversation history (used for compaction).

```rust theme={null}
pub async fn replace_conversation(&self, id: &str, conversation: &Conversation) -> Result<()>
```

<ParamField path="id" type="&str" required>
  Session ID
</ParamField>

<ParamField path="conversation" type="&Conversation" required>
  New conversation to store
</ParamField>

**Source:** `crates/goose/src/session/session_manager.rs:294-296`

### truncate\_conversation()

Delete messages after a timestamp.

```rust theme={null}
pub async fn truncate_conversation(&self, session_id: &str, timestamp: i64) -> Result<()>
```

<ParamField path="session_id" type="&str" required>
  Session ID
</ParamField>

<ParamField path="timestamp" type="i64" required>
  Unix timestamp (seconds) - messages >= this timestamp are deleted
</ParamField>

**Source:** `crates/goose/src/session/session_manager.rs:326-330`

## Update Operations

### update()

Get a builder for updating session fields.

```rust theme={null}
pub fn update(&self, id: &str) -> SessionUpdateBuilder<'_>
```

<ParamField path="id" type="&str" required>
  Session ID to update
</ParamField>

**Returns:** Builder for chaining updates

**Source:** `crates/goose/src/session/session_manager.rs:282-284`

### SessionUpdateBuilder

Builder pattern for updating sessions.

**Source:** `crates/goose/src/session/session_manager.rs:98-117`

#### user\_provided\_name()

Set user-provided name.

```rust theme={null}
pub fn user_provided_name(mut self, name: impl Into<String>) -> Self
```

**Source:** `crates/goose/src/session/session_manager.rs:154-161`

#### system\_generated\_name()

Set auto-generated name.

```rust theme={null}
pub fn system_generated_name(mut self, name: impl Into<String>) -> Self
```

**Source:** `crates/goose/src/session/session_manager.rs:163-170`

#### extension\_data()

Update extension state.

```rust theme={null}
pub fn extension_data(mut self, data: ExtensionData) -> Self
```

**Source:** `crates/goose/src/session/session_manager.rs:182-185`

#### apply()

Execute the update.

```rust theme={null}
pub async fn apply(self) -> Result<()>
```

**Source:** `crates/goose/src/session/session_manager.rs:150-152`

**Example:**

```rust theme={null}
session_manager
    .update("20260304_1")
    .user_provided_name("My Renamed Session")
    .total_tokens(Some(1500))
    .apply()
    .await?;
```

## Import/Export

### export\_session()

Export session to JSON.

```rust theme={null}
pub async fn export_session(&self, id: &str) -> Result<String>
```

<ParamField path="id" type="&str" required>
  Session ID to export
</ParamField>

**Returns:** JSON string representation

**Source:** `crates/goose/src/session/session_manager.rs:314-316`

### import\_session()

Import session from JSON.

```rust theme={null}
pub async fn import_session(&self, json: &str) -> Result<Session>
```

<ParamField path="json" type="&str" required>
  JSON session data
</ParamField>

**Returns:** Newly created Session

**Source:** `crates/goose/src/session/session_manager.rs:318-320`

### copy\_session()

Duplicate a session.

```rust theme={null}
pub async fn copy_session(&self, session_id: &str, new_name: String) -> Result<Session>
```

<ParamField path="session_id" type="&str" required>
  ID of session to copy
</ParamField>

<ParamField path="new_name" type="String" required>
  Name for the new session
</ParamField>

**Source:** `crates/goose/src/session/session_manager.rs:322-324`

## Analytics

### get\_insights()

Get aggregated session statistics.

```rust theme={null}
pub async fn get_insights(&self) -> Result<SessionInsights>
```

**Returns:** Session insights with token totals

**Source:** `crates/goose/src/session/session_manager.rs:310-312`

### SessionInsights

```rust theme={null}
pub struct SessionInsights {
    pub total_sessions: usize,
    pub total_tokens: i64,
}
```

**Source:** `crates/goose/src/session/session_manager.rs:119-124`

## Chat History Search

### search\_chat\_history()

Search messages across all sessions.

```rust theme={null}
pub async fn search_chat_history(
    &self,
    query: &str,
    limit: Option<usize>,
    after_date: Option<DateTime<Utc>>,
    before_date: Option<DateTime<Utc>>,
    exclude_session_id: Option<String>,
) -> Result<ChatRecallResults>
```

<ParamField path="query" type="&str" required>
  Search query string
</ParamField>

<ParamField path="limit" type="Option<usize>">
  Maximum results to return
</ParamField>

<ParamField path="after_date" type="Option<DateTime<Utc>>">
  Only include messages after this date
</ParamField>

<ParamField path="before_date" type="Option<DateTime<Utc>>">
  Only include messages before this date
</ParamField>

<ParamField path="exclude_session_id" type="Option<String>">
  Session ID to exclude from results
</ParamField>

**Source:** `crates/goose/src/session/session_manager.rs:357-368`

## Related Types

* [Agent](/api/core/agent) - Main agent orchestrator
* [Conversation](/api/core/conversation) - Message history
* [Config](/api/core/config) - Configuration system
