@bastani/atomic 0.10.9 → 0.10.10-alpha.1

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 (401) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +211 -155
  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} +145 -58
  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 +85 -114
  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 +37 -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 +71 -138
  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 +60 -87
  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 +235 -243
  297. package/docs/build.md +12 -11
  298. package/docs/codemode.md +60 -51
  299. package/docs/compaction/reference.md +61 -24
  300. package/docs/compaction.md +117 -65
  301. package/docs/computer-use.md +179 -146
  302. package/docs/containerization.md +79 -33
  303. package/docs/custom-provider/api-reference.md +148 -11
  304. package/docs/custom-provider/oauth.md +44 -27
  305. package/docs/custom-provider/override.md +14 -7
  306. package/docs/custom-provider/registration.md +75 -65
  307. package/docs/custom-provider/streaming.md +42 -19
  308. package/docs/custom-provider.md +25 -61
  309. package/docs/development.md +47 -43
  310. package/docs/docs.json +33 -33
  311. package/docs/environment-variables.md +83 -57
  312. package/docs/extensions/api-reference.md +323 -734
  313. package/docs/extensions/authoring.md +186 -269
  314. package/docs/extensions/events.md +308 -375
  315. package/docs/extensions/examples.md +122 -74
  316. package/docs/extensions/ui.md +217 -197
  317. package/docs/extensions.md +152 -259
  318. package/docs/getting-started/authentication.md +27 -14
  319. package/docs/getting-started/first-session.md +25 -26
  320. package/docs/getting-started/installation.md +62 -84
  321. package/docs/getting-started/project-instructions.md +39 -14
  322. package/docs/guides/configuration.md +42 -20
  323. package/docs/guides/intercom.md +17 -13
  324. package/docs/guides/non-interactive.md +29 -16
  325. package/docs/guides/orchestration.md +16 -10
  326. package/docs/guides/resume-on-any-machine.md +54 -49
  327. package/docs/guides/subagents.md +22 -14
  328. package/docs/guides/team-setup.md +37 -26
  329. package/docs/guides.md +22 -21
  330. package/docs/herdr.md +21 -16
  331. package/docs/index.md +16 -17
  332. package/docs/intercom/operations.md +68 -66
  333. package/docs/intercom/reference.md +196 -191
  334. package/docs/intercom.md +103 -92
  335. package/docs/json.md +71 -71
  336. package/docs/keybindings.md +63 -50
  337. package/docs/libraries/agent-core.md +49 -8
  338. package/docs/libraries/ai.md +21 -12
  339. package/docs/libraries/codemode.md +28 -6
  340. package/docs/libraries/schema.md +7 -7
  341. package/docs/libraries/telemetry.md +7 -7
  342. package/docs/libraries/tui.md +74 -94
  343. package/docs/libraries.md +5 -5
  344. package/docs/llama-cpp.md +38 -33
  345. package/docs/mcp-servers.md +96 -90
  346. package/docs/models/reference.md +46 -33
  347. package/docs/models-configuration.md +12 -6
  348. package/docs/models.md +93 -88
  349. package/docs/orchestration/migrating-workflows.md +21 -19
  350. package/docs/orchestration/patterns.md +35 -20
  351. package/docs/orchestration.md +22 -21
  352. package/docs/packages/authoring.md +28 -19
  353. package/docs/packages/reference.md +75 -16
  354. package/docs/packages.md +31 -33
  355. package/docs/programmatic.md +22 -21
  356. package/docs/prompt-templates.md +63 -41
  357. package/docs/providers/reference.md +35 -19
  358. package/docs/providers.md +61 -71
  359. package/docs/quickstart.md +32 -46
  360. package/docs/reference/cli.md +249 -252
  361. package/docs/reference.md +23 -20
  362. package/docs/rpc/examples.md +74 -17
  363. package/docs/rpc/extension-ui.md +79 -62
  364. package/docs/rpc/protocol.md +816 -358
  365. package/docs/rpc.md +75 -151
  366. package/docs/sdk/reference.md +175 -45
  367. package/docs/sdk/structured-decisions.md +92 -62
  368. package/docs/sdk/web-server.md +79 -46
  369. package/docs/sdk.md +237 -195
  370. package/docs/security.md +106 -43
  371. package/docs/session-format.md +96 -59
  372. package/docs/sessions.md +149 -113
  373. package/docs/settings.md +289 -204
  374. package/docs/shell-aliases.md +15 -6
  375. package/docs/skills/authoring.md +17 -9
  376. package/docs/skills/reference.md +23 -21
  377. package/docs/skills.md +104 -97
  378. package/docs/storage.md +140 -242
  379. package/docs/subagents/authoring.md +147 -16
  380. package/docs/subagents/reference.md +100 -30
  381. package/docs/subagents.md +220 -252
  382. package/docs/terminal-setup.md +97 -69
  383. package/docs/termux.md +51 -85
  384. package/docs/themes/reference.md +51 -37
  385. package/docs/themes.md +49 -54
  386. package/docs/tmux.md +38 -21
  387. package/docs/tools.md +198 -147
  388. package/docs/tui/reference.md +64 -32
  389. package/docs/tui.md +38 -66
  390. package/docs/usage.md +76 -78
  391. package/docs/verification.md +25 -25
  392. package/docs/web-access.md +72 -55
  393. package/docs/windows.md +53 -58
  394. package/docs/worktree-snapshots.md +62 -65
  395. package/package.json +8 -8
  396. package/schemas/models.schema.json +51 -0
  397. package/dist/_shared/sdk-OSBEPR3Q.js.map +0 -1
  398. package/dist/_shared/startup-0-0-TYUFUOJZ.js.map +0 -1
  399. package/dist/_shared/startup-0-1-W2G2UY7R.js.map +0 -1
  400. package/dist/_shared/startup-0-2-UXBUEOXW.js.map +0 -1
  401. package/dist/_shared/startup-0-4-HN5EB4K7.js.map +0 -1
@@ -1,34 +1,40 @@
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
8
-
9
7
  ## ExtensionContext
10
8
 
11
- All handlers receive `ctx: ExtensionContext`.
9
+ All event handlers, tool callbacks, and command handlers receive `ctx: ExtensionContext`.
12
10
 
13
11
  ### ctx.ui
14
12
 
15
- UI methods for user interaction. See [Custom UI](/extensions/ui#custom-ui) for full details.
13
+ UI methods for user interaction. See [Extension UI](/extensions/ui#custom-ui) for full details.
14
+
15
+ ### ctx.mode
16
+
17
+ 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
18
 
17
19
  ### ctx.hasUI
18
20
 
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)).
21
+ `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)).
22
+
23
+ ### ctx.hasHumanInput
24
+
25
+ `boolean` indicating whether a human-input adapter is available independently of terminal rendering.
20
26
 
21
27
  ### ctx.isPresentationOnly
22
28
 
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.
29
+ `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
30
 
25
31
  ### ctx.cwd
26
32
 
27
33
  Current working directory.
28
34
 
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.
35
+ 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
36
 
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.
37
+ Use `CONFIG_DIR_NAME` instead of hardcoding `.atomic` (or legacy `.pi`) when building project config paths:
32
38
 
33
39
  ```typescript
34
40
  import { CONFIG_DIR_NAME, type ExtensionAPI } from "@bastani/atomic";
@@ -44,9 +50,7 @@ export default function (atomic: ExtensionAPI) {
44
50
 
45
51
  ### ctx.isProjectTrusted()
46
52
 
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.
53
+ 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
54
 
51
55
  ```typescript
52
56
  atomic.registerCommand("project-status", {
@@ -61,108 +65,83 @@ atomic.registerCommand("project-status", {
61
65
 
62
66
  Read-only access to session state. See [Session format](/session-format) for the full `SessionManager` API and entry types.
63
67
 
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.
68
+ 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
69
 
66
70
  ```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
71
+ ctx.sessionManager.getEntries() // Entries held in the active window
72
+ ctx.sessionManager.getBranch() // Current branch
73
+ ctx.sessionManager.getLeafId() // Current leaf entry ID
70
74
  ```
71
75
 
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.
76
+ 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
77
 
74
- To inspect older history without keeping the whole session in memory:
78
+ To inspect older history without loading the entire session into memory:
75
79
 
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.
80
+ - `await ctx.sessionManager.readEntry(id)` fetches a single entry.
81
+ - `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)`.
82
+ - `await ctx.sessionManager.loadFullHistory()` loads every stored entry into memory; prefer paged reads for large sessions.
80
83
 
81
84
  ### ctx.modelRegistry / ctx.model / ctx.scopedModels
82
85
 
83
86
  Access models, authentication state, and provider-aware requests.
84
87
 
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.
88
+ 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
89
 
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.
90
+ ```typescript
91
+ const model = ctx.modelRegistry.find("github-copilot", "gpt-5.5");
92
+ if (!model) throw new Error("Model not found");
88
93
 
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`.
94
+ const response = await ctx.modelRegistry.complete(model, { messages }, { signal: ctx.signal });
95
+ ```
90
96
 
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.
97
+ 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.
92
98
 
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`.
99
+ 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.
100
+
101
+ `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
102
 
95
103
  ```typescript
96
104
  const flare = ctx.modelRegistry.getModelOfType("image", "openai-images", "gpt-image-2.6-flare");
97
105
  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
-
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
 
106
- const motion = await ctx.modelRegistry.generateImages(
107
+ const logo = await ctx.modelRegistry.generateImages(
107
108
  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 },
109
+ { input: [{ type: "text", text: "A flat red paper lantern icon" }] },
110
+ { outputFormat: "svg", signal: ctx.signal },
126
111
  );
112
+ if (logo.stopReason !== "stop") throw new Error(logo.errorMessage);
127
113
  ```
128
114
 
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.
115
+ 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).
132
116
 
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
+ 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.
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.
136
-
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
- ```
119
+ 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
120
 
145
- Both `ScopedModel` and `ExtensionScopedModels` are exported from `@bastani/atomic`:
121
+ `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
122
 
147
123
  ```typescript
148
124
  import type { ExtensionScopedModels, ScopedModel } from "@bastani/atomic";
149
125
 
150
- function firstScoped(scope: ExtensionScopedModels): ScopedModel | undefined {
151
- return scope[0];
126
+ function formatScope(scope: ExtensionScopedModels): string[] {
127
+ return scope.map(
128
+ ({ model, thinkingLevel }: ScopedModel) =>
129
+ `${model.provider}/${model.id}${thinkingLevel ? `:${thinkingLevel}` : ""}`,
130
+ );
152
131
  }
153
132
  ```
154
133
 
155
- ### ctx.signal
134
+ ### ctx.thinkingLevel
135
+
136
+ Current `ThinkingLevel` (`"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"`) or `undefined`, resolved from the active session at access time.
156
137
 
157
- The current agent abort signal, or `undefined` when no agent turn is active.
138
+ ### ctx.getDecisionModel()
158
139
 
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`
140
+ 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. Throws `DecisionModelUnavailableError` (`reason: "host-unsupported"`) if the host does not support decision models.
141
+
142
+ ### ctx.signal
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
+ 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
145
 
167
146
  ```typescript
168
147
  atomic.on("tool_result", async (event, ctx) => {
@@ -171,17 +150,15 @@ atomic.on("tool_result", async (event, ctx) => {
171
150
  body: JSON.stringify(event),
172
151
  signal: ctx.signal,
173
152
  });
174
-
175
- const data = await response.json();
176
- return { details: data };
153
+ return { details: await response.json() };
177
154
  });
178
155
  ```
179
156
 
180
157
  ### ctx.sessionSignal
181
158
 
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.
159
+ 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
160
 
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.
161
+ 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
162
 
186
163
  ```typescript
187
164
  import { Text } from "@bastani/atomic-tui";
@@ -198,44 +175,32 @@ atomic.registerCommand("monitor", {
198
175
 
199
176
  ### ctx.isIdle() / ctx.abort() / ctx.hasPendingMessages()
200
177
 
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.
178
+ 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
179
 
205
180
  ### ctx.shutdown()
206
181
 
207
- Request a graceful shutdown of Atomic.
182
+ Request a graceful shutdown of Atomic (emits `session_shutdown` before exiting):
208
183
 
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.
212
-
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
- ```
184
+ - **Interactive mode:** Deferred until the agent becomes idle after processing queued messages.
185
+ - **RPC mode:** Runs once idle and after pending command responses are written.
186
+ - **Print mode:** No-op (the process exits automatically after finishing prompts).
222
187
 
223
188
  ### ctx.getContextUsage()
224
189
 
225
- Returns current context usage for the active model. Uses last assistant usage when available, then estimates tokens for trailing messages.
190
+ 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
191
 
227
192
  ```typescript
228
193
  const usage = ctx.getContextUsage();
229
- if (usage && usage.tokens > 100_000) {
230
- // ...
194
+ if (usage && usage.tokens !== null && usage.tokens > 100_000) {
195
+ ctx.ui.notify(`Context at ${usage.tokens} tokens`, "warning");
231
196
  }
232
197
  ```
233
198
 
234
199
  ### ctx.compact()
235
200
 
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.
201
+ 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
202
 
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.
203
+ Options: `query` (passed to the boundary message and compactor), `compactionModel` (`"auto"` or an exact model ID for this run only), `onComplete`, and `onError`.
239
204
 
240
205
  ```typescript
241
206
  ctx.compact({
@@ -249,71 +214,70 @@ ctx.compact({
249
214
  });
250
215
  ```
251
216
 
252
- Extensions that need their own replacement text can return `compactedText` from `session_before_compact`. See [Compaction](/compaction) for both forms.
217
+ See [Compaction](/compaction).
253
218
 
254
219
  ### ctx.getSystemPrompt()
255
220
 
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
- ```
221
+ 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
222
 
270
223
  ### ctx.getSkillCatalog()
271
224
 
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.
225
+ Optional method returning the loader-owned `SkillCatalog`. Use `catalog.resolve(selector)` to look up exact skill selectors.
226
+
227
+ 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
228
 
274
229
  ```typescript
275
230
  atomic.on("session_start", (_event, ctx) => {
276
231
  const catalog = ctx.getSkillCatalog?.();
277
- const resolved = catalog?.resolve("tdd@builtin");
232
+ const resolved = catalog?.resolve("tdd");
278
233
  if (resolved?.ok) {
279
234
  ctx.ui.notify(`Using ${resolved.candidate.selector}`, "info");
280
235
  }
281
236
  });
282
237
  ```
283
238
 
284
- `atomic.getCommands()` already includes the same advertised `/skill:name` and `/skill:name@source` names. See [Skill Commands](/skills#skill-commands).
239
+ `atomic.getCommands()` returns the same advertised `/skill:name` and `/skill:name@source` names. See [Skill commands](/skills#skill-commands).
240
+
241
+ ### Additional optional context getters
242
+
243
+ These optional methods are present when supported by the host:
244
+
245
+ - **`ctx.getHttpIdleTimeoutMs?(): number`:** Returns the session's `httpIdleTimeoutMs` setting in milliseconds (`0` means idle timeout is disabled).
246
+ - **`ctx.getPackageAgents?(): readonly PackageAgentFile[]`:** Returns enabled subagent definition files contributed by installed packages (only from project packages when the project is trusted).
247
+ - **`ctx.getExtensionPaths?(): string[]`:** Returns the file paths of loaded extensions.
248
+ - **`ctx.isSessionSummaryEnabled?(): boolean`:** Returns whether background session summaries are enabled.
285
249
 
286
250
  ## ExtensionToolContext
287
251
 
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.
252
+ 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
253
 
290
254
  ## ExtensionCommandContext
291
255
 
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.
256
+ Command handlers receive `ExtensionCommandContext`, extending `ExtensionContext` with session-control methods that would deadlock if called from event handlers.
257
+
258
+ ### ctx.getSystemPromptOptions()
259
+
260
+ Returns the current base `BuildSystemPromptOptions` used to construct the session's system prompt.
293
261
 
294
262
  ### ctx.waitForIdle()
295
263
 
296
- Wait for the agent to finish streaming:
264
+ Wait for the agent to finish streaming before modifying session state:
297
265
 
298
266
  ```typescript
299
267
  atomic.registerCommand("my-cmd", {
300
- handler: async (args, ctx) => {
268
+ handler: async (_args, ctx) => {
301
269
  await ctx.waitForIdle();
302
- // Agent is now idle, safe to modify session
303
270
  },
304
271
  });
305
272
  ```
306
273
 
307
274
  ### ctx.newSession(options?)
308
275
 
309
- Create a new session:
276
+ Create a new session. Options: `parentSession`, `setup(sessionManager)` (runs before switching), and `withSession(ctx)` (runs post-switch work against a fresh `ReplacedSessionContext`):
310
277
 
311
278
  ```typescript
312
- const parentSession = ctx.sessionManager.getSessionId();
313
- const kickoff = "Continue in the replacement session";
314
-
315
279
  const result = await ctx.newSession({
316
- parentSession,
280
+ parentSession: ctx.sessionManager.getSessionId(),
317
281
  setup: async (sm) => {
318
282
  await sm.appendMessage({
319
283
  role: "user",
@@ -321,105 +285,61 @@ const result = await ctx.newSession({
321
285
  timestamp: Date.now(),
322
286
  });
323
287
  },
324
- withSession: async (ctx) => {
325
- // Use only the replacement-session ctx here.
326
- await ctx.sendUserMessage(kickoff);
288
+ withSession: async (nextCtx) => {
289
+ await nextCtx.sendUserMessage("Continue in the new session");
327
290
  },
328
291
  });
329
-
330
292
  if (result.cancelled) {
331
- // An extension cancelled the new session
293
+ // Cancelled by session_before_switch
332
294
  }
333
295
  ```
334
296
 
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
297
  ### ctx.fork(entryId, options?)
341
298
 
342
- Fork from a specific entry, creating a new session file:
299
+ 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
300
 
344
301
  ```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");
302
+ const forkResult = await ctx.fork("entry-id-123", {
303
+ withSession: async (nextCtx) => {
304
+ nextCtx.ui.notify("Now in the forked session", "info");
349
305
  },
350
306
  });
351
- if (result.cancelled) {
352
- // An extension cancelled the fork
353
- }
354
307
 
355
308
  const cloneResult = await ctx.fork("entry-id-456", { position: "at" });
356
- if (cloneResult.cancelled) {
357
- // An extension cancelled the clone
358
- }
359
309
  ```
360
310
 
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
311
  ### ctx.navigateTree(targetId, options?)
367
312
 
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.
313
+ 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
314
 
370
315
  ```typescript
371
- const result = await ctx.navigateTree("entry-id-456", {
316
+ await ctx.navigateTree("entry-id-456", {
372
317
  summarize: true,
373
318
  customInstructions: "Focus on error handling changes",
374
- replaceInstructions: false, // true = replace default prompt entirely
319
+ replaceInstructions: false,
375
320
  label: "review-checkpoint",
376
321
  });
377
322
  ```
378
323
 
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
324
  ### ctx.switchSession(sessionId, options?)
386
325
 
387
- Switch to a different session by its exact ID:
326
+ Switch to another session by exact ID. Options: `withSession(ctx)`.
388
327
 
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).
402
-
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:
328
+ 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
329
 
407
330
  ```typescript
408
331
  import { SessionManager } from "@bastani/atomic";
409
332
 
410
333
  atomic.registerCommand("switch", {
411
334
  description: "Switch to another session",
412
- handler: async (args, ctx) => {
335
+ handler: async (_args, ctx) => {
413
336
  const sessions = await SessionManager.list(ctx.cwd);
414
337
  if (sessions.length === 0) return;
415
- const choice = await ctx.ui.select(
416
- "Pick session:",
417
- sessions.map(s => s.id),
418
- );
338
+ const choice = await ctx.ui.select("Pick session:", sessions.map((s) => s.id));
419
339
  if (choice) {
420
340
  await ctx.switchSession(choice, {
421
- withSession: async (ctx) => {
422
- ctx.ui.notify("Switched session", "info");
341
+ withSession: async (nextCtx) => {
342
+ nextCtx.ui.notify("Switched session", "info");
423
343
  },
424
344
  });
425
345
  }
@@ -429,386 +349,158 @@ atomic.registerCommand("switch", {
429
349
 
430
350
  ### Session replacement lifecycle and footguns
431
351
 
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:
352
+ `withSession` receives a fresh `ReplacedSessionContext`, which extends `ExtensionCommandContext` with async `sendMessage()` and `sendUserMessage(): Promise<void>` bound to the replacement session.
458
353
 
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
- ```
354
+ - `withSession` runs after the old session has emitted `session_shutdown`, reloaded extensions, and emitted `session_start` on the new session.
355
+ - 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).
356
+ - Use `isStaleExtensionContextError(error)` from `@bastani/atomic` to detect stale-context errors in long-lived callbacks.
473
357
 
474
358
  ### ctx.reload()
475
359
 
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
- });
360
+ 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
361
 
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
- ```
362
+ 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
363
 
530
364
  ## ExtensionAPI methods
531
365
 
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" />
539
-
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.
549
-
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.
366
+ ### atomic.getSettings()
553
367
 
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.
368
+ 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).
555
369
 
556
- #### Built-in tool prompt contributions
370
+ ### atomic.on(event, handler)
557
371
 
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:
372
+ 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
373
 
560
374
  ```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;
375
+ const unsubscribe = atomic.on("turn_end", (event) => {
376
+ if (event.turnIndex >= 5) unsubscribe();
377
+ });
572
378
  ```
573
379
 
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.
380
+ ### atomic.registerTool(definition)
575
381
 
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.
382
+ 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
383
 
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
- },
598
-
599
- async execute(toolCallId, params, signal, onUpdate, ctx) {
600
- // Stream progress
601
- onUpdate?.({ content: [{ type: "text", text: "Working..." }] });
384
+ Collision rules:
602
385
 
603
- return {
604
- content: [{ type: "text", text: "Done" }],
605
- details: { result: "..." },
606
- };
607
- },
386
+ - Within one extension, registering the same tool name twice keeps the last registration and shows a warning under `[Extension issues]`.
387
+ - Across multiple extensions, the **first** loaded extension wins. The mandatory bundled `intercom` tool cannot be shadowed.
608
388
 
609
- // Optional: Custom rendering
610
- renderCall(args, theme, context) { ... },
611
- renderResult(result, options, theme, context) { ... },
612
- });
613
- ```
389
+ 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
390
 
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.
391
+ #### Built-in tool prompt contributions
616
392
 
617
- <a id="pi-sendmessage-message-options" />
393
+ 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
394
 
619
395
  ### atomic.sendMessage(message, options?)
620
396
 
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.
397
+ 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).
398
+
399
+ `customType` must be a string and `content` a string or content-block array, or the call throws `TypeError` and saves nothing.
622
400
 
623
401
  ```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
- });
402
+ await Promise.resolve(
403
+ atomic.sendMessage(
404
+ {
405
+ customType: "my-extension",
406
+ content: "Message text",
407
+ display: true,
408
+ details: { step: 1 },
409
+ },
410
+ { triggerTurn: true, deliverAs: "steer" },
411
+ ),
412
+ );
633
413
  ```
634
414
 
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.
415
+ Options (`SendMessageOptions`):
647
416
 
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`.
417
+ - `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).
418
+ - `triggerTurn`: start a model turn immediately if idle (required for `"interrupt"`, ignored for `"nextTurn"`).
419
+ - `excludeFromContext`: render and persist the message without adding it to model context.
420
+ - `interruptAbortMessage`: custom abort text when `deliverAs: "interrupt"` stops an active turn.
421
+ - `persistWhenStreaming`: persist the custom message immediately even while a turn is streaming.
422
+ - `stageAdmissionKey`: optional deduplication key for staged recovery deliveries.
649
423
 
650
- <a id="pi-sendmessages-messages-options" />
424
+ In print (`-p`) and JSON modes, Atomic waits for messages queued before a command handler returns (and the turns they trigger) before exiting.
651
425
 
652
426
  ### atomic.sendMessages(messages, options?)
653
427
 
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.
428
+ 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
429
 
656
430
  ```typescript
657
- atomic.sendMessages([
658
- { customType: "worker-update", content: "Ready", display: true },
659
- { customType: "worker-terminal", content: "Completed", display: true },
660
- ], { triggerTurn: true });
431
+ await Promise.resolve(
432
+ atomic.sendMessages(
433
+ [
434
+ { customType: "worker-update", content: "Ready", display: true },
435
+ { customType: "worker-terminal", content: "Completed", display: true },
436
+ ],
437
+ { triggerTurn: true },
438
+ ),
439
+ );
661
440
  ```
662
441
 
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
442
  ### atomic.sendUserMessage(content, options?)
668
443
 
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.
444
+ Send an actual user message (always triggering a turn). Returns `void` on `ExtensionAPI` (whereas `ReplacedSessionContext.sendUserMessage()` inside `withSession` returns `Promise<void>`).
670
445
 
671
446
  ```typescript
672
- // Simple text message
673
447
  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
448
  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
449
  atomic.sendUserMessage("/review src/index.ts", { expandPromptTemplates: true });
687
450
  ```
688
451
 
689
452
  Options:
690
453
 
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.
454
+ - `deliverAs`: `"steer"` or `"followUp"` (required when the agent is streaming; omitting it while streaming throws an error).
455
+ - `expandPromptTemplates`: defaults to `false`; set `true` to dispatch extension commands and expand `/skill:` and prompt templates.
697
456
 
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" />
457
+ While the session is compacting, the message waits in the queue and sends once compaction ends.
701
458
 
702
459
  ### atomic.appendEntry(customType, data?)
703
460
 
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.
461
+ 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`.
462
+
463
+ 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
464
 
706
465
  ```typescript
707
466
  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
467
  ```
718
468
 
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
469
  ### atomic.registerEntryRenderer(customType, renderer)
726
470
 
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.
471
+ Register a TUI renderer for durable custom entries created by `atomic.appendEntry()`. `Ctrl+O` or clicking the entry in fullscreen mode toggles `expanded`.
730
472
 
731
473
  ```typescript
732
474
  import { Text } from "@bastani/atomic-tui";
733
475
 
734
476
  atomic.registerEntryRenderer("status-card", (entry, { expanded }, theme) =>
735
- new Text(theme.fg("accent", `${expanded ? "Details" : "Status"}: ${JSON.stringify(entry.data)}`), 0, 0)
477
+ new Text(theme.fg("accent", `${expanded ? "Details" : "Status"}: ${JSON.stringify(entry.data)}`), 0, 0),
736
478
  );
737
479
  ```
738
480
 
481
+ ### atomic.setSessionName(name) / atomic.getSessionName()
739
482
 
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" />
483
+ Set (`Promise<void>`) or read (`string | undefined`) the session display name shown in `/resume` and the session selector.
764
484
 
765
485
  ### atomic.setLabel(entryId, label)
766
486
 
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" />
487
+ 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
488
 
784
489
  ### atomic.registerCommand(name, options)
785
490
 
786
- Register a command.
491
+ 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
492
 
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 ...`:
493
+ `getArgumentCompletions(prefix)` may return `AutocompleteItem[] | null` or `Promise<AutocompleteItem[] | null>`:
801
494
 
802
495
  ```typescript
803
496
  import type { AutocompleteItem } from "@bastani/atomic-tui";
804
497
 
805
498
  atomic.registerCommand("deploy", {
806
499
  description: "Deploy to an environment",
807
- getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => {
500
+ getArgumentCompletions: async (prefix: string): Promise<AutocompleteItem[] | null> => {
808
501
  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;
502
+ const items = envs.filter((e) => e.startsWith(prefix)).map((e) => ({ value: e, label: e }));
503
+ return items.length > 0 ? items : null;
812
504
  },
813
505
  handler: async (args, ctx) => {
814
506
  ctx.ui.notify(`Deploying: ${args}`, "info");
@@ -816,24 +508,13 @@ atomic.registerCommand("deploy", {
816
508
  });
817
509
  ```
818
510
 
819
- <a id="pi-getcommands" />
820
-
821
511
  ### atomic.getCommands()
822
512
 
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:
513
+ 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
514
 
834
515
  ```typescript
835
516
  {
836
- name: string; // Invokable command name without the leading slash. May be suffixed like "review:1"
517
+ name: string; // Without leading slash; may be suffixed like "review:1"
837
518
  description?: string;
838
519
  source: "extension" | "prompt" | "skill";
839
520
  sourceInfo: {
@@ -842,90 +523,57 @@ Each entry has this shape:
842
523
  scope: "user" | "project" | "temporary";
843
524
  origin: "package" | "top-level";
844
525
  baseDir?: string;
526
+ configurationOrigin?: "atomic" | "inherited-pi" | "bundled";
845
527
  };
846
528
  }
847
529
  ```
848
530
 
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
531
  ### atomic.registerMessageRenderer(customType, renderer)
857
532
 
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" />
533
+ 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
534
 
862
535
  ### atomic.registerToolRenderer(resolver)
863
536
 
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).
537
+ 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
538
 
868
- <a id="pi-registermarkdowntransformer-transformer" />
539
+ <div id="pi-registermarkdowntransformer-transformer" />
869
540
 
870
- ### atomic.registerMarkdownTransformer(transformer)
541
+ ### atomic.registerMarkdownTransformer(transformer, options?)
871
542
 
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.
543
+ 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
544
 
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:
545
+ 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
546
 
893
547
  ```typescript
894
548
  atomic.registerMarkdownTransformer((markdown, { messageType, isStreaming }) => {
895
549
  if (isStreaming || messageType === "assistant-thinking") return markdown;
896
550
  return markdown.replaceAll("-->", "→");
897
551
  });
898
-
899
- // Show :warning: shortcodes in the changelog as a symbol.
900
- atomic.registerMarkdownTransformer((markdown) => markdown.replaceAll(":warning:", "⚠"), {
901
- messageTypes: ["changelog"],
902
- });
903
552
  ```
904
553
 
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
554
  ### atomic.registerShortcut(shortcut, options)
910
555
 
911
- Register a keyboard shortcut. See [Keybindings](/keybindings) for the shortcut format and built-in keybindings.
556
+ Register a keyboard shortcut. See [Keybindings](/keybindings) for shortcut syntax.
912
557
 
913
558
  ```typescript
914
559
  atomic.registerShortcut("ctrl+shift+p", {
915
560
  description: "Toggle plan mode",
916
561
  handler: async (ctx) => {
917
- ctx.ui.notify("Toggled!");
562
+ ctx.ui.notify("Toggled!", "info");
918
563
  },
919
564
  });
920
565
  ```
921
566
 
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.
567
+ Conflict policy:
923
568
 
924
- <a id="pi-registerflag-name-options" />
569
+ - **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.
570
+ - **Non-reserved built-in shortcuts** are overridden by extensions (with a warning) unless `preferEditor: true` is set, which yields to the editor binding.
571
+ - **Between two extensions**, the **last** registered shortcut wins (with a warning).
572
+ - 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
573
 
926
- ### atomic.registerFlag(name, options)
574
+ ### atomic.registerFlag(name, options) / atomic.getFlag(name)
927
575
 
928
- Register a CLI flag.
576
+ Register and read a custom CLI flag (`type: "boolean" | "string"`):
929
577
 
930
578
  ```typescript
931
579
  atomic.registerFlag("plan", {
@@ -934,17 +582,22 @@ atomic.registerFlag("plan", {
934
582
  default: false,
935
583
  });
936
584
 
937
- // Check value
938
585
  if (atomic.getFlag("plan")) {
939
586
  // Plan mode enabled
940
587
  }
941
588
  ```
942
589
 
943
- <a id="pi-registeragentpanelsource-source" />
590
+ Flag rules:
591
+
592
+ - `default`, if supplied, must match `type` (`boolean` or `string`) or `registerFlag()` throws.
593
+ - Across extensions, the **first** extension registering a flag name wins.
594
+ - `atomic.getFlag(name)` reads **only** flags registered by that same extension; it returns `undefined` for other extensions' flags or built-in CLI flags.
595
+
596
+ <div id="pi-registeragentpanelsource-source" />
944
597
 
945
598
  ### atomic.registerAgentPanelSource(source)
946
599
 
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.
600
+ 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
601
 
949
602
  ```typescript
950
603
  import type { AgentPanelItem, ExtensionAPI } from "@bastani/atomic";
@@ -977,159 +630,114 @@ export default function (atomic: ExtensionAPI) {
977
630
  }
978
631
  ```
979
632
 
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:
633
+ 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
634
 
986
635
  | Field | Meaning |
987
636
  | --- | --- |
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`.
637
+ | `id` | Unique in the session (prefix with your source name; `main` and `task:` are reserved). |
638
+ | `kind` | `"agent"` or `"shell"` (`"shell"` appears in `/tasks` and main footer count only). |
639
+ | `state` | `running`, `queued`, `input`, `paused`, `stopping`, `waiting`, `done`, `failed`, or `stopped`. |
640
+ | `name`, `task` | Display name and active task description. |
641
+ | `model`, `thinking` | Optional `provider/model-id` string and reasoning level string. |
642
+ | `elapsedMs`, `tokens` | Finite non-negative milliseconds and safe integer token count. |
643
+ | `progress` | Finite non-negative `{ done, total }` stage progress bar. |
644
+ | `question`, `choices`, `promptId` | Prompt details for `input` items (change `promptId` for every new question). |
645
+ | `reason`, `waitingOn`, `queued`, `endedAt`, `runGeneration` | Failure summary, waiting label, queued message count, finish timestamp (epoch ms), and monotonic per-item run counter. |
1014
646
 
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()`.
647
+ 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
648
 
1017
- <a id="pi-exec-command-args-options" />
649
+ 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
650
 
1019
651
  ### atomic.exec(command, args, options?)
1020
652
 
1021
- Execute a command without a shell.
653
+ Execute a command directly without a shell:
1022
654
 
1023
655
  ```typescript
1024
656
  const result = await atomic.exec("git", ["status"], { signal, timeout: 5000 });
1025
657
  // result.stdout, result.stderr, result.code, result.killed, result.truncated
1026
658
  ```
1027
659
 
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" />
660
+ - On Windows, bare command names (like `git`) resolve only from absolute directories on `PATH`, never from `cwd` or Atomic's own directory.
661
+ - 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`.
662
+ - On timeout, abort, or `maxBuffer`: terminates the process tree (`SIGTERM`, then `SIGKILL` after 5 s on Unix; immediate descendant termination on Windows).
663
+ - 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
664
 
1040
665
  ### atomic.getActiveTools() / atomic.getAllTools() / atomic.setActiveTools(names)
1041
666
 
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.
667
+ 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
668
 
1044
669
  ```typescript
1045
- const active = atomic.getActiveTools(); // ["read", "bash", ...]
670
+ const active = atomic.getActiveTools();
1046
671
  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
672
+ atomic.setActiveTools([...new Set([...active, "my_custom_tool"])]);
1058
673
  ```
1059
674
 
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" />
675
+ 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
676
 
1069
677
  ### atomic.setModel(model)
1070
678
 
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" />
679
+ 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
680
 
1085
681
  ### atomic.getThinkingLevel() / atomic.setThinkingLevel(level)
1086
682
 
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" />
683
+ 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
684
 
1098
685
  ### atomic.events
1099
686
 
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:
687
+ 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
688
 
1102
689
  ```typescript
1103
- const unsubscribe = atomic.events.on("my:event", (data) => { ... });
1104
- atomic.events.emit("my:event", { ... });
690
+ const unsubscribe = atomic.events.on("my:event", (data) => { /* ... */ });
691
+ atomic.events.emit("my:event", { ok: true });
1105
692
  unsubscribe();
1106
693
  ```
1107
694
 
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.
695
+ 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
696
 
697
+ Embedded hosts implementing `ExtensionRuntime` must implement `trackEventBusSubscription(unsubscribe)` and return `markdownTransformers` (plus optional `renderLatex`, `fullscreenScrollbar`, `fullscreenWheelScrollLines`) from `ExtensionUIContext.getChatRenderSettings()`.
1112
698
 
1113
699
  ### Native providers
1114
700
 
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.
701
+ 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
702
 
1117
- <a id="pi-registerprovider-name-config" />
703
+ ```typescript
704
+ import type { Provider } from "@bastani/atomic-ai";
1118
705
 
1119
- ### atomic.registerProvider(name, config)
706
+ const localServerProvider: Provider = {
707
+ id: "local-server",
708
+ name: "Local Server",
709
+ auth: {
710
+ apiKey: {
711
+ name: "Local server connection",
712
+ async login({ signal, prompt }) {
713
+ const baseUrl = await prompt({
714
+ type: "text",
715
+ message: "Server URL",
716
+ placeholder: "http://localhost:9931",
717
+ });
718
+ if (signal.aborted) throw new Error("Login cancelled");
719
+ return { type: "api_key", env: { LOCAL_SERVER_URL: baseUrl } };
720
+ },
721
+ },
722
+ },
723
+ // ...models and transport methods
724
+ };
725
+
726
+ await atomic.registerProvider(localServerProvider);
727
+ ```
1120
728
 
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.
729
+ 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
730
 
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`.
731
+ ### atomic.registerProvider(name, config)
1124
732
 
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`.
733
+ 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
734
 
1127
735
  ```typescript
1128
736
  // Register a new provider with custom models
1129
737
  await atomic.registerProvider("my-proxy", {
1130
738
  name: "My Proxy",
1131
739
  baseUrl: "https://proxy.example.com",
1132
- apiKey: "$PROXY_API_KEY", // env var reference; omit $ for a literal
740
+ apiKey: "$PROXY_API_KEY",
1133
741
  api: "anthropic-messages",
1134
742
  models: [
1135
743
  {
@@ -1139,134 +747,115 @@ await atomic.registerProvider("my-proxy", {
1139
747
  input: ["text", "image"],
1140
748
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1141
749
  contextWindow: 200000,
1142
- maxTokens: 16384
1143
- }
1144
- ]
750
+ maxTokens: 16384,
751
+ },
752
+ ],
1145
753
  });
1146
754
 
1147
- // Override baseUrl for an existing provider (keeps all models)
755
+ // Override baseUrl for an existing provider (keeps existing models)
1148
756
  await atomic.registerProvider("anthropic", {
1149
- baseUrl: "https://proxy.example.com"
757
+ baseUrl: "https://proxy.example.com",
1150
758
  });
1151
759
 
1152
- // Register provider with OAuth support for /login
760
+ // Register a provider with OAuth login
1153
761
  await atomic.registerProvider("corporate-ai", {
1154
762
  baseUrl: "https://ai.corp.com",
1155
763
  api: "openai-responses",
1156
764
  models: [...],
1157
765
  oauth: {
1158
766
  name: "Corporate AI (SSO)",
767
+ loginLabel: "Sign in with SSO",
768
+ usesCallbackServer: false,
1159
769
  async login(callbacks, signal) {
1160
- // Custom OAuth flow
1161
770
  callbacks.onAuth({ url: "https://sso.corp.com/..." });
1162
771
  const code = await callbacks.onPrompt({ message: "Enter code:" });
1163
772
  signal.throwIfAborted();
1164
773
  return { refresh: code, access: code, expires: Date.now() + 3600000 };
1165
774
  },
1166
775
  async refreshToken(credentials, signal) {
1167
- // Pass `signal` through, but add no timeout or abort of your own (see below).
776
+ // Throw OAuthRefreshRejectedError on permanent rejection (for example invalid_grant)
1168
777
  return refreshCorporateToken(credentials.refresh, { signal });
1169
778
  },
1170
779
  getApiKey(credentials) {
1171
780
  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
- }
781
+ },
782
+ },
1193
783
  });
1194
784
  ```
1195
785
 
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.
786
+ `ProviderConfig` options:
1197
787
 
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.
788
+ - `name`: display name in UI such as `/login`.
789
+ - `aliasOf`: ID of an existing provider to alias.
790
+ - `baseUrl`: API endpoint URL (required when defining models).
791
+ - `apiKey`: literal key or environment variable reference (`$ENV_VAR` or `${ENV_VAR}`; required when defining models unless `oauth` is set).
792
+ - `api`: API protocol (`"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc.).
793
+ - `headers`, `authHeader`: extra headers, or `authHeader: true` to send `Authorization: Bearer`.
794
+ - `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`.
795
+ - `refreshModels?(context)`: dynamically refresh the provider's model catalog (replaces extension-provided models on success).
796
+ - `images`, `classifiers`: custom image or classifier API handlers keyed by API name.
797
+ - `streamSimple`: custom streaming implementation for non-standard APIs.
798
+ - `oauth`: OAuth configuration with `name`, optional `loginLabel`, optional `usesCallbackServer`, `login(callbacks, signal)`, `refreshToken(credentials, signal)`, `getApiKey(credentials)`, and optional `modifyModels(models, credentials)`.
1199
799
 
1200
- Config options:
800
+ **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
801
 
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)
802
+ See [Custom providers](/custom-provider) for full details.
1218
803
 
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.
804
+ ### atomic.registerProviderAlias(config)
1220
805
 
1221
- Like `registerProvider`, this takes effect immediately after the initial load phase without requiring `/reload`.
806
+ Register an alias pointing to an existing provider (for example, multiple accounts on the same provider). Returns `Promise<void>`:
1222
807
 
1223
808
  ```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
- },
809
+ await atomic.registerProviderAlias({
810
+ id: "openai-work",
811
+ name: "OpenAI (Work)",
812
+ provider: "openai",
1229
813
  });
1230
814
  ```
1231
815
 
1232
- <a id="pi-registermcpserver-name-config" />
816
+ See [examples/extensions/provider-accounts.ts](https://github.com/bastani-inc/atomic/blob/main/packages/coding-agent/examples/extensions/provider-accounts.ts).
817
+
818
+ ### atomic.unregisterProvider(name)
819
+
820
+ 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`.
1233
821
 
1234
822
  ### atomic.registerMcpServer(name, config)
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
+ 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
825
 
1238
826
  ```typescript
1239
827
  export default function (atomic: ExtensionAPI) {
1240
828
  atomic.on("session_start", async () => {
1241
829
  const port = await startLocalService();
1242
- atomic.registerMcpServer("local-service", { url: `http://127.0.0.1:${port}/mcp`, exposure: "direct" });
830
+ atomic.registerMcpServer("local-service", {
831
+ url: `http://127.0.0.1:${port}/mcp`,
832
+ exposure: "direct",
833
+ });
1243
834
  });
1244
835
  }
1245
836
  ```
1246
837
 
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.
838
+ 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
839
 
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`.
840
+ `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
841
 
1255
842
  ## Error handling
1256
843
 
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.
844
+ - Uncaught errors in most event handlers are logged and the session continues.
845
+ - 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.
846
+ - 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.
847
+ - Inside tool `execute()`, throw an `Error` to report failure; Atomic catches it, sends it to the model with `isError: true`, and continues.
1261
848
 
1262
849
  ### Typed errors from built-in tools and providers
1263
850
 
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`. |
851
+ These error classes and type guards are exported from `@bastani/atomic`. 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.
852
+
853
+ | Class | `code` | When | Key fields / notes |
854
+ | --- | --- | --- | --- |
855
+ | `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`. |
856
+ | `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`. |
857
+ | `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. |
858
+ | `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>`. |
859
+ | `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. |
860
+ | `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. |
861
+ | `MissingSessionCwdError` | `session-cwd-missing` | `ctx.switchSession()` targeted a session whose recorded working directory no longer exists. | Guard with `isMissingSessionCwdError(error)`. |