@bastani/atomic 0.10.9 → 0.10.10-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (406) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +226 -163
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +27 -12
  7. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js.map +1 -1
  8. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +47 -7
  9. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js.map +1 -1
  10. package/dist/_shared/mode-shared-2QJSCUM6.js +48 -19
  11. package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -1
  12. package/dist/_shared/{p1a-prewarm-UQY3X2UK.js → p1a-prewarm-XIU57JHF.js} +5 -5
  13. package/dist/_shared/{p1a-prewarm-UQY3X2UK.js.map → p1a-prewarm-XIU57JHF.js.map} +1 -1
  14. package/dist/_shared/p2-shell-main-B2WIALFD.js +30 -25
  15. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  16. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  17. package/dist/_shared/{sdk-OSBEPR3Q.js → sdk-RRLVN7ER.js} +15 -9
  18. package/dist/_shared/sdk-RRLVN7ER.js.map +1 -0
  19. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  20. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  21. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +4 -1
  22. package/dist/_shared/settings-startup-8-DNZ2RIHM.js.map +1 -1
  23. package/dist/_shared/{startup-0-0-TYUFUOJZ.js → startup-0-0-4VG2G44V.js} +427 -33
  24. package/dist/_shared/startup-0-0-4VG2G44V.js.map +1 -0
  25. package/dist/_shared/{startup-0-1-W2G2UY7R.js → startup-0-1-XTIL65D4.js} +18 -11
  26. package/dist/_shared/startup-0-1-XTIL65D4.js.map +1 -0
  27. package/dist/_shared/{startup-0-2-UXBUEOXW.js → startup-0-2-27OWFHV6.js} +150 -62
  28. package/dist/_shared/startup-0-2-27OWFHV6.js.map +1 -0
  29. package/dist/_shared/startup-0-3-T4DVFYWX.js +15 -25
  30. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +1 -1
  31. package/dist/_shared/{startup-0-4-HN5EB4K7.js → startup-0-4-ZMJV547D.js} +81 -12
  32. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -0
  33. package/dist/_shared/startup-0-5-FD2P735I.js +90 -50
  34. package/dist/_shared/startup-0-5-FD2P735I.js.map +1 -1
  35. package/dist/_shared/startup-10-0-TDQNBDDL.js +5 -5
  36. package/dist/_shared/startup-12-0-55AAXBJZ.js +13 -7
  37. package/dist/_shared/startup-12-0-55AAXBJZ.js.map +1 -1
  38. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -4
  39. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  40. package/dist/_shared/startup-15-1-4S7FLMNG.js +88 -28
  41. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  42. package/dist/_shared/startup-8-0-34CBHPZH.js +5 -5
  43. package/dist/_shared/startup-8-1-4KANEHRA.js +61 -17
  44. package/dist/_shared/startup-8-1-4KANEHRA.js.map +1 -1
  45. package/dist/_shared/storage-command-7MGXLJGZ.js +4 -4
  46. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  47. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  48. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  49. package/dist/builtin/intercom/README.md +87 -116
  50. package/dist/builtin/intercom/broker/broker.bundle.mjs +3 -3
  51. package/dist/builtin/intercom/broker/presence-handler.ts +1 -1
  52. package/dist/builtin/intercom/group.ts +7 -3
  53. package/dist/builtin/intercom/index.bundle.mjs +1 -1
  54. package/dist/builtin/intercom/package.json +1 -1
  55. package/dist/builtin/mcp/README.md +61 -27
  56. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  57. package/dist/builtin/mcp/package.json +1 -1
  58. package/dist/builtin/subagents/CHANGELOG.md +8 -0
  59. package/dist/builtin/subagents/README.md +74 -141
  60. package/dist/builtin/subagents/package.json +1 -1
  61. package/dist/builtin/subagents/src/extension/index.bundle.mjs +213 -74
  62. package/dist/builtin/web-access/CHANGELOG.md +9 -0
  63. package/dist/builtin/web-access/README.md +61 -88
  64. package/dist/builtin/web-access/index.bundle.mjs +387 -351
  65. package/dist/builtin/web-access/package.json +1 -1
  66. package/dist/cli/args.js +2 -2
  67. package/dist/cli/auth-cli.code.js +4 -4
  68. package/dist/cli/auth-cli.impl.js +3 -3
  69. package/dist/cli/auth-cli.js +3 -3
  70. package/dist/cli/blueprint-command.code.js +2 -2
  71. package/dist/cli/blueprint-command.impl.js +3 -3
  72. package/dist/cli/blueprint-command.js +3 -3
  73. package/dist/cli/intercom-command.code.js +3 -3
  74. package/dist/cli/intercom-command.impl.js +3 -3
  75. package/dist/cli/intercom-command.js +3 -3
  76. package/dist/cli/list-models.code.js +3 -3
  77. package/dist/cli/list-models.impl.js +3 -3
  78. package/dist/cli/list-models.js +3 -3
  79. package/dist/cli/session-picker.code.js +2 -2
  80. package/dist/cli/session-picker.impl.js +3 -3
  81. package/dist/cli/session-picker.js +3 -3
  82. package/dist/cli/startup-ui.code.js +2 -2
  83. package/dist/cli/startup-ui.impl.js +3 -3
  84. package/dist/cli/startup-ui.js +3 -3
  85. package/dist/cli/storage-command.impl.js +3 -3
  86. package/dist/cli/storage-command.js +3 -3
  87. package/dist/cli/storage-search-session.code.js +2 -2
  88. package/dist/cli/storage-search-session.impl.js +3 -3
  89. package/dist/cli/storage-search-session.js +3 -3
  90. package/dist/cli/team-command.code.js +2 -2
  91. package/dist/cli/team-command.impl.js +3 -3
  92. package/dist/cli/team-command.js +3 -3
  93. package/dist/cli.js +2 -2
  94. package/dist/core/agent-session-methods.d.ts +4 -1
  95. package/dist/core/agent-session-methods.js.map +1 -1
  96. package/dist/core/agent-session.d.ts +3 -0
  97. package/dist/core/compaction/compactor.d.ts +20 -14
  98. package/dist/core/compaction/errors.d.ts +120 -0
  99. package/dist/core/compaction/index.d.ts +1 -0
  100. package/dist/core/compaction/model-resolver.d.ts +2 -2
  101. package/dist/core/debug.impl.js +3 -3
  102. package/dist/core/debug.js +3 -3
  103. package/dist/core/export-html/card-projection.impl.js +3 -3
  104. package/dist/core/export-html/card-projection.js +3 -3
  105. package/dist/core/export-html/index.code.js +2 -2
  106. package/dist/core/export-html/index.impl.js +3 -3
  107. package/dist/core/export-html/index.js +3 -3
  108. package/dist/core/export-html/json-spans.impl.js +3 -3
  109. package/dist/core/export-html/json-spans.js +3 -3
  110. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  111. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  112. package/dist/core/export-html/tool-renderer.code.js +1 -1
  113. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  114. package/dist/core/export-html/tool-renderer.js +3 -3
  115. package/dist/core/extensions/api-types.d.ts +1 -1
  116. package/dist/core/extensions/api-types.js.map +1 -1
  117. package/dist/core/extensions/index.d.ts +1 -1
  118. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  119. package/dist/core/extensions/jiti-loader.js +3 -3
  120. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  121. package/dist/core/extensions/jiti-static-loader.js +3 -3
  122. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  123. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  124. package/dist/core/extensions/loader-host-modules.js +3 -3
  125. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  126. package/dist/core/extensions/provider-types.d.ts +18 -6
  127. package/dist/core/extensions/provider-types.js.map +1 -1
  128. package/dist/core/extensions/runner-context.js +1 -1
  129. package/dist/core/intercom-broker-control-host.code.js +1 -1
  130. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  131. package/dist/core/intercom-broker-control-host.js +3 -3
  132. package/dist/core/intercom-broker-control.code.js +3 -3
  133. package/dist/core/intercom-broker-control.impl.js +3 -3
  134. package/dist/core/intercom-broker-control.js +3 -3
  135. package/dist/core/model-config.d.ts +40 -0
  136. package/dist/core/model-registry.js +1 -1
  137. package/dist/core/model-resolver-scope.d.ts +4 -4
  138. package/dist/core/model-runtime.d.ts +1 -1
  139. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  140. package/dist/core/package-manager-storage-adapters.js +3 -3
  141. package/dist/core/provider-composer-internal.d.ts +11 -2
  142. package/dist/core/sdk.code.js +3 -3
  143. package/dist/core/sdk.impl.js +3 -3
  144. package/dist/core/sdk.js +3 -3
  145. package/dist/core/session-manager-core.js +5 -5
  146. package/dist/core/session-manager-list.impl.js +3 -3
  147. package/dist/core/session-manager-list.js +3 -3
  148. package/dist/core/session-manager.code.js +1 -1
  149. package/dist/core/session-manager.impl.js +3 -3
  150. package/dist/core/session-manager.js +3 -3
  151. package/dist/core/session-storage.impl.js +3 -3
  152. package/dist/core/session-storage.js +3 -3
  153. package/dist/core/settings-manager-basic-accessors.d.ts +6 -2
  154. package/dist/core/storage/index.js +2 -2
  155. package/dist/core/storage/node-sqlite-thread.js +2 -2
  156. package/dist/core/storage/node-sqlite.js +2 -2
  157. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  158. package/dist/core/storage/offline-snapshot-file.js +3 -3
  159. package/dist/core/storage/provider.js +2 -2
  160. package/dist/core/storage/selection.js +2 -2
  161. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  162. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  163. package/dist/core/storage/session/branch-fork-source.js +3 -3
  164. package/dist/core/storage/session/card-view.impl.js +3 -3
  165. package/dist/core/storage/session/card-view.js +3 -3
  166. package/dist/core/storage/session/child-reader.code.js +3 -3
  167. package/dist/core/storage/session/child-reader.impl.js +3 -3
  168. package/dist/core/storage/session/child-reader.js +3 -3
  169. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  170. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  171. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  172. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  173. package/dist/core/storage/session/expanded-child-details.js +3 -3
  174. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  175. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  176. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  177. package/dist/core/storage/session/fork-row-index.js +3 -3
  178. package/dist/core/storage/session/fork-staging.code.js +2 -2
  179. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  180. package/dist/core/storage/session/fork-staging.js +3 -3
  181. package/dist/core/storage/session/fork-window.code.js +3 -3
  182. package/dist/core/storage/session/fork-window.impl.js +3 -3
  183. package/dist/core/storage/session/fork-window.js +3 -3
  184. package/dist/core/storage/session/history-pages.impl.js +3 -3
  185. package/dist/core/storage/session/history-pages.js +3 -3
  186. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  187. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  188. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  189. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  190. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  191. package/dist/core/storage/session/memory-session-store.js +3 -3
  192. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  193. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  194. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  195. package/dist/core/storage/session/released-history-files.code.js +3 -3
  196. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  197. package/dist/core/storage/session/released-history-files.js +3 -3
  198. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  199. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  200. package/dist/core/storage/session/session-resume.impl.js +3 -3
  201. package/dist/core/storage/session/session-resume.js +3 -3
  202. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  203. package/dist/core/storage/session/snapshot-cut.js +3 -3
  204. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  205. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  206. package/dist/core/storage/session/snapshot-history.js +3 -3
  207. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  208. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  209. package/dist/core/storage/session/sql-session-store.js +3 -3
  210. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  211. package/dist/core/storage/session/tree-outline.js +3 -3
  212. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  213. package/dist/core/storage/session/tree-presentation.js +3 -3
  214. package/dist/core/storage/storage-status.impl.js +3 -3
  215. package/dist/core/storage/storage-status.js +3 -3
  216. package/dist/core/storage/team.impl.js +3 -3
  217. package/dist/core/storage/team.js +3 -3
  218. package/dist/core/structured-output/index.code.js +1 -1
  219. package/dist/core/structured-output/index.impl.js +3 -3
  220. package/dist/core/structured-output/index.js +3 -3
  221. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  222. package/dist/core/tasks/task-completion-entry.js +3 -3
  223. package/dist/core/tasks/task-file-history.code.js +3 -3
  224. package/dist/core/tasks/task-file-history.impl.js +3 -3
  225. package/dist/core/tasks/task-file-history.js +3 -3
  226. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  227. package/dist/core/tasks/task-reference-archive.js +3 -3
  228. package/dist/core/tasks/task-reference-identity.code.js +1 -1
  229. package/dist/core/tasks/task-reference-identity.js +3 -3
  230. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  231. package/dist/core/tasks/task-reference-stream.js +3 -3
  232. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  233. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  234. package/dist/core/tasks/task-view-source.impl.js +3 -3
  235. package/dist/core/tasks/task-view-source.js +3 -3
  236. package/dist/core/tools/read-url.code.js +2 -2
  237. package/dist/core/tools/read-url.impl.js +3 -3
  238. package/dist/core/tools/read-url.js +3 -3
  239. package/dist/core/worktree-snapshot/blob-store.js +2 -2
  240. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  241. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  242. package/dist/core/worktree-snapshot/errors.js +3 -3
  243. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  244. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  245. package/dist/extensions/codemode/execute.code.js +1 -1
  246. package/dist/extensions/codemode/execute.impl.js +3 -3
  247. package/dist/extensions/codemode/execute.js +3 -3
  248. package/dist/extensions/codemode/renderer.code.js +2 -2
  249. package/dist/extensions/codemode/renderer.impl.js +3 -3
  250. package/dist/extensions/codemode/renderer.js +3 -3
  251. package/dist/extensions/mcp/cli.code.js +2 -2
  252. package/dist/extensions/mcp/cli.impl.js +3 -3
  253. package/dist/extensions/mcp/cli.js +3 -3
  254. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  255. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  256. package/dist/extensions/mcp/cli.lazy.js +3 -3
  257. package/dist/extensions/mcp/runtime.code.js +1 -1
  258. package/dist/extensions/mcp/runtime.impl.js +3 -3
  259. package/dist/extensions/mcp/runtime.js +3 -3
  260. package/dist/index-extensions.d.ts +1 -1
  261. package/dist/index.d.ts +8 -1
  262. package/dist/index.js +7 -7
  263. package/dist/main-first-time-setup.code.js +2 -2
  264. package/dist/main-first-time-setup.impl.js +3 -3
  265. package/dist/main-first-time-setup.js +3 -3
  266. package/dist/modes/interactive/components/settings-selector-types.d.ts +1 -0
  267. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  268. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  269. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  270. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  271. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  272. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  273. package/dist/modes/interactive/theme/color-utils.d.ts +5 -5
  274. package/dist/modes/interactive/theme/theme-loading.d.ts +1 -0
  275. package/dist/modes/interactive-engine/engine-prewarm.js +1 -1
  276. package/dist/modes/interactive-engine/remote-model-catalog.d.ts +1 -0
  277. package/dist/modes/print-mode.js +1 -1
  278. package/dist/modes/rpc/rpc-client-api.d.ts +6 -0
  279. package/dist/modes/rpc/rpc-types.d.ts +29 -2
  280. package/dist/package-manager-cli.code.js +5 -5
  281. package/dist/package-manager-cli.impl.js +3 -3
  282. package/dist/package-manager-cli.js +3 -3
  283. package/dist/rpc-entry.js +1 -1
  284. package/dist/startup-files.json +1 -1
  285. package/dist/startup-stages/5.js +1 -1
  286. package/dist/startup-stages/7.js +1 -1
  287. package/dist/startup-stages/8.js +1 -2
  288. package/dist/startup-stages/9.js +2 -1
  289. package/dist/utils/native-module.d.ts +44 -0
  290. package/dist/utils/startup-database-spare.code.js +3 -3
  291. package/dist/utils/startup-database-spare.impl.js +3 -3
  292. package/dist/utils/startup-database-spare.js +3 -3
  293. package/dist/utils/tools-manager.code.js +1 -1
  294. package/dist/utils/tools-manager.impl.js +3 -3
  295. package/dist/utils/tools-manager.js +3 -3
  296. package/docs/background-tasks.md +238 -243
  297. package/docs/build.md +21 -15
  298. package/docs/changelog.mdx +1 -1
  299. package/docs/codemode.md +68 -51
  300. package/docs/compaction/reference.md +65 -26
  301. package/docs/compaction.md +118 -66
  302. package/docs/computer-use.md +179 -146
  303. package/docs/containerization.md +87 -33
  304. package/docs/custom-provider/api-reference.md +152 -13
  305. package/docs/custom-provider/oauth.md +45 -28
  306. package/docs/custom-provider/override.md +14 -7
  307. package/docs/custom-provider/registration.md +77 -67
  308. package/docs/custom-provider/streaming.md +42 -19
  309. package/docs/custom-provider.md +26 -62
  310. package/docs/development.md +81 -42
  311. package/docs/docs.json +54 -38
  312. package/docs/environment-variables.md +92 -64
  313. package/docs/extensions/api-reference.md +326 -735
  314. package/docs/extensions/authoring.md +186 -269
  315. package/docs/extensions/events.md +308 -375
  316. package/docs/extensions/examples.md +122 -74
  317. package/docs/extensions/ui.md +217 -197
  318. package/docs/extensions.md +189 -259
  319. package/docs/getting-started/authentication.md +27 -14
  320. package/docs/getting-started/first-session.md +25 -26
  321. package/docs/getting-started/installation.md +62 -84
  322. package/docs/getting-started/project-instructions.md +39 -14
  323. package/docs/guides/configuration.md +62 -20
  324. package/docs/guides/intercom.md +20 -12
  325. package/docs/guides/non-interactive.md +31 -16
  326. package/docs/guides/orchestration.md +17 -9
  327. package/docs/guides/resume-on-any-machine.md +63 -52
  328. package/docs/guides/subagents.md +26 -14
  329. package/docs/guides/team-setup.md +49 -27
  330. package/docs/guides.md +30 -23
  331. package/docs/herdr.md +22 -17
  332. package/docs/index.md +24 -17
  333. package/docs/intercom/operations.md +90 -66
  334. package/docs/intercom/reference.md +219 -192
  335. package/docs/intercom.md +111 -92
  336. package/docs/json.md +73 -71
  337. package/docs/keybindings.md +74 -48
  338. package/docs/libraries/agent-core.md +52 -9
  339. package/docs/libraries/ai.md +90 -63
  340. package/docs/libraries/codemode.md +31 -8
  341. package/docs/libraries/schema.md +12 -9
  342. package/docs/libraries/storage-libsql.md +92 -0
  343. package/docs/libraries/storage-postgres.md +119 -0
  344. package/docs/libraries/telemetry.md +42 -9
  345. package/docs/libraries/tui.md +74 -94
  346. package/docs/libraries.md +25 -8
  347. package/docs/llama-cpp.md +38 -33
  348. package/docs/mcp-servers.md +140 -88
  349. package/docs/models/reference.md +53 -36
  350. package/docs/models-configuration.md +19 -13
  351. package/docs/models.md +102 -87
  352. package/docs/orchestration/migrating-workflows.md +22 -20
  353. package/docs/orchestration/patterns.md +36 -21
  354. package/docs/orchestration.md +24 -21
  355. package/docs/packages/authoring.md +29 -18
  356. package/docs/packages/reference.md +77 -16
  357. package/docs/packages.md +34 -34
  358. package/docs/programmatic.md +28 -21
  359. package/docs/prompt-templates.md +65 -41
  360. package/docs/providers/reference.md +36 -20
  361. package/docs/providers.md +78 -76
  362. package/docs/quickstart.md +42 -54
  363. package/docs/reference/cli.md +256 -254
  364. package/docs/reference.md +30 -23
  365. package/docs/rpc/examples.md +121 -17
  366. package/docs/rpc/extension-ui.md +86 -63
  367. package/docs/rpc/protocol.md +817 -358
  368. package/docs/rpc.md +78 -152
  369. package/docs/sdk/reference.md +309 -73
  370. package/docs/sdk/storage.md +614 -0
  371. package/docs/sdk/structured-decisions.md +168 -65
  372. package/docs/sdk/web-server.md +80 -46
  373. package/docs/sdk.md +168 -215
  374. package/docs/security.md +117 -44
  375. package/docs/session-format.md +127 -76
  376. package/docs/sessions.md +155 -113
  377. package/docs/settings.md +293 -205
  378. package/docs/shell-aliases.md +15 -6
  379. package/docs/skills/authoring.md +17 -9
  380. package/docs/skills/reference.md +23 -21
  381. package/docs/skills.md +148 -97
  382. package/docs/storage.md +172 -260
  383. package/docs/subagents/authoring.md +148 -15
  384. package/docs/subagents/reference.md +105 -29
  385. package/docs/subagents.md +247 -250
  386. package/docs/terminal-setup.md +97 -69
  387. package/docs/termux.md +51 -85
  388. package/docs/themes/reference.md +51 -37
  389. package/docs/themes.md +52 -55
  390. package/docs/tmux.md +38 -21
  391. package/docs/tools.md +209 -147
  392. package/docs/tui/reference.md +64 -32
  393. package/docs/tui.md +38 -66
  394. package/docs/usage.md +94 -86
  395. package/docs/verification.md +25 -25
  396. package/docs/web-access.md +106 -54
  397. package/docs/windows.md +55 -57
  398. package/docs/worktree-snapshots.md +82 -74
  399. package/examples/sdk/11-sessions.ts +4 -4
  400. package/package.json +8 -8
  401. package/schemas/models.schema.json +58 -7
  402. package/dist/_shared/sdk-OSBEPR3Q.js.map +0 -1
  403. package/dist/_shared/startup-0-0-TYUFUOJZ.js.map +0 -1
  404. package/dist/_shared/startup-0-1-W2G2UY7R.js.map +0 -1
  405. package/dist/_shared/startup-0-2-UXBUEOXW.js.map +0 -1
  406. package/dist/_shared/startup-0-4-HN5EB4K7.js.map +0 -1
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
+ - **Session storage:** [SDK storage guide](/sdk/storage) and [Storage backends](/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
- ### Sharing Atomic's TypeBox registry
56
+ ### Sharing Atomic's TypeBox registry {#sharing-atomics-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,73 +132,73 @@ 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` with the `session_` table prefix. Override storage per session with `sessionStore`, `storage`, or an explicit `sessionManager`. Read the **[SDK storage guide](/sdk/storage)** for complete recipes across all five backends, `createAgentSessionRuntime()` wiring, `SessionManager` CRUD, `JsonlSessionStore` `exactDirectory` behavior, `npm install` vs `atomic install` adapter resolution, ownership and close rules, and `StorageError` handling.
179
143
 
180
- ```typescript
181
- import { createAgentSession, MemorySessionStore, POSTGRES_ADAPTER_PACKAGE } from "@bastani/atomic";
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()` and `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`](/libraries/storage-libsql) | `{ kind: "adapter", module: LIBSQL_ADAPTER_PACKAGE, ... }` or caller-owned `openLibsqlDatabase()` |
150
+ | PostgreSQL (16+ for sessions) | [`@bastani/atomic-storage-postgres`](/libraries/storage-postgres) | `{ kind: "adapter", module: POSTGRES_ADAPTER_PACKAGE, ... }` or caller-owned `openPostgresDatabase()` |
182
151
 
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 });
152
+ Quick local SQLite session. Atomic opens the store and closes it in `dispose()`:
186
153
 
187
- // JSONL directory
188
- const jsonl = await createAgentSession({
189
- sessionStore: { kind: "jsonl", dir: "./sessions" },
190
- });
154
+ ```typescript
155
+ import { createAgentSession } from "@bastani/atomic";
191
156
 
192
- // SQLite file
193
- const sqlite = await createAgentSession({
157
+ const { session } = await createAgentSession({
194
158
  sessionStore: { kind: "sqlite", path: "./sessions.sqlite", prefix: "project_" },
195
159
  });
196
-
197
- // PostgreSQL (install @bastani/atomic-storage-postgres)
198
- const pg = await createAgentSession({
199
- sessionStore: {
200
- kind: "adapter",
201
- module: POSTGRES_ADAPTER_PACKAGE,
202
- options: { url: process.env.DATABASE_URL },
203
- prefix: "project_",
204
- },
205
- });
160
+ try {
161
+ await session.prompt("Summarize recent commits");
162
+ } finally {
163
+ await session.dispose();
164
+ }
206
165
  ```
207
166
 
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.
210
- - **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)):
167
+ Quick PostgreSQL session with a caller-owned database pool (`npm install @bastani/atomic-storage-postgres`):
212
168
 
213
169
  ```typescript
214
- import { createAgentSession, resolveSessionStore, SessionManager } from "@bastani/atomic";
215
-
216
- const store = await resolveSessionStore(process.cwd());
170
+ import { readFile } from "node:fs/promises";
171
+ import { createAgentSession } from "@bastani/atomic";
172
+ import { openPostgresDatabase } from "@bastani/atomic-storage-postgres";
173
+
174
+ // Pass a username-only URL (embedded passwords reject with credential-in-url).
175
+ const pgDb = await openPostgresDatabase({
176
+ url: "postgresql://atomic_runtime@db.example.com:5432/atomic",
177
+ password: async () => (await readFile("/run/secrets/postgres-password", "utf8")).trim(),
178
+ });
217
179
  try {
218
- const manager = await SessionManager.open(store, savedSessionId);
219
- const { session } = await createAgentSession({ sessionManager: manager });
180
+ const { session } = await createAgentSession({
181
+ sessionStore: { kind: "database", database: pgDb, prefix: "project_" },
182
+ });
220
183
  try {
221
- await session.prompt("Continue the task");
184
+ await session.prompt("Summarize recent commits");
222
185
  } finally {
223
186
  await session.dispose();
224
187
  }
225
188
  } finally {
226
- await store.close();
189
+ await pgDb.close();
227
190
  }
228
191
  ```
229
192
 
230
- `ExtensionContext.sessionSignal` aborts when reload or shutdown begins so extensions can cancel long waits while still awaiting already-started session writes.
193
+ - **`sessionStore` vs. `storage`:** `sessionStore` accepts a `SessionStore` instance (`SqlSessionStore`, `JsonlSessionStore`, `MemorySessionStore`) or a tagged selection (`{ kind: "sqlite" | "jsonl" | "memory" | "database" | "adapter", ... }`). `storage` uses the `settings.json` shape returned by `teamProfileSelection()` (`{ path, prefix? }`, `{ database, prefix? }`, `{ memory: true }`, or `{ adapter, options?, secrets?, prefix? }`) and does not support JSONL.
194
+ - **Precedence:** Atomic resolves storage in order from `sessionManager`, `sessionStore`, `storage`, process flags and variables (`ATOMIC_SESSIONS_STORAGE` and `ATOMIC_STORAGE`), settings (`sessions.storage` before `storage`), and default SQLite. Memory is never an automatic fallback.
195
+ - **Ownership and mutations:** Atomic closes stores it opened from selection objects during `dispose()`, while leaving caller-owned `SessionStore`, `SessionManager`, and `database` instances open. Await every `SessionManager` write and every `atomic.appendEntry`, `setSessionName`, `setLabel`, `setThinkingLevel`, and `cycleThinkingLevel` call; there is no `flush()` method. `ExtensionContext.sessionSignal` aborts when reload or shutdown starts so extensions can cancel waits while finishing in-flight writes.
231
196
 
232
- ### Human input without a terminal
197
+ See the **[SDK storage guide](/sdk/storage)** for all five backends, `createAgentSessionRuntime()` wiring, `SessionManager` CRUD, `JsonlSessionStore` `exactDirectory` behavior, `npm install` vs `atomic install` adapter resolution, ownership and close rules, and `StorageError` handling. For CLI session commands, the full `SessionManager` method list, operator setup, and cross-machine resume, see [Sessions](/sessions), [SessionManager API](/session-format#sessionmanager-api), [Storage backends](/storage), and [Resume on any machine](/guides/resume-on-any-machine).
233
198
 
234
- <a id="binding-and-withdrawing-an-input-adapter" />
235
- <a id="diagnostics-and-provider-state" />
199
+ ### Human input without a terminal
236
200
 
237
- Pass `extensionBindings.humanInput` implementing all five `HostInput` methods (`confirm`, `select`, `input`, `editor`, `questionnaire`; `QuestionParams` and `QuestionnaireResult` are exported):
201
+ Pass `extensionBindings.humanInput` implementing all five `HostInput` methods (`confirm`, `select`, `input`, `editor`, `questionnaire`; `QuestionParams` and `QuestionnaireResult` are exported from `@bastani/atomic`):
238
202
 
239
203
  ```typescript
240
204
  import { createAgentSession, type HostInput } from "@bastani/atomic";
@@ -256,28 +220,28 @@ async function attachApplication(humanInput: HostInput) {
256
220
  }
257
221
  ```
258
222
 
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.
223
+ - **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`.
224
+ - **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.
225
+ - **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`.
226
+ - **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
227
 
264
228
  ### Stored session summaries
265
229
 
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.
230
+ 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
231
 
268
232
  ### Worktree snapshots
269
233
 
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:
234
+ 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
235
 
272
236
  ```typescript
273
237
  import { createAgentSession, SessionManager } from "@bastani/atomic";
274
238
 
275
- const sessionManager = await SessionManager.open(store, sessionId);
239
+ const sessionManager = await SessionManager.open(store, savedSessionId);
276
240
  const { session } = await createAgentSession({ sessionManager });
277
241
  ```
278
242
 
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).
243
+ - 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)).
244
+ - 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
245
 
282
246
  ### Intercom group and reach
283
247
 
@@ -291,25 +255,34 @@ const { session } = await createAgentSession({
291
255
  await session.intercom.setReachable(["doc-1907", "doc-2011"]);
292
256
  ```
293
257
 
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`.
258
+ - `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`.
259
+ - 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.
260
+ - `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
261
 
297
262
  ### Subagent children
298
263
 
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.
264
+ 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
265
 
301
266
  - Child tool lists can only narrow parent permissions, never expand them (`builtins`, `excludedTools`, `tools: []`, and `noTools: "all"` stay enforced).
302
267
  - Pass explicit child `extensionBindings.humanInput` to override (or `null` to withdraw). Shared callbacks distinguish children by `sessionId`.
303
268
 
304
- ### AgentSession
269
+ ### Driving a session
305
270
 
306
- Core session handle for prompting, queueing, model switching, events, compaction, and disposal:
271
+ `AgentSession` is the handle for prompting, queueing, model switching, events, compaction, and disposal:
307
272
 
308
273
  ```typescript
309
274
  interface AgentSession {
310
275
  prompt(text: string, options?: PromptOptions): Promise<void>;
311
- steer(text: string): Promise<void>;
312
- followUp(text: string): Promise<void>;
276
+ steer(
277
+ text: string,
278
+ images?: ImageContent[],
279
+ options?: Pick<PromptOptions, "source" | "expandPromptTemplates">,
280
+ ): Promise<"handled" | "queued">;
281
+ followUp(
282
+ text: string,
283
+ images?: ImageContent[],
284
+ options?: Pick<PromptOptions, "source" | "expandPromptTemplates">,
285
+ ): Promise<"handled" | "queued">;
313
286
  readonly queuedMessagesPaused: boolean;
314
287
  pauseQueuedMessages(): void;
315
288
  resumeQueuedMessages(): Promise<boolean>;
@@ -319,20 +292,25 @@ interface AgentSession {
319
292
 
320
293
  sessionFile: string | undefined;
321
294
  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;
295
+ setModel(model: Model<Api>, options?: { persist?: boolean; thinkingLevel?: ThinkingLevel }): Promise<void>;
296
+ setThinkingLevel(level: ThinkingLevel, options?: { persist?: boolean }): Promise<void>;
297
+ cycleModel(direction?: "forward" | "backward", options?: { persist?: boolean }): Promise<ModelCycleResult | undefined>;
298
+ cycleThinkingLevel(options?: { persist?: boolean }): Promise<ThinkingLevel | undefined>;
299
+ setCompactionModel(model: string, scope?: "global" | "project", options?: { persist?: boolean }): void;
300
+ setDecisionModel(model: string, scope?: "global" | "project", options?: { persist?: boolean }): void;
326
301
 
327
302
  agent: Agent;
328
303
  sessionManager: SessionManager;
329
304
  refreshContext(): void;
330
- model: Model | undefined;
305
+ model: Model<Api> | undefined;
331
306
  thinkingLevel: ThinkingLevel;
332
307
  messages: AgentMessage[];
333
308
  isStreaming: boolean;
334
309
 
335
- navigateTree(targetId: string, options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string }): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;
310
+ navigateTree(
311
+ targetId: string,
312
+ options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },
313
+ ): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;
336
314
  compact(options?: SessionCompactOptions): Promise<VerbatimCompactionResult>;
337
315
  abortCompaction(): void;
338
316
  abort(options?: { pauseQueuedMessages?: boolean }): Promise<void>;
@@ -340,7 +318,7 @@ interface AgentSession {
340
318
  }
341
319
  ```
342
320
 
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 }`:
321
+ **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
322
 
345
323
  ```typescript
346
324
  try {
@@ -351,12 +329,13 @@ try {
351
329
  }
352
330
  ```
353
331
 
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.
332
+ - `setModel(model, { thinkingLevel: "high", persist: true })` clamps unsupported thinking levels and optionally writes global defaults (project overrides still win at startup).
333
+ - `setCompactionModel(model, scope?, options?)` and `setDecisionModel(model, scope?, options?)` update the active session's compaction or decision model immediately without restarting or reloading. They save to `"global"` (default) or `"project"` settings unless `{ persist: false }` is passed. Pass `""` or `"auto"` for automatic selection, or an exact `provider/model` ID. Invalid values throw `CompactionConfigError` or `DecisionConfigError` synchronously. See [Compaction](/compaction) and [Structured decisions API](/sdk/structured-decisions).
334
+ - 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
335
 
357
336
  #### Event subscriptions
358
337
 
359
- Subscribe a session to external event streams without polluting main context (`maxConcurrent` default `4`, optional `name` and `maxRate`):
338
+ Subscribe a session to external event streams without cluttering main context (`maxConcurrent` default `4`, optional `name` and `maxRate`):
360
339
 
361
340
  ```typescript
362
341
  import { githubReviews } from "@bastani/atomic";
@@ -371,54 +350,32 @@ const subscription = session.subscribe(
371
350
  // later: await subscription.close();
372
351
  ```
373
352
 
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`.
353
+ - `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
354
  - `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.
355
+ - 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.
377
356
 
378
- #### Finishing admitted work
357
+ #### Draining work on reload and shutdown {#finishing-admitted-work}
379
358
 
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.
359
+ 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.
381
360
 
382
- #### Reload failures and resource ownership
383
-
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.
361
+ - `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.
362
+ - 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.
363
+ - For transactional reload lifecycle effects (`publishExtensionContextEffect`, `registerExtensionContextRetirementEffect`), see [Reload lifecycle and resource ownership](/sdk/reference#reload-lifecycle-and-resource-ownership).
407
364
 
408
365
  #### Compaction and tree navigation
409
366
 
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).
367
+ `session.compact({ query?, compactionModel? })` stops active runs, clears context or replaces it with output from a configured compactor model such as `morph/morph-compactor`, appends a `verbatim-lines` `compaction` entry, and returns `VerbatimCompactionResult` (`form: "cleared" | "compacted"`). It rejects with `CompactionStateError` (`code: "nothing-to-compact"`) when nothing new has entered context since the last boundary; concurrent calls coalesce. Call `session.setCompactionModel(model, scope?, options?)` to change the configured compactor live. A chat, classifier, or unknown `compactionModel` ID clears the context with a notice instead of failing. See [Compaction errors](/compaction/reference#compaction-errors), [Compaction](/compaction), and [Session format](/session-format#compactionentry).
411
368
 
412
369
  ```typescript
413
370
  const result = await session.compact({ query: "keep the auth decisions" });
414
371
  console.log(result.form, result.history?.boundaryEntry);
415
372
  ```
416
373
 
417
- `session.navigateTree()` rejects if streaming, compacting, or summarizing a branch (leaving the branch unchanged).
374
+ `session.navigateTree()` rejects if the session is currently streaming, compacting, or summarizing a branch, leaving the active branch unchanged.
418
375
 
419
- ### createAgentSessionRuntime() and AgentSessionRuntime
376
+ ### Replacing and rehydrating sessions
420
377
 
421
- Use `AgentSessionRuntime` when your host needs session replacement (`newSession()`, `switchSession()`, `fork()`, clone via `fork(entryId, { position: "at" })`, `importFromJsonl()`) with rebuilt cwd-bound services:
378
+ 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
379
 
423
380
  ```typescript
424
381
  import {
@@ -446,11 +403,11 @@ const runtime = await createAgentSessionRuntime(createRuntime, {
446
403
  });
447
404
  ```
448
405
 
449
- After any replacement, `runtime.session` points to the new instance. Re-subscribe to events, call `bindExtensions()` again, and call `startPendingRecovery("resume")` after `switchSession()`.
406
+ After any replacement, `runtime.session` points to the new session. Re-subscribe to events, call `bindExtensions()` again, and call `startPendingRecovery("resume")` after `switchSession()`.
450
407
 
451
408
  ### Releasing idle sessions
452
409
 
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)`:
410
+ 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
411
 
455
412
  ```typescript
456
413
  const released = await session.release(); // { sessionId, cwd, sessionFile? }
@@ -459,17 +416,17 @@ await live.prompt("Here is the CI result you were waiting for.");
459
416
  await live.release();
460
417
  ```
461
418
 
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()`).
419
+ - **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
420
  - **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)`.
421
+ - **In-memory store spilling:** A directly constructed `new MemorySessionStore()` has no spill directory and keeps released session history in RAM. Opening a memory store through `resolveSessionStore(cwd, { agentDir, sessionStore: { kind: "memory" } })` enables disk spilling 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)). Spill 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
422
 
466
423
  Release and wake errors throw `AgentRehydrateError` (guards `isAgentRehydrateError`, `isAgentReleaseConfigError`, `isRetryableAgentRehydrateError`; cross-process `serializeAgentRehydrateError` and `rehydrateAgentRehydrateError`):
467
424
 
468
425
  | Class | `code` | When | Fields | What to do |
469
426
  | --- | --- | --- | --- | --- |
470
- | `AgentReleaseConfigError` | `invalid-release-policy` | Invalid `releaseWhenIdle.afterMs` (must be `0` to `2147483647`). | `source`, `field`, `value` | Fix the option. |
427
+ | `AgentReleaseConfigError` | `invalid-release-policy` | Invalid `releaseWhenIdle.afterMs` (must be `0` to `2,147,483,647`). | `source`, `field`, `value` | Fix the option. |
471
428
  | `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`. |
429
+ | `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
430
  | `AgentRehydrateError` | `session-not-found` | Session missing in this node's storage. | `sessionId`, `storage`, `localOnly` | Verify ID, or join shared storage (`atomic storage join`). |
474
431
  | `AgentRehydrateError` | `no-wake-handler` | Wake delivered to unregistered namespace. | `wakeKey`, `namespace` | Register handler with `handle()` first. |
475
432
  | `AgentRehydrateError` | `wake-handler-conflict` | Duplicate handler for namespace. | `namespace` | Dispose existing handler first. |
@@ -489,28 +446,25 @@ interface PromptOptions {
489
446
  }
490
447
  ```
491
448
 
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"`.
449
+ - **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.
450
+ - **`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
451
  - **`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.
452
+ - **`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.
453
+ - **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
454
 
498
455
  ### Agent and AgentState
499
456
 
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()`.
457
+ 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
458
 
504
- <a id="events" />
505
- <a id="collecting-assistant-output" />
459
+ `session.sessionManager` is the source of truth for model context (see [SessionManager API](/session-format#sessionmanager-api)). 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
460
 
507
461
  ### Events and transcript collection
508
462
 
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`).
463
+ 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
464
 
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.
465
+ 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
466
 
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:
467
+ 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
468
 
515
469
  ```typescript
516
470
  import { createTranscript } from "@bastani/atomic";
@@ -600,39 +554,38 @@ try {
600
554
  }
601
555
  ```
602
556
 
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" />
557
+ ## Runtime notes and errors
558
+
559
+ ### Error classes vs. `.code`-tagged errors
560
+
561
+ - **`NativeModuleUnavailableError` is exported from `@bastani/atomic`** (`code: "NativeModuleUnavailable"`). `createAgentSession()` throws it when `@bastani/atomic-natives` cannot load or came from a different Atomic release.
562
+ - **`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`.
563
+
564
+ ### Node 22 hosts
565
+
566
+ 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.
567
+
568
+ 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.
569
+
570
+ ### Updating Atomic while your program runs
571
+
572
+ 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.
573
+
574
+ `createAgentSession()` verifies `@bastani/atomic-natives` before opening a session and throws `NativeModuleUnavailableError` when it cannot load or does not match the running release:
575
+
576
+ - If the native module was missing on disk, later calls retry once installed.
577
+ - 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).
578
+
579
+ Also restart after an in-place update if your process launched on an older Atomic release or before importing `@bastani/atomic/rpc-entry`.
580
+
581
+ ### Migrating an existing Node host
582
+
583
+ - **Builtins load automatically:** Remove manual registration of shipped builtin extensions; disable selectively with `builtins` and restrict tools with `tools` / `excludedTools` (`tools: []` excludes Intercom too).
584
+ - **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"`).
585
+ - **Removed `workflows` builtin:** Remove `workflows` from `builtins`; workflow SDK exports were removed. Convert older workflow files into skills ([Migrating workflows](/orchestration/migrating-workflows)).
586
+ - **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()`.
587
+ - **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`.
588
+ - **Removed experimental client:** `@bastani/atomic/client` was removed; embed `createAgentSession()` directly or drive [RPC mode](/rpc) (`--mode rpc` / `@bastani/atomic/rpc-entry`).
636
589
 
637
590
  ## API reference
638
591