@bastani/atomic 0.10.9-alpha.1 → 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 +69 -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
package/docs/sdk.md CHANGED
@@ -1,22 +1,20 @@
1
1
  ---
2
- title: "SDK"
3
- description: "Embed Atomic in a Node.js application."
2
+ title: "TypeScript SDK"
3
+ sidebarTitle: "SDK"
4
+ description: "Embed Atomic agent sessions in Node.js applications with programmatic control over models, tools, storage, and human input."
4
5
  ---
5
6
 
6
- # SDK
7
+ Embed Atomic in Node.js applications (Node.js 22.19 or newer) to build custom UIs, power backend services, or drive automated workflows directly inside your Node.js process. Working examples live in [examples/sdk/](https://github.com/bastani-inc/atomic/tree/main/packages/coding-agent/examples/sdk).
7
8
 
8
- <a id="on-this-page-and-its-reference" />
9
-
10
- Embed Atomic in Node.js apps to build custom UIs, integrate agent sessions into backend services, or drive automated pipelines programmatically. Working examples live in [examples/sdk/](https://github.com/bastani-inc/atomic/tree/main/packages/coding-agent/examples/sdk).
11
-
12
- - **Full options and exports:** [SDK API reference](/sdk/reference) (also covers [Owner-bound task supervisor](/sdk/reference#owner-bound-task-supervisor), [Supervised command SDK](/sdk/reference#supervised-command-sdk), and [Task transcript references](/sdk/reference#task-transcript-references)).
13
- - **SQLite & custom storage adapters:** [SQLite storage API](/storage).
14
- - **Serving over HTTP:** [Embedding Atomic in a web server](/sdk/web-server) (Next.js App Router streaming guide).
15
- - **Choosing an integration mode:** Compare SDK, RPC, and JSON on [Programmatic use](/programmatic).
9
+ - **Full options and exports:** [SDK API reference](/sdk/reference) (includes [Owner-bound task supervisor](/sdk/reference#owner-bound-task-supervisor), [Supervised command SDK](/sdk/reference#supervised-command-sdk), and [Task transcript references](/sdk/reference#task-transcript-references)).
10
+ - **Typed decisions:** [Structured decisions API](/sdk/structured-decisions).
11
+ - **SQLite and custom storage adapters:** [SQLite storage API](/storage).
12
+ - **HTTP streaming servers:** [Embed Atomic in a web server](/sdk/web-server) (Next.js App Router guide).
13
+ - **Compare modes:** [Programmatic integration](/programmatic).
16
14
 
17
15
  ## Quick start
18
16
 
19
- Install `@bastani/atomic` (the SDK ships in the main package; pass `--ignore-scripts` if you disable dependency install scripts):
17
+ Install `@bastani/atomic` (the SDK ships in the main package; install scripts are not required):
20
18
 
21
19
  ```bash
22
20
  npm install @bastani/atomic
@@ -24,6 +22,8 @@ npm install @bastani/atomic
24
22
  # or: bun add @bastani/atomic
25
23
  ```
26
24
 
25
+ For TypeScript ESM projects, set `"type": "module"` in `package.json` and `"module": "NodeNext"`, `"moduleResolution": "NodeNext"`, `"strict": true` in `tsconfig.json`.
26
+
27
27
  Create a session, stream text deltas, and dispose cleanly in `finally`:
28
28
 
29
29
  ```typescript
@@ -49,21 +49,13 @@ try {
49
49
  }
50
50
  ```
51
51
 
52
- - **`ModelRuntime`:** Canonical async runtime for credentials, native providers, and dynamic catalogs. Accepts `authPath`, `modelsPath`, `credentials`, runtime auth overrides, and catalog options `allowModelNetwork`, `modelRefreshTimeoutMs`, `modelsStorePath`, and `modelsStore` (see [Model catalog persistence and refresh](/sdk/reference#model-catalog-persistence-and-refresh)). Legacy synchronous facades `ModelRegistry` and `AuthStorage` remain available; `readStoredCredential(provider, authPath?)` reads one stored credential.
53
- - **Exact model restoration:** Call `await resolveRestoredModelReference(provider, modelId, modelRuntime)` to resolve an authenticated saved model (including custom/dynamic IDs) or get `undefined` without falling back to a default.
54
- - **Extensions & context helpers:** Exported root types/helpers include `InlineExtension`, `registerProvider(Provider)`, `registerEntryRenderer`, `entry_appended`, `before_provider_headers`, `agent_settled`, `buildContextEntries`, `sessionEntryToContextMessages`, `CompactionEntry`, and `sessionManager.buildContextEntries()`.
55
-
56
- ## Installation
57
-
58
- For TypeScript ESM Node apps, set `"type": "module"` in `package.json` and `"module": "NodeNext"`, `"moduleResolution": "NodeNext"`, `"strict": true` in `tsconfig.json` (typechecks cleanly with `skipLibCheck: false`). Import directly from `@bastani/atomic`:
59
-
60
- ```typescript
61
- import { createAgentSession, type HostInput } from "@bastani/atomic";
62
- ```
52
+ - **`ModelRuntime`:** Async runtime for credentials, native providers, and dynamic catalogs. Accepts `authPath`, `modelsPath`, `credentials`, runtime auth overrides, and catalog options (`allowModelNetwork`, `modelRefreshTimeoutMs`, `modelsStorePath`, `modelsStore`; see [Model catalog persistence and refresh](/sdk/reference#model-catalog-persistence-and-refresh)). Legacy synchronous facades `ModelRegistry` and `AuthStorage` remain available, and `readStoredCredential(provider, authPath?)` reads one stored credential.
53
+ - **Exact model restoration:** Call `await resolveRestoredModelReference(provider, modelId, modelRuntime)` to resolve an authenticated saved model (including custom or dynamic IDs) or receive `undefined` without falling back to a default.
54
+ - **Context helpers:** Root exports include `InlineExtension`, `buildContextEntries`, `sessionEntryToContextMessages`, `CompactionEntry`, and `sessionManager.buildContextEntries()`.
63
55
 
64
56
  ### Sharing Atomic's TypeBox registry
65
57
 
66
- Atomic ships its own TypeBox instance. If your SDK application (or a package an extension depends on) imports `typebox` directly, custom formats, settings, or locales will not reach Atomic's tool validation. Import from `@bastani/atomic/typebox` and its subpaths instead:
58
+ Atomic ships its own TypeBox instance. If your app imports `typebox` directly, custom formats, settings, or locales will not reach Atomic's tool validation. Import from `@bastani/atomic/typebox` and its subpaths instead:
67
59
 
68
60
  - `@bastani/atomic/typebox`
69
61
  - `@bastani/atomic/typebox/compile`
@@ -75,40 +67,11 @@ Atomic ships its own TypeBox instance. If your SDK application (or a package an
75
67
  - `@bastani/atomic/typebox/type`
76
68
  - `@bastani/atomic/typebox/value`
77
69
 
78
- ### Node 22 hosts
79
-
80
- On Node 22, `AsyncLocalStorage` runs on promise hooks. Once a session has run, they stay on for the whole process, and every `await` in your application costs more. Atomic keeps all of its context in one store, so the cost does not grow with the number of sessions. Node 24 and Bun have no such cost.
81
-
82
- On Node 22.7 or a later 22.x release, start your host with `node --experimental-async-context-frame` to avoid it. The flag switches `AsyncLocalStorage` to Node 24's implementation for the whole process, so check any code of your own that relies on Node 22's behavior, such as `disable()`. Pass it on the host's own command line, not in `NODE_OPTIONS`: Node 24 and later refuse the flag, and commands your sessions' tools run inherit `NODE_OPTIONS`, so a newer Node among them would fail to start.
83
-
84
- ### Updating Atomic while your program runs
85
-
86
- When `npm install`, `pnpm add`, or `bun add` replaces `@bastani/atomic` while your program runs, the program keeps the Atomic code it already loaded and loads new modules from the update when it first needs them. When updated code cannot load beside the running copy, Atomic reports an error telling you to restart (see [updating the CLI](/reference/cli#package-commands)).
87
-
88
- `createAgentSession()` checks Atomic's native module (`@bastani/atomic-natives`) before opening a session and throws `NativeModuleUnavailableError` (`code: "NativeModuleUnavailable"`) when the module cannot load or comes from another release:
89
-
90
- - If the native module failed to load at all, later calls try again once it is installed.
91
- - If the process loaded a native module from another release, that module stays loaded and `createAgentSession()` keeps refusing sessions until the process restarts. Once the matching native module is reinstalled while the process runs, subsequent calls still throw `NativeModuleUnavailableError` and update the message to `atomic's native module was reinstalled while this process was running; restart it.`.
92
-
93
- Also restart after an in-place update if your process started on an older Atomic release or before importing `@bastani/atomic/rpc-entry` for the first time, because those transitions may not emit a restart notice.
94
-
95
- ### Migrating an existing Node host
96
-
97
- <a id="migrating-from-the-experimental-client" />
98
- <a id="experimental-harness-factory" />
99
-
100
- - **Builtins are automatic:** Remove manual registration of shipped builtin extensions; disable selectively with `builtins` and restrict tools with `tools` / `excludedTools` (`tools: []` also excludes Intercom).
101
- - **Host input:** Supply all five `HostInput` methods (`confirm`, `select`, `input`, `editor`, `questionnaire`) on `extensionBindings.humanInput`, honoring abort signals and returning literal `true` only on explicit approval (missing adapter rejects with `HumanInputUnavailable`).
102
- - **Removed `workflows` builtin:** Remove `workflows` from `builtins`; workflow SDK exports were removed. Convert older workflow files into skills ([Migrating workflows](/orchestration/migrating-workflows)).
103
- - **Always `await session.dispose()` in `finally`:** Disposal is async and may reject with `ShutdownFailed` after attempting all cleanup; do not swallow it or call `process.exit()`.
104
- - **Diagnostics & packaging:** Route operational events via `extensionBindings.onDiagnostic`. If creation throws `BuiltinUnavailable`, reinstall the full package rather than copying only `dist/index.js`.
105
- - **Removed experimental client:** `@bastani/atomic/client` was removed; use `createAgentSession()` in-process or [RPC mode](/rpc) (`--mode rpc` / `@bastani/atomic/rpc-entry`).
106
-
107
70
  ## Core concepts
108
71
 
109
- ### createAgentSession()
72
+ ### Creating a session
110
73
 
111
- Creates a single `AgentSession` with bundled subagents, MCP, web access, and Intercom enabled by default (plus normal user, project, and package discovery unless you pass a custom `resourceLoader`).
74
+ `createAgentSession()` creates an `AgentSession` with bundled subagents, MCP, web access, and Intercom enabled by default, plus standard user, project, and package discovery unless you pass a custom `resourceLoader`.
112
75
 
113
76
  ```typescript
114
77
  import { createAgentSession, SessionManager } from "@bastani/atomic";
@@ -126,9 +89,9 @@ const { session: custom } = await createAgentSession({
126
89
  });
127
90
  ```
128
91
 
129
- - **Disable builtins or tools:** Pass `builtins: { "web-access": false, intercom: false }` to disable packages. `tools: []` or `noTools: "all"` disables every tool including Intercom; `excludedTools` always wins and survives `/reload`. See [tool precedence](/sdk/reference#tools).
130
- - **Startup hooks and rebinding:** `createAgentSession()` completes extension `session_start` before returning. Pass `extensionBindings` here if startup hooks need them. Later `session.bindExtensions(...)` calls update bindings without replaying `session_start`.
131
- - **Explicit recovery:** Opening a session never auto-recovers interrupted work. Call `await session.startPendingRecovery("resume")` once ready to display output; it returns `{ replayed, dropped, completions, notices }`.
92
+ - **Disable builtins or tools:** Pass `builtins: { "web-access": false, intercom: false }` to disable bundled packages. `tools: []` or `noTools: "all"` disables every tool including Intercom. `excludedTools` always wins and survives `/reload`. See [Tools](/sdk/reference#tools) for wildcard matching and MCP retention rules.
93
+ - **Startup hooks and rebinding:** `createAgentSession()` runs extension `session_start` hooks before resolving. Pass `extensionBindings` here if startup hooks need them; later `session.bindExtensions(...)` calls update bindings without replaying `session_start`.
94
+ - **Explicit recovery:** Opening a session never recovers interrupted work automatically. Call `await session.startPendingRecovery("resume")` once ready to display output; it returns `{ replayed, dropped, completions, notices }`.
132
95
 
133
96
  ### Workspaces
134
97
 
@@ -143,13 +106,14 @@ const { session, workspace: binding } = await createAgentSession({ workspace: ap
143
106
  const reviewer = await createAgentSession({ workspace: api.readOnly() });
144
107
  ```
145
108
 
146
- - **Resolution:** Local `repo` must be a repository root. Remote repositories clone once under `<storageHome>/repos/` ([storage home](/storage#storage-home)) and create worktrees after fetching. Missing branches start at `base`; existing worktrees must match repo and branch (interrupted checkouts re-create automatically). Explicit `cwd` resolves inside the worktree, and a supplied `sessionManager` must already be inside it (`WorkspaceConfigError` otherwise).
147
- - **Read-only (`api.readOnly()`):** Removes and blocks `write`, `edit`, and `todo` even if listed in `tools`. Shell tools still run because this is not an OS sandbox. Children stay read-only even with their own workspace.
148
- - **Persistence and PRs:** Saved as a `workspace_binding` entry and restored on reopen (call `bindSessionWorkspace(workspace, sessionManager)` beforehand if you need the path early). Inspect commits with `workspaceChangeSet(binding)` and open PRs via `publishPullRequest(changeSet, { draft: true })`. Invalid options throw `WorkspaceConfigError`; binding failures throw `WorkspaceBindingError` (`wrong-branch`, `cwd-outside-worktree`, `git-unavailable`).
109
+ - **Resolution:** Local `repo` must point to a repository root. Remote repositories clone once under `<storageHome>/repos/` ([storage home](/storage#storage-home)) and create worktrees after fetching. Missing branches start from `base`; existing worktrees must match repository and branch (interrupted checkouts re-create automatically). Explicit `cwd` must stay inside the worktree, and an explicit `sessionManager` must already point inside it (`WorkspaceConfigError` otherwise).
110
+ - **Read-only (`api.readOnly()`):** Removes and blocks `write`, `edit`, and `todo` even if listed in `tools`. Shell tools still run because read-only workspaces are not an OS sandbox. Child sessions stay read-only even with their own workspace.
111
+ - **Persistence and PRs:** Bindings persist as a `workspace_binding` entry and restore on reopen (call `bindSessionWorkspace(workspace, sessionManager, signal?)` beforehand if you need the resolved path early). Inspect commits with `workspaceChangeSet(binding)` and open pull requests via `publishPullRequest(changeSet, { draft: true })`.
112
+ - **Errors:** Invalid options throw `WorkspaceConfigError`. Binding failures throw `WorkspaceBindingError` with one of these `code` values: `wrong-repository`, `wrong-branch`, `conflicting-worktree-input`, `invalid-repository`, `unknown-base`, `cwd-outside-worktree`, `git-unavailable`, `git-failed`, `filesystem-failed`, `drift`, `writer-conflict`, or `incomplete-worktree`.
149
113
 
150
114
  ### Shared resource admission
151
115
 
152
- Enforce host-wide session and process capacity caps via `resourceAdmission`:
116
+ Enforce host-wide session and process capacity caps with `resourceAdmission`:
153
117
 
154
118
  ```typescript
155
119
  import type { ResourceAdmission } from "@bastani/atomic";
@@ -168,47 +132,142 @@ const resourceAdmission: ResourceAdmission = {
168
132
  const { session } = await createAgentSession({ resourceAdmission });
169
133
  ```
170
134
 
171
- - `kind` is `"session"` or `"process"`. Make `acquire` honor `signal` (`resourceAdmissionSignal` cancels session wait; children inherit the service, not that signal) and make release functions idempotent.
172
- - **Deadlock rule (`request.delegated`):** Parents hold their session permit while children run, so **never queue** `request.delegated` acquisitions. Grant immediately or throw, and size your cap above maximum concurrent parents.
173
- - **Permit lifetime and crash recovery:** Session permits release on clean `dispose()`; managed command permits release after confirmed process cleanup (never recycle on a timer). On Unix, implement `permit.bindProcess({ kind: "unix-process-group", id })` to persist process-group identity for post-crash reconciliation (Windows commands report no identity).
174
- - **Scoping:** Wrap async flows in `withResourceAdmission(service, fn)` (explicit session service wins; `resourceAdmission: null` opts out). Child sessions from `getChildSessionOptions()` and delivered-message turns always use their own or parent service rather than a sender's scope.
135
+ - `kind` is `"session"` or `"process"`. Honor `signal` inside `acquire()` (`resourceAdmissionSignal` cancels session wait; children inherit the service, not that signal) and keep release callbacks idempotent.
136
+ - **Deadlock rule (`request.delegated`):** Parent sessions hold their session permit while children run, so never queue `request.delegated` acquisitions. Grant immediately or throw, and size capacity above your maximum concurrent parents.
137
+ - **Permit lifetime and crash recovery:** Session permits release on clean `dispose()`; managed command permits release after confirmed process cleanup. On Unix, implement `permit.bindProcess({ kind: "unix-process-group", id })` to record process-group IDs for crash reconciliation (Windows reports no process-group identity).
138
+ - **Scoping:** Wrap async flows with `withResourceAdmission(service, fn)` (explicit session service wins; `resourceAdmission: null` opts out). Child sessions always use their own or parent service rather than a sender's scope.
175
139
 
176
140
  ### Session storage
177
141
 
178
- Sessions default to `~/.atomic/workflows/journal.sqlite` (`session_` prefix). Override with `sessionStore`, `storage` (same shape as `settings.json` `storage` or `teamProfileSelection()`, see [Team and CI setup](/guides/team-setup#from-the-sdk)), or an explicit `sessionManager`:
142
+ Sessions default to local SQLite at `~/.atomic/workflows/journal.sqlite` (`session_` table prefix). Override storage per session with `sessionStore`, `storage`, or an explicit `sessionManager`:
143
+
144
+ | Backend | Package | How to pass it to `createAgentSession()` |
145
+ | --- | --- | --- |
146
+ | Local SQLite (default) | Built into `@bastani/atomic` (`@bastani/atomic/storage`) | `{ kind: "sqlite", path, prefix? }` or caller-owned `openNodeSqliteDatabase()` / `SqlSessionStore.open()` |
147
+ | JSONL directory | Built into `@bastani/atomic` | `{ kind: "jsonl", dir }` or caller-owned `JsonlSessionStore.open()` |
148
+ | In-memory | Built into `@bastani/atomic` | `new MemorySessionStore()` (caller-owned) or `{ kind: "memory" }` (discarded on `dispose()`) |
149
+ | libSQL / Turso | `@bastani/atomic-storage-libsql` | `{ kind: "adapter", module: LIBSQL_ADAPTER_PACKAGE, ... }` or caller-owned `openLibsqlDatabase()` |
150
+ | PostgreSQL (16+ for sessions) | `@bastani/atomic-storage-postgres` | `{ kind: "adapter", module: POSTGRES_ADAPTER_PACKAGE, ... }` or caller-owned `openPostgresDatabase()` |
151
+
152
+ #### Built-in backends (SQLite, JSONL, in-memory)
179
153
 
180
154
  ```typescript
181
- import { createAgentSession, MemorySessionStore, POSTGRES_ADAPTER_PACKAGE } from "@bastani/atomic";
155
+ import {
156
+ createAgentSession,
157
+ JsonlSessionStore,
158
+ MemorySessionStore,
159
+ SqlSessionStore,
160
+ } from "@bastani/atomic";
161
+ import { openNodeSqliteDatabase } from "@bastani/atomic/storage";
182
162
 
183
- // In-memory (pass a MemorySessionStore instance to keep history across session.release() / runtime.rehydrate())
184
- const memoryStore = new MemorySessionStore();
185
- const mem = await createAgentSession({ sessionStore: memoryStore });
163
+ // 1. Local SQLite file (session-owned: Atomic opens and closes it on dispose())
164
+ const sqlite = await createAgentSession({
165
+ sessionStore: { kind: "sqlite", path: "./sessions.sqlite", prefix: "project_" },
166
+ });
186
167
 
187
- // JSONL directory
168
+ // 2. JSONL directory (one JSONL file per session; session-owned)
188
169
  const jsonl = await createAgentSession({
189
170
  sessionStore: { kind: "jsonl", dir: "./sessions" },
190
171
  });
191
172
 
192
- // SQLite file
193
- const sqlite = await createAgentSession({
194
- sessionStore: { kind: "sqlite", path: "./sessions.sqlite", prefix: "project_" },
173
+ // 3. Caller-owned in-memory store (preserves history across session.release() / runtime.rehydrate())
174
+ const memoryStore = new MemorySessionStore();
175
+ const mem = await createAgentSession({ sessionStore: memoryStore });
176
+
177
+ // 4. Caller-owned SQLite or JSONL store (share across sessions; close it yourself)
178
+ const db = await openNodeSqliteDatabase("./shared.sqlite");
179
+ const sqlStore = await SqlSessionStore.open(db, { prefix: "project_" });
180
+ const jsonlStore = await JsonlSessionStore.open("./shared-jsonl");
181
+ ```
182
+
183
+ #### Remote SQL packages (`@bastani/atomic-storage-postgres` and `@bastani/atomic-storage-libsql`)
184
+
185
+ Install the adapter package alongside `@bastani/atomic` in your application (`npm install @bastani/atomic-storage-postgres` or `npm install @bastani/atomic-storage-libsql`). For CLI-resolved `{ kind: "adapter" }` loading outside `node_modules`, install in user scope with `atomic install npm:@bastani/atomic-storage-postgres` or `atomic install npm:@bastani/atomic-storage-libsql`. Both packages ship plain ESM with TypeScript declarations.
186
+
187
+ **Option A — Pass a caller-owned database handle directly (recommended for SDK hosts sharing one pool):**
188
+
189
+ ```typescript
190
+ import { readFile } from "node:fs/promises";
191
+ import { createAgentSession } from "@bastani/atomic";
192
+ import { openPostgresDatabase } from "@bastani/atomic-storage-postgres";
193
+ import { openLibsqlDatabase } from "@bastani/atomic-storage-libsql";
194
+
195
+ // PostgreSQL: pass a username-only URL (embedded passwords are rejected with credential-in-url).
196
+ // `password` accepts a string or an async callback invoked per new connection for secret rotation.
197
+ const pgDb = await openPostgresDatabase({
198
+ url: "postgresql://atomic_runtime@db.example.com:5432/atomic",
199
+ password: async () => (await readFile("/run/secrets/postgres-password", "utf8")).trim(),
195
200
  });
201
+ try {
202
+ const { session } = await createAgentSession({
203
+ sessionStore: { kind: "database", database: pgDb, prefix: "project_" },
204
+ });
205
+ try {
206
+ await session.prompt("Summarize recent commits");
207
+ } finally {
208
+ await session.dispose();
209
+ }
210
+ } finally {
211
+ await pgDb.close();
212
+ }
213
+
214
+ // libSQL / Turso:
215
+ const libsqlDb = await openLibsqlDatabase({
216
+ url: "libsql://<db>.turso.io",
217
+ authToken: process.env.TURSO_AUTH_TOKEN,
218
+ });
219
+ try {
220
+ const { session } = await createAgentSession({
221
+ sessionStore: { kind: "database", database: libsqlDb, prefix: "project_" },
222
+ });
223
+ await session.dispose();
224
+ } finally {
225
+ await libsqlDb.close();
226
+ }
227
+ ```
228
+
229
+ **Option B — Let Atomic open and close the adapter per session via `{ kind: "adapter" }`:**
230
+
231
+ ```typescript
232
+ import {
233
+ createAgentSession,
234
+ LIBSQL_ADAPTER_PACKAGE,
235
+ POSTGRES_ADAPTER_PACKAGE,
236
+ } from "@bastani/atomic";
196
237
 
197
- // PostgreSQL (install @bastani/atomic-storage-postgres)
238
+ // PostgreSQL via adapter selection (pass credentials through `secrets`, never inside `url`)
198
239
  const pg = await createAgentSession({
199
240
  sessionStore: {
200
241
  kind: "adapter",
201
242
  module: POSTGRES_ADAPTER_PACKAGE,
202
- options: { url: process.env.DATABASE_URL },
243
+ options: { url: "postgresql://atomic_runtime@db.example.com:5432/atomic" },
244
+ secrets: { password: { env: "PGPASSWORD" } },
245
+ prefix: "project_",
246
+ },
247
+ });
248
+
249
+ // libSQL / Turso via adapter selection
250
+ const libsql = await createAgentSession({
251
+ sessionStore: {
252
+ kind: "adapter",
253
+ module: LIBSQL_ADAPTER_PACKAGE,
254
+ options: { url: "libsql://<db>.turso.io" },
255
+ secrets: { authToken: { env: "TURSO_AUTH_TOKEN" } },
203
256
  prefix: "project_",
204
257
  },
205
258
  });
206
259
  ```
207
260
 
208
- - **Selections:** `{ kind: "sqlite", path, prefix? }`, `{ kind: "jsonl", dir }`, `{ kind: "memory" }`, `{ kind: "database", database, prefix? }`, `{ kind: "adapter", module, options?, secrets?, prefix? }`, or a `SessionStore` instance. Legacy `sessionDir` was removed.
209
- - **Precedence:** Resolved in order from `sessionManager`, then `sessionStore`, then `storage`, then process environment variables or flags (`ATOMIC_SESSIONS_STORAGE` and `ATOMIC_STORAGE`, see [Selecting storage per process](/storage#selecting-storage-per-process)), then settings (`sessions.storage` before `storage`, see [Session settings](/settings#sessions)), and finally default SQLite. Memory is never a fallback.
261
+ For cloud IAM authentication on PostgreSQL (`auth: "azure-entra" | "aws-iam" | "gcp-iam"`), omit `secrets.password` / `password`. Run `atomic storage migrate` as the database owner role before connecting with a least-privilege runtime role. See [Storage](/storage) for TLS, proxies, connection poolers, schema migrations, and wrapping custom drivers.
262
+
263
+ - **`sessionStore` vs. `storage` shapes:**
264
+ - `sessionStore` accepts a `SessionStore` instance (`SqlSessionStore`, `JsonlSessionStore`, `MemorySessionStore`) or a tagged selection object: `{ kind: "sqlite", path, prefix? }`, `{ kind: "jsonl", dir }`, `{ kind: "memory" }`, `{ kind: "database", database, prefix? }`, or `{ kind: "adapter", module, options?, secrets?, prefix? }`.
265
+ - `storage` uses the `settings.json` shape (also returned by `teamProfileSelection()`, see [Team and CI setup](/guides/team-setup#from-the-sdk)): `{ path, prefix? }`, `{ database, prefix? }`, `{ memory: true }`, or `{ adapter, options?, secrets?, prefix? }`. `storage` does not support JSONL; use `sessionStore: { kind: "jsonl", dir }` for JSONL directories.
266
+ - Legacy `sessionDir` was removed.
267
+ - **Precedence:** Resolved in order from `sessionManager`, `sessionStore`, `storage`, process environment/flags (`ATOMIC_SESSIONS_STORAGE` and `ATOMIC_STORAGE`; see [Selecting storage per process](/storage#selecting-storage-per-process)), settings (`sessions.storage` before `storage`; see [Session settings](/settings#sessions)), and finally default SQLite. Memory is never an automatic fallback.
268
+ - **Ownership and resume:** Atomic closes stores it opened from selection objects (`sqlite`, `jsonl`, `adapter`, `memory`) during `dispose()`, while leaving caller-owned `SessionStore`, `SessionManager`, and `database` instances open. Because session-owned `{ kind: "memory" }` and `storage: { memory: true }` stores are closed and discarded on `dispose()`, pass a caller-owned `new MemorySessionStore()` if you plan to call `session.release()` and later `runtime.rehydrate()`.
210
269
  - **Package adapters:** Pass `additionalExtensionPaths: [packageRoot]` on `DefaultResourceLoader` before opening storage to select an embedded package adapter by name ([Adapters from Atomic packages](/storage#adapters-from-atomic-packages)).
211
- - **Ownership and resume:** Atomic closes stores opened from selections during `dispose()`, leaving caller-owned `SessionStore`, `SessionManager`, and `database` instances open. Await every `SessionManager` mutation and `atomic.appendEntry`, `setSessionName`, `setLabel`, and `setThinkingLevel` call (there is no `flush()`; see [Storage errors](/storage#storage-errors)):
270
+ - **Await mutations:** Await every `SessionManager` write and every `atomic.appendEntry`, `setSessionName`, `setLabel`, `setThinkingLevel`, and `cycleThinkingLevel` call (there is no `flush()`; see [Storage errors](/storage#storage-errors)):
212
271
 
213
272
  ```typescript
214
273
  import { createAgentSession, resolveSessionStore, SessionManager } from "@bastani/atomic";
@@ -227,14 +286,11 @@ try {
227
286
  }
228
287
  ```
229
288
 
230
- `ExtensionContext.sessionSignal` aborts when reload or shutdown begins so extensions can cancel long waits while still awaiting already-started session writes.
289
+ `ExtensionContext.sessionSignal` aborts when reload or shutdown starts so extensions can cancel waits while finishing in-flight writes.
231
290
 
232
291
  ### Human input without a terminal
233
292
 
234
- <a id="binding-and-withdrawing-an-input-adapter" />
235
- <a id="diagnostics-and-provider-state" />
236
-
237
- Pass `extensionBindings.humanInput` implementing all five `HostInput` methods (`confirm`, `select`, `input`, `editor`, `questionnaire`; `QuestionParams` and `QuestionnaireResult` are exported):
293
+ Pass `extensionBindings.humanInput` implementing all five `HostInput` methods (`confirm`, `select`, `input`, `editor`, `questionnaire`; `QuestionParams` and `QuestionnaireResult` are exported from `@bastani/atomic`):
238
294
 
239
295
  ```typescript
240
296
  import { createAgentSession, type HostInput } from "@bastani/atomic";
@@ -256,28 +312,28 @@ async function attachApplication(humanInput: HostInput) {
256
312
  }
257
313
  ```
258
314
 
259
- - **Routing & abort:** Each call receives `{ requestId, sessionId, signal, timeout? }`. Route prompts by `sessionId` (children inherit explicit `humanInput`; see [Session-local task prompts](/sdk/reference#session-local-task-prompts)) and dismiss UI immediately on `signal` abort. Plain RPC clients and SDK hosts that provide only `uiContext` keep receiving child dialogs through that presentation. Setting `mode: "tui"` alone does not enable held task prompts. Abort, reload, and disposal invalidate pending replies, including late successful replies from callbacks that ignore cancellation.
260
- - **Return contracts:** `confirm` returns boolean; `select` returns a supplied option or `undefined`; `input`/`editor` return string or `undefined` (preserving whitespace/empty strings). Malformed replies reject with `InvalidHostInput`; `false`, cancellation, or errors never approve.
261
- - **Omission rules:** Omitting `humanInput` at creation leaves no input (unless `uiContext` supplies dialogs; without either, dialogs reject with `HumanInputUnavailable` and `ask_user_question` returns `{ answers: [], cancelled: true, error: "no_ui" }`). Omitting it on `bindExtensions()` keeps the current adapter; passing `null` withdraws it. `ui.custom` is not part of `HostInput`.
262
- - **Diagnostics & session-local caches:** `onDiagnostic` captures session-attributed notices (does not intercept third-party `console.*`). MCP OAuth PKCE state and web-provider config caches stay per session, while durable MCP tokens persist by server name.
315
+ - **Routing and abort:** Every method receives `{ requestId, sessionId, signal, timeout? }`. Route prompts by `sessionId` (child sessions inherit explicit `humanInput`; see [Session-local task prompts](/sdk/reference#session-local-task-prompts)) and dismiss UI immediately when `signal` aborts. Abort, reload, and disposal invalidate pending replies, including late replies from callbacks that ignored `signal`.
316
+ - **Return contracts:** `confirm` returns a boolean; `select` returns one of the supplied options or `undefined`; `input` and `editor` return a string or `undefined` (preserving whitespace and empty strings). Malformed replies reject with an `Error` tagged with `code: "InvalidHostInput"`; `false`, cancellation, and errors never approve.
317
+ - **Omission rules:** Omitting `humanInput` at creation leaves no input handler (unless `uiContext` supplies dialogs; without either, dialogs reject with an `Error` tagged with `code: "HumanInputUnavailable"` and `ask_user_question` returns `{ answers: [], cancelled: true, error: "no_ui" }`). Omitting `humanInput` on `bindExtensions()` keeps the current adapter; passing `null` withdraws it. `ui.custom` is not part of `HostInput`.
318
+ - **Diagnostics and session-local caches:** `onDiagnostic` receives session-attributed notices (it does not intercept `console.*`). MCP OAuth PKCE state and web-provider config caches remain session-local, while durable MCP tokens persist by server name.
263
319
 
264
320
  ### Stored session summaries
265
321
 
266
- Read `session.sessionSummary` (`summary` and `summarizedThroughId`) or inspect `SessionManager.list()` / `listAll()`. Stored summaries stay readable when `sessionSummary.enabled` is `false`; `SessionManager.inMemory()` never generates summaries.
322
+ Read `session.sessionSummary` (`summary` and `summarizedThroughId`) or inspect `SessionManager.list()` / `listAll()`. Stored summaries remain readable when `sessionSummary.enabled` is `false`; `SessionManager.inMemory()` never generates summaries.
267
323
 
268
324
  ### Worktree snapshots
269
325
 
270
- SQLite and adapter-backed sessions capture checkout state automatically. Passing a reopened `sessionManager` to `createAgentSession({ sessionManager })` (or `runtime.rehydrate()`) restores missing or drifted checkouts into fresh worktrees while leaving local matching checkouts untouched. If a checkout cannot be rebuilt or Git is unavailable, session resume restores the best reachable state (or continues without restoring) with a warning notice and never fails fast for `WorkspaceDriftError` or missing Git:
326
+ SQLite and adapter-backed sessions capture checkout state automatically. Passing a reopened `sessionManager` to `createAgentSession({ sessionManager })` (or `runtime.rehydrate()`) restores missing or drifted checkouts into fresh worktrees while leaving matching local checkouts untouched. If a checkout cannot be rebuilt or Git is unavailable, resume continues with a warning notice instead of failing fast:
271
327
 
272
328
  ```typescript
273
329
  import { createAgentSession, SessionManager } from "@bastani/atomic";
274
330
 
275
- const sessionManager = await SessionManager.open(store, sessionId);
331
+ const sessionManager = await SessionManager.open(store, savedSessionId);
276
332
  const { session } = await createAgentSession({ sessionManager });
277
333
  ```
278
334
 
279
- - By default in the SDK (`resume.waitForBlueprint: "tools"`), `createAgentSession` returns immediately while blueprint setup runs in the background and gates tool calls. Call `await blueprintBuildSettled(sessionId)` to wait explicitly, register `onBlueprintBuildFinished(listener)` to receive warnings, or set `resume.waitForBlueprint: "prompt"` to block startup (see [Start the first turn while the build runs](/guides/resume-on-any-machine#start-the-first-turn-while-the-build-runs)).
280
- - Override per-session snapshot settings via `createAgentSession({ snapshots: { enabled: false } })`. Exported helpers include `captureWorktreeSnapshot()`, `restoreWorktreeSnapshot()`, `verifyWorktree()`, `session.sessionManager.getWorktreeRootMappings()`, `latestResumeTimings()`, `formatResumeTimings()`, and `session.exportToJsonl()`. See [Worktree snapshots](/worktree-snapshots).
335
+ - By default in the SDK (`resume.waitForBlueprint: "tools"`), `createAgentSession()` returns immediately while blueprint setup runs in the background and gates tool calls. Call `await blueprintBuildSettled(sessionId)` to wait explicitly, register `onBlueprintBuildFinished(listener)` for warnings, or set `resume.waitForBlueprint: "prompt"` to block startup (see [Start the first turn while the build runs](/guides/resume-on-any-machine#start-the-first-turn-while-the-build-runs)).
336
+ - Override per-session snapshot settings with `createAgentSession({ snapshots: { enabled: false } })`. Exported helpers include `captureWorktreeSnapshot()`, `restoreWorktreeSnapshot()`, `verifyWorktree()`, `session.sessionManager.getWorktreeRootMappings()`, `latestResumeTimings()`, `formatResumeTimings()`, and `session.exportToJsonl()`. See [Worktree snapshots](/worktree-snapshots).
281
337
 
282
338
  ### Intercom group and reach
283
339
 
@@ -291,25 +347,34 @@ const { session } = await createAgentSession({
291
347
  await session.intercom.setReachable(["doc-1907", "doc-2011"]);
292
348
  ```
293
349
 
294
- - `group` sets the session's home group (beating `ATOMIC_INTERCOM_GROUP`, config, and project groups). `reachable` lists up to 1,000 one-way target groups (targets can reply to asks, not initiate). Subagents with `group: "x"` live under `<group>/x` and never inherit `reachable`.
295
- - `setReachable()` updates live policy on the broker and leaves newly unreachable groups. Calling it on a session created without `intercom`, or passing an empty/reserved group (`auto`) or more than 1,000 reachable groups, throws `IntercomPolicyError`.
350
+ - `group` sets the session's home group (beating `ATOMIC_INTERCOM_GROUP`, config, and project groups). `reachable` lists up to 1,000 one-way target groups (targets may reply to asks, not initiate messages). Subagents with `group: "x"` live under `<group>/x` and never inherit `reachable`.
351
+ - Group names are trimmed of surrounding whitespace, cannot be empty, cannot exceed 1,024 characters, and cannot be the reserved names `"auto"` or `"true"` (case-insensitively). Duplicates and self-references in `reachable` are removed automatically.
352
+ - `setReachable()` updates live policy on the broker and leaves newly unreachable groups. Calling it on a session created without `intercom`, or passing an invalid group name or more than 1,000 reachable groups, throws `IntercomPolicyError` (which extends `TypeError`).
296
353
 
297
354
  ### Subagent children
298
355
 
299
- Children inherit the parent's `ModelRuntime`, settings, `agentDir`, `humanInput`, and diagnostics. Working directory resolves in order: child `workspace`, then child `cwd`, then `child sessionManager.getCwd()`, then parent `cwd` or worktree.
356
+ Children inherit the parent's `ModelRuntime`, settings, `agentDir`, `scopedModels`, `fallbackModels`, `customTools`, `resourceAdmission`, `humanInput`, and diagnostics. Working directory resolves in order: child `workspace`, child `cwd`, child `sessionManager.getCwd()`, then parent `cwd` or worktree.
300
357
 
301
358
  - Child tool lists can only narrow parent permissions, never expand them (`builtins`, `excludedTools`, `tools: []`, and `noTools: "all"` stay enforced).
302
359
  - Pass explicit child `extensionBindings.humanInput` to override (or `null` to withdraw). Shared callbacks distinguish children by `sessionId`.
303
360
 
304
- ### AgentSession
361
+ ### Driving a session
305
362
 
306
- Core session handle for prompting, queueing, model switching, events, compaction, and disposal:
363
+ `AgentSession` is the handle for prompting, queueing, model switching, events, compaction, and disposal:
307
364
 
308
365
  ```typescript
309
366
  interface AgentSession {
310
367
  prompt(text: string, options?: PromptOptions): Promise<void>;
311
- steer(text: string): Promise<void>;
312
- followUp(text: string): Promise<void>;
368
+ steer(
369
+ text: string,
370
+ images?: ImageContent[],
371
+ options?: Pick<PromptOptions, "source" | "expandPromptTemplates">,
372
+ ): Promise<"handled" | "queued">;
373
+ followUp(
374
+ text: string,
375
+ images?: ImageContent[],
376
+ options?: Pick<PromptOptions, "source" | "expandPromptTemplates">,
377
+ ): Promise<"handled" | "queued">;
313
378
  readonly queuedMessagesPaused: boolean;
314
379
  pauseQueuedMessages(): void;
315
380
  resumeQueuedMessages(): Promise<boolean>;
@@ -319,20 +384,23 @@ interface AgentSession {
319
384
 
320
385
  sessionFile: string | undefined;
321
386
  sessionId: string;
322
- setModel(model: Model, options?: { persist?: boolean; thinkingLevel?: ThinkingLevel }): Promise<void>;
323
- setThinkingLevel(level: ThinkingLevel): void;
324
- cycleModel(): Promise<ModelCycleResult | undefined>;
325
- cycleThinkingLevel(): ThinkingLevel | undefined;
387
+ setModel(model: Model<Api>, options?: { persist?: boolean; thinkingLevel?: ThinkingLevel }): Promise<void>;
388
+ setThinkingLevel(level: ThinkingLevel, options?: { persist?: boolean }): Promise<void>;
389
+ cycleModel(direction?: "forward" | "backward", options?: { persist?: boolean }): Promise<ModelCycleResult | undefined>;
390
+ cycleThinkingLevel(options?: { persist?: boolean }): Promise<ThinkingLevel | undefined>;
326
391
 
327
392
  agent: Agent;
328
393
  sessionManager: SessionManager;
329
394
  refreshContext(): void;
330
- model: Model | undefined;
395
+ model: Model<Api> | undefined;
331
396
  thinkingLevel: ThinkingLevel;
332
397
  messages: AgentMessage[];
333
398
  isStreaming: boolean;
334
399
 
335
- navigateTree(targetId: string, options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string }): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;
400
+ navigateTree(
401
+ targetId: string,
402
+ options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },
403
+ ): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;
336
404
  compact(options?: SessionCompactOptions): Promise<VerbatimCompactionResult>;
337
405
  abortCompaction(): void;
338
406
  abort(options?: { pauseQueuedMessages?: boolean }): Promise<void>;
@@ -340,7 +408,7 @@ interface AgentSession {
340
408
  }
341
409
  ```
342
410
 
343
- **Clean stop and disposal:** Always `await session.dispose()` in `finally` (60 s drain limit; rejects with `ShutdownFailed` carrying `errors` if a step stalls). To abort active work before disposing without letting background notices start a new turn, pass `{ pauseQueuedMessages: true }`:
411
+ **Clean stop and disposal:** Always `await session.dispose()` in `finally` (60 s drain limit). If any cleanup step fails or stalls, `dispose()` rejects with an `AggregateError` tagged with `code: "ShutdownFailed"` (inspect `error.errors` for the individual causes). Pass `{ pauseQueuedMessages: true }` when aborting before disposal so arriving background notices do not launch another turn:
344
412
 
345
413
  ```typescript
346
414
  try {
@@ -351,12 +419,12 @@ try {
351
419
  }
352
420
  ```
353
421
 
354
- - `setModel(model, { thinkingLevel: "high", persist: true })` clamps unsupported thinking levels and optionally saves global defaults (project overrides still win at startup).
355
- - Extension APIs reject new actions once close or reload begins; give `atomic.exec()` calls timeouts or abort signals. Custom messages with `persistWhenStreaming: true` survive reload.
422
+ - `setModel(model, { thinkingLevel: "high", persist: true })` clamps unsupported thinking levels and optionally writes global defaults (project overrides still win at startup).
423
+ - Extension APIs reject new actions with an `Error` tagged with `code: "SessionClosed"` once close or reload starts. Give `atomic.exec()` calls timeouts or abort signals. Custom messages with `persistWhenStreaming: true` survive reload.
356
424
 
357
425
  #### Event subscriptions
358
426
 
359
- Subscribe a session to external event streams without polluting main context (`maxConcurrent` default `4`, optional `name` and `maxRate`):
427
+ Subscribe a session to external event streams without cluttering main context (`maxConcurrent` default `4`, optional `name` and `maxRate`):
360
428
 
361
429
  ```typescript
362
430
  import { githubReviews } from "@bastani/atomic";
@@ -371,54 +439,32 @@ const subscription = session.subscribe(
371
439
  // later: await subscription.close();
372
440
  ```
373
441
 
374
- - `child.task({ prompt, model?, thinkingLevel?, tools?, noTools?, excludedTools? })` runs a short-lived in-process child (`<name>#<n>/<eventId>`) with `report_to_subscriber` (call `child.report()` directly if `noTools: "all"`), returning `{ text, sessionId }`. Disposing the session aborts children (`AbortError`, with cleanup errors in `cleanupCause`); sessions not built via `createAgentSession()` fail with `SubscriptionChildUnavailableError`.
442
+ - `child.task({ prompt, model?, thinkingLevel?, tools?, noTools?, excludedTools? })` runs a short-lived child session (`<name>#<n>/<eventId>`) equipped with `report_to_subscriber` (call `child.report()` directly if `noTools: "all"`), returning `{ text, sessionId }`. Disposing the parent aborts children (`AbortError`, with cleanup errors in `cleanupCause`); sessions not created by `createAgentSession()` fail with `SubscriptionChildUnavailableError`.
375
443
  - `child.report(text)` sends an `event_report` custom message (`details: { subscriptionId, eventId, child }`), persisted before returning if streaming.
376
- - Deduplication uses transcript entries (`event_subscription_child`, up to 500 chars); persistence errors reject `subscription.done` with `SubscriptionRecordError`. Pass `subscription.id` to `publishEvent()` to bridge custom webhooks.
377
-
378
- #### Finishing admitted work
444
+ - Deduplication records processed event IDs in `event_subscription_processed` entries, and finished child answers are stored in `event_subscription_child` entries (up to 500 chars). Persistence failures reject `subscription.done` with `SubscriptionRecordError`. Pass `subscription.id` to `publishEvent()` to bridge custom webhooks.
379
445
 
380
- Disposal and reload drain admitted callbacks, refreshes, and `atomic.exec()` subprocesses. Always register cleanup before acquiring resources, pass timeouts/signals to subprocesses, unsubscribe `atomic.events.on()` listeners when done, and never await disposal from inside a cleanup handler.
446
+ #### Draining work on reload and shutdown {#finishing-admitted-work}
381
447
 
382
- #### Reload failures and resource ownership
448
+ Disposal and reload drain admitted callbacks, model refreshes, and `atomic.exec()` subprocesses. Register cleanup before acquiring resources, pass timeouts or abort signals to subprocesses, unsubscribe `atomic.events.on()` listeners when finished, and never await disposal from inside a cleanup handler.
383
449
 
384
- - **Transactional vs. ordinary reload:** Failed transactional reloads keep the previous generation usable; failed ordinary reloads do not. Both clean up newly acquired resources and report cleanup errors via `ShutdownFailed`.
385
- - **Lifecycle effects:** Acquire resources in `session_start` (or register `session_shutdown` immediately if acquired earlier). Use `publishExtensionContextEffect(ctx, effect)` (default `"start"` phase after retirement, or synchronous `"commit"` phase before revocation) to publish shared state only on commit, and `registerExtensionContextRetirementEffect(ctx, dispose)` for synchronous pre-revocation cleanup. Never cache `ctx.ui` across reloads.
386
-
387
- ```typescript
388
- import { publishExtensionContextEffect, type ExtensionFactory } from "@bastani/atomic";
389
-
390
- const extension: ExtensionFactory = (atomic) => {
391
- atomic.on("session_start", (_event, ctx) =>
392
- publishExtensionContextEffect(ctx, () => {
393
- atomic.events.emit("example:session-ready", { sessionId: ctx.sessionManager.getSessionId() });
394
- }),
395
- );
396
- };
397
- ```
398
-
399
- #### Session replacement and deferred cleanup
400
-
401
- - `await runtime.dispose()` rejects new replacements, drains pending work, waits up to 3 s for in-flight OAuth token refreshes, and cancels/waits for Intercom broker startup. Pass `{ fromSignal: true }` on `SIGTERM`/`SIGHUP` so `session_shutdown` handlers see it.
402
- - Extension commands awaiting `ctx.newSession()`, `ctx.fork()`, `ctx.switchSession()`, or `session.reload()` keep their generation alive until the command finishes; always switch to the new generation's APIs afterward.
403
-
404
- <a id="settings-failures-and-operation-ids" />
405
-
406
- - Unrecovered `persist: true` settings write failures make `dispose()` reject with `ShutdownFailed`. `executeBash()` IDs are correlation IDs: `abortBash(id)` cancels all active calls with that ID.
450
+ - `await runtime.dispose()` rejects new replacements, drains pending work, waits up to 3 s for in-flight OAuth token refreshes, and stops Intercom broker startup. Pass `{ fromSignal: true }` on `SIGTERM` or `SIGHUP` so `session_shutdown` handlers receive the signal flag.
451
+ - Unrecovered `persist: true` settings write failures cause `dispose()` to reject with `AggregateError` (`code: "ShutdownFailed"`). `executeBash()` IDs are correlation IDs: `abortBash(id)` cancels all active calls sharing that ID.
452
+ - For transactional reload lifecycle effects (`publishExtensionContextEffect`, `registerExtensionContextRetirementEffect`), see [Reload lifecycle and resource ownership](/sdk/reference#reload-lifecycle-and-resource-ownership).
407
453
 
408
454
  #### Compaction and tree navigation
409
455
 
410
- `session.compact({ query?, compactionModel? })` stops active runs, clears context (or summarizes with an exact compactor model like `morph/morph-compactor`), appends a `verbatim-lines` `compaction` entry, and returns `VerbatimCompactionResult` (`form: "cleared" | "compacted"`). Rejects with `Nothing to compact` when nothing new entered context; concurrent calls coalesce. A chat, classifier or unknown `compactionModel` ID clears the context with a notice instead of failing. `compression_ratio` and `preserve_recent` are no longer options; they are ignored if passed. See [Compaction](/compaction) and [Session format](/session-format#compactionentry).
456
+ `session.compact({ query?, compactionModel? })` stops active runs, clears context (or summarizes with a configured compactor model such as `morph/morph-compactor`), appends a `verbatim-lines` `compaction` entry, and returns `VerbatimCompactionResult` (`form: "cleared" | "compacted"`). Rejects with `Nothing to compact` when nothing new entered context; concurrent calls coalesce. A chat, classifier, or unknown `compactionModel` ID clears the context with a notice instead of failing. See [Compaction](/compaction) and [Session format](/session-format#compactionentry).
411
457
 
412
458
  ```typescript
413
459
  const result = await session.compact({ query: "keep the auth decisions" });
414
460
  console.log(result.form, result.history?.boundaryEntry);
415
461
  ```
416
462
 
417
- `session.navigateTree()` rejects if streaming, compacting, or summarizing a branch (leaving the branch unchanged).
463
+ `session.navigateTree()` rejects if the session is currently streaming, compacting, or summarizing a branch, leaving the active branch unchanged.
418
464
 
419
- ### createAgentSessionRuntime() and AgentSessionRuntime
465
+ ### Replacing and rehydrating sessions
420
466
 
421
- Use `AgentSessionRuntime` when your host needs session replacement (`newSession()`, `switchSession()`, `fork()`, clone via `fork(entryId, { position: "at" })`, `importFromJsonl()`) with rebuilt cwd-bound services:
467
+ Use `createAgentSessionRuntime()` and `AgentSessionRuntime` when your host needs session replacement (`newSession()`, `switchSession()`, `fork()`, clone via `fork(entryId, { position: "at" })`, `importFromJsonl()`) with rebuilt working-directory services:
422
468
 
423
469
  ```typescript
424
470
  import {
@@ -446,11 +492,11 @@ const runtime = await createAgentSessionRuntime(createRuntime, {
446
492
  });
447
493
  ```
448
494
 
449
- After any replacement, `runtime.session` points to the new instance. Re-subscribe to events, call `bindExtensions()` again, and call `startPendingRecovery("resume")` after `switchSession()`.
495
+ After any replacement, `runtime.session` points to the new session. Re-subscribe to events, call `bindExtensions()` again, and call `startPendingRecovery("resume")` after `switchSession()`.
450
496
 
451
497
  ### Releasing idle sessions
452
498
 
453
- Free in-memory resources (agent loop, extensions, tools, timers, MCP/Intercom connections) for idle conversations with `session.release()`, and restore on demand with `runtime.rehydrate(sessionId)`:
499
+ Free in-memory resources (agent loop, extensions, tools, timers, MCP and Intercom connections) for idle conversations with `session.release()`, and restore them on demand with `runtime.rehydrate(sessionId)`:
454
500
 
455
501
  ```typescript
456
502
  const released = await session.release(); // { sessionId, cwd, sessionFile? }
@@ -459,17 +505,17 @@ await live.prompt("Here is the CI result you were waiting for.");
459
505
  await live.release();
460
506
  ```
461
507
 
462
- - **Auto-release:** Pass `releaseWhenIdle: { afterMs }` (`0` to `2147483647` ms; invalid values throw `AgentReleaseConfigError`) to `createAgentSession()` or `createAgentSessionFromServices()`. Driven by the process-wide `agentWakeDispatcher()` (`handle`, `deliver`, `onUnobservedFailure`, `whenIdle`, `stats()`).
508
+ - **Auto-release:** Pass `releaseWhenIdle: { afterMs }` (`0` to `2,147,483,647` ms; invalid values throw `AgentReleaseConfigError`) to `createAgentSession()` or `createAgentSessionFromServices()`. If the session is still busy when the timer fires, Atomic reschedules for another `afterMs` instead of failing. Managed by the process-wide `agentWakeDispatcher()` (`handle`, `deliver`, `onUnobservedFailure`, `whenIdle`, `stats()`).
463
509
  - **Lifecycle:** Emits `session_released` before closing. Rejects with retryable `session-busy` if streaming, compacting, running shells or background tasks, or holding queued messages. `rehydrate()` opens at the current context window (`readHistory()` and `readEntry()` fetch older entries), shares matching-cwd `services`, runs alongside `runtime.session` without replacing it, deduplicates concurrent calls, and closes on `runtime.dispose()`.
464
- - **In-memory store spilling:** Releasing a session in a host-owned `{ kind: "memory" }` store spills history to private owner-only files (`0700`/`0600`) under `<agentDir>/released-history/` with integrity verification (`SessionSpillError` on missing or corrupt files; see [Storage errors](/storage#storage-errors)). Files are cleaned up on exit and swept on restart after crashes; worker-only hosts must close stores before `worker.terminate()`. Custom stores can implement `releaseSession(id)`, `readEntryRange(id, query)`, and `readForkWindow(id, entryId)`.
510
+ - **In-memory store spilling:** Releasing a session stored in a caller-owned `MemorySessionStore` spills history to private owner-only files (`0700`/`0600`) under `<agentDir>/released-history/` with integrity verification (`SessionSpillError` on missing or corrupt files; see [Storage errors](/storage#storage-errors)). Files clean up on exit and sweep on restart after crashes; worker-only hosts must close stores before `worker.terminate()`. Custom stores can implement `releaseSession(id)`, `readEntryRange(id, query)`, and `readForkWindow(id, entryId)`.
465
511
 
466
512
  Release and wake errors throw `AgentRehydrateError` (guards `isAgentRehydrateError`, `isAgentReleaseConfigError`, `isRetryableAgentRehydrateError`; cross-process `serializeAgentRehydrateError` and `rehydrateAgentRehydrateError`):
467
513
 
468
514
  | Class | `code` | When | Fields | What to do |
469
515
  | --- | --- | --- | --- | --- |
470
- | `AgentReleaseConfigError` | `invalid-release-policy` | Invalid `releaseWhenIdle.afterMs` (must be `0` to `2147483647`). | `source`, `field`, `value` | Fix the option. |
516
+ | `AgentReleaseConfigError` | `invalid-release-policy` | Invalid `releaseWhenIdle.afterMs` (must be `0` to `2,147,483,647`). | `source`, `field`, `value` | Fix the option. |
471
517
  | `AgentRehydrateError` | `session-busy` | `release()` called while active work or queued messages remain (`retryable: true`). | `sessionId`, `activity` | Wait for `agent_settled` or background tasks, then retry. |
472
- | `AgentRehydrateError` | `not-reopenable` | Session uses private `SessionManager.inMemory()`. | `sessionId`, `storage` | Use SQLite, JSONL, or a host-owned `MemorySessionStore`. |
518
+ | `AgentRehydrateError` | `not-reopenable` | Session uses private `SessionManager.inMemory()` or a session-owned memory store. | `sessionId`, `storage` | Use SQLite, JSONL, or a caller-owned `MemorySessionStore`. |
473
519
  | `AgentRehydrateError` | `session-not-found` | Session missing in this node's storage. | `sessionId`, `storage`, `localOnly` | Verify ID, or join shared storage (`atomic storage join`). |
474
520
  | `AgentRehydrateError` | `no-wake-handler` | Wake delivered to unregistered namespace. | `wakeKey`, `namespace` | Register handler with `handle()` first. |
475
521
  | `AgentRehydrateError` | `wake-handler-conflict` | Duplicate handler for namespace. | `namespace` | Dispose existing handler first. |
@@ -489,28 +535,25 @@ interface PromptOptions {
489
535
  }
490
536
  ```
491
537
 
492
- - **Basic vs. streaming prompts:** `prompt()` expands file-based prompt templates and executes extension commands immediately even while streaming. Calling `prompt()` while streaming without `streamingBehavior` throws `AgentSessionBusyError` (`code: "agent_session_busy"`, guard `isAgentSessionBusyError`). Prompts arriving during compaction queue automatically.
493
- - **`startTurnOnly`:** When `true`, `prompt()` starts a turn only if the session is idle and queued messages are not paused; otherwise it sends and queues nothing and resolves as `"handled"`.
538
+ - **Basic vs. streaming prompts:** `prompt()` expands file-based prompt templates and runs extension commands immediately even while streaming. Calling `prompt()` while streaming without `streamingBehavior` throws `AgentSessionBusyError` (`code: "agent_session_busy"`, guard `isAgentSessionBusyError`). Prompts arriving during compaction queue automatically.
539
+ - **`startTurnOnly`:** When `true`, `prompt()` starts a turn only if the session is idle and queued messages are not paused. Otherwise it sends and queues nothing, calls `preflightResult(true, "handled")`, and resolves with `undefined`.
494
540
  - **`preflightResult(success, disposition?)`:** Fires once before `prompt()` settles (`true` with `"handled"`, `"queued"`, or `"started"`; `false` on preflight rejection).
495
- - **`steer()` and `followUp()`:** Queue during streaming (or start a turn immediately if idle with existing messages; stay queued on empty or aborted sessions), return `"queued"` or `"handled"`, expand templates, and reject extension commands.
496
- - **Queue control:** `clearQueue()` returns `{ steering, followUp, typed?, images? }` (`typed` keeps pre-hook raw text so re-submitting does not double-run hooks). `pauseQueuedMessages()` holds queues across an abort boundary; `resumeQueuedMessages()` releases the hold once (returning `true` if held work existed) without starting a turn.
541
+ - **`steer()` and `followUp()`:** Accept `(text, images?, options?)` and return `Promise<"handled" | "queued">`. They queue during streaming (or start a turn immediately if idle with existing messages; stay queued on empty or aborted sessions), expand templates, and reject extension commands.
542
+ - **Queue control:** `clearQueue()` returns `{ steering, followUp, typed?, images? }` (`typed` preserves pre-hook text so re-submitting does not re-run hooks). `pauseQueuedMessages()` holds queues across an abort boundary; `resumeQueuedMessages()` releases the hold once (returning `true` if held work existed) without starting a turn.
497
543
 
498
544
  ### Agent and AgentState
499
545
 
500
- Access the underlying [`@bastani/atomic-agent-core`](/libraries/agent-core) `Agent` via `session.agent` (`state.messages`, `model`, `thinkingLevel`, `systemPrompt`, `tools`, `streamingMessage`, `errorMessage`, and `waitForIdle()`).
501
-
502
- `session.sessionManager` is the source of truth for model context. Never assign `session.agent.state.messages` to restore history. Instead, initialize `SessionManager.inMemory(cwd, { id }, entries)` before `createAgentSession()`, use `session.navigateTree()`, or call `session.sessionManager.appendMessage()` followed by `session.refreshContext()`.
546
+ Access the underlying [`@bastani/atomic-agent-core`](/libraries/agent-core) `Agent` through `session.agent` (`state.messages`, `model`, `thinkingLevel`, `systemPrompt`, `tools`, `streamingMessage`, `errorMessage`, and `waitForIdle()`).
503
547
 
504
- <a id="events" />
505
- <a id="collecting-assistant-output" />
548
+ `session.sessionManager` is the source of truth for model context. Never mutate `session.agent.state.messages` directly to restore history. Instead, pass entries to `SessionManager.inMemory(cwd, { id }, entries)` before `createAgentSession()`, call `session.navigateTree()`, or append via `session.sessionManager.appendMessage()` followed by `session.refreshContext()`.
506
549
 
507
550
  ### Events and transcript collection
508
551
 
509
- Subscribe with `session.subscribe((event) => ...)` for `message_start`/`message_update`/`message_end`, `tool_execution_start`/`update`/`end`, `agent_start`/`end`, `turn_start`/`end`, `queue_update`, `compaction_start`/`end`, and retry events. Do not mutate or append deltas onto `message_start`'s live partial object (it updates in place; seed mid-turn subscribers from `session.agent.state.streamingMessage`).
552
+ Subscribe with `session.subscribe((event) => ...)` for `message_start`/`message_update`/`message_end`, `tool_execution_start`/`update`/`end`, `agent_start`/`end`/`settled`, `turn_start`/`end`, `queue_update`, `compaction_start`/`end`, and retry events. Never mutate `message_start`'s live partial object (seed mid-turn subscribers from `session.agent.state.streamingMessage`).
510
553
 
511
- Use `createTranscript()` to collect ordered JSON-serializable parts (`text`, `thinking`, and `toolCall` with `result`). Pass `toolResult: (name) => "details" | "content"` to choose structured details over text; redacted thinking is omitted, and nested tool events (`parentToolCallId`) are ignored.
554
+ Use `createTranscript()` to collect ordered JSON-serializable parts (`text`, `thinking`, and `toolCall` with `result`). Pass `toolResult: (name) => "details" | "content"` to prefer structured details over text; redacted thinking is omitted, and nested tool events (`parentToolCallId`) are ignored.
512
555
 
513
- A `toolCall` part gets its `result` (`isError`, `isPartial`) once the tool reports progress or finishes, with `isPartial: true` until completion. If the message fails or is aborted, unfinished tool calls receive an error result carrying the error message:
556
+ A `toolCall` part receives its `result` (`isError`, `isPartial`) once the tool emits progress or finishes, with `isPartial: true` until completion. If the message fails or aborts, unfinished tool calls receive an error result carrying the error message:
514
557
 
515
558
  ```typescript
516
559
  import { createTranscript } from "@bastani/atomic";
@@ -600,39 +643,38 @@ try {
600
643
  }
601
644
  ```
602
645
 
603
- ## RPC mode alternative
604
-
605
- For non-Node languages or process isolation, run `atomic --mode rpc --no-session` over stdin/stdout instead of embedding the SDK. See [RPC](/rpc).
606
-
607
- <a id="options-reference" />
608
- <a id="directories" />
609
- <a id="model" />
610
- <a id="model-catalog-persistence-and-refresh" />
611
- <a id="api-keys-and-oauth" />
612
- <a id="system-prompt" />
613
- <a id="tools" />
614
- <a id="bash-tool-behavior" />
615
- <a id="waiting-for-existing-shell-tasks" />
616
- <a id="powershell-tool-behavior" />
617
- <a id="tools-with-custom-cwd" />
618
- <a id="custom-tools" />
619
- <a id="structured-output-final-results" />
620
- <a id="extensions" />
621
- <a id="skills" />
622
- <a id="context-files" />
623
- <a id="slash-commands" />
624
- <a id="session-management" />
625
- <a id="settings-management" />
626
- <a id="resourceloader" />
627
- <a id="return-value" />
628
- <a id="run-modes" />
629
- <a id="interactivemode" />
630
- <a id="runprintmode" />
631
- <a id="runrpcmode" />
632
- <a id="exports" />
633
- <a id="owner-bound-task-supervisor-s1" />
634
- <a id="supervised-command-sdk" />
635
- <a id="task-transcript-references" />
646
+ ## Runtime notes and errors
647
+
648
+ ### Error classes vs. `.code`-tagged errors
649
+
650
+ - **`NativeModuleUnavailableError` is exported from `@bastani/atomic`** (`code: "NativeModuleUnavailable"`). `createAgentSession()` throws it when `@bastani/atomic-natives` cannot load or came from a different Atomic release.
651
+ - **`ShutdownFailed`, `HumanInputUnavailable`, `InvalidHostInput`, `BuiltinUnavailable`, and `SessionClosed` are NOT exported classes.** They are standard `Error` (or `AggregateError` for `ShutdownFailed`) instances tagged with string `.code` properties. Check `(error as { code?: string }).code === "HumanInputUnavailable"` (and `error instanceof AggregateError` for `ShutdownFailed`) rather than `instanceof`.
652
+
653
+ ### Node 22 hosts
654
+
655
+ Atomic requires Node.js 22.19 or newer. On Node 22, `AsyncLocalStorage` uses promise hooks, which add small per-`await` overhead across the process once a session has run (Node 24 and Bun have no such overhead). Atomic stores all session context in one store so overhead stays flat regardless of active session count.
656
+
657
+ To switch Node 22 to Node 24's faster `AsyncLocalStorage` implementation, launch your host with `node --experimental-async-context-frame`. Pass the flag on your host command line, not in `NODE_OPTIONS` (Node 24+ rejects the flag, and tool subprocesses inherit `NODE_OPTIONS`). Verify that your own code does not depend on Node 22 `AsyncLocalStorage.disable()` behavior.
658
+
659
+ ### Updating Atomic while your program runs
660
+
661
+ When `npm install`, `pnpm add`, or `bun add` replaces `@bastani/atomic` while a Node.js host is running, modules already loaded remain in memory while newly imported modules load from disk.
662
+
663
+ `createAgentSession()` verifies `@bastani/atomic-natives` before opening a session and throws `NativeModuleUnavailableError` when it cannot load or does not match the running release:
664
+
665
+ - If the native module was missing on disk, later calls retry once installed.
666
+ - If a native module from another release was already loaded, `createAgentSession()` continues throwing `NativeModuleUnavailableError` until the process restarts (updating its message once the matching release is reinstalled).
667
+
668
+ Also restart after an in-place update if your process launched on an older Atomic release or before importing `@bastani/atomic/rpc-entry`.
669
+
670
+ ### Migrating an existing Node host
671
+
672
+ - **Builtins load automatically:** Remove manual registration of shipped builtin extensions; disable selectively with `builtins` and restrict tools with `tools` / `excludedTools` (`tools: []` excludes Intercom too).
673
+ - **Host input:** Supply all five `HostInput` methods (`confirm`, `select`, `input`, `editor`, `questionnaire`) on `extensionBindings.humanInput`, honoring abort signals and returning literal `true` only on explicit approval (omission rejects with `code: "HumanInputUnavailable"`).
674
+ - **Removed `workflows` builtin:** Remove `workflows` from `builtins`; workflow SDK exports were removed. Convert older workflow files into skills ([Migrating workflows](/orchestration/migrating-workflows)).
675
+ - **Always `await session.dispose()` in `finally`:** Disposal is async and may reject with `AggregateError` (`code: "ShutdownFailed"`) after attempting all cleanup; do not swallow it or call `process.exit()`.
676
+ - **Diagnostics and packaging:** Capture operational events via `extensionBindings.onDiagnostic`. If creation fails with `code: "BuiltinUnavailable"`, reinstall the full package rather than copying only `dist/index.js`.
677
+ - **Removed experimental client:** `@bastani/atomic/client` was removed; embed `createAgentSession()` directly or drive [RPC mode](/rpc) (`--mode rpc` / `@bastani/atomic/rpc-entry`).
636
678
 
637
679
  ## API reference
638
680