@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
@@ -4,7 +4,7 @@ sidebarTitle: "@bastani/atomic-codemode"
4
4
  description: "Run model-written JavaScript in a QuickJS WebAssembly sandbox whose only capability is calling injected tools."
5
5
  ---
6
6
 
7
- Runs model-written JavaScript in a QuickJS VM (compiled to WebAssembly) where the only capability is calling injected tools. Nested tool calls never enter the LLM context; only the script's output and return value do. See [Standalone libraries](/libraries) for all standalone packages.
7
+ Runs model-written JavaScript inside a QuickJS WebAssembly VM whose only capability is calling injected tools. Nested tool calls stay outside the LLM context; only the script's output and return value enter the conversation. Atomic uses this library for its built-in [`codemode` tool](/codemode), and it has zero dependencies on other Atomic packages. See [Standalone libraries](/libraries) for all standalone packages.
8
8
 
9
9
  ## Installation
10
10
 
@@ -12,26 +12,22 @@ Runs model-written JavaScript in a QuickJS VM (compiled to WebAssembly) where th
12
12
  npm install @bastani/atomic-codemode
13
13
  ```
14
14
 
15
- Requires Node.js 24.20+ (or Bun / Cloudflare Workers via the portable subpaths). Available package entry points:
15
+ Requires Node.js 24.20+ (or Bun / Cloudflare Workers via the portable subpaths). Public entry points:
16
16
 
17
- - `@bastani/atomic-codemode`: `CodemodeSandbox`, `loadQuickJSWasm`, `parseCodemodeSource`, `renderDeclarations`, and worker runtime for Node and Bun.
18
- - `@bastani/atomic-codemode/portable`: `RemoteCodemodeSandbox` and `InlineCodemodeSandbox` with zero Node.js imports.
19
- - `@bastani/atomic-codemode/cloudflare`: `CodemodeSandboxDurableObject` and `createInlineCodemodeSandbox` for Cloudflare Workers.
20
- - `@bastani/atomic-codemode/declarations`: lightweight `renderDeclarations()` without worker or WebAssembly dependencies.
21
- - `@bastani/atomic-codemode/source`: lightweight `parseCodemodeSource()`, `CodemodeSourceError`, and `CODEMODE_SOURCE_GRAMMAR`.
22
- - `@bastani/atomic-codemode/node-options`: Node worker option helpers.
23
- - `@bastani/atomic-codemode/worker`: worker entrypoint for bundled hosts.
17
+ - **`@bastani/atomic-codemode`:** `CodemodeSandbox`, `loadQuickJSWasm`, `parseCodemodeSource`, `renderDeclarations`, and worker runtime for Node and Bun.
18
+ - **`@bastani/atomic-codemode/portable`:** `RemoteCodemodeSandbox` and `InlineCodemodeSandbox` with zero Node.js imports.
19
+ - **`@bastani/atomic-codemode/cloudflare`:** `CodemodeSandboxDurableObject` and `createInlineCodemodeSandbox` for Cloudflare Workers.
20
+ - **`@bastani/atomic-codemode/declarations`:** Lightweight `renderDeclarations()` with no worker or WebAssembly dependencies.
21
+ - **`@bastani/atomic-codemode/source`:** Lightweight `parseCodemodeSource()`, `CodemodeSourceError`, and `CODEMODE_SOURCE_GRAMMAR`.
22
+ - **`@bastani/atomic-codemode/worker`:** Worker entrypoint for bundled Node/Bun hosts.
24
23
 
25
- Scripts use `tools`, `ALL_TOOLS`, `text`, `image`, `exit`, `store`, and `load`, and may start with a `// @options:` line. Atomic uses it for its built-in [`codemode` tool](/codemode). It has no dependency on the other Atomic packages and can be used on its own to expose any functions (remote APIs, MCP servers, application services) to model-written scripts.
26
-
27
- The package runs in two kinds of environments. Each has its own sandbox class, but they share one API, one script environment, and one result format:
24
+ Three sandbox classes share the same API, script environment, and result format:
28
25
 
29
26
  | Environment | Sandbox | Import from | Where scripts run |
30
27
  | --- | --- | --- | --- |
31
- | Node and Bun | `CodemodeSandbox` | `@bastani/atomic-codemode` | a worker thread per execution |
32
- | Cloudflare Workers and Durable Objects | `RemoteCodemodeSandbox` | `@bastani/atomic-codemode/portable` | a Durable Object in a separately deployed Worker |
33
-
34
- See [Usage on Node and Bun](#usage-on-node-and-bun) and [Usage on Cloudflare Workers](#usage-on-cloudflare-workers). A third sandbox, `InlineCodemodeSandbox`, runs scripts on the calling thread for other runtimes, or on Cloudflare when blocking the caller is acceptable.
28
+ | Node and Bun | `CodemodeSandbox` | `@bastani/atomic-codemode` | A worker thread per execution |
29
+ | Cloudflare Workers / Durable Objects | `RemoteCodemodeSandbox` | `@bastani/atomic-codemode/portable` | A Durable Object in a separately deployed Worker |
30
+ | Other WASM runtimes / single-request Workers | `InlineCodemodeSandbox` | `@bastani/atomic-codemode/portable` (or `/cloudflare`) | The calling thread (blocks caller during compute) |
35
31
 
36
32
  ## Usage on Node and Bun
37
33
 
@@ -40,22 +36,22 @@ import { readFile } from "node:fs/promises";
40
36
  import { CodemodeSandbox } from "@bastani/atomic-codemode";
41
37
 
42
38
  const sandbox = new CodemodeSandbox({
43
- timeoutMs: 60_000,
44
- tools: [
45
- {
46
- name: "read",
47
- execute: async (args, { signal }) => {
48
- const { path } = args as { path: string };
49
- return await readFile(path, { encoding: "utf8", signal });
50
- },
51
- },
52
- ],
39
+ timeoutMs: 60_000,
40
+ tools: [
41
+ {
42
+ name: "read",
43
+ execute: async (args, { signal }) => {
44
+ const { path } = args as { path: string };
45
+ return await readFile(path, { encoding: "utf8", signal });
46
+ },
47
+ },
48
+ ],
53
49
  });
54
50
 
55
51
  const result = await sandbox.execute(`
56
- const source = await tools.read({ path: "package.json" });
57
- text("bytes " + source.length);
58
- return JSON.parse(source).name;
52
+ const source = await tools.read({ path: "package.json" });
53
+ text("bytes " + source.length);
54
+ return JSON.parse(source).name;
59
55
  `);
60
56
 
61
57
  console.log(result.output); // [{ type: "text", text: "bytes 1234" }]
@@ -65,59 +61,41 @@ else console.error(result.error.kind, result.error.message);
65
61
  await sandbox.close();
66
62
  ```
67
63
 
68
- `code` is the body of an async function, so `return` and top-level `await` work. Inside the script, every sandbox provides:
69
-
70
- - `tools.<name>(args)` returns a promise. Arguments and results go through a JSON round trip. When a tool rejects with an `Error`, the script catches an `Error` with the same message plus any extra JSON-serializable own properties from that error (such as `code`, excluding `name`, `message`, and `stack`). Tool names are also exposed as identifiers with invalid characters replaced by `_` via `toCodemodeIdentifier`, so `my-tool` is available as both `tools.my_tool` and `tools["my-tool"]`.
71
- - `ALL_TOOLS` lists `{ name, description }` for every tool, using the identifier form for `name`.
72
- - `text(value)` appends a text item to `result.output`, JSON-stringifying non-string values. `console.log`, `info`, `warn`, `error`, and `debug` append text items with `console: true`.
73
- - `image(urlOrItem)` appends an image item. It accepts a base64 `data:` URL, `{ image_url }`, or an image block (`{ type: "image", data, mimeType }`, as MCP tools and `@bastani/atomic-ai` produce). Remote URLs are rejected.
74
- - `exit()` ends the script immediately with a successful result, keeping its output and store writes.
75
- - `globals` passed to the sandbox are callable as top-level functions, such as a host helper `image(ref)`. They behave like tools but are not recorded in `result.calls`. Global names must be valid JavaScript identifiers (or dotted `namespace.member` forms, placing the function on a frozen namespace object) and cannot collide with reserved names: `tools`, `ALL_TOOLS`, `console`, `text`, `image`, `exit`, `globalThis`, `store`, or `load`. With `spread: true`, `execute` receives all call arguments as an array instead of only the first argument, and `signature` replaces the declaration generated from the schemas.
76
- - `store(key, value)` and `load(key)` read and write JSON values synchronously. See [Store](#store).
77
- - **Frozen built-in prototypes:** Before running scripts, the VM freezes built-in prototypes (`Object.prototype`, `Array.prototype`, and others, while still allowing instance overrides of `constructor`, `name`, `message`, `toString`, `toLocaleString`, `valueOf`, and `toJSON`). Scripts that attempt to monkey-patch built-in prototypes throw a `TypeError`.
78
- - Nothing else is available. There are no timers, `fetch`, `process`, `require`, modules, or `WebAssembly`. `eval` and `Function` work, but they only evaluate code inside the same VM.
79
-
80
- When `timeoutMs` is omitted, `CodemodeSandbox` uses `DEFAULT_TIMEOUT_MS` (`300_000` ms, or 5 minutes). Setting `timeoutMs: Infinity` disables the deadline so the script runs until it settles or `signal` aborts it. A script that awaits a promise nothing can settle (with no tool call pending and no timers or I/O in the VM) fails immediately instead of hanging.
81
-
82
- `memoryLimitBytes` caps the VM heap. Allocations beyond that limit fail inside the script with `InternalError: out of memory`.
64
+ `code` runs as the body of an async function, so `return` and top-level `await` work. Inside the script, every sandbox provides:
83
65
 
84
- Aborts, timeouts, and `close()` request worker termination without waiting for the worker to exit. On Bun, a built-in such as a long `String.prototype.indexOf` may not poll QuickJS's interrupt handler, so its worker can continue computing until the built-in returns.
66
+ - **`tools.<name>(args)`:** Returns a promise; arguments and results pass through JSON round trips. Rejected `Error` instances cross into the script with the same message plus any extra JSON-serializable own properties (such as `code`, excluding `name`, `message`, and `stack`). Hyphenated or special names are also exposed via `toCodemodeIdentifier`, so `my-tool` works as both `tools.my_tool` and `tools["my-tool"]`.
67
+ - **`ALL_TOOLS`:** Array of `{ name, description }` for every tool, using the identifier form for `name`.
68
+ - **`text(value)` and `console.*`:** `text()` appends a text item to `result.output` (JSON-stringifying non-strings); `console.log`/`info`/`warn`/`error`/`debug` append text items with `console: true`.
69
+ - **`image(urlOrItem)`:** Appends an image item from a base64 `data:` URL, `{ image_url }`, or an image block (`{ type: "image", data, mimeType }`). Remote URLs are rejected.
70
+ - **`exit()`:** Ends the script immediately with a successful result, preserving output and store writes.
71
+ - **`globals`:** Optional host helpers callable as top-level functions (or dotted `namespace.member` on a frozen object) that are not recorded in `result.calls`. Reserved names (`tools`, `ALL_TOOLS`, `console`, `text`, `image`, `exit`, `globalThis`, `store`, `load`) cannot be shadowed. Set `spread: true` to pass all arguments as an array, and `signature` to customize the generated declaration.
72
+ - **`store(key, value)` / `load(key)`:** Synchronous JSON key-value store across runs (see [Store](#store)).
73
+ - **Frozen built-in prototypes:** Built-in prototypes (`Object.prototype`, `Array.prototype`, etc.) are frozen before execution; monkey-patching throws a `TypeError` (instance overrides of `constructor`, `name`, `message`, `toString`, `toLocaleString`, `valueOf`, and `toJSON` remain allowed).
74
+ - **No ambient capabilities:** No timers, `fetch`, `process`, `require`, modules, or `WebAssembly`. `eval` and `Function` evaluate only inside the same VM.
85
75
 
86
- Stopping unrefs the worker after requesting termination because `terminate()` refs it internally. That does not guarantee computation has stopped, and on Bun a pending `terminate()` can still delay host process exit. Cancellation results and `close()` never wait for worker exit.
76
+ When `timeoutMs` is omitted, `CodemodeSandbox` defaults to `300,000` ms (5 minutes). Pass `timeoutMs: Infinity` to disable the deadline so scripts run until completion or `signal` abort. A script that awaits a promise nothing can settle fails immediately instead of hanging. `memoryLimitBytes` caps the VM heap (`InternalError: out of memory` when exceeded).
87
77
 
88
- Hosts that limit concurrency can track actual worker lifetime with `onWorkerStarted(exited)`, called for each worker started by `execute()` or `start()`. Its promise resolves when that worker exits, not when the script result settles:
89
-
90
- ```ts
91
- const workers = new Set<Promise<void>>();
92
- const sandbox = new CodemodeSandbox({
93
- onWorkerStarted(exited) {
94
- workers.add(exited);
95
- void exited.then(() => workers.delete(exited));
96
- },
97
- });
98
- ```
99
-
100
- Keep a concurrency slot occupied until `exited` resolves. `close()` does not wait for these promises.
101
-
102
- To enforce an admission limit, pass `acquireWorker()`. It runs synchronously after WASM loading, immediately before each worker is created. Throw to reject the execution without starting a worker; otherwise return a release callback. The sandbox calls it once on actual worker exit or if the worker constructor fails. Share reservation state across sandbox instances, and do not release it when a script result settles.
78
+ <Note>
79
+ **Worker termination and concurrency limits:** Aborts, timeouts, and `close()` request worker termination and unref the worker without waiting for it to exit. On Bun, long-running built-ins such as `String.prototype.indexOf` may not poll QuickJS's interrupt handler and can delay process exit until the built-in returns. Use `onWorkerStarted(exited)` to hold concurrency slots until actual worker exit, or `acquireWorker()` (synchronous callback called immediately before creating each worker; throw to reject admission, or return a release callback) to enforce shared admission limits across sandbox instances.
80
+ </Note>
103
81
 
104
82
  ## Store
105
83
 
106
- `store()` and `load()` let scripts keep values across executions. The sandbox does not persist anything itself. Pass the current values in `options.store`, and a successful result returns what the script changed in `result.storeWrites` (`{ set, delete }`). Failed executions report no writes.
84
+ `store()` and `load()` let scripts carry JSON state across executions without the sandbox persisting anything itself. Pass saved values in `options.store`, and apply `result.storeWrites` (`{ set, delete }`) when `result.ok` is `true` (failed executions report no writes):
107
85
 
108
86
  ```ts
109
87
  const result = await sandbox.execute(`store("runs", (load("runs") ?? 0) + 1)`, { store: saved });
110
88
  if (result.ok) {
111
- for (const key of result.storeWrites.delete) delete saved[key];
112
- Object.assign(saved, result.storeWrites.set);
89
+ for (const key of result.storeWrites.delete) delete saved[key];
90
+ Object.assign(saved, result.storeWrites.set);
113
91
  }
114
92
  ```
115
93
 
116
- `load()` returns a copy, so mutating it does not change the store. Storing `undefined` deletes the key. Each stored value may be at most `MAX_STORE_VALUE_CHARS` (256 Ki) characters of JSON, and all stored values together may be at most `MAX_STORE_TOTAL_CHARS` (1 Mi) characters. Larger writes throw a `RangeError` inside the script.
94
+ `load()` returns a copy so mutations do not affect the store, and storing `undefined` deletes a key. Individual values cap at `MAX_STORE_VALUE_CHARS` (256 Ki) JSON characters, and total stored data caps at `MAX_STORE_TOTAL_CHARS` (1 Mi) characters (`RangeError` inside the script when exceeded).
117
95
 
118
96
  ## Source format
119
97
 
120
- `parseCodemodeSource()` accepts a script whose first line may be an options line:
98
+ `parseCodemodeSource()` accepts an optional `// @options:` JSON header on line 1:
121
99
 
122
100
  ```js
123
101
  // @options: {"max_output_tokens": 2000, "timeout_ms": 30000}
@@ -125,307 +103,239 @@ const source = await tools.read({ path: "package.json" });
125
103
  text(JSON.parse(source).name);
126
104
  ```
127
105
 
128
- Supported JSON fields on the `// @options:` header line are snake_case:
129
-
130
- - `max_output_tokens`: non-negative safe integer (`>= 0`; `0` is valid), returned as `options.maxOutputTokens`.
131
- - `timeout_ms`: positive safe integer from `1` to `2,147,483,647`, returned as `options.timeoutMs`.
106
+ Supported header fields (snake_case):
132
107
 
133
- `parseCodemodeSource()` returns `{ code, options: { maxOutputTokens?, timeoutMs? } }`. The sandbox does not enforce these limits itself; the caller decides how to apply them. The options line is replaced by a blank line so line numbers in stack traces still match the input.
108
+ - `max_output_tokens`: non-negative safe integer (`>= 0`), returned as `options.maxOutputTokens`.
109
+ - `timeout_ms`: positive safe integer (`1` to `2,147,483,647`), returned as `options.timeoutMs`.
134
110
 
135
- Empty input, invalid JSON, unknown fields, an options line without code, or an options line after line 1 throw `CodemodeSourceError`. `CODEMODE_SOURCE_GRAMMAR` is a Lark grammar for providers that support grammar-constrained tool input. Both exports are also available from the lightweight `@bastani/atomic-codemode/source` entry.
111
+ `parseCodemodeSource()` returns `{ code, options: { maxOutputTokens?, timeoutMs? } }` and replaces line 1 with a blank line so stack-trace line numbers match the input. Empty input, invalid JSON, unknown fields, header-only input, or a header after line 1 throws `CodemodeSourceError`. `CODEMODE_SOURCE_GRAMMAR` exports a Lark grammar for grammar-constrained tool calling (both also exported from `@bastani/atomic-codemode/source`). The sandbox does not enforce these parsed options automatically; your caller applies them.
136
112
 
137
- ## Bundled Node and Bun hosts
113
+ ## Declarations for the model
138
114
 
139
- By default, `CodemodeSandbox` loads `quickjs-wasi/quickjs.wasm` from the installed package and starts the worker file next to this package's module. Neither exists on disk in a bundled host, so pass both explicitly:
115
+ Tools and globals can carry `description`, `inputSchema`, and `outputSchema` (JSON Schema). `renderDeclarations()` generates compact TypeScript declarations for a model-facing tool description:
140
116
 
141
117
  ```ts
142
- import { CodemodeSandbox, loadQuickJSWasm } from "@bastani/atomic-codemode";
143
-
144
- const sandbox = new CodemodeSandbox({
145
- tools,
146
- // Compiled once per path and cached.
147
- wasm: loadQuickJSWasm(pathToQuickJSWasm),
148
- // A file of your build containing `import "@bastani/atomic-codemode/worker";`
149
- workerUrl: new URL("./codemode-worker.js", import.meta.url),
150
- });
118
+ renderDeclarations({ tools: sandbox.tools, globals: sandbox.globals });
119
+ // declare const tools: {
120
+ // /** Read a file */
121
+ // read(args: {
122
+ // path: string;
123
+ // }): Promise<string>;
124
+ // };
151
125
  ```
152
126
 
153
- `workerUrl` accepts a `URL` or string. For a Bun compiled executable, include the worker as an additional build entrypoint and pass its relative source path as a string, such as `"./src/codemode-worker.ts"`. Bun resolves that form from its embedded module graph.
154
-
155
- ## Usage on Cloudflare Workers
156
-
157
- `CodemodeSandbox` requires Node or Bun because it starts a worker thread per script and reads the QuickJS binary from disk. Cloudflare Workers have neither, and they cannot compile WebAssembly at runtime. Two other sandboxes share the same API, script environment, and `CodemodeResult`, differing only in where the VM runs:
127
+ Property descriptions render as `//` comments, and extra JSON Schema constraints render as tags (`// @integer @minimum 1 @default 20`, dropped first if a declaration hits the size limit). Local `$ref`s (`#/$defs/...`, `#/definitions/...`) expand inline; recursive and remote references render as `unknown`. Schemas shape declarations only—they do not validate runtime values.
158
128
 
159
- | Sandbox | Where the VM runs | Use it for |
160
- | --- | --- | --- |
161
- | `CodemodeSandbox` | A worker thread | Node and Bun |
162
- | `RemoteCodemodeSandbox` | Another isolate, usually a Durable Object in a separate Worker | A Durable Object that runs an agent session |
163
- | `InlineCodemodeSandbox` | The calling thread | Other runtimes with WebAssembly when blocking the caller is acceptable |
129
+ ## Results
164
130
 
165
- Import `RemoteCodemodeSandbox` and `InlineCodemodeSandbox` from `@bastani/atomic-codemode/portable`, which has no Node imports. On Cloudflare, `@bastani/atomic-codemode/cloudflare` adds the deployable Durable Object and the QuickJS module compiled by Wrangler.
131
+ `execute()` never rejects for script failures. When `result.ok` is `false`, `result.error.kind` is one of:
166
132
 
167
- ### Why a separate Worker
133
+ | Kind | Meaning |
134
+ | --- | --- |
135
+ | `script` | The script threw or failed to parse (`stack` references `codemode.js:<line>`). |
136
+ | `timeout` | The deadline expired or the interrupt budget ran out, and VM shutdown was requested. |
137
+ | `aborted` | `options.signal` fired or `close()` was called, and VM shutdown was requested. |
138
+ | `sandbox` | The VM or its transport failed (WebAssembly trap, missing worker file, or failed remote). |
168
139
 
169
- QuickJS runs synchronously, so a script that computes holds its thread until it awaits a tool. Running the VM inside the session's Durable Object or inside a Dynamic Worker loaded by that object blocks other requests to the session object for the entire compute burst.
140
+ `result.output` holds text and image blocks in production order (including on failures), capped at `MAX_OUTPUT_CHARS` (16 Mi characters) and `MAX_OUTPUT_ITEMS` (100,000 items)—exceeding either fails the script with an uncatchable `RangeError`.
170
141
 
171
- Running the VM in a Durable Object of a separately deployed Worker moves computation to another isolate and keeps the session object responsive. `RemoteCodemodeSandbox` keeps the tools and call records in the session and sends only the VM to the sandbox Worker. Each tool call travels back to the session over Workers RPC.
142
+ `result.calls` records every tool call with `status: "ok" | "error" | "cancelled"`. Any unawaited call still running when the script returns is aborted via its `signal` and recorded as `"cancelled"`.
172
143
 
173
- ### Deploying the sandbox Worker
144
+ ## Using with agent-core
174
145
 
175
- A complete setup is in [`packages/codemode/examples/cloudflare`](https://github.com/bastani-inc/atomic/tree/main/packages/codemode/examples/cloudflare). The sandbox Worker is one file:
146
+ Expose an [`@bastani/atomic-agent-core`](/libraries/agent-core) `Agent`'s tools to a sandbox and wrap `execute()` as an `AgentTool`:
176
147
 
177
148
  ```ts
178
- // sandbox/src/index.ts
179
- export { CodemodeSandboxDurableObject as CodemodeSandbox } from "@bastani/atomic-codemode/cloudflare";
180
-
181
- export default {
182
- fetch: () => new Response("Not found", { status: 404 }),
183
- };
184
- ```
185
-
186
- ```jsonc
187
- // sandbox/wrangler.jsonc
188
- {
189
- "name": "atomic-codemode-sandbox",
190
- "main": "src/index.ts",
191
- "compatibility_date": "2026-04-22",
192
- "workers_dev": false,
193
- "preview_urls": false,
194
- "migrations": [{ "tag": "v1", "new_sqlite_classes": ["CodemodeSandbox"] }],
195
- "limits": { "cpu_ms": 60000 }
196
- }
197
- ```
198
-
199
- Install `@bastani/atomic-codemode` in the sandbox Worker's project and run `npx wrangler deploy`. Wrangler bundles QuickJS (about 640 KB) as a compiled WebAssembly module. The object has no routes and keeps no state, and it never uses its storage.
200
-
201
- ### Using it from the agent's Worker
149
+ import type { AgentTool } from "@bastani/atomic-agent-core";
150
+ import {
151
+ type CodemodeJsonSchema,
152
+ CodemodeSandbox,
153
+ type CodemodeTool,
154
+ renderDeclarations,
155
+ } from "@bastani/atomic-codemode";
156
+ import { obj, str } from "@bastani/atomic-schema";
202
157
 
203
- Bind the class with `script_name`. Binding a class exported from the agent's own Worker would bring back the blocking described above.
158
+ const sandboxTools: CodemodeTool[] = agentTools.map((tool) => ({
159
+ name: tool.name,
160
+ description: tool.description,
161
+ inputSchema: tool.parameters as CodemodeJsonSchema,
162
+ outputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? { type: "string" },
163
+ execute: async (args, { signal }) => {
164
+ const result = await tool.execute("nested", args as never, signal);
165
+ if (tool.outputSchema && result.structuredContent !== undefined) return result.structuredContent;
166
+ return result.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
167
+ },
168
+ }));
204
169
 
205
- ```jsonc
206
- // agent/wrangler.jsonc
207
- "durable_objects": {
208
- "bindings": [
209
- { "name": "CODEMODE_SANDBOX", "class_name": "CodemodeSandbox", "script_name": "atomic-codemode-sandbox" }
210
- ]
211
- }
170
+ const codemodeTool: AgentTool = {
171
+ name: "codemode",
172
+ label: "Codemode",
173
+ description: `Run JavaScript that calls tools as \`await tools.<name>(args)\`. Output with text() or return.\n\n${renderDeclarations({ tools: sandboxTools })}`,
174
+ parameters: obj({ code: str() }),
175
+ execute: async (_toolCallId, { code }, signal) => {
176
+ const sandbox = new CodemodeSandbox({ tools: sandboxTools });
177
+ try {
178
+ const result = await sandbox.execute(code, { signal });
179
+ const content = [...result.output];
180
+ if (result.ok && result.value !== undefined) content.push({ type: "text", text: JSON.stringify(result.value) });
181
+ if (!result.ok) content.push({ type: "text", text: result.error.stack ?? result.error.message });
182
+ return { content, details: undefined, isError: !result.ok };
183
+ } finally {
184
+ await sandbox.close();
185
+ }
186
+ },
187
+ };
212
188
  ```
213
189
 
214
- Then replace the sandbox. Tools, options other than the worker-specific `wasm`, `workerUrl`, `acquireWorker`, and `onWorkerStarted`, and results stay the same:
190
+ `result.output` items already match `@bastani/atomic-ai`'s `TextContent` and `ImageContent`. Calling `tool.execute()` directly bypasses `beforeToolCall` and `afterToolCall`; route nested calls through `runToolCall()` from `@bastani/atomic-agent-core` so argument validation and hooks apply consistently:
215
191
 
216
192
  ```ts
217
- import type { CodemodeSandboxDurableObject } from "@bastani/atomic-codemode/cloudflare";
218
- import { RemoteCodemodeSandbox } from "@bastani/atomic-codemode/portable";
193
+ import { type Agent, type AgentToolCallOutcome, runToolCall } from "@bastani/atomic-agent-core";
194
+ import type { JsonObject } from "@bastani/atomic-ai";
219
195
 
220
- interface Env {
221
- CODEMODE_SANDBOX: DurableObjectNamespace<CodemodeSandboxDurableObject>;
196
+ function createNestedToolRunner(
197
+ agent: Agent,
198
+ ): (name: string, args: unknown, signal: AbortSignal) => Promise<AgentToolCallOutcome> {
199
+ let nextId = 1;
200
+ return (name, args, signal) => {
201
+ const assistantMessage = agent.state.messages.findLast((message) => message.role === "assistant");
202
+ if (assistantMessage?.role !== "assistant") throw new Error("Nested tool calls need an assistant message");
203
+ const tools = agent.state.tools;
204
+ return runToolCall(
205
+ { type: "toolCall", id: `nested-${nextId++}`, name, arguments: (args ?? {}) as JsonObject },
206
+ {
207
+ tools,
208
+ assistantMessage,
209
+ context: { messages: agent.state.messages, tools },
210
+ beforeToolCall: agent.beforeToolCall,
211
+ afterToolCall: agent.afterToolCall,
212
+ signal,
213
+ },
214
+ );
215
+ };
222
216
  }
223
-
224
- // Before: new CodemodeSandbox({ tools, timeoutMs: 60_000 })
225
- const sandbox = new RemoteCodemodeSandbox({
226
- tools,
227
- timeoutMs: 60_000,
228
- remote: () => env.CODEMODE_SANDBOX.getByName(sessionId),
229
- });
230
- const result = await sandbox.execute(code, { signal, store });
231
217
  ```
232
218
 
233
- Import the sandbox from `/portable` in the agent's Worker. Importing `/cloudflare` would also bundle QuickJS there. `remote` is called once per execution and picks the Durable Object that runs it.
219
+ Invoke the runner from each sandbox tool's `execute`, throwing when `outcome.isError` is `true` so the script catches the failure.
234
220
 
235
- - **One object per session**, `getByName(sessionId)`, keeps a session's scripts together. Two scripts of the same session take turns on one thread.
236
- - **One object per execution**, `getByName(crypto.randomUUID())`, runs every script on its own.
237
-
238
- Run both Workers locally with `wrangler dev -c agent/wrangler.jsonc -c sandbox/wrangler.jsonc`.
221
+ ## Deterministic runs
239
222
 
240
- ### Limits on Cloudflare
223
+ `sandbox.start(code, options)` runs a script deterministically so a durable host can replay it after restarts from a log of call results (`execute()` is unaffected):
241
224
 
242
- - **Interrupt budget.** While a script computes without calling a tool, no timer runs and `Date.now()` does not advance. A script that never yields is bounded by the interrupt budget rather than `timeoutMs`. QuickJS polls an interrupt handler while running, and the sandbox counts polls. Past the budget, execution fails with `kind: "timeout"`.
243
- * The default `DEFAULT_INTERRUPT_BUDGET` of 100,000 polls allows roughly 10 seconds of a tight loop on Cloudflare Workers.
244
- * Keep the budget below the Worker's `cpu_ms` limit (30 seconds by default). Hitting that limit resets the Durable Object instead of failing only the script.
245
- - **Memory.** Each VM may use up to 32 MiB by default. All VMs in one isolate share its 128 MB limit.
246
- - **Changing the limits.** The Durable Object caps every request at its own limits regardless of what the client requests. Subclass it in the sandbox Worker to raise or lower those caps:
225
+ - **Time:** `Date.now()` starts at `startedAt` and advances monotonically from each delivered result's `now`; `performance.now()` counts from `startedAt`.
226
+ - **Randomness, timezone, and GC:** `Math.random()` uses `seed`, timezone is fixed to UTC, and `WeakRef`/`FinalizationRegistry` are absent.
227
+ - **Strict result order:** Results are delivered with sequential numbers (`1`, `2`, ...) and applied in exact order regardless of transport arrival.
247
228
 
248
229
  ```ts
249
- import { CodemodeSandboxDurableObject } from "@bastani/atomic-codemode/cloudflare";
250
-
251
- export class CodemodeSandbox extends CodemodeSandboxDurableObject {
252
- protected maxInterruptBudget = 200_000;
253
- protected maxMemoryLimitBytes = 64 * 1024 * 1024;
254
- }
230
+ const run = sandbox.start(code, {
231
+ startedAt: Date.now(),
232
+ seed: 7,
233
+ tools: [{ name: "read", description: "Read a file" }],
234
+ onStarted: (_fingerprint) => {}, // engine versions, prelude hash, limits
235
+ onCall: (call) => {
236
+ void readFile(call.args).then((content) =>
237
+ run.deliver(nextResult++, Date.now(), call.id, { ok: true, value: content }),
238
+ );
239
+ },
240
+ onIdle: (_seq, _issued) => {},
241
+ });
242
+ const result = await run.result;
255
243
  ```
256
244
 
257
- - **Aborts and timeouts.** `timeoutMs` and `signal` end execution in the caller immediately with `kind: "timeout"` or `kind: "aborted"`. The remote VM stops at its next tool call, or keeps running until it calls a tool or exhausts its interrupt budget.
258
- - **Billing.** Each execution is one Durable Object request. The sandbox object is billed for wall-clock duration while an execution runs, including time spent waiting on tools.
245
+ Deterministic runs have no deadline unless `timeoutMs` is passed. Replaying the same script, `startedAt`, `seed`, tools, globals, store, and ordered results produces identical calls and output on any VM with the same fingerprint. Abort `signal` to terminate a run with an uncatchable error.
259
246
 
260
- ### On the calling thread
247
+ ## Bundled Node and Bun hosts
261
248
 
262
- When blocking the caller is acceptable, such as in a stateless Worker serving a single request, run the VM on the caller's thread instead with no extra deployment:
249
+ By default, `CodemodeSandbox` reads `quickjs-wasi/quickjs.wasm` and starts its worker file next to this package. In bundled executables, pass both explicitly:
263
250
 
264
251
  ```ts
265
- import { createInlineCodemodeSandbox } from "@bastani/atomic-codemode/cloudflare";
252
+ import { CodemodeSandbox, loadQuickJSWasm } from "@bastani/atomic-codemode";
266
253
 
267
- const sandbox = createInlineCodemodeSandbox({ tools, timeoutMs: 60_000, interruptBudget: 50_000 });
268
- const result = await sandbox.execute(code);
254
+ const sandbox = new CodemodeSandbox({
255
+ tools,
256
+ wasm: loadQuickJSWasm(pathToQuickJSWasm), // compiled once per path and cached
257
+ workerUrl: new URL("./codemode-worker.js", import.meta.url), // file containing `import "@bastani/atomic-codemode/worker";`
258
+ });
269
259
  ```
270
260
 
271
- `createInlineCodemodeSandbox()` passes the Wrangler-compiled QuickJS module to `InlineCodemodeSandbox`. With another bundler, import `InlineCodemodeSandbox` from `/portable` and pass your own compiled module as `wasm`.
272
-
273
- - **Blocking.** A script that computes blocks the caller until it awaits a tool or exhausts its `interruptBudget`.
274
- - **Stack.** QuickJS's stack guard is lowered to 256 KiB so deep recursion trips before the caller's smaller stack overflows.
261
+ For Bun compiled executables, include the worker as an additional build entrypoint and pass its relative source path as a string (such as `"./src/codemode-worker.ts"`).
275
262
 
276
- ## Declarations for the model
277
-
278
- Tools and globals can carry `description`, `inputSchema`, and `outputSchema` (JSON Schema). `renderDeclarations()` turns them into TypeScript declarations for a model-facing tool description:
279
-
280
- ```ts
281
- renderDeclarations({ tools: sandbox.tools, globals: sandbox.globals });
282
- // declare const tools: {
283
- // /** Read a file */
284
- // read(args: {
285
- // path: string;
286
- // }): Promise<string>;
287
- // };
288
- ```
263
+ ## Usage on Cloudflare Workers
289
264
 
290
- Property descriptions become `//` comments. Constraints the type cannot express follow as tags, such as `// @integer @minimum 1 @default 20`; they are dropped first when a type exceeds the size limit. Schemas only shape the declarations; values are not validated against them. Local references (`#/$defs/...`, `#/definitions/...`) are expanded; recursive and remote references render as `unknown`.
265
+ Cloudflare Workers cannot spawn Node worker threads or compile WebAssembly at runtime. Use `RemoteCodemodeSandbox` (from `@bastani/atomic-codemode/portable`, which has zero Node imports) paired with `CodemodeSandboxDurableObject` (from `@bastani/atomic-codemode/cloudflare`) in a **separate** Worker so synchronous QuickJS compute bursts never block your agent session's Durable Object.
291
266
 
292
- ## Using with agent-core
267
+ A complete deployment example lives in [`packages/codemode/examples/cloudflare`](https://github.com/bastani-inc/atomic/tree/main/packages/codemode/examples/cloudflare).
293
268
 
294
- To give an [`@bastani/atomic-agent-core`](/libraries/agent-core) `Agent` a codemode tool, expose its other tools to the sandbox and wrap `execute()` as an `AgentTool`:
269
+ ### Deploying the sandbox Worker
295
270
 
296
271
  ```ts
297
- import type { AgentTool } from "@bastani/atomic-agent-core";
298
- import {
299
- type CodemodeJsonSchema,
300
- CodemodeSandbox,
301
- type CodemodeTool,
302
- renderDeclarations,
303
- } from "@bastani/atomic-codemode";
304
- import { obj, str } from "@bastani/atomic-schema";
305
-
306
- const sandboxTools: CodemodeTool[] = agentTools.map((tool) => ({
307
- name: tool.name,
308
- description: tool.description,
309
- inputSchema: tool.parameters as CodemodeJsonSchema,
310
- outputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? { type: "string" },
311
- execute: async (args, { signal }) => {
312
- const result = await tool.execute("nested", args as never, signal);
313
- if (tool.outputSchema && result.structuredContent !== undefined) return result.structuredContent;
314
- return result.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
315
- },
316
- }));
272
+ // sandbox/src/index.ts
273
+ export { CodemodeSandboxDurableObject as CodemodeSandbox } from "@bastani/atomic-codemode/cloudflare";
317
274
 
318
- const codemodeTool: AgentTool = {
319
- name: "codemode",
320
- label: "Codemode",
321
- description: `Run JavaScript that calls tools as \`await tools.<name>(args)\`. Output with text() or return.\n\n${renderDeclarations({ tools: sandboxTools })}`,
322
- parameters: obj({ code: str() }),
323
- execute: async (_toolCallId, { code }, signal) => {
324
- const sandbox = new CodemodeSandbox({ tools: sandboxTools });
325
- try {
326
- const result = await sandbox.execute(code, { signal });
327
- const content = [...result.output];
328
- if (result.ok && result.value !== undefined) content.push({ type: "text", text: JSON.stringify(result.value) });
329
- if (!result.ok) content.push({ type: "text", text: result.error.stack ?? result.error.message });
330
- return { content, details: undefined, isError: !result.ok };
331
- } finally {
332
- await sandbox.close();
333
- }
334
- },
275
+ export default {
276
+ fetch: () => new Response("Not found", { status: 404 }),
335
277
  };
336
278
  ```
337
279
 
338
- `result.output` items already have the shape of `@bastani/atomic-ai`'s `TextContent` and `ImageContent`. Calling `tool.execute()` directly skips the agent's `beforeToolCall` and `afterToolCall` hooks. To apply them to nested calls too, run each call through `runToolCall()` from `@bastani/atomic-agent-core`. It runs argument validation and the agent's hooks as for a call the model makes, and returns failures as `isError: true` instead of throwing:
339
-
340
- ```ts
341
- import { type Agent, type AgentToolCallOutcome, runToolCall } from "@bastani/atomic-agent-core";
342
- import type { JsonObject } from "@bastani/atomic-ai";
343
-
344
- function createNestedToolRunner(
345
- agent: Agent,
346
- ): (name: string, args: unknown, signal: AbortSignal) => Promise<AgentToolCallOutcome> {
347
- let nextId = 1;
348
- return (name, args, signal) => {
349
- const assistantMessage = agent.state.messages.findLast((message) => message.role === "assistant");
350
- if (assistantMessage?.role !== "assistant") throw new Error("Nested tool calls need an assistant message");
351
- const tools = agent.state.tools;
352
- return runToolCall(
353
- { type: "toolCall", id: `nested-${nextId++}`, name, arguments: (args ?? {}) as JsonObject },
354
- {
355
- tools,
356
- assistantMessage,
357
- context: { messages: agent.state.messages, tools },
358
- beforeToolCall: agent.beforeToolCall,
359
- afterToolCall: agent.afterToolCall,
360
- signal,
361
- },
362
- );
363
- };
280
+ ```jsonc
281
+ // sandbox/wrangler.jsonc
282
+ {
283
+ "name": "atomic-codemode-sandbox",
284
+ "main": "src/index.ts",
285
+ "compatibility_date": "2026-04-22",
286
+ "workers_dev": false,
287
+ "preview_urls": false,
288
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["CodemodeSandbox"] }],
289
+ "limits": { "cpu_ms": 60000 }
364
290
  }
365
291
  ```
366
292
 
367
- Call the runner from each sandbox tool's `execute` instead of `tool.execute()`, and throw when the outcome has `isError: true` so the script sees the failure.
293
+ Install `@bastani/atomic-codemode` and run `npx wrangler deploy`. Wrangler bundles QuickJS (~640 KB) as a precompiled WebAssembly module; the Durable Object stores no state.
368
294
 
369
- ## Deterministic runs
295
+ ### Calling it from the agent Worker
370
296
 
371
- `sandbox.start(code, options)` runs a script so that a host can run it again after a restart and get the same behavior, for example to resume it from a durable log of its calls' results. `execute()` is unaffected.
297
+ Bind the class using `script_name` (binding a class in the agent's own Worker would reintroduce main-thread blocking):
372
298
 
373
- The VM only runs when the host hands it something, and has no timers or I/O, so it is deterministic except for what it reads from its environment. `start()` fixes that:
299
+ ```jsonc
300
+ // agent/wrangler.jsonc
301
+ "durable_objects": {
302
+ "bindings": [
303
+ { "name": "CODEMODE_SANDBOX", "class_name": "CodemodeSandbox", "script_name": "atomic-codemode-sandbox" }
304
+ ]
305
+ }
306
+ ```
374
307
 
375
- - **Time.** `Date.now()` reads `startedAt`, then the `now` of each delivered result without ever going backwards. `performance.now()` counts from `startedAt`.
376
- - **Randomness.** `Math.random()` and the VM's other randomness come from `seed`.
377
- - **Timezone.** The VM always uses UTC, regardless of the host timezone.
378
- - **Garbage collection.** `WeakRef` and `FinalizationRegistry` are absent.
379
- - **Result order.** The host answers each call with a sequential result number (`1`, `2`, ...), and the VM applies results strictly in that order regardless of transport delivery order.
308
+ ```ts
309
+ import type { CodemodeSandboxDurableObject } from "@bastani/atomic-codemode/cloudflare";
310
+ import { RemoteCodemodeSandbox } from "@bastani/atomic-codemode/portable";
380
311
 
381
- The run declares its own tools and globals, and the host answers every call itself:
312
+ interface Env {
313
+ CODEMODE_SANDBOX: DurableObjectNamespace<CodemodeSandboxDurableObject>;
314
+ }
382
315
 
383
- ```ts
384
- const run = sandbox.start(code, {
385
- startedAt: Date.now(),
386
- seed: 7,
387
- tools: [{ name: "read", description: "Read a file" }],
388
- onStarted: (fingerprint) => {}, // what the VM is: engine versions, prelude hash, limits
389
- onCall: (call) => {
390
- // call.id is the VM's own number for the call, in the order the script made them.
391
- void readFile(call.args).then((text) => run.deliver(nextResult++, Date.now(), call.id, { ok: true, value: text }));
392
- },
393
- onIdle: (seq, issued) => {}, // after result `seq` (0: the first run), `issued` calls in total
316
+ const sandbox = new RemoteCodemodeSandbox({
317
+ tools,
318
+ timeoutMs: 60_000,
319
+ remote: () => env.CODEMODE_SANDBOX.getByName(sessionId), // or crypto.randomUUID() for one DO per execution
394
320
  });
395
- const result = await run.result;
321
+ const result = await sandbox.execute(code, { signal, store });
396
322
  ```
397
323
 
398
- A run has no deadline unless `timeoutMs` is given. Result numbers must run 1, 2, ... without gaps. The same script, `startedAt`, `seed`, tools (with their `jsName`), globals and store, answered with the same results in the same order, makes the same calls with the same arguments and produces the same output on any VM with the same fingerprint. To end a run with an error the script cannot catch, abort its `signal`.
399
-
400
- ## Results
401
-
402
- `execute()` never rejects for script failures. `result.error.kind` is one of:
324
+ Import `RemoteCodemodeSandbox` from `/portable` in the agent Worker so QuickJS is not bundled there. Run both Workers locally with `wrangler dev -c agent/wrangler.jsonc -c sandbox/wrangler.jsonc`.
403
325
 
404
- | Kind | Meaning |
405
- | --- | --- |
406
- | `script` | The script threw or failed to parse. `stack` points at `codemode.js:<line>`. |
407
- | `timeout` | The deadline expired or the interrupt budget ran out, and VM shutdown was requested. |
408
- | `aborted` | `options.signal` fired or `close()` was called, and VM shutdown was requested. |
409
- | `sandbox` | The VM or its transport failed, such as a WebAssembly trap, a missing worker file, or a failed remote. |
410
-
411
- `result.output` holds text and image items in the order the script produced them, including for failed executions. Because the host retains all output until the script ends, output is capped at `MAX_OUTPUT_CHARS` (16 Mi) characters of text and base64 image data and `MAX_OUTPUT_ITEMS` (100,000) items. Past either limit, the script fails with a `RangeError` even if it catches the error.
326
+ ### Cloudflare limits and inline execution
412
327
 
413
- `result.calls` lists every tool call with `status: "ok" | "error" | "cancelled"`. Any unawaited call still running when the script returns is aborted through its `signal` and reported as `cancelled`.
328
+ - **Interrupt budget:** Tight loops without tool calls are bounded by `DEFAULT_INTERRUPT_BUDGET` (`100,000` polls, ~10 seconds on Workers) and fail with `kind: "timeout"`. Keep this below the Worker's `cpu_ms` limit so scripts fail cleanly instead of resetting the Durable Object.
329
+ - **Memory & caps:** Default 32 MiB per VM (shared within the isolate's 128 MB cap). Subclass `CodemodeSandboxDurableObject` and override `protected maxInterruptBudget` / `protected maxMemoryLimitBytes` to adjust caps.
330
+ - **Aborts, timeouts, and billing:** `timeoutMs` and `signal` settle immediately in the caller (`kind: "timeout"` or `"aborted"`); the remote VM stops at its next tool call or interrupt budget. Each execution bills one Durable Object request for wall-clock duration.
331
+ - **Calling thread (`InlineCodemodeSandbox`):** When blocking a stateless request Worker is acceptable, use `createInlineCodemodeSandbox({ tools, timeoutMs, interruptBudget })` from `@bastani/atomic-codemode/cloudflare` (lowers QuickJS's stack guard to 256 KiB; blocks the caller during compute).
414
332
 
415
333
  ## How it works
416
334
 
417
- This section describes `CodemodeSandbox`. The other sandboxes share the same host code, prelude, and VM, replacing only the worker thread. See [Usage on Cloudflare Workers](#usage-on-cloudflare-workers).
418
-
419
- Each `execute()` starts a worker thread that instantiates a fresh QuickJS VM from the compiled WebAssembly module. Each VM is a separate WebAssembly instance with its own linear memory. Its only imports are a WASI shim (clock, random, and discarded stdout/stderr writes) and one host-call entry point, so the script can reach the host only through functions registered by the worker.
420
-
421
- The worker evaluates a prelude inside the VM that holds the single host bridge in a closure and builds `tools`, `console`, and globals on top of it. The script compiles as an async function body.
422
-
423
- Tool calls travel to the host thread as messages; the host runs each tool and posts the JSON result back. The host owns the deadline and abort signal. When either fires, it sets a shared interrupt flag that the VM polls and then calls `worker.terminate()`. The shared flag stops tight loops on Bun, where `terminate()` alone cannot stop a thread spinning inside WebAssembly.
424
-
425
- Running scripts in a worker keeps execution off the host thread. Because QuickJS runs synchronously, a spinning script on the host thread would block its event loop.
335
+ Each `CodemodeSandbox.execute()` spawns a worker thread that instantiates a fresh QuickJS WebAssembly instance with its own linear memory, importing only a minimal WASI shim (clock, random, discarded stdio) and one host-call bridge. Tool calls travel to the host thread over worker messages; timeouts and aborts set a shared interrupt flag polled by QuickJS and call `worker.terminate()`.
426
336
 
427
- ## Runtime notes
337
+ ### Runtime notes
428
338
 
429
- - Node and Bun support memory limits, interrupts, and a catchable `RangeError` for deep recursion because QuickJS's stack guard is enabled. Bun may delay worker exit during non-interruptible built-ins, though script results do not wait for exit.
430
- - Stack traces use QuickJS frames (`at f (codemode.js:2:31)`), prefixed with `Name: message` like V8. The wrapper prefix shares line 1 with the script, so line numbers are exact while column numbers on line 1 are shifted.
431
- - QuickJS is an interpreter. Glue code and tool-result filtering run fast enough, while heavy computation is slower than in V8.
339
+ - Node and Bun enforce memory limits, interrupts, and catchable `RangeError` stack guards for deep recursion.
340
+ - Stack traces use QuickJS frames (`at f (codemode.js:2:31)`), prefixed with `Name: message` like V8; line numbers match the script (column numbers on line 1 are shifted by the async wrapper prefix).
341
+ - QuickJS is an interpreter: glue code and result filtering run quickly, while heavy CPU computation is slower than in V8.