@bastani/atomic 0.10.14-alpha.1 → 0.10.15-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 (341) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/_shared/dist-KOELCESV.js +2 -2
  3. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  4. package/dist/_shared/lib-4PES5P4V.js +2 -2
  5. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +3 -3
  6. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +3 -3
  7. package/dist/_shared/mode-shared-2QJSCUM6.js +3 -3
  8. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  9. package/dist/_shared/runtime-O4KCSG4C.js +2 -2
  10. package/dist/_shared/{sdk-B5LEWGGI.js → sdk-OHKMDJ74.js} +27 -5
  11. package/dist/_shared/{sdk-B5LEWGGI.js.map → sdk-OHKMDJ74.js.map} +1 -1
  12. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  13. package/dist/_shared/startup-0-0-Q3MWKUK4.js +2 -2
  14. package/dist/_shared/startup-0-1-M6OWAYHH.js +2 -2
  15. package/dist/_shared/{startup-0-2-5QHPCEON.js → startup-0-2-2HUMCPKX.js} +14 -16
  16. package/dist/_shared/startup-0-2-2HUMCPKX.js.map +1 -0
  17. package/dist/_shared/startup-0-3-4ZYBYQNM.js +3 -3
  18. package/dist/_shared/startup-0-4-ZMJV547D.js +3 -3
  19. package/dist/_shared/startup-0-5-YDW47QX6.js +3 -3
  20. package/dist/_shared/startup-10-0-TDQNBDDL.js +3 -3
  21. package/dist/_shared/startup-14-0-MLX36RBG.js +1 -1
  22. package/dist/_shared/startup-15-0-YUKGAC63.js +1 -1
  23. package/dist/_shared/startup-15-1-4S7FLMNG.js +6 -30
  24. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  25. package/dist/_shared/startup-8-0-34CBHPZH.js +3 -3
  26. package/dist/_shared/startup-8-1-LZFXSD3Z.js +3 -3
  27. package/dist/_shared/storage-command-7MGXLJGZ.js +2 -2
  28. package/dist/_shared/storage-status-K7PX2RXA.js +3 -3
  29. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  30. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  31. package/dist/builtin/intercom/index.bundle.mjs +1 -1
  32. package/dist/builtin/intercom/package.json +1 -1
  33. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  34. package/dist/builtin/mcp/package.json +1 -1
  35. package/dist/builtin/subagents/package.json +1 -1
  36. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  37. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  38. package/dist/builtin/web-access/package.json +1 -1
  39. package/dist/cli/auth-cli.code.js +1 -1
  40. package/dist/cli/auth-cli.impl.js +3 -3
  41. package/dist/cli/auth-cli.js +3 -3
  42. package/dist/cli/blueprint-command.impl.js +3 -3
  43. package/dist/cli/blueprint-command.js +3 -3
  44. package/dist/cli/intercom-command.code.js +3 -3
  45. package/dist/cli/intercom-command.impl.js +3 -3
  46. package/dist/cli/intercom-command.js +3 -3
  47. package/dist/cli/list-models.impl.js +3 -3
  48. package/dist/cli/list-models.js +3 -3
  49. package/dist/cli/session-picker.code.js +1 -1
  50. package/dist/cli/session-picker.impl.js +3 -3
  51. package/dist/cli/session-picker.js +3 -3
  52. package/dist/cli/startup-ui.code.js +1 -1
  53. package/dist/cli/startup-ui.impl.js +3 -3
  54. package/dist/cli/startup-ui.js +3 -3
  55. package/dist/cli/storage-command.impl.js +3 -3
  56. package/dist/cli/storage-command.js +3 -3
  57. package/dist/cli/storage-search-session.code.js +1 -1
  58. package/dist/cli/storage-search-session.impl.js +3 -3
  59. package/dist/cli/storage-search-session.js +3 -3
  60. package/dist/cli/team-command.code.js +1 -1
  61. package/dist/cli/team-command.impl.js +3 -3
  62. package/dist/cli/team-command.js +3 -3
  63. package/dist/cli.js +2 -2
  64. package/dist/core/compaction/compactor.d.ts +0 -8
  65. package/dist/core/debug.impl.js +3 -3
  66. package/dist/core/debug.js +3 -3
  67. package/dist/core/export-html/card-projection.impl.js +3 -3
  68. package/dist/core/export-html/card-projection.js +3 -3
  69. package/dist/core/export-html/index.code.js +2 -2
  70. package/dist/core/export-html/index.impl.js +3 -3
  71. package/dist/core/export-html/index.js +3 -3
  72. package/dist/core/export-html/json-spans.impl.js +3 -3
  73. package/dist/core/export-html/json-spans.js +3 -3
  74. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  75. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  76. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  77. package/dist/core/export-html/tool-renderer.js +3 -3
  78. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  79. package/dist/core/extensions/jiti-loader.js +3 -3
  80. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  81. package/dist/core/extensions/jiti-static-loader.js +3 -3
  82. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  83. package/dist/core/extensions/loader-host-modules.js +3 -3
  84. package/dist/core/intercom-broker-control-host.code.js +1 -1
  85. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  86. package/dist/core/intercom-broker-control-host.js +3 -3
  87. package/dist/core/intercom-broker-control.code.js +2 -2
  88. package/dist/core/intercom-broker-control.impl.js +3 -3
  89. package/dist/core/intercom-broker-control.js +3 -3
  90. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  91. package/dist/core/package-manager-storage-adapters.js +3 -3
  92. package/dist/core/sdk.code.js +1 -1
  93. package/dist/core/sdk.impl.js +3 -3
  94. package/dist/core/sdk.js +3 -3
  95. package/dist/core/session-manager-core.js +3 -3
  96. package/dist/core/session-manager-list.impl.js +3 -3
  97. package/dist/core/session-manager-list.js +3 -3
  98. package/dist/core/session-manager.impl.js +3 -3
  99. package/dist/core/session-manager.js +3 -3
  100. package/dist/core/session-storage.impl.js +3 -3
  101. package/dist/core/session-storage.js +3 -3
  102. package/dist/core/storage/index.js +2 -2
  103. package/dist/core/storage/node-sqlite-thread.js +2 -2
  104. package/dist/core/storage/node-sqlite.js +2 -2
  105. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  106. package/dist/core/storage/offline-snapshot-file.js +3 -3
  107. package/dist/core/storage/provider.js +2 -2
  108. package/dist/core/storage/selection.js +2 -2
  109. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  110. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  111. package/dist/core/storage/session/branch-fork-source.js +3 -3
  112. package/dist/core/storage/session/card-view.impl.js +3 -3
  113. package/dist/core/storage/session/card-view.js +3 -3
  114. package/dist/core/storage/session/child-reader.code.js +2 -2
  115. package/dist/core/storage/session/child-reader.impl.js +3 -3
  116. package/dist/core/storage/session/child-reader.js +3 -3
  117. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  118. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  119. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  120. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  121. package/dist/core/storage/session/expanded-child-details.js +3 -3
  122. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  123. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  124. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  125. package/dist/core/storage/session/fork-row-index.js +3 -3
  126. package/dist/core/storage/session/fork-staging.code.js +1 -1
  127. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  128. package/dist/core/storage/session/fork-staging.js +3 -3
  129. package/dist/core/storage/session/fork-window.code.js +2 -2
  130. package/dist/core/storage/session/fork-window.impl.js +3 -3
  131. package/dist/core/storage/session/fork-window.js +3 -3
  132. package/dist/core/storage/session/history-pages.impl.js +3 -3
  133. package/dist/core/storage/session/history-pages.js +3 -3
  134. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  135. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  136. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  137. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  138. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  139. package/dist/core/storage/session/memory-session-store.js +3 -3
  140. package/dist/core/storage/session/pinned-branch-resume.code.js +2 -2
  141. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  142. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  143. package/dist/core/storage/session/released-history-files.code.js +1 -1
  144. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  145. package/dist/core/storage/session/released-history-files.js +3 -3
  146. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  147. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  148. package/dist/core/storage/session/session-resume.impl.js +3 -3
  149. package/dist/core/storage/session/session-resume.js +3 -3
  150. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  151. package/dist/core/storage/session/snapshot-cut.js +3 -3
  152. package/dist/core/storage/session/snapshot-history.code.js +2 -2
  153. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  154. package/dist/core/storage/session/snapshot-history.js +3 -3
  155. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  156. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  157. package/dist/core/storage/session/sql-session-store.js +3 -3
  158. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  159. package/dist/core/storage/session/tree-outline.js +3 -3
  160. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  161. package/dist/core/storage/session/tree-presentation.js +3 -3
  162. package/dist/core/storage/storage-status.impl.js +3 -3
  163. package/dist/core/storage/storage-status.js +3 -3
  164. package/dist/core/storage/team.impl.js +3 -3
  165. package/dist/core/storage/team.js +3 -3
  166. package/dist/core/structured-output/index.code.js +1 -1
  167. package/dist/core/structured-output/index.impl.js +3 -3
  168. package/dist/core/structured-output/index.js +3 -3
  169. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  170. package/dist/core/tasks/task-completion-entry.js +3 -3
  171. package/dist/core/tasks/task-file-history.code.js +2 -2
  172. package/dist/core/tasks/task-file-history.impl.js +3 -3
  173. package/dist/core/tasks/task-file-history.js +3 -3
  174. package/dist/core/tasks/task-reference-archive.code.js +2 -2
  175. package/dist/core/tasks/task-reference-archive.js +3 -3
  176. package/dist/core/tasks/task-reference-identity.js +3 -3
  177. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  178. package/dist/core/tasks/task-reference-stream.js +3 -3
  179. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  180. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  181. package/dist/core/tasks/task-view-source.impl.js +3 -3
  182. package/dist/core/tasks/task-view-source.js +3 -3
  183. package/dist/core/tools/read-url.impl.js +3 -3
  184. package/dist/core/tools/read-url.js +3 -3
  185. package/dist/core/worktree-snapshot/blob-store.js +2 -2
  186. package/dist/core/worktree-snapshot/errors.code.js +1 -1
  187. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  188. package/dist/core/worktree-snapshot/errors.js +3 -3
  189. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  190. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  191. package/dist/extensions/codemode/execute.impl.js +3 -3
  192. package/dist/extensions/codemode/execute.js +3 -3
  193. package/dist/extensions/codemode/renderer.impl.js +3 -3
  194. package/dist/extensions/codemode/renderer.js +3 -3
  195. package/dist/extensions/mcp/cli.code.js +1 -1
  196. package/dist/extensions/mcp/cli.impl.js +3 -3
  197. package/dist/extensions/mcp/cli.js +3 -3
  198. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  199. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  200. package/dist/extensions/mcp/cli.lazy.js +3 -3
  201. package/dist/extensions/mcp/runtime.code.js +1 -1
  202. package/dist/extensions/mcp/runtime.impl.js +3 -3
  203. package/dist/extensions/mcp/runtime.js +3 -3
  204. package/dist/index.d.ts +21 -1
  205. package/dist/index.js +2 -2
  206. package/dist/main-first-time-setup.code.js +1 -1
  207. package/dist/main-first-time-setup.impl.js +3 -3
  208. package/dist/main-first-time-setup.js +3 -3
  209. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  210. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  211. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  212. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  213. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  214. package/dist/modes/print-mode.js +1 -1
  215. package/dist/package-manager-cli.code.js +2 -2
  216. package/dist/package-manager-cli.impl.js +3 -3
  217. package/dist/package-manager-cli.js +3 -3
  218. package/dist/startup-files.json +1 -1
  219. package/dist/startup-stages/6.js +1 -1
  220. package/dist/utils/startup-database-spare.code.js +1 -1
  221. package/dist/utils/startup-database-spare.impl.js +3 -3
  222. package/dist/utils/startup-database-spare.js +3 -3
  223. package/dist/utils/tools-manager.impl.js +3 -3
  224. package/dist/utils/tools-manager.js +3 -3
  225. package/docs/background-tasks/reference.md +182 -0
  226. package/docs/background-tasks.md +98 -405
  227. package/docs/build.md +67 -27
  228. package/docs/changelog.mdx +9 -0
  229. package/docs/codemode.md +108 -39
  230. package/docs/compaction/branch-summaries.md +54 -0
  231. package/docs/compaction/custom-compactors.md +161 -0
  232. package/docs/compaction/memory-compaction.md +77 -0
  233. package/docs/compaction/reference.md +86 -38
  234. package/docs/compaction.md +51 -252
  235. package/docs/computer-use.md +169 -321
  236. package/docs/containerization.md +71 -57
  237. package/docs/custom-provider/api-reference.md +119 -25
  238. package/docs/custom-provider/oauth.md +114 -132
  239. package/docs/custom-provider/override.md +37 -27
  240. package/docs/custom-provider/registration.md +107 -83
  241. package/docs/custom-provider/streaming.md +85 -71
  242. package/docs/custom-provider.md +85 -52
  243. package/docs/development.md +39 -29
  244. package/docs/docs.json +76 -63
  245. package/docs/environment-variables.md +94 -44
  246. package/docs/extensions/api-reference.md +86 -43
  247. package/docs/extensions/authoring.md +162 -154
  248. package/docs/extensions/events.md +80 -25
  249. package/docs/extensions/examples.md +90 -85
  250. package/docs/extensions/ui.md +206 -82
  251. package/docs/extensions.md +79 -108
  252. package/docs/getting-started/authentication.md +67 -36
  253. package/docs/getting-started/first-session.md +53 -43
  254. package/docs/getting-started/installation.md +116 -89
  255. package/docs/getting-started/project-instructions.md +48 -34
  256. package/docs/guides/configuration.md +82 -20
  257. package/docs/guides/non-interactive.md +66 -24
  258. package/docs/guides/resume-on-any-machine.md +135 -82
  259. package/docs/guides/team-setup.md +114 -105
  260. package/docs/guides.md +76 -32
  261. package/docs/herdr.md +15 -16
  262. package/docs/how-atomic-works.md +140 -0
  263. package/docs/index.md +58 -44
  264. package/docs/intercom/operations.md +141 -151
  265. package/docs/intercom/reference.md +85 -108
  266. package/docs/intercom.md +84 -145
  267. package/docs/json.md +120 -67
  268. package/docs/keybindings.md +85 -49
  269. package/docs/libraries/agent-core.md +137 -275
  270. package/docs/libraries/ai.md +100 -84
  271. package/docs/libraries/codemode.md +210 -300
  272. package/docs/libraries/schema.md +59 -53
  273. package/docs/libraries/storage-postgres.md +49 -35
  274. package/docs/libraries/telemetry.md +153 -354
  275. package/docs/libraries/tui.md +265 -393
  276. package/docs/libraries.md +42 -26
  277. package/docs/llama-cpp.md +171 -161
  278. package/docs/mcp-servers.md +90 -51
  279. package/docs/models/choose-a-model.md +188 -0
  280. package/docs/models/reference.md +74 -30
  281. package/docs/models.md +153 -88
  282. package/docs/orchestration/migrating-workflows.md +23 -16
  283. package/docs/orchestration/patterns.md +39 -44
  284. package/docs/orchestration.md +65 -26
  285. package/docs/packages/authoring.md +51 -29
  286. package/docs/packages/reference.md +42 -21
  287. package/docs/packages.md +69 -58
  288. package/docs/programmatic.md +118 -24
  289. package/docs/prompt-templates.md +84 -83
  290. package/docs/providers/reference.md +43 -48
  291. package/docs/providers.md +219 -451
  292. package/docs/quickstart.md +140 -120
  293. package/docs/reference/cli.md +135 -97
  294. package/docs/reference.md +20 -18
  295. package/docs/rpc/examples.md +76 -20
  296. package/docs/rpc/extension-ui.md +64 -38
  297. package/docs/rpc/protocol.md +361 -110
  298. package/docs/rpc.md +57 -17
  299. package/docs/sdk/reference.md +409 -534
  300. package/docs/sdk/storage.md +53 -13
  301. package/docs/sdk/structured-decisions.md +82 -56
  302. package/docs/sdk/web-server.md +57 -43
  303. package/docs/sdk.md +106 -84
  304. package/docs/security.md +42 -64
  305. package/docs/session-format.md +62 -38
  306. package/docs/sessions.md +99 -214
  307. package/docs/settings.md +165 -195
  308. package/docs/shell-aliases.md +9 -6
  309. package/docs/skills/authoring.md +69 -48
  310. package/docs/skills/reference.md +51 -20
  311. package/docs/skills.md +99 -148
  312. package/docs/slash-commands.md +129 -0
  313. package/docs/storage/custom-adapters.md +160 -85
  314. package/docs/storage/jsonl.md +81 -66
  315. package/docs/storage/postgres/pgbouncer.md +120 -126
  316. package/docs/storage/postgres/tuning.md +120 -143
  317. package/docs/storage/postgres.md +314 -330
  318. package/docs/storage/sqlite.md +71 -42
  319. package/docs/storage.md +298 -302
  320. package/docs/subagents/authoring.md +55 -38
  321. package/docs/subagents/reference.md +73 -33
  322. package/docs/subagents.md +119 -187
  323. package/docs/terminal-setup.md +50 -38
  324. package/docs/termux.md +67 -41
  325. package/docs/themes/reference.md +23 -19
  326. package/docs/themes.md +142 -127
  327. package/docs/tmux.md +47 -55
  328. package/docs/tools.md +147 -109
  329. package/docs/tui/reference.md +166 -214
  330. package/docs/tui.md +196 -341
  331. package/docs/usage.md +118 -138
  332. package/docs/verification.md +79 -51
  333. package/docs/web-access.md +121 -101
  334. package/docs/windows.md +26 -27
  335. package/docs/worktree-snapshots/reference.md +245 -0
  336. package/docs/worktree-snapshots.md +71 -259
  337. package/package.json +8 -8
  338. package/dist/_shared/startup-0-2-5QHPCEON.js.map +0 -1
  339. package/docs/guides/intercom.md +0 -32
  340. package/docs/guides/orchestration.md +0 -28
  341. package/docs/guides/subagents.md +0 -37
@@ -1,14 +1,14 @@
1
1
  ---
2
- title: "SDK storage backends"
3
- sidebarTitle: "Storage backends"
2
+ title: "Configure session storage"
3
+ sidebarTitle: "Configure storage"
4
4
  description: "Configure local SQLite, JSONL, in-memory, and PostgreSQL storage for createAgentSession(), createAgentSessionRuntime(), and SessionManager."
5
5
  ---
6
6
 
7
- By default, Atomic persists sessions in local SQLite at `~/.atomic/workflows/journal.sqlite` (`session_` table prefix). In SDK applications, you can select any built-in or remote backend per session, share one database connection across multiple sessions, or manage lifecycle explicitly through `createAgentSessionRuntime()` and `SessionManager`.
7
+ By default, Atomic persists sessions in local SQLite at `~/.atomic/workflows/journal.sqlite` (`session_` table prefix). In SDK applications, you can choose any of the four supported backends per session, share one database connection across multiple sessions, or manage lifecycle explicitly through `createAgentSessionRuntime()` and `SessionManager`.
8
8
 
9
9
  For CLI setup, database role administration, migrations, and custom drivers, see [Storage](/storage).
10
10
 
11
- ## Choosing a backend
11
+ ## Choose a backend
12
12
 
13
13
  | Backend | Package | How to pass it | Best for |
14
14
  | --- | --- | --- | --- |
@@ -127,7 +127,7 @@ import { createAgentSession, JsonlSessionStore } from "@bastani/atomic";
127
127
 
128
128
  Atomic offers three in-memory configurations with different release and rehydrate behavior:
129
129
 
130
- 1. **`SessionManager.inMemory()`:** Ephemeral private session with no external store handle. Cannot be released and rehydrated (`not-reopenable`).
130
+ 1. **`SessionManager.inMemory()`:** Ephemeral private session with no external store handle. Cannot be released and rehydrated (`not-reopenable`); combining it with `releaseWhenIdle` rejects immediately in `createAgentSession()`.
131
131
  2. **Caller-owned `new MemorySessionStore()`:** Keeps session history in process RAM across `session.release()` and `runtime.rehydrate()` without writing anything to disk. You own the store and close it with `await store.close()`.
132
132
  3. **Disk-spilling memory store via `resolveSessionStore(cwd, { agentDir, sessionStore: { kind: "memory" } })`:** Writes released session history to private owner-only files (`0700`/`0600`) under `<agentDir>/released-history/` to free RAM while idle, cleaning up files on close and process exit (throws `SessionSpillError` if a spill file is missing or corrupt).
133
133
 
@@ -292,14 +292,20 @@ try {
292
292
  }
293
293
  ```
294
294
 
295
- > **Module resolution for `{ kind: "adapter" }`:** Atomic resolves adapter package names from user-scope packages installed with `atomic install` (`~/.atomic/agent/npm`), paths passed in `DefaultResourceLoader({ additionalExtensionPaths: [packageRoot] })`, or relative to `agentDir` — **not** from your application's local `node_modules`. If your app installed `@bastani/atomic-storage-postgres` only with `npm install`, use **Option A** (`openPostgresDatabase()`), install the package in user scope (`atomic install npm:@bastani/atomic-storage-postgres`), pass its directory via `additionalExtensionPaths`, or pass a resolved file path (`fileURLToPath(import.meta.resolve(POSTGRES_ADAPTER_PACKAGE))`).
295
+ <Warning>
296
+ **`{ kind: "adapter" }` does not search your application's local `node_modules`.** Atomic resolves adapter package names from user-scope packages installed with `atomic install` (`~/.atomic/agent/npm`), directories passed in `DefaultResourceLoader({ additionalExtensionPaths: [packageRoot] })`, or paths relative to `agentDir`. If your app installed `@bastani/atomic-storage-postgres` only with `npm install`, use **Option A** (`openPostgresDatabase()`), install it in user scope (`atomic install npm:@bastani/atomic-storage-postgres`), pass its directory via `additionalExtensionPaths`, or pass a resolved file path (`fileURLToPath(import.meta.resolve(POSTGRES_ADAPTER_PACKAGE))`).
297
+ </Warning>
296
298
 
297
- > Atomic 0.10.11 removed libSQL and Turso support, including `@bastani/atomic-storage-libsql`, `teamProfileSelection()`, and `LIBSQL_ADAPTER_PACKAGE`. To move sessions off libSQL, see [Moving off libSQL](/storage#moving-off-libsql).
299
+ <Note>
300
+ Atomic 0.10.11 removed libSQL and Turso support, including `@bastani/atomic-storage-libsql`, `teamProfileSelection()`, and `LIBSQL_ADAPTER_PACKAGE`. To move sessions off libSQL, see [Moving off libSQL](/storage#moving-off-libsql).
301
+ </Note>
298
302
 
299
303
  ## `createAgentSessionRuntime()` and `SessionManager` with explicit stores
300
304
 
301
305
  Neither `createAgentSessionRuntime()` nor `createAgentSessionFromServices()` takes `sessionStore` or `storage` directly. Both take a pre-opened `sessionManager: SessionManager`, and every later `newSession()`, `switchSession()`, `fork()`, and `rehydrate()` call inherits the store from `sessionManager.getSessionStore()`.
302
306
 
307
+ Pass `interactive: true` to `createAgentSessionRuntime()` only when attaching an interactive UI; when omitted (`false`), resuming a worktree snapshot starts the first turn while the blueprint build runs in the background unless `resume.waitForBlueprint` is set. Call `runtime.takeResumeNotices()` after `switchSession()` or `rehydrate()` to retrieve resume warnings once.
308
+
303
309
  Use these explicit-store `SessionManager` methods to open, resume, and inspect sessions against any `SessionStore` (`SqlSessionStore`, `JsonlSessionStore`, `MemorySessionStore`, or a store from `resolveSessionStore()`):
304
310
 
305
311
  ```typescript
@@ -519,12 +525,46 @@ async function runWithStorageHandling(fn: () => Promise<void>): Promise<void> {
519
525
  }
520
526
  ```
521
527
 
522
- For the full list of storage error classes, cross-process `serializeStorageError()` / `rehydrateStorageError()`, and team setup errors, see [Storage errors](/storage#storage-errors) and [Session and storage errors](/sdk/reference#session-and-storage-errors).
528
+ For the full list of storage error classes and cross-process `serializeStorageError()` / `rehydrateStorageError()`, see [Storage errors](/storage#storage-errors) and [Session and storage errors](/sdk/reference#session-and-storage-errors).
529
+
530
+ ## Testing custom storage adapters
531
+
532
+ If you implement a custom `SqliteDatabase` driver or storage adapter, import `registerSqliteDatabaseConformance()` from `@bastani/atomic/storage/testing` to run Atomic's conformance test suite (parameter binding, binary blobs, transactions, rollbacks, reopening, and typed error contracts) inside your own test runner:
533
+
534
+ ```typescript
535
+ import { describe, it } from "vitest";
536
+ import { registerSqliteDatabaseConformance } from "@bastani/atomic/storage/testing";
537
+
538
+ registerSqliteDatabaseConformance({ describe, it }, "MyDatabaseAdapter", async (body) => {
539
+ const database = await openMyAdapter();
540
+ try {
541
+ await body({
542
+ database,
543
+ reopen: () => openMyAdapter(),
544
+ withRollbackFailure: async (cause, fn) => {
545
+ // Inject a rollback failure using `cause` while running `fn`
546
+ await fn();
547
+ },
548
+ });
549
+ } finally {
550
+ await database.close();
551
+ }
552
+ });
553
+ ```
523
554
 
524
555
  ## Related docs
525
556
 
526
- - [Operator storage setup](/storage): PostgreSQL roles, TLS, proxies, poolers, migrations, `atomic storage` commands, and custom drivers.
527
- - [`@bastani/atomic-storage-postgres`](/libraries/storage-postgres): PostgreSQL adapter options, cloud IAM, and SQL helpers.
528
- - [SDK overview](/sdk): `createAgentSession()`, workspaces, Intercom policies, and lifecycle hooks.
529
- - [SDK API reference](/sdk/reference): Full options, loaders, run modes, and exports.
530
- - [`SessionManager` API](/session-format#sessionmanager-api): Entry types, tree navigation, and session append methods.
557
+ <Columns cols={2}>
558
+ <Card title="Operator storage setup" href="/storage">
559
+ PostgreSQL roles, TLS, proxies, poolers, migrations, `atomic storage` commands, and custom drivers.
560
+ </Card>
561
+ <Card title="@bastani/atomic-storage-postgres" href="/libraries/storage-postgres">
562
+ PostgreSQL adapter options, PgBouncer auto-detection, cloud IAM, and SQL helpers.
563
+ </Card>
564
+ <Card title="Use the TypeScript SDK" href="/sdk">
565
+ `createAgentSession()`, workspaces, Intercom policies, and lifecycle hooks.
566
+ </Card>
567
+ <Card title="SessionManager API" href="/session-format#sessionmanager-api">
568
+ Entry types, tree navigation, and session append methods, plus [SDK API reference](/sdk/reference).
569
+ </Card>
570
+ </Columns>
@@ -1,14 +1,16 @@
1
1
  ---
2
- title: "Structured decisions API"
3
- sidebarTitle: "Structured decisions"
4
- description: "Make typed, schema-validated classifier or chat model decisions with decide() and generateStructuredOutput() without starting an agent session."
2
+ title: "Make structured decisions"
3
+ sidebarTitle: "Make decisions"
4
+ description: "Make typed, schema-validated classifier or chat model decisions with decide(), generateStructuredOutput(), and structured_output without starting an agent session."
5
5
  ---
6
6
 
7
- Atomic provides one decision service across three entry points:
7
+ Atomic provides one decision engine across three entry points:
8
8
 
9
- - [`decide()`](#decide) asks the configured [`decisionModel`](/settings#decisionmodel) typed `choice`, `bool`, and `score` questions and returns typed answers with optional probabilities.
10
- - The `structured_output` tool uses the same decision model and raises `DecisionError` subclasses on failure.
11
- - `generateStructuredOutput()` from `@bastani/atomic` makes one schema-validated decision on the models you pass through the same runtime.
9
+ | Entry point | Use when | Error contract |
10
+ | --- | --- | --- |
11
+ | [`decide()`](#decide) | You want typed `choice`, `bool`, or `score` answers (with classifier probabilities) and built-in secret screening | Always throws `DecisionError` subclasses (or `signal.reason` on caller abort) |
12
+ | [`generateStructuredOutput()`](#select-the-inference-model) | You need arbitrary JSON Schema output from explicit model candidates or `settings` | Wraps into `DecisionError` only when `settings` is passed and `model` is omitted (timeouts always throw `DecisionTimeoutError`) |
13
+ | `structured_output` tool | An agent session should infer and return a final schema-validated answer | Same as `generateStructuredOutput()` using session `decisionModel` unless the model passes an explicit `model` |
12
14
 
13
15
  None of these APIs starts a child agent, invokes other tools, authorizes an action, or changes the selected chat model.
14
16
 
@@ -16,11 +18,11 @@ None of these APIs starts a child agent, invokes other tools, authorizes an acti
16
18
 
17
19
  `decide({ state, questions, settings, modelRegistry, currentModel, ... })` evaluates one or more independent named questions against one `state` object in a single request:
18
20
 
19
- - `choice`: pick one option. `criteria` maps each option name to its meaning.
20
- - `bool`: a yes/no question. `criteria` defines what `true` and `false` mean.
21
- - `score`: grade on ordered levels. `criteria` lists at least two level descriptions, lowest first.
21
+ - **`choice`:** pick one option. `criteria` maps each option name to its meaning.
22
+ - **`bool`:** a yes/no question. `criteria` defines what `true` and `false` mean.
23
+ - **`score`:** grade on ordered levels. `criteria` lists at least two level descriptions, lowest first.
22
24
 
23
- `decide()` resolves `decisionModel` once. When a classifier answers, `source` is `"classifier"` and answers include probabilities and confidence scores. If the classifier fails, the current chat model answers without probabilities, sets `source: "chat"`, and populates `result.fallback`. An empty or `"auto"` `decisionModel` uses `currentModel` directly. Pass `requireProbabilities: true` to restrict answers to classifiers so chat models or classifier failures reject instead of falling back.
25
+ `decide()` resolves [`decisionModel`](/settings#decisionmodel) once. When a classifier answers, `source` is `"classifier"` and answers include probabilities and confidence scores. If the classifier fails, the current chat model answers without probabilities, sets `source: "chat"`, and populates `result.fallback`. An empty or `"auto"` `decisionModel` uses `currentModel` directly. Pass `requireProbabilities: true` to restrict answers to classifiers so chat models or classifier failures reject instead of falling back.
24
26
 
25
27
  Standalone SDK usage with `ModelRuntime`, `ModelRegistry`, and `SettingsManager`:
26
28
 
@@ -66,16 +68,14 @@ Inside an extension handler, pass `settings: { getDecisionModel: () => ctx.getDe
66
68
  - `state`: non-empty plain JSON object containing the facts to evaluate.
67
69
  - `questions`: non-empty record mapping caller-chosen IDs to `choice`, `bool`, or `score` question definitions.
68
70
  - `instructions`: optional top-level context shared across all questions. Defaults to ``"Answer each question about `state`."`` and must be non-blank if supplied.
69
- - `deadline`: optional positive integer wall-clock limit in milliseconds covering credential screening, requests, retries, repairs, and fallbacks. Defaults to [`httpIdleTimeoutMs`](/settings#http).
70
- - `retry`: optional `RetryPolicy` overriding default chat retries (`{ enabled: true, maxRetries: 3, baseDelayMs: 2000 }`).
71
- - `signal`: optional `AbortSignal`; cancellation rejects immediately with the signal's reason.
72
- - `model`: optional exact `provider/model` ID to use instead of `decisionModel`.
71
+ - `deadline`: optional positive safe integer wall-clock limit in milliseconds covering credential screening, requests, retries, repairs, and fallbacks. Defaults to `settings.getHttpIdleTimeoutMs?.()` (from [`httpIdleTimeoutMs`](/settings#http)), or 10 minutes if unset.
72
+ - `retry`: optional `RetryPolicy` for transient chat transport errors. Precedence is `request.retry` → `settings.getRetrySettings?.()` → `{ enabled: true, maxRetries: 3, baseDelayMs: 2000 }`.
73
+ - `signal`: optional `AbortSignal`; cancellation rejects immediately with `signal.reason`.
74
+ - `model`: optional exact `provider/model` ID to use instead of `decisionModel` (cannot be `"auto"` or have surrounding whitespace).
73
75
  - `requireProbabilities`: when `true`, only a classifier may answer.
74
76
 
75
77
  ### Return value (`DecisionResult`)
76
78
 
77
- `decide()` resolves with:
78
-
79
79
  ```typescript
80
80
  interface DecisionResult<Q> {
81
81
  answers: Record<keyof Q, DecisionAnswer>;
@@ -95,32 +95,39 @@ Each entry in `result.answers.<id>` matches its question type:
95
95
 
96
96
  Keep action logic in application code. Compare probabilities against per-action thresholds, require stricter thresholds for irreversible actions, and pair `choice` questions with a `bool` applicability check (because `choice` always picks one option). `decide()` never caches results; cache them yourself if needed.
97
97
 
98
- ### Credential screening boundary
98
+ ### Input validation and credential screening
99
99
 
100
- `decide()` actively screens `state` before sending any request. It snapshots `state` (so later caller mutations cannot alter an in-flight call) and rejects with `DecisionRequestError` (`reason: "credential-in-state"`) if `state` contains:
100
+ `decide()` validates and snapshots the request before calling any model so later caller mutations cannot alter an in-flight call. It rejects immediately with `DecisionRequestError` (`code: "invalid-request"`) if:
101
101
 
102
- - any known environment credential,
103
- - `Bearer` tokens, PEM private keys, or `sk-`, `ghp_`, or `github_pat_` key patterns, or
104
- - a credential configured in `modelRegistry`.
102
+ - `state` is empty, an array, cyclic, contains `NaN`/`Infinity`, or contains non-plain objects (such as `Date`, `Map`, or class instances);
103
+ - `questions` is empty, has blank/whitespace question IDs or option keys, blank instructions/criteria descriptions, or a `score` question with fewer than 2 levels;
104
+ - `instructions` is blank when supplied, `deadline` is not a positive safe integer, or `model` is `"auto"`, empty, or has leading/trailing whitespace; or
105
+ - `state` contains a credential (`reason: "credential-in-state"`): any known environment credential, `Bearer` tokens, PEM private keys, `sk-`/`ghp_`/`github_pat_` key patterns, or a credential configured in `modelRegistry`.
105
106
 
106
- `generateStructuredOutput()` does **not** run automatic credential screening. Always strip secrets from `state` and `instructions` yourself before calling `generateStructuredOutput()`.
107
+ If `modelRegistry.containsConfiguredCredential()` throws during screening, `decide()` rejects with `DecisionProviderError` (`detail: "configured-credential screening failed before any model was asked"`).
107
108
 
108
- ### Errors
109
+ <Warning>
110
+ `generateStructuredOutput()` does **not** run automatic credential screening. Always strip secrets from `state` and `instructions` yourself before calling `generateStructuredOutput()`.
111
+ </Warning>
109
112
 
110
- Every failure from `decide()` rejects with a `DecisionError`. Branch on the error class or `code`, never on message text.
113
+ ### Errors {#errors}
111
114
 
112
- Each error includes `hint`, `retryable`, and `cause`. `isDecisionError(error)` and the per-class guards recognize errors across process boundaries. Use `serializeDecisionError()` and `rehydrateDecisionError()` to transport errors between processes, and `findDecisionError(error)` or `isRetryableDecisionError(error)` to walk a `cause` chain. Validate untrusted serialized payloads with `parseSerializedDecisionError()` before calling `rehydrateDecisionError()` (returns `undefined` when malformed).
115
+ Every failure from `decide()` rejects with a `DecisionError` (except caller cancellation, which rejects with `signal.reason`). Branch on the error class, type guard, or `code` — never on message text.
113
116
 
114
- Legacy `routerModel` settings migrate to `decisionModel` automatically. An existing `decisionModel` takes precedence, and invalid legacy values are ignored with a one-time warning. See [decisionModel](/settings#decisionmodel).
117
+ Every `DecisionError` exposes `code`, `hint`, `retryable`, `cause`, and `fields()` (returning the JSON-safe structured fields for that subclass). Use `isDecisionError(error)` and the per-class guards across process boundaries, `findDecisionError(error)` or `isRetryableDecisionError(error)` to walk a `cause` chain, and `serializeDecisionError()` / `parseSerializedDecisionError()` / `rehydrateDecisionError()` to transport errors across processes (`parseSerializedDecisionError()` returns `undefined` for malformed payloads).
115
118
 
116
- | Class | `code` | When | Fields | What to do |
119
+ | Class | `code` | When | Fields (`error.fields()`) | What to do |
117
120
  | --- | --- | --- | --- | --- |
118
- | `DecisionConfigError` | `invalid-setting` (or legacy decode-only `renamed-setting`) | `decisionModel` is not a string or has surrounding whitespace | `source`, `field`, optional `scope` (`"global" \| "project"`) | Set an exact `provider/model`, `"auto"`, or `""`. |
119
- | `DecisionRequestError` | `invalid-request` | Empty or non-JSON `state`, credential in `state`, no questions, malformed question, blank `instructions`, invalid `deadline`, or invalid `model` | `field`, `reason` | Fix the request; nothing was sent. |
121
+ | `DecisionConfigError` | `invalid-setting` | `decisionModel` is not a string or has surrounding whitespace | `source`, `field`, optional `scope` (`"global" \| "project"`) | Set an exact `provider/model`, `"auto"`, or `""`. |
122
+ | `DecisionRequestError` | `invalid-request` | Invalid `state`, credential in `state`, malformed `questions`, blank `instructions`, invalid `deadline`, or invalid `model` | `field`, `reason` | Fix the request; nothing was sent. |
120
123
  | `DecisionModelUnavailableError` | `model-unavailable` | `decisionModel` is not a registered chat or classifier model (`not-in-catalog`), no chat model is selected (`no-chat-model`), probabilities are required from a chat model (`no-probabilities`), or the host provides no decision model or registry (`host-unsupported`) | `reason`, `model` | Choose another decision model or select a chat model. |
121
- | `DecisionTimeoutError` | `timeout` | The wall-clock deadline expired | `timeoutMs`, `elapsedMs`, `phase`, `attempts` | Retry, or raise `deadline` / `timeoutMs`. Retryable. |
124
+ | `DecisionTimeoutError` | `timeout` | The wall-clock deadline expired | `timeoutMs`, `elapsedMs`, `phase`, `attempts` | Retry, or raise `deadline` / `timeoutMs`. `retryable` is `true`. |
122
125
  | `DecisionOutputError` | `invalid-output` | The model responded, but output failed schema validation after repairs | `model`, `detail` | Clarify questions or pick another model. |
123
- | `DecisionProviderError` | `provider-failure` | The provider request failed | `model`, `providerStatus`, `providerCode`, `retryAfterMs`, `detail` | Retryable on rate limits or quota exhaustion (`providerCode`); otherwise check provider status and auth. |
126
+ | `DecisionProviderError` | `provider-failure` | The provider request failed (or credential screening threw) | `model`, `providerStatus`, `providerCode`, `retryAfterMs`, `detail` | `retryable` is `true` **only** when `providerCode` is `"rate_limit_exceeded"` or `"insufficient_quota"`; otherwise check provider status and auth. |
127
+
128
+ <Note>
129
+ Legacy `routerModel` entries in `settings.json` migrate to `decisionModel` automatically (an existing `decisionModel` wins, and invalid legacy values are ignored with a one-time warning). `DecisionConfigError` still recognizes the legacy decode-only code `"renamed-setting"` when rehydrating serialized errors from older processes. See [decisionModel](/settings#decisionmodel).
130
+ </Note>
124
131
 
125
132
  ```typescript
126
133
  import { decide, isDecisionError, isDecisionProviderError, isDecisionTimeoutError } from "@bastani/atomic";
@@ -152,7 +159,8 @@ try {
152
159
  break;
153
160
  case "provider-failure":
154
161
  if (isDecisionProviderError(error) && error.retryable) {
155
- console.error(`Retryable provider error (${error.providerCode ?? "transient"}); wait ${error.retryAfterMs ?? 0}ms.`);
162
+ // retryable is true only when providerCode is "rate_limit_exceeded" or "insufficient_quota".
163
+ console.error(`Retryable provider error (${error.providerCode}); wait ${error.retryAfterMs ?? 0}ms.`);
156
164
  } else {
157
165
  console.error(error.hint);
158
166
  }
@@ -161,17 +169,26 @@ try {
161
169
  case "invalid-setting":
162
170
  case "invalid-request":
163
171
  case "invalid-output":
164
- case "renamed-setting":
165
172
  console.error(`${error.code}: ${error.hint}`);
166
173
  break;
167
174
  }
168
175
  }
169
176
  ```
170
177
 
171
- ## How `decisionModel` applies across APIs
178
+ ## How `decisionModel` and `DecisionError` wrapping apply
172
179
 
173
- - **The `structured_output` tool** (when called without its own `model`) starts on `decisionModel`. A classifier answers when the schema is a finite Choice; otherwise Atomic tries `fallbackModels` and then `currentModel`. Failures always reject with a `DecisionError`.
174
- - **`generateStructuredOutput()`** uses only the models you pass (`model`, `fallbackModels`, `currentModel`) unless you pass `settings`, in which case omitting `model` starts on `decisionModel` like the tool. Note: calling `generateStructuredOutput()` **without `settings`** throws plain `Error` instances rather than `DecisionError` subclasses; `DecisionError` wrapping applies whenever `settings` is passed or when calling `decide()` or `structured_output`.
180
+ `DecisionError` wrapping differs between `decide()`, `generateStructuredOutput()`, and `structured_output`:
181
+
182
+ <Warning>
183
+ In `generateStructuredOutput()` (and the `structured_output` tool), passing an explicit `model` causes Atomic to **ignore `settings`** (`decisionModel` is not consulted), so inference, output, and provider errors throw plain `Error` instances rather than `DecisionError` subclasses. Input validation errors (invalid `maxTokens`, invalid `state`, blank `instructions`, invalid `currentModel`, invalid `timeoutMs`, or missing `model`/`currentModel`) also throw plain `Error` even when `settings` is passed.
184
+ </Warning>
185
+
186
+ - **`decide()`:** Always resolves `decisionModel` (or validates explicit `model`) and wraps every failure into a `DecisionError` subclass (except caller aborts, which reject with `signal.reason`).
187
+ - **`generateStructuredOutput()`:**
188
+ - **With `settings` and `model` omitted:** resolves `decisionModel` (throwing `DecisionConfigError` or `DecisionModelUnavailableError` immediately if invalid) and wraps inference/output/provider failures into `DecisionError` subclasses (`DecisionOutputError`, `DecisionProviderError`). Input validation errors still throw plain `Error`.
189
+ - **Without `settings`, OR with an explicit `model`:** ignores `settings` and throws plain `Error` instances on resolution, inference, output, and provider failures.
190
+ - **Timeouts:** Always reject with `DecisionTimeoutError` regardless of whether `settings` or `model` was passed.
191
+ - **`structured_output` tool:** Delegates to `generateStructuredOutput()` with session `settings` and `timeoutMs` resolved from the session's `httpIdleTimeoutMs`. When the calling model omits `model`, it starts on `decisionModel` and wraps inference failures into `DecisionError`; when the calling model passes an explicit `model`, `settings` is ignored and non-timeout failures throw plain `Error`.
175
192
 
176
193
  ### Switch `decisionModel` on a live session
177
194
 
@@ -192,14 +209,14 @@ session.setDecisionModel("auto", "project", { persist: false });
192
209
 
193
210
  ## Select the inference model
194
211
 
195
- Pass an optional exact `provider/model` string (not a `Model` object and not `"auto"`):
212
+ In `generateStructuredOutput()`, pass an optional exact `provider/model` string (not a `Model` object and not `"auto"`):
196
213
 
197
214
  - `model`: primary candidate (chat model or registered classifier such as `typesafe/jev-latest`).
198
215
  - `fallbackModels`: ordered list of exact `provider/model` IDs.
199
216
  - Omit `model` to start on `decisionModel` when `settings` is passed, or on `currentModel` otherwise.
200
217
  - After `model` and `fallbackModels`, Atomic tries `currentModel` if it has not already been tried.
201
218
 
202
- Image-generation models, wildcard patterns, reasoning suffixes, surrounding whitespace, and unregistered IDs are invalid. Atomic skips invalid `model`/`fallbackModels` entries, records each error in `modelAttempts`, and advances to the remaining candidates including `currentModel` (failing with the first error only when no candidate resolves). When `model` is omitted and `settings` is provided, an invalid or unregistered `decisionModel` fails immediately with a [`DecisionError`](#errors) instead of skipping.
219
+ Image-generation models, wildcard patterns, reasoning suffixes, surrounding whitespace, and unregistered IDs are invalid. When `model` is explicitly passed (or `settings` is omitted), Atomic skips invalid `model`/`fallbackModels` entries, records each error in `modelAttempts`, and advances to the remaining candidates including `currentModel` (failing with the first error only when no candidate resolves). When `model` is omitted and `settings` is provided, an invalid or unregistered `decisionModel` fails immediately with a [`DecisionError`](#errors) instead of skipping.
203
220
 
204
221
  ### Choice-compatible schemas
205
222
 
@@ -232,11 +249,9 @@ const result = await generateStructuredOutput({
232
249
  console.log(result.value.category, result.model);
233
250
  ```
234
251
 
235
- `result.value` holds the schema-validated result, `result.model` identifies the candidate that answered, and `result.modelAttempts` records skipped and failed candidates when a fallback chain ran.
236
-
237
- `result.usage` reports chat token usage when a chat candidate produced the result (classifier billing is reported separately by the classifier operation). A schema-valid result does not guarantee policy compliance, so check the result against your own rules before acting.
252
+ `result.value` holds the schema-validated result, `result.model` identifies the candidate that answered, and `result.modelAttempts` records skipped and failed candidates when a fallback chain ran. `result.usage` reports chat token usage when a chat candidate produced the result (classifier billing is reported separately by the classifier operation). A schema-valid result does not guarantee policy compliance, so check the result against your own rules before acting.
238
253
 
239
- The `structured_output` tool accepts required `instructions`, non-empty named `state`, and optional `model` and `fallbackModels` from the calling model. `createStructuredOutputTool({ schema })` fixes the output schema. The calling model cannot override the deadline; set it with `timeoutMs`. See [Structured output final results](/sdk/reference#structured-output-final-results).
254
+ The `structured_output` tool accepts required `instructions`, non-empty named `state`, and optional `model` and `fallbackModels` from the calling model. `createStructuredOutputTool({ schema })` fixes the output schema; the calling model cannot override the deadline (set it with `timeoutMs`). See [Structured output final results](/sdk/reference#structured-output-final-results).
240
255
 
241
256
  ## Prepare a decision
242
257
 
@@ -244,28 +259,39 @@ Put the task criteria in `instructions` and all relevant facts, constraints, and
244
259
 
245
260
  For `generateStructuredOutput()`, supply `instructions`, `state`, and `schema` (prefer `{ additionalProperties: false }` on object schemas). Keep numeric thresholds in application code, and add an explicit abstention option when no choice may fit.
246
261
 
247
- ## Provider behavior and limits
262
+ ## Provider behavior and limits {#provider-behavior-and-limits}
248
263
 
249
- Chat candidates receive one internal result tool matching `schema`. Atomic serializes schemas per provider, enables strict sampling where supported, and validates returned arguments without type coercion or stripping extra keys. Always set `additionalProperties: false` on closed objects. Prose-only replies, extra tool calls, truncated output, or invalid payloads trigger up to 3 repair attempts (1 initial attempt plus 3 repairs) before advancing to the next fallback candidate.
264
+ | Behavior | Chat models | Classifiers (for example [TypeSafe Jev](/providers#typesafe-jev)) |
265
+ | --- | --- | --- |
266
+ | **Schema support** | Any valid JSON Schema | Finite Choice schemas only (skipped otherwise) |
267
+ | **Execution mechanism** | One internal result tool matching `schema`, strict sampling where supported, validated without coercion or key stripping | One `classify` call with `state` and derived choice questions (no trimming of `state`) |
268
+ | **Repair loop** | Up to 3 repair attempts (1 initial + 3 repairs) for prose-only replies, extra tool calls, truncated output, or invalid payloads | No repair loop; invalid or rejected requests advance directly to the next fallback candidate |
269
+ | **Transport and retries** | HTTP/SSE only (no WebSocket fallback; Anthropic server-side fallbacks disabled); transient transport errors follow `retry` (default `{ enabled: true, maxRetries: 3, baseDelayMs: 2000 }`) | Provider `classify` implementation owns transport retries within the shared abort signal and retry limit |
270
+ | **Probabilities & confidence** | Not returned | Returned on `decide()` answers; advisory and never reject an otherwise valid option |
250
271
 
251
- Use `Type.Optional(...)` for fields that may be omitted. When a strict provider encodes an omitted optional field as `null`, Atomic strips that `null` placeholder if the property schema rejects `null` (including inside nested objects and array items). Allow `null` explicitly in the schema if `null` is a valid answer.
272
+ ### Optional fields and `null` placeholders
252
273
 
253
- Chat decisions use HTTP/SSE transport (not WebSocket fallback) and disable configured Anthropic server-side fallbacks. Transient chat transport errors follow `retry` (default `{ enabled: true, maxRetries: 3, baseDelayMs: 2000 }`). Classifier calls invoke the provider's `classify` method with the retry limit and abort signal; provider implementations own transport retries.
274
+ Use `Type.Optional(...)` for fields that may be omitted. When a strict chat provider encodes an omitted optional field as `null`, Atomic strips that `null` placeholder if the property schema rejects `null` (including inside nested objects and array items). Allow `null` explicitly in the schema if `null` is a valid answer. Always set `additionalProperties: false` on closed objects.
254
275
 
255
- Registered classifiers (such as [TypeSafe Jev](/providers#typesafe-jev)) receive `state` and derived choice questions in one `classify` call without trimming `state`. If a classifier rejects the size or context, or cannot represent the schema, Atomic skips or advances to the next candidate without retrying the rejected request.
276
+ ## Cancellation and failures {#cancellation-and-failures}
256
277
 
257
- Atomic verifies that every classifier answer chooses a valid option. Reported model names, probabilities, and confidence values are advisory and never reject an otherwise valid answer.
278
+ ### Deadlines and timeouts
258
279
 
259
- ## Cancellation and failures
280
+ One wall-clock deadline covers the entire call: credential screening, every repair attempt, transport retry, and fallback candidate combined. Configure it with `deadline` (in `decide()`) or `timeoutMs` (in `generateStructuredOutput()` and `createStructuredOutputTool()`) as a positive safe integer in milliseconds. Atomic checks the deadline before every retry so overdue backoffs never start another request.
260
281
 
261
- One wall-clock deadline covers the entire call: every repair attempt, transport retry, and fallback candidate combined. Configure it with `timeoutMs` (or `deadline` in `decide()`) as a positive safe integer in milliseconds. Atomic checks the deadline before every retry so overdue backoffs never start another request.
282
+ - **Default deadline:**
283
+ - `decide()` and `structured_output`: read `httpIdleTimeoutMs` from settings/session first, then fall back to 10 minutes (`600_000` ms).
284
+ - Standalone `generateStructuredOutput()`: defaults directly to 10 minutes (`600_000` ms) and does **not** read `settings.getHttpIdleTimeoutMs()`. Pass `timeoutMs` explicitly to override it.
285
+ - Setting `httpIdleTimeoutMs` to `0` (`"disabled"`) uses JavaScript's maximum timer delay (`2,147,483,647` ms, ~24.8 days).
286
+ - **On expiration:** Atomic aborts the in-flight request (even if the provider ignores abort signals) and rejects with `DecisionTimeoutError`, including `timeoutMs`, `elapsedMs`, `phase`, `hint`, and per-attempt timings (for example, `Attempts: 1) stopReason=stop 25m02s; 2) still generating 4m58s.`). Timeouts are final and never trigger further repairs or fallbacks.
262
287
 
263
- When omitted, `structured_output` uses the session's [`httpIdleTimeoutMs`](/settings#http) setting and standalone calls default to 10 minutes. Disabling the idle timeout (`0` or `"disabled"`) leaves only the JavaScript timer limit (~24.8 days). Increase the deadline for slow reasoning models or large `state` payloads.
288
+ ### Caller cancellation (`AbortSignal`)
264
289
 
265
- When the deadline expires, Atomic aborts the in-flight request (even if the provider ignores abort signals) and rejects with `DecisionTimeoutError`, including the deadline, phase, hint, and per-attempt timings (for example, `Attempts: 1) stopReason=stop 25m02s; 2) still generating 4m58s.`). Timeouts are final and do not trigger further repairs or fallbacks.
290
+ Pass an `AbortSignal` (such as `AbortSignal.timeout(ms)`) to cancel sooner; cancellation stops the in-flight request immediately and halts the fallback chain:
266
291
 
267
- Pass an `AbortSignal` (such as `AbortSignal.timeout(ms)`) to cancel sooner; cancellation rejects immediately and halts the fallback chain.
292
+ - **`decide()`** rejects with `signal.reason`.
293
+ - **`generateStructuredOutput()`** replaces non-timeout caller aborts with a plain `Error("Structured output cancelled; no decision was accepted.")` (discarding custom `signal.reason`).
268
294
 
269
- `generateStructuredOutput()` sets no default output token cap; pass optional `maxTokens` as a positive safe integer up to `2,147,483,647` to cap output below the model's limit.
295
+ ### Output token cap and error hygiene
270
296
 
271
- Provider errors report static reasons without raw response bodies or credentials. Classifier failures and chat provider errors advance to the next fallback candidate; ordinary chat text without a valid tool call gets up to 3 repair attempts before advancing.
297
+ `generateStructuredOutput()` sets no default output token cap; pass optional `maxTokens` as a positive safe integer up to `2,147,483,647` to cap output below the model's limit. Provider errors report static reasons without raw response bodies or credentials. Classifier failures and chat provider errors advance to the next fallback candidate; ordinary chat text without a valid tool call gets up to 3 repair attempts before advancing.
@@ -1,47 +1,49 @@
1
1
  ---
2
- title: "Embed Atomic in a web server"
3
- sidebarTitle: "Web server guide"
2
+ title: "Stream from a web server"
3
+ sidebarTitle: "Stream over HTTP"
4
4
  description: "Run Atomic sessions behind a Next.js App Router endpoint and stream newline-delimited JSON output to a browser."
5
5
  ---
6
6
 
7
- This guide puts an Atomic agent behind an HTTP endpoint using Next.js App Router. The same pattern works in any long-running Node.js server: keep one session per conversation, start a prompt per request, and stream session events back as newline-delimited JSON (NDJSON).
7
+ This guide puts an Atomic agent behind an HTTP endpoint using Next.js App Router. The same pattern works in any long-running Node.js server: keep one session per conversation, start one prompt per request, and stream session events back as newline-delimited JSON (NDJSON).
8
8
 
9
- Read [TypeScript SDK](/sdk) first for `createAgentSession()`, `AgentSession`, `AgentSessionRuntime`, and session events. For servers that release idle sessions and rehydrate them on later requests, wrap sessions with `createAgentSessionRuntime()` instead (see [Releasing idle sessions](/sdk#releasing-idle-sessions)).
9
+ Read [Use the TypeScript SDK](/sdk) first for `createAgentSession()`, `AgentSession`, `AgentSessionRuntime`, and session events. For servers that release idle sessions and rehydrate them on later requests, wrap sessions with `createAgentSessionRuntime()` instead (see [Releasing idle sessions](/sdk#releasing-idle-sessions)).
10
10
 
11
- ## Install
11
+ ## Prerequisites and setup
12
12
 
13
- ```bash
14
- npm install @bastani/atomic
15
- ```
16
-
17
- Atomic requires Node.js 24.20 or newer. Dependency install scripts are not required; if your package manager blocks install scripts, leave them disabled.
18
-
19
- ## Keep Atomic out of the server bundle
13
+ <Steps>
14
+ <Step title="Install @bastani/atomic">
15
+ Atomic requires Node.js 24.20 or newer. Dependency install scripts are not required; if your package manager blocks install scripts, leave them disabled.
20
16
 
21
- Atomic resolves its bundled resources and native modules relative to `node_modules`, so keep it outside Next.js's server bundle using `serverExternalPackages` (Next.js 15 and later):
17
+ ```bash
18
+ npm install @bastani/atomic
19
+ ```
20
+ </Step>
21
+ <Step title="Keep Atomic external to the server bundle">
22
+ Atomic resolves its bundled resources and native modules relative to `node_modules`, so list it in `serverExternalPackages` (Next.js 15 and later):
22
23
 
23
- ```typescript
24
- // next.config.ts
25
- import type { NextConfig } from "next";
24
+ ```typescript
25
+ // next.config.ts
26
+ import type { NextConfig } from "next";
26
27
 
27
- const nextConfig: NextConfig = {
28
- serverExternalPackages: ["@bastani/atomic", "@bastani/atomic-natives", "@bastani/atomic-ai"],
29
- };
28
+ const nextConfig: NextConfig = {
29
+ serverExternalPackages: ["@bastani/atomic", "@bastani/atomic-natives", "@bastani/atomic-ai"],
30
+ };
30
31
 
31
- export default nextConfig;
32
- ```
32
+ export default nextConfig;
33
+ ```
33
34
 
34
- Once `@bastani/atomic` is external, its dependencies load from `node_modules`. List any other Atomic packages your application imports directly, including [`@bastani/atomic-storage-postgres`](/libraries/storage-postgres) when using remote SQL storage (see [SDK storage guide](/sdk/storage)).
35
+ List any other Atomic packages your server imports directly, including [`@bastani/atomic-storage-postgres`](/libraries/storage-postgres) when storing sessions in PostgreSQL (see [Configure session storage](/sdk/storage)).
36
+ </Step>
37
+ <Step title="Use the Node.js runtime and Atomic's TypeBox subpath">
38
+ Every route handler that imports Atomic must run on the Node.js runtime, not Edge:
35
39
 
36
- Import TypeBox for custom tool schemas from `@bastani/atomic/typebox` (and its subpaths such as `/value`, `/compile`, and `/format`) rather than `typebox` directly so custom formats and settings share Atomic's TypeBox registry.
40
+ ```typescript
41
+ export const runtime = "nodejs";
42
+ ```
37
43
 
38
- Every route that imports Atomic must run on the Node.js runtime:
39
-
40
- ```typescript
41
- export const runtime = "nodejs";
42
- ```
43
-
44
- Import Atomic only from server code. Client components may use `import type` from `@bastani/atomic`, which adds zero bytes to the browser bundle.
44
+ Import Atomic only from server code (client components may use `import type` from `@bastani/atomic`, which adds zero bytes to the browser bundle). When defining custom tool schemas, import TypeBox from `@bastani/atomic/typebox` (and its subpaths such as `/value`, `/compile`, and `/format`) so custom formats share Atomic's validation registry.
45
+ </Step>
46
+ </Steps>
45
47
 
46
48
  ## Keep one session per conversation
47
49
 
@@ -126,9 +128,11 @@ if (!state.shutdownRegistered) {
126
128
  }
127
129
  ```
128
130
 
129
- `SessionManager.inMemory()` keeps history in process memory. To persist conversations across restarts, pass a SQLite, JSONL, or PostgreSQL `SessionManager` or `sessionStore` (see [SDK storage guide](/sdk/storage)). Call `closeConversation()` when a conversation finishes or goes idle, and run `closeAllConversations()` on `SIGTERM`/`SIGINT` so session stores and child processes close cleanly.
131
+ <Warning>
132
+ Sessions stored on `globalThis` live in one Node.js server process. Run this pattern on a long-lived server with sticky routing per conversation if you scale to multiple instances; short-lived serverless functions discard process memory between requests.
133
+ </Warning>
130
134
 
131
- Sessions on `globalThis` live in one server process. Run this on a long-lived Node.js server with sticky routing per conversation if you scale to multiple instances; short-lived serverless functions discard process memory between requests.
135
+ `SessionManager.inMemory()` keeps history only in RAM. To persist conversations across restarts or share them across servers, pass a SQLite, JSONL, or PostgreSQL `SessionManager` or `sessionStore` (see [Configure session storage](/sdk/storage)). Call `closeConversation()` when a conversation finishes or goes idle, and run `closeAllConversations()` on `SIGTERM`/`SIGINT` so session stores and child processes close cleanly.
132
136
 
133
137
  ## Stream a prompt
134
138
 
@@ -219,9 +223,8 @@ Key behaviors:
219
223
  - **One prompt at a time:** `session.prompt()` rejects while streaming, so the route returns `409` and flips `busy` synchronously to prevent races. To queue prompts instead of rejecting, call `session.prompt(message, { streamingBehavior: "followUp" })`.
220
224
  - **Stop on disconnect:** When the browser disconnects or aborts `fetch`, `request.signal` and `cancel()` call `session.abort()`, stopping the current turn and tools while keeping the session reusable.
221
225
  - **Payload throttling:** Each line emits the complete transcript so far. For long responses, throttle updates on a short timer or send incremental diffs.
222
- - **Error sanitization:** Log raw errors server-side and send sanitized user-safe error messages to the browser.
223
-
224
- `createTranscript()` returns a tool result's text by default. To send structured `details` for specific tools instead, pass `createTranscript({ toolResult: (toolName) => (toolName === "todo" ? "details" : "content") })`.
226
+ - **Structured tool details:** `createTranscript()` returns a tool result's text by default. Pass `createTranscript({ toolResult: (toolName) => (toolName === "todo" ? "details" : "content") })` to emit structured `details` for specific tools.
227
+ - **Error sanitization:** Log raw errors server-side and return generic user-safe messages to the browser.
225
228
 
226
229
  ## Read the stream in the browser
227
230
 
@@ -266,19 +269,30 @@ Render each part by `type`: `text` and `thinking` hold strings, and a `toolCall`
266
269
 
267
270
  ## Secure the endpoint
268
271
 
269
- Any route driving an agent session lets callers run tools with the server process's OS permissions. Atomic has [no built-in sandbox](/security#no-built-in-sandbox).
272
+ <Warning>
273
+ Atomic has [no built-in sandbox](/security#no-built-in-sandbox). Any HTTP route driving an agent session lets callers execute enabled tools with the server process's OS permissions, and `cwd` does not jail file tools to that directory.
274
+ </Warning>
270
275
 
271
276
  - **Require authentication** on every route that creates sessions or sends prompts, and scope conversation IDs to the authenticated user.
272
- - **Allow only needed tools.** `tools` is an allowlist; the example enables only read-only `read`, `find`, and `search`. Omit `bash`, `edit`, and `write` unless the agent must mutate files or run commands. `excludedTools` removes tools, and `noTools: "all"` exposes none. Omit `ask_user_question` in headless sessions. See [Tools](/sdk/reference#tools).
277
+ - **Allow only needed tools.** `tools` is an allowlist; the example enables only read-only `read`, `find`, and `search`. Omit `bash`, `edit`, and `write` unless the agent must mutate files or run commands. Use `excludedTools` to strip specific tools or `noTools: "all"` to expose none, and omit `ask_user_question` in headless servers. See [Tools](/sdk/reference#tools).
273
278
  - **Disable unused builtins.** Turn off `subagents`, `mcp`, `web-access`, and `intercom` via `builtins` when not required.
274
- - **Choose `cwd` deliberately.** `cwd` sets the starting directory for relative tool paths and project discovery, but does not jail file access (tools can read absolute paths outside `cwd`). Point `cwd` at a controlled directory, never user input.
279
+ - **Choose `cwd` deliberately.** `cwd` sets the starting directory for relative paths and project discovery, but tools can still access absolute paths outside `cwd`. Point `cwd` at a controlled directory, never user input.
275
280
  - **Isolate the process** in a container, VM, or restricted OS account whenever callers must not reach other server files or when write/shell tools are enabled. See [Containerization](/containerization).
276
281
  - **Keep credentials server-side.** Provider keys live in the server's `ModelRuntime`. Never forward them to browsers or accept raw keys from untrusted clients.
277
282
 
278
283
  ## Next steps
279
284
 
280
- - [TypeScript SDK](/sdk): sessions, prompting, storage, and events.
281
- - [SDK storage guide](/sdk/storage): persist server sessions in SQLite, JSONL, or PostgreSQL and wire `createAgentSessionRuntime()`.
282
- - [SDK API reference](/sdk/reference): every `createAgentSession()` option and export.
283
- - [Orchestration](/orchestration): multi-step workflows with codemode and subagents.
284
- - [Migrating workflows](/orchestration/migrating-workflows): replacing older workflow definitions.
285
+ <Columns cols={2}>
286
+ <Card title="Use the TypeScript SDK" href="/sdk">
287
+ Sessions, prompting, workspaces, Intercom policies, and lifecycle hooks.
288
+ </Card>
289
+ <Card title="Configure session storage" href="/sdk/storage">
290
+ Persist server sessions in SQLite, JSONL, or PostgreSQL and wire `createAgentSessionRuntime()`.
291
+ </Card>
292
+ <Card title="SDK API reference" href="/sdk/reference">
293
+ Every `createAgentSession()` option, runtime method, error class, and export.
294
+ </Card>
295
+ <Card title="Orchestration" href="/orchestration">
296
+ Multi-step workflows with codemode and subagents, plus [migrating older workflows](/orchestration/migrating-workflows).
297
+ </Card>
298
+ </Columns>