@bastani/atomic 0.10.14 → 0.10.15-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/README.md +1 -1
- package/dist/_shared/dist-KOELCESV.js +2 -2
- package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
- package/dist/_shared/lib-4PES5P4V.js +2 -2
- package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +3 -3
- package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +3 -3
- package/dist/_shared/mode-shared-2QJSCUM6.js +3 -3
- package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
- package/dist/_shared/runtime-O4KCSG4C.js +2 -2
- package/dist/_shared/{sdk-B5LEWGGI.js → sdk-OHKMDJ74.js} +27 -5
- package/dist/_shared/{sdk-B5LEWGGI.js.map → sdk-OHKMDJ74.js.map} +1 -1
- package/dist/_shared/session-data-AHTU7IS6.js +2 -2
- package/dist/_shared/startup-0-0-Q3MWKUK4.js +2 -2
- package/dist/_shared/startup-0-1-M6OWAYHH.js +2 -2
- package/dist/_shared/{startup-0-2-5QHPCEON.js → startup-0-2-2HUMCPKX.js} +14 -16
- package/dist/_shared/startup-0-2-2HUMCPKX.js.map +1 -0
- package/dist/_shared/startup-0-3-4ZYBYQNM.js +3 -3
- package/dist/_shared/startup-0-4-ZMJV547D.js +3 -3
- package/dist/_shared/startup-0-5-YDW47QX6.js +3 -3
- package/dist/_shared/startup-10-0-TDQNBDDL.js +3 -3
- package/dist/_shared/startup-14-0-MLX36RBG.js +1 -1
- package/dist/_shared/startup-15-0-YUKGAC63.js +1 -1
- package/dist/_shared/startup-15-1-4S7FLMNG.js +6 -30
- package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
- package/dist/_shared/startup-8-0-34CBHPZH.js +3 -3
- package/dist/_shared/startup-8-1-LZFXSD3Z.js +3 -3
- package/dist/_shared/storage-command-7MGXLJGZ.js +2 -2
- package/dist/_shared/storage-status-K7PX2RXA.js +3 -3
- package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
- package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
- package/dist/builtin/intercom/index.bundle.mjs +1 -1
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/index.bundle.mjs +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
- package/dist/builtin/web-access/index.bundle.mjs +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/cli/auth-cli.code.js +1 -1
- package/dist/cli/auth-cli.impl.js +3 -3
- package/dist/cli/auth-cli.js +3 -3
- package/dist/cli/blueprint-command.impl.js +3 -3
- package/dist/cli/blueprint-command.js +3 -3
- package/dist/cli/intercom-command.code.js +3 -3
- package/dist/cli/intercom-command.impl.js +3 -3
- package/dist/cli/intercom-command.js +3 -3
- package/dist/cli/list-models.impl.js +3 -3
- package/dist/cli/list-models.js +3 -3
- package/dist/cli/session-picker.code.js +1 -1
- package/dist/cli/session-picker.impl.js +3 -3
- package/dist/cli/session-picker.js +3 -3
- package/dist/cli/startup-ui.code.js +1 -1
- package/dist/cli/startup-ui.impl.js +3 -3
- package/dist/cli/startup-ui.js +3 -3
- package/dist/cli/storage-command.impl.js +3 -3
- package/dist/cli/storage-command.js +3 -3
- package/dist/cli/storage-search-session.code.js +1 -1
- package/dist/cli/storage-search-session.impl.js +3 -3
- package/dist/cli/storage-search-session.js +3 -3
- package/dist/cli/team-command.code.js +1 -1
- package/dist/cli/team-command.impl.js +3 -3
- package/dist/cli/team-command.js +3 -3
- package/dist/cli.js +2 -2
- package/dist/core/compaction/compactor.d.ts +0 -8
- package/dist/core/debug.impl.js +3 -3
- package/dist/core/debug.js +3 -3
- package/dist/core/export-html/card-projection.impl.js +3 -3
- package/dist/core/export-html/card-projection.js +3 -3
- package/dist/core/export-html/index.code.js +2 -2
- package/dist/core/export-html/index.impl.js +3 -3
- package/dist/core/export-html/index.js +3 -3
- package/dist/core/export-html/json-spans.impl.js +3 -3
- package/dist/core/export-html/json-spans.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.js +3 -3
- package/dist/core/export-html/tool-renderer.impl.js +3 -3
- package/dist/core/export-html/tool-renderer.js +3 -3
- package/dist/core/extensions/jiti-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-loader.js +3 -3
- package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-static-loader.js +3 -3
- package/dist/core/extensions/loader-host-modules.impl.js +3 -3
- package/dist/core/extensions/loader-host-modules.js +3 -3
- package/dist/core/intercom-broker-control-host.code.js +1 -1
- package/dist/core/intercom-broker-control-host.impl.js +3 -3
- package/dist/core/intercom-broker-control-host.js +3 -3
- package/dist/core/intercom-broker-control.code.js +2 -2
- package/dist/core/intercom-broker-control.impl.js +3 -3
- package/dist/core/intercom-broker-control.js +3 -3
- package/dist/core/package-manager-storage-adapters.impl.js +3 -3
- package/dist/core/package-manager-storage-adapters.js +3 -3
- package/dist/core/sdk.code.js +1 -1
- package/dist/core/sdk.impl.js +3 -3
- package/dist/core/sdk.js +3 -3
- package/dist/core/session-manager-core.js +3 -3
- package/dist/core/session-manager-list.impl.js +3 -3
- package/dist/core/session-manager-list.js +3 -3
- package/dist/core/session-manager.impl.js +3 -3
- package/dist/core/session-manager.js +3 -3
- package/dist/core/session-storage.impl.js +3 -3
- package/dist/core/session-storage.js +3 -3
- package/dist/core/storage/index.js +2 -2
- package/dist/core/storage/node-sqlite-thread.js +2 -2
- package/dist/core/storage/node-sqlite.js +2 -2
- package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
- package/dist/core/storage/offline-snapshot-file.js +3 -3
- package/dist/core/storage/provider.js +2 -2
- package/dist/core/storage/selection.js +2 -2
- package/dist/core/storage/session/branch-fork-source.code.js +2 -2
- package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
- package/dist/core/storage/session/branch-fork-source.js +3 -3
- package/dist/core/storage/session/card-view.impl.js +3 -3
- package/dist/core/storage/session/card-view.js +3 -3
- package/dist/core/storage/session/child-reader.code.js +2 -2
- package/dist/core/storage/session/child-reader.impl.js +3 -3
- package/dist/core/storage/session/child-reader.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.js +3 -3
- package/dist/core/storage/session/expanded-child-details.code.js +2 -2
- package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
- package/dist/core/storage/session/expanded-child-details.js +3 -3
- package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
- package/dist/core/storage/session/fork-row-bytes.js +3 -3
- package/dist/core/storage/session/fork-row-index.impl.js +3 -3
- package/dist/core/storage/session/fork-row-index.js +3 -3
- package/dist/core/storage/session/fork-staging.code.js +1 -1
- package/dist/core/storage/session/fork-staging.impl.js +3 -3
- package/dist/core/storage/session/fork-staging.js +3 -3
- package/dist/core/storage/session/fork-window.code.js +2 -2
- package/dist/core/storage/session/fork-window.impl.js +3 -3
- package/dist/core/storage/session/fork-window.js +3 -3
- package/dist/core/storage/session/history-pages.impl.js +3 -3
- package/dist/core/storage/session/history-pages.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
- package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
- package/dist/core/storage/session/jsonl-session-store.js +3 -3
- package/dist/core/storage/session/memory-session-store.impl.js +3 -3
- package/dist/core/storage/session/memory-session-store.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.code.js +2 -2
- package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.js +3 -3
- package/dist/core/storage/session/released-history-files.code.js +1 -1
- package/dist/core/storage/session/released-history-files.impl.js +3 -3
- package/dist/core/storage/session/released-history-files.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.js +3 -3
- package/dist/core/storage/session/session-resume.impl.js +3 -3
- package/dist/core/storage/session/session-resume.js +3 -3
- package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
- package/dist/core/storage/session/snapshot-cut.js +3 -3
- package/dist/core/storage/session/snapshot-history.code.js +2 -2
- package/dist/core/storage/session/snapshot-history.impl.js +3 -3
- package/dist/core/storage/session/snapshot-history.js +3 -3
- package/dist/core/storage/session/sql-session-store.code.js +1 -1
- package/dist/core/storage/session/sql-session-store.impl.js +3 -3
- package/dist/core/storage/session/sql-session-store.js +3 -3
- package/dist/core/storage/session/tree-outline.impl.js +3 -3
- package/dist/core/storage/session/tree-outline.js +3 -3
- package/dist/core/storage/session/tree-presentation.impl.js +3 -3
- package/dist/core/storage/session/tree-presentation.js +3 -3
- package/dist/core/storage/storage-status.impl.js +3 -3
- package/dist/core/storage/storage-status.js +3 -3
- package/dist/core/storage/team.impl.js +3 -3
- package/dist/core/storage/team.js +3 -3
- package/dist/core/structured-output/index.code.js +1 -1
- package/dist/core/structured-output/index.impl.js +3 -3
- package/dist/core/structured-output/index.js +3 -3
- package/dist/core/tasks/task-completion-entry.impl.js +3 -3
- package/dist/core/tasks/task-completion-entry.js +3 -3
- package/dist/core/tasks/task-file-history.code.js +2 -2
- package/dist/core/tasks/task-file-history.impl.js +3 -3
- package/dist/core/tasks/task-file-history.js +3 -3
- package/dist/core/tasks/task-reference-archive.code.js +2 -2
- package/dist/core/tasks/task-reference-archive.js +3 -3
- package/dist/core/tasks/task-reference-identity.js +3 -3
- package/dist/core/tasks/task-reference-stream.impl.js +3 -3
- package/dist/core/tasks/task-reference-stream.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.js +3 -3
- package/dist/core/tasks/task-view-source.impl.js +3 -3
- package/dist/core/tasks/task-view-source.js +3 -3
- package/dist/core/tools/read-url.impl.js +3 -3
- package/dist/core/tools/read-url.js +3 -3
- package/dist/core/worktree-snapshot/blob-store.js +2 -2
- package/dist/core/worktree-snapshot/errors.code.js +1 -1
- package/dist/core/worktree-snapshot/errors.impl.js +3 -3
- package/dist/core/worktree-snapshot/errors.js +3 -3
- package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
- package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
- package/dist/extensions/codemode/execute.impl.js +3 -3
- package/dist/extensions/codemode/execute.js +3 -3
- package/dist/extensions/codemode/renderer.impl.js +3 -3
- package/dist/extensions/codemode/renderer.js +3 -3
- package/dist/extensions/mcp/cli.code.js +1 -1
- package/dist/extensions/mcp/cli.impl.js +3 -3
- package/dist/extensions/mcp/cli.js +3 -3
- package/dist/extensions/mcp/cli.lazy.code.js +2 -2
- package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
- package/dist/extensions/mcp/cli.lazy.js +3 -3
- package/dist/extensions/mcp/runtime.code.js +1 -1
- package/dist/extensions/mcp/runtime.impl.js +3 -3
- package/dist/extensions/mcp/runtime.js +3 -3
- package/dist/index.d.ts +21 -1
- package/dist/index.js +2 -2
- package/dist/main-first-time-setup.code.js +1 -1
- package/dist/main-first-time-setup.impl.js +3 -3
- package/dist/main-first-time-setup.js +3 -3
- package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
- package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
- package/dist/modes/interactive/components/stored-tree-view.js +3 -3
- package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
- package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
- package/dist/modes/print-mode.js +1 -1
- package/dist/package-manager-cli.code.js +2 -2
- package/dist/package-manager-cli.impl.js +3 -3
- package/dist/package-manager-cli.js +3 -3
- package/dist/startup-files.json +1 -1
- package/dist/startup-stages/6.js +1 -1
- package/dist/utils/startup-database-spare.code.js +1 -1
- package/dist/utils/startup-database-spare.impl.js +3 -3
- package/dist/utils/startup-database-spare.js +3 -3
- package/dist/utils/tools-manager.impl.js +3 -3
- package/dist/utils/tools-manager.js +3 -3
- package/docs/background-tasks/reference.md +182 -0
- package/docs/background-tasks.md +98 -405
- package/docs/build.md +67 -27
- package/docs/changelog.mdx +11 -1
- package/docs/codemode.md +108 -39
- package/docs/compaction/branch-summaries.md +54 -0
- package/docs/compaction/custom-compactors.md +161 -0
- package/docs/compaction/memory-compaction.md +77 -0
- package/docs/compaction/reference.md +86 -38
- package/docs/compaction.md +51 -252
- package/docs/computer-use.md +169 -321
- package/docs/containerization.md +71 -57
- package/docs/custom-provider/api-reference.md +119 -25
- package/docs/custom-provider/oauth.md +114 -132
- package/docs/custom-provider/override.md +37 -27
- package/docs/custom-provider/registration.md +107 -83
- package/docs/custom-provider/streaming.md +85 -71
- package/docs/custom-provider.md +85 -52
- package/docs/development.md +39 -29
- package/docs/docs.json +80 -67
- package/docs/environment-variables.md +94 -44
- package/docs/extensions/api-reference.md +86 -43
- package/docs/extensions/authoring.md +162 -154
- package/docs/extensions/events.md +80 -25
- package/docs/extensions/examples.md +90 -85
- package/docs/extensions/ui.md +206 -82
- package/docs/extensions.md +79 -108
- package/docs/getting-started/authentication.md +67 -36
- package/docs/getting-started/first-session.md +53 -43
- package/docs/getting-started/installation.md +117 -90
- package/docs/getting-started/project-instructions.md +48 -34
- package/docs/guides/configuration.md +82 -20
- package/docs/guides/non-interactive.md +66 -24
- package/docs/guides/resume-on-any-machine.md +135 -82
- package/docs/guides/team-setup.md +114 -105
- package/docs/guides.md +76 -32
- package/docs/herdr.md +16 -17
- package/docs/how-atomic-works.md +140 -0
- package/docs/index.md +58 -44
- package/docs/intercom/operations.md +141 -151
- package/docs/intercom/reference.md +85 -108
- package/docs/intercom.md +84 -145
- package/docs/json.md +120 -67
- package/docs/keybindings.md +85 -49
- package/docs/libraries/agent-core.md +137 -275
- package/docs/libraries/ai.md +100 -84
- package/docs/libraries/codemode.md +210 -300
- package/docs/libraries/schema.md +59 -53
- package/docs/libraries/storage-postgres.md +49 -35
- package/docs/libraries/telemetry.md +153 -354
- package/docs/libraries/tui.md +265 -393
- package/docs/libraries.md +42 -26
- package/docs/llama-cpp.md +171 -161
- package/docs/mcp-servers.md +90 -51
- package/docs/models/choose-a-model.md +188 -0
- package/docs/models/reference.md +74 -30
- package/docs/models.md +153 -88
- package/docs/orchestration/migrating-workflows.md +23 -16
- package/docs/orchestration/patterns.md +39 -44
- package/docs/orchestration.md +65 -26
- package/docs/packages/authoring.md +51 -29
- package/docs/packages/reference.md +42 -21
- package/docs/packages.md +69 -58
- package/docs/programmatic.md +118 -24
- package/docs/prompt-templates.md +84 -83
- package/docs/providers/reference.md +43 -48
- package/docs/providers.md +219 -451
- package/docs/quickstart.md +140 -120
- package/docs/reference/cli.md +135 -97
- package/docs/reference.md +20 -19
- package/docs/rpc/examples.md +76 -20
- package/docs/rpc/extension-ui.md +64 -38
- package/docs/rpc/protocol.md +361 -110
- package/docs/rpc.md +57 -17
- package/docs/sdk/reference.md +409 -534
- package/docs/sdk/storage.md +53 -13
- package/docs/sdk/structured-decisions.md +82 -56
- package/docs/sdk/web-server.md +57 -43
- package/docs/sdk.md +106 -84
- package/docs/security.md +42 -64
- package/docs/session-format.md +62 -38
- package/docs/sessions.md +99 -214
- package/docs/settings.md +165 -195
- package/docs/shell-aliases.md +9 -6
- package/docs/skills/authoring.md +69 -48
- package/docs/skills/reference.md +51 -20
- package/docs/skills.md +99 -148
- package/docs/slash-commands.md +129 -0
- package/docs/storage/custom-adapters.md +160 -85
- package/docs/storage/jsonl.md +81 -66
- package/docs/storage/postgres/pgbouncer.md +120 -126
- package/docs/storage/postgres/tuning.md +120 -143
- package/docs/storage/postgres.md +314 -330
- package/docs/storage/sqlite.md +71 -42
- package/docs/storage.md +298 -302
- package/docs/subagents/authoring.md +55 -38
- package/docs/subagents/reference.md +73 -33
- package/docs/subagents.md +119 -187
- package/docs/terminal-setup.md +51 -39
- package/docs/themes/reference.md +23 -19
- package/docs/themes.md +142 -127
- package/docs/tmux.md +47 -55
- package/docs/tools.md +147 -109
- package/docs/tui/reference.md +166 -214
- package/docs/tui.md +196 -341
- package/docs/usage.md +118 -138
- package/docs/verification.md +79 -51
- package/docs/web-access.md +121 -101
- package/docs/windows.md +26 -27
- package/docs/worktree-snapshots/reference.md +245 -0
- package/docs/worktree-snapshots.md +71 -259
- package/package.json +8 -8
- package/dist/_shared/startup-0-2-5QHPCEON.js.map +0 -1
- package/docs/guides/intercom.md +0 -32
- package/docs/guides/orchestration.md +0 -28
- package/docs/guides/subagents.md +0 -37
- package/docs/termux.md +0 -118
|
@@ -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
|
|
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).
|
|
15
|
+
Requires Node.js 24.20+ (or Bun / Cloudflare Workers via the portable subpaths). Public entry points:
|
|
16
16
|
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
22
|
-
-
|
|
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
|
-
|
|
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` |
|
|
32
|
-
| Cloudflare Workers
|
|
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
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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`
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
|
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
|
-
|
|
112
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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,
|
|
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
|
-
##
|
|
113
|
+
## Declarations for the model
|
|
138
114
|
|
|
139
|
-
|
|
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
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
131
|
+
`execute()` never rejects for script failures. When `result.ok` is `false`, `result.error.kind` is one of:
|
|
166
132
|
|
|
167
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
144
|
+
## Using with agent-core
|
|
174
145
|
|
|
175
|
-
|
|
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
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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
|
-
|
|
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
|
-
|
|
206
|
-
|
|
207
|
-
"
|
|
208
|
-
|
|
209
|
-
|
|
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
|
-
|
|
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
|
|
218
|
-
import {
|
|
193
|
+
import { type Agent, type AgentToolCallOutcome, runToolCall } from "@bastani/atomic-agent-core";
|
|
194
|
+
import type { JsonObject } from "@bastani/atomic-ai";
|
|
219
195
|
|
|
220
|
-
|
|
221
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
- **
|
|
243
|
-
|
|
244
|
-
|
|
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
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
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
|
-
|
|
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
|
-
|
|
247
|
+
## Bundled Node and Bun hosts
|
|
261
248
|
|
|
262
|
-
|
|
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 {
|
|
252
|
+
import { CodemodeSandbox, loadQuickJSWasm } from "@bastani/atomic-codemode";
|
|
266
253
|
|
|
267
|
-
const sandbox =
|
|
268
|
-
|
|
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
|
-
|
|
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
|
-
##
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
269
|
+
### Deploying the sandbox Worker
|
|
295
270
|
|
|
296
271
|
```ts
|
|
297
|
-
|
|
298
|
-
|
|
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
|
-
|
|
319
|
-
|
|
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
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
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
|
-
|
|
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
|
-
|
|
295
|
+
### Calling it from the agent Worker
|
|
370
296
|
|
|
371
|
-
|
|
297
|
+
Bind the class using `script_name` (binding a class in the agent's own Worker would reintroduce main-thread blocking):
|
|
372
298
|
|
|
373
|
-
|
|
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
|
-
|
|
376
|
-
|
|
377
|
-
|
|
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
|
-
|
|
312
|
+
interface Env {
|
|
313
|
+
CODEMODE_SANDBOX: DurableObjectNamespace<CodemodeSandboxDurableObject>;
|
|
314
|
+
}
|
|
382
315
|
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
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
|
|
321
|
+
const result = await sandbox.execute(code, { signal, store });
|
|
396
322
|
```
|
|
397
323
|
|
|
398
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
337
|
+
### Runtime notes
|
|
428
338
|
|
|
429
|
-
- Node and Bun
|
|
430
|
-
- Stack traces use QuickJS frames (`at f (codemode.js:2:31)`), prefixed with `Name: message` like V8
|
|
431
|
-
- QuickJS is an interpreter
|
|
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.
|