Sessions
Record every agent interaction as a durable session you can inspect, replay, and control
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
Bootstrap the stream once, start a session, record a model call and a tool call, keep some state, and read the session back.
import { AgentId, LastN, Laser, ModelRequest, SessionConfig, TopicRetention, sessionTurnText } from "@laserdata/laser-sdk"
const utf8 = (text: string) => new TextEncoder().encode(text)
await using laser = await Laser.connectEnv()
const sessions = laser.sessions(new SessionConfig().stream("ops"))
await sessions.bootstrap(4, TopicRetention.expireAfter(7 * 86_400_000))
const { session, lease } = await sessions.create("incident-42").agent(AgentId.new("triage")).begin()
await session.run(lease, async (session) => {
const assembled = await session.assemble(new LastN(20))
const call = await session.model(new ModelRequest("gpt-4o", utf8(assembled.text())), assembled)
// Call your model provider here, then record its answer.
await call.complete({ body: utf8("Check the cache on node-7"), usage: { inputTokens: 812n, outputTokens: 64n } })
const tool = await session.tool("read_metrics", { host: "node-7" })
await tool.complete(utf8("cache hit rate 41%"))
await session.state().set("status", "triaged")
})
for (const turn of await sessions.open(session.conversation).context()) {
console.log(turn.display, sessionTurnText(turn))
}use laser_sdk::agent::{ModelRequest, ModelResponse};
use laser_sdk::prelude::full::*;
use laser_sdk::wire::agent::TokenUsage;
use serde_json::json;
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<(), LaserError> {
let laser = Laser::connect_env().await?;
let sessions = laser.sessions_with(SessionConfig::new().stream("ops"));
sessions
.bootstrap(4, TopicRetention::expire_after(Duration::from_secs(7 * 86_400)))
.await?;
let (session, lease) = sessions.create("incident-42").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", assembled.text()), 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?;
for turn in sessions.open(id).context().await? {
println!("{} {}", turn.display, turn.text());
}
Ok(())
}import asyncio
import laser_sdk as ls
async def main():
async with await ls.Laser.connect_env() as laser:
sessions = laser.sessions(stream="ops")
await sessions.bootstrap(4, ls.TopicRetention.expire_after(7 * 86_400_000))
async with sessions.create("incident-42").agent("triage") as session:
assembled = await session.assemble(ls.LastN(20))
call = await session.model(ls.ModelRequest("gpt-4o", assembled.text()), assembled)
# Call your model provider here, then record its answer.
await call.complete(
ls.ModelResponse("Check the cache on node-7", usage={"input_tokens": 812, "output_tokens": 64})
)
tool = await session.tool("read_metrics", {"host": "node-7"})
await tool.complete("cache hit rate 41%")
await session.state().set("status", "triaged")
for turn in await sessions.open(session.conversation).context():
print(turn.display, turn.text())
asyncio.run(main())The read prints 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. In Rust, sessions need the agent feature.
Bootstrap once
bootstrap(partitions, retention) creates the session topic agent.sessions and the other agent topics in the stream. Run it once per stream before the first session. The retention is required, 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.
const { session, lease } = await sessions.start().agent(AgentId.new("triage")).begin()
try {
await triage(session)
await session.end()
} catch (error) {
await session.fail({ code: { kind: "known", name: "Internal" }, message: String(error), retryable: false })
throw error
} finally {
lease.release()
}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);session, lease = await sessions.start().agent("triage").begin()
try:
await triage(session)
await session.end()
except Exception as error:
await session.fail({"code": 7, "message": str(error), "retryable": False})
raise
finally:
lease.release()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.
const { session: child, lease } = await sessions
.start()
.agent(AgentId.new("specialist"))
.parent(session.conversation, session.conversation)
.begin()
await child.run(lease, async (child) => {
const tool = await child.tool("inspect_service", { service: "api" })
await tool.complete(utf8("cache saturation"))
})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?;child_builder = sessions.start().agent("specialist").parent(session.conversation, session.conversation)
async with child_builder as child:
tool = await child.tool("inspect_service", {"service": "api"})
await tool.complete("cache saturation")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:
const page = await sessions.list().status("active").results(20).fetch()
for (const info of page.items) {
console.log(info.label, info.status, info.idle, info.toolCalls, info.tokensIn)
}
const timeline = await sessions.events(session.conversation).results(100).fetch()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?;page = await sessions.list(status="active", results=20)
for info in page["items"]:
print(info.get("label"), info["status"], info["idle"], info["tool_calls"], info["tokens_in"])
timeline = await sessions.events(session.conversation, results=100)In Rust, SessionStatus is part of laser_sdk::prelude::full.
Good to know
- The stream is the isolation boundary. A session and its child sessions never leave their stream. Give each application and environment its own stream.
- By default every session's records ride one
agent.sessionstopic 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 or LaserData Cloud.
Sessions in depth
Leases, layouts, submission, operator control, budgets, pause, state, and managed reads
Context
Assemble a bounded, prompt-ready history
Agents
Agents that handle work inside sessions
Memory
Remember and recall facts across sessions
Sessions example
An incident root session with two child sessions in Rust, Python, and TypeScript