query() starts a brand new session with each call. Through several fields in options, you can specify a session ID, resume a historical session, or fork from an existing session.
Concepts
A session corresponds to a persisted conversation history on the CLI side (including context, tool call records, compaction boundaries, etc.), identified by a UUID. Theinit system message contains the current session_id, which also serves as the anchor point for subsequent resume/fork operations.
The auth: accessTokenFromEnv() shown in the examples below can be replaced with any other authentication method used in your project. See SDK Authentication.
Creating New Sessions
Default
Without passing any session-related fields, a new session is created each time:Specifying a Session ID
Let the caller determine the session UUID (suitable when the host manages its own session index):Resuming Sessions
Resume by ID
Resume the Most Recent
When you don’t know the session ID, usecontinue: true to pick up the most recently modified session:
resume and continue simultaneously.
Forking Sessions
Derive a new session from an existing one, preserving the original context but obtaining a new session ID. The original session is unaffected:Field Reference
| Field | Type | Behavior |
|---|---|---|
sessionId | string | Used alone: creates with this ID; with forkSession: ID of the new forked session |
resume | string | Session ID to resume |
continue | boolean | true resumes the most recent session |
forkSession | boolean | Used with resume; forks rather than continues |
Getting the Current Session ID
Listen for theinit message:
Generating Session Titles
Useq.generateSessionTitle() when the host application needs a short display title for an existing session:
ai-title transcript entries are still visible through session-list APIs.
Reading Subagent Transcripts
Subagents write their own transcripts under the parent session. After the parent session completes, uselistSubagents() to discover subagent IDs, then getSubagentMessages() to read one subagent’s message chain:
getSubagentMessages() follows the subagent transcript’s parent chain and returns user / assistant messages in chronological order.