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
Quick start
Create~/.atomic/agent/extensions/my-extension.ts (the factory parameter can have any name; older extensions and examples call it pi):
-e (or --extension):
Loading 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 these locations:
Discovery rules:
- Scanning respects
.gitignore,.ignore, and.fdignoreinside extension directories, and skips dotfiles, dot-directories, andnode_modules. - Disable auto-discovery with
--no-extensions(-ne). 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:
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 rather than filesystem paths. Toggle them 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 are evaluated in array order (last match wins), so "+builtin:codemode" re-enables a globally excluded built-in. You can also load a built-in explicitly alongside --no-extensions (-ne):
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 do not 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:
Atomic maintains these packages directly; Libraries documents each one. Legacy import names (
@earendil-works/pi-*, @mariozechner/pi-*, and @bastani/pi-ai) resolve to the same modules, including in release-archive installs. New extensions should import the @bastani/atomic-* names.
Node.js built-ins (node:fs, node:path, and the rest of node:*) are always available.
Third-party npm dependencies: 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 are 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 (such as an MCP server’s schema or one built with
@bastani/atomic-schema) is coerced and checked by@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, but UI availability differs:
Check
ctx.hasUI (or ctx.mode === "tui") before showing terminal UI, and check ctx.hasHumanInput before calling dialog methods in extensions that may run in print or JSON modes.
Reloading and startup behavior
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.
- 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. Named npm packages, files undernode_modulesoutside the extension’s own package, and modules loaded viacreateRequire()are loaded 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 does not freeze keyboard input or terminal spinners.Cancellation and Ctrl+C safety
- Escape asks the active turn or tool to cancel cooperatively and waits until it finishes. Escape never kills the worker process, so in-flight tool state is not 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+Cterminates and restarts the worker (taking priority over custom UI bindings). BothEscapeandCtrl+Cmatch physical keys, so rebindingapp.clearcannot disable recovery.
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 is not 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 may already have had side effects.
- If you spawn child processes from an extension, derive an explicit
envobject fromprocess.env; internal startup variables are not 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 are unavailable or 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()/setToolsExpanded()track only a worker-local boolean,editor()omitstimeoutcountdowns, andgetChatRenderSettings()returns static defaults for some display fields.