Sandbox package
pi-roundtable-sandbox makes selected guild channels guest-only.
Each message that mentions or replies to the bot runs a tool-using agent in a new Docker container; channel memory and recent conversation text persist in that channel’s workspace.
Messages not directed to the bot are dropped rather than routed to a host agent.
Install and requirements
Section titled “Install and requirements”bun add pi-roundtable-sandbox pi-roundtableUse Bun 1.4.4 or newer, pi-roundtable >=0.50.0 <0.51.0, a native Linux host, and a local Docker daemon.
The service account must be allowed to use Docker and must not run the guest as root.
macOS supports development and image builds, but not sandbox execution because Docker Desktop does not share host Unix sockets into its Linux VM.
You also need a trusted OpenAI-compatible, non-streaming Chat Completions endpoint with function tools and max_tokens.
Build the worker image from the installed package before starting the host:
docker build -f node_modules/pi-roundtable-sandbox/worker/Dockerfile -t pi-roundtable-sandbox:local node_modules/pi-roundtable-sandboximport { sandbox } from "pi-roundtable-sandbox";
export default { // ...your roundtable settings... plugins: [sandbox({ image: "pi-roundtable-sandbox:local", runRoot: "/tmp/roundtable-sandbox-run", workspaceRoot: "/srv/roundtable-sandbox/workspaces", stateFile: "/srv/roundtable-sandbox/state/channels.json", provider: "openai", model: "operator-selected-model", modelUrl: "https://api.openai.com/v1/chat/completions", })],};The directories must be dedicated to this package, owned by the service account, and have private permissions.
stateFile must be absolute and outside both mounted roots.
Keep runRoot short enough for Unix socket paths.
Only one host process may own these directories.
Configuration and tools
Section titled “Configuration and tools”Required runtime options include image, runRoot, workspaceRoot, model, and modelUrl; stateFile is also required by the plugin.
provider defaults to openai and is used to look up the host’s model login when apiKey is not supplied.
apiKey may provide a credential getter; otherwise the host reads the provider login on each request.
initialChannels seeds only a new routing-state file.
Optional prompt sets the guest system prompt; the time zone comes from the host’s env.timeZone.
Optional uid and gid must match the non-root host account.
Optional tools and mcp explicitly grant host callbacks and selected MCP tools.
Resource and deadline controls include limits (memoryMb, cpus, pids) and turnTimeoutMs (1–600 seconds).
Do not grant generic shell, arbitrary paths, or arbitrary URLs.
Callback schemas guide the model but do not validate inputs on the host.
After restart, the owner can run /roundtable sandbox on, /roundtable sandbox status, or /roundtable sandbox off in a guild channel.
Turning the mode off retains workspace memory and restores normal routing after queued work completes.
Serving a whole server
Section titled “Serving a whole server”These options are all optional; with none set, behavior is that of 0.23.x.
Those marked protocol 2 need a worker image built from this release, and startup stops with a rebuild message on an older one (the image carries the label pi-roundtable-sandbox.protocol).
“Bytes” are measured as the worker does, Buffer.byteLength(JSON.stringify(text)): a Traditional Chinese character is 3 bytes.
| Option | Capability |
|---|---|
guilds |
Discord guild ids whose every channel and thread (including ones created later) is a sandbox channel, with no /roundtable sandbox on. Direct messages and other guilds are unaffected. /roundtable sandbox off is refused there. |
workspace: "server" |
Protocol 2. The channels of one guild share one workspace (memory notes and files); each channel keeps its own history in a state directory mounted at /channel. Turns sharing a workspace run one at a time, with at most maxWaiting (default 4) waiting; the rest are refused as busy. Default "channel": one workspace per channel. |
files |
Protocol 2. files_list, files_read, files_write and files_delete inside files/ of the workspace; true is 256 KiB per file and 32 MiB in all. A symlink at any path segment is refused. |
skills |
Protocol 2. Directories of skill folders; the prompt ends with a skill index and host_read_skill pages a skill’s files from the host. |
budgets |
Protocol 2. promptBytes (8,192, at most 32,768; prompt plus skill index, over it stops startup), toolResultBytes (4,096, at most 32,768) and requestBytes (196,608, at most 196,608). Startup stops when requestBytes cannot hold the prompt budget plus 8,192 bytes of memory notes, 49,152 bytes for the current message and 8 KiB of tool-result room; the trim never drops the newest tool-call group, it cuts that group’s results to a share instead. Host tools receive context.resultBytes. |
maxCalls, maxOutputTokens |
Broker calls per turn (48) and output tokens per model call (4,096; a thinking model’s thinking counts). |
replyText |
A host function (text, { channel, space }) that rewrites each successful reply before it is posted, such as converting stray Simplified Chinese to Traditional. Failure texts skip it, the worker’s history keeps the model’s words, and a throw fails the turn. No image rebuild. |
replyCard |
A host function (text, { channel, space }) that returns a PNG (Uint8Array), undefined, or a promise of either, run after replyText on the text that is posted; the surface posts the card before the text (Discord does). A throw or rejection is logged and the reply is posted without a card. Failure texts get no card. No image rebuild. |
peerBots |
Off by default. true answers the bots the host lists under discord.peerBots when they mention the bot or reply to it, as it answers a person, within the host’s round cap; any other bot is still ignored. The host’s list decides who, and a peer’s text is as untrusted as a guest’s. |
channelContext |
Off by default. true or the Discord plugin’s ChannelContextOptions. A turn in a Discord server channel also carries what others said in that channel since the assistant last posted (core’s defaults: the newest 15, 500 characters each, other bots 80; the host’s discord.channelContext settings merge in under this option, and a host channelContext: false turns it off), read through DISCORD.channelContext for the addressed message’s own channel only; direct messages and other surfaces get none. It is appended after the addressed message, framed as untrusted public text and not instructions, and is cut oldest first to fit the turn. Images are never read, even when attachments asks. A failed read is logged and the turn runs without it. Needs the Discord plugin; host-only, no image rebuild. |
modelUrl may use http:// on 127.0.0.1, ::1 or localhost, because the broker runs on the host.
Host tools reach the model as host_<name>, so a skill that names a tool writes host_roll_dice.
With workspace: "server" the guild’s channels share files and notes, so treat them as visible to every guest in the guild; the file tools’ caps bound the tools only, so keep a filesystem quota on workspaceRoot.
Switching from "channel" to "server" migrates nothing: the old per-channel workspaces stay on disk.
A host that imports old chats can call guildWorkspaceDir, channelStateDir, historyFilePath, workspaceFilesDir, encodeHistory and userHistoryContent instead of re-deriving the on-disk layout; the README lists them.
Explicit Pi/subscription mode
Section titled “Explicit Pi/subscription mode”The default sandbox() stays sealed and text-only.
Opt into PiSandboxRuntime behind your own channel claim/store when you need full Pi JSONL sessions, subscription auth, media, personas, skills or host-scoped state.
The worker loads compatible Pi SDK, Typebox, pi-claude-bridge (with its bundled Claude Agent SDK runtime), and optional pi-mcp-adapter for MCP profiles from the operator’s dependency image; the bridge is not loaded by host setup.
Its Anthropic broker supports streamed messages, token counting, custom tools and host-selected thinking, not arbitrary provider endpoints.
| Host option | Capability and boundary |
|---|---|
partyDir, image, profiles |
Private state root, trusted image and fixed profile-to-Anthropic-model/MCP allow-lists. |
oauthToken() |
Refreshable host-only subscription credential; only a dummy enters the container. |
memory.promptBlock(channel,id,name) |
Host-bound current-speaker context; existing PostgreSQL person/notes/moments schemas and migration receipts stay in adapters. |
effort.judge(text,{level}) |
Host-selected low/medium/high/xhigh, with previous channel judgment. |
tools.names, tools.call |
Explicit capabilities receiving fixed channel/profile/speaker/signal; input schemas are not host validators. |
mcp.servers, mcp.token() |
Fixed endpoints, explicit tool names and host-only credential getter. |
upstream, fetchImpl, allowHttpMcp |
Trusted endpoint/test override and explicit trusted-network HTTP exception; never guest options. |
timeZone, containerPrefix, labelChannel, labelProfile |
Operator time zone (UTC default) and existing-container compatibility names. |
driver, logger |
Trusted local Docker/offline adapter and host logger. |
startTimeoutMs, turnTimeoutMs |
1–600 seconds, default 90/600. |
compaction |
Optional host compactor: engine, compact(request, { channel, signal }), timeoutMs (default the smaller of 120 seconds and a third of the turn, at most half; each compaction also gets at most half the time the turn has left) and maxRequestBytes (default 32 MiB). |
maxCalls, maxOutputTokens |
Default 128 calls/128,000 output tokens; configurable 1–1,000 calls and 1,025–200,000 tokens. |
runTurn({channel,profile,turnId,author,text,images,signal?}) returns text and bounded byte-backed files.
start, stop, status, startFresh, sessionsDir, attachmentDir and stopBrokers support trusted lifecycle adapters.
Optional memory, image quotas, schedules and presentation stay scoped host callbacks; schedules must use a declared channel-local target and host-bound author.
No owner shell, memory, agent dispatcher, registry or auth file is granted.
Worker content and continuity
Section titled “Worker content and continuity”The trusted /app/worker/content.ts exports workerContent(profile): PiWorkerContent.
Its fields are model:{provider,id}, optional prompt, skillsDir, brokerTools, toolNames and extensions(turn).
Align the Pi model with the host’s fixed Anthropic model.
skillsDir provides skill indexing, read_skill and per-skill tool gates, with 256 KiB file and 40,000-character result limits; symlink escapes are refused.
Built-in shell/read/write/edit tools and automatic extension/skill/context discovery stay disabled.
Keep operator dice/TRPG extensions in this explicit seam.
contributionExtension wraps public core tool contributions, using withReplyFiles and ToolTurn.attachFile; wrap official drawing tools instead of keeping renderers.
Build dependencies with the package’s worker/Dockerfile.deps.pi and installed node_modules context, then build worker/Dockerfile.pi with DEPS_IMAGE and the trusted application release content (assets, persona, shared, worker).
The entry is the installed worker/pi-main.ts, not an app runtime copy.
Sessions retain partyDir/channelSegment(channel)/workspace/sessions, /workspace cwd and SessionManager.continueRecent JSONL compatibility.
startFresh archives plain top-level session files after the container is removed (guest-planted symlinks are replaced, never followed) and keeps database memory; no table, ledger, profile or workspace migration is performed.
A host-only .channel-key record beside the workspace prevents legacy path/container-name collisions on every lifecycle/session/attachment operation; back it up too.
Keep the complete broker socket path within 100 characters.
The app owns admission/routing, channel profiles, table schemas, MCP grants, image quota and content.
All guests in a channel share its workspace/history; speaker scoping is not secrecy against compromised code in the same channel.
Media, resources and transport
Section titled “Media, resources and transport”collectPiAttachments allows ten attachments, 25 MiB each and 50 MiB total, and prepares up to four images from bytes through a trusted prepareImage hook such as core prepareImageBytes.
Downloads use controlled fetch and exclusive no-follow directory-descriptor writes, not guest symlink paths.
Its fetchImpl is a trusted fixture seam only; optional describeFailure(error) provides application-owned failure wording without exposing raw host exceptions.
Native image decoding remains a host trust/resource boundary; compressed image dimensions may need further decoder isolation.
Rich turns allow eight PNG/JPEG/WebP/GIF images, 20 MiB each and 64 MiB decoded total.
Current text, memory context and final text each allow 100,000 characters; speaker ID/name each allows 256.
Core reply-file limits apply: ten files, 10 MiB each and 50 MiB total.
Persisted files/sessions have no automatic retention or disk quota; provision filesystem quotas.
Pi containers have network none, read-only root, no capabilities, no-new-privileges, 1.5 GiB RAM/no extra swap, one CPU, 256 PIDs, 512 MiB /tmp, and journald logs tagged sandbox/<channel> that outlive the container (another Docker log driver through PiDockerContainerDriver’s log option).
Worker sessions compact with the core’s tiers: at 300,000 tokens through the host compactor when one is set, past 500,000 through Pi’s own summary over the broker; any compactor failure, timeout or oversized request falls back to Pi’s summary, and the host logs each compaction and fallback per channel.
A failed turn keeps its cause, upstream failures are logged with status, latency and the error body, and a timed-out worker’s last 200 log lines are logged before its container is removed.
Only the writable channel workspace and read-only host broker directory are mounted.
Worker-initiated /worker/ready, /worker/next and /worker/result carry turns and base64 reply bytes; the host never connects to guest-created sockets or reopens guest reply paths.
Cancellation removes the exact container, and workers re-announce readiness after host restart.
The broker permits one pending long poll/turn/reply packet per channel (inactive/duplicate packets are refused before body reading), 16 connections, a ten-second header deadline, streamed responses limited by 120 seconds of silence rather than total time (the turn deadline bounds every call), four credential-bearing in-flight calls, 96 MiB input, 50 MiB upstream output and 72 MiB encoded worker replies.
It buffers bounded replies; these limits are not host capacity or spend quotas.
Only Anthropic messages/count_tokens (optional ?beta=true), explicit host tools and declared MCP methods/tools may use credentials.
Model payloads are reconstructed as text/base64-image/custom-tool traffic; native server tools, remote media/schemas, unrelated account routes and redirects are refused.
MCP supports initialize, initialized notification, ping, list and allow-listed calls, not batches/resources/prompts/sampling.
A 90-second/32-call pre-turn scope permits only eager MCP metadata handshake; the first host bind revokes it.
Rebuilt headers and bounded response streams reject obvious credential reflections across chunks; upstream services still must be trusted not to encode secrets deliberately.
Controlled fetch and channel-local delegation
Section titled “Controlled fetch and channel-local delegation”safeFetch(url,{signal?,timeoutMs?,maxBytes?,maxRedirects?}) accepts credential-free HTTP(S), resolves all addresses at every redirect, rejects private/loopback/link-local/metadata/reserved/transition ranges (including encoded IPv4 and mapped IPv6), and pins the actual socket to a vetted address.
HTTPS validates the original hostname; no proxy environment or second DNS lookup is used.
Failed connections fall back only among those vetted addresses, with a three-second TCP/TLS connect deadline per address inside the whole-request deadline.
Defaults are 60 seconds/five redirects/5 MiB wire and decoded body; gzip/deflate/Brotli decoding is bounded too.
Configuration ranges are 1 millisecond–120 seconds, 0–10 redirects and 1 byte–32 MiB.
resolve/transport are trusted test seams only.
Parse SafeFetchResult bytes directly, or check the URL with assertPublicUrl before passing it to another network extractor and send that extractor’s own page fetches back through safeFetch (followRedirects:false gives one vetted, pinned hop at a time; headers sets trusted host headers).
ScopedSandboxDelegator fixes the target, host author and channel-local report, refusing arbitrary target/origin/tier selection.
Options are target, maxRunning (1–10, default two per channel), timeoutMs (1–1,200 seconds, default ten minutes), maxTitleChars (default 200), maxReportChars (default 80,000), diagnosticChars (default 600), run(task,context), deliver(job,result) and logger.
Tasks allow 4,000 characters; title, report and diagnostic-text bounds are configurable whole numbers of at least 1, or Infinity.
runningChannels, idle and dispose support shutdown, cancelling process-local jobs.
Optional SandboxResearchWorker takes modelRuntime, agentDir, workDir, model, thinking, search and extractFetched (or a host-owned fetchContent(url, signal), which then owns address checks and bounds).
It uses a fresh unsaved host subscription session with only web search and controlled fetch, no shell/owner data/discovery; extraction receives fetched bytes and must not fetch again.
Preserve app model/thinking and report adapters explicitly instead of forwarding to an unrestricted owner/default worker.
Review every opt-in hook and enforce provider spend, ingress, filesystem and host capacity limits.
Threat model
Section titled “Threat model”Treat prompts, model output, and container code as untrusted. Docker provides process isolation, not a VM boundary. The container has no network, host credentials, Docker socket, or host environment; only the broker can reach the configured model and explicitly allowed tools. A malicious guest can still spend through the allowed model endpoint and use every granted capability. The host, Docker daemon, Linux kernel, image, callbacks, and upstream services remain trusted. Use a patched, dedicated machine for higher-risk workloads, and apply provider spend limits, ingress limits, filesystem quotas, and host capacity controls.
See the pi-roundtable-sandbox README for every isolation control, persistence limit, deployment constraint, and Docker integration test.