Write an extension
Structure an extension, manage state across reloads, register custom tools, and customize terminal rendering.
Extension events
Look up every lifecycle event, payload shape, handler chaining rule, and return contract.
Build custom UI
Build dialogs, widgets, host-native pickers and forms, custom components, overlays, and message renderers.
Extension API reference
Reference
ExtensionContext, ExtensionToolContext, ExtensionCommandContext, ExtensionAPI methods, and typed errors.Extension examples
Browse runnable extensions shipped with Atomic for tools, gates, UI, sandboxes, and providers.
SDK extensions
Load extensions programmatically with
DefaultResourceLoader, pass inline factories, or register standalone customTools.What extensions can do
The following table maps common customization goals to the main extension APIs:Before you begin
Before building your first extension, confirm the following:- Atomic is installed and available on your
PATH. - For project extensions under
.atomic/extensions/, you have granted project trust with/trustor--approve.
Quick start
Follow these steps to create and test your first extension:1
Create the extension file
Save the following TypeScript module as
./my-extension.ts (the factory parameter can have any name; older extensions and examples call it pi):2
Run Atomic with the extension
Test the file for one session without installing it globally by passing
-e (--extension):3
Verify the extension loaded
Confirm that the
Extension loaded! notification appears at startup, then run /hello Atomic to verify the slash command responds with Hello Atomic!. To keep the extension loaded in every session, move it into ~/.atomic/agent/extensions/.Load extensions in the SDK
Embedded apps can load extension files, pass inline factories throughDefaultResourceLoader, or register standalone tools directly with createAgentSession({ customTools }):
Extension locations
Atomic auto-discovers extensions from the locations listed in the following table (%USERPROFILE%\.atomic\agent\extensions\ on Windows):
Extension discovery follows these rules:
- Scanning respects
.gitignore,.ignore, and.fdignoreinside extension directories, and skips dotfiles, dot-directories, andnode_modules. - Pass
--no-extensions(-ne) to disable auto-discovery. Explicit-epaths and the mandatory bundled Intercom extension still load. - Atomic also discovers extensions and packages inherited from legacy
~/.pi/agentand.pidirectories. If an inherited legacy extension registers the same tool, command, prompt, flag, or shortcut name as a bundled Atomic extension, Atomic keeps the bundled registration and skips only the conflicting registration (summarized in yellow on interactive startup). Extensions configured under.atomicor passed with-efollow normal override rules.
settings.json:
settings.json (~/.atomic/agent/ or .atomic/). To share extensions over npm or Git, see Install and manage packages.
Built-in extension resources
Atomic exposesbuiltin:llama.cpp (llama.cpp), builtin:codemode (Codemode), and builtin:tool-search (which registers the tool_search tool) as built-in extension resources instead of filesystem paths. Turn them on or off interactively in atomic config, or disable one in settings.json:
settings.json, extensions entries follow operator precedence (! < + < -). In a trusted project’s settings.json, override entries evaluate in array order (last match wins), so "+builtin:codemode" re-enables a globally excluded built-in.
To load a built-in explicitly alongside --no-extensions (-ne), pass it with -e:
builtin:<name> with -e stops with Unknown built-in extension: builtin:<name>.
Loading a built-in resource registers its tool. codemode is enabled in the default tool list (so a custom --tools list must name it), while tool_search is opt-in. Both codemode and tool-search are replaceable: a custom extension that registers the same tool, command, or flag takes over, and Atomic reports the replacement. Disable that extension in atomic config to restore the built-in version.
These built-in names don’t replace Atomic’s bundled MCP, subagent, web-access, or Intercom packages. There are no builtin:mcp or builtin:subagents aliases; configure those through package settings and MCP servers.
Available imports
Extensions can import Atomic’s bundled packages without installing them innode_modules. The following table lists every host-provided package:
Atomic maintains these packages directly; see Standalone libraries for details on each one. Legacy import names (
@earendil-works/pi-*, @mariozechner/pi-*, and @bastani/pi-ai) resolve to the same modules, including in release-archive installs. Import the @bastani/atomic-* names in your extensions.
Node.js built-ins (node:fs, node:path, and the rest of node:*) are always available.
To use third-party npm packages, add a package.json next to your extension (or in a parent directory) and install dependencies with npm install (or your package manager). Imports from node_modules/ resolve automatically. For distributed packages installed with atomic install, declare runtime dependencies in dependencies (devDependencies are omitted by default; see Install and manage packages for npmCommand details).
Tool parameter schemas
A tool’sparameters can be a TypeBox schema or any plain JSON Schema object. Atomic validates arguments from the model after coercing loosely typed values (such as a numeric string to a number, "true" to true, or dropping null on an optional property):
- TypeBox schemas: Validated by TypeBox, so TypeBox features outside JSON Schema (such as
Type.Refine()and formats registered withFormat.Set()) apply and errors use TypeBox’s format. - Plain JSON Schema:
@bastani/atomic-schemacoerces and checks schemas from MCP servers or@bastani/atomic-schema. Single values wrap into one-item arrays when an array is expected,urlandjson-pointer-uri-fragmentformats are checked, and an unresolved$refrejects only that field instead of every call. Errors use@bastani/atomic-schema’s format, such as- path: missingor- limit: expected number, got string.
Mode behavior
Extensions run in every Atomic mode, though UI availability differs across modes. The following table compares UI support in interactive, Remote Procedure Call (RPC), JSON, and print runtimes:
Check
ctx.hasUI (or ctx.mode === "tui") before showing terminal UI, and check ctx.hasHumanInput before calling dialog methods in extensions that might run in print or JSON modes.
Reload behavior and startup errors
Auto-discovered extensions hot-reload when you run/reload. Atomic transpiles each extension file along with local TypeScript, JavaScript (.mjs, .cjs, .js), and JSON files it imports by relative path, so edits to those local files take effect on /reload.
Reloading and startup error handling follow these rules:
- Module format: ESM files keep
import.meta.url, strict mode, top-levelawait, and package or Node built-in imports. CommonJS files keeprequire,module.exports,__filename, and__dirname. - Caching on
/reload: Atomic loads named npm packages, files undernode_modulesoutside the extension’s own package, and modules loaded throughcreateRequire()once per process. Restart Atomic after editing those files. - Load failures: If an optional extension fails to import or initialize during interactive startup or
/reload, Atomic skips it, lists its path and error under[Extension issues], and keeps the session open. Fix the issue and run/reload. In print (-p) and standalone RPC (--mode rpc) modes, any extension load failure prints the error and exits with code 1. Required built-in failures and cleanup failures stop startup in every mode. - Cleanup failures on
/reload: If a retiring extension’ssession_shutdownhandler fails during/reload, Atomic reports the failing handler while keeping the replacement extensions and updated settings active. Fix the cleanup error before reloading again.
Inside a Herdr pane, Atomic reports parent session status automatically with its built-in integration. See Herdr setup if you previously installed a separate Herdr status extension.
Responsive UI and crash recovery
In default interactive CLI mode, Atomic runs extensions in a separate background worker process so slow or stuck extension code doesn’t freeze keyboard input or terminal spinners.Cancellation and Ctrl+C safety
Atomic protects keyboard responsiveness with the following cancellation rules:- Escape asks the active turn or tool to cancel cooperatively and waits until it finishes. Escape never terminates the worker process, so in-flight tool state isn’t discarded mid-operation.
- Ctrl+C while custom UI is open:
- If a
ctx.ui.custom()component sets{ handlesCtrlC: true }, it receives the firstCtrl+Cpress for its own skip, close, or cancel behavior. If the same component still holds input on a secondCtrl+C, Atomic closes it so no extension can trap your keyboard. - Without
handlesCtrlC: true, the firstCtrl+Ccloses the component immediately, resolves itsctx.ui.custom()promise withundefined, and returns focus to the editor while the session keeps running. - Set
handlesCtrlC: truewhenever your component displays actrl+chint. Built-in selectors, dialogs, input forms, and session pickers handleCtrl+Cdirectly.
- If a
- Ctrl+C when the worker is hung: If the extension worker stops responding, an abort or restart waits longer than one second, or a prior restart failed,
Ctrl+Cstops and restarts the worker (taking priority over custom UI bindings). BothEscapeandCtrl+Cmatch physical keys, so rebindingapp.clearcan’t disable recovery.
Ctrl+C:
Automatic restart and queued messages
If the extension worker crashes unexpectedly, Atomic closes open custom UI and attempts one automatic restart. A clean restart stays quiet unless messages were still queued:- Queued main-chat messages return to the editor (steering messages first) with a warning such as
Engine restarted; 2 queued messages weren't sent and are back in the editor. - Queued subagent messages confirmed not yet sent return ahead of any draft in that subagent’s editor (immediately if open and writable, or when reopened), or print a notice if the subagent view is read-only. They are never placed into the main chat editor or sent twice.
- Drafts that never started are restored verbatim; work that already started isn’t retried automatically. If a saved tool call has no recorded result, reopening the session marks its result unavailable. Inspect affected files or external systems before retrying because the tool might already have had side effects.
- If you spawn child processes from an extension, derive an explicit
envobject fromprocess.env; internal startup variables aren’t exported there.
UI APIs in default interactive mode
Dialogs,ctx.ui.custom() components, widget factories, status text, notifications, setTitle(), setEditorText(), and host-native pickers and forms (hostSessionPicker(), hostInputForm()) all work in default interactive CLI mode. Values returned from ctx.ui.custom() must be JSON-serializable because they cross the worker boundary.
Because extensions run outside the terminal UI process in default interactive mode, several ctx.ui APIs behave differently:
- Warn and skip:
onTerminalInput(),getEditorText(),setEditorComponent(),addAutocompleteProvider(),setHeader(), andsetFooter(). - Silent no-ops or stubs:
setWorkingMessage(),setWorkingVisible(),setWorkingIndicator(),setHiddenThinkingLabel(),getAllThemes(),getTheme(),setTheme()(returns{ success: false, error: "Theme switching not supported in RPC mode" }), andatomic.registerMarkdownTransformer(). - Degraded behavior:
pasteToEditor()falls back tosetEditorText()(replacing text without paste collapse),getToolsExpanded()andsetToolsExpanded()track only a boolean local to the extension worker,editor()omitstimeoutcountdowns, andgetChatRenderSettings()uses static values forhiddenThinkingLabelandmarkdownTransformers.
Troubleshooting
The following table lists common extension startup and runtime issues and how to fix them:Next steps
Continue building extensions with these guides:- Learn extension layouts, state management, and custom tool patterns in Write an extension.
- Check every lifecycle event and return contract in Extension events.
- Add dialogs, widgets, and custom components in Build custom UI.
- Look up every context method and error class in the Extension API reference.