跳到內容

Sandbox 套件

pi-roundtable-sandbox 能把指定的 guild 頻道設成 guest-only。 每則提及 bot 或回覆 bot 的訊息,都會在新的 Docker container 裡執行工具型 agent;頻道記憶和近期對話會保存在該頻道專用的 workspace。 沒有對 bot 發話的訊息會直接丟棄,不會交給 host agent。

終端機視窗
bun add pi-roundtable-sandbox pi-roundtable

需要 Bun 1.4.4 以上、>=0.50.0 <0.51.0 的 pi-roundtable、原生 Linux host,以及本機 Docker daemon。 服務帳號必須能使用 Docker,guest 不可用 root 執行。 macOS 可用於開發、測試和建置 image;實際執行 sandbox 需要 Linux,因為 Docker Desktop 不會把 host Unix socket 分享進 Linux VM。 還要有可信任的 OpenAI-compatible Chat Completions endpoint,支援 non-streaming、function tools 和 max_tokens。

啟動 host 前,從安裝好的套件建置 worker image:

終端機視窗
docker build -f node_modules/pi-roundtable-sandbox/worker/Dockerfile -t pi-roundtable-sandbox:local node_modules/pi-roundtable-sandbox
import { sandbox } from "pi-roundtable-sandbox";
export default {
// ...其他 roundtable 設定...
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",
})],
};

這些目錄必須由服務帳號擁有,供此套件專用,並使用私人權限。 stateFile 必須是絕對路徑,且不能放在兩個 mount root 之內。 runRoot 路徑要夠短,才能容納 Unix socket。 同一組目錄只能由一個 host process 使用。

必要的 runtime 選項包括 image、runRoot、workspaceRoot、model 和 modelUrl;plugin 也要求 stateFile。 provider 預設為 openai,只有沒有設定 apiKey 時,host 才用它查找模型登入資料。 apiKey 可提供 credential getter;否則 host 會在每次 request 讀取登入資料。 initialChannels 只會用來初始化新的 routing state file。 選擇性設定 prompt 來指定 guest system prompt;時區使用 host 的 env.timeZone。 選填的 uid 和 gid 必須與非 root host 帳號相同。 設定 tools 和 mcp 可明確授權 host callback 與特定 MCP tool。 資源和期限可用 limits(memoryMb、cpus、pids)和 turnTimeoutMs(1 到 600 秒)設定。 不要授權通用 shell、任意路徑或任意 URL。 Schema 是給模型看的提示,host 不會用它驗證輸入。

重啟後,owner 可在 guild 頻道執行 /roundtable sandbox on、status 或 off。 關閉模式會保留 workspace 記憶;等排隊工作結束後,訊息會恢復一般 routing。

這些選項都是選填;全都不設時,行為與 0.23.x 相同。 標示 protocol 2 的選項需要用此版本重新建置 worker image;image 太舊時,啟動會停下並提示重建(image 帶有標籤 pi-roundtable-sandbox.protocol)。 「bytes」依 worker 的算法計算,即 Buffer.byteLength(JSON.stringify(text)):一個繁體中文字是 3 bytes。

選項 能力
guilds Discord guild id;該 guild 的每個頻道和討論串(含之後新建的)都是 sandbox 頻道,不必執行 /roundtable sandbox on。私訊和其他 guild 不受影響,該 guild 內 /roundtable sandbox off 會被拒絕。
workspace: "server" Protocol 2。同一個 guild 的頻道共用一個 workspace(記憶筆記和檔案);每個頻道的對話歷史放在自己的 state 目錄,掛載到 /channel。共用 workspace 的 turn 一次跑一個,最多 maxWaiting(預設 4)個排隊等候,超過的直接以 busy 拒絕。預設 "channel":每個頻道各自一個 workspace。
files Protocol 2。在 workspace 的 files/ 內提供 files_list、files_read、files_write、files_delete;true 表示每檔 256 KiB、全部 32 MiB。路徑任一段是 symlink 都會被拒絕。
skills Protocol 2。放 skill 資料夾的目錄;system prompt 結尾附 skill 索引,host_read_skill 由 host 分頁讀取 skill 檔案。
budgets Protocol 2。promptBytes(8,192,上限 32,768;prompt 加 skill 索引,超過會讓啟動停下)、toolResultBytes(4,096,上限 32,768)、requestBytes(196,608,上限 196,608)。若 requestBytes 容不下 prompt 預算加 8,192 bytes 的記憶筆記、49,152 bytes 的當前訊息與 8 KiB 的 tool 結果空間,啟動會停下;裁剪不會丟掉最新一組 tool call,放不下時改把該組的每個結果裁成均分的份額。host tool 會收到 context.resultBytes。
maxCalls、maxOutputTokens 每個 turn 的 broker 呼叫數(48)與每次模型呼叫的輸出 token(4,096;推理模型的思考也算)。
replyText host 端函式 (text, { channel, space }),在每則成功的回覆送出前改寫,例如把模型漏出的簡體字轉成繁體。失敗訊息不經過它,worker 保留的對話歷史仍是模型原文;它丟出錯誤時該 turn 算失敗。不必重建 image。
replyCard host 端函式 (text, { channel, space }),回傳 PNG(Uint8Array)、undefined,或其中之一的 promise;在 replyText 之後、對實際送出的文字執行,surface 會先送卡片再送文字(Discord 會)。丟出錯誤或 reject 時只記 log,回覆照常送出、不附卡片。失敗訊息不產生卡片。不必重建 image。
peerBots 預設關閉。true 時,host 在 discord.peerBots 列出的 bot 若提及此 bot 或回覆它,會像一般使用者一樣被回應,並受 host 的輪數上限限制;其他 bot 仍被忽略。由 host 的名單決定是誰,對方的文字和訪客的一樣不可信。
channelContext 預設關閉。true 或 Discord plugin 的 ChannelContextOptions。Discord 伺服器頻道中的 turn 會另外帶上騎士上次發言之後別人在該頻道說的話(沿用 core 預設:最新 15 則、每則 500 字、其他 bot 80 字;host 的 discord.channelContext 設定會併進來,此選項優先,host 設 channelContext: false 則整個關閉),透過 DISCORD.channelContext 只讀被提問那則訊息所在的頻道;私訊與其他 surface 不讀。內容附在被提問的訊息之後,標明是不可信的公開文字、不是指示,放不下時從最舊的開始裁。永遠不讀圖片,即使 attachments 要求也一樣。讀取失敗只記 log,turn 照常執行。需要 Discord plugin;只在 host 端,不必重建 image。

modelUrl 在 127.0.0.1、::1 或 localhost 上可以用 http://,因為 broker 就跑在 host 上。 host tool 對模型的名稱是 host_<name>,所以 skill 提到工具時要寫 host_roll_dice。 使用 workspace: "server" 時,同一個 guild 的頻道共用檔案和筆記,請當作該 guild 的所有 guest 都看得到;檔案工具的上限只約束工具本身,所以仍要在 workspaceRoot 設檔案系統 quota。 從 "channel" 改成 "server" 不會搬移任何資料:舊的各頻道 workspace 原封不動留在磁碟上。

要匯入舊對話的 host,可以直接用 guildWorkspaceDir、channelStateDir、historyFilePath、workspaceFilesDir、encodeHistory 和 userHistoryContent,不必自己推導磁碟配置;README 有完整清單。

sandbox() 的 sealed、純文字預設不變。 需要完整 Pi JSONL session、subscription 登入、媒體、persona、skills 或 host 狀態時,在自己的 channel claim/store 中明確使用 PiSandboxRuntime。 worker dependency image 須安裝相容的 Pi SDK、Typebox、pi-claude-bridge(含 bundled Claude Agent SDK runtime);MCP profile 另須 pi-mcp-adapter。 host setup 不會載入 bridge。 Anthropic broker 支援串流 messages、token counting、custom tools 和 host 選定的 thinking,不代理任意 provider endpoint。

Host 選項 能力與邊界
partyDir、image、profiles 私人 state root、可信任 image,以及 profile 對應的固定 Anthropic model/MCP 清單。
oauthToken() 每次 request 取得可更新的 host credential;container 只有 dummy。
memory.promptBlock(channel,id,name) 目前發話者的 host context;PostgreSQL person/notes/moments、schema 和 migration ledger 留在 adapter。
effort.judge(text,{level}) host 選 low/medium/high/xhigh,並取得頻道上次的判斷。
tools.names、tools.call 明確的能力清單;callback 收到固定 channel/profile/speaker/signal,須自行驗證輸入。
mcp.servers、mcp.token() 固定 endpoint、tool name 清單和 host credential getter。
upstream、fetchImpl、allowHttpMcp 可信任 endpoint/測試 transport,以及可信任內網的 HTTP 例外;不可來自 guest。
timeZone、containerPrefix、labelChannel、labelProfile worker 時區(預設 UTC)和既有 container 名稱/label 的相容設定。
driver、logger 可信任本機 Docker/離線 adapter 和 host logger。
startTimeoutMs、turnTimeoutMs 1–600 秒,預設 90/600 秒。
compaction 選用的 host compactor:engine、compact(request, { channel, signal })、timeoutMs(預設取 120 秒與回合三分之一的較小者,最多半個回合;每次 compaction 也最多只用回合剩餘時間的一半)和 maxRequestBytes(預設 32 MiB)。
maxCalls、maxOutputTokens 預設 128 次 credential-bearing call/128,000 output tokens;可設 1–1,000 次/1,025–200,000 tokens。

runTurn({channel,profile,turnId,author,text,images,signal?}) 回傳文字和已驗證的檔案 bytes。 start、stop、status、startFresh、sessionsDir、attachmentDir、stopBrokers 供可信任 lifecycle adapter 使用。 記憶、image quota、schedules 和 presentation 可透過有範圍的 host callback 提供;schedule 必須使用明確的 channel-local target 和 host 綁定的發話者。 guest body 不能改掉 channel/speaker/credential,也不會得到 owner shell、記憶、agent dispatcher、registry 或 auth file。

可信任的 /app/worker/content.ts 匯出 workerContent(profile): PiWorkerContent。 欄位為 model:{provider,id},以及選填的 prompt、skillsDir、brokerTools、toolNames、extensions(turn)。 Pi model 必須與 host profile 固定的 Anthropic model 一致。 skillsDir 提供索引、read_skill 和先讀 skill 才能使用的 tool gate;每檔上限 256 KiB,回傳上限 40,000 字元,拒絕 symlink 越界。 built-in shell/read/write/edit 和自動 extension/skill/context discovery 維持關閉。 dice/TRPG 等 app 工具放在明確的 extension seam。 contributionExtension 包裝 public core tool contributions,透過 withReplyFiles/ToolTurn.attachFile 收集檔案;drawing 請用官方 contributions,不要保留 renderer 副本。 先用套件的 worker/Dockerfile.deps.pi 和已安裝的 node_modules 建 dependency image,再以 DEPS_IMAGE 和可信任 release content(assets、persona、shared、worker)建 worker/Dockerfile.pi。 入口是安裝好的 worker/pi-main.ts,不是 app 複製的 runtime。

保留 partyDir/channelSegment(channel)/workspace/sessions、/workspace cwd 和 SessionManager.continueRecent 的既有 JSONL。 startFresh 在 container 移除後才封存頂層一般 session 檔(guest 放的 symlink 一律取代、不跟隨),但不刪 DB 記憶;套件不遷移 table、ledger、profile 或 workspace。 workspace 旁新增 host-only .channel-key,讓所有 lifecycle/session/attachment 操作都拒絕既有 path/container name 的頻道鍵碰撞;備份時一併保留。 完整 broker socket 路徑不可超過 100 字元。 admission/routing、channel profile、table schema、MCP grant、image quota 和內容仍由 app adapter 負責。 同頻道 guest 共用 workspace/history;speaker 範圍不是對同頻道受入侵程式的保密保證。

collectPiAttachments 最多下載十個附件,每檔 25 MiB、合計 50 MiB;透過可信任 prepareImage(如 core prepareImageBytes)從 bytes 準備最多四張圖片。 下載走 controlled fetch,寫入使用 exclusive、no-follow directory descriptor,不追隨 guest symlink。 fetchImpl 僅供可信任 fixture 使用;選填的 describeFailure(error) 可提供 app 的失敗說明,但不要曝露原始 host exception。 native image decoder 仍是 host 的信任/資源邊界;壓縮圖片的解碼尺寸可能需要額外隔離。 rich turn 接受最多八張 PNG/JPEG/WebP/GIF,每張 20 MiB、decoded 合計 64 MiB。 目前訊息、memory context、最終文字各限 100,000 字元;speaker ID/name 各限 256 字元。 回覆遵循 core 限制:十檔、每檔 10 MiB、合計 50 MiB。 持久附件/session 沒有自動 retention 或磁碟 quota,部署時須補 filesystem quota。

Pi container 維持 network none、read-only root、無 capabilities、no-new-privileges;資源為 1.5 GiB RAM/不額外使用 swap、一 CPU、256 PIDs、512 MiB /tmp;log 寫進 journald,tag 為 sandbox/<channel>,container 移除後仍在(PiDockerContainerDriver 的 log 選項可改用其他 Docker log driver)。 Worker session 依 core 的分層門檻壓縮:有設 host compactor 時,300,000 tokens 由它壓縮;超過 500,000 改用 Pi 自己的摘要,模型呼叫照樣經過 broker。compactor 失敗、逾時或 request 過大時都退回 Pi 的摘要,host 會依頻道記下每次壓縮與退回原因。 回合失敗時保留原因;upstream 失敗會記下 status、延遲和錯誤內容;回合逾時、移除 container 前,會先記下 worker 最後 200 行 log。 只 mount 可寫的頻道 workspace 和唯讀的 host broker directory。 worker 主動呼叫 /worker/ready、/worker/next、/worker/result 傳遞 turn 和 base64 reply bytes;host 不連 guest 建立的 socket,也不重新開啟 guest reply path。 取消會移除精確對應的 container;host 重啟後 worker 重新宣告 ready。 broker 每頻道只容許一個 pending long poll/turn/reply packet,inactive 或重複 packet 在讀 body 前就拒絕;最多 16 connections;header deadline 十秒、串流回應只限制靜默 120 秒而非總時間(turn deadline 為每個呼叫的硬上限)、四個 credential-bearing in-flight calls、request 96 MiB、upstream response 50 MiB、encoded worker reply 72 MiB。 listener 會暫存有上限的回覆;這些上限不取代 host 容量和費用控管。

只有 Anthropic messages/count_tokens(可帶 ?beta=true)、明確 host tools 和允許的 MCP method/tool 能使用 credential。 model payload 重建為 text/base64-image/custom-tool;拒絕 native server tool、remote media/schema、其他 account route 和 upstream redirect。 MCP 支援 initialize、initialized notification、ping、list 和 allow-listed call;不支援 batch/resources/prompts/sampling。 第一個 turn 前有 90 秒/32 次 metadata-only scope,供 eager MCP handshake;第一次 host bind 後就撤銷。 headers 重新建立,bounded response stream 會拒絕跨 chunk 的明顯 credential reflection;仍須信任上游不刻意編碼外洩 secret。

Controlled fetch 與 channel-local delegation

Section titled “Controlled fetch 與 channel-local delegation”

safeFetch(url,{signal?,timeoutMs?,maxBytes?,maxRedirects?}) 只接受不含 credential 的 HTTP(S)。 每個 redirect 都重新解析所有地址,拒絕 private/loopback/link-local/metadata/reserved/transition 範圍,包括 encoded IPv4 和 mapped IPv6;實際 socket 綁到已驗證的地址。 HTTPS 仍驗證原 hostname,不用 proxy environment,也不再次 DNS lookup。 連線失敗只能改試同一批已驗證地址;每個 TCP/TLS 連線期限三秒,仍受整體 request deadline 限制。 預設 60 秒、五次 redirect、wire 和 decoded body 各 5 MiB;gzip/deflate/Brotli 解壓縮也有上限。 可設定 1 毫秒–120 秒、0–10 次 redirect、1 byte–32 MiB。 resolve/transport 只供可信任測試使用。 直接解析 SafeFetchResult bytes;或先用 assertPublicUrl 檢查 URL,再交給其他 extractor,並把該 extractor 自己的頁面下載送回 safeFetch(followRedirects:false 一次只走一跳、每跳都檢查並釘住位址;headers 設定 host 信任的標頭)。

ScopedSandboxDelegator 固定 target、host author 和 channel-local report,不接受任意 target/origin/tier。 選項是 target、maxRunning(1–10,預設每頻道二個)、timeoutMs(1–1,200 秒,預設十分鐘)、maxTitleChars(預設 200)、maxReportChars(預設 80,000)、diagnosticChars(預設 600)、run(task,context)、deliver(job,result)、logger。 task 最多 4,000 字元;title、report 和 diagnostic text 的長度限制可設定,各為至少 1 的整數或 Infinity。 runningChannels、idle、dispose 支援 lifecycle,dispose 取消 process-local jobs。 選用 SandboxResearchWorker 時,明確提供 modelRuntime、agentDir、workDir、model、thinking、search、extractFetched(或由 host 自備的 fetchContent(url, signal),此時位址檢查與上限由 host 負責)。 它用未儲存的 host subscription session,只提供 web search 和 controlled fetch,沒有 shell/owner data/discovery;extractor 收到已下載 bytes,不可再次 fetch。 明確保留 app 的 model/thinking 和 report adapter,不轉交沒有同等範圍限制的 owner/default worker。 所有 opt-in hook 都要審查,並設定 provider spend、ingress、filesystem 和 host 容量限制。

把 prompt、模型輸出和 container 內的程式碼都視為不可信任。 Docker 提供 process isolation,不等同 VM 隔離。 container 沒有網路、host credential、Docker socket 或 host 環境變數;只有 broker 能連到設定好的 model 和明確授權的工具。 惡意 guest 仍能消耗允許使用的 model 額度,並使用已授予的所有能力。 host、Docker daemon、Linux kernel、image、callback 和上游服務都在信任範圍內。 風險較高時,使用已修補的專用機器,並為 provider 設定費用上限、入口流量限制、檔案系統 quota 和 host 資源控管。

完整隔離措施、持久化限制、部署條件和 Docker integration test 見pi-roundtable-sandbox README(英文)。