@bastani/atomic 0.10.9 → 0.10.10-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (406) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +226 -163
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +27 -12
  7. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js.map +1 -1
  8. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +47 -7
  9. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js.map +1 -1
  10. package/dist/_shared/mode-shared-2QJSCUM6.js +48 -19
  11. package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -1
  12. package/dist/_shared/{p1a-prewarm-UQY3X2UK.js → p1a-prewarm-XIU57JHF.js} +5 -5
  13. package/dist/_shared/{p1a-prewarm-UQY3X2UK.js.map → p1a-prewarm-XIU57JHF.js.map} +1 -1
  14. package/dist/_shared/p2-shell-main-B2WIALFD.js +30 -25
  15. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  16. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  17. package/dist/_shared/{sdk-OSBEPR3Q.js → sdk-RRLVN7ER.js} +15 -9
  18. package/dist/_shared/sdk-RRLVN7ER.js.map +1 -0
  19. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  20. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  21. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +4 -1
  22. package/dist/_shared/settings-startup-8-DNZ2RIHM.js.map +1 -1
  23. package/dist/_shared/{startup-0-0-TYUFUOJZ.js → startup-0-0-4VG2G44V.js} +427 -33
  24. package/dist/_shared/startup-0-0-4VG2G44V.js.map +1 -0
  25. package/dist/_shared/{startup-0-1-W2G2UY7R.js → startup-0-1-XTIL65D4.js} +18 -11
  26. package/dist/_shared/startup-0-1-XTIL65D4.js.map +1 -0
  27. package/dist/_shared/{startup-0-2-UXBUEOXW.js → startup-0-2-27OWFHV6.js} +150 -62
  28. package/dist/_shared/startup-0-2-27OWFHV6.js.map +1 -0
  29. package/dist/_shared/startup-0-3-T4DVFYWX.js +15 -25
  30. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +1 -1
  31. package/dist/_shared/{startup-0-4-HN5EB4K7.js → startup-0-4-ZMJV547D.js} +81 -12
  32. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -0
  33. package/dist/_shared/startup-0-5-FD2P735I.js +90 -50
  34. package/dist/_shared/startup-0-5-FD2P735I.js.map +1 -1
  35. package/dist/_shared/startup-10-0-TDQNBDDL.js +5 -5
  36. package/dist/_shared/startup-12-0-55AAXBJZ.js +13 -7
  37. package/dist/_shared/startup-12-0-55AAXBJZ.js.map +1 -1
  38. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -4
  39. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  40. package/dist/_shared/startup-15-1-4S7FLMNG.js +88 -28
  41. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  42. package/dist/_shared/startup-8-0-34CBHPZH.js +5 -5
  43. package/dist/_shared/startup-8-1-4KANEHRA.js +61 -17
  44. package/dist/_shared/startup-8-1-4KANEHRA.js.map +1 -1
  45. package/dist/_shared/storage-command-7MGXLJGZ.js +4 -4
  46. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  47. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  48. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  49. package/dist/builtin/intercom/README.md +87 -116
  50. package/dist/builtin/intercom/broker/broker.bundle.mjs +3 -3
  51. package/dist/builtin/intercom/broker/presence-handler.ts +1 -1
  52. package/dist/builtin/intercom/group.ts +7 -3
  53. package/dist/builtin/intercom/index.bundle.mjs +1 -1
  54. package/dist/builtin/intercom/package.json +1 -1
  55. package/dist/builtin/mcp/README.md +61 -27
  56. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  57. package/dist/builtin/mcp/package.json +1 -1
  58. package/dist/builtin/subagents/CHANGELOG.md +8 -0
  59. package/dist/builtin/subagents/README.md +74 -141
  60. package/dist/builtin/subagents/package.json +1 -1
  61. package/dist/builtin/subagents/src/extension/index.bundle.mjs +213 -74
  62. package/dist/builtin/web-access/CHANGELOG.md +9 -0
  63. package/dist/builtin/web-access/README.md +61 -88
  64. package/dist/builtin/web-access/index.bundle.mjs +387 -351
  65. package/dist/builtin/web-access/package.json +1 -1
  66. package/dist/cli/args.js +2 -2
  67. package/dist/cli/auth-cli.code.js +4 -4
  68. package/dist/cli/auth-cli.impl.js +3 -3
  69. package/dist/cli/auth-cli.js +3 -3
  70. package/dist/cli/blueprint-command.code.js +2 -2
  71. package/dist/cli/blueprint-command.impl.js +3 -3
  72. package/dist/cli/blueprint-command.js +3 -3
  73. package/dist/cli/intercom-command.code.js +3 -3
  74. package/dist/cli/intercom-command.impl.js +3 -3
  75. package/dist/cli/intercom-command.js +3 -3
  76. package/dist/cli/list-models.code.js +3 -3
  77. package/dist/cli/list-models.impl.js +3 -3
  78. package/dist/cli/list-models.js +3 -3
  79. package/dist/cli/session-picker.code.js +2 -2
  80. package/dist/cli/session-picker.impl.js +3 -3
  81. package/dist/cli/session-picker.js +3 -3
  82. package/dist/cli/startup-ui.code.js +2 -2
  83. package/dist/cli/startup-ui.impl.js +3 -3
  84. package/dist/cli/startup-ui.js +3 -3
  85. package/dist/cli/storage-command.impl.js +3 -3
  86. package/dist/cli/storage-command.js +3 -3
  87. package/dist/cli/storage-search-session.code.js +2 -2
  88. package/dist/cli/storage-search-session.impl.js +3 -3
  89. package/dist/cli/storage-search-session.js +3 -3
  90. package/dist/cli/team-command.code.js +2 -2
  91. package/dist/cli/team-command.impl.js +3 -3
  92. package/dist/cli/team-command.js +3 -3
  93. package/dist/cli.js +2 -2
  94. package/dist/core/agent-session-methods.d.ts +4 -1
  95. package/dist/core/agent-session-methods.js.map +1 -1
  96. package/dist/core/agent-session.d.ts +3 -0
  97. package/dist/core/compaction/compactor.d.ts +20 -14
  98. package/dist/core/compaction/errors.d.ts +120 -0
  99. package/dist/core/compaction/index.d.ts +1 -0
  100. package/dist/core/compaction/model-resolver.d.ts +2 -2
  101. package/dist/core/debug.impl.js +3 -3
  102. package/dist/core/debug.js +3 -3
  103. package/dist/core/export-html/card-projection.impl.js +3 -3
  104. package/dist/core/export-html/card-projection.js +3 -3
  105. package/dist/core/export-html/index.code.js +2 -2
  106. package/dist/core/export-html/index.impl.js +3 -3
  107. package/dist/core/export-html/index.js +3 -3
  108. package/dist/core/export-html/json-spans.impl.js +3 -3
  109. package/dist/core/export-html/json-spans.js +3 -3
  110. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  111. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  112. package/dist/core/export-html/tool-renderer.code.js +1 -1
  113. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  114. package/dist/core/export-html/tool-renderer.js +3 -3
  115. package/dist/core/extensions/api-types.d.ts +1 -1
  116. package/dist/core/extensions/api-types.js.map +1 -1
  117. package/dist/core/extensions/index.d.ts +1 -1
  118. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  119. package/dist/core/extensions/jiti-loader.js +3 -3
  120. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  121. package/dist/core/extensions/jiti-static-loader.js +3 -3
  122. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  123. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  124. package/dist/core/extensions/loader-host-modules.js +3 -3
  125. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  126. package/dist/core/extensions/provider-types.d.ts +18 -6
  127. package/dist/core/extensions/provider-types.js.map +1 -1
  128. package/dist/core/extensions/runner-context.js +1 -1
  129. package/dist/core/intercom-broker-control-host.code.js +1 -1
  130. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  131. package/dist/core/intercom-broker-control-host.js +3 -3
  132. package/dist/core/intercom-broker-control.code.js +3 -3
  133. package/dist/core/intercom-broker-control.impl.js +3 -3
  134. package/dist/core/intercom-broker-control.js +3 -3
  135. package/dist/core/model-config.d.ts +40 -0
  136. package/dist/core/model-registry.js +1 -1
  137. package/dist/core/model-resolver-scope.d.ts +4 -4
  138. package/dist/core/model-runtime.d.ts +1 -1
  139. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  140. package/dist/core/package-manager-storage-adapters.js +3 -3
  141. package/dist/core/provider-composer-internal.d.ts +11 -2
  142. package/dist/core/sdk.code.js +3 -3
  143. package/dist/core/sdk.impl.js +3 -3
  144. package/dist/core/sdk.js +3 -3
  145. package/dist/core/session-manager-core.js +5 -5
  146. package/dist/core/session-manager-list.impl.js +3 -3
  147. package/dist/core/session-manager-list.js +3 -3
  148. package/dist/core/session-manager.code.js +1 -1
  149. package/dist/core/session-manager.impl.js +3 -3
  150. package/dist/core/session-manager.js +3 -3
  151. package/dist/core/session-storage.impl.js +3 -3
  152. package/dist/core/session-storage.js +3 -3
  153. package/dist/core/settings-manager-basic-accessors.d.ts +6 -2
  154. package/dist/core/storage/index.js +2 -2
  155. package/dist/core/storage/node-sqlite-thread.js +2 -2
  156. package/dist/core/storage/node-sqlite.js +2 -2
  157. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  158. package/dist/core/storage/offline-snapshot-file.js +3 -3
  159. package/dist/core/storage/provider.js +2 -2
  160. package/dist/core/storage/selection.js +2 -2
  161. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  162. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  163. package/dist/core/storage/session/branch-fork-source.js +3 -3
  164. package/dist/core/storage/session/card-view.impl.js +3 -3
  165. package/dist/core/storage/session/card-view.js +3 -3
  166. package/dist/core/storage/session/child-reader.code.js +3 -3
  167. package/dist/core/storage/session/child-reader.impl.js +3 -3
  168. package/dist/core/storage/session/child-reader.js +3 -3
  169. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  170. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  171. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  172. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  173. package/dist/core/storage/session/expanded-child-details.js +3 -3
  174. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  175. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  176. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  177. package/dist/core/storage/session/fork-row-index.js +3 -3
  178. package/dist/core/storage/session/fork-staging.code.js +2 -2
  179. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  180. package/dist/core/storage/session/fork-staging.js +3 -3
  181. package/dist/core/storage/session/fork-window.code.js +3 -3
  182. package/dist/core/storage/session/fork-window.impl.js +3 -3
  183. package/dist/core/storage/session/fork-window.js +3 -3
  184. package/dist/core/storage/session/history-pages.impl.js +3 -3
  185. package/dist/core/storage/session/history-pages.js +3 -3
  186. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  187. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  188. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  189. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  190. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  191. package/dist/core/storage/session/memory-session-store.js +3 -3
  192. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  193. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  194. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  195. package/dist/core/storage/session/released-history-files.code.js +3 -3
  196. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  197. package/dist/core/storage/session/released-history-files.js +3 -3
  198. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  199. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  200. package/dist/core/storage/session/session-resume.impl.js +3 -3
  201. package/dist/core/storage/session/session-resume.js +3 -3
  202. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  203. package/dist/core/storage/session/snapshot-cut.js +3 -3
  204. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  205. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  206. package/dist/core/storage/session/snapshot-history.js +3 -3
  207. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  208. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  209. package/dist/core/storage/session/sql-session-store.js +3 -3
  210. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  211. package/dist/core/storage/session/tree-outline.js +3 -3
  212. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  213. package/dist/core/storage/session/tree-presentation.js +3 -3
  214. package/dist/core/storage/storage-status.impl.js +3 -3
  215. package/dist/core/storage/storage-status.js +3 -3
  216. package/dist/core/storage/team.impl.js +3 -3
  217. package/dist/core/storage/team.js +3 -3
  218. package/dist/core/structured-output/index.code.js +1 -1
  219. package/dist/core/structured-output/index.impl.js +3 -3
  220. package/dist/core/structured-output/index.js +3 -3
  221. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  222. package/dist/core/tasks/task-completion-entry.js +3 -3
  223. package/dist/core/tasks/task-file-history.code.js +3 -3
  224. package/dist/core/tasks/task-file-history.impl.js +3 -3
  225. package/dist/core/tasks/task-file-history.js +3 -3
  226. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  227. package/dist/core/tasks/task-reference-archive.js +3 -3
  228. package/dist/core/tasks/task-reference-identity.code.js +1 -1
  229. package/dist/core/tasks/task-reference-identity.js +3 -3
  230. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  231. package/dist/core/tasks/task-reference-stream.js +3 -3
  232. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  233. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  234. package/dist/core/tasks/task-view-source.impl.js +3 -3
  235. package/dist/core/tasks/task-view-source.js +3 -3
  236. package/dist/core/tools/read-url.code.js +2 -2
  237. package/dist/core/tools/read-url.impl.js +3 -3
  238. package/dist/core/tools/read-url.js +3 -3
  239. package/dist/core/worktree-snapshot/blob-store.js +2 -2
  240. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  241. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  242. package/dist/core/worktree-snapshot/errors.js +3 -3
  243. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  244. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  245. package/dist/extensions/codemode/execute.code.js +1 -1
  246. package/dist/extensions/codemode/execute.impl.js +3 -3
  247. package/dist/extensions/codemode/execute.js +3 -3
  248. package/dist/extensions/codemode/renderer.code.js +2 -2
  249. package/dist/extensions/codemode/renderer.impl.js +3 -3
  250. package/dist/extensions/codemode/renderer.js +3 -3
  251. package/dist/extensions/mcp/cli.code.js +2 -2
  252. package/dist/extensions/mcp/cli.impl.js +3 -3
  253. package/dist/extensions/mcp/cli.js +3 -3
  254. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  255. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  256. package/dist/extensions/mcp/cli.lazy.js +3 -3
  257. package/dist/extensions/mcp/runtime.code.js +1 -1
  258. package/dist/extensions/mcp/runtime.impl.js +3 -3
  259. package/dist/extensions/mcp/runtime.js +3 -3
  260. package/dist/index-extensions.d.ts +1 -1
  261. package/dist/index.d.ts +8 -1
  262. package/dist/index.js +7 -7
  263. package/dist/main-first-time-setup.code.js +2 -2
  264. package/dist/main-first-time-setup.impl.js +3 -3
  265. package/dist/main-first-time-setup.js +3 -3
  266. package/dist/modes/interactive/components/settings-selector-types.d.ts +1 -0
  267. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  268. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  269. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  270. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  271. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  272. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  273. package/dist/modes/interactive/theme/color-utils.d.ts +5 -5
  274. package/dist/modes/interactive/theme/theme-loading.d.ts +1 -0
  275. package/dist/modes/interactive-engine/engine-prewarm.js +1 -1
  276. package/dist/modes/interactive-engine/remote-model-catalog.d.ts +1 -0
  277. package/dist/modes/print-mode.js +1 -1
  278. package/dist/modes/rpc/rpc-client-api.d.ts +6 -0
  279. package/dist/modes/rpc/rpc-types.d.ts +29 -2
  280. package/dist/package-manager-cli.code.js +5 -5
  281. package/dist/package-manager-cli.impl.js +3 -3
  282. package/dist/package-manager-cli.js +3 -3
  283. package/dist/rpc-entry.js +1 -1
  284. package/dist/startup-files.json +1 -1
  285. package/dist/startup-stages/5.js +1 -1
  286. package/dist/startup-stages/7.js +1 -1
  287. package/dist/startup-stages/8.js +1 -2
  288. package/dist/startup-stages/9.js +2 -1
  289. package/dist/utils/native-module.d.ts +44 -0
  290. package/dist/utils/startup-database-spare.code.js +3 -3
  291. package/dist/utils/startup-database-spare.impl.js +3 -3
  292. package/dist/utils/startup-database-spare.js +3 -3
  293. package/dist/utils/tools-manager.code.js +1 -1
  294. package/dist/utils/tools-manager.impl.js +3 -3
  295. package/dist/utils/tools-manager.js +3 -3
  296. package/docs/background-tasks.md +238 -243
  297. package/docs/build.md +21 -15
  298. package/docs/changelog.mdx +1 -1
  299. package/docs/codemode.md +68 -51
  300. package/docs/compaction/reference.md +65 -26
  301. package/docs/compaction.md +118 -66
  302. package/docs/computer-use.md +179 -146
  303. package/docs/containerization.md +87 -33
  304. package/docs/custom-provider/api-reference.md +152 -13
  305. package/docs/custom-provider/oauth.md +45 -28
  306. package/docs/custom-provider/override.md +14 -7
  307. package/docs/custom-provider/registration.md +77 -67
  308. package/docs/custom-provider/streaming.md +42 -19
  309. package/docs/custom-provider.md +26 -62
  310. package/docs/development.md +81 -42
  311. package/docs/docs.json +54 -38
  312. package/docs/environment-variables.md +92 -64
  313. package/docs/extensions/api-reference.md +326 -735
  314. package/docs/extensions/authoring.md +186 -269
  315. package/docs/extensions/events.md +308 -375
  316. package/docs/extensions/examples.md +122 -74
  317. package/docs/extensions/ui.md +217 -197
  318. package/docs/extensions.md +189 -259
  319. package/docs/getting-started/authentication.md +27 -14
  320. package/docs/getting-started/first-session.md +25 -26
  321. package/docs/getting-started/installation.md +62 -84
  322. package/docs/getting-started/project-instructions.md +39 -14
  323. package/docs/guides/configuration.md +62 -20
  324. package/docs/guides/intercom.md +20 -12
  325. package/docs/guides/non-interactive.md +31 -16
  326. package/docs/guides/orchestration.md +17 -9
  327. package/docs/guides/resume-on-any-machine.md +63 -52
  328. package/docs/guides/subagents.md +26 -14
  329. package/docs/guides/team-setup.md +49 -27
  330. package/docs/guides.md +30 -23
  331. package/docs/herdr.md +22 -17
  332. package/docs/index.md +24 -17
  333. package/docs/intercom/operations.md +90 -66
  334. package/docs/intercom/reference.md +219 -192
  335. package/docs/intercom.md +111 -92
  336. package/docs/json.md +73 -71
  337. package/docs/keybindings.md +74 -48
  338. package/docs/libraries/agent-core.md +52 -9
  339. package/docs/libraries/ai.md +90 -63
  340. package/docs/libraries/codemode.md +31 -8
  341. package/docs/libraries/schema.md +12 -9
  342. package/docs/libraries/storage-libsql.md +92 -0
  343. package/docs/libraries/storage-postgres.md +119 -0
  344. package/docs/libraries/telemetry.md +42 -9
  345. package/docs/libraries/tui.md +74 -94
  346. package/docs/libraries.md +25 -8
  347. package/docs/llama-cpp.md +38 -33
  348. package/docs/mcp-servers.md +140 -88
  349. package/docs/models/reference.md +53 -36
  350. package/docs/models-configuration.md +19 -13
  351. package/docs/models.md +102 -87
  352. package/docs/orchestration/migrating-workflows.md +22 -20
  353. package/docs/orchestration/patterns.md +36 -21
  354. package/docs/orchestration.md +24 -21
  355. package/docs/packages/authoring.md +29 -18
  356. package/docs/packages/reference.md +77 -16
  357. package/docs/packages.md +34 -34
  358. package/docs/programmatic.md +28 -21
  359. package/docs/prompt-templates.md +65 -41
  360. package/docs/providers/reference.md +36 -20
  361. package/docs/providers.md +78 -76
  362. package/docs/quickstart.md +42 -54
  363. package/docs/reference/cli.md +256 -254
  364. package/docs/reference.md +30 -23
  365. package/docs/rpc/examples.md +121 -17
  366. package/docs/rpc/extension-ui.md +86 -63
  367. package/docs/rpc/protocol.md +817 -358
  368. package/docs/rpc.md +78 -152
  369. package/docs/sdk/reference.md +309 -73
  370. package/docs/sdk/storage.md +614 -0
  371. package/docs/sdk/structured-decisions.md +168 -65
  372. package/docs/sdk/web-server.md +80 -46
  373. package/docs/sdk.md +168 -215
  374. package/docs/security.md +117 -44
  375. package/docs/session-format.md +127 -76
  376. package/docs/sessions.md +155 -113
  377. package/docs/settings.md +293 -205
  378. package/docs/shell-aliases.md +15 -6
  379. package/docs/skills/authoring.md +17 -9
  380. package/docs/skills/reference.md +23 -21
  381. package/docs/skills.md +148 -97
  382. package/docs/storage.md +172 -260
  383. package/docs/subagents/authoring.md +148 -15
  384. package/docs/subagents/reference.md +105 -29
  385. package/docs/subagents.md +247 -250
  386. package/docs/terminal-setup.md +97 -69
  387. package/docs/termux.md +51 -85
  388. package/docs/themes/reference.md +51 -37
  389. package/docs/themes.md +52 -55
  390. package/docs/tmux.md +38 -21
  391. package/docs/tools.md +209 -147
  392. package/docs/tui/reference.md +64 -32
  393. package/docs/tui.md +38 -66
  394. package/docs/usage.md +94 -86
  395. package/docs/verification.md +25 -25
  396. package/docs/web-access.md +106 -54
  397. package/docs/windows.md +55 -57
  398. package/docs/worktree-snapshots.md +82 -74
  399. package/examples/sdk/11-sessions.ts +4 -4
  400. package/package.json +8 -8
  401. package/schemas/models.schema.json +58 -7
  402. package/dist/_shared/sdk-OSBEPR3Q.js.map +0 -1
  403. package/dist/_shared/startup-0-0-TYUFUOJZ.js.map +0 -1
  404. package/dist/_shared/startup-0-1-W2G2UY7R.js.map +0 -1
  405. package/dist/_shared/startup-0-2-UXBUEOXW.js.map +0 -1
  406. package/dist/_shared/startup-0-4-HN5EB4K7.js.map +0 -1
@@ -1,34 +1,42 @@
1
1
  ---
2
- title: Extension API reference
2
+ title: "Extension API reference"
3
3
  sidebarTitle: "Extension API"
4
- description: ExtensionContext, ExtensionCommandContext, ExtensionAPI methods, and error handling.
4
+ description: "Reference for ExtensionContext, ExtensionToolContext, ExtensionCommandContext, ExtensionAPI methods, and typed errors."
5
5
  ---
6
6
 
7
- # Extension API reference
7
+ This page documents `ExtensionContext`, `ExtensionToolContext`, `ExtensionCommandContext`, `ExtensionAPI` methods, and typed errors. For setup and discovery, see [Extensions overview](/extensions). For patterns and custom tools, see [Write an extension](/extensions/authoring). For embedding Atomic and loading inline extension factories, see [SDK overview](/sdk), [SDK extensions](/sdk/reference#extensions), and [Structured decisions](/sdk/structured-decisions).
8
8
 
9
9
  ## ExtensionContext
10
10
 
11
- All handlers receive `ctx: ExtensionContext`.
11
+ All event handlers, tool callbacks, and command handlers receive `ctx: ExtensionContext`.
12
12
 
13
13
  ### ctx.ui
14
14
 
15
- UI methods for user interaction. See [Custom UI](/extensions/ui#custom-ui) for full details.
15
+ UI methods for user interaction. See [Extension UI](/extensions/ui#custom-ui) for full details.
16
+
17
+ ### ctx.mode
18
+
19
+ Current run mode: `"tui" | "rpc" | "json" | "print"`. Use `ctx.mode === "tui"` to guard terminal-only UI such as custom components or host-native pickers.
16
20
 
17
21
  ### ctx.hasUI
18
22
 
19
- `false` in print mode (`-p`) and JSON mode. `true` in interactive and RPC mode. In RPC mode, dialog methods (`select`, `confirm`, `input`, `editor`) work via the extension UI sub-protocol, and fire-and-forget methods (`notify`, `setStatus`, `setWidget`, `setTitle`, `setEditorText`) emit requests to the client. Some TUI-specific methods are no-ops or return defaults (see [RPC mode](/rpc/extension-ui#extension-ui-protocol)).
23
+ `false` in print mode (`-p`) and JSON mode; `true` in interactive and RPC modes. In RPC mode, dialog methods (`select`, `confirm`, `input`, `editor`) run through the extension UI sub-protocol and fire-and-forget methods (`notify`, `setStatus`, `setWidget`, `setTitle`, `setEditorText`) send requests to the client. Some TUI-specific methods are no-ops or return defaults (see [RPC extension UI](/rpc/extension-ui#extension-ui-protocol)).
24
+
25
+ ### ctx.hasHumanInput
26
+
27
+ `boolean` indicating whether a human-input adapter is available independently of terminal rendering.
20
28
 
21
29
  ### ctx.isPresentationOnly
22
30
 
23
- `true` in the local presentation host when the isolated interactive engine owns execution. Keep UI registration active, but skip background execution and durable recovery in lifecycle hooks in this context to avoid starting the same work in both processes. Normal SDK, print, RPC, and engine contexts leave this flag false or unset.
31
+ `true` when Atomic loads an extension in the terminal UI process while running session execution in a separate worker process. Keep UI registration active, but skip background work and recovery hooks so both processes do not start the same work. Normal SDK, print, RPC, and worker contexts leave this flag `false` or `undefined`.
24
32
 
25
33
  ### ctx.cwd
26
34
 
27
35
  Current working directory.
28
36
 
29
- Built-in cwd-sensitive tools (`read`, `write`, `edit`, `search`, `find`, `ls`, `bash`, `powershell`) resolve relative paths against `ctx.cwd` when an extension invokes them, falling back to the cwd captured when the tool was created. An extension that registers a tool and forwards its own context therefore gets paths resolved against the live session cwd rather than a stale one.
37
+ Built-in cwd-sensitive tools (`read`, `write`, `edit`, `search`, `find`, `ls`, `bash`, `powershell`) resolve relative paths against `ctx.cwd` when an extension invokes them, falling back to the directory captured when the tool was created.
30
38
 
31
- Use `CONFIG_DIR_NAME` instead of hardcoding `.atomic` (or legacy `.pi`) when constructing project-local config paths. Rebranded distributions can use a different config directory name.
39
+ Use `CONFIG_DIR_NAME` instead of hardcoding `.atomic` (or legacy `.pi`) when building project config paths:
32
40
 
33
41
  ```typescript
34
42
  import { CONFIG_DIR_NAME, type ExtensionAPI } from "@bastani/atomic";
@@ -44,9 +52,7 @@ export default function (atomic: ExtensionAPI) {
44
52
 
45
53
  ### ctx.isProjectTrusted()
46
54
 
47
- Returns whether project-local trust is active for the current session context. This includes temporary trust decisions and CLI trust overrides, not only saved decisions in the global trust store.
48
-
49
- Use this before reading project-local extension configuration, loading project-local resources, or exposing actions that should only run after the user trusts the working directory.
55
+ Returns whether project-local trust is active for the current session, including temporary trust decisions and CLI overrides as well as saved decisions in `trust.json`. Check this before reading project-local config files or running project-scoped automation.
50
56
 
51
57
  ```typescript
52
58
  atomic.registerCommand("project-status", {
@@ -61,108 +67,83 @@ atomic.registerCommand("project-status", {
61
67
 
62
68
  Read-only access to session state. See [Session format](/session-format) for the full `SessionManager` API and entry types.
63
69
 
64
- For `tool_call`, this state is synchronized through the current assistant message before handlers run. In parallel tool execution mode it is not guaranteed to include sibling tool results from the same assistant message.
70
+ For `tool_call`, `ctx.sessionManager` is synchronized through the current assistant tool-calling message; in parallel tool mode it may not include sibling tool results from the same assistant message.
65
71
 
66
72
  ```typescript
67
- ctx.sessionManager.getEntries() // Entries held for the current window
68
- ctx.sessionManager.getBranch() // Current branch
69
- ctx.sessionManager.getLeafId() // Current leaf entry ID
73
+ ctx.sessionManager.getEntries() // Entries held in the active window
74
+ ctx.sessionManager.getBranch() // Current branch
75
+ ctx.sessionManager.getLeafId() // Current leaf entry ID
70
76
  ```
71
77
 
72
- Starting an extension does not load older conversation entries. Entries your extension saved with `atomic.appendEntry()` on the current branch stay in `getBranch()` and `getEntries()`, so restoring state in `session_start` works without extra loads.
78
+ Custom entries saved with `atomic.appendEntry()` on the current branch remain in `getBranch()` and `getEntries()`, so restoring state in `session_start` does not require extra loads.
73
79
 
74
- To inspect older history without keeping the whole session in memory:
80
+ To inspect older history without loading the entire session into memory:
75
81
 
76
- - Call `await ctx.sessionManager.readEntry(id)` to look up a single entry.
77
- - Iterate `for await (const page of ctx.sessionManager.readHistory({ fromSeq, toSeq }))` to visit entries in append order. Each item in `page.items` is either `{ seq, entry }` or an oversized reference (`kind: "oversized"`, `seq`, `bytes`) that you stream with `ctx.sessionManager.readHistoryChunks(item)`.
78
- - Break out of either loop once you have what you need; the manager does not retain read pages.
79
- - `await ctx.sessionManager.loadFullHistory()` loads every stored entry into memory; prefer paged reads when possible.
82
+ - `await ctx.sessionManager.readEntry(id)` fetches a single entry.
83
+ - `for await (const page of ctx.sessionManager.readHistory({ fromSeq, toSeq }))` iterates entries in append order. Oversized items (`kind: "oversized"`) stream via `ctx.sessionManager.readHistoryChunks(item)`.
84
+ - `await ctx.sessionManager.loadFullHistory()` loads every stored entry into memory; prefer paged reads for large sessions.
80
85
 
81
- ### ctx.modelRegistry / ctx.model / ctx.scopedModels
86
+ ### ctx.modelRegistry / ctx.model / ctx.scopedModels {#ctx-modelregistry-ctx-model-ctx-scopedmodels}
82
87
 
83
88
  Access models, authentication state, and provider-aware requests.
84
89
 
85
- Use `ctx.modelRegistry.complete()` for an extension model request that uses Atomic's provider composition. It dispatches through the active `ModelRuntime`, keeping registered custom providers and resolved request authentication: the credential-specific `baseUrl`, headers (including `null` suppression markers), and environment values.
90
+ Use `ctx.modelRegistry.complete()` for non-streaming model calls and `ctx.modelRegistry.streamSimple()` or `ctx.modelRegistry.stream()` for streaming calls. All three run through Atomic's active provider configuration and request-time authentication, including extension-registered providers (global standalone helpers do not see extension providers):
86
91
 
87
- Use `ctx.modelRegistry.generateImages(model, context, options)` to run an image model with request-time authentication. It resolves to the generated image blocks and usage, and reports provider errors through `stopReason`, `errorMessage`, and `error` instead of rejecting.
92
+ ```typescript
93
+ const model = ctx.modelRegistry.find("github-copilot", "gpt-5.5");
94
+ if (!model) throw new Error("Model not found");
95
+
96
+ const response = await ctx.modelRegistry.complete(model, { messages }, { signal: ctx.signal });
97
+ ```
88
98
 
89
- For `openai-images` models, `options` accepts `size`, `quality`, `n`, `background`, `outputFormat` (`png`, `jpeg`, `webp`, `gif`, `svg`), `outputCompression`, `frameCount`, `frameDurationMs`, `complexity`, `svg`, `moderation`, and `safetyIdentifier`. An image block with `role: "markup"` or `role: "mask"` maps to the `markup` or `mask` field, and the first other image is the base image of an edit. GIF, SVG, `complexity`, and the frame options require a GPT Image 2.6 model that declares them in `model.capabilities`.
99
+ Use `ctx.modelRegistry.generateImages(model, context, options)` to call an image model with request-time authentication. It returns generated blocks and usage and reports provider failures via `stopReason`, `errorMessage`, and `error` instead of rejecting.
90
100
 
91
- `outputFormat: "svg"` works without passing `svg`. When the API requires `svg.model` and your request omitted `svg`, Atomic retries once with `gpt-6.1-sol` (exported as `DEFAULT_SVG_AUTHOR_MODEL` from `@bastani/atomic-ai`), and `result.svgModel` reports the model that wrote the SVG.
101
+ For `openai-images` models, `options` accepts `size`, `quality`, `n`, `background`, `outputFormat` (`png`, `jpeg`, `webp`, `gif`, `svg`), `outputCompression`, `frameCount`, `frameDurationMs`, `complexity`, `svg`, `moderation`, and `safetyIdentifier`. Image inputs with `role: "markup"` or `role: "mask"` map to those edit roles, and the first remaining image is the base image. GIF, SVG, `complexity`, and frame options require a GPT Image 2.6 model declaring those capabilities.
92
102
 
93
- Pass `svg: { model, reasoning }` to choose a specific authoring model; an explicit `svg` object is sent as given and never replaced. If the API rejects the retry's `svg` parameter as unsupported, Atomic retries once more without it (at most three requests total). Because SVG authoring can take up to two minutes on complex prompts, leave `timeoutMs` unset (the 10-minute default) or set it to at least `180000`.
103
+ `outputFormat: "svg"` works without passing `svg`: when an account requires `svg.model`, Atomic retries once with `gpt-6.1-sol` (`DEFAULT_SVG_AUTHOR_MODEL` from `@bastani/atomic-ai`) and reports it in `result.svgModel`, retrying once more without `svg` if rejected as unsupported. An explicit `svg: { model, reasoning }` object is sent verbatim. Leave `timeoutMs` unset (10-minute default) or set at least `180000` for SVG requests.
94
104
 
95
105
  ```typescript
96
106
  const flare = ctx.modelRegistry.getModelOfType("image", "openai-images", "gpt-image-2.6-flare");
97
107
  if (!flare) throw new Error("gpt-image-2.6-flare is unavailable");
98
- const input = [{ type: "text" as const, text: "A flat red paper lantern icon" }];
99
108
 
100
- const logo = await ctx.modelRegistry.generateImages(flare, { input }, { outputFormat: "svg", signal: ctx.signal });
101
- if (logo.stopReason !== "stop") throw new Error(logo.errorMessage);
102
- const svgBlock = logo.output.find((block) => block.type === "image");
103
- const svg = svgBlock?.type === "image" ? Buffer.from(svgBlock.data, "base64").toString("utf8") : undefined;
104
- console.log(logo.svgModel, svg?.slice(0, 60)); // gpt-6.1-sol <svg ...
105
-
106
- const motion = await ctx.modelRegistry.generateImages(
109
+ const logo = await ctx.modelRegistry.generateImages(
107
110
  flare,
108
- { input: [{ type: "text", text: "A paper lantern swinging gently, flat vector style" }] },
109
- { outputFormat: "gif", frameCount: 4, frameDurationMs: 200, size: "512x512", signal: ctx.signal },
110
- );
111
- if (motion.stopReason !== "stop") throw new Error(motion.errorMessage);
112
- ```
113
-
114
- When image generation fails, `result.error` holds a JSON-safe `ImageGenerationErrorData`. Rebuild the typed error with `imageGenerationErrorFromData()` from `@bastani/atomic-ai` and branch on its class, type guard (`isImageGenerationError`, `isImageGenerationConfigError`, and related guards), or `code`, not on `message`. Use `findImageGenerationError(error, guard)` to inspect a `cause` chain and `isRetryableImageGenerationError()` to check retryability. A cancelled request resolves with `stopReason: "aborted"` and no `error`. See [Image generation](/libraries/ai#image-generation) for the full `ImageGenerationError` class table, `ImageGenerationConfigError` reasons, and `OPENAI_IMAGES_LIMITS` bounds.
115
-
116
- For streaming requests, use `ctx.modelRegistry.streamSimple(model, context, options)` with provider-neutral options, or `stream()` with API-specific options. Both use configured providers and request-time authentication, including extension registrations. Iterate the returned `AssistantMessageEventStream` for events and await `.result()` for the final message. Setup failures produce error events and error results. The global compatibility streaming functions do not see extension provider registrations.
117
-
118
- ```typescript
119
- const model = ctx.modelRegistry.find("github-copilot", "gpt-5.5");
120
- if (!model) throw new Error("Model not found");
121
-
122
- const response = await ctx.modelRegistry.complete(
123
- model,
124
- { messages },
125
- { signal: ctx.signal },
111
+ { input: [{ type: "text", text: "A flat red paper lantern icon" }] },
112
+ { outputFormat: "svg", signal: ctx.signal },
126
113
  );
114
+ if (logo.stopReason !== "stop") throw new Error(logo.errorMessage);
127
115
  ```
128
116
 
129
- Use `getApiKeyAndHeaders()` only when an extension must inspect authentication before dispatch; normal requests resolve and apply authentication automatically.
130
-
131
- OpenRouter Chat Completions and Anthropic Messages requests send `x-session-id` by default when `sessionId` is supplied and prompt caching is enabled. Set the model's `compat.sendSessionAffinityHeaders` to `false` to opt out, or set `cacheRetention: "none"` on the request to disable cache-related affinity. Explicit request headers override generated headers.
132
-
133
- `await ctx.modelRegistry.refresh(options)` returns `{ aborted, errors }`, where `errors` is a per-provider map so extensions can report partial refresh failures. Calling `ModelRuntime.setRuntimeApiKey(providerId, apiKey, options)` records the runtime credential without refreshing the catalog; call `refresh({ providers: [providerId], signal })` explicitly when you need an updated catalog.
117
+ When image generation fails, rebuild `result.error` (`ImageGenerationErrorData`) with `imageGenerationErrorFromData()` from `@bastani/atomic-ai` and branch on its class, type guards (`isImageGenerationError`, `isImageGenerationConfigError`, `findImageGenerationError`, `isRetryableImageGenerationError`), or `code`. Cancelled requests resolve with `stopReason: "aborted"` and no `error`. See [Image generation](/libraries/ai#image-generation).
134
118
 
135
- `ctx.scopedModels` is the read-only list of models scoped to the current session, matching `/scoped-models`. It resolves from `--models` and `enabledModels` against the available catalog and is empty when no scoping is configured (meaning every available model is usable). Each entry is `{ model, thinkingLevel? }`, where `thinkingLevel` is set only when a pattern pinned it (for example `anthropic/*:high`). Use it to build a model picker that matches Atomic's built-in scope.
119
+ Use `getApiKeyAndHeaders()` only when inspecting credentials before dispatch. `await ctx.modelRegistry.refresh(options)` returns `{ aborted, errors }` with per-provider errors. Calling `ModelRuntime.setRuntimeApiKey(providerId, apiKey, options)` stores a runtime credential without refreshing the catalog; call `refresh({ providers: [providerId], signal })` explicitly if needed (see [API keys and OAuth in the SDK](/sdk/reference#api-keys-and-oauth)).
136
120
 
137
- The value resolves at access time, so it tracks session replacement and reflects the engine's catalog in isolated interactive mode. `ctx.scopedModels` is a getter with no setter (`readonly ScopedModel[]`), and each read returns fresh, frozen copies of the array, every entry, and each model so mutations throw. Change scope through the commands and settings that own it.
138
-
139
- ```typescript
140
- for (const { model, thinkingLevel } of ctx.scopedModels) {
141
- console.log(`${model.provider}/${model.id}${thinkingLevel ? `:${thinkingLevel}` : ""}`);
142
- }
143
- ```
121
+ OpenRouter Chat Completions and Anthropic Messages requests send `x-session-id` by default when `sessionId` is supplied and prompt caching is active; set `compat.sendSessionAffinityHeaders: false` or `cacheRetention: "none"` to opt out.
144
122
 
145
- Both `ScopedModel` and `ExtensionScopedModels` are exported from `@bastani/atomic`:
123
+ `ctx.scopedModels` is the read-only list of models scoped to the current session (matching `/scoped-models`, resolved from `--models` and `enabledModels`; empty when unscoped). Each entry is `{ model, thinkingLevel? }`, resolved at access time so it stays current in default interactive mode as well as embedded sessions. Every read returns fresh frozen copies (`ScopedModel` and `ExtensionScopedModels` are exported from `@bastani/atomic`):
146
124
 
147
125
  ```typescript
148
126
  import type { ExtensionScopedModels, ScopedModel } from "@bastani/atomic";
149
127
 
150
- function firstScoped(scope: ExtensionScopedModels): ScopedModel | undefined {
151
- return scope[0];
128
+ function formatScope(scope: ExtensionScopedModels): string[] {
129
+ return scope.map(
130
+ ({ model, thinkingLevel }: ScopedModel) =>
131
+ `${model.provider}/${model.id}${thinkingLevel ? `:${thinkingLevel}` : ""}`,
132
+ );
152
133
  }
153
134
  ```
154
135
 
155
- ### ctx.signal
136
+ ### ctx.thinkingLevel
137
+
138
+ Current `ThinkingLevel` (`"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"`) or `undefined`, resolved from the active session at access time.
156
139
 
157
- The current agent abort signal, or `undefined` when no agent turn is active.
140
+ ### ctx.getDecisionModel()
158
141
 
159
- Use this for abort-aware nested work started by extension handlers, for example:
160
- - `fetch(..., { signal: ctx.signal })`
161
- - model calls that accept `signal`
162
- - file or process helpers that accept `AbortSignal`
142
+ Returns the session's configured `decisionModel` (`"provider/model"`, `"auto"`, or `""`). Atomic uses this for `structured_output` calls that omit `model`, steer readiness checks, and `decide()`, without changing the chat model (see [Structured decisions](/sdk/structured-decisions)). Throws `DecisionModelUnavailableError` (`reason: "host-unsupported"`) if the host does not support decision models.
163
143
 
164
- `ctx.signal` is typically defined during active turn events such as `tool_call`, `tool_result`, `message_update`, and `turn_end`.
165
- It is usually `undefined` in idle or non-turn contexts such as session events, extension commands, and shortcuts fired while Atomic is idle.
144
+ ### ctx.signal
145
+
146
+ The active turn's `AbortSignal`, or `undefined` when idle. Forward it to `fetch()`, model calls, or process helpers inside turn hooks (`tool_call`, `tool_result`, `message_update`, `turn_end`) so Escape cancels your async work too:
166
147
 
167
148
  ```typescript
168
149
  atomic.on("tool_result", async (event, ctx) => {
@@ -171,17 +152,15 @@ atomic.on("tool_result", async (event, ctx) => {
171
152
  body: JSON.stringify(event),
172
153
  signal: ctx.signal,
173
154
  });
174
-
175
- const data = await response.json();
176
- return { details: data };
155
+ return { details: await response.json() };
177
156
  });
178
157
  ```
179
158
 
180
159
  ### ctx.sessionSignal
181
160
 
182
- A read-only `AbortSignal` for the session lifetime, available even while the agent is idle. It aborts when reload or shutdown begins, **before** Atomic drains admitted commands and emits `session_shutdown`. Unlike `ctx.signal`, it does not end when an agent turn finishes. A replacement session generation receives a new signal.
161
+ A read-only `AbortSignal` for the session's lifetime, available even while idle. It aborts when reload or shutdown starts, **before** Atomic finishes active commands and emits `session_shutdown`. After a reload or session switch, the new session receives a fresh signal.
183
162
 
184
- Custom UI mounted through `ctx.ui.custom` is dismissed automatically when the session ends; an explicit caller signal can still dismiss it earlier. Use `ctx.sessionSignal` for other long-running command resources, such as browser windows, instead of waiting for `session_shutdown`, which cannot run until those commands settle. Cancellation should stop waiting for input, not abandon a session write already started: keep awaiting that write so teardown can drain it safely.
163
+ Custom UI mounted with `ctx.ui.custom()` closes automatically when the session ends. Use `ctx.sessionSignal` to cancel long-lived command watchers instead of waiting for `session_shutdown`, while still awaiting any in-progress session write so teardown drains cleanly:
185
164
 
186
165
  ```typescript
187
166
  import { Text } from "@bastani/atomic-tui";
@@ -198,44 +177,32 @@ atomic.registerCommand("monitor", {
198
177
 
199
178
  ### ctx.isIdle() / ctx.abort() / ctx.hasPendingMessages()
200
179
 
201
- Control flow helpers.
202
-
203
- `ctx.isIdle()` reports whether the agent is streaming a response. It stays `true` while the session compacts, because a `sendUserMessage()` sent then waits for compaction to end instead of starting a turn.
180
+ Control-flow helpers. `ctx.isIdle()` reports whether the agent is streaming a response (it remains `true` during compaction, when `sendUserMessage()` queues behind compaction instead of starting a turn).
204
181
 
205
182
  ### ctx.shutdown()
206
183
 
207
- Request a graceful shutdown of Atomic.
208
-
209
- - **Interactive mode:** Deferred until the agent becomes idle (after processing all queued steering and follow-up messages).
210
- - **RPC mode:** Runs when the session is idle and all command responses have been written. An idle request does not need another client command to trigger it. Requests during startup wait for input setup; requests during a turn wait for it to settle. If an extension starts compaction outside a turn, shutdown waits for the next command or turn after compaction finishes.
211
- - **Print mode:** No-op. The process exits automatically when all prompts are processed.
184
+ Request a graceful shutdown of Atomic (emits `session_shutdown` before exiting):
212
185
 
213
- Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands, shortcuts).
214
-
215
- ```typescript
216
- atomic.on("tool_call", (event, ctx) => {
217
- if (isFatal(event.input)) {
218
- ctx.shutdown();
219
- }
220
- });
221
- ```
186
+ - **Interactive mode:** Deferred until the agent becomes idle after processing queued messages.
187
+ - **RPC mode:** Runs once idle and after pending command responses are written.
188
+ - **Print mode:** No-op (the process exits automatically after finishing prompts).
222
189
 
223
190
  ### ctx.getContextUsage()
224
191
 
225
- Returns current context usage for the active model. Uses last assistant usage when available, then estimates tokens for trailing messages.
192
+ Returns current context usage `{ tokens, contextWindow, percent }` for the active model, or `undefined` when no model is active. Both `tokens` and `percent` are `number | null` (`null` immediately after compaction before the next assistant response arrives), so check for `null` before comparing:
226
193
 
227
194
  ```typescript
228
195
  const usage = ctx.getContextUsage();
229
- if (usage && usage.tokens > 100_000) {
230
- // ...
196
+ if (usage && usage.tokens !== null && usage.tokens > 100_000) {
197
+ ctx.ui.notify(`Context at ${usage.tokens} tokens`, "warning");
231
198
  }
232
199
  ```
233
200
 
234
201
  ### ctx.compact()
235
202
 
236
- Trigger compaction without awaiting completion. By default it clears the context window so the agent recovers what it needs from session history; with a compactor model configured, the compactor's output replaces the context.
203
+ Trigger compaction without awaiting completion. By default it clears the active context window so the agent recovers details from session history; when a compactor model is configured, the compactor's output replaces the context.
237
204
 
238
- Options include `query` (added to the boundary message and passed to the compactor), `compactionModel` (`"auto"` or an exact model ID for this run without changing settings), and `onComplete` or `onError` callbacks. `compression_ratio` and `preserve_recent` are ignored if passed.
205
+ Options: `query` (passed to the boundary message and compactor), `compactionModel` (`"auto"` or an exact model ID for this run only), `onComplete`, and `onError`.
239
206
 
240
207
  ```typescript
241
208
  ctx.compact({
@@ -249,71 +216,70 @@ ctx.compact({
249
216
  });
250
217
  ```
251
218
 
252
- Extensions that need their own replacement text can return `compactedText` from `session_before_compact`. See [Compaction](/compaction) for both forms.
219
+ See [Compaction](/compaction).
253
220
 
254
221
  ### ctx.getSystemPrompt()
255
222
 
256
- Returns Atomic's current system prompt string.
257
-
258
- - During `before_agent_start`, this reflects chained system-prompt changes made so far for the current turn.
259
- - It does not include later `context` message mutations.
260
- - It does not include `before_provider_request` payload rewrites.
261
- - If later-loaded extensions run after yours, they can still change what is ultimately sent.
262
-
263
- ```typescript
264
- atomic.on("before_agent_start", (event, ctx) => {
265
- const prompt = ctx.getSystemPrompt();
266
- console.log(`System prompt length: ${prompt.length}`);
267
- });
268
- ```
223
+ Returns Atomic's current system prompt string. Inside `before_agent_start`, it reflects changes made by earlier handlers; it does not include `context` or `before_provider_request` payload rewrites.
269
224
 
270
225
  ### ctx.getSkillCatalog()
271
226
 
272
- Returns the current loader-owned skill catalog when the host provides one. Use it to resolve exact skill selectors, including source-qualified names such as `tdd@builtin`, without falling back to the bare precedence winner.
227
+ Optional method returning the loader-owned `SkillCatalog`. Use `catalog.resolve(selector)` to look up exact skill selectors.
228
+
229
+ Note that source-qualified selectors such as `"tdd@builtin"` exist **only** when two or more distinct skill files collide on `"tdd"`. When only one file defines `"tdd"`, `catalog.resolve("tdd@builtin")` returns `{ ok: false, kind: "unknown" }` and you should resolve `"tdd"` instead:
273
230
 
274
231
  ```typescript
275
232
  atomic.on("session_start", (_event, ctx) => {
276
233
  const catalog = ctx.getSkillCatalog?.();
277
- const resolved = catalog?.resolve("tdd@builtin");
234
+ const resolved = catalog?.resolve("tdd");
278
235
  if (resolved?.ok) {
279
236
  ctx.ui.notify(`Using ${resolved.candidate.selector}`, "info");
280
237
  }
281
238
  });
282
239
  ```
283
240
 
284
- `atomic.getCommands()` already includes the same advertised `/skill:name` and `/skill:name@source` names. See [Skill Commands](/skills#skill-commands).
241
+ `atomic.getCommands()` returns the same advertised `/skill:name` and `/skill:name@source` names. See [Skill commands](/skills#skill-commands).
242
+
243
+ ### Additional optional context getters
244
+
245
+ These optional methods are present when supported by the host:
246
+
247
+ - **`ctx.getHttpIdleTimeoutMs?(): number`:** Returns the session's `httpIdleTimeoutMs` setting in milliseconds (`0` means idle timeout is disabled).
248
+ - **`ctx.getPackageAgents?(): readonly PackageAgentFile[]`:** Returns enabled subagent definition files contributed by installed packages (only from project packages when the project is trusted).
249
+ - **`ctx.getExtensionPaths?(): string[]`:** Returns the file paths of loaded extensions.
250
+ - **`ctx.isSessionSummaryEnabled?(): boolean`:** Returns whether background session summaries are enabled.
285
251
 
286
252
  ## ExtensionToolContext
287
253
 
288
- Tool `execute` callbacks receive an `ExtensionToolContext`, which extends `ExtensionContext` with `tools`, `executeTool(name, args, options?)`, and `parentToolCallId` for nested invocations. Event and command contexts do not provide these tool-only methods. See [structured results and nested tools](/extensions/authoring#structured-results-and-nested-tools) for permissions, cancellation, result hooks, and exclusive-call requirements.
254
+ Tool `execute` callbacks receive `ExtensionToolContext`, extending `ExtensionContext` with `tools`, `executeTool(name, args, options?)`, and `parentToolCallId` for nested tool invocations. See [Structured results and nested tools](/extensions/authoring#structured-results-and-nested-tools).
289
255
 
290
256
  ## ExtensionCommandContext
291
257
 
292
- Command handlers receive `ExtensionCommandContext`, which extends `ExtensionContext` with session control methods. These are only available in commands because they can deadlock if called from event handlers.
258
+ Command handlers receive `ExtensionCommandContext`, extending `ExtensionContext` with session-control methods that would deadlock if called from event handlers.
259
+
260
+ ### ctx.getSystemPromptOptions()
261
+
262
+ Returns the current base `BuildSystemPromptOptions` used to construct the session's system prompt.
293
263
 
294
264
  ### ctx.waitForIdle()
295
265
 
296
- Wait for the agent to finish streaming:
266
+ Wait for the agent to finish streaming before modifying session state:
297
267
 
298
268
  ```typescript
299
269
  atomic.registerCommand("my-cmd", {
300
- handler: async (args, ctx) => {
270
+ handler: async (_args, ctx) => {
301
271
  await ctx.waitForIdle();
302
- // Agent is now idle, safe to modify session
303
272
  },
304
273
  });
305
274
  ```
306
275
 
307
276
  ### ctx.newSession(options?)
308
277
 
309
- Create a new session:
278
+ Create a new session. Options: `parentSession`, `setup(sessionManager)` (runs before switching), and `withSession(ctx)` (runs post-switch work against a fresh `ReplacedSessionContext`):
310
279
 
311
280
  ```typescript
312
- const parentSession = ctx.sessionManager.getSessionId();
313
- const kickoff = "Continue in the replacement session";
314
-
315
281
  const result = await ctx.newSession({
316
- parentSession,
282
+ parentSession: ctx.sessionManager.getSessionId(),
317
283
  setup: async (sm) => {
318
284
  await sm.appendMessage({
319
285
  role: "user",
@@ -321,105 +287,61 @@ const result = await ctx.newSession({
321
287
  timestamp: Date.now(),
322
288
  });
323
289
  },
324
- withSession: async (ctx) => {
325
- // Use only the replacement-session ctx here.
326
- await ctx.sendUserMessage(kickoff);
290
+ withSession: async (nextCtx) => {
291
+ await nextCtx.sendUserMessage("Continue in the new session");
327
292
  },
328
293
  });
329
-
330
294
  if (result.cancelled) {
331
- // An extension cancelled the new session
295
+ // Cancelled by session_before_switch
332
296
  }
333
297
  ```
334
298
 
335
- Options:
336
- - `parentSession`: parent session ID to record in the new session header
337
- - `setup`: mutate the new session's `SessionManager` before `withSession` runs
338
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `atomic` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
339
-
340
299
  ### ctx.fork(entryId, options?)
341
300
 
342
- Fork from a specific entry, creating a new session file:
301
+ Fork from an entry into a new session file. Options: `position` (`"before"` default, restoring that user prompt into the editor; `"at"` clones through that entry without restoring editor text) and `withSession(ctx)`:
343
302
 
344
303
  ```typescript
345
- const result = await ctx.fork("entry-id-123", {
346
- withSession: async (ctx) => {
347
- // Use only the replacement-session ctx here.
348
- ctx.ui.notify("Now in the forked session", "info");
304
+ const forkResult = await ctx.fork("entry-id-123", {
305
+ withSession: async (nextCtx) => {
306
+ nextCtx.ui.notify("Now in the forked session", "info");
349
307
  },
350
308
  });
351
- if (result.cancelled) {
352
- // An extension cancelled the fork
353
- }
354
309
 
355
310
  const cloneResult = await ctx.fork("entry-id-456", { position: "at" });
356
- if (cloneResult.cancelled) {
357
- // An extension cancelled the clone
358
- }
359
311
  ```
360
312
 
361
- Options:
362
- - `position`: `"before"` (default) forks before the selected user message, restoring that prompt into the editor
363
- - `position`: `"at"` duplicates the active path through the selected entry without restoring editor text
364
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `atomic` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
365
-
366
313
  ### ctx.navigateTree(targetId, options?)
367
314
 
368
- Navigate to a different point in the session tree. Navigation rejects while a response, compaction, or branch summarization is active, even with `summarize: false`. Rejection leaves the active branch unchanged. Wait for the active operation to finish and retry.
315
+ Navigate to another point in the session tree. Rejects while streaming, compacting, or summarizing without changing the active branch. Options: `summarize`, `customInstructions`, `replaceInstructions`, and `label`:
369
316
 
370
317
  ```typescript
371
- const result = await ctx.navigateTree("entry-id-456", {
318
+ await ctx.navigateTree("entry-id-456", {
372
319
  summarize: true,
373
320
  customInstructions: "Focus on error handling changes",
374
- replaceInstructions: false, // true = replace default prompt entirely
321
+ replaceInstructions: false,
375
322
  label: "review-checkpoint",
376
323
  });
377
324
  ```
378
325
 
379
- Options:
380
- - `summarize`: Whether to generate a summary of the abandoned branch
381
- - `customInstructions`: Custom instructions for the summarizer
382
- - `replaceInstructions`: If true, `customInstructions` replaces the default prompt instead of being appended
383
- - `label`: Label to attach to the branch summary entry (or target entry if not summarizing)
384
-
385
326
  ### ctx.switchSession(sessionId, options?)
386
327
 
387
- Switch to a different session by its exact ID:
388
-
389
- ```typescript
390
- const result = await ctx.switchSession("my-session-id", {
391
- withSession: async (ctx) => {
392
- await ctx.sendUserMessage("Resume work in the replacement session");
393
- },
394
- });
395
- if (result.cancelled) {
396
- // An extension cancelled the switch via session_before_switch
397
- }
398
- ```
399
-
400
- Options:
401
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `atomic` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
328
+ Switch to another session by exact ID. Options: `withSession(ctx)`.
402
329
 
403
- If the session's recorded working directory does not exist, nothing is opened and the call rejects with a `MissingSessionCwdError` (`code: "session-cwd-missing"`; check it with `isMissingSessionCwdError`). Atomic asks the user whether to continue in the current directory or fork the session there only when it runs the session in the terminal's own process; the default interactive mode runs extensions in a separate process, so the rejection reaches your code. See [Sessions](/sessions#resuming-and-deleting-sessions).
404
-
405
- To discover available sessions, use the static `SessionManager.list()` or `SessionManager.listAll()` methods:
330
+ If the target session's recorded working directory no longer exists, `switchSession()` rejects with `MissingSessionCwdError` (`code: "session-cwd-missing"`; guard with `isMissingSessionCwdError`). Use `SessionManager.list(cwd)` or `SessionManager.listAll()` to discover session IDs:
406
331
 
407
332
  ```typescript
408
333
  import { SessionManager } from "@bastani/atomic";
409
334
 
410
335
  atomic.registerCommand("switch", {
411
336
  description: "Switch to another session",
412
- handler: async (args, ctx) => {
337
+ handler: async (_args, ctx) => {
413
338
  const sessions = await SessionManager.list(ctx.cwd);
414
339
  if (sessions.length === 0) return;
415
- const choice = await ctx.ui.select(
416
- "Pick session:",
417
- sessions.map(s => s.id),
418
- );
340
+ const choice = await ctx.ui.select("Pick session:", sessions.map((s) => s.id));
419
341
  if (choice) {
420
342
  await ctx.switchSession(choice, {
421
- withSession: async (ctx) => {
422
- ctx.ui.notify("Switched session", "info");
343
+ withSession: async (nextCtx) => {
344
+ nextCtx.ui.notify("Switched session", "info");
423
345
  },
424
346
  });
425
347
  }
@@ -429,386 +351,158 @@ atomic.registerCommand("switch", {
429
351
 
430
352
  ### Session replacement lifecycle and footguns
431
353
 
432
- `withSession` receives a fresh `ReplacedSessionContext`, which extends `ExtensionCommandContext` with async `sendMessage()` and `sendUserMessage()` helpers bound to the replacement session.
433
-
434
- Lifecycle and footguns:
435
- - `withSession` runs only after the old session has emitted `session_shutdown`, the old runtime has been torn down, the replacement session has been rebound, and the new extension instance has already received `session_start`.
436
- - The callback still executes in the original closure, not inside the new extension instance. That means your old extension instance may already have run its shutdown cleanup before `withSession` starts.
437
- - Captured old `atomic` / old command `ctx` session-bound objects are stale after replacement and will throw if used. Use only the `ctx` passed to `withSession` for session-bound work.
438
- - Previously extracted raw objects are still your responsibility. For example, if you capture `const sm = ctx.sessionManager` before replacement, `sm` is still the old `SessionManager` object. Do not reuse it after replacement.
439
- - Code in `withSession` should assume any state invalidated by your `session_shutdown` handler is already gone. Only capture plain data that survives shutdown cleanly, such as strings, ids, and serialized config.
440
- - Long-lived callbacks that need to classify a stale API error should use `isStaleExtensionContextError(error)` from `@bastani/atomic`, not match the host's error message.
441
-
442
- Safe pattern:
443
-
444
- ```typescript
445
- atomic.registerCommand("handoff", {
446
- handler: async (_args, ctx) => {
447
- const kickoff = "Continue from the replacement session";
448
- await ctx.newSession({
449
- withSession: async (ctx) => {
450
- await ctx.sendUserMessage(kickoff);
451
- },
452
- });
453
- },
454
- });
455
- ```
456
-
457
- Unsafe pattern:
354
+ `withSession` receives a fresh `ReplacedSessionContext`, which extends `ExtensionCommandContext` with async `sendMessage()` and `sendUserMessage(): Promise<void>` bound to the replacement session.
458
355
 
459
- ```typescript
460
- atomic.registerCommand("handoff", {
461
- handler: async (_args, ctx) => {
462
- const oldSessionManager = ctx.sessionManager;
463
- await ctx.newSession({
464
- withSession: async (_ctx) => {
465
- // stale old objects: do not do this
466
- oldSessionManager.getSessionFile();
467
- atomic.sendUserMessage("wrong");
468
- },
469
- });
470
- },
471
- });
472
- ```
356
+ - `withSession` runs after the old session has emitted `session_shutdown`, reloaded extensions, and emitted `session_start` on the new session.
357
+ - Because `withSession` executes inside your original closure, old `atomic` handles, old `ctx`, and extracted objects like `const sm = ctx.sessionManager` are stale and throw if used. Use only the `nextCtx` parameter passed to `withSession`, and capture only plain serializable data (strings, IDs, config).
358
+ - Use `isStaleExtensionContextError(error)` from `@bastani/atomic` to detect stale-context errors in long-lived callbacks.
473
359
 
474
360
  ### ctx.reload()
475
361
 
476
- Run the same reload flow as `/reload`.
477
-
478
- ```typescript
479
- atomic.registerCommand("reload-runtime", {
480
- description: "Reload extensions, skills, prompts, and themes",
481
- handler: async (_args, ctx) => {
482
- await ctx.reload();
483
- return;
484
- },
485
- });
486
- ```
487
-
488
- Important behavior:
489
- - `await ctx.reload()` emits `session_shutdown` for the current extension runtime
490
- - It then reloads resources and emits `session_start` with `reason: "reload"` and `resources_discover` with reason `"reload"`
491
- - The currently running command handler still continues in the old call frame
492
- - Code after `await ctx.reload()` still runs from the pre-reload version
493
- - Code after `await ctx.reload()` must not assume old in-memory extension state is still valid
494
- - After the handler returns, future commands/events/tool calls use the new extension version
495
-
496
- For predictable behavior, treat reload as terminal for that handler (`await ctx.reload(); return;`).
497
-
498
- Tools run with `ExtensionContext`, so they cannot call `ctx.reload()` directly. Use a command as the reload entrypoint, then expose a tool that queues that command as a follow-up user message.
499
-
500
- Example tool the LLM can call to trigger reload:
501
-
502
- ```typescript
503
- import type { ExtensionAPI } from "@bastani/atomic";
504
- import { Type } from "typebox";
505
-
506
- export default function (atomic: ExtensionAPI) {
507
- atomic.registerCommand("reload-runtime", {
508
- description: "Reload extensions, skills, prompts, and themes",
509
- handler: async (_args, ctx) => {
510
- await ctx.reload();
511
- return;
512
- },
513
- });
362
+ Runs the same reload sequence as `/reload` (emits `session_shutdown`, reloads resources, emits `session_start` and `resources_discover` with `reason: "reload"`). Code after `await ctx.reload()` still executes in the pre-reload function frame, so return immediately (`await ctx.reload(); return;`).
514
363
 
515
- atomic.registerTool({
516
- name: "reload_runtime",
517
- label: "Reload Runtime",
518
- description: "Reload extensions, skills, prompts, and themes",
519
- parameters: Type.Object({}),
520
- async execute() {
521
- atomic.sendUserMessage("/reload-runtime", { deliverAs: "followUp" });
522
- return {
523
- content: [{ type: "text", text: "Queued /reload-runtime as a follow-up command." }],
524
- };
525
- },
526
- });
527
- }
528
- ```
364
+ Tools receive `ExtensionContext` and cannot call `ctx.reload()` directly; register a command and have a tool queue it with `atomic.sendUserMessage("/reload-runtime", { deliverAs: "followUp" })`.
529
365
 
530
366
  ## ExtensionAPI methods
531
367
 
532
- <a id="pi-on-event-handler" />
533
-
534
- ### atomic.on(event, handler)
535
-
536
- Subscribe to events. See [Events](/extensions/events#events) for event types and return values.
537
-
538
- <a id="pi-registertool-definition" />
368
+ ### atomic.getSettings()
539
369
 
540
- ### atomic.registerTool(definition)
541
-
542
- Register a custom tool callable by the LLM. See [Custom tools](/extensions/authoring#custom-tools) for full details.
543
-
544
- `atomic.registerTool()` works both during extension load and after startup. You can call it inside `session_start`, command handlers, or other event handlers. New tools refresh immediately in the same session, so they appear in `atomic.getAllTools()` and are callable by the LLM without `/reload`.
545
-
546
- If an extension registers the same tool name more than once while it loads, the last registration wins and Atomic shows a warning under `[Extension issues]`.
547
-
548
- Use `atomic.setActiveTools()` to enable or disable registered tools, including dynamically added tools and Intercom. Tools suppressed by a session allowlist or exclusions cannot be activated this way.
370
+ Returns a snapshot of effective `Settings`. Available after the session runtime binds (call from `session_start`, commands, tools, or event handlers rather than top-level factory code).
549
371
 
550
- Use `promptSnippet` to opt a custom tool into a one-line entry in `Available tools`, and `promptGuidelines` to append tool-specific bullets to the default `Guidelines` section when the tool is active. Because `promptGuidelines` bullets are appended flat without a tool name prefix, each guideline must name the tool it refers to (write "Use `my_tool` when..." instead of "Use this tool when...").
551
-
552
- An orchestrating tool can adjust what the model sees by implementing `prepareLoadout(loadout)`. The hook receives declared, callable, and registered tools along with `getExposure()`, `getNamespace()`, and `getPromptGuidelines()`. Return replacement `descriptions` or `hiddenDeclarations` to hide active tools' declarations while keeping them callable from scripts. The default system prompt omits hidden tools from its tool list and rules, and names no tool in the skills hint when the file reader is hidden; the orchestrating tool should present those guidelines itself, as `codemode` does.
553
-
554
- See [dynamic-tools.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/dynamic-tools.ts) for a full example.
555
-
556
- #### Built-in tool prompt contributions
372
+ ### atomic.on(event, handler)
557
373
 
558
- Atomic exports immutable prompt metadata for its built-in coding tools. Use these constants when an embedded application or tool registry needs the same prompt entries as the built-in factories:
374
+ Subscribe to a lifecycle event and return an unsubscribe function `() => void`. See [Extension events](/extensions/events#events) for all event types, payloads, and return contracts:
559
375
 
560
376
  ```typescript
561
- import {
562
- bashToolSystemPromptContribution,
563
- editToolSystemPromptContribution,
564
- findToolSystemPromptContribution,
565
- lsToolSystemPromptContribution,
566
- readToolSystemPromptContribution,
567
- searchToolSystemPromptContribution,
568
- writeToolSystemPromptContribution,
569
- } from "@bastani/atomic";
570
-
571
- const { snippet, guidelines } = readToolSystemPromptContribution;
377
+ const unsubscribe = atomic.on("turn_end", (event) => {
378
+ if (event.turnIndex >= 5) unsubscribe();
379
+ });
572
380
  ```
573
381
 
574
- Each contribution provides a readonly `snippet` for the `Available tools` section and readonly `guidelines` for the active tool's `Guidelines` entries. The seven exports cover `bash`, `edit`, `find`, `ls`, `read`, `search`, and `write`. The built-in factories use these values directly, so callers do not need to duplicate prompt text.
382
+ ### atomic.registerTool(definition)
575
383
 
576
- Import `StringEnum` from `@bastani/atomic` (also exported from `@bastani/atomic-ai`) for string enum parameters so the schema stays Google-compatible and typed against Atomic's TypeBox version.
384
+ Register a custom tool callable by the model. Works both during extension load and dynamically afterward (inside `session_start`, commands, or event handlers), taking effect immediately without `/reload`. See [Custom tools](/extensions/authoring#custom-tools).
577
385
 
578
- ```typescript
579
- import { Type } from "typebox";
580
- import { StringEnum } from "@bastani/atomic";
581
-
582
- atomic.registerTool({
583
- name: "my_tool",
584
- label: "My Tool",
585
- description: "What this tool does",
586
- promptSnippet: "Summarize or transform text according to action",
587
- promptGuidelines: ["Use my_tool when the user asks to summarize previously generated text."],
588
- parameters: Type.Object({
589
- action: StringEnum(["list", "add"] as const),
590
- text: Type.Optional(Type.String()),
591
- }),
592
- prepareArguments(args) {
593
- // Optional compatibility shim. Runs before schema validation.
594
- // Return the current schema shape, for example to fold legacy fields
595
- // into the modern parameter object.
596
- return args;
597
- },
386
+ Collision rules:
598
387
 
599
- async execute(toolCallId, params, signal, onUpdate, ctx) {
600
- // Stream progress
601
- onUpdate?.({ content: [{ type: "text", text: "Working..." }] });
388
+ - Within one extension, registering the same tool name twice keeps the last registration and shows a warning under `[Extension issues]`.
389
+ - Across multiple extensions, the **first** loaded extension wins. The mandatory bundled `intercom` tool cannot be shadowed.
602
390
 
603
- return {
604
- content: [{ type: "text", text: "Done" }],
605
- details: { result: "..." },
606
- };
607
- },
608
-
609
- // Optional: Custom rendering
610
- renderCall(args, theme, context) { ... },
611
- renderResult(result, options, theme, context) { ... },
612
- });
613
- ```
391
+ Stop promptly when `signal` aborts. A tool call that does not settle within 10 seconds after abort (`ATOMIC_TOOL_ABORT_GRACE_MS`) gets an `Operation aborted` error result and any late return value is discarded.
614
392
 
615
- Stop promptly when `signal` aborts because the user interrupted the turn or the session is stopping. A call that has not returned 10 seconds after the abort (`ATOMIC_TOOL_ABORT_GRACE_MS`) receives an `Operation aborted` error result so the turn can finish and later tool calls stop waiting. Its late return value or error is discarded rather than added to the transcript or sent to the model. A call still waiting for an earlier call when the turn is interrupted never starts and gets `Operation aborted` immediately.
393
+ #### Built-in tool prompt contributions
616
394
 
617
- <a id="pi-sendmessage-message-options" />
395
+ Atomic exports immutable `{ snippet, guidelines }` constants for built-in coding tools (`bashToolSystemPromptContribution`, `editToolSystemPromptContribution`, `findToolSystemPromptContribution`, `lsToolSystemPromptContribution`, `readToolSystemPromptContribution`, `searchToolSystemPromptContribution`, `writeToolSystemPromptContribution`) so overrides can reuse built-in prompt text without duplicating it.
618
396
 
619
397
  ### atomic.sendMessage(message, options?)
620
398
 
621
- Inject a custom message into the session. The call returns `void | Promise<void>` for compatibility with synchronous hosts; use `await Promise.resolve(atomic.sendMessage(...))` when admission or routing failure must be observed. Atomic's `AgentSession` runtime returns an admission receipt that settles once the message enters the local queue, without waiting for the resulting model turn to finish.
399
+ Queue a custom message into the session. Returns `void | Promise<void>`; wrap with `await Promise.resolve(atomic.sendMessage(...))` to catch validation or routing failures. In Atomic's standard session runtime, the returned promise resolves once the message is queued (without waiting for the resulting model turn to finish).
400
+
401
+ `customType` must be a string and `content` a string or content-block array, or the call throws `TypeError` and saves nothing.
622
402
 
623
403
  ```typescript
624
- atomic.sendMessage({
625
- customType: "my-extension",
626
- content: "Message text",
627
- display: true,
628
- details: { ... },
629
- }, {
630
- triggerTurn: true,
631
- deliverAs: "steer",
632
- });
404
+ await Promise.resolve(
405
+ atomic.sendMessage(
406
+ {
407
+ customType: "my-extension",
408
+ content: "Message text",
409
+ display: true,
410
+ details: { step: 1 },
411
+ },
412
+ { triggerTurn: true, deliverAs: "steer" },
413
+ ),
414
+ );
633
415
  ```
634
416
 
635
- `display: true` shows the message in the chat; `false`, or omitting `display`, keeps it out of the chat. `customType` must be a string and `content` a string or an array of content blocks; otherwise the call throws a `TypeError` and saves nothing.
636
-
637
- Options:
638
-
639
- - `deliverAs`. Delivery mode:
640
- - `"steer"` (default). Queues the message while streaming and delivers it after the current assistant turn finishes its tool calls, before the next LLM call.
641
- - `"followUp"`. Waits for the agent to finish all tool calls before delivering.
642
- - `"nextTurn"`. Queues for the next user prompt without interrupting or triggering a turn.
643
- - `"interrupt"`. With `triggerTurn: true`, aborts an active streaming turn and immediately starts a new turn with the custom message. When idle, behaves like a triggered custom message.
644
- - `triggerTurn: true`. If the agent is idle, triggers an LLM response immediately. Required for `"interrupt"`; ignored for `"nextTurn"`.
645
- - `excludeFromContext: true`. Renders and persists the custom message without adding it to LLM context. With no `deliverAs`, remains display-only even while the agent is streaming.
646
- - `interruptAbortMessage`. Optional text replacing generic abort results (such as `Operation aborted`) when `deliverAs: "interrupt"` aborts an active turn.
417
+ Options (`SendMessageOptions`):
647
418
 
648
- A command can answer with `sendMessage()`, `sendMessages()`, or `sendUserMessage()` without awaiting it. In print mode (`-p`) and JSON event stream mode, Atomic waits for messages sent before the command handler returns and for the turns they start before printing the result or running the next prompt. Messages sent later from a timer or background task are not waited for. With text output (`-p` without `--mode json`), a command whose messages could not be saved and that sent nothing else prints nothing and exits with status `1`.
419
+ - `deliverAs`: `"steer"` (default; queues after current turn's tool calls), `"followUp"` (waits until all tool calls finish), `"nextTurn"` (attaches to the next user prompt without triggering a turn), or `"interrupt"` (with `triggerTurn: true`, aborts the active turn and starts a new turn immediately).
420
+ - `triggerTurn`: start a model turn immediately if idle (required for `"interrupt"`, ignored for `"nextTurn"`).
421
+ - `excludeFromContext`: render and persist the message without adding it to model context.
422
+ - `interruptAbortMessage`: custom abort text when `deliverAs: "interrupt"` stops an active turn.
423
+ - `persistWhenStreaming`: persist the custom message immediately even while a turn is streaming.
424
+ - `stageAdmissionKey`: optional deduplication key for staged recovery deliveries.
649
425
 
650
- <a id="pi-sendmessages-messages-options" />
426
+ In print (`-p`) and JSON modes, Atomic waits for messages queued before a command handler returns (and the turns they trigger) before exiting.
651
427
 
652
428
  ### atomic.sendMessages(messages, options?)
653
429
 
654
- Atomically admit a batch of custom messages in array order. The call returns `void | Promise<void>` for compatibility with synchronous hosts; use `await Promise.resolve(atomic.sendMessages(...))` when admission or routing failure must be observed. The promise is an admission receipt and does not wait for the resulting model turn. Admission is indivisible, which keeps a prelude and terminal notice contiguous without globally serializing other extension work.
430
+ Queue a batch of custom messages together in array order so no other message can split them. Returns `void | Promise<void>` (resolving once queued, not when the turn finishes). Supports `triggerTurn`, `excludeFromContext`, and `deliverAs: "steer" | "followUp" | "nextTurn"` (not `"interrupt"`). If any message fails validation, throws `TypeError` and queues none.
655
431
 
656
432
  ```typescript
657
- atomic.sendMessages([
658
- { customType: "worker-update", content: "Ready", display: true },
659
- { customType: "worker-terminal", content: "Completed", display: true },
660
- ], { triggerTurn: true });
433
+ await Promise.resolve(
434
+ atomic.sendMessages(
435
+ [
436
+ { customType: "worker-update", content: "Ready", display: true },
437
+ { customType: "worker-terminal", content: "Completed", display: true },
438
+ ],
439
+ { triggerTurn: true },
440
+ ),
441
+ );
661
442
  ```
662
443
 
663
- The batch supports `triggerTurn`, `excludeFromContext`, and `deliverAs: "steer" | "followUp" | "nextTurn"`. Interrupt delivery remains a single-message operation. Each message follows the `atomic.sendMessage()` rules; if any message breaks them, the call throws a `TypeError` and none are sent.
664
-
665
- <a id="pi-sendusermessage-content-options" />
666
-
667
444
  ### atomic.sendUserMessage(content, options?)
668
445
 
669
- Send a user message to the agent. Unlike `sendMessage()`, which sends custom messages, this sends an actual user message as if typed by the user and always triggers a turn.
446
+ Send an actual user message (always triggering a turn). Returns `void` on `ExtensionAPI` (whereas `ReplacedSessionContext.sendUserMessage()` inside `withSession` returns `Promise<void>`).
670
447
 
671
448
  ```typescript
672
- // Simple text message
673
449
  atomic.sendUserMessage("What is 2+2?");
674
-
675
- // With content array (text + images)
676
- atomic.sendUserMessage([
677
- { type: "text", text: "Describe this image:" },
678
- { type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } },
679
- ]);
680
-
681
- // During streaming: specify delivery mode
682
450
  atomic.sendUserMessage("Focus on error handling", { deliverAs: "steer" });
683
- atomic.sendUserMessage("And then summarize", { deliverAs: "followUp" });
684
-
685
- // Opt in to extension command dispatch and skill/prompt template expansion
686
451
  atomic.sendUserMessage("/review src/index.ts", { expandPromptTemplates: true });
687
452
  ```
688
453
 
689
454
  Options:
690
455
 
691
- - `deliverAs`. Required when the agent is streaming:
692
- - `"steer"`. Queues the message for delivery after the current assistant turn finishes its tool calls.
693
- - `"followUp"`. Waits for the agent to finish all tools.
694
- - `expandPromptTemplates`. Dispatches extension commands and expands skill commands and prompt templates instead of sending the text literally. Defaults to `false`, so an extension-authored message is sent as-is unless it opts in. An unknown command falls through to a literal send.
695
-
696
- When idle, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, the call throws an error. While the session compacts, the message waits, shows as queued, and sends once compaction ends, after messages sent before it; if one of those has already started a turn, a message without `deliverAs` queues behind it as steering.
456
+ - `deliverAs`: `"steer"` or `"followUp"` (required when the agent is streaming; omitting it while streaming throws an error).
457
+ - `expandPromptTemplates`: defaults to `false`; set `true` to dispatch extension commands and expand `/skill:` and prompt templates.
697
458
 
698
- See [send-user-message.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/send-user-message.ts) for a complete example.
699
-
700
- <a id="pi-appendentry-customtype-data" />
459
+ While the session is compacting, the message waits in the queue and sends once compaction ends.
701
460
 
702
461
  ### atomic.appendEntry(customType, data?)
703
462
 
704
- Persist extension state (does NOT participate in LLM context). `customType` must be a string; otherwise the returned promise rejects with a `TypeError` and nothing is saved.
463
+ Persist durable extension state without adding it to model context. `customType` must be a string (otherwise rejects with `TypeError`). Await the returned promise before reading the entry; appending emits `entry_appended`.
464
+
465
+ During `session_start` on `/reload`, `appendEntry()`, `setSessionName()`, and `setLabel()` stage writes until reload succeeds (a failed reload discards them), so do not read staged writes back inside that `session_start` handler.
705
466
 
706
467
  ```typescript
707
468
  await atomic.appendEntry("my-state", { count: 42 });
708
-
709
- // Restore on reload
710
- atomic.on("session_start", async (_event, ctx) => {
711
- for (const entry of ctx.sessionManager.getEntries()) {
712
- if (entry.type === "custom" && entry.customType === "my-state") {
713
- // Reconstruct from entry.data
714
- }
715
- }
716
- });
717
469
  ```
718
470
 
719
- Await `atomic.appendEntry` before using the new entry. The promise resolves after the write commits and rejects with the store's typed error if it fails. Setup entries also commit before the promise resolves. Appending emits `entry_appended` with the committed entry. This lets extensions react to session entries without polling.
720
-
721
- During a transactional reload's `session_start` handler, `atomic.appendEntry`, `atomic.setSessionName`, and `atomic.setLabel` stage their writes instead. Awaiting them confirms staging; the writes and their notifications are published in call order only after reload succeeds. Rejected reloads discard these changes. Do not depend on reading the staged changes back during that handler.
722
-
723
- <a id="pi-registerentryrenderer-customtype-renderer" />
724
-
725
471
  ### atomic.registerEntryRenderer(customType, renderer)
726
472
 
727
- Register a TUI renderer for durable custom entries created by `atomic.appendEntry()`. These entries render in the transcript but do not enter model context. Ctrl+O, or a click on the entry in fullscreen mode, toggles `expanded`.
728
-
729
- SDK hosts can inspect the original callback with `session.extensionRunner.getEntryRenderer(customType)`. To render through the owning session, call `session.extensionRunner.renderEntry(customType, entry, { expanded }, theme)`; retired runners reject rendering.
473
+ Register a TUI renderer for durable custom entries created by `atomic.appendEntry()`. `Ctrl+O` or clicking the entry in fullscreen mode toggles `expanded`.
730
474
 
731
475
  ```typescript
732
476
  import { Text } from "@bastani/atomic-tui";
733
477
 
734
478
  atomic.registerEntryRenderer("status-card", (entry, { expanded }, theme) =>
735
- new Text(theme.fg("accent", `${expanded ? "Details" : "Status"}: ${JSON.stringify(entry.data)}`), 0, 0)
479
+ new Text(theme.fg("accent", `${expanded ? "Details" : "Status"}: ${JSON.stringify(entry.data)}`), 0, 0),
736
480
  );
737
481
  ```
738
482
 
483
+ ### atomic.setSessionName(name) / atomic.getSessionName()
739
484
 
740
- <a id="pi-setsessionname-name" />
741
-
742
- ### atomic.setSessionName(name)
743
-
744
- Set the session display name (shown in session selector instead of first message).
745
-
746
- ```typescript
747
- await atomic.setSessionName("Refactor auth module");
748
- ```
749
-
750
- <a id="pi-getsessionname" />
751
-
752
- ### atomic.getSessionName()
753
-
754
- Get the current session name, if set.
755
-
756
- ```typescript
757
- const name = atomic.getSessionName();
758
- if (name) {
759
- console.log(`Session: ${name}`);
760
- }
761
- ```
762
-
763
- <a id="pi-setlabel-entryid-label" />
485
+ Set (`Promise<void>`) or read (`string | undefined`) the session display name shown in `/resume` and the session selector.
764
486
 
765
487
  ### atomic.setLabel(entryId, label)
766
488
 
767
- Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation (shown in `/tree` selector). A label is a string, or `undefined` to clear it; any other value rejects with a `TypeError`.
768
-
769
- ```typescript
770
- // Set a label
771
- await atomic.setLabel(entryId, "checkpoint-before-refactor");
772
-
773
- // Clear a label
774
- await atomic.setLabel(entryId, undefined);
775
-
776
- // Read labels via sessionManager
777
- const label = ctx.sessionManager.getLabel(entryId);
778
- ```
779
-
780
- Labels persist in the session and survive restarts. Use them to mark important points (turns, checkpoints) in the conversation tree.
781
-
782
- <a id="pi-registercommand-name-options" />
489
+ Set a string bookmark label on an entry (shown in `/tree`), or pass `undefined` to clear it. Any other value rejects with `TypeError`. Read labels with `ctx.sessionManager.getLabel(entryId)`.
783
490
 
784
491
  ### atomic.registerCommand(name, options)
785
492
 
786
- Register a command.
493
+ Register a slash command. If multiple extensions register the same command name, **all** colliding commands receive numeric suffixes in load order (`/review:1`, `/review:2`), and no bare `/review` command remains.
787
494
 
788
- If multiple extensions register the same command name, Atomic keeps them all and assigns numeric invocation suffixes in load order, for example `/review:1` and `/review:2`.
789
-
790
- ```typescript
791
- atomic.registerCommand("stats", {
792
- description: "Show session statistics",
793
- handler: async (args, ctx) => {
794
- const count = ctx.sessionManager.getEntries().length;
795
- ctx.ui.notify(`${count} entries`, "info");
796
- }
797
- });
798
- ```
799
-
800
- Optional: add argument auto-completion for `/command ...`:
495
+ `getArgumentCompletions(prefix)` may return `AutocompleteItem[] | null` or `Promise<AutocompleteItem[] | null>`:
801
496
 
802
497
  ```typescript
803
498
  import type { AutocompleteItem } from "@bastani/atomic-tui";
804
499
 
805
500
  atomic.registerCommand("deploy", {
806
501
  description: "Deploy to an environment",
807
- getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => {
502
+ getArgumentCompletions: async (prefix: string): Promise<AutocompleteItem[] | null> => {
808
503
  const envs = ["dev", "staging", "prod"];
809
- const items = envs.map((e) => ({ value: e, label: e }));
810
- const filtered = items.filter((i) => i.value.startsWith(prefix));
811
- return filtered.length > 0 ? filtered : null;
504
+ const items = envs.filter((e) => e.startsWith(prefix)).map((e) => ({ value: e, label: e }));
505
+ return items.length > 0 ? items : null;
812
506
  },
813
507
  handler: async (args, ctx) => {
814
508
  ctx.ui.notify(`Deploying: ${args}`, "info");
@@ -816,24 +510,13 @@ atomic.registerCommand("deploy", {
816
510
  });
817
511
  ```
818
512
 
819
- <a id="pi-getcommands" />
820
-
821
513
  ### atomic.getCommands()
822
514
 
823
- Get the slash commands available for invocation via `prompt` in the current session. Includes extension commands, prompt templates, and skill commands.
824
- The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills.
825
-
826
- ```typescript
827
- const commands = atomic.getCommands();
828
- const bySource = commands.filter((command) => command.source === "extension");
829
- const userScoped = commands.filter((command) => command.sourceInfo.scope === "user");
830
- ```
831
-
832
- Each entry has this shape:
515
+ Returns all slash commands invocable via prompts (`extension`, `prompt`, and `skill` sources, in that order; excludes interactive-only built-in commands like `/model` and `/settings`). Each item contains:
833
516
 
834
517
  ```typescript
835
518
  {
836
- name: string; // Invokable command name without the leading slash. May be suffixed like "review:1"
519
+ name: string; // Without leading slash; may be suffixed like "review:1"
837
520
  description?: string;
838
521
  source: "extension" | "prompt" | "skill";
839
522
  sourceInfo: {
@@ -842,90 +525,57 @@ Each entry has this shape:
842
525
  scope: "user" | "project" | "temporary";
843
526
  origin: "package" | "top-level";
844
527
  baseDir?: string;
528
+ configurationOrigin?: "atomic" | "inherited-pi" | "bundled";
845
529
  };
846
530
  }
847
531
  ```
848
532
 
849
- Use `sourceInfo` as the canonical provenance field. Do not infer ownership from command names or from ad hoc path parsing.
850
-
851
- Built-in interactive commands (like `/model` and `/settings`) are not included here. They are handled only in interactive
852
- mode and would not execute if sent via `prompt`.
853
-
854
- <a id="pi-registermessagerenderer-customtype-renderer" />
855
-
856
533
  ### atomic.registerMessageRenderer(customType, renderer)
857
534
 
858
- Register a custom TUI renderer for messages with your `customType`. The renderer options contain `expanded` and the current numeric `outputPad`, so custom output can align with built-in messages. The same options are provided in normal and isolated-engine rendering. A click on the message in fullscreen mode toggles `expanded` when that changes what the renderer draws, unless its in-process component handles the click itself. See [Custom UI](/extensions/ui#custom-ui).
859
-
860
- <a id="pi-registertoolrenderer-resolver" />
535
+ Register a TUI renderer for custom messages with `customType`. Options include `expanded`, `outputPad`, `keyHint()`, and `keyText()` in both interactive and embedded rendering. Returning a `Component` renders it, returning `null` suppresses the message completely (zero rows, no box), and returning `undefined` falls back to the default boxed rendering. Clicking the message in fullscreen mode toggles `expanded` unless a custom mouse handler consumes the click. See [Message rendering](/extensions/ui#message-rendering).
861
536
 
862
537
  ### atomic.registerToolRenderer(resolver)
863
538
 
864
- Register a resolver `(toolName, next) => renderers` that supplies `renderCall` and `renderResult` (and optional `renderShell`) for any tool in the interactive transcript and HTML exports, including MCP tools in resumed sessions before their server connects.
865
-
866
- Resolvers run in extension load order. Calling `next()` returns the remaining resolvers' choice and then the registered tool's own renderers, so `next() ?? myRenderers` fills in only when no renderer exists. Extension `Image` components returned by tool renderers also display JPEG, GIF, and WebP images automatically on Kitty-protocol terminals. See [Custom rendering](/extensions/authoring#custom-rendering).
539
+ Register a resolver `(toolName, next) => renderers` supplying `renderCall`, `renderResult`, and optional `renderShell` for any tool (including MCP tools in resumed sessions before their server connects). Resolvers run in extension load order; `next()` returns the remaining resolvers' choice and then the tool's own renderers. See [Custom rendering](/extensions/authoring#custom-rendering).
867
540
 
868
- <a id="pi-registermarkdowntransformer-transformer" />
541
+ <div id="pi-registermarkdowntransformer-transformer" />
869
542
 
870
- ### atomic.registerMarkdownTransformer(transformer)
543
+ ### atomic.registerMarkdownTransformer(transformer, options?)
871
544
 
872
- Register a synchronous, display-only transformer for Markdown before Atomic renders it in interactive mode. Atomic runs transformers in extension load order. Each extension keeps one transformer, so a later call from the same extension replaces its earlier transformer. Each transformer receives the Markdown returned by the previous one, and Atomic renders the final value with its built-in Markdown renderer.
545
+ Register a synchronous, display-only Markdown transformer for interactive rendering. Transformers run in load order (one per extension; a second call replaces the first). Optional `options.messageTypes` selects which message kinds to transform (default `["user", "assistant", "assistant-thinking"]`; also supports `"custom"`, `"summary"`, `"changelog"`).
873
546
 
874
- The optional second argument, `atomic.registerMarkdownTransformer(transformer, options)`, accepts `options.messageTypes`. By default a transformer runs on normal user text, assistant text, and thinking blocks; `messageTypes` lists the message kinds it runs on instead:
875
-
876
- | `messageType` | Rendered content |
877
- | --- | --- |
878
- | `"user"`, `"assistant"`, `"assistant-thinking"` | Transcript messages (default) |
879
- | `"custom"` | Custom messages from `atomic.sendMessage()` without a registered message renderer, and expanded skill blocks (their content, without Atomic's header) |
880
- | `"summary"` | Expanded branch summaries (the summary, without Atomic's header) |
881
- | `"changelog"` | Atomic's changelog ("What's New" at startup and `/changelog`) |
882
-
883
- The transformer receives the Markdown string and a context object:
884
-
885
- - `messageType`. One of the rendered content kinds above.
886
- - `isStreaming`. `true` for partial assistant updates; `false` otherwise.
887
- - `availableWidth`. Exact terminal columns available for the transformed Markdown content.
888
- - `messageId`. The session entry ID when rendering from the saved session (resume, `/tree`, or rebuilds); `undefined` for live messages and the changelog.
889
- - `timestamp`. The session entry's ISO timestamp under the same conditions; `undefined` for live messages and the changelog.
890
-
891
- Return the transformed Markdown:
547
+ Context fields passed to the transformer: `messageType`, `isStreaming`, `availableWidth`, `messageId` (`undefined` for live messages and changelog), and `timestamp` (`undefined` for live messages and changelog). Display transformers do not run when extensions execute in the separate interactive worker process.
892
548
 
893
549
  ```typescript
894
550
  atomic.registerMarkdownTransformer((markdown, { messageType, isStreaming }) => {
895
551
  if (isStreaming || messageType === "assistant-thinking") return markdown;
896
552
  return markdown.replaceAll("-->", "→");
897
553
  });
898
-
899
- // Show :warning: shortcodes in the changelog as a symbol.
900
- atomic.registerMarkdownTransformer((markdown) => markdown.replaceAll(":warning:", "⚠"), {
901
- messageTypes: ["changelog"],
902
- });
903
554
  ```
904
555
 
905
- If a transformer throws, Atomic keeps the Markdown produced so far and continues with the next transformer. The hook never changes the original message, session transcript, or model context. It runs for new messages, assistant streaming updates, restored session messages, and terminal-width changes, so keep transformers synchronous and fast. Isolated-engine rendering does not run host-side display transformers.
906
-
907
- <a id="pi-registershortcut-shortcut-options" />
908
-
909
556
  ### atomic.registerShortcut(shortcut, options)
910
557
 
911
- Register a keyboard shortcut. See [Keybindings](/keybindings) for the shortcut format and built-in keybindings.
558
+ Register a keyboard shortcut. See [Keybindings](/keybindings) for shortcut syntax.
912
559
 
913
560
  ```typescript
914
561
  atomic.registerShortcut("ctrl+shift+p", {
915
562
  description: "Toggle plan mode",
916
563
  handler: async (ctx) => {
917
- ctx.ui.notify("Toggled!");
564
+ ctx.ui.notify("Toggled!", "info");
918
565
  },
919
566
  });
920
567
  ```
921
568
 
922
- Set `preferEditor: true` to skip a shortcut when another resolved editor binding uses that key. Omitting it preserves the usual extension conflict policy. Optional `keybinding` selects the keys for an existing named action from `keybindings.json` instead of the literal registration key; an empty action binding disables it.
569
+ Conflict policy:
923
570
 
924
- <a id="pi-registerflag-name-options" />
571
+ - **17 reserved built-in actions cannot be overridden** (`app.interrupt`, `app.clear`, `app.exit`, `app.suspend`, `app.thinking.cycle`, `app.model.cycleForward`, `app.model.cycleBackward`, `app.model.select`, `app.tools.expand`, `app.thinking.toggle`, `app.editor.external`, `app.message.followUp`, `tui.input.submit`, `tui.select.confirm`, `tui.select.cancel`, `tui.input.copy`, `tui.editor.deleteToLineEnd`). Registering their keys skips with a warning.
572
+ - **Non-reserved built-in shortcuts** are overridden by extensions (with a warning) unless `preferEditor: true` is set, which yields to the editor binding.
573
+ - **Between two extensions**, the **last** registered shortcut wins (with a warning).
574
+ - Optional `keybinding` selects keys from an existing named action in `keybindings.json` instead of a hardcoded key; an empty action binding disables the shortcut.
925
575
 
926
- ### atomic.registerFlag(name, options)
576
+ ### atomic.registerFlag(name, options) / atomic.getFlag(name)
927
577
 
928
- Register a CLI flag.
578
+ Register and read a custom CLI flag (`type: "boolean" | "string"`):
929
579
 
930
580
  ```typescript
931
581
  atomic.registerFlag("plan", {
@@ -934,17 +584,22 @@ atomic.registerFlag("plan", {
934
584
  default: false,
935
585
  });
936
586
 
937
- // Check value
938
587
  if (atomic.getFlag("plan")) {
939
588
  // Plan mode enabled
940
589
  }
941
590
  ```
942
591
 
943
- <a id="pi-registeragentpanelsource-source" />
592
+ Flag rules:
593
+
594
+ - `default`, if supplied, must match `type` (`boolean` or `string`) or `registerFlag()` throws.
595
+ - Across extensions, the **first** extension registering a flag name wins.
596
+ - `atomic.getFlag(name)` reads **only** flags registered by that same extension; it returns `undefined` for other extensions' flags or built-in CLI flags.
597
+
598
+ <div id="pi-registeragentpanelsource-source" />
944
599
 
945
600
  ### atomic.registerAgentPanelSource(source)
946
601
 
947
- Add rows to the [agent panel](/background-tasks#the-agent-panel) below the prompt and to `/tasks`. The registration is released with the extension generation, and `/reload` re-registers it.
602
+ Add rows to the [agent panel](/background-tasks#the-agent-panel) below the prompt and to `/tasks`. Registrations are removed automatically when the extension reloads or the session closes.
948
603
 
949
604
  ```typescript
950
605
  import type { AgentPanelItem, ExtensionAPI } from "@bastani/atomic";
@@ -977,159 +632,114 @@ export default function (atomic: ExtensionAPI) {
977
632
  }
978
633
  ```
979
634
 
980
- Here `showDeploy` stands for your extension's own view of an item. `items()` synchronously returns the source's current `AgentPanelItem`s. Call the `subscribe` listener whenever they may have changed; the host reads `items()` again and repaints. Apply pending changes before taking the snapshot `items()` returns, or notify after returning; a listener call made while `items()` runs is honoured once.
981
-
982
- Keep `items()` and subscription callbacks short and synchronous. Compute `elapsedMs` when `items()` is called; Atomic advances a running row from that read until the next one and uses the reported value when it pauses or finishes. Publish a new change notification when that state changes.
983
-
984
- Return at most 10,000 rows per source. Atomic ignores additional rows and warns once per registration. A row with more than 128 choices is hidden; keep longer lists in the view opened by `open()`. Each item has:
635
+ Keep `items()` and `subscribe()` fast and synchronous. Return at most 10,000 rows per source (extra rows are ignored with one warning), and keep `choices` to 128 items or fewer.
985
636
 
986
637
  | Field | Meaning |
987
638
  | --- | --- |
988
- | `id` | Unique in the session. Prefix it with your source's name, for example `deploys:42`; `main` and the `task:` prefix are reserved. |
989
- | `kind` | `"agent"` or `"shell"`. It decides the row's layout. A `"shell"` item is listed in `/tasks` only; the main chat's footer counts it while it is not finished. |
990
- | `state` | `running`, `queued`, `input` (waits for an answer), `paused`, `stopping`, `waiting` (not working, and wakes by itself when what it waits on finishes), `done`, `failed` or `stopped`. It decides the glyph, the state word, the `/tasks` group and whether `x` stops or dismisses. |
991
- | `name`, `task` | The name and what it works on, for example `stage build`. |
992
- | `model`, `thinking` | Optional: the model the item runs on now, as `provider/model-id`, and its reasoning level, shown after its name as for a subagent. Leave `thinking` out for a model without reasoning levels. Update them when the item switches model. A value that is not a string is ignored. |
993
- | `elapsedMs`, `tokens` | Shown on the right. `elapsedMs` is finite, non-negative milliseconds. `tokens` is a non-negative safe integer, at most `Number.MAX_SAFE_INTEGER`. Between your updates, the panel and `/tasks` share the advancing time of running, waiting and stopping items. Paused and finished items keep their last elapsed time. |
994
- | `progress` | Finite, non-negative `{ done, total }` stages, drawn as a bar. |
995
- | `question`, `choices` | What an `input` item asks, and its numbered choices. |
996
- | `promptId` | Optional opaque identity of that pending question. Change it for each new question, even when its text and choices repeat. |
997
- | `reason` | A failed item's one-line reason. |
998
- | `waitingOn` | What a `waiting` item waits on, shown as `waiting on <waitingOn>`. |
999
- | `queued` | Messages typed to it that it has not taken yet. A non-negative safe integer. |
1000
- | `endedAt` | When a finished item finished, in finite, non-negative epoch milliseconds. |
1001
- | `runGeneration` | Optional opaque identity of the item's latest run. Use a per-item counter rather than a timestamp: two attempts can start in the same millisecond. Advance it whenever the item runs again (resumed, woken or sent a follow-up), not when the source republishes the same attempt. A `stopped` or `paused` row that left the panel is listed again while other work runs once this changes, even if it ran only briefly between two updates. Without it, such a row comes back only after the panel has seen it in another state. |
1002
-
1003
- Atomic strips terminal control sequences from the text fields before drawing them. An item with invalid fields is skipped, and `items()` or `subscribe` throwing is reported as an extension error. The source's other items, and the other sources, are still shown.
1004
-
1005
- The actions are optional:
1006
-
1007
- - `open(id, options)` runs on Enter or Right on the row. Return `false` (or throw) when the item cannot be opened; `/tasks` stays open and shows `Could not open <name>`, and the focused agent panel reports the same warning. A failed open does not mark the item viewed, and a throw is also reported as an extension error. When your view returns one level, call `options.onReturn()` so the panel or `/tasks` appears again.
1008
- - `stop(id)` runs on the second `x` for an unfinished item. Finished items are dismissed by the host without calling your source.
1009
- - `answer(id, text, options)` delivers a reply typed in an `input` item's `/tasks` peek card. Offer `question` and `answer` only for questions that typed text can answer. `options` carries the `promptId`, `question`, and `choices` shown when the reply started, plus a zero-based `choiceIndex` for numbered choices. Use `choiceIndex` after checking prompt identity and bounds rather than matching display labels, which may lose terminal controls or share text. An empty draft follows a newly shown question, whereas a nonempty draft keeps its original identity even after closing and reopening the card. Compare `options.promptId` against the current pending question and return `{ ok: false, reason }` when they differ so an earlier reply cannot answer a replacement question.
1010
-
1011
- `stop` and `answer` resolve to `{ ok: true }`, or `{ ok: false, reason }` to show `reason` to the user.
1012
-
1013
- The exported types from `@bastani/atomic` are `AgentPanelSource`, `AgentPanelItem`, `AgentPanelState`, `AgentPanelActionResult`, `AgentPanelOpenOptions`, `AgentPanelAnswerOptions`, `AgentPanelSourceRegistration`, and `AgentPanelSession`.
639
+ | `id` | Unique in the session (prefix with your source name; `main` and `task:` are reserved). |
640
+ | `kind` | `"agent"` or `"shell"` (`"shell"` appears in `/tasks` and main footer count only). |
641
+ | `state` | `running`, `queued`, `input`, `paused`, `stopping`, `waiting`, `done`, `failed`, or `stopped`. |
642
+ | `name`, `task` | Display name and active task description. |
643
+ | `model`, `thinking` | Optional `provider/model-id` string and reasoning level string. |
644
+ | `elapsedMs`, `tokens` | Finite non-negative milliseconds and safe integer token count. |
645
+ | `progress` | Finite non-negative `{ done, total }` stage progress bar. |
646
+ | `question`, `choices`, `promptId` | Prompt details for `input` items (change `promptId` for every new question). |
647
+ | `reason`, `waitingOn`, `queued`, `endedAt`, `runGeneration` | Failure summary, waiting label, queued message count, finish timestamp (epoch ms), and monotonic per-item run counter. |
1014
648
 
1015
- The same rows are also available outside extensions: `agentPanelItems(session)` returns the session's tasks and every source's items; `subscribeAgentPanel(session, listener)` notifies on any change (including after reload); `openAgentPanelItem`, `stopAgentPanelItem`, and `answerAgentPanelItem` run actions by item ID; `dismissedAgentPanelItems(session)` returns dismissed IDs; and `agentPanelTaskId(id)` returns the task ID of a `task:` item. Obtain the item from `agentPanelItems(session)` before acting on it, and pass the question's captured `AgentPanelAnswerOptions` to `answerAgentPanelItem()`.
649
+ Optional actions (`open`, `stop`, `answer`) return `{ ok: true }` or `{ ok: false, reason }` (for `open`, `false` keeps `/tasks` open and shows `Could not open <name>`). Check `options.promptId` and `options.choiceIndex` in `answer()` rather than matching display labels.
1016
650
 
1017
- <a id="pi-exec-command-args-options" />
651
+ Exported types and standalone helpers: `AgentPanelSource`, `AgentPanelItem`, `AgentPanelState`, `AgentPanelActionResult`, `AgentPanelOpenOptions`, `AgentPanelAnswerOptions`, `AgentPanelSourceRegistration`, `AgentPanelSession`, `agentPanelItems(session)`, `subscribeAgentPanel(session, listener)`, `openAgentPanelItem`, `stopAgentPanelItem`, `answerAgentPanelItem`, `dismissedAgentPanelItems(session)`, and `agentPanelTaskId(id)`.
1018
652
 
1019
653
  ### atomic.exec(command, args, options?)
1020
654
 
1021
- Execute a command without a shell.
655
+ Execute a command directly without a shell:
1022
656
 
1023
657
  ```typescript
1024
658
  const result = await atomic.exec("git", ["status"], { signal, timeout: 5000 });
1025
659
  // result.stdout, result.stderr, result.code, result.killed, result.truncated
1026
660
  ```
1027
661
 
1028
- On Windows, a bare `command` without a path (such as `git`) runs only from absolute directories on `PATH`, never from the working directory or Atomic's own directory, so a project folder cannot shadow it. A `command` with a path (such as `.\tools\build.exe`) runs as written.
1029
-
1030
- Options include `signal`, `timeout`, `cwd`, and `maxBuffer` (default 256 MiB for combined stdout and stderr). Exceeding `maxBuffer` terminates the command and returns the output captured so far with `truncated: true`, `killed: true`, and a nonzero `code`. `killed` is `true` whenever Atomic terminates the command (timeout, abort, `maxBuffer`, or quitting the interactive app). A command terminated by a signal reports `128 + signal` as `code`, matching shell conventions (`143` for `SIGTERM`, `137` for `SIGKILL`).
1031
-
1032
- Process-tree termination rules:
1033
-
1034
- - **Timeout, abort, or `maxBuffer`.** Atomic terminates the command and child processes it started. On Linux and macOS, the command and its process group receive `SIGTERM`, followed by `SIGKILL` 5 seconds later; processes that started their own session (`setsid`) keep running. On Windows, descendant processes end immediately before the command itself (descendants whose parent already exited cannot be found).
1035
- - **Quitting the interactive app.** Running commands and their process groups receive `SIGTERM` followed by `SIGKILL` after 1 second (immediate termination on Windows) so they cannot delay `session_shutdown` handlers. Commands started inside a `session_shutdown` handler are not terminated this way. Print mode and SDK `dispose()` wait for running commands instead.
1036
- - **Forced exit (`SIGKILL` to Atomic).** The interactive engine kills running commands and their process groups with `SIGKILL`. On Linux, the OS also ends direct child commands (though not their descendants) when the owning Atomic process exits. On macOS, a command running in Atomic's own process keeps running. On Windows, the command ends with Atomic, while its children keep running unless the command placed them in its own job object (as Node.js commands do).
1037
-
1038
- <a id="pi-getactivetools-/-pi-getalltools-/-pi-setactivetools-names" />
662
+ - On Windows, bare command names (like `git`) resolve only from absolute directories on `PATH`, never from `cwd` or Atomic's own directory.
663
+ - Options: `signal`, `timeout`, `cwd`, `maxBuffer` (default 256 MiB combined stdout/stderr). Exceeding `maxBuffer` kills the process and sets `truncated: true`, `killed: true`, and nonzero `code`. Signal terminations report `128 + signal`.
664
+ - On timeout, abort, or `maxBuffer`: terminates the process tree (`SIGTERM`, then `SIGKILL` after 5 s on Unix; immediate descendant termination on Windows).
665
+ - On interactive quit: kills running commands after 1 s (`SIGTERM` then `SIGKILL` on Unix; immediate on Windows) before `session_shutdown` runs; commands started inside `session_shutdown` are not killed this way. On forced `SIGKILL` to Atomic, running interactive commands and their process groups receive `SIGKILL`.
1039
666
 
1040
667
  ### atomic.getActiveTools() / atomic.getAllTools() / atomic.setActiveTools(names)
1041
668
 
1042
- Manage active tools. This works for both built-in tools and dynamically registered tools. `atomic.getActiveTools()` returns the active tool names as `string[]`; `atomic.getAllTools()` returns metadata for all configured tools.
669
+ Inspect or change the active tool list (including dynamically registered tools and Intercom; tools excluded by a session allowlist or exclusions cannot be activated):
1043
670
 
1044
671
  ```typescript
1045
- const active = atomic.getActiveTools(); // ["read", "bash", ...]
672
+ const active = atomic.getActiveTools();
1046
673
  const all = atomic.getAllTools();
1047
- // all = [{
1048
- // name: "read",
1049
- // description: "Read file contents...",
1050
- // parameters: ...,
1051
- // promptGuidelines: ["Use read to examine files instead of cat or sed."],
1052
- // sourceInfo: { path: "<builtin:read>", source: "builtin", scope: "temporary", origin: "top-level" }
1053
- // }, ...]
1054
- const builtinTools = all.filter((t) => t.sourceInfo.source === "builtin");
1055
- const extensionTools = all.filter((t) => t.sourceInfo.source !== "builtin" && t.sourceInfo.source !== "sdk");
1056
- atomic.setActiveTools([...new Set([...active, "my_custom_tool"])]); // Keep current tools and enable my_custom_tool
1057
- atomic.setActiveTools(["read", "bash"]); // Switch to read-only
674
+ atomic.setActiveTools([...new Set([...active, "my_custom_tool"])]);
1058
675
  ```
1059
676
 
1060
- `atomic.getAllTools()` returns `name`, `description`, `parameters`, `promptGuidelines`, `exposure`, `namespace`, `annotations`, and `sourceInfo`. `explicitDefaultOptOut: true` means a `-name` modifier explicitly removed that tool from the defaults; respect it when considering automatic activation. See [tool exposure](/extensions/authoring#tool-exposure) before changing activation for script-callable tools.
1061
-
1062
- Typical `sourceInfo.source` values:
1063
- - `builtin` for built-in tools
1064
- - `sdk` for tools passed via `createAgentSession({ customTools })`
1065
- - extension source metadata for tools registered by extensions
1066
-
1067
- <a id="pi-setmodel-model" />
677
+ Each entry from `atomic.getAllTools()` includes `name`, `description`, `parameters`, `promptGuidelines`, `exposure`, `namespace`, `annotations`, `constrainedSampling`, `explicitDefaultOptOut`, and `sourceInfo` (`source: "builtin" | "sdk" | ...`). Respect `explicitDefaultOptOut: true` before re-enabling a tool automatically. See [Tool exposure](/extensions/authoring#tool-exposure).
1068
678
 
1069
679
  ### atomic.setModel(model)
1070
680
 
1071
- Set the model for the current session. The change is recorded in session history and restored when that session is resumed, but it does not change the configured `defaultProvider` or `defaultModel` used by new sessions. Returns `false` if authentication is not configured for the model's provider. See [Custom models](/models) for configuring custom models.
1072
-
1073
- ```typescript
1074
- const model = ctx.modelRegistry.find("anthropic", "claude-sonnet-4-5");
1075
- if (model) {
1076
- const success = await atomic.setModel(model);
1077
- if (!success) {
1078
- ctx.ui.notify("No API key for this model", "error");
1079
- }
1080
- }
1081
- ```
1082
-
1083
- <a id="pi-getthinkinglevel-/-pi-setthinkinglevel-level" />
681
+ Set the active model for the current session (recorded in session history; does not modify `defaultProvider` or `defaultModel` in settings). Returns `false` if the provider lacks credentials.
1084
682
 
1085
683
  ### atomic.getThinkingLevel() / atomic.setThinkingLevel(level)
1086
684
 
1087
- Get the current thinking level. Level is clamped to model capabilities (non-reasoning models always use `"off"`; `"xhigh"` and `"max"` require model support). Changes emit `thinking_level_select`.
1088
-
1089
- `atomic.setThinkingLevel()` changes the thinking level for the current session. The change is recorded in session history and restored when that session is resumed, but it does not change the configured default used by new sessions.
1090
-
1091
- ```typescript
1092
- const current = atomic.getThinkingLevel(); // "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"
1093
- await atomic.setThinkingLevel("high");
1094
- ```
1095
-
1096
- <a id="pi-events" />
685
+ Get or set the session's thinking level (`"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"`), clamped to model capabilities. Changes emit `thinking_level_select`.
1097
686
 
1098
687
  ### atomic.events
1099
688
 
1100
- Shared event bus for communication between active extensions. A subscription made with `on()` is removed automatically when its extension reloads or the session disposes. Use the returned function if you need to stop listening sooner:
689
+ Shared event bus between active extensions in the same session. Subscriptions created with `atomic.events.on()` are cleaned up automatically on reload or disposal and return an unsubscribe function:
1101
690
 
1102
691
  ```typescript
1103
- const unsubscribe = atomic.events.on("my:event", (data) => { ... });
1104
- atomic.events.emit("my:event", { ... });
692
+ const unsubscribe = atomic.events.on("my:event", (data) => { /* ... */ });
693
+ atomic.events.emit("my:event", { ok: true });
1105
694
  unsubscribe();
1106
695
  ```
1107
696
 
1108
- `atomic.events` belongs to the extension instance that received it. Register listeners again when that instance reloads, and do not retain the object for later use: calling `on()` or `emit()` through a captured handle after reload or disposal throws. To keep in-memory state across `/reload`, pass this facade to [`sessionScopedExtensionState`](/extensions/authoring#session-scoped-in-memory-state); do not capture the facade itself.
1109
-
1110
- If you implement an `ExtensionRuntime` for an embedded host, provide `trackEventBusSubscription(unsubscribe)` and retain each returned subscription until that extension runtime is reloaded or disposed. `ExtensionUIContext.getChatRenderSettings()` must return `markdownTransformers`; it may also return `renderLatex` to control terminal math rendering, and `fullscreenScrollbar` and `fullscreenWheelScrollLines` for transcripts that an overlay scrolls itself. These fields keep event subscriptions and display transforms scoped to the active extension instance.
697
+ Do not retain `atomic.events` across `/reload` (calling `on()` or `emit()` on a retired handle throws). Pass `atomic.events` to [`sessionScopedExtensionState`](/extensions/authoring#session-scoped-in-memory-state) to preserve in-memory state across reloads.
1111
698
 
699
+ Embedded hosts implementing `ExtensionRuntime` must implement `trackEventBusSubscription(unsubscribe)` and return `markdownTransformers` (plus optional `renderLatex`, `fullscreenScrollbar`, `fullscreenWheelScrollLines`) from `ExtensionUIContext.getChatRenderSettings()`. See [SDK extensions](/sdk/reference#extensions).
1112
700
 
1113
701
  ### Native providers
1114
702
 
1115
- In addition to `registerProvider(name, config)`, extensions can register a complete native `Provider` from `@bastani/atomic-ai` with `atomic.registerProvider(provider)`. Use the native overload for provider-owned authentication, catalog refresh, and transport behavior; use the config overload for ordinary proxies and custom endpoints.
703
+ Pass a complete native `Provider` from `@bastani/atomic-ai` to `await atomic.registerProvider(provider)` when you need provider-owned API-key login flows, custom transport, or native catalog refresh:
1116
704
 
1117
- <a id="pi-registerprovider-name-config" />
705
+ ```typescript
706
+ import type { Provider } from "@bastani/atomic-ai";
1118
707
 
1119
- ### atomic.registerProvider(name, config)
708
+ const localServerProvider: Provider = {
709
+ id: "local-server",
710
+ name: "Local Server",
711
+ auth: {
712
+ apiKey: {
713
+ name: "Local server connection",
714
+ async login({ signal, prompt }) {
715
+ const baseUrl = await prompt({
716
+ type: "text",
717
+ message: "Server URL",
718
+ placeholder: "http://localhost:9931",
719
+ });
720
+ if (signal.aborted) throw new Error("Login cancelled");
721
+ return { type: "api_key", env: { LOCAL_SERVER_URL: baseUrl } };
722
+ },
723
+ },
724
+ },
725
+ // ...models and transport methods
726
+ };
727
+
728
+ await atomic.registerProvider(localServerProvider);
729
+ ```
1120
730
 
1121
- Register or override a model provider dynamically. Await registration, aliases, and removal before starting dependent work. Use this for proxies, custom endpoints, or team-wide model configurations.
731
+ Provider-owned `auth.apiKey` (`{ name, login, check?, resolve? }`) is supported **only** on native `Provider` objects passed to single-argument `atomic.registerProvider(provider)`, not on two-argument `ProviderConfig`. Providers registered in interactive extensions appear in `/login`; their callbacks run in the extension worker while prompts render in the terminal.
1122
732
 
1123
- Calls made during the extension factory function are queued and applied once the runner initializes. Calls made afterward (for example from a command handler after a setup flow) take effect immediately without `/reload`.
733
+ ### atomic.registerProvider(name, config)
1124
734
 
1125
- If you need to discover models from a remote endpoint, prefer an async extension factory over deferring the fetch to `session_start`. Atomic waits for the factory before startup continues, so the registered models are available immediately, including to `atomic --list-models`.
735
+ Register or override a provider dynamically using a `ProviderConfig` object (for proxies, custom endpoints, OAuth flows, or custom models). Await registration, aliases, and unregistration before dependent work. Calls during an async factory complete before startup continues and appear in `atomic --list-models`; calls afterward take effect immediately without `/reload`.
1126
736
 
1127
737
  ```typescript
1128
738
  // Register a new provider with custom models
1129
739
  await atomic.registerProvider("my-proxy", {
1130
740
  name: "My Proxy",
1131
741
  baseUrl: "https://proxy.example.com",
1132
- apiKey: "$PROXY_API_KEY", // env var reference; omit $ for a literal
742
+ apiKey: "$PROXY_API_KEY",
1133
743
  api: "anthropic-messages",
1134
744
  models: [
1135
745
  {
@@ -1139,134 +749,115 @@ await atomic.registerProvider("my-proxy", {
1139
749
  input: ["text", "image"],
1140
750
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1141
751
  contextWindow: 200000,
1142
- maxTokens: 16384
1143
- }
1144
- ]
752
+ maxTokens: 16384,
753
+ },
754
+ ],
1145
755
  });
1146
756
 
1147
- // Override baseUrl for an existing provider (keeps all models)
757
+ // Override baseUrl for an existing provider (keeps existing models)
1148
758
  await atomic.registerProvider("anthropic", {
1149
- baseUrl: "https://proxy.example.com"
759
+ baseUrl: "https://proxy.example.com",
1150
760
  });
1151
761
 
1152
- // Register provider with OAuth support for /login
762
+ // Register a provider with OAuth login
1153
763
  await atomic.registerProvider("corporate-ai", {
1154
764
  baseUrl: "https://ai.corp.com",
1155
765
  api: "openai-responses",
1156
766
  models: [...],
1157
767
  oauth: {
1158
768
  name: "Corporate AI (SSO)",
769
+ loginLabel: "Sign in with SSO",
770
+ usesCallbackServer: false,
1159
771
  async login(callbacks, signal) {
1160
- // Custom OAuth flow
1161
772
  callbacks.onAuth({ url: "https://sso.corp.com/..." });
1162
773
  const code = await callbacks.onPrompt({ message: "Enter code:" });
1163
774
  signal.throwIfAborted();
1164
775
  return { refresh: code, access: code, expires: Date.now() + 3600000 };
1165
776
  },
1166
777
  async refreshToken(credentials, signal) {
1167
- // Pass `signal` through, but add no timeout or abort of your own (see below).
778
+ // Throw OAuthRefreshRejectedError on permanent rejection (for example invalid_grant)
1168
779
  return refreshCorporateToken(credentials.refresh, { signal });
1169
780
  },
1170
781
  getApiKey(credentials) {
1171
782
  return credentials.access;
1172
- }
1173
- }
1174
- });
1175
-
1176
- // Register provider-owned API-key setup for /login
1177
- await atomic.registerProvider("local-server", {
1178
- name: "Local Server",
1179
- auth: {
1180
- apiKey: {
1181
- name: "Local server connection",
1182
- async login({ signal, prompt }) {
1183
- const baseUrl = await prompt({
1184
- type: "text",
1185
- message: "Server URL",
1186
- placeholder: "http://localhost:9931"
1187
- });
1188
- if (signal.aborted) throw new Error("Login cancelled");
1189
- return { type: "api_key", env: { LOCAL_SERVER_URL: baseUrl } };
1190
- }
1191
- }
1192
- }
783
+ },
784
+ },
1193
785
  });
1194
786
  ```
1195
787
 
1196
- OAuth `refreshToken` receives a signal that Atomic does not abort on a timeout because the provider may have already rotated the refresh token once the request is sent. The caller stops waiting after 60 seconds, while the exchange keeps running and saves its result when it arrives.
788
+ `ProviderConfig` options:
1197
789
 
1198
- On normal exit, Atomic waits up to 3 seconds for an exchange still in flight, and cancelling a request or model refresh stops only that caller's wait. Do not add your own timeout or abort to the token request, and do not send the same refresh token twice after the provider may have received it. Always return the rotated credentials even if the initiating caller stopped waiting.
790
+ - `name`: display name in UI such as `/login`.
791
+ - `aliasOf`: ID of an existing provider to alias.
792
+ - `baseUrl`: API endpoint URL (required when defining models).
793
+ - `apiKey`: literal key or environment variable reference (`$ENV_VAR` or `${ENV_VAR}`; required when defining models unless `oauth` is set).
794
+ - `api`: API protocol (`"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc.).
795
+ - `headers`, `authHeader`: extra headers, or `authHeader: true` to send `Authorization: Bearer`.
796
+ - `models`: array of `ProviderModelConfig` entries (`type?: "chat" | "image" | "classifier"`, defaulting to `"chat"`). Chat models support `reasoning`, `thinkingLevelMap`, `contextWindow`, `maxTokens`, `samplingParams`, `samplingParamsByThinkingLevel`, `promptCache`, and `compat`; image models support `output` and `capabilities`; classifier models support `contextWindow` and `compat`. Individual models may set `baseUrl`.
797
+ - `refreshModels?(context)`: dynamically refresh the provider's model catalog (replaces extension-provided models on success).
798
+ - `images`, `classifiers`: custom image or classifier API handlers keyed by API name.
799
+ - `streamSimple`: custom streaming implementation for non-standard APIs.
800
+ - `oauth`: OAuth configuration with `name`, optional `loginLabel`, optional `usesCallbackServer`, `login(callbacks, signal)`, `refreshToken(credentials, signal)`, `getApiKey(credentials)`, and optional `modifyModels(models, credentials)`.
1199
801
 
1200
- Config options:
802
+ **OAuth refresh contract:** Atomic does not abort the `refreshToken` `signal` on timeout because a provider may already have rotated the refresh token once sent. Callers stop waiting after 60 seconds while the exchange keeps running and saves rotated credentials when done (on normal exit, Atomic waits up to 3 seconds). Do not add your own timeout or retry a rotated refresh token. If the provider permanently rejects the login (such as `invalid_grant`), throw `OAuthRefreshRejectedError` (exported from `@bastani/atomic`) so Atomic instructs the user to run `/login <provider>`.
1201
803
 
1202
- - `name`. Display name for the provider in UI such as `/login`.
1203
- - `baseUrl`. API endpoint URL. Required when defining models.
1204
- - `apiKey`. API key literal or explicit environment variable reference (`$ENV_VAR` or `${ENV_VAR}`). Required when defining models unless `oauth` is provided.
1205
- - `api`. API type such as `"anthropic-messages"`, `"openai-completions"`, or `"openai-responses"`.
1206
- - `headers`. Custom headers to include in requests.
1207
- - `authHeader`. When `true`, adds an `Authorization: Bearer` header automatically.
1208
- - `models`. Array of model definitions; replaces all existing models for this provider. Individual model definitions can set `baseUrl` to override the provider endpoint.
1209
- - `oauth`. OAuth provider config for `/login` support.
1210
- - `auth.apiKey`. Provider-owned API-key or connection setup for `/login`. Its `name` appears in the provider list, and `login({ signal, prompt })` returns the credential Atomic persists. Providers registered in the isolated interactive engine child sync into the host's `/login` list; their callbacks run in the child while prompts render in the terminal host.
1211
- - `streamSimple`. Custom streaming implementation for non-standard APIs.
1212
-
1213
- See [Custom providers](/custom-provider) for custom streaming APIs, OAuth details, and the model definition reference.
1214
-
1215
- <a id="pi-unregisterprovider-name" />
1216
-
1217
- ### atomic.unregisterProvider(name)
804
+ See [Custom providers](/custom-provider) for full details.
1218
805
 
1219
- Remove a previously registered provider and its models. Built-in models that were overridden by the provider are restored. Calling this for an unregistered name is a no-op.
806
+ ### atomic.registerProviderAlias(config)
1220
807
 
1221
- Like `registerProvider`, this takes effect immediately after the initial load phase without requiring `/reload`.
808
+ Register an alias pointing to an existing provider (for example, multiple accounts on the same provider). Returns `Promise<void>`:
1222
809
 
1223
810
  ```typescript
1224
- atomic.registerCommand("my-setup-teardown", {
1225
- description: "Remove the custom proxy provider",
1226
- handler: async (_args, _ctx) => {
1227
- await atomic.unregisterProvider("my-proxy");
1228
- },
811
+ await atomic.registerProviderAlias({
812
+ id: "openai-work",
813
+ name: "OpenAI (Work)",
814
+ provider: "openai",
1229
815
  });
1230
816
  ```
1231
817
 
1232
- <a id="pi-registermcpserver-name-config" />
818
+ See [examples/extensions/provider-accounts.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/provider-accounts.ts).
819
+
820
+ ### atomic.unregisterProvider(name)
1233
821
 
1234
- ### atomic.registerMcpServer(name, config)
822
+ Remove a previously registered provider and its models, restoring any built-in models it overrode. No-op for unknown names. Takes effect immediately without `/reload`.
1235
823
 
1236
- Contribute an MCP server whose configuration is computed at runtime, such as the URL of a local service the extension starts. `config` uses the same schema as an entry in [`mcp.json`](/mcp-servers#configure-servers), including `url`, `command`, `args`, `env`, `cwd`, `headers`, OAuth settings, `exposure`, and per-request `timeout` in seconds. URLs support `${VAR}` and `$env:VAR` interpolation.
824
+ ### atomic.registerMcpServer(name, config) {#atomic-registermcpserver-name-config}
825
+
826
+ Contribute an MCP server whose configuration is computed at runtime (for example, a dynamically bound local port). `name` must match `^[A-Za-z0-9_-]+$`, and `config` follows the [`mcp.json`](/mcp-servers#configure-servers) schema (`url`, `command`, `args`, `env`, `cwd`, `headers`, OAuth settings, `exposure`, positive `timeout` in seconds, `${VAR}` / `$env:VAR` URL interpolation). `type: "sse"` is rejected (use streamable HTTP).
1237
827
 
1238
828
  ```typescript
1239
829
  export default function (atomic: ExtensionAPI) {
1240
830
  atomic.on("session_start", async () => {
1241
831
  const port = await startLocalService();
1242
- atomic.registerMcpServer("local-service", { url: `http://127.0.0.1:${port}/mcp`, exposure: "direct" });
832
+ atomic.registerMcpServer("local-service", {
833
+ url: `http://127.0.0.1:${port}/mcp`,
834
+ exposure: "direct",
835
+ });
1243
836
  });
1244
837
  }
1245
838
  ```
1246
839
 
1247
- Call `atomic.registerMcpServer()` from the extension factory or from `session_start`. Load order does not matter: registrations made after the MCP adapter has started connect without a reload, and registering the same name again replaces the earlier registration.
840
+ Call from the extension factory or `session_start`; servers connect immediately without `/reload`, and re-registering the same name replaces the previous registration. Extension-registered servers override package-manifest servers while user and trusted-project `mcp.json` entries take precedence over both (set `"enabled": false` on a file-configured entry to disable it).
1248
841
 
1249
- Registered servers connect like file-configured servers and appear in `/mcp` with the registering extension as their source. They replace a same-named server from a package manifest, while user or trusted-project `mcp.json` entries take precedence over them. Set `"enabled": false` on a complete file-configured entry to keep it without connecting.
1250
-
1251
- Enabled-state and exposure changes to extension-registered servers apply only to the current session and are not saved to `mcp.json`. Shell `atomic mcp` commands do not load extensions. Provider-token authentication (`auth.provider`) is allowed for extension registrations and global configuration, not project configuration or package manifests.
1252
-
1253
- `atomic.getMcpServerContributions()` returns the package-manifest and registered servers for the session, each with its `name`, `config`, `origin` (`"package"` or `"extension"`), and `sourceInfo`.
842
+ `auth.provider` is allowed on extension-registered servers (requiring HTTPS or a loopback URL) and global `mcp.json`, not project config or package manifests. Shell `atomic mcp` commands do not load extensions. Call `atomic.getMcpServerContributions()` to inspect all package and extension server contributions.
1254
843
 
1255
844
  ## Error handling
1256
845
 
1257
- - Extension errors are logged and the agent continues.
1258
- - In the interactive terminal, a `session_start` or `resources_discover` handler that throws during startup, `-c` or `--resume`, `/new`, `/resume`, `/fork`, or `/reload` is shown once with the extension's path and error, and the session keeps working. The extension stays loaded, so its commands, tools, and other handlers still run. Print mode (`-p`), standalone RPC mode (`--mode rpc`), and SDK sessions instead fail startup with `ExtensionStartupError`, which names each failing extension.
1259
- - `tool_call` errors block the tool (fail-safe).
1260
- - Tool `execute` errors must be signaled by throwing; Atomic catches the error, reports it to the LLM with `isError: true`, and continues execution.
846
+ - Uncaught errors in most event handlers are logged and the session continues.
847
+ - In interactive mode, an error thrown in `session_start` or `resources_discover` is shown once with the extension's path and error while keeping the session open and the extension loaded. In print mode (`-p`), standalone RPC mode (`--mode rpc`), and SDK sessions, startup fails with `ExtensionStartupError` naming each failing extension.
848
+ - If a `tool_call` handler throws an error, Atomic blocks the tool call and reports the error to the model instead of running the tool.
849
+ - Inside tool `execute()`, throw an `Error` to report failure; Atomic catches it, sends it to the model with `isError: true`, and continues.
1261
850
 
1262
851
  ### Typed errors from built-in tools and providers
1263
852
 
1264
- These classes are exported from `@bastani/atomic`. Branch on the class, its guard, or `code`, not on `message`. Each error has `hint` (what to do next), `retryable`, and `toJSON()`, which returns `{ name, code, message, hint, retryable, fields, cause }` for relaying across a process boundary.
1265
-
1266
- Use `rehydrateShellToolError()` and `rehydrateLlamaServerError()` to rebuild the same class on the receiving side. Type guards (`isShellTimeoutError()`, `isLlamaServerError()`, and related guards) accept relayed errors directly. User names and passwords in URLs are stripped from `detail`, `message`, and serialized causes. `isRetryableLlamaServerError()` checks retryability by `code` through the error and its cause chain, including relayed errors.
1267
-
1268
- | Class | `code` | When | Fields | What to do |
1269
- | --- | --- | --- | --- | --- |
1270
- | `ShellTimeoutError` (family `ShellToolError`) | `shell-timeout` | The local shell backend of `createLocalBashOperations()` hit the command's timeout. `phase` is `draining-output` when the shell had already exited and background processes it started kept output open; `shellExit` then holds the shell's exit code. | `timeoutMs`, `elapsedMs`, `phase`, `shellExit` | Redirect background output or raise `timeout`. Its `message` stays `timeout:<seconds>`, matching custom `BashOperations`. |
1271
- | `LlamaServerUnreachableError` (family `LlamaServerError`) | `server-unreachable` | A `llama.cpp` router request failed before the server answered (connection refused, nothing listening on the port, DNS failure, or `https` against a plain-HTTP server). Cancellation and the request timeout are rethrown unchanged. | `serverUrl` (without user information), `detail` (the network-level reason) | Start `llama serve`, or fix the URL with `/login llama.cpp` or `LLAMA_BASE_URL`. `retryable` is `true`. |
1272
- | `LlamaServerRequestError` (family `LlamaServerError`) | `request-rejected` | The runtime refused to send a `llama.cpp` router request, so the server was never contacted (for example Node's `fetch` rejecting a URL with credentials or a blocked port such as `6000`). | `serverUrl` (without user information), `detail` (the runtime's reason, URL credentials removed) | Use a plain `http` or `https` URL without credentials (pass an API key separately) on a port `fetch` allows. `retryable` is `false`. |
853
+ These error classes and type guards are exported from `@bastani/atomic` (see [Session and storage errors](/sdk/reference#session-and-storage-errors) for session, storage, and startup errors). Branch on the class, its type guard, or `code` rather than `message`. Each tool/provider error includes `hint`, `retryable`, and `toJSON()` for cross-process serialization (credentials in URLs are stripped). Use `rehydrateShellToolError()` and `rehydrateLlamaServerError()` to rebuild serialized instances.
854
+
855
+ | Class | `code` | When | Key fields / notes |
856
+ | --- | --- | --- | --- |
857
+ | `ShellTimeoutError` (`ShellToolError`) | `shell-timeout` | `createLocalBashOperations()` hit the command timeout (`phase: "draining-output"` means the shell exited while background children kept stdout/stderr open). | `timeoutMs`, `elapsedMs`, `phase`, `shellExit`. Redirect background output or increase `timeout`. |
858
+ | `LlamaServerUnreachableError` (`LlamaServerError`) | `server-unreachable` | A `llama.cpp` router request failed before any response (connection refused, DNS error, TLS mismatch). | `serverUrl`, `detail`; `retryable: true`. Start `llama serve` or fix URL with `/login llama.cpp` / `LLAMA_BASE_URL`. |
859
+ | `LlamaServerRequestError` (`LlamaServerError`) | `request-rejected` | The runtime refused to send a `llama.cpp` request (credentials in URL or blocked port such as `6000`). | `serverUrl`, `detail`; `retryable: false`. Use a plain `http`/`https` URL without embedded credentials. |
860
+ | `OAuthRefreshRejectedError` | *(OAuth refresh)* | Thrown by an extension's `oauth.refreshToken()` when the provider permanently rejects stored credentials (such as `invalid_grant`). | Prompts the user to re-authenticate with `/login <provider>`. |
861
+ | `DecisionModelUnavailableError` | *(decision model)* | `ctx.getDecisionModel()` called in a host without decision-model support (`reason: "host-unsupported"`). | Check host support or handle gracefully before invoking decision helpers. |
862
+ | `NativeModuleUnavailableError` | *(native addon)* | Optional native N-API bindings (`@bastani/atomic-natives`) are unavailable on the host runtime. | Exported from `@bastani/atomic` for callers checking native-module fallbacks. |
863
+ | `MissingSessionCwdError` | `session-cwd-missing` | `ctx.switchSession()` targeted a session whose recorded working directory no longer exists. | Guard with `isMissingSessionCwdError(error)`. |