@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,10 +1,10 @@
1
1
  ---
2
2
  title: "@bastani/atomic-agent-core"
3
3
  sidebarTitle: "@bastani/atomic-agent-core"
4
- description: "Stateful agent loop with tool execution, event streaming, steering, and follow-up messages."
4
+ description: "Stateful agent loop with tool execution, event streaming, steering, follow-up messages, and proxy streaming."
5
5
  ---
6
6
 
7
- Stateful agent with tool execution and event streaming, built on [`@bastani/atomic-ai`](/libraries/ai) (requires Node.js 24.20+). Atomic's sessions run on this agent loop, and you can use it directly to build your own agent. Atomic's [TypeScript SDK](/sdk) wraps it with sessions, tools, extensions, and compaction, so prefer the SDK when you want Atomic's built-in behavior. See [Standalone libraries](/libraries) for all standalone packages.
7
+ Stateful agent loop with tool execution and event streaming, built on [`@bastani/atomic-ai`](/libraries/ai) (requires Node.js 24.20+). Atomic's sessions run on this loop, and you can use it directly to build custom agents. Atomic's [TypeScript SDK](/sdk) wraps it with sessions, tools, extensions, and compaction, so prefer the SDK when you want Atomic's built-in behavior. See [Standalone libraries](/libraries) for all standalone packages.
8
8
 
9
9
  ## Installation
10
10
 
@@ -36,7 +36,6 @@ const agent = new Agent({
36
36
 
37
37
  agent.subscribe((event) => {
38
38
  if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
39
- // Stream just the new text chunk
40
39
  process.stdout.write(event.assistantMessageEvent.delta);
41
40
  }
42
41
  });
@@ -48,31 +47,20 @@ await agent.prompt("Hello!");
48
47
 
49
48
  ### AgentMessage vs LLM Message
50
49
 
51
- The agent works with `AgentMessage`, which can include:
52
-
53
- - Standard LLM messages (`system`, `user`, `assistant`, and `toolResult`)
54
- - Custom app-specific message types added through declaration merging
55
-
56
- LLMs accept only `system`, `user`, `assistant`, and `toolResult` messages. `convertToLlm` filters and transforms custom message types before each LLM call.
57
-
58
- ### Message flow
50
+ The agent works with `AgentMessage`, which includes standard LLM messages (`system`, `user`, `assistant`, and `toolResult`) plus any custom app-specific message types added through declaration merging. Because LLMs accept only standard message roles, `convertToLlm` filters or transforms custom types before each request:
59
51
 
60
52
  ```text
61
53
  AgentMessage[] -> transformContext() -> AgentMessage[] -> convertToLlm() -> Message[] -> LLM
62
54
  (optional) (required)
63
55
  ```
64
56
 
65
- 1. **`transformContext`.** Prune old messages or inject external context.
66
- 2. **`convertToLlm`.** Filter out UI-only messages and convert custom types to LLM messages.
57
+ 1. **`transformContext`:** Prune old messages or inject external context.
58
+ 2. **`convertToLlm`:** Filter out UI-only messages and convert custom types to LLM messages.
67
59
 
68
60
  ## Event flow
69
61
 
70
- The agent emits events as turns run so your interface can update incrementally.
71
-
72
62
  ### `prompt()` event sequence
73
63
 
74
- When you call `prompt("Hello")`:
75
-
76
64
  ```text
77
65
  prompt("Hello")
78
66
  ├─ agent_start
@@ -81,7 +69,6 @@ prompt("Hello")
81
69
  ├─ message_end { message: userMessage }
82
70
  ├─ message_start { message: assistantMessage } // LLM starts responding
83
71
  ├─ message_update { message: partial... } // Streaming chunks
84
- ├─ message_update { message: partial... }
85
72
  ├─ message_end { message: assistantMessage } // Complete response
86
73
  ├─ turn_end { message, toolResults: [] }
87
74
  └─ agent_end { messages: [...] }
@@ -89,7 +76,7 @@ prompt("Hello")
89
76
 
90
77
  ### With tool calls
91
78
 
92
- If the assistant calls tools, the loop continues:
79
+ If the assistant calls tools, the loop executes them and starts another turn:
93
80
 
94
81
  ```text
95
82
  prompt("Read config.json")
@@ -113,108 +100,101 @@ prompt("Read config.json")
113
100
  └─ agent_end
114
101
  ```
115
102
 
116
- Tool execution mode is configurable:
117
-
118
- - `parallel` (default): preflight tool calls sequentially, run allowed tools concurrently, emit `tool_execution_end` as each tool finishes, then emit `toolResult` messages and `turn_end.toolResults` in assistant source order.
119
- - `sequential`: run tool calls one at a time in assistant source order.
103
+ Tool execution mode is configurable globally via `toolExecution` in `AgentOptions` or per tool via `executionMode` on `AgentTool`:
120
104
 
121
- In parallel mode, `tool_execution_end` events follow tool completion order, while persisted `toolResult` messages still follow assistant source order.
105
+ - **`parallel` (default):** Preflights tool calls sequentially, runs allowed tools concurrently, emits `tool_execution_end` in completion order, then emits `toolResult` messages and `turn_end.toolResults` in assistant source order.
106
+ - **`sequential`:** Runs tool calls one at a time in assistant source order. If any call in a batch targets a tool with `executionMode: "sequential"`, the entire batch runs sequentially.
122
107
 
123
- Set the mode globally through `toolExecution` in `AgentOptions`, or per tool through `executionMode` on `AgentTool`. If any tool call in a batch targets a tool with `executionMode: "sequential"`, the entire batch runs sequentially regardless of the global setting.
108
+ `beforeToolCall` runs after `tool_execution_start` and argument validation (and after assistant `message_end` processing settles on `Agent`, so agent state already contains the assistant message). It can block execution and attach `terminate: true`. `afterToolCall` runs after execution finishes and before `tool_execution_end` and final tool-result events.
124
109
 
125
- `beforeToolCall` runs after `tool_execution_start` and argument validation. It can block execution and attach `terminate: true` to the blocked result. `afterToolCall` runs after tool execution finishes and before `tool_execution_end` and the final tool result message events are emitted.
110
+ **`afterToolCall` merge rules:** Overrides merge field-by-field (`content`, `details`, `structuredContent`, `isError`, `usage`, `terminate`) with no deep merge. Returning `content` **without** `structuredContent` drops the original `structuredContent` so the two cannot go out of sync; pass `structuredContent` alongside `content` to preserve it.
126
111
 
127
- **`afterToolCall` merge rules:** Overrides merge field-by-field (`content`, `details`, `structuredContent`, `isError`, `usage`, `terminate`) with no deep merge. Importantly, returning `content` **without** `structuredContent` drops the original `structuredContent` so the two cannot go out of sync; pass `structuredContent` alongside `content` if you want to keep it.
112
+ Tools, blocked `beforeToolCall` results, and `afterToolCall` overrides can return `terminate: true` to skip the automatic follow-up LLM call—taking effect only when every finalized tool result in that batch sets `terminate: true`.
128
113
 
129
- Tools, blocked `beforeToolCall` results, and `afterToolCall` overrides can return `terminate: true` to skip the automatic follow-up LLM call. The loop stops early only when every finalized tool result in that batch sets `terminate: true`. Mixed batches continue normally.
114
+ ### Turn lifecycle hooks
130
115
 
131
- With the `Agent` class, assistant `message_end` processing finishes before tool preflight begins. That guarantees `beforeToolCall` sees agent state that already includes the assistant message requesting the tool call.
116
+ Each provider turn follows this exact sequence:
132
117
 
133
- ### Request preparation and turn finalization
118
+ ```text
119
+ selected input events
120
+ -> prepareRequest (before every request, including turn 1)
121
+ -> provider response
122
+ -> tool results
123
+ -> finishTurn (before turn_end; decides continue / end / default)
124
+ -> turn_end
125
+ -> continuation check
126
+ -> prepareNextTurn / prepareNextTurnWithContext (only when starting another turn)
127
+ -> next turn OR agent_end
128
+ ```
134
129
 
135
- `prepareRequest` runs immediately before every conversational provider request, including the first. Use it to install canonical persisted context after pending input has been emitted:
130
+ | Hook | When it runs | Return shape | Use it for |
131
+ | --- | --- | --- | --- |
132
+ | `prepareRequest` | Immediately before **every** conversational provider request (including the first), after pending messages are emitted; does not poll queues. | `AgentRequestUpdate` (`{ context?, model?, thinkingLevel? }`) or `undefined` | Installing canonical persisted context, model, or thinking level for the request. |
133
+ | `finishTurn` | After the assistant message and all tool results finalize, before `turn_end` (runs on normal, error, and aborted responses). | `{ action: "continue" } \| { action: "end" } \| undefined` | Stopping a run immediately after `turn_end` without polling queues (`"end"`), or forcing one more request on a normal response (`"continue"`). |
134
+ | `prepareNextTurn` / `prepareNextTurnWithContext` | After `turn_end` only when the loop will continue to another turn, immediately before the next turn starts. | `AgentLoopTurnUpdate` (`{ context?, messages?, model?, thinkingLevel? }`) or `undefined` | Swapping context, model, thinking level, or appending lifecycle-emitted `messages` between turns (for example, post-turn compaction or dynamic tool/model transitions). |
136
135
 
137
136
  ```typescript
137
+ // Install canonical context right before every request
138
138
  agent.prepareRequest = async ({ context }) => ({
139
139
  context: { ...context, messages: await session.loadModelContext() },
140
140
  });
141
- ```
142
141
 
143
- `prepareRequest` does not poll queues. Steering messages queued while it runs wait for the next normal steering poll.
144
-
145
- `finishTurn` runs after the assistant message and all tool results are finalized, before `turn_end`. It runs for normal, error, and aborted responses:
146
-
147
- ```typescript
142
+ // Decide whether to stop or force continuation before turn_end
148
143
  agent.finishTurn = async ({ message }) => {
149
144
  if (message.stopReason === "error" || message.stopReason === "aborted") return;
150
145
  if (shouldEndRun(message)) return { action: "end" };
151
146
  return needsAnotherResponse(message) ? { action: "continue" } : undefined;
152
147
  };
153
- ```
154
-
155
- Returning `undefined` keeps normal scheduling. Returning `{ action: "end" }` stops immediately after `turn_end` without polling steering or follow-up queues or starting another request.
156
-
157
- On a normal response, returning `{ action: "continue" }` guarantees one more provider request. If tool results, steering messages, or follow-up messages already schedule that request, no extra request is sent; otherwise the loop sends one context-only request. Error and aborted responses remain hard exits whose decisions are ignored. Because `finishTurn` runs again after the next request, returning `{ action: "continue" }` unconditionally creates an infinite loop.
158
-
159
- To migrate from the removed `shouldStopAfterTurn` hook, return `{ action: "end" }`. Guard error and aborted responses so your predicate runs only on successful turns:
160
148
 
161
- ```typescript
162
- finishTurn: async (turn, signal) => {
163
- if (turn.message.stopReason === "error" || turn.message.stopReason === "aborted") return;
164
- return (await shouldStop(turn, signal)) ? { action: "end" } : undefined;
165
- },
149
+ // Update state or append messages between turns when another turn is scheduled
150
+ agent.prepareNextTurnWithContext = async (turn, signal) => {
151
+ // turn: { message, toolResults, context, newMessages }
152
+ const updated = await maybeCompactBetweenTurns(turn.context, signal);
153
+ return updated ? { context: updated } : undefined;
154
+ };
166
155
  ```
167
156
 
168
- Each provider turn follows this order:
157
+ On `Agent`, `prepareNextTurnWithContext(context, signal)` receives the completed turn's `PrepareNextTurnContext` (`{ message, toolResults, context, newMessages }`) and takes precedence over `prepareNextTurn(signal)` if both are set. On the low-level `agentLoop()` `AgentLoopConfig`, `prepareNextTurn(context)` always receives `PrepareNextTurnContext`.
169
158
 
170
- ```text
171
- selected input events
172
- -> prepareRequest
173
- -> provider response
174
- -> tool results
175
- -> finishTurn
176
- -> turn_end
177
- -> continuation scheduling or agent_end
178
- ```
159
+ On `finishTurn`, returning `{ action: "continue" }` on a normal response guarantees one more provider request (satisfied by tool results, steering, or follow-up scheduling when present, or a context-only request otherwise). Error and aborted responses remain hard exits whose `finishTurn` decisions are ignored. Do not return `{ action: "continue" }` unconditionally or the loop will run forever.
160
+
161
+ <Note>
162
+ **Migrating from `shouldStopAfterTurn`:** Replace the removed `shouldStopAfterTurn` hook with `finishTurn`, guarding `error`/`aborted` responses and returning `{ action: "end" }` when you want the run to stop after `turn_end`.
163
+ </Note>
179
164
 
180
165
  ### `continue()` and queued input
181
166
 
182
- Empty and system-only transcripts reject `continue()` without consuming queues. A non-assistant tail continues from existing context. Steering is polled at startup, while follow-up input waits until the response stops naturally.
167
+ Empty and system-only transcripts reject `continue()` without consuming queues. A non-assistant tail continues from existing context (steering is polled at startup; follow-up input waits until the response stops naturally).
183
168
 
184
- ```typescript
185
- agent.followUp({ role: "user", content: "After the retry", timestamp: Date.now() });
186
- await agent.continue(); // The first request retries the existing user/toolResult tail.
187
- ```
188
-
189
- An assistant tail cannot be sent directly, so `continue()` falls back to one queued steering batch, or else one queued follow-up batch. Queue mode still determines whether that batch takes one message or all queued messages:
169
+ An assistant tail cannot be sent directly, so `continue()` falls back to one queued steering batch, or else one queued follow-up batch (respecting queue mode):
190
170
 
191
171
  ```typescript
192
172
  agent.steer({ role: "user", content: "Continue from here", timestamp: Date.now() });
193
- await agent.continue(); // Uses the queued message only because the tail is assistant.
173
+ await agent.continue(); // Consumes the queued message because the tail is an assistant message
194
174
  ```
195
175
 
196
176
  ### Event types
197
177
 
198
178
  | Event | Description |
199
- |-------|-------------|
179
+ | --- | --- |
200
180
  | `agent_start` | Agent begins processing |
201
- | `agent_end` | Final event for the run. Awaited subscribers for this event still count toward settlement |
181
+ | `agent_end` | Final event for the run; awaited subscribers for this event still count toward settlement |
202
182
  | `turn_start` | New turn begins (one LLM call + tool executions) |
203
183
  | `turn_end` | Turn completes with assistant message and tool results |
204
- | `message_start` | Any message begins (user, assistant, toolResult) |
205
- | `message_update` | **Assistant only.** Includes `assistantMessageEvent` with delta |
184
+ | `message_start` | Any message begins (`user`, `assistant`, `toolResult`) |
185
+ | `message_update` | **Assistant only.** Includes `assistantMessageEvent` with streaming delta |
206
186
  | `message_end` | Message completes |
207
187
  | `tool_execution_start` | Tool begins |
208
188
  | `tool_execution_update` | Tool streams progress |
209
189
  | `tool_execution_end` | Tool completes |
210
190
 
211
- `Agent.subscribe()` listeners receive `(event, signal)` and are awaited in registration order. If a listener throws or rejects, the error propagates to the caller awaiting `prompt()` or `continue()`. `agent_end` means no more loop events will be emitted, and `await agent.waitForIdle()` and `await agent.prompt(...)` settle only after awaited `agent_end` listeners finish.
191
+ `Agent.subscribe()` listeners receive `(event, signal)` and are awaited in registration order. Thrown or rejected listener errors propagate to the caller awaiting `prompt()` or `continue()`. `await agent.waitForIdle()` and `await agent.prompt(...)` settle only after awaited `agent_end` listeners finish.
212
192
 
213
193
  ## Agent options
214
194
 
215
195
  ```typescript
216
196
  const agent = new Agent({
217
- // Initial state. systemPrompt and tools become the leading system message
197
+ // Initial state: systemPrompt and tools seed the leading system message
218
198
  // unless messages already starts with one.
219
199
  initialState: {
220
200
  systemPrompt: string,
@@ -224,94 +204,68 @@ const agent = new Agent({
224
204
  messages: AgentMessage[],
225
205
  },
226
206
 
227
- // Convert AgentMessage[] to LLM Message[] (required for custom message types; must not throw or reject)
207
+ // Convert AgentMessage[] to LLM Message[] (required for custom message types; must not throw)
228
208
  convertToLlm: (messages) => messages.filter(...),
229
209
 
230
- // Transform context before convertToLlm (for pruning, compaction)
210
+ // Transform context before convertToLlm (for pruning or compaction)
231
211
  transformContext: async (messages, signal) => pruneOldMessages(messages),
232
212
 
233
- // Steering mode: "one-at-a-time" (default) or "all"
213
+ // Queue drain modes: "one-at-a-time" (default) or "all"
234
214
  steeringMode: "one-at-a-time",
235
-
236
- // Follow-up mode: "one-at-a-time" (default) or "all"
237
215
  followUpMode: "one-at-a-time",
238
216
 
239
- // Required stream function. Receives a TranscriptContext: the prompt and tools
240
- // are in the transcript's system messages, not on the context.
217
+ // Required stream function receiving a TranscriptContext
241
218
  streamFn: models.streamSimple.bind(models),
242
219
 
243
220
  // Session ID for provider caching
244
221
  sessionId: "session-123",
245
222
 
246
- // How requests identify the app to providers (a ClientIdentity from @bastani/atomic-ai), merged over
247
- // DEFAULT_AGENT_IDENTITY ({ attribution: ATOMIC_ATTRIBUTION }: attribution headers name Atomic).
248
- // Pass { attribution: null } to send no attribution headers.
223
+ // Client identity (merged over DEFAULT_AGENT_IDENTITY; pass { attribution: null } to omit attribution)
249
224
  identity: { attribution: { name: "my-app", url: "https://my-app.example" } },
250
225
 
251
226
  // Dynamic API key resolution (for expiring OAuth tokens)
252
227
  getApiKey: async (provider) => refreshToken(),
253
228
 
254
- // Optional provider transport, retry cap, and request/response inspection hooks
229
+ // Transport, retry cap, and request/response inspection hooks
255
230
  transport: "sse",
256
231
  maxRetryDelayMs: 60_000,
257
232
  onPayload: (payload, model) => payload,
258
233
  onResponse: (response) => {},
259
234
  onProviderStreamEvent: (event) => {},
260
235
 
261
- // Tool execution mode: "parallel" (default) or "sequential"
236
+ // Tool execution mode ("parallel" default, or "sequential") and unknown-tool text
262
237
  toolExecution: "parallel",
263
-
264
- // Custom error text when the model calls an unregistered tool name
265
238
  unknownToolMessage: (toolName) => `Tool "${toolName}" is not available.`,
266
239
 
267
- // Preflight each tool call after args are validated. Can block execution.
268
- beforeToolCall: async ({ toolCall, args, context }) => {
269
- if (toolCall.name === "bash") {
270
- return { block: true, reason: "bash is disabled", terminate: true };
271
- }
272
- },
273
-
274
- // Postprocess each tool result before final tool events are emitted.
275
- afterToolCall: async ({ toolCall, result, isError, context }) => {
276
- if (toolCall.name === "notify_done" && !isError) {
277
- return { terminate: true };
278
- }
279
- if (!isError) {
280
- return { details: { ...result.details, audited: true } };
281
- }
240
+ // Tool preflight and postprocessing hooks
241
+ beforeToolCall: async ({ toolCall }) => {
242
+ if (toolCall.name === "bash") return { block: true, reason: "bash is disabled", terminate: true };
282
243
  },
283
-
284
- // Rebuild finalized context immediately before every provider request.
285
- prepareRequest: async ({ context }, signal) => {
286
- return { context: { ...context, messages: await loadCanonicalMessages(signal) } };
244
+ afterToolCall: async ({ toolCall, result, isError }) => {
245
+ if (toolCall.name === "notify_done" && !isError) return { terminate: true };
246
+ if (!isError) return { details: { ...result.details, audited: true } };
287
247
  },
288
248
 
289
- // Optional turn-boundary hooks that update model, tools, or system messages between turns.
249
+ // Turn lifecycle hooks (see "Turn lifecycle hooks" above)
250
+ prepareRequest: async ({ context }, signal) => ({
251
+ context: { ...context, messages: await loadCanonicalMessages(signal) },
252
+ }),
290
253
  prepareNextTurn: async (signal) => undefined,
291
- prepareNextTurnWithContext: async (context, signal) => undefined,
292
-
293
- // Finalize a completed turn before turn_end is emitted.
294
- // `continue` ensures one next request; existing tool/queue scheduling can satisfy it.
295
- // `end` ends this run after turn_end without polling queues.
296
- finishTurn: async ({ message, toolResults }, signal) => {
297
- return shouldContinue(message, toolResults) ? { action: "continue" } : undefined;
298
- },
254
+ prepareNextTurnWithContext: async (turn, signal) => undefined,
255
+ finishTurn: async ({ message, toolResults }, signal) =>
256
+ shouldContinue(message, toolResults) ? { action: "continue" } : undefined,
299
257
 
300
258
  // Custom thinking budgets for token-based providers
301
- thinkingBudgets: {
302
- minimal: 128,
303
- low: 512,
304
- medium: 1024,
305
- high: 2048,
306
- },
259
+ thinkingBudgets: { minimal: 128, low: 512, medium: 1024, high: 2048 },
307
260
  });
308
261
  ```
309
262
 
310
- ### `StreamFn`, `setDefaultStreamFn()`, and `convertToLlm` contracts
311
-
312
- - **`StreamFn` must never throw or reject** for request, model, or runtime failures. Always return an `AssistantMessageEventStream` and encode failures via stream `error` events and a final `AssistantMessage` with `stopReason: "error"` or `"aborted"` and `errorMessage`.
313
- - **`convertToLlm` must never throw or reject**; filter or normalize custom messages deterministically.
314
- - **`setDefaultStreamFn(streamFn | undefined)`:** Sets a process-wide fallback `StreamFn` used when `Agent` or `agentLoop()` callers do not supply an explicit `streamFn`.
263
+ <Note>
264
+ **No-throw contracts (`StreamFn` and `convertToLlm`):**
265
+ - **`StreamFn`** must never throw or reject for request, model, or runtime failures. Always return an `AssistantMessageEventStream` and report failures via stream `error` events and a final `AssistantMessage` with `stopReason: "error"` or `"aborted"` and `errorMessage`.
266
+ - **`convertToLlm`** must never throw or reject; filter or normalize custom messages deterministically.
267
+ - **`setDefaultStreamFn(streamFn | undefined)`** sets a process-wide fallback `StreamFn` when callers omit `streamFn`.
268
+ </Note>
315
269
 
316
270
  ## Agent state
317
271
 
@@ -329,13 +283,9 @@ interface AgentState {
329
283
  }
330
284
  ```
331
285
 
332
- Access state through `agent.state`. Assigning `agent.state.tools = [...]` or `agent.state.messages = [...]` copies the top-level array before storing it, while mutating the returned array mutates current agent state.
286
+ Assigning `agent.state.tools = [...]` or `agent.state.messages = [...]` copies the top-level array before storing it, while mutating the returned array mutates current state. `agent.state.isStreaming` stays `true` until awaited `agent_end` subscribers finish.
333
287
 
334
- The transcript owns the system prompt and tool declarations. The leading system message sets the prompt, and later system messages patch it (see `SystemMessage` in [`@bastani/atomic-ai`](/libraries/ai)). `agent.state.systemPrompt` is read-only and replays the transcript.
335
-
336
- `agent.state.tools` holds the executable tools. Before every request, the loop compares `agent.state.tools` against the tools declared in the transcript and announces any difference in a system message, merging into a pending system message when one exists. `getCurrentSystemMessage(messages)` from `@bastani/atomic-ai` returns the replayed head, including declared tools, for any message array including agent transcripts with custom message roles.
337
-
338
- To change the prompt mid-conversation, append a system message with `content` (added instructions) or `sections` (named replacements):
288
+ The transcript owns the system prompt and tool declarations: `agent.state.systemPrompt` is read-only and replays the transcript's system messages (see `SystemMessage` in [`@bastani/atomic-ai`](/libraries/ai)). Before each request, the loop diffs `agent.state.tools` against declared tools in the transcript and appends a system-message update when they change. To update the prompt mid-conversation, append a system message:
339
289
 
340
290
  ```typescript
341
291
  await agent.prompt([
@@ -344,125 +294,53 @@ await agent.prompt([
344
294
  ]);
345
295
  ```
346
296
 
347
- During streaming, `agent.state.streamingMessage` contains the current partial assistant message.
348
-
349
- `agent.state.isStreaming` remains `true` until the run fully settles, including awaited `agent_end` subscribers.
350
-
351
297
  ## Methods
352
298
 
353
- ### Prompting
354
-
355
299
  ```typescript
356
- // Text prompt
300
+ // Prompting and continuation
357
301
  await agent.prompt("Hello");
358
-
359
- // With images
360
- await agent.prompt("What's in this image?", [
361
- { type: "image", data: base64Data, mimeType: "image/jpeg" }
362
- ]);
363
-
364
- // AgentMessage directly
302
+ await agent.prompt("Describe this", [{ type: "image", data: base64Data, mimeType: "image/jpeg" }]);
365
303
  await agent.prompt({ role: "user", content: "Hello", timestamp: Date.now() });
366
-
367
- // Continue existing non-assistant input; an assistant tail may use queued input as fallback
368
304
  await agent.continue();
369
- ```
370
-
371
- ### State management
372
305
 
373
- ```typescript
306
+ // State and configuration
374
307
  const nextModel = models.getModel("openai", "gpt-4o");
375
308
  if (nextModel) agent.state.model = nextModel;
376
309
  agent.state.thinkingLevel = "medium";
377
310
  agent.state.tools = [myTool];
378
- agent.toolExecution = "sequential";
379
- agent.beforeToolCall = async ({ toolCall }) => undefined;
380
- agent.afterToolCall = async ({ toolCall, result }) => undefined;
381
- agent.prepareRequest = async ({ context }) => ({
382
- context: { ...context, messages: await loadCanonicalMessages() },
383
- });
384
- agent.finishTurn = async () => undefined;
385
- agent.state.messages = newMessages; // top-level array is copied
386
- agent.state.messages.push(message);
387
- const nextQueuedMessages = agent.peekQueuedMessages(); // respects queue modes; does not consume
388
- agent.reset();
389
- ```
390
-
391
- ### Session and thinking budgets
392
-
393
- ```typescript
394
311
  agent.sessionId = "session-123";
312
+ agent.thinkingBudgets = { minimal: 128, low: 512, medium: 1024, high: 2048 };
313
+ const queued = agent.peekQueuedMessages(); // inspects next batch without consuming
314
+ agent.reset();
395
315
 
396
- agent.thinkingBudgets = {
397
- minimal: 128,
398
- low: 512,
399
- medium: 1024,
400
- high: 2048,
401
- };
402
- ```
403
-
404
- ### Control
405
-
406
- ```typescript
407
- agent.abort(); // Cancel current operation
408
- await agent.waitForIdle(); // Wait for completion
409
- ```
410
-
411
- ### Events
412
-
413
- ```typescript
316
+ // Lifecycle control and events
317
+ agent.abort();
318
+ await agent.waitForIdle();
414
319
  const unsubscribe = agent.subscribe(async (event, signal) => {
415
- if (event.type === "agent_end") {
416
- // Final barrier work for the run
417
- await flushSessionState(signal);
418
- }
320
+ if (event.type === "agent_end") await flushSessionState(signal);
419
321
  });
420
322
  unsubscribe();
421
323
  ```
422
324
 
423
325
  ## Steering and follow-up
424
326
 
425
- Steering messages let you interrupt the agent while tools are running. Follow-up messages let you queue work after the agent would otherwise stop.
327
+ Steering messages interrupt the agent after the current turn's tool batch completes; follow-up messages run only after no tool calls or steering messages remain:
426
328
 
427
329
  ```typescript
428
- agent.steeringMode = "one-at-a-time";
429
- agent.followUpMode = "one-at-a-time";
430
-
431
- // While agent is running tools
432
- agent.steer({
433
- role: "user",
434
- content: "Stop! Do this instead.",
435
- timestamp: Date.now(),
436
- });
437
-
438
- // After the agent finishes its current work
439
- agent.followUp({
440
- role: "user",
441
- content: "Also summarize the result.",
442
- timestamp: Date.now(),
443
- });
330
+ agent.steeringMode = "one-at-a-time"; // or "all"
331
+ agent.followUpMode = "one-at-a-time"; // or "all"
444
332
 
445
- const steeringMode = agent.steeringMode;
446
- const followUpMode = agent.followUpMode;
333
+ agent.steer({ role: "user", content: "Stop! Do this instead.", timestamp: Date.now() });
334
+ agent.followUp({ role: "user", content: "Also summarize the result.", timestamp: Date.now() });
447
335
 
448
336
  agent.clearSteeringQueue();
449
337
  agent.clearFollowUpQueue();
450
338
  agent.clearAllQueues();
451
339
  ```
452
340
 
453
- Use `clearSteeringQueue()`, `clearFollowUpQueue()`, or `clearAllQueues()` to drop queued messages.
454
-
455
- When steering messages are detected after a turn completes:
456
-
457
- 1. All tool calls from the current assistant message have already finished.
458
- 2. Steering messages are injected.
459
- 3. The LLM responds on the next turn.
460
-
461
- Follow-up messages are checked only when there are no more tool calls and no steering messages. If any are queued, they are injected and another turn runs.
462
-
463
341
  ## Custom message types
464
342
 
465
- Extend `AgentMessage` through declaration merging:
343
+ Extend `AgentMessage` with declaration merging and handle your custom roles inside `convertToLlm`:
466
344
 
467
345
  ```typescript
468
346
  declare module "@bastani/atomic-agent-core" {
@@ -471,53 +349,31 @@ declare module "@bastani/atomic-agent-core" {
471
349
  }
472
350
  }
473
351
 
474
- // Now valid
475
- const msg: AgentMessage = { role: "notification", text: "Info", timestamp: Date.now() };
476
- ```
477
-
478
- Handle custom types in `convertToLlm`:
479
-
480
- ```typescript
481
352
  const agent = new Agent({
482
353
  streamFn: models.streamSimple.bind(models),
483
- convertToLlm: (messages) => messages.flatMap(m => {
484
- if (m.role === "notification") return []; // Filter out
485
- return [m];
486
- }),
354
+ convertToLlm: (messages) => messages.flatMap((m) => (m.role === "notification" ? [] : [m])),
487
355
  });
488
356
  ```
489
357
 
490
358
  ## Tools
491
359
 
492
- Define tools with `AgentTool`. `parameters` is any JSON Schema object. When built with `@bastani/atomic-schema` builders, it also types `params` (other schemas produce `unknown`, and `AgentTool<any>` produces `any`):
360
+ Define tools with `AgentTool` using any JSON Schema (using `@bastani/atomic-schema` builders types `params` automatically):
493
361
 
494
362
  ```typescript
495
363
  import { obj, str } from "@bastani/atomic-schema";
496
364
 
497
- const readFileParameters = obj({
498
- path: str({ description: "File path" }),
499
- });
365
+ const readFileParameters = obj({ path: str({ description: "File path" }) });
500
366
 
501
367
  const readFileTool: AgentTool<typeof readFileParameters> = {
502
368
  name: "read_file",
503
- label: "Read File", // For UI display
369
+ label: "Read File",
504
370
  description: "Read a file's contents",
505
371
  parameters: readFileParameters,
506
- // Optional JSON Schema describing structuredContent returned to programmatic/codemode callers
507
- outputSchema: obj({ path: str(), content: str() }),
508
- // Override execution mode for this tool (optional).
509
- // "sequential" forces the entire batch to run one at a time.
510
- // "parallel" allows concurrent execution with other tool calls.
511
- // If omitted, the global toolExecution config applies.
512
- executionMode: "sequential",
513
- execute: async (toolCallId, params, signal, onUpdate) => {
372
+ outputSchema: obj({ path: str(), content: str() }), // optional structuredContent schema
373
+ executionMode: "sequential", // optional override ("sequential" forces the batch sequential)
374
+ execute: async (_toolCallId, params, _signal, onUpdate) => {
514
375
  const content = await fs.readFile(params.path, "utf-8");
515
-
516
- // Optional: stream progress
517
376
  onUpdate?.({ content: [{ type: "text", text: "Reading..." }], details: {} });
518
-
519
- // Optional: add `terminate: true` here to skip the automatic follow-up LLM call
520
- // when every finalized tool result in the batch does the same.
521
377
  return {
522
378
  content: [{ type: "text", text: content }],
523
379
  structuredContent: { path: params.path, content },
@@ -531,28 +387,14 @@ agent.state.tools = [readFileTool];
531
387
 
532
388
  ### Error handling
533
389
 
534
- Throw an error or return a result with `isError: true` when a tool fails. Do not only describe the failure in `content`.
535
-
536
- ```typescript
537
- execute: async (toolCallId, params, signal, onUpdate) => {
538
- if (!fs.existsSync(params.path)) {
539
- throw new Error(`File not found: ${params.path}`);
540
- }
541
- // Return content only on success
542
- return { content: [{ type: "text", text: "..." }], details: {} };
543
- }
544
- ```
545
-
546
- The agent catches thrown errors and reports them to the LLM as tool errors with `isError: true`. Returning `{ content, details, structuredContent, isError: true }` reports the same error status to the model while keeping `details` and `structuredContent` for UI and programmatic callers.
547
-
548
- Return `terminate: true` from `execute()`, a blocked `beforeToolCall`, or `afterToolCall` to skip the follow-up LLM call after the current tool batch. This takes effect only when every finalized tool result in the batch sets `terminate: true`. The hint is runtime-only, so emitted `toolResult` transcript messages remain standard LLM tool results.
390
+ Throw an error or return `{ content, details, structuredContent?, isError: true }` when a tool fails (do not only describe the failure in text). Returning `isError: true` preserves `details` and `structuredContent` for UI and programmatic callers.
549
391
 
550
392
  ### MCP, Codemode, and `runToolCall()`
551
393
 
552
- [`@bastani/atomic-codemode`](/libraries/codemode) runs model-written JavaScript that calls tools. Wrap it as an `AgentTool` named `codemode` whose scripts invoke the agent's tools through `runToolCall(toolCall, options)` so argument validation, `beforeToolCall`, and `afterToolCall` apply to nested calls too.
394
+ When embedding [`@bastani/atomic-codemode`](/libraries/codemode) or MCP wrappers, invoke nested tools through `runToolCall()` so argument validation, `beforeToolCall`, and `afterToolCall` run consistently:
553
395
 
554
396
  ```typescript
555
- import { type AgentToolCall, type AgentToolCallOutcome, type RunToolCallOptions, runToolCall } from "@bastani/atomic-agent-core";
397
+ import { type AgentToolCallOutcome, runToolCall } from "@bastani/atomic-agent-core";
556
398
 
557
399
  const outcome: AgentToolCallOutcome = await runToolCall(toolCall, {
558
400
  tools,
@@ -565,11 +407,11 @@ const outcome: AgentToolCallOutcome = await runToolCall(toolCall, {
565
407
  // outcome: { result: AgentToolResult<unknown>, isError: boolean, durationMs?: number }
566
408
  ```
567
409
 
568
- `runToolCall()` returns `{ result, isError, durationMs? }` (returning tool failures as `isError: true` rather than throwing). See [Using with agent-core](/libraries/codemode#using-with-agent-core). Tools that wrap an MCP server's tools work the same way. Atomic's own MCP support lives in the [MCP servers](/mcp-servers) extension.
410
+ See [Using with agent-core](/libraries/codemode#using-with-agent-core) for a full example.
569
411
 
570
412
  ## Proxy usage
571
413
 
572
- For browser apps that proxy requests through a backend:
414
+ For browser apps that route LLM requests through a backend server without exposing provider API keys, pass `streamProxy()` as `streamFn`:
573
415
 
574
416
  ```typescript
575
417
  import { Agent, streamProxy } from "@bastani/atomic-agent-core";
@@ -584,9 +426,32 @@ const agent = new Agent({
584
426
  });
585
427
  ```
586
428
 
429
+ ### Proxy server HTTP and SSE contract
430
+
431
+ Your backend must expose `POST <proxyUrl>/api/stream`:
432
+
433
+ - **Request headers:** `Authorization: Bearer <authToken>` and `Content-Type: application/json`.
434
+ - **Request JSON body:** `{ model, context, options }`, where `model` is the serialized `Model`, `context` is the `TranscriptContext`, and `options` contains the serializable `SimpleStreamOptions` fields (`temperature`, `samplingParams`, `maxTokens`, `reasoning`, `cacheRetention`, `sessionId`, `disableContinuation`, `headers`, `metadata`, `transport`, `thinkingBudgets`, `maxRetryDelayMs`).
435
+ - **Error responses:** On non-2xx HTTP responses, `streamProxy()` reads `{ "error": "..." }` from a JSON response body when present (otherwise using the HTTP status text) and surfaces a stream `error` event.
436
+ - **Streaming response (SSE):** Return newline-delimited `data: <JSON>` lines where each payload is a `ProxyAssistantMessageEvent` (the same event vocabulary as `AssistantMessageEvent`, with `partial` omitted to reduce bandwidth—`streamProxy()` reconstructs `partial` client-side):
437
+
438
+ | `type` | Required fields | Optional fields |
439
+ | --- | --- | --- |
440
+ | `start` | — | — |
441
+ | `text_start` / `thinking_start` | `contentIndex` | — |
442
+ | `text_delta` / `thinking_delta` | `contentIndex`, `delta` | — |
443
+ | `text_end` / `thinking_end` | `contentIndex` | `contentSignature` |
444
+ | `toolcall_start` | `contentIndex`, `id`, `toolName` | — |
445
+ | `toolcall_delta` | `contentIndex`, `delta` | — |
446
+ | `toolcall_end` | `contentIndex`, `toolCall` | — |
447
+ | `done` | `reason` (`"stop"` \| `"length"` \| `"toolUse"`), `usage` | `providerThinkingLevel` |
448
+ | `error` | `reason` (`"aborted"` \| `"error"`), `usage` | `errorMessage`, `providerThinkingLevel` |
449
+
450
+ If the server closes the HTTP stream cleanly without sending a terminal `done` or `error` event, `streamProxy()` synthesizes an `error` event (`"Connection closed by proxy server before the response completed"`) instead of hanging.
451
+
587
452
  ## Low-level API
588
453
 
589
- For direct control without the `Agent` class:
454
+ Use `agentLoop()` and `agentLoopContinue()` directly when you do not want the stateful `Agent` wrapper:
590
455
 
591
456
  ```typescript
592
457
  import {
@@ -612,22 +477,19 @@ const config: AgentLoopConfig = {
612
477
  model,
613
478
  convertToLlm: (msgs) =>
614
479
  msgs.filter((m) => ["system", "user", "assistant", "toolResult"].includes(m.role)),
615
- toolExecution: "parallel", // overridden by per-tool executionMode if set
616
- beforeToolCall: async ({ toolCall, args, context }) => undefined,
617
- afterToolCall: async ({ toolCall, result, isError, context }) => undefined,
480
+ toolExecution: "parallel",
618
481
  };
619
482
 
620
483
  const userMessage = { role: "user", content: "Hello", timestamp: Date.now() };
621
-
622
484
  const streamFn = models.streamSimple.bind(models);
485
+
623
486
  for await (const event of agentLoop([userMessage], context, config, undefined, streamFn)) {
624
487
  console.log(event.type);
625
488
  }
626
489
 
627
- // Continue from existing context
628
490
  for await (const event of agentLoopContinue(context, config, undefined, streamFn)) {
629
491
  console.log(event.type);
630
492
  }
631
493
  ```
632
494
 
633
- These low-level streams are observational. They preserve event order, but they do not wait for your async event handling to settle before later producer phases continue. If message processing must act as a barrier before tool preflight, use the `Agent` class instead of raw `agentLoop()` or `agentLoopContinue()`.
495
+ Low-level streams are observational: they preserve event order without waiting for async consumer work before later producer phases continue. Use the `Agent` class when async event handling must act as a barrier before tool preflight or completion.