createAgentSession(), AgentSession, AgentSessionRuntime, and session events. For servers that release idle sessions and rehydrate them on later requests, wrap sessions with createAgentSessionRuntime() instead (see Releasing idle sessions).
Prerequisites and setup
1
Install @bastani/atomic
Atomic requires Node.js 24.20 or newer. Dependency install scripts are not required; if your package manager blocks install scripts, leave them disabled.
2
Keep Atomic external to the server bundle
Atomic resolves its bundled resources and native modules relative to List any other Atomic packages your server imports directly, including
node_modules, so list it in serverExternalPackages (Next.js 15 and later):@bastani/atomic-storage-postgres when storing sessions in PostgreSQL (see Configure session storage).3
Use the Node.js runtime and Atomic's TypeBox subpath
Every route handler that imports Atomic must run on the Node.js runtime, not Edge:Import Atomic only from server code (client components may use
import type from @bastani/atomic, which adds zero bytes to the browser bundle). When defining custom tool schemas, import TypeBox from @bastani/atomic/typebox (and its subpaths such as /value, /compile, and /format) so custom formats share Atomic’s validation registry.Keep one session per conversation
AnAgentSession owns the conversation history, so create one per conversation and reuse it across requests. Store shared state on globalThis so next dev hot reloads preserve active sessions without leaking them. Restart the dev server after changing session options because existing sessions keep their creation options.
SessionManager.inMemory() keeps history only in RAM. To persist conversations across restarts or share them across servers, pass a SQLite, JSONL, or PostgreSQL SessionManager or sessionStore (see Configure session storage). Call closeConversation() when a conversation finishes or goes idle, and run closeAllConversations() on SIGTERM/SIGINT so session stores and child processes close cleanly.
Stream a prompt
This route starts one prompt and streams the assistant’s output as NDJSON.createTranscript() converts session events into ordered JSON-serializable parts (text, thinking, and toolCall paired with its result). Tool calls appear in message_end before execution begins and gain their result as tool_execution_update and tool_execution_end arrive, so each line carries the full output so far and the browser replaces its rendered list.
- One prompt at a time:
session.prompt()rejects while streaming, so the route returns409and flipsbusysynchronously to prevent races. To queue prompts instead of rejecting, callsession.prompt(message, { streamingBehavior: "followUp" }). - Stop on disconnect: When the browser disconnects or aborts
fetch,request.signalandcancel()callsession.abort(), stopping the current turn and tools while keeping the session reusable. - Payload throttling: Each line emits the complete transcript so far. For long responses, throttle updates on a short timer or send incremental diffs.
- Structured tool details:
createTranscript()returns a tool result’s text by default. PasscreateTranscript({ toolResult: (toolName) => (toolName === "todo" ? "details" : "content") })to emit structureddetailsfor specific tools. - Error sanitization: Log raw errors server-side and return generic user-safe messages to the browser.
Read the stream in the browser
type: text and thinking hold strings, and a toolCall part has name, arguments, and (once progress or completion arrives) result (content, isError, isPartial). Pass an AbortController signal to cancel from the UI.
Secure the endpoint
- Require authentication on every route that creates sessions or sends prompts, and scope conversation IDs to the authenticated user.
- Allow only needed tools.
toolsis an allowlist; the example enables only read-onlyread,find, andsearch. Omitbash,edit, andwriteunless the agent must mutate files or run commands. UseexcludedToolsto strip specific tools ornoTools: "all"to expose none, and omitask_user_questionin headless servers. See Tools. - Disable unused builtins. Turn off
subagents,mcp,web-access, andintercomviabuiltinswhen not required. - Choose
cwddeliberately.cwdsets the starting directory for relative paths and project discovery, but tools can still access absolute paths outsidecwd. Pointcwdat a controlled directory, never user input. - Isolate the process in a container, VM, or restricted OS account whenever callers must not reach other server files or when write/shell tools are enabled. See Containerization.
- Keep credentials server-side. Provider keys live in the server’s
ModelRuntime. Never forward them to browsers or accept raw keys from untrusted clients.
Next steps
Use the TypeScript SDK
Sessions, prompting, workspaces, Intercom policies, and lifecycle hooks.
Configure session storage
Persist server sessions in SQLite, JSONL, or PostgreSQL and wire
createAgentSessionRuntime().SDK API reference
Every
createAgentSession() option, runtime method, error class, and export.Orchestration
Multi-step workflows with codemode and subagents, plus migrating older workflows.