AI Sandbox
Standalone NocoBase 2 plugin. It adds browser MicroPython execution to AI Employee chat and a Python/Node.js workflow node. It does not require or modify Agent Orchestrator or replace SES/RunJS.
Execution paths
flowchart LR
Chat[AI Employee chat] --> Tool[sandbox_run_python_browser]
Tool --> Frame[Opaque-origin sandbox iframe]
Frame --> Worker[Disposable Web Worker / MicroPython WASM]
Worker --> Result[JSON / logs / local downloads]
Result --> Chat
Trigger[AI Employee workflow / schedule / event] --> Node[AI Sandbox workflow node]
Node --> Broker[Authenticated external runner]
Broker --> Container[Disposable Python / Node.js container]
Container --> Job[Workflow job result]
Browser chat
Enable the plugin with AI Employee and Workflow enabled. The sandbox_run_python_browser tool is registered with execution: frontend, scope GENERAL and default ASK permission. Enable/select it for the appropriate employee using the native AI Employee tool configuration. Native chat pauses for frontend execution, invokes the client tool, sends its result back, then continues the conversation. No server Python process participates in this path.
Input fields: code, optional JSON input, optional timeoutMs (100–30000, default 10000). Code reads input, assigns JSON-compatible result, uses print() for logs, and nb.emit_file() for downloads:
from nb import emit_file
result = {"total": sum(input["values"])}
print("Calculated", result["total"])
emit_file("report.csv", "total\n" + str(result["total"]))
The tool card provides approval/rejection and Browser results. That dialog shows the last five runs, logs, output, download buttons and cancellation. One execution per tab is allowed. Each execution has a new interpreter and filesystem. Downloads stay in tab memory and are discarded by refresh, closing the tab, clearing results, or eviction after five runs. File contents are not sent to the LLM; only filenames are returned. No automatic upload or database writes occur.
This is MicroPython, not CPython: pandas, python-docx, openpyxl, reportlab and matplotlib are not available in the browser runtime. Standard MicroPython modules and nb.emit_file() are available. JavaScript document-library wrappers discussed during design are not included in this version. Use the backend workflow for the complete report stack. SES/RunJS remains the existing path for DOM/React/NocoBase UI manipulation; this tool provides isolated browser computation.
Backend workflows
- Deploy the external runner as described below; set
AI_SANDBOX_RUNNER_URL and AI_SANDBOX_RUNNER_TOKEN on NocoBase application/worker nodes.
- Create a workflow with the desired trigger. For AI chat use NocoBase's AI Employee workflow trigger (
ai-employee) so its enabled workflow becomes a native AI tool. For background work use schedule/collection triggers.
- Add AI Sandbox under extended nodes; choose Python or Node.js, bind named input arguments with the workflow variable picker, enter code, and set a bounded timeout.
- Downstream nodes consume the job's
result object: ok, result, stdout, stderr, files (name/base64), optional error. A failed script fails the workflow node. For AI-facing output select the useful result fields rather than returning base64 file contents to the LLM. Persist artifacts through an explicitly configured file/storage workflow step if needed; this plugin does not upload them automatically.
Python uses the same input, result, nb.emit_file() convention. Node.js supports require(), top-level await inside the task wrapper, input, result, and emit_file(name, stringOrBuffer):
const ExcelJS = require('exceljs');
const workbook = new ExcelJS.Workbook();
workbook.addWorksheet('Report').addRow(['total', input.total]);
emit_file('report.xlsx', await workbook.xlsx.writeBuffer());
result = { generated: true };
Python packages: pandas, python-docx, openpyxl, reportlab, matplotlib (headless Agg), and their locked dependencies. Node.js packages: docx, exceljs, pdfmake. Add dependencies by rebuilding the trusted image; tasks cannot request package installation, images, mounts or Docker flags. Guest code can write files directly to OUTPUT_DIR=/tmp/job/output if a library requires a path.
Orchestrator 1.3.0 uses the separate /v1/skill compatibility protocol to route existing Skill Hub tools through managed native workflows without renaming tools or rewriting templates. Generated installation manifests create separate Manual approval workflows. See Skill Hub migration and deployment. Browser execution never silently falls back to server execution.
The Skill Hub endpoint accepts language: "python" | "node", code, inputArgs, a bounded array of {name, base64} package files, timeoutSeconds and maxOutputSizeMb. It returns the legacy success/stdout/stderr/duration fields and output files. Its limits are 600 seconds, 2,000 files / 50 MiB each direction, and 256 MiB tmpfs; it uses the same container isolation policy as /v1/run. It supports package-relative imports and SKILL_INPUT_FILE, SKILL_DIR, OUTPUT_DIR.
The image also includes the former Skill Hub default dependencies: Jinja2, PyYAML, tabulate, XlsxWriter, python-pptx, SheetJS, pdfkit, csv-parse, archiver, sharp, lodash and dayjs. SheetJS is pinned to the official 0.20.3 distribution. The lockfile overrides archiver-utils' glob and ExcelJS' uuid with patched versions; integration tests exercise archive traversal and Office output with these versions. Dependencies are installed only while building the trusted image.
Runner deployment
The runner is an independent Node.js service, bundled under runner/; it has no npm dependencies. Its job image contains both CPython and Node.js. Build on a dedicated Linux sandbox host (preferably a rootless Docker daemon; use gVisor runsc when available and validated):
docker build -t nocobase-ai-sandbox-runtime:0.2.0 runner/runtime
# Configure a random token of at least 32 characters through your secret manager.
export SANDBOX_TOKEN='<secret-manager-value>'
export SANDBOX_IMAGE='nocobase-ai-sandbox-runtime:0.2.0'
export HOST='127.0.0.1'
export PORT='8788'
# Optional: SANDBOX_OCI_RUNTIME=runsc (must already be installed in Docker).
node runner/server.mjs
Use a process supervisor and a private TLS reverse proxy; the service binds to loopback by default. Configure the reachable private URL in AI_SANDBOX_RUNNER_URL and the matching token in AI_SANDBOX_RUNNER_TOKEN on NocoBase. Protect both the network path and token. Do not mount a Docker socket into NocoBase or a guest container. The broker's Docker access is privileged infrastructure access even when guest containers are restricted; keep the broker/daemon away from NocoBase volumes, databases and secrets. In production promote the tested image by digest and keep the base images/package lockfiles patched.
API: POST /v1/run, Bearer authentication, JSON {language:"python"|"nodejs", code, input, timeoutMs}. Timeout 100–120000 ms. GET /health is process liveness, not proof that Docker/images are usable. Two concurrent requests maximum; excess returns 429 without a hidden queue. Invalid input fails before creating a container. Missing NocoBase runner configuration fails closed.
Each execution uses a fresh container with no bind mounts or network, read-only root, UID/GID 65532, all capabilities dropped, no-new-privileges, default Docker seccomp, 512 MiB memory with no extra swap, one CPU, 64 PIDs, 256 file descriptors, 64 MiB tmpfs and bounded stdout/results/files. Docker --pull=never prevents task-time image pulls. Request cancellation and timeouts force removal. A deadline-label reaper cleans expired job containers on startup and every 15 seconds. Shutdown aborts active requests. There are no transparent retries; retry deliberately in the workflow when appropriate.
Containers share the host kernel with the default OCI runtime. These controls materially improve isolation over spawning code inside NocoBase, but are not a claim of microVM isolation. A broker/host outage can delay cleanup until recovery; run a supervised broker and monitor cleanup failures. gVisor support is configurable, not included or verified by the default Docker tests.
Browser boundary and limits
Runtime assets are bundled and version pinned: MicroPython WASM 1.29.0-6; no CDN/runtime package downloads. scripts/prepare-runtime.mjs verifies the upstream npm archive SHA-512 before extracting the two known assets. The public GET-only aiSandbox:asset action serves an exact filename allowlist, with CORS only for these nonsecret static assets.
The iframe has sandbox="allow-scripts" without allow-same-origin. Its response CSP permits scripts/WASM fetches only from the fixed asset endpoint and blocks other connections, forms and navigation capabilities. Guest code runs in a classic Blob Worker inside that opaque origin (module Blob Workers failed the opaque-origin browser test; dynamic ESM import of the runtime works). MicroPython's JavaScript FFI therefore reaches only the worker environment. No application window, DOM, cookie, storage, token, ctx or API client is passed in. The parent/frame handshake checks event.source and transfers a private MessagePort. Results and filenames are validated before use; rendered output is escaped text and file downloads use octet-stream.
Code/input/result limits are 64000/256000/64000 characters; logs are truncated to 16000 characters per stream. At most ten output files, 1 MB each and 2 MB total. Python starts with an 8 MiB GC heap; this is not a hard limit on total browser memory. A parent-side watchdog terminates the worker/frame, including CPU-bound loops; browser throttling/background suspension can delay timers. Closing or refreshing the page ends browser work. Client results are untrusted tool output, never backend authorization or trusted business validation.
Development verification
From the repository root (server tests sequential):
yarn test packages/plugins/plugin-ai-sandbox/src/shared/__tests__/protocol.test.ts --run
yarn test packages/plugins/plugin-ai-sandbox/src/server/__tests__/tool.test.ts --run
yarn test packages/plugins/plugin-ai-sandbox/src/server/__tests__/runner-client.test.ts --run
yarn test packages/plugins/plugin-ai-sandbox/src/server/__tests__/instruction.test.ts --run
yarn test packages/plugins/plugin-ai-sandbox/src/server/__tests__/assets.test.ts --run
node --test packages/plugins/plugin-ai-sandbox/runner/__tests__/runner.test.mjs
$env:PLAYWRIGHT_CHANNEL='chrome' # Or msedge; omit when Playwright Chromium is installed.
yarn playwright test --config packages/plugins/plugin-ai-sandbox/playwright.config.ts
node --max-old-space-size=10000 packages/plugins/plugin-ai-sandbox/scripts/typecheck.mjs
docker build -t nocobase-ai-sandbox-runtime:0.2.0 packages/plugins/plugin-ai-sandbox/runner/runtime
$env:SANDBOX_TEST_IMAGE='nocobase-ai-sandbox-runtime:0.2.0'
node --test packages/plugins/plugin-ai-sandbox/runner/__tests__/container.integration.test.mjs
yarn nocobase build plugin-ai-sandbox --no-dts
Type checking is scoped to plugin files against actual workspace source contracts. Browser tests use a local static fixture with the production CSP and runtime. Container tests run disposable containers, not the NocoBase deployment. These tests do not establish live NocoBase chat resumption, workflow UI persistence, reverse-proxy headers or compatibility across all browser versions; validate those on the target stack before rollout.