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_KEYorOPENAI_API_KEY) or saved withatomic 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:ModelRuntime: Async runtime for credentials, native providers, and dynamic catalogs. AcceptsauthPath,modelsPath,credentials, runtime auth overrides, and catalog options (allowModelNetwork,modelRefreshTimeoutMs,modelsStorePath,modelsStore; see Model catalog persistence and refresh). Legacy synchronous facadesModelRegistryandAuthStorageremain available, andreadStoredCredential(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 receiveundefinedwithout falling back to a default. - Context helpers: Root exports include
InlineExtension,buildContextEntries,sessionEntryToContextMessages,CompactionEntry, andsessionManager.buildContextEntries().
Share Atomic’s TypeBox registry
Atomic ships its own TypeBox instance. If your app importstypebox 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:
- Disable builtins or tools: Pass
builtins: { "web-access": false, intercom: false }to disable bundled packages. Passingtools: []ornoTools: "all"disables every tool, including Intercom.excludedToolsalways wins and survives/reload. See Tools for wildcard matching and MCP retention rules. - Startup hooks and rebinding:
createAgentSession()runs extensionsession_starthooks before resolving. PassextensionBindingshere if startup hooks need them; latersession.bindExtensions(...)calls update bindings without replayingsession_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 withworkspace({ ... }) (requires Git 2.33 or newer). The following example creates a writable session and a read-only reviewer session on the same workspace:
- Resolution: A local
repomust point to a repository root. Remote repositories clone once under<storageHome>/repos/(see Storage home) and create worktrees after fetching. Missing branches start frombase; existing worktrees must match the repository and branch. Explicitcwdmust stay inside the worktree, and an explicitsessionManagermust already point inside it (otherwise Atomic throwsWorkspaceConfigError). - 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 blockswrite,edit, andtodoeven if listed intools. Child sessions stay read-only even with their own workspace. - Persistence and pull requests: Bindings persist as a
workspace_bindingentry and restore on reopen. CallbindSessionWorkspace(workspace, sessionManager, signal?)beforehand if you need the resolved path early. Inspect commits withworkspaceChangeSet(binding)and open pull requests withpublishPullRequest(changeSet, { draft: true }). - Errors: Invalid options throw
WorkspaceConfigError. Binding failures throwWorkspaceBindingErrorwithcodeset towrong-repository,wrong-branch,conflicting-worktree-input,invalid-repository,unknown-base,cwd-outside-worktree,git-unavailable,git-failed,filesystem-failed,drift,writer-conflict, orincomplete-worktree. See Workspace for the full helper and error-class list.
Enforce shared resource admission
To enforce host-wide session and process capacity limits, pass aresourceAdmission service to createAgentSession():
ResourceAdmission:
- Kind and cancellation:
kindis"session"or"process". Honorsignalinsideacquire()(resourceAdmissionSignalcancels 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 queuerequest.delegatedacquisitions. 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, implementpermit.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, andresourceAdmission: nullopts 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:observeProviderRateLimits(listener)callslistenereach 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).
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:
npm install @bastani/atomic-storage-postgres), pass { kind: "database", database }:
sessionStoreversusstorage:sessionStoreaccepts aSessionStoreinstance (SqlSessionStore,JsonlSessionStore,MemorySessionStore) or a tagged selection ({ kind: "sqlite" | "jsonl" | "memory" | "database" | "adapter", ... }).storageuses thesettings.jsonshape ({ 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_STORAGEandATOMIC_STORAGE), settings (sessions.storagebeforestorage), 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-ownedSessionStore,SessionManager, anddatabaseinstances open. Await everySessionManagerwrite and everyatomic.appendEntry,setSessionName,setLabel,setThinkingLevel, andcycleThinkingLevelcall; there is noflush()method.ExtensionContext.sessionSignalaborts when reload or shutdown starts so extensions can cancel waits while finishing in-flight writes.
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
PassextensionBindings.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:
HostInput according to these contracts:
- Routing and cancellation: Every method receives
{ requestId, sessionId, signal, timeout? }. Route prompts bysessionId(child sessions inherit explicithumanInput; see Session-local task prompts) and dismiss UI immediately whensignalaborts. Abort, reload, and disposal invalidate pending replies, including late replies from callbacks that ignoredsignal. - Return contracts:
confirmreturns a boolean;selectreturns one of the supplied options orundefined;inputandeditorreturn a string orundefined(preserving whitespace and empty strings). Malformed replies reject with anErrortagged withcode: "InvalidHostInput";false, cancellation, and errors never approve. - Omission rules: Omitting
humanInputat creation leaves no input handler unlessuiContextsupplies dialogs. Without either, dialogs reject with anErrortagged withcode: "HumanInputUnavailable", andask_user_questionreturns{ answers: [], cancelled: true, error: "no_ui" }. OmittinghumanInputonbindExtensions()keeps the active adapter; passingnullwithdraws it.ui.customisn’t part ofHostInput. - Diagnostics and caches:
onDiagnosticreceives session-attributed notices (it doesn’t interceptconsole.*). 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
Readsession.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 reopenedsessionManager 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:
SESSION_ID: The ID of a stored session instore.
- 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. Callawait blueprintBuildSettled(sessionId)to wait explicitly, registeronBlueprintBuildFinished(listener)for warnings, or setresume.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 includecaptureWorktreeSnapshot(),restoreWorktreeSnapshot(),verifyWorktree(),session.sessionManager.getWorktreeRootMappings(),latestResumeTimings(),formatResumeTimings(), andsession.exportToJsonl().
Isolate Intercom groups and reach
To isolate multi-session hosts in one process, pass broker-enforcedintercom policies to createAgentSession() or createAgentSessionFromServices():
- Home group and one-way reach:
groupsets the session’s home group, overridingATOMIC_INTERCOM_GROUP, Intercom config, and project groups.reachablelists up to 1,000 one-way target groups (targets can reply to asks, not initiate messages). Subagents withgroup: "x"live under<group>/xand never inheritreachable. - 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 inreachableautomatically. - Live updates:
setReachable()updates live policy on the broker and leaves newly unreachable groups. Calling it on a session created withoutintercom, or passing an invalid group name or more than 1,000 reachable groups, throwsIntercomPolicyError(which extendsTypeError).
Configure subagent children
Subagent child sessions inherit the parent’sModelRuntime, 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: [], andnoTools: "all"stay enforced). - Human input overrides: Pass explicit child
extensionBindings.humanInputto override the parent adapter, or passnullto withdraw it. Shared callbacks distinguish children bysessionId.
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:
- 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?)andsetDecisionModel(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 compactorprovider/modelID. For decisions, pass an exact registered classifierprovider/modelID or""to unset it (when you omitscope, a trusted project override updates in place). Invalid values throwCompactionConfigError,DecisionConfigError, orDecisionModelUnavailableErrorsynchronously without mutating the active setting. See Compaction and Make structured decisions. - Closed-session rejections: Extension APIs reject new actions with an
Errortagged withcode: "SessionClosed"after close or reload starts. Giveatomic.exec()calls timeouts or abort signals. Custom messages withpersistWhenStreaming: truesurvive 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():
- Child tasks:
child.task({ prompt, model?, thinkingLevel?, tools?, noTools?, excludedTools? })runs a short-lived child session (<name>#<index>/<eventId>) equipped withreport_to_subscriber(callchild.report()directly whennoTools: "all"), returning{ text, sessionId }. Disposing of the parent aborts children (AbortError, with cleanup errors incleanupCause). Sessions not created withcreateAgentSession()fail withSubscriptionChildUnavailableError. - Reporting and deduplication:
child.report(text)sends anevent_reportcustom message (details: { subscriptionId, eventId, child }), persisted before returning if streaming. Atomic records processed event IDs inevent_subscription_processedentries and finished child answers (up to 500 characters) inevent_subscription_childentries. Persistence failures rejectsubscription.donewithSubscriptionRecordError. Passsubscription.idtopublishEvent()to bridge custom webhooks.
Drain work on reload and shutdown
Disposal and reload drain admitted callbacks, model refreshes, andatomic.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 }onSIGTERMorSIGHUPsosession_shutdownhandlers receive the signal flag.- Unrecovered settings and bash IDs: Unrecovered
persist: truesettings write failures causedispose()to reject withAggregateError(code: "ShutdownFailed").executeBash()IDs are correlation IDs:abortBash(id)cancels all active calls sharing that ID. - Reload effects: For
publishExtensionContextEffectandregisterExtensionContextRetirementEffect, 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:
session.compact()rejects withCompactionStateError(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 unknowncompactionModelID 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 fromruntime.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:
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—callsession.release() to free in-memory resources (agent loop, extensions, tools, timers, MCP, and Intercom connections) and runtime.rehydrate(sessionId) to restore them on demand:
- Auto-release: Pass
releaseWhenIdle: { afterMs }(0to2,147,483,647ms; invalid values throwAgentReleaseConfigError) tocreateAgentSession()orcreateAgentSessionFromServices(). CombiningreleaseWhenIdlewithSessionManager.inMemory()rejects immediately increateAgentSession()withAgentRehydrateError(code: "not-reopenable") before constructing the session. If the session is busy when the timer fires, Atomic reschedules for anotherafterMsinstead of failing. Wakes are coordinated by the process-wideagentWakeDispatcher()(handle,deliver,onUnobservedFailure,whenIdle,stats()). - Lifecycle:
release()emitssession_releasedbefore closing and rejects with retryablesession-busyif streaming, compacting, running shells or background tasks, or holding queued messages.rehydrate()opens at the active context window (readHistory()andreadEntry()fetch older entries), shares matching-cwdservices, runs alongsideruntime.sessionwithout replacing it, deduplicates concurrent calls, and closes onruntime.dispose(). - In-memory store spilling: A directly constructed
new MemorySessionStore()keeps released session history in RAM. Opening a memory store throughresolveSessionStore(cwd, { agentDir, sessionStore: { kind: "memory" } })enables disk spilling to private owner-only files (0700/0600) under<agentDir>/released-history/with integrity checks (SessionSpillErroron 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 beforeworker.terminate(). Custom stores can implementreleaseSession(id),readEntryRange(id, query), andreadForkWindow(id, entryId).
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:
- Basic versus streaming prompts:
prompt()expands file-based prompt templates and runs extension commands immediately, even while streaming. Callingprompt()while streaming withoutstreamingBehaviorthrowsAgentSessionBusyError(code: "agent_session_busy", guardisAgentSessionBusyError). Prompts arriving during compaction queue automatically. startTurnOnly: Whentrue,prompt()starts a turn only if the session is idle and queued messages aren’t paused. Otherwise it sends and queues nothing, callspreflightResult(true, "handled"), and resolves withundefined.preflightResult(success, disposition?): Fires once beforeprompt()settles (truewith"handled","queued", or"started";falseon preflight rejection).steer()andfollowUp(): Accept(text, images?, options?)and returnPromise<"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? }(typedpreserves pre-hook text so re-submitting doesn’t rerun hooks).pauseQueuedMessages()holds queues across an abort boundary;resumeQueuedMessages()releases the hold once (returningtrueif 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 withsession.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():
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 configuresModelRuntime, registers a custom tool using @bastani/atomic/typebox, applies in-memory settings, overrides the system prompt, streams text deltas, and disposes cleanly:
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
Whennpm 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 throwingNativeModuleUnavailableErroruntil the process restarts (updating its message after the matching release is reinstalled).
@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:- Check your installed version with
node --version. - Install Node.js 24.20.0 or newer from nodejs.org, or with
nvm install 24,fnm install 24, ormise use -g node@24. - Reinstall project dependencies with
npm install. - Remove
--experimental-async-context-framefrom your startup command if you passed it on Node.js 22 (Node.js 24 refuses to start with that flag).
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
builtinsand restrict tools withtoolsorexcludedTools(tools: []excludes Intercom too). - Host input: Supply all five
HostInputmethods (confirm,select,input,editor,questionnaire) onextensionBindings.humanInput, honoring abort signals and returning literaltrueonly on explicit approval. Omission rejects withcode: "HumanInputUnavailable". - Removed
workflowsbuiltin: Removeworkflowsfrombuiltins; Atomic removed workflow SDK exports. Convert older workflow files into skills (see Migrating workflows). - Async disposal: Always
await session.dispose()infinally. Disposal can reject withAggregateError(code: "ShutdownFailed") after attempting all cleanup; don’t swallow it or callprocess.exit(). - Diagnostics and packaging: Capture operational events through
extensionBindings.onDiagnostic. If creation fails withcode: "BuiltinUnavailable", reinstall the full package instead of copying onlydist/index.js. - Removed experimental client: Atomic removed
@bastani/atomic/client. EmbedcreateAgentSession()directly or drive RPC mode (--mode rpcor@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.