> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_04_session_system/4.1_session_data_model.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 4.1 Session Data Model

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2025-02-17

***

The Session is the core abstraction in OpenCode. Every conversation between the user and the AI takes place within a Session -- it manages the full lifecycle of a conversation: from creation, message exchange, and tool invocation, to compaction, sharing, and archiving.

## 4.1.1 The `Session.Info` Zod Schema Definition

The Session data model is defined in `session/index.ts` using a Zod Schema:

```typescript
export const Info = z.object({
  id: Identifier.schema("session"),    // Unique session identifier
  slug: z.string(),                     // Human-readable short-link identifier
  projectID: z.string(),                // ID of the owning project
  directory: z.string(),                // Working directory
  parentID: Identifier.schema("session").optional(), // Parent session ID

  title: z.string(),                    // Session title
  version: z.string(),                  // OpenCode version number

  summary: z.object({                   // File change summary
    additions: z.number(),
    deletions: z.number(),
    files: z.number(),
    diffs: Snapshot.FileDiff.array().optional(),
  }).optional(),

  share: z.object({                     // Sharing information
    url: z.string(),
  }).optional(),

  time: z.object({                      // Timestamps
    created: z.number(),
    updated: z.number(),
    compacting: z.number().optional(),   // Time when compaction is in progress
    archived: z.number().optional(),     // Archive time
  }),

  permission: PermissionNext.Ruleset.optional(), // Session-level permission rules
  revert: z.object({                    // Revert information
    messageID: z.string(),
    partID: z.string().optional(),
    snapshot: z.string().optional(),
    diff: z.string().optional(),
  }).optional(),
})
```

**Key Field Breakdown**:

* **`id`**: Uses a descending ULID (Universally Unique Lexicographically Sortable Identifier). Descending order means that newly created Sessions have IDs that sort earlier in lexicographic order -- so sorting by ID naturally yields reverse-chronological order.
* **`slug`**: A short-link identifier used for sharing URLs, shorter and more user-friendly than a full ULID.
* **`parentID`**: Marks the parent-child relationship. When the main Agent creates a sub-Agent via the Task tool, the sub-Agent's Session sets `parentID` to point to the parent Session.
* **`permission`**: Session-level permission overrides. Allows dynamically modifying the permission rules for a specific session at runtime.
* **`revert`**: Revert marker. When the user triggers a revert operation, it records the target messageID and the corresponding Snapshot.

## 4.1.2 Parent-Child Session Relationships: `parentID` and Sub-agent Sessions

OpenCode supports **multi-level session nesting**. The most typical scenario is the Task tool creating a sub-Agent:

```
Main session (session_001, agent: build)
+-- User: "Help me refactor the auth module"
+-- AI: Calls the task tool -> creates a child session
|
+-- Child session (session_002, parentID: session_001, agent: explore)
    +-- System: "Search for auth-related code"
    +-- AI: Returns search results
```

The significance of parent-child relationships:

1. **Traceability**: The origin of a subtask can be traced via `parentID`
2. **Resource Isolation**: Child sessions have independent message histories and permissions
3. **Lifecycle Management**: Child sessions can be cleaned up when the parent session ends

## 4.1.3 The Session Fork Mechanism

`Session.fork()` allows branching a new session from a specific point in an existing session:

```typescript
export const fork = fn(
  z.object({
    sessionID: Identifier.schema("session"),
    messageID: Identifier.schema("message").optional(),
  }),
  async (input) => {
    const original = await get(input.sessionID)
    const title = getForkedTitle(original.title) // "xxx (fork #1)"
    const session = await createNext({ directory: Instance.directory, title })

    const msgs = await messages({ sessionID: input.sessionID })
    for (const msg of msgs) {
      if (input.messageID && msg.info.id >= input.messageID) break
      // Copy messages and Parts to the new session
    }
    return session
  },
)
```

Use cases for Fork:

* The user wants to return to a certain point in the conversation history and start fresh
* The user wants to try different approaches without losing the previous conversation record
* The title format is `"Original Title (fork #N)"`, where N increments

## 4.1.4 Session Events

The Session module publishes the following events via the Bus:

```typescript
export const Event = {
  Created: BusEvent.define("session.created", z.object({ info: Info })),
  Updated: BusEvent.define("session.updated", z.object({ info: Info })),
  Deleted: BusEvent.define("session.deleted", z.object({ info: Info })),
  Diff:    BusEvent.define("session.diff", z.object({
    sessionID: z.string(),
    diff: Snapshot.FileDiff.array(),
  })),
  Error:   BusEvent.define("session.error", z.object({
    sessionID: z.string().optional(),
    error: MessageV2.Assistant.shape.error,
  })),
}
```

These events drive real-time updates in the TUI/Web UI -- whenever the session state changes, the frontend receives a notification and refreshes the interface.
