Skip to content

SessionHandle

A SessionHandle represents an interactive conversation with an agent. Created via agent.createSession() or resumed via client.session(id).

typescript
const session = await agent.createSession({ title: "My Session" });
// or
const session = client.session("existing-session-id");

Properties

session.id

The session ID. Save this to resume the session later.

Type: string (readonly)


Messaging

session.send(input, callbacks?)

Send a message and stream the response via callbacks. Resolves when the agent finishes its turn.

typescript
const result = await session.send("Create a REST API", {
    onText: delta => process.stdout.write(delta),
    onToolStart: part => console.log(`[tool] ${part.tool}`),
});

console.log(result.text);
console.log(result.parts);
  • input string | MessageInput required — A text string, or a MessageInput object with parts for multi-part messages (text + files).
  • callbacks StreamCallbacks — Optional callbacks for streaming events. See the Streaming guide for all callback types.

Returns: Promise<SendResult>

typescript
interface SendResult {
    messageId: string;
    text: string;
    parts: Part[];
    tokens?: Tokens;
    cost?: number;
    error?: { name: string; data: Record<string, unknown> };
}

session.stream(input)

Send a message and get back a typed async iterator of events. Use this for full control over every event.

typescript
for await (const event of session.stream("Add tests")) {
    if (event.type === "text-delta") {
        process.stdout.write(event.delta);
    }
}
  • input string | MessageInput required — Same as send().

Returns: AsyncIterable<AgentEvent>

See the Streaming guide for all event types.


Session Control

session.abort()

Cancel the current turn. The agent stops immediately.

typescript
await session.abort();

Returns: Promise<void>


session.summarize()

Trigger context compaction. Useful for long conversations approaching the context limit.

typescript
await session.summarize();

Returns: Promise<void>


session.revert(messageId)

Undo the conversation back to a specific message. All subsequent messages are removed.

typescript
await session.revert("msg-id-to-revert-to");
  • messageId string required — The message ID to revert to.

Returns: Promise<void>


Sandbox

session.shell(command, opts?)

Execute a shell command in the session's Linux container. No LLM involved — direct execution.

typescript
const result = await session.shell("npm test");
console.log(result.stdout);
console.log(result.exitCode);
  • command string required — The shell command to execute.
  • opts.timeout number — Timeout in milliseconds.
  • opts.cwd string — Working directory for the command.

Returns: Promise<ShellResult>

typescript
interface ShellResult {
    stdout: string;
    stderr: string;
    exitCode: number;
}

session.getFile(path)

Read a text file from the sandbox filesystem.

typescript
const src = await session.getFile("/workspace/src/index.ts");
  • path string required — Absolute path in the sandbox.

Returns: Promise<string>


session.getFileBuffer(path)

Read a file as raw bytes. Use for binary files (images, PDFs, etc.).

typescript
const buf = await session.getFileBuffer("/workspace/chart.png");
writeFileSync("chart.png", Buffer.from(buf));
  • path string required — Absolute path in the sandbox.

Returns: Promise<ArrayBuffer>


session.getArtifact(key) / session.getArtifactBuffer(key)

Read named artifacts produced by the agent. Same interface as getFile/getFileBuffer but keyed by artifact name instead of path.

Returns: Promise<string> or Promise<ArrayBuffer>


Metadata

session.getInfo()

Get session metadata.

typescript
const info = await session.getInfo();
console.log(info.title, info.status);

Returns: Promise<SessionInfo>

typescript
interface SessionInfo {
    id: string;
    title: string;
    status: "idle" | "busy" | "compacting" | "error";
    parentId?: string;
    timeCreated: number;
    timeUpdated: number;
}

session.getMessages()

Get the full message history with all parts.

typescript
const messages = await session.getMessages();
for (const msg of messages) {
    console.log(`${msg.info.role}: ${msg.parts.length} parts`);
}

Returns: Promise<WithParts[]>


session.getMetrics()

Get usage metrics for the session.

typescript
const metrics = await session.getMetrics();
console.log(`${metrics.toolCalls} tool calls, $${metrics.cost.toFixed(4)}`);

Returns: Promise<SessionMetrics>

typescript
interface SessionMetrics {
    sessionId: string;
    messages: number;
    steps: number;
    toolCalls: number;
    toolUsage: Record<string, number>;
    tokens: Tokens;
    cost: number;
}

session.getTodos()

Get the agent's todo list for this session.

typescript
const todos = await session.getTodos();

Returns: Promise<TodoItem[]>


Management

session.update(opts)

Update session metadata.

typescript
await session.update({ title: "New Title", archived: true });
  • title string — New session title.
  • archived boolean — Archive or unarchive the session.

Returns: Promise<void>


session.end()

End the session and its sandbox permanently.

typescript
await session.end();

Returns: Promise<void>


Permissions

session.replyToPermission(requestId, reply, message?)

Reply to a permission request. Used with the async iterator API when handling permission-asked events manually.

typescript
for await (const event of session.stream("Install lodash")) {
    if (event.type === "permission-asked") {
        await session.replyToPermission(event.request.id, "once");
    }
}
  • requestId string required — The permission request ID from the event.
  • reply 'once' | 'always' | 'reject' required — Your response.
  • message string — Optional message to send along with the reply.

Returns: Promise<void>


Advanced

session.runCommand(name, args?)

Run a named command template.

typescript
const output = await session.runCommand("test", { path: "./src" });

Returns: Promise<string>


session.events(lastEventId?)

Get a raw SSE event stream. For advanced use cases where you want to manage the connection yourself.

Returns: Promise<ReadableStream<Uint8Array>>

SDK released under the MIT License.