Skip to main content
This guide is for Node.js and TypeScript developers embedding Atomic inside custom UIs, backend services, or automated pipelines. By the end of this page, you can create and drive an AgentSession, configure workspaces, session storage, and human input, release idle sessions for later wake-up, and handle SDK lifecycle errors. If you want to drive Atomic from another language or isolate it in a subprocess, see Drive Atomic over RPC. To compare all programmatic modes, see Choose an integration mode. For complete option lists and export signatures, see SDK API reference. Working examples live in examples/sdk/.

SDK API reference

Full options, AgentSession and AgentSessionRuntime methods, loaders, run modes, task supervision, error classes, and exports.

Configure session storage

Recipes for SQLite, JSONL, in-memory, and PostgreSQL session storage, StorageProvider, ownership rules, and StorageError handling.

Make structured decisions

Run typed classifier or chat decisions with decide(), generateStructuredOutput(), and structured_output.

Stream from a web server

Build a streaming newline-delimited JSON (NDJSON) HTTP endpoint with Next.js App Router and createAgentSession().

Before you begin

Before you write your first SDK script, confirm that you have:
  • Node.js 24.20.0 or newer (node --version).
  • A provider credential configured in your environment (such as ANTHROPIC_API_KEY or OPENAI_API_KEY) or saved with atomic auth login (see Authentication).
  • Optional: Git 2.33 or newer if you plan to bind sessions to repositories with workspace().

Quick start

Follow these steps to install @bastani/atomic and run your first in-process session:
1

Install @bastani/atomic

Install the package with your package manager. Dependency install scripts aren’t required:
2

Configure TypeScript ESM

In package.json, set "type": "module" for ECMAScript Modules (ESM). In tsconfig.json, set "module": "NodeNext", "moduleResolution": "NodeNext", and "strict": true.
3

Create a session, stream deltas, and dispose cleanly

Save the following script and run it with your TypeScript runner or compiled ESM output:
Confirm that the response streams to stdout and the process exits cleanly after session.dispose() settles, for example:
Keep these runtime building blocks in mind as you expand your host:
  • ModelRuntime: Async runtime for credentials, native providers, and dynamic catalogs. Accepts authPath, modelsPath, credentials, runtime auth overrides, and catalog options (allowModelNetwork, modelRefreshTimeoutMs, modelsStorePath, modelsStore; see Model catalog persistence and refresh). Legacy synchronous facades ModelRegistry and AuthStorage remain available, and readStoredCredential(provider, authPath?) reads one stored credential.
  • Exact model restoration: Call await resolveRestoredModelReference(provider, modelId, modelRuntime) to resolve an authenticated saved model (including custom or dynamic IDs) or receive undefined without falling back to a default.
  • Context helpers: Root exports include InlineExtension, buildContextEntries, sessionEntryToContextMessages, CompactionEntry, and sessionManager.buildContextEntries().

Share Atomic’s TypeBox registry

Atomic ships its own TypeBox instance. If your app imports typebox directly, custom formats, settings, or locales won’t reach Atomic’s tool validation. Import TypeBox from @bastani/atomic/typebox or its subpaths instead:
  • @bastani/atomic/typebox
  • @bastani/atomic/typebox/compile
  • @bastani/atomic/typebox/error
  • @bastani/atomic/typebox/format
  • @bastani/atomic/typebox/guard
  • @bastani/atomic/typebox/schema
  • @bastani/atomic/typebox/system
  • @bastani/atomic/typebox/type
  • @bastani/atomic/typebox/value

Core concepts

The following sections cover the core capabilities for configuring, isolating, and driving SDK sessions.

Create a session

createAgentSession() creates an AgentSession with bundled subagents, Model Context Protocol (MCP), web access, and Intercom enabled by default, plus standard user, project, and package discovery unless you pass a custom resourceLoader. The following example shows default creation alongside a custom tool and session storage selection:
Control startup behavior with these options:
  • Disable builtins or tools: Pass builtins: { "web-access": false, intercom: false } to disable bundled packages. Passing tools: [] or noTools: "all" disables every tool, including Intercom. excludedTools always wins and survives /reload. See Tools for wildcard matching and MCP retention rules.
  • Startup hooks and rebinding: createAgentSession() runs extension session_start hooks before resolving. Pass extensionBindings here if startup hooks need them; later session.bindExtensions(...) calls update bindings without replaying session_start.
  • Explicit recovery: Opening a session never recovers interrupted work automatically. After your UI or logger is ready to display output, call await session.startPendingRecovery("resume"); it returns { replayed, dropped, completions, notices }.

Bind a Git workspace

Bind a session to a Git repository, branch, and worktree with workspace({ ... }) (requires Git 2.33 or newer). The following example creates a writable session and a read-only reviewer session on the same workspace:
Workspace bindings follow these rules:
  • Resolution: A local repo must point to a repository root. Remote repositories clone once under <storageHome>/repos/ (see Storage home) and create worktrees after fetching. Missing branches start from base; existing worktrees must match the repository and branch. Explicit cwd must stay inside the worktree, and an explicit sessionManager must already point inside it (otherwise Atomic throws WorkspaceConfigError).
  • Interrupted setup: If Atomic stopped while creating a worktree, retry createAgentSession({ workspace: api }) with the same workspace. Atomic recreates the incomplete checkout and clears the stale branch lock it left behind, while leaving unrelated Git locks untouched. If another Git operation is running, wait for it to finish before retrying.
  • Read-only mode (api.readOnly()): Removes and blocks write, edit, and todo even if listed in tools. Child sessions stay read-only even with their own workspace.
  • Persistence and pull requests: Bindings persist as a workspace_binding entry and restore on reopen. Call bindSessionWorkspace(workspace, sessionManager, signal?) beforehand if you need the resolved path early. Inspect commits with workspaceChangeSet(binding) and open pull requests with publishPullRequest(changeSet, { draft: true }).
  • Errors: Invalid options throw WorkspaceConfigError. Binding failures throw WorkspaceBindingError with code set to wrong-repository, wrong-branch, conflicting-worktree-input, invalid-repository, unknown-base, cwd-outside-worktree, git-unavailable, git-failed, filesystem-failed, drift, writer-conflict, or incomplete-worktree. See Workspace for the full helper and error-class list.
Read-only workspaces aren’t an OS sandbox. Shell tools (bash, powershell) can still run and modify files unless you disable them with tools or excludedTools or isolate the process in a container or VM.

Enforce shared resource admission

To enforce host-wide session and process capacity limits, pass a resourceAdmission service to createAgentSession():
Follow these rules when implementing ResourceAdmission:
  • Kind and cancellation: kind is "session" or "process". Honor signal inside acquire() (resourceAdmissionSignal cancels a session wait; children inherit the service, not that signal) and keep release callbacks idempotent.
  • Avoid deadlocks on request.delegated: Parent sessions hold their session permit while children run, so never queue request.delegated acquisitions. Grant immediately or throw, and size capacity above your maximum concurrent parents.
  • Permit lifetime and crash recovery: Session permits release on clean dispose(); managed command permits release after confirmed process cleanup. On Unix, implement permit.bindProcess({ kind: "unix-process-group", id }) to record process-group IDs for crash reconciliation (Windows reports no process-group identity).
  • Scoping: Wrap async flows with withResourceAdmission(service, fn). An explicit session service wins, and resourceAdmission: null opts out. Child sessions always use their own or parent service rather than a sender’s scope.

Share provider limits across processes

Each process tracks its own provider rate limits. To share limits across processes on one host (such as workers in a pool), broadcast each recorded limit to peers and apply incoming observations:
These three functions coordinate rate limits without echo loops:
  • observeProviderRateLimits(listener) calls listener each time the process records or extends a limit, and returns a function that stops observing.
  • providerRateLimitObservations() returns active limits that haven’t ended yet, so newly started processes can catch up.
  • applyProviderRateLimitObservation(observation) applies a limit from another process. It only extends a limit, ignores expired limits, counts no failure, and doesn’t notify observers (preventing echo loops).
The following table lists the fields on ProviderRateLimitObservation: Pass observations unchanged. Without origin, a wait covers every model on the account, and without cause, it counts as a rate limit. Older Atomic versions ignore both fields and apply such waits to every model as a rate limit.

Choose session storage

By default, sessions save to local SQLite at ~/.atomic/workflows/journal.sqlite with the session_ table prefix. Override session storage per session with sessionStore, storage, or an explicit sessionManager. See Storage for CLI session storage setup, Worktree snapshots for repository snapshots, and Configure session storage for complete recipes across all four session storage options, createAgentSessionRuntime() wiring, SessionManager operations, JsonlSessionStore exactDirectory behavior, adapter resolution, ownership rules, and StorageError handling. The following table summarizes the four session storage options: To open a local SQLite session that Atomic opens and closes in dispose(), pass sessionStore:
To share a caller-owned PostgreSQL pool across sessions (npm install @bastani/atomic-storage-postgres), pass { kind: "database", database }:
Keep these session storage rules in mind:
  • sessionStore versus storage: sessionStore accepts a SessionStore instance (SqlSessionStore, JsonlSessionStore, MemorySessionStore) or a tagged selection ({ kind: "sqlite" | "jsonl" | "memory" | "database" | "adapter", ... }). storage uses the settings.json shape ({ path, prefix? }, { database, prefix? }, { memory: true }, or { adapter, options?, secrets?, prefix? }) and doesn’t support JSONL.
  • Precedence: Atomic resolves session storage in order from sessionManager, sessionStore, storage, process flags and variables (ATOMIC_SESSIONS_STORAGE and ATOMIC_STORAGE), settings (sessions.storage before storage), and default SQLite. Memory is never an automatic fallback.
  • Ownership and mutations: Atomic closes stores it opened from selection objects during dispose(), while leaving caller-owned SessionStore, SessionManager, and database instances open. Await every SessionManager write and every atomic.appendEntry, setSessionName, setLabel, setThinkingLevel, and cycleThinkingLevel call; there is no flush() method. ExtensionContext.sessionSignal aborts when reload or shutdown starts so extensions can cancel waits while finishing in-flight writes.
For CLI session commands, the full SessionManager method list, operator setup, and cross-machine resume, see Sessions, SessionManager API, Storage, and Resume on any machine.

Handle human input without a terminal

Pass extensionBindings.humanInput implementing all five HostInput methods (confirm, select, input, editor, questionnaire; QuestionParams and QuestionnaireResult are exported from @bastani/atomic). The following example attaches, withdraws, and reattaches a host input adapter:
Implement HostInput according to these contracts:
  • Routing and cancellation: Every method receives { requestId, sessionId, signal, timeout? }. Route prompts by sessionId (child sessions inherit explicit humanInput; see Session-local task prompts) and dismiss UI immediately when signal aborts. Abort, reload, and disposal invalidate pending replies, including late replies from callbacks that ignored signal.
  • Return contracts: confirm returns a boolean; select returns one of the supplied options or undefined; input and editor return a string or undefined (preserving whitespace and empty strings). Malformed replies reject with an Error tagged with code: "InvalidHostInput"; false, cancellation, and errors never approve.
  • Omission rules: Omitting humanInput at creation leaves no input handler unless uiContext supplies dialogs. Without either, dialogs reject with an Error tagged with code: "HumanInputUnavailable", and ask_user_question returns { answers: [], cancelled: true, error: "no_ui" }. Omitting humanInput on bindExtensions() keeps the active adapter; passing null withdraws it. ui.custom isn’t part of HostInput.
  • Diagnostics and caches: onDiagnostic receives session-attributed notices (it doesn’t intercept console.*). MCP OAuth Proof Key for Code Exchange (PKCE) state and web-provider config caches remain session-local, while durable MCP tokens persist by server name.

Read stored session summaries

Read session.sessionSummary (summary and summarizedThroughId) or inspect SessionManager.list() and SessionManager.listAll(). Stored summaries stay readable when sessionSummary.enabled is false. SessionManager.inMemory() never generates summaries.

Restore checkouts with worktree snapshots

SQLite and adapter-backed sessions capture checkout state automatically; JSONL and in-memory sessions don’t capture snapshots. Passing a reopened sessionManager to createAgentSession({ sessionManager }) or runtime.rehydrate() restores missing or drifted checkouts into fresh worktrees while leaving matching local checkouts untouched. If a checkout can’t be rebuilt or Git isn’t available, resume continues with a warning notice instead of failing fast. The following example reopens a saved session so Atomic restores its recorded checkout state:
Replace the following:
  • SESSION_ID: The ID of a stored session in store.
Configure snapshot and blueprint behavior with these options:
  • Background blueprint builds: By default in the SDK (resume.waitForBlueprint: "tools"), createAgentSession() returns immediately while blueprint setup runs in the background and gates tool calls. Call await blueprintBuildSettled(sessionId) to wait explicitly, register onBlueprintBuildFinished(listener) for warnings, or set resume.waitForBlueprint: "prompt" to block startup (see Start the first turn while the build runs).
  • Per-session overrides and helpers: Override snapshot settings for one session with createAgentSession({ snapshots: { enabled: false } }). Exported helpers include captureWorktreeSnapshot(), restoreWorktreeSnapshot(), verifyWorktree(), session.sessionManager.getWorktreeRootMappings(), latestResumeTimings(), formatResumeTimings(), and session.exportToJsonl().
For snapshot settings, retention, and recovery details, see Worktree snapshots, Worktree snapshots reference, and Resume on any machine.

Isolate Intercom groups and reach

To isolate multi-session hosts in one process, pass broker-enforced intercom policies to createAgentSession() or createAgentSessionFromServices():
Intercom policies follow these rules:
  • Home group and one-way reach: group sets the session’s home group, overriding ATOMIC_INTERCOM_GROUP, Intercom config, and project groups. reachable lists up to 1,000 one-way target groups (targets can reply to asks, not initiate messages). Subagents with group: "x" live under <group>/x and never inherit reachable.
  • Validation: Atomic trims surrounding whitespace from group names. Names can’t be empty, can’t exceed 1,024 characters, and can’t use the reserved names "auto" or "true" (case-insensitively). Atomic removes duplicates and self-references in reachable automatically.
  • Live updates: setReachable() updates live policy on the broker and leaves newly unreachable groups. Calling it on a session created without intercom, or passing an invalid group name or more than 1,000 reachable groups, throws IntercomPolicyError (which extends TypeError).

Configure subagent children

Subagent child sessions inherit the parent’s ModelRuntime, settings, agentDir, scopedModels, fallbackModels, customTools, resourceAdmission, humanInput, and diagnostics. Working directory resolves in order: child workspace, child cwd, child sessionManager.getCwd(), then parent cwd or worktree. Subagent child sessions follow these additional rules:
  • Permission narrowing: Child tool lists can only narrow parent permissions, never expand them (builtins, excludedTools, tools: [], and noTools: "all" stay enforced).
  • Human input overrides: Pass explicit child extensionBindings.humanInput to override the parent adapter, or pass null to withdraw it. Shared callbacks distinguish children by sessionId.

Drive a session

AgentSession is the primary handle for prompting, queueing, model switching, events, compaction, and disposal. The following interface shows its core members:
AgentSession also exposes stopTurns(), sendUserMessage(), sendCustomMessage(), executeBash(), abortBash(), exportToJsonl(), exportToHtml(), getSessionStats(), getContextUsage(), setActiveToolsByName(), setScopedModels(), reload(), and cache-warming controls (cacheWarmingStatus, setCacheWarmingMode()). See AgentSession and AgentSessionRuntime for every method. Always await session.dispose() in finally (60-second drain limit). If any cleanup step fails or stalls, dispose() rejects with an AggregateError tagged with code: "ShutdownFailed" (inspect error.errors for the individual causes). Pass { pauseQueuedMessages: true } when aborting before disposal so arriving background notices don’t start another turn:
Keep these model and extension rules in mind while driving a session:
  • Model and thinking updates: setModel(model, { thinkingLevel: "high", persist: true }) clamps unsupported thinking levels and optionally writes global defaults (project overrides still win at startup).
  • Live compaction and decision model switches: setCompactionModel(model, scope?, options?) and setDecisionModel(model, scope?, options?) update the active session immediately without restarting or running /reload, saving to "global" or "project" settings unless you pass { persist: false }. For compaction, pass "" or "auto" for automatic memory compaction or an exact compactor provider/model ID. For decisions, pass an exact registered classifier provider/model ID or "" to unset it (when you omit scope, a trusted project override updates in place). Invalid values throw CompactionConfigError, DecisionConfigError, or DecisionModelUnavailableError synchronously without mutating the active setting. See Compaction and Make structured decisions.
  • Closed-session rejections: Extension APIs reject new actions with an Error tagged with code: "SessionClosed" after close or reload starts. Give atomic.exec() calls timeouts or abort signals. Custom messages with persistWhenStreaming: true survive reload.

Subscribe to external event streams

To subscribe a session to external event streams without cluttering the main conversation context (maxConcurrent defaults to 4, with optional name and maxRate), pass an EventSource to session.subscribe():
Event subscriptions follow these rules:
  • Child tasks: child.task({ prompt, model?, thinkingLevel?, tools?, noTools?, excludedTools? }) runs a short-lived child session (<name>#<index>/<eventId>) equipped with report_to_subscriber (call child.report() directly when noTools: "all"), returning { text, sessionId }. Disposing of the parent aborts children (AbortError, with cleanup errors in cleanupCause). Sessions not created with createAgentSession() fail with SubscriptionChildUnavailableError.
  • Reporting and deduplication: child.report(text) sends an event_report custom message (details: { subscriptionId, eventId, child }), persisted before returning if streaming. Atomic records processed event IDs in event_subscription_processed entries and finished child answers (up to 500 characters) in event_subscription_child entries. Persistence failures reject subscription.done with SubscriptionRecordError. Pass subscription.id to publishEvent() to bridge custom webhooks.

Drain work on reload and shutdown

Disposal and reload drain admitted callbacks, model refreshes, and atomic.exec() subprocesses. Register cleanup before acquiring resources, pass timeouts or abort signals to subprocesses, unsubscribe atomic.events.on() listeners when finished, and never await disposal from inside a cleanup handler. Keep these shutdown details in mind:
  • runtime.dispose(): Rejects new replacements, drains pending work, waits up to 3 seconds for in-flight OAuth token refreshes, and stops Intercom broker startup. Pass { fromSignal: true } on SIGTERM or SIGHUP so session_shutdown handlers receive the signal flag.
  • Unrecovered settings and bash IDs: Unrecovered persist: true settings write failures cause dispose() to reject with AggregateError (code: "ShutdownFailed"). executeBash() IDs are correlation IDs: abortBash(id) cancels all active calls sharing that ID.
  • Reload effects: For publishExtensionContextEffect and registerExtensionContextRetirementEffect, see Reload lifecycle and resource ownership.

Compact context and navigate the session tree

session.compact({ query?, compactionModel? }) stops active runs, clears context or replaces it with output from a configured compactor model such as morph/morph-compactor, appends a verbatim-lines compaction entry, and returns VerbatimCompactionResult (form: "cleared" | "compacted"). To trigger compaction with a focus query, run:
Compaction and tree navigation behave as follows:
  • session.compact() rejects with CompactionStateError (code: "nothing-to-compact") when nothing new has entered context since the last boundary; concurrent calls coalesce.
  • Call session.setCompactionModel(model, scope?, options?) to change the configured compactor live. A chat, classifier, or unknown compactionModel ID clears the context with a notice instead of failing. See Compaction errors, Compaction, and Session format.
  • session.navigateTree() rejects if the session is streaming, compacting, or summarizing a branch, leaving the active branch unchanged.

Replace and rehydrate sessions

When your app displays progress while opening a session, see Show your own loading indicator to wire progress events from runtime.subscribe(). Use createAgentSessionRuntime() and AgentSessionRuntime when your host needs session replacement (newSession(), switchSession(), fork(), cloning with fork(entryId, { position: "at" }), importFromJsonl()) with rebuilt working-directory services:
After any replacement, runtime.session points to the new session. Re-subscribe to events, call bindExtensions() again, call runtime.takeResumeNotices() to display resume warnings, and call startPendingRecovery("resume") after switchSession(). Pass interactive: true to createAgentSessionRuntime() only when attaching an interactive UI (by default false, so resumed worktree blueprint builds run behind the first turn unless resume.waitForBlueprint is set).

Release idle sessions

In a host that sleeps sessions and wakes them on fresh machines—or in a long-lived server managing many idle conversations—call session.release() to free in-memory resources (agent loop, extensions, tools, timers, MCP, and Intercom connections) and runtime.rehydrate(sessionId) to restore them on demand:
Release and rehydration follow these rules:
  • Auto-release: Pass releaseWhenIdle: { afterMs } (0 to 2,147,483,647 ms; invalid values throw AgentReleaseConfigError) to createAgentSession() or createAgentSessionFromServices(). Combining releaseWhenIdle with SessionManager.inMemory() rejects immediately in createAgentSession() with AgentRehydrateError (code: "not-reopenable") before constructing the session. If the session is busy when the timer fires, Atomic reschedules for another afterMs instead of failing. Wakes are coordinated by the process-wide agentWakeDispatcher() (handle, deliver, onUnobservedFailure, whenIdle, stats()).
  • Lifecycle: release() emits session_released before closing and rejects with retryable session-busy if streaming, compacting, running shells or background tasks, or holding queued messages. rehydrate() opens at the active context window (readHistory() and readEntry() fetch older entries), shares matching-cwd services, runs alongside runtime.session without replacing it, deduplicates concurrent calls, and closes on runtime.dispose().
  • In-memory store spilling: A directly constructed new MemorySessionStore() keeps released session history in RAM. Opening a memory store through resolveSessionStore(cwd, { agentDir, sessionStore: { kind: "memory" } }) enables disk spilling to private owner-only files (0700/0600) under <agentDir>/released-history/ with integrity checks (SessionSpillError on missing or corrupt files; see Storage errors). Spill files clean up on exit and sweep on restart after crashes; hosts running in worker threads must close stores before worker.terminate(). Custom stores can implement releaseSession(id), readEntryRange(id, query), and readForkWindow(id, entryId).
Release and wake errors throw AgentRehydrateError (guards isAgentRehydrateError, isAgentReleaseConfigError, isRetryableAgentRehydrateError; cross-process serializeAgentRehydrateError and rehydrateAgentRehydrateError). The following table lists every error code:

Send prompts and queue messages

session.prompt() accepts the following PromptOptions:
Prompt and queue methods behave as follows:
  • Basic versus streaming prompts: prompt() expands file-based prompt templates and runs extension commands immediately, even while streaming. Calling prompt() while streaming without streamingBehavior throws AgentSessionBusyError (code: "agent_session_busy", guard isAgentSessionBusyError). Prompts arriving during compaction queue automatically.
  • startTurnOnly: When true, prompt() starts a turn only if the session is idle and queued messages aren’t paused. Otherwise it sends and queues nothing, calls preflightResult(true, "handled"), and resolves with undefined.
  • preflightResult(success, disposition?): Fires once before prompt() settles (true with "handled", "queued", or "started"; false on preflight rejection).
  • steer() and followUp(): Accept (text, images?, options?) and return Promise<"handled" | "queued">. They queue during streaming, start a turn immediately if idle with existing messages (staying queued on empty or aborted sessions), expand templates, and reject extension commands.
  • Queue control: clearQueue() returns { steering, followUp, typed?, images? } (typed preserves pre-hook text so re-submitting doesn’t rerun hooks). pauseQueuedMessages() holds queues across an abort boundary; resumeQueuedMessages() releases the hold once (returning true if held work existed) without starting a turn.

Inspect Agent and AgentState

Access the underlying @bastani/atomic-agent-core Agent through session.agent (state.messages, model, thinkingLevel, systemPrompt, tools, streamingMessage, errorMessage, and waitForIdle()). session.sessionManager is the source of truth for model context (see SessionManager API). Never mutate session.agent.state.messages directly to restore history. Instead, pass entries to SessionManager.inMemory(cwd, { id }, entries) before createAgentSession(), call session.navigateTree(), or append with session.sessionManager.appendMessage() followed by session.refreshContext().

Collect transcripts from events

Subscribe with session.subscribe((event) => ...) for message_start, message_update, message_end, tool_execution_start, tool_execution_update, tool_execution_end, agent_start, agent_end, agent_settled, turn_start, turn_end, queue_update, compaction_start, compaction_end, session_storage_reconnect, and retry or fallback events. Never mutate message_start’s live partial object; seed mid-turn subscribers from session.agent.state.streamingMessage. To reduce events into ordered JSON-serializable parts (text, thinking, and toolCall paired with its result), use createTranscript():
Pass toolResult: (name) => "details" | "content" to prefer structured details over text. createTranscript() omits redacted thinking and ignores nested tool events (parentToolCallId). A toolCall part gains its result (isError, isPartial) when the tool emits progress or finishes, with isPartial: true until completion. If the message fails or aborts, unfinished tool calls receive an error result carrying the error message.

Complete example

The following end-to-end example configures ModelRuntime, registers a custom tool using @bastani/atomic/typebox, applies in-memory settings, overrides the system prompt, streams text deltas, and disposes cleanly:
Replace the following:
  • AGENT_DIR: The directory where Atomic stores auth and config files for this host, for example "/var/lib/payments-agent".

Runtime notes and upgrades

Use these sections when handling SDK errors, upgrading in place, or moving off older Node.js releases.

Error classes versus .code-tagged errors

NativeModuleUnavailableError is an exported class (code: "NativeModuleUnavailable"). By contrast, ShutdownFailed, HumanInputUnavailable, InvalidHostInput, BuiltinUnavailable, and SessionClosed aren’t exported classes; they are standard Error (or AggregateError for ShutdownFailed) instances tagged with string .code properties. Branch on (error as { code?: string }).code instead of instanceof.

Update Atomic while your process runs

When npm install, pnpm add, or bun add replaces @bastani/atomic while a Node.js host is running, modules already loaded stay in memory while newly imported modules load from disk. createAgentSession() verifies @bastani/atomic-natives before opening a session and throws NativeModuleUnavailableError when it can’t load or doesn’t match the running release:
  • If the native module was missing on disk, later calls retry after it is installed.
  • If a native module from another release was already loaded, createAgentSession() continues throwing NativeModuleUnavailableError until the process restarts (updating its message after the matching release is reinstalled).
Restart the host process after an in-place update if it launched on an older Atomic release or before importing @bastani/atomic/rpc-entry.

Upgrade from Node.js 22 hosts

Atomic requires Node.js 24.20.0 or newer and doesn’t run on Node.js 22. To upgrade a Node.js 22 host:
  1. Check your installed version with node --version.
  2. Install Node.js 24.20.0 or newer from nodejs.org, or with nvm install 24, fnm install 24, or mise use -g node@24.
  3. Reinstall project dependencies with npm install.
  4. Remove --experimental-async-context-frame from your startup command if you passed it on Node.js 22 (Node.js 24 refuses to start with that flag).
See Node.js version for details.

Migrate from earlier Atomic releases

When upgrading an older Node.js host, apply these changes:
  • Builtins load automatically: Remove manual registration of shipped builtin extensions. Disable them selectively with builtins and restrict tools with tools or excludedTools (tools: [] excludes Intercom too).
  • Host input: Supply all five HostInput methods (confirm, select, input, editor, questionnaire) on extensionBindings.humanInput, honoring abort signals and returning literal true only on explicit approval. Omission rejects with code: "HumanInputUnavailable".
  • Removed workflows builtin: Remove workflows from builtins; Atomic removed workflow SDK exports. Convert older workflow files into skills (see Migrating workflows).
  • Async disposal: Always await session.dispose() in finally. Disposal can reject with AggregateError (code: "ShutdownFailed") after attempting all cleanup; don’t swallow it or call process.exit().
  • Diagnostics and packaging: Capture operational events through extensionBindings.onDiagnostic. If creation fails with code: "BuiltinUnavailable", reinstall the full package instead of copying only dist/index.js.
  • Removed experimental client: Atomic removed @bastani/atomic/client. Embed createAgentSession() directly or drive RPC mode (--mode rpc or @bastani/atomic/rpc-entry).

Troubleshooting

Use the following table to resolve common SDK errors:

Next steps

SDK API reference

Look up every factory option, AgentSession and AgentSessionRuntime method, run mode, and export.

Configure session storage

Wire SQLite, JSONL, in-memory, and PostgreSQL session storage with explicit ownership and error handling.

Make structured decisions

Evaluate typed classifier and chat decisions with decide() and generateStructuredOutput().

Stream from a web server

Expose an AgentSession behind a Next.js App Router endpoint with NDJSON streaming.