# Sessions

Code on this page is in Rust. The same page in [Python](https://docs.laserdata.com/md/python/laser-sdk/session.md), [TypeScript](https://docs.laserdata.com/md/typescript/laser-sdk/session.md), or with every language at https://docs.laserdata.com/md/laser-sdk/session.md.

The complete programs on this page are plain text, one language each, at [https://docs.laserdata.com/md/python/laser-sdk/session.md](https://docs.laserdata.com/md/python/laser-sdk/session.md), [https://docs.laserdata.com/md/typescript/laser-sdk/session.md](https://docs.laserdata.com/md/typescript/laser-sdk/session.md), and [https://docs.laserdata.com/md/rust/laser-sdk/session.md](https://docs.laserdata.com/md/rust/laser-sdk/session.md).

A session is one unit of agent work in a stream, with a lifecycle: it starts, runs, and ends as completed, failed, or canceled. Every model call, tool call, state change, and handoff inside it is recorded on the log, so you can read back exactly what an agent did. Use a session for each ticket, incident, request, or task an agent handles.

The SDK never calls a model. Your code calls its provider, and the session records the call.

## Quick example

This program starts a session, records a model call and a tool call, keeps some state, reads the session back, and prints the record types as JSON. It runs on a scratch stream with a unique name and deletes that stream at the end, so it leaves nothing to clean up.

The program connects with `LASER_CONNECTION_STRING`. With that variable set, it needs no Docker and no local server. `echo "${LASER_CONNECTION_STRING:+configured}"` prints `configured` when the variable is set and a blank line when it is not. Without it, the [resolve block](#run-it-with-an-api-key) below connects with a LaserData API key.

Sessions are in the `agent` feature of the `laser-sdk` crate, a default feature.

```rust
// cargo add laser-sdk
// cargo add tokio --features macros,rt-multi-thread
// cargo add serde_json --features preserve_order
use laser_sdk::agent::{ModelRequest, ModelResponse};
use laser_sdk::prelude::full::*;
use laser_sdk::wire::agent::TokenUsage;
use serde_json::{Value, json};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = Laser::connect_env().await?;
    let scratch = root.scratch_stream("sessions").await?;
    let result = record_session(scratch.laser(), scratch.name()).await;
    scratch.delete().await?;
    println!("{}", result?);
    Ok(())
}

async fn record_session(laser: &Laser, stream: &str) -> Result<Value, LaserError> {
    let sessions = laser.sessions_with(SessionConfig::new().stream(stream));
    sessions.bootstrap(1, TopicRetention::default()).await?;

    let (session, lease) = sessions.start().agent("triage".parse::<AgentId>()?).begin().await?;
    let id = session.conversation();
    session
        .run(lease, |session| async move {
            let assembled = session.assemble(Box::new(LastN(20))).await?;
            let call = session
                .model(ModelRequest::new("gpt-4o", "Why is node-7 slow?"), Some(&assembled))
                .await?;
            // Call your model provider here, then record its answer.
            call.complete(ModelResponse {
                body: b"Check the cache on node-7".to_vec(),
                usage: Some(TokenUsage { input_tokens: 812, output_tokens: 64, ..Default::default() }),
                ..Default::default()
            })
            .await?;

            let tool = session.tool("read_metrics", json!({ "host": "node-7" })).await?;
            tool.complete(b"cache hit rate 41%".to_vec()).await?;
            session.state().set("status", json!("triaged")).await?;
            Ok(())
        })
        .await?;

    let records: Vec<String> = sessions.open(id).context().await?.iter().map(|turn| turn.display.to_string()).collect();
    Ok(json!({ "session": id.to_string(), "records": records }))
}
```

The `records` list holds `session.started`, `model.request`, `context.assembled`, `model.response`, `tool.call`, `tool.result`, `state.updated` twice (the change and the snapshot written at the end), and `session.completed`. Lifecycle and state records have structured binary bodies, so `text()` does not decode them. Use `session.state().get()` to read the state document, and `text()` only for bodies your application wrote as text. The model request body is the prompt your code sends to its provider. An empty body is refused with `command requires body`.

`sessions()`, `start()`, `agent(id)`, `open(id)`, and `session.state()` return at once. `bootstrap()`, `begin()`, `assemble`, `model`, `tool`, each `complete`, `state().set()`, and `context()` return an awaitable. In Python, `async with sessions.start().agent(id) as session` begins the session and ends it as completed, or as failed when the block raises.

## Run it with an API key

With a LaserData API key in `LD_API_KEY` instead of a connection string, add this block to the program. It turns the key into the connection string in three calls: the key's organization from `/tenants`, the deployments the key can read from `/tenants/{tenant_id}/deployments`, and the login from the deployment's `/credentials`. Set `LD_DEPLOYMENT` to the deployment's name or ID when the key sees more than one deployment. The block then exits and lists the ones it sees. The key's role needs `deployment:read` and `deployment:credentials:read` on the deployment's environment. The block keeps the connection string in memory and never prints it.

```rust
// cargo add reqwest --features json
// cargo add serde_json
// Add these two functions, then connect with Laser::connect(&connection_string().await?) in main.
use serde_json::Value;

async fn laserdata(client: &reqwest::Client, url: &str) -> Result<Value, Box<dyn std::error::Error>> {
    let key = std::env::var("LD_API_KEY")?;
    let response = client.get(url).header("ld-api-key", key).header("user-agent", "laserdata-docs-example").send().await?;
    let status = response.status();
    if !status.is_success() {
        return Err(format!("GET {url} answered {status}: {}", response.text().await?).into());
    }
    Ok(response.json().await?)
}

async fn connection_string() -> Result<String, Box<dyn std::error::Error>> {
    if let Ok(value) = std::env::var("LASER_CONNECTION_STRING") {
        return Ok(value);
    }
    let api_url = std::env::var("LD_API_URL").unwrap_or_else(|_| "https://api.laserdata.cloud".to_owned());
    let client = reqwest::Client::new();
    let tenants = laserdata(&client, &format!("{api_url}/tenants")).await?;
    let mut deployments = Vec::new();
    for page in 1_u64.. {
        let url = format!("{api_url}/tenants/{}/deployments?results=100&page={page}", tenants[0]["id"]);
        let reply = laserdata(&client, &url).await?;
        deployments.extend(reply["items"].as_array().cloned().unwrap_or_default());
        if page >= reply["total_pages"].as_u64().unwrap_or(0) {
            break;
        }
    }
    let wanted = std::env::var("LD_DEPLOYMENT").ok();
    let matches: Vec<&Value> = deployments
        .iter()
        .filter(|deployment| wanted.as_deref().is_none_or(|wanted| deployment["name"] == wanted || deployment["id"].to_string() == wanted))
        .collect();
    let [deployment] = matches.as_slice() else {
        let visible: Vec<String> = deployments.iter().map(|deployment| format!("{} ({})", deployment["name"].as_str().unwrap_or_default(), deployment["id"])).collect();
        eprintln!("Set LD_DEPLOYMENT to the name or ID of one deployment. Visible: {}", visible.join(", "));
        std::process::exit(1);
    };
    let supervisor_url = deployment["supervisor_url"].as_str().ok_or("The deployment has no supervisor_url yet")?;
    let credentials = laserdata(&client, &format!("{supervisor_url}/deployments/{}/credentials", deployment["id"])).await?;
    Ok(credentials["connection_string"].as_str().ok_or("The credentials answer has no connection_string")?.to_owned())
}
```

The block calls nothing else: it never changes access rules and never needs `info:read`. A Free deployment admits every address, so the program connects at once. A paid deployment admits only the addresses its [access rules](/networking/access-rules) allow, and a connect from any other address times out naming `the Iggy server to accept the connection`. [Agent access](/agents#the-network-path) shows how to admit an address, and [When no deployment exists](/agents#when-no-deployment-exists) shows how to create one.

## Resume a session after a restart

A session's state lives on the log, so a new process can pick up where an earlier one stopped. Run this program once to start an incident session. It prints the session ID. Run it again with `SESSION_ID` set to that ID, and the second process recovers the stored state, resumes the same session, records a tool call with its result, changes the state, and reads the state and the session's records back. It uses the named stream `ops`, not a scratch stream, because the second run reads what the first one wrote. Delete the stream when you are done with `laser.stream("ops").delete()`.

It connects with `LASER_CONNECTION_STRING` like the program above. The program records data and calls no model provider, so it works with plain Apache Iggy.

```rust
// cargo add laser-sdk
// cargo add tokio --features macros,rt-multi-thread
// cargo add serde_json --features preserve_order
use laser_sdk::prelude::full::*;
use serde_json::json;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let laser = Laser::connect_env().await?;
    let sessions = laser.sessions_with(SessionConfig::new().stream("ops"));
    sessions
        .bootstrap(1, TopicRetention::expire_after(Duration::from_secs(86_400)))
        .await?;
    let triage: AgentId = "triage".parse()?;

    let Ok(session_id) = std::env::var("SESSION_ID") else {
        let (session, lease) = sessions.start().agent(triage).begin().await?;
        let id = session.conversation().to_string();
        session.run(lease, |active| async move {
            active.state().replace(json!({ "host": "node-7", "status": "triaged" })).await?;
            Ok(())
        }).await?;
        println!("Started session {id}");
        return Ok(());
    };

    let id = session_id.parse::<ConversationId>()?;
    let recovered = sessions.open(id).state().get().await?;
    if !recovered.complete {
        return Err("Part of this session's history is no longer retained".into());
    }
    println!("Recovered {}", recovered.document);

    let (session, lease) = sessions.start().with_id(id).agent(triage).resume().await?;
    session.run(lease, |active| async move {
        let tool = active.tool("restart_cache", json!({ "host": "node-7" })).await?;
        tool.complete(b"cache restarted".to_vec()).await?;
        active.state().set("status", json!("resolved")).await?;
        Ok(())
    }).await?;
    let current = sessions.open(id).state().get().await?;
    let records = sessions.open(id).context().await?;
    println!("Now {} at revision {}", current.document, current.revision);
    let types: Vec<String> = records.iter().map(|turn| turn.display.to_string()).collect();
    println!("{} records: {}", records.len(), types.join(", "));
    Ok(())
}
```

The second run prints this. Python separates the JSON fields with a space:

```text
Recovered {"host":"node-7","status":"triaged"}
Now {"host":"node-7","status":"resolved"} at revision 2
10 records: session.started, state.updated, state.updated, session.completed, session.started, tool.call, tool.result, state.updated, state.updated, session.completed
```

The revision counts the state changes: 1 after the first run's `replace`, 2 after the second run's `set`. Each run also writes a state snapshot when it ends, which is the second `state.updated` record of that run and does not change the revision. In TypeScript `revision` is a `bigint`, which `JSON.stringify` refuses, so print it with `toString()` or convert it with `Number(revision)`.

`state().set(key, value)` changes one key, `state().replace(document)` sets the whole document, and `state().get()` returns the `document`, its `revision`, and `complete`. `open(id).context()` returns the session's latest records in order, one per recorded event, such as `session.started`, `model.request`, `tool.call`, and `state.updated`, up to the session factory's read bounds. In Python, pass `last_n` and `token_budget` to read further back. A resumed session adds a new `session.started` record to the same session.

A canceled session cannot resume. An ended session needs `resume()` instead of `begin()`. `resume()` appends a new `session.started` record and acquires a session lease. To read history without writing, use `open(id).context()`. When `complete` is false, part of the history fell out of retention, so restore from a snapshot or checkpoint before you continue, and never treat a partial history as the current state. Each session has its own state, and sessions in one stream share its access rules. Keep data that different customers must not see in different deployments or streams with their own credentials.

## Bootstrap once

`bootstrap(partitions, retention)` creates a missing stream, the session topic `agent.sessions`, and the other agent topics. Call it before the first session. It is safe to repeat at process startup. Existing streams and topics keep their configuration. The defaults are one partition and records that expire after one day: leave both arguments out in TypeScript and Python, and pass `1, TopicRetention::default()` in Rust. Pass a longer retention for sessions you keep, because `agent.sessions` holds every session's records. On Laser Stack and LaserData Cloud, bootstrap also registers the stream so the managed session reads below can see it.

## Start a session

`create(label)` derives the session ID from the stream, the namespace, and the label, so the same label always reaches the same session. `start()` gives a fresh ID. Both need `.agent(id)` for the agent that owns the session, then `begin()` writes the start record and returns the session with a lease. The lease keeps the session listed in the client's heartbeat while your process works on it.

## End a session or mark it failed

The guard in the quick example ends the session as completed when the work returns and as failed when it throws: `run(lease, work)` in Rust and TypeScript, `async with` or `run(lease, work)` in Python. To control the outcome yourself, call `end()`, `fail(error)`, or `cancel()`. The first terminal call wins, and a different one afterwards fails.

```rust
let (session, lease) = sessions.start().agent("triage".parse::<AgentId>()?).begin().await?;
match triage(&session).await {
    Ok(()) => session.end().await?,
    Err(error) => {
        let body = AgentErrorBody {
            code: AgentErrorCode::Internal,
            message: Some(error.to_string()),
            retryable: false,
            detail: None,
        };
        session.fail(body).await?;
    }
}
drop(lease);
```

In Rust, `AgentErrorBody` and `AgentErrorCode` are part of `laser_sdk::prelude::full`. Python passes the same body as a dict whose `code` is the wire number, 7 for `Internal`.

## Delegate work to a child session

Give delegated work its own lifecycle as a child session. Pass the parent and the root, which is the parent itself for a top-level session. The child lives in the same stream, and its history stays in the child.

```rust
let (child, lease) = sessions
    .start()
    .agent("specialist".parse::<AgentId>()?)
    .parent(id, id)
    .begin()
    .await?;
child
    .run(lease, |child| async move {
        let tool = child.tool("inspect_service", json!({ "service": "api" })).await?;
        tool.complete(b"cache saturation".to_vec()).await?;
        Ok(())
    })
    .await?;
```

Workflow steps become child sessions on their own. So do contracts, A2A tasks, and MCP tool calls that you start with a parent.

## Read a session back

`open(id).context()` returns the session's recent records with their display types, as in the quick example. It reads the log directly, so it works everywhere. `checkpoint()` with `turns_since(checkpoint)` or `replay(..)` reads what happened after a saved point.

On Laser Stack or LaserData Cloud, the managed session index adds a searchable list, summaries with counts and tokens, and a timeline per session:

```rust
let page = sessions.list().status(SessionStatus::Active).results(20).fetch().await?;
for info in &page.items {
    println!("{:?} {:?} {} {} {}", info.label, info.status, info.idle, info.tool_calls, info.tokens_in);
}
let timeline = sessions.events(id).results(100).fetch().await?;
```

In Rust, `SessionStatus` is part of `laser_sdk::prelude::full`.

## Good to know

* Session records are scoped to their stream. Enforce customer access with Iggy permissions and managed authorization grants. A label, namespace, session ID, or user filter is not an authentication boundary.
* By default every session's records ride one `agent.sessions` topic keyed by session, so one session's lane is one partition with exact order.
* A session whose process stops without ending it shows as idle, never as failed. The defaults are a 60-second heartbeat and a 5-minute idle timeout.
* A dead-lettered record never fails its session by itself. Failing on a dead letter is an opt-in setting.
* Labels always derive the same ID within a namespace. Use `start()` or a per-parent namespace for child work that repeats a label.
* Recording, state, context, replay, budget checks with `over_budget()`, operator control, and pause work on plain Apache Iggy. Listing sessions, summaries, timelines, links, the change feed, and runtime budget enforcement need the managed session index on [Laser Stack](/laser-sdk/laser-stack) or LaserData Cloud.

- [Sessions in depth](/laser-sdk/advanced/sessions): Leases, layouts, submission, operator control, budgets, pause, state, and managed reads
- [Context](/laser-sdk/context): Assemble a bounded, prompt-ready history
- [Agents](/laser-sdk/fabric): Agents that handle work inside sessions
- [Memory](/laser-sdk/memory): Remember and recall facts across sessions
- [Sessions example](https://github.com/laserdata/laser-sdk/tree/main/examples): An incident root session with two child sessions in Rust, Python, and TypeScript

Source: https://docs.laserdata.com/laser-sdk/session
