Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(sandbox): Docker 后端支持会话级长驻容器与远程守护进程
wizardchen9c5c52f0a4e2
diff --git a/docker/Dockerfile.sandbox b/docker/Dockerfile.sandboxindex a64b8837f..edc37d401 100644--- a/docker/Dockerfile.sandbox+++ b/docker/Dockerfile.sandbox@@ -23,9 +23,13 @@ COPY --from=node-base /usr/local/lib/node_modules /usr/local/lib/node_modulesRUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm && \ln -s /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx-# Install minimal CLI tools (bash/grep/sed/coreutils already in slim image)+# Install minimal CLI tools (bash/grep/sed/coreutils/findutils already in slim+# image). curl is not optional: the sandbox connectivity check probes egress+# with it, and skills that fetch a URL expect it to be there.RUN apt-get update && apt-get install -y --no-install-recommends \jq \+ curl \+ ca-certificates \&& rm -rf /var/lib/apt/lists/* /var/cache/apt/*# Note: Current preloaded skills only use Python stdlib@@ -39,6 +43,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \RUN groupadd -g 1000 user && \useradd -u 1000 -g user -m -s /bin/bash user+# Pre-create the two directories every backend writes to and hand them to the+# sandbox account. WeKnora otherwise has to create and chown them as root on+# each execution, which needs capabilities a hardened container should not+# have to keep.+RUN mkdir -p /workspace/input /workspace/output && \+ chown -R user:user /workspace+WORKDIR /workspaceUSER userdiff --git a/docs/agent-skills.md b/docs/agent-skills.mdindex 4348056c7..de9717264 100644--- a/docs/agent-skills.md+++ b/docs/agent-skills.md@@ -132,7 +132,7 @@ Docker、Local、CubeSandbox、E2B 均通过同一套空间配置 CRUD、连接| 模式 | 状态 | 说明 ||------|------|------|-| `docker` | 稳定 | 每次执行启动短生命周期容器;镜像和环境变量按空间配置,不保留会话绑定 |+| `docker` | 稳定 | 单机 Docker daemon;会话级持久(一个会话一个长驻容器),支持多机 WeKnora 副本(需 Redis),但沙箱都落在同一台 daemon 上。见 [Docker 沙箱后端](sandbox-docker-backend.md) || `local` | 开发 | 直接在 WeKnora 服务主机执行;无容器/MicroVM 隔离,不保留会话绑定 || `cube` | 稳定 | Tencent CubeSandbox MicroVM;会话级持久,支持多机(需 Redis) || `e2b` | 稳定 | E2B 云端 MicroVM;会话级持久,支持多机(需 Redis);依赖第三方 SDK go-e2b |@@ -538,7 +538,7 @@ docker pull wechatopenai/weknora-sandbox:latestsh scripts/build_images.sh -s```-> 如果未预拉取,应用启动时会自动异步拉取镜像(`EnsureImage`),但首次执行可能需要等待下载完成。+> 如果未预拉取,创建第一个沙箱时会先拉取镜像,首次执行需要等待下载完成;也可以在设置页的模板步骤提前触发拉取。**镜像内置环境**:- Python 3.11 + pip(requests、pyyaml、pandas、beautifulsoup4)diff --git a/docs/poc/docker-sandbox/README.md b/docs/poc/docker-sandbox/README.mdnew file mode 100644index 000000000..9062598fa--- /dev/null+++ b/docs/poc/docker-sandbox/README.md@@ -0,0 +1,32 @@+# Docker 沙箱后端可行性 PoC++配套文档:[Docker 沙箱后端重做调研](../../sandbox-docker-backend.md)。++这个程序直接打 Docker Engine API,逐项验证「Docker 能不能承载 WeKnora+`RemoteSandboxClient` 契约 + E2B 那套 Snapshot 工作流」。它不是产品代码,也不参与主模块构建+(自带 `go.mod`),只作为调研结论的可复现证据。++每一项都打印 `PASS/FAIL` 和实际观测值。带 `(GAP)` 的步骤断言的是「Docker 做不到什么」,+它们同样以 PASS 结束——PASS 表示差距被复现了,不是表示能力具备。++## 跑法++需要一个可达的 Docker daemon(尊重 `DOCKER_HOST`),能拉 `python:3.11-slim`:++```bash+cd docs/poc/docker-sandbox+go run . # daemon 在本机 unix socket 上时可能需要 sudo -E+```++程序会自建一个带 uid 1000 `user` 账号的模板镜像(对齐 E2B 模板约定),跑完自行删除它创建的容器。+留下的 `weknora-poc/*` 镜像用 `docker image rm` 清理。++## 覆盖的内容++- 生命周期:Create / Connect(换客户端重连)/ List(label 过滤)/ Delete / Pause / Stop+Start+- 执行:user、workdir、env、stdin、stdout+stderr 分离、退出码、超时+- 文件面:archive API 读写与 stat、exec 实现的 mkdir/ls/rm+- 会话语义:`pip install` 与写文件跨 exec 存活+- Snapshot:commit 成镜像、从快照启新沙箱、v1→v2 增量、按 label 列举、层数与体积+- 差距复现:客户端取消不杀进程、CapDrop ALL 后 root 越不过权限位、快照不含内存态、+ daemon 无空闲 TTL、kill `docker run` 会留下还在跑的容器diff --git a/docs/poc/docker-sandbox/go.mod b/docs/poc/docker-sandbox/go.modnew file mode 100644index 000000000..283b78331--- /dev/null+++ b/docs/poc/docker-sandbox/go.mod@@ -0,0 +1,29 @@+module github.com/Tencent/WeKnora/docs/poc/docker-sandbox++go 1.26.0++require (+ github.com/moby/moby/api v1.55.0+ github.com/moby/moby/client v0.5.1+)++require (+ github.com/Microsoft/go-winio v0.6.2 // indirect+ github.com/containerd/errdefs v1.0.0 // indirect+ github.com/containerd/errdefs/pkg v0.3.0 // indirect+ github.com/distribution/reference v0.6.0 // indirect+ github.com/docker/go-connections v0.7.0 // indirect+ github.com/docker/go-units v0.5.0 // indirect+ github.com/felixge/httpsnoop v1.0.4 // indirect+ github.com/go-logr/logr v1.4.2 // indirect+ github.com/go-logr/stdr v1.2.2 // indirect+ github.com/moby/docker-image-spec v1.3.1 // indirect+ github.com/opencontainers/go-digest v1.0.0 // indirect+ github.com/opencontainers/image-spec v1.1.1 // indirect+ go.opentelemetry.io/auto/sdk v1.1.0 // indirect+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 // indirect+ go.opentelemetry.io/otel v1.35.0 // indirect+ go.opentelemetry.io/otel/metric v1.35.0 // indirect+ go.opentelemetry.io/otel/trace v1.35.0 // indirect+ golang.org/x/sys v0.33.0 // indirect+)diff --git a/docs/poc/docker-sandbox/go.sum b/docs/poc/docker-sandbox/go.sumnew file mode 100644index 000000000..b5499c4e3--- /dev/null+++ b/docs/poc/docker-sandbox/go.sum@@ -0,0 +1,61 @@+github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=+github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=+github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=+github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=+github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=+github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=+github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=+github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=+github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=+github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=+github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=+github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=+github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=+github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=+github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=+github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=+github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=+github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc=+github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=+github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw=+github.com/moby/moby/client v0.5.1/go.mod h1:odLstlZ6uSnfvAgVxMpvgmb8SUdd+siH2T0GBuxVAlM=+github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=+github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=+github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=+github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=+go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=+go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 h1:sbiXRNDSWJOTobXh5HyQKjq6wUC5tNybqjIqDpAY4CU=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0/go.mod h1:69uWxva0WgAA/4bu2Yy70SLDBwZXuQ6PbBpbsa5iZrQ=+go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ=+go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y=+go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M=+go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE=+go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY=+go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg=+go.opentelemetry.io/otel/sdk/metric v1.35.0 h1:1RriWBmCKgkeHEhM7a2uMjMUfP7MsOF5JpUCaEqEI9o=+go.opentelemetry.io/otel/sdk/metric v1.35.0/go.mod h1:is6XYCUMpcKi+ZsOvfluY5YstFnhW0BidkR+gL+qN+w=+go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs=+go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc=+golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=+golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=+gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=+pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk=+pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04=diff --git a/docs/poc/docker-sandbox/main.go b/docs/poc/docker-sandbox/main.gonew file mode 100644index 000000000..571bd8af3--- /dev/null+++ b/docs/poc/docker-sandbox/main.go@@ -0,0 +1,612 @@+// PoC for docs/sandbox-docker-backend.md: can the Docker Engine API back the+// semantics WeKnora's RemoteSandboxClient contract requires (session-persistent+// sandbox, exec, filesystem, metadata, lifecycle), plus the snapshot workflow+// planned for E2B?+//+// It drives a real daemon and prints PASS/FAIL plus the observed evidence for+// every operation, including the ones Docker cannot honour ("GAP" steps, which+// assert the gap rather than a capability).+//+// Run with a reachable daemon (DOCKER_HOST honoured):+//+// cd docs/poc/docker-sandbox && go run .+package main++import (+ "archive/tar"+ "bytes"+ "context"+ "errors"+ "fmt"+ "io"+ "os"+ "os/exec"+ "strings"+ "time"++ "github.com/moby/moby/api/pkg/stdcopy"+ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/client"+)++const (+ baseImage = "python:3.11-slim"+ execUser = "user"+)++var failures int++func step(name string, err error, detail string) {+ if err != nil {+ failures+++ fmt.Printf("FAIL %-48s %v\n", name, err)+ return+ }+ fmt.Printf("PASS %-48s %s\n", name, detail)+}++func main() {+ ctx := context.Background()+ cli, err := client.New(client.WithHostFromEnv(), client.WithAPIVersionNegotiation())+ if err != nil {+ fmt.Println("cannot reach docker:", err)+ os.Exit(1)+ }+ defer cli.Close()++ ping, err := cli.Ping(ctx, client.PingOptions{})+ step("Health: ping control plane", err, fmt.Sprintf("api=%s", ping.APIVersion))++ tmplImage := "weknora-poc/template:v2"+ err = buildTemplateImage(ctx, cli, tmplImage)+ step("Template: base image with uid-1000 user", err, tmplImage)+ if err != nil {+ os.Exit(1)+ }++ sessionID := fmt.Sprintf("poc-session-%d", time.Now().Unix())+ labels := map[string]string{+ "weknora.managed": "true",+ "weknora.tenant": "1",+ "weknora.session": sessionID,+ "weknora.config": "cfg-poc",+ "weknora.createdAt": time.Now().UTC().Format(time.RFC3339),+ }++ // --- Create -------------------------------------------------------------+ id, err := createSandbox(ctx, cli, tmplImage, labels)+ step("Create: container as session sandbox", err, short(id))+ if err != nil {+ os.Exit(1)+ }+ defer remove(cli, id)++ // --- Connect / Get ------------------------------------------------------+ fresh, err := client.New(client.WithHostFromEnv(), client.WithAPIVersionNegotiation())+ if err == nil {+ defer fresh.Close()+ var insp client.ContainerInspectResult+ insp, err = fresh.ContainerInspect(ctx, id, client.ContainerInspectOptions{})+ if err == nil && insp.Container.Config.Labels["weknora.session"] != sessionID {+ err = errors.New("metadata labels not preserved")+ }+ step("Connect+Metadata: re-attach from a new client", err,+ fmt.Sprintf("state=%s session=%s", insp.Container.State.Status,+ insp.Container.Config.Labels["weknora.session"]))+ }++ // --- List by metadata ---------------------------------------------------+ listed, err := cli.ContainerList(ctx, client.ContainerListOptions{+ All: true,+ Filters: client.Filters{}.Add("label", "weknora.session="+sessionID),+ })+ if err == nil && len(listed.Items) != 1 {+ err = fmt.Errorf("expected 1 container, got %d", len(listed.Items))+ }+ step("List: server-side metadata filter", err, fmt.Sprintf("matched=%d", len(listed.Items)))++ // --- Exec: user / workdir / env / stdin / demux / exit code -------------+ res, err := execIn(ctx, cli, id, execRequest{+ cmd: []string{"bash", "-lc", `cat; echo "user=$(id -un) cwd=$(pwd) env=$GREET"; echo oops >&2; exit 7`},+ user: execUser,+ workDir: "/workspace",+ env: []string{"GREET=hello"},+ stdin: "stdin-payload\n",+ })+ if err == nil {+ switch {+ case res.exitCode != 7:+ err = fmt.Errorf("exit code %d, want 7", res.exitCode)+ case !strings.Contains(res.stdout, "user=user cwd=/workspace env=hello"):+ err = fmt.Errorf("stdout mismatch: %q", res.stdout)+ case !strings.Contains(res.stdout, "stdin-payload"):+ err = fmt.Errorf("stdin not delivered: %q", res.stdout)+ case !strings.Contains(res.stderr, "oops"):+ err = fmt.Errorf("stderr not separated: %q", res.stderr)+ }+ }+ step("Exec: user/workdir/env/stdin/demux/exit", err,+ fmt.Sprintf("exit=%d stdout=%q stderr=%q", res.exitCode, oneline(res.stdout), oneline(res.stderr)))++ // --- Exec cancellation: does a client-side cancel kill the process? -----+ cancelCtx, cancel := context.WithTimeout(ctx, 2*time.Second)+ _, execErr := execIn(cancelCtx, cli, id, execRequest{+ cmd: []string{"bash", "-lc", "sleep 30"},+ })+ cancel()+ time.Sleep(1 * time.Second)+ probe, _ := execIn(ctx, cli, id, execRequest{+ cmd: []string{"bash", "-lc", "ps -eo args= | grep -c '^sleep 30$' || true"},+ })+ step("Exec cancel: client cancel does NOT kill process (GAP)", nil,+ fmt.Sprintf("clientErr=%v surviving 'sleep' procs=%s", execErr != nil, oneline(probe.stdout)))++ // --- Timeout enforced inside the container ------------------------------+ start := time.Now()+ killRes, err := execIn(ctx, cli, id, execRequest{+ cmd: []string{"timeout", "-s", "KILL", "2", "bash", "-lc", "sleep 30"},+ })+ elapsed := time.Since(start)+ if err == nil && killRes.exitCode != 137 {+ err = fmt.Errorf("exit code %d, want 137 (SIGKILL)", killRes.exitCode)+ }+ step("Timeout: enforce via in-container timeout(1)", err,+ fmt.Sprintf("exit=%d after=%s", killRes.exitCode, elapsed.Round(100*time.Millisecond)))++ // --- Filesystem: write / read / stat / mkdir / list / remove ------------+ err = writeFile(ctx, cli, id, "/workspace/input/attachment.txt", []byte("attachment payload\n"))+ step("WriteFile: PUT /containers/{id}/archive", err, "/workspace/input/attachment.txt")++ content, err := readFile(ctx, cli, id, "/workspace/input/attachment.txt")+ if err == nil && string(content) != "attachment payload\n" {+ err = fmt.Errorf("content mismatch: %q", content)+ }+ step("ReadFile: GET /containers/{id}/archive", err, fmt.Sprintf("%d bytes", len(content)))++ stat, err := cli.ContainerStatPath(ctx, id, client.ContainerStatPathOptions{+ Path: "/workspace/input/attachment.txt",+ })+ step("Stat: HEAD /containers/{id}/archive", err,+ fmt.Sprintf("size=%d mode=%v mtime=%s", stat.Stat.Size, stat.Stat.Mode.Perm(),+ stat.Stat.Mtime.Format(time.RFC3339)))++ rootMk, _ := execIn(ctx, cli, id, execRequest{cmd: []string{"mkdir", "-p", "/workspace/output/rootdir"}})+ step("CapDrop ALL: root cannot bypass mode bits (GAP)", nil,+ fmt.Sprintf("mkdir as root exit=%d stderr=%q", rootMk.exitCode, oneline(rootMk.stderr)))++ _, err = mustExec(ctx, cli, id, execRequest{+ cmd: []string{"mkdir", "-p", "/workspace/output/nested"},+ user: execUser,+ })+ step("MakeDir: exec mkdir -p as sandbox user", err, "/workspace/output/nested")++ if _, err = mustExec(ctx, cli, id, execRequest{+ cmd: []string{"bash", "-lc", "echo body > /workspace/output/nested/report.txt"},+ user: execUser,+ }); err != nil {+ step("ListDir: seed a file to list", err, "")+ }+ lsRes, err := mustExec(ctx, cli, id, execRequest{+ cmd: []string{"find", "/workspace/output", "-mindepth", "1", "-printf", `%y\t%s\t%T@\t%p\n`},+ user: execUser,+ })+ if err == nil && !strings.Contains(lsRes.stdout, "report.txt") {+ err = fmt.Errorf("listing missing report.txt: %q", lsRes.stdout)+ }+ step("ListDir: exec find (no native API)", err,+ fmt.Sprintf("exit=%d out=%q err=%q", lsRes.exitCode, oneline(lsRes.stdout), oneline(lsRes.stderr)))++ _, err = mustExec(ctx, cli, id, execRequest{+ cmd: []string{"rm", "-rf", "/workspace/input/attachment.txt"},+ user: execUser,+ })+ step("Remove: exec rm (no native API)", err, "removed")++ // --- Session-scoped state persists across executions --------------------+ installRes, err := execIn(ctx, cli, id, execRequest{+ cmd: []string{"bash", "-lc", "pip install --quiet --no-cache-dir --user cowsay==6.1 && echo 1 > /workspace/output/counter.txt"},+ user: execUser,+ })+ if err == nil && installRes.exitCode != 0 {+ err = fmt.Errorf("install failed: %s %s", oneline(installRes.stdout), oneline(installRes.stderr))+ }+ if err == nil {+ var second execResult+ second, err = execIn(ctx, cli, id, execRequest{+ cmd: []string{"bash", "-lc", `python -c 'import cowsay; print("cowsay ok")' && cat /workspace/output/counter.txt`},+ user: execUser,+ })+ if err == nil && (!strings.Contains(second.stdout, "cowsay ok") || !strings.Contains(second.stdout, "1")) {+ err = fmt.Errorf("state lost between executions: %q %q", second.stdout, second.stderr)+ }+ }+ step("Session state: pip install survives next exec", err, "package + file both visible")++ // --- Pause / Unpause (memory kept resident) -----------------------------+ _, err = cli.ContainerPause(ctx, id, client.ContainerPauseOptions{})+ if err == nil {+ insp, _ := cli.ContainerInspect(ctx, id, client.ContainerInspectOptions{})+ if insp.Container.State.Status != "paused" {+ err = fmt.Errorf("state=%s", insp.Container.State.Status)+ }+ }+ if err == nil {+ _, err = cli.ContainerUnpause(ctx, id, client.ContainerUnpauseOptions{})+ }+ if err == nil {+ var after execResult+ after, err = execIn(ctx, cli, id, execRequest{cmd: []string{"cat", "/workspace/output/counter.txt"}})+ if err == nil && !strings.Contains(after.stdout, "1") {+ err = fmt.Errorf("state lost after unpause: %q", after.stdout)+ }+ }+ step("Pause/Unpause: cgroup freezer round-trip", err,+ "RAM + processes retained, host memory still occupied")++ // --- Stop / Start (filesystem kept, processes lost) ---------------------+ _, _ = execIn(ctx, cli, id, execRequest{cmd: []string{"bash", "-lc", "nohup sleep 900 >/dev/null 2>&1 & echo started"}})+ timeoutSec := 5+ _, err = cli.ContainerStop(ctx, id, client.ContainerStopOptions{Timeout: &timeoutSec})+ if err == nil {+ _, err = cli.ContainerStart(ctx, id, client.ContainerStartOptions{})+ }+ var afterRestart execResult+ if err == nil {+ afterRestart, err = execIn(ctx, cli, id, execRequest{+ cmd: []string{"bash", "-lc", "cat /workspace/output/counter.txt; ps -eo args= | grep -c '^sleep 900$' || true"},+ })+ if err == nil && !strings.Contains(afterRestart.stdout, "1") {+ err = fmt.Errorf("filesystem lost after restart: %q", afterRestart.stdout)+ }+ }+ step("Stop/Start: filesystem survives, processes do not", err,+ fmt.Sprintf("counter+sleep-count=%s", oneline(afterRestart.stdout)))++ // --- Snapshot workflow --------------------------------------------------+ mgmtID, err := createSandbox(ctx, cli, tmplImage,+ map[string]string{"weknora.managed": "true", "weknora.role": "snapshot-builder"})+ step("Snapshot: create workspace management sandbox", err, short(mgmtID))+ if err != nil {+ report()+ return+ }+ defer remove(cli, mgmtID)++ skillRes, err := execIn(ctx, cli, mgmtID, execRequest{+ cmd: []string{"bash", "-lc", "pip install --quiet --no-cache-dir requests==2.32.3 && mkdir -p /opt/skills/pdf && echo 'skill v1' > /opt/skills/pdf/SKILL.md"},+ })+ if err == nil && skillRes.exitCode != 0 {+ err = fmt.Errorf("skill install failed: %s", oneline(skillRes.stderr))+ }+ step("Snapshot: install a skill into that sandbox", err, "requests==2.32.3 + /opt/skills/pdf")++ snapV1 := "weknora-poc/snapshot:v1"+ commitRes, err := cli.ContainerCommit(ctx, mgmtID, client.ContainerCommitOptions{+ Reference: snapV1,+ Comment: "weknora snapshot v1",+ Changes: []string{`LABEL weknora.snapshot.version=1`, `LABEL weknora.snapshot.tenant=1`},+ })+ step("Snapshot: commit container -> image", err, short(commitRes.ID))++ snapSessionID, err := createSandbox(ctx, cli, snapV1,+ map[string]string{"weknora.managed": "true", "weknora.session": sessionID + "-from-snapshot"})+ step("Snapshot: session sandbox boots from snapshot", err, short(snapSessionID))+ if err == nil {+ defer remove(cli, snapSessionID)+ var check execResult+ check, err = execIn(ctx, cli, snapSessionID, execRequest{+ cmd: []string{"bash", "-lc", `python -c 'import requests; print(requests.__version__)' && cat /opt/skills/pdf/SKILL.md`},+ })+ if err == nil && (!strings.Contains(check.stdout, "2.32.3") || !strings.Contains(check.stdout, "skill v1")) {+ err = fmt.Errorf("snapshot content missing: %q %q", check.stdout, check.stderr)+ }+ step("Snapshot: installed skill present in new sandbox", err, oneline(check.stdout))+ }++ // Incremental snapshot update: install a second skill on top of v1.+ upgradeID, err := createSandbox(ctx, cli, snapV1, map[string]string{"weknora.role": "snapshot-builder"})+ if err == nil {+ defer remove(cli, upgradeID)+ _, err = execIn(ctx, cli, upgradeID, execRequest{+ cmd: []string{"bash", "-lc", "mkdir -p /opt/skills/chart && echo 'skill v2' > /opt/skills/chart/SKILL.md"},+ })+ }+ snapV2 := "weknora-poc/snapshot:v2"+ if err == nil {+ _, err = cli.ContainerCommit(ctx, upgradeID, client.ContainerCommitOptions{+ Reference: snapV2,+ Changes: []string{`LABEL weknora.snapshot.version=2`},+ })+ }+ step("Snapshot: incremental update v1 -> v2", err, snapV2)++ imgs, err := cli.ImageList(ctx, client.ImageListOptions{+ All: true,+ Filters: client.Filters{}.Add("label", "weknora.snapshot.version"),+ })+ step("Snapshot: list snapshots by label", err, fmt.Sprintf("count=%d", len(imgs.Items)))++ insp, err := cli.ImageInspect(ctx, snapV2)+ if err == nil {+ step("Snapshot: layer/size accounting", nil,+ fmt.Sprintf("layers=%d size=%.1fMB (image layer hard limit: 127)",+ len(insp.RootFS.Layers), float64(insp.Size)/1e6))+ } else {+ step("Snapshot: layer/size accounting", err, "")+ }++ // Does a snapshot preserve running processes / RAM? (E2B pause does.)+ _, _ = execIn(ctx, cli, mgmtID, execRequest{cmd: []string{"bash", "-lc", "nohup sleep 600 >/dev/null 2>&1 & echo started"}})+ procSnap := "weknora-poc/snapshot:proc"+ _, err = cli.ContainerCommit(ctx, mgmtID, client.ContainerCommitOptions{Reference: procSnap})+ if err == nil {+ var procID string+ procID, err = createSandbox(ctx, cli, procSnap, map[string]string{"weknora.role": "proc-check"})+ if err == nil {+ defer remove(cli, procID)+ var out execResult+ out, err = execIn(ctx, cli, procID, execRequest{cmd: []string{"bash", "-lc", "ps -eo args= | grep -c '^sleep 600$' || true"}})+ step("Snapshot: running processes NOT captured (GAP)", err,+ fmt.Sprintf("'sleep' procs in restored sandbox=%s", oneline(out.stdout)))+ }+ }++ insp2, err := cli.ContainerInspect(ctx, id, client.ContainerInspectOptions{})+ step("Idle TTL: daemon has none, only timestamps (GAP)", err,+ fmt.Sprintf("startedAt=%s -> WeKnora must sweep", insp2.Container.State.StartedAt))++ checkCLIOrphan(ctx)++ report()+}++// checkCLIOrphan reproduces what today's CLI-based DockerSandbox does on+// timeout: exec.CommandContext kills the `docker run --rm` client process. The+// workload lives in the daemon, so killing the client does not stop it — the+// timeout is reported to the caller while the container keeps burning CPU.+func checkCLIOrphan(ctx context.Context) {+ if _, err := exec.LookPath("docker"); err != nil {+ step("CLI orphan: skipped (docker CLI not on PATH)", nil, "")+ return+ }+ name := fmt.Sprintf("weknora-poc-orphan-%d", time.Now().UnixNano())+ runCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ cmd := exec.CommandContext(runCtx, "docker", "run", "--rm", "--name", name,+ baseImage, "sleep", "120")+ cliErr := cmd.Run()+ time.Sleep(2 * time.Second)++ out, err := exec.CommandContext(ctx, "docker", "ps", "--filter", "name="+name,+ "--format", "{{.State}} {{.Status}}").Output()+ state := oneline(string(out))+ _ = exec.CommandContext(ctx, "docker", "rm", "-f", name).Run()+ if state == "" {+ state = "gone"+ }+ step("CLI orphan: killing `docker run` leaves it running (GAP)", err,+ fmt.Sprintf("cliErr=%v container=%s", cliErr != nil, state))+}++func report() {+ fmt.Println()+ if failures == 0 {+ fmt.Println("RESULT: all checks passed")+ return+ }+ fmt.Printf("RESULT: %d check(s) failed\n", failures)+ os.Exit(1)+}++// --- helpers -----------------------------------------------------------------++func remove(cli *client.Client, id string) {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ _, _ = cli.ContainerRemove(ctx, id, client.ContainerRemoveOptions{Force: true})+}++func buildTemplateImage(ctx context.Context, cli *client.Client, tag string) error {+ if _, err := cli.ImageInspect(ctx, tag); err == nil {+ return nil+ }+ dockerfile := `FROM ` + baseImage + `+RUN apt-get update && apt-get install -y --no-install-recommends procps findutils && rm -rf /var/lib/apt/lists/*+RUN useradd -m -u 1000 user && mkdir -p /workspace/input /workspace/output && chown -R user:user /workspace+WORKDIR /workspace+`+ var buf bytes.Buffer+ tw := tar.NewWriter(&buf)+ if err := tw.WriteHeader(&tar.Header{Name: "Dockerfile", Mode: 0o644, Size: int64(len(dockerfile))}); err != nil {+ return err+ }+ if _, err := tw.Write([]byte(dockerfile)); err != nil {+ return err+ }+ if err := tw.Close(); err != nil {+ return err+ }+ resp, err := cli.ImageBuild(ctx, &buf, client.ImageBuildOptions{Tags: []string{tag}, Remove: true})+ if err != nil {+ return err+ }+ defer resp.Body.Close()+ _, err = io.Copy(io.Discard, resp.Body)+ return err+}++func createSandbox(ctx context.Context, cli *client.Client, img string, labels map[string]string) (string, error) {+ pids := int64(256)+ created, err := cli.ContainerCreate(ctx, client.ContainerCreateOptions{+ Image: img,+ Config: &container.Config{+ Cmd: []string{"sleep", "infinity"},+ WorkingDir: "/workspace",+ Labels: labels,+ },+ HostConfig: &container.HostConfig{+ Resources: container.Resources{+ Memory: 1 << 30,+ MemorySwap: 1 << 30,+ NanoCPUs: 1_000_000_000,+ PidsLimit: &pids,+ },+ CapDrop: []string{"ALL"},+ SecurityOpt: []string{"no-new-privileges"},+ },+ })+ if err != nil {+ return "", err+ }+ if _, err := cli.ContainerStart(ctx, created.ID, client.ContainerStartOptions{}); err != nil {+ return created.ID, err+ }+ return created.ID, nil+}++type execRequest struct {+ cmd []string+ user string+ workDir string+ env []string+ stdin string+}++type execResult struct {+ stdout string+ stderr string+ exitCode int+}++func execIn(ctx context.Context, cli *client.Client, id string, req execRequest) (execResult, error) {+ created, err := cli.ExecCreate(ctx, id, client.ExecCreateOptions{+ Cmd: req.cmd,+ User: req.user,+ WorkingDir: req.workDir,+ Env: req.env,+ AttachStdin: req.stdin != "",+ AttachStdout: true,+ AttachStderr: true,+ })+ if err != nil {+ return execResult{}, err+ }+ attached, err := cli.ExecAttach(ctx, created.ID, client.ExecAttachOptions{})+ if err != nil {+ return execResult{}, err+ }+ defer attached.Close()++ if req.stdin != "" {+ if _, err := attached.Conn.Write([]byte(req.stdin)); err != nil {+ return execResult{}, err+ }+ if cw, ok := attached.Conn.(interface{ CloseWrite() error }); ok {+ _ = cw.CloseWrite()+ }+ }++ var stdout, stderr bytes.Buffer+ copyDone := make(chan error, 1)+ go func() {+ _, copyErr := stdcopy.StdCopy(&stdout, &stderr, attached.Reader)+ copyDone <- copyErr+ }()+ select {+ case err = <-copyDone:+ if err != nil {+ return execResult{}, err+ }+ case <-ctx.Done():+ return execResult{stdout: stdout.String(), stderr: stderr.String()}, ctx.Err()+ }++ inspect, err := cli.ExecInspect(ctx, created.ID, client.ExecInspectOptions{})+ if err != nil {+ return execResult{}, err+ }+ return execResult{+ stdout: stdout.String(),+ stderr: stderr.String(),+ exitCode: inspect.ExitCode,+ }, nil+}++// mustExec fails when the command itself exits non-zero, so a silently+// failing setup step cannot be mistaken for a passing capability check.+func mustExec(ctx context.Context, cli *client.Client, id string, req execRequest) (execResult, error) {+ res, err := execIn(ctx, cli, id, req)+ if err != nil {+ return res, err+ }+ if res.exitCode != 0 {+ return res, fmt.Errorf("exit=%d stderr=%s", res.exitCode, oneline(res.stderr))+ }+ return res, nil+}++func writeFile(ctx context.Context, cli *client.Client, id, dest string, content []byte) error {+ if _, err := execIn(ctx, cli, id, execRequest{cmd: []string{"mkdir", "-p", dirOf(dest)}}); err != nil {+ return err+ }+ var buf bytes.Buffer+ tw := tar.NewWriter(&buf)+ name := dest[strings.LastIndex(dest, "/")+1:]+ if err := tw.WriteHeader(&tar.Header{+ Name: name, Mode: 0o644, Size: int64(len(content)), Uid: 1000, Gid: 1000,+ }); err != nil {+ return err+ }+ if _, err := tw.Write(content); err != nil {+ return err+ }+ if err := tw.Close(); err != nil {+ return err+ }+ _, err := cli.CopyToContainer(ctx, id, client.CopyToContainerOptions{+ DestinationPath: dirOf(dest),+ Content: &buf,+ CopyUIDGID: true,+ })+ return err+}++func readFile(ctx context.Context, cli *client.Client, id, src string) ([]byte, error) {+ res, err := cli.CopyFromContainer(ctx, id, client.CopyFromContainerOptions{SourcePath: src})+ if err != nil {+ return nil, err+ }+ defer res.Content.Close()+ tr := tar.NewReader(res.Content)+ for {+ header, err := tr.Next()+ if err == io.EOF {+ return nil, errors.New("file not present in archive")+ }+ if err != nil {+ return nil, err+ }+ if header.Typeflag == tar.TypeReg {+ return io.ReadAll(tr)+ }+ }+}++func dirOf(p string) string {+ idx := strings.LastIndex(p, "/")+ if idx <= 0 {+ return "/"+ }+ return p[:idx]+}++func short(id string) string {+ if len(id) > 12 {+ return id[:12]+ }+ return id+}++func oneline(s string) string {+ return strings.Join(strings.Fields(s), " ")+}diff --git a/docs/sandbox-cluster.md b/docs/sandbox-cluster.mdindex d8c75c8d8..74a5164dd 100644--- a/docs/sandbox-cluster.md+++ b/docs/sandbox-cluster.md@@ -31,7 +31,7 @@| 变体 | 标签 | 用途 || --- | --- | --- |-| `sandbox`(默认) | `wechatopenai/weknora-sandbox:<版本>` | Docker 后端直接执行脚本;同时作为 E2B 模板的基础镜像 |+| `sandbox`(默认) | `wechatopenai/weknora-sandbox:<版本>` | Docker 后端的会话容器镜像;同时作为 E2B 模板的基础镜像 || `cube` | `wechatopenai/weknora-sandbox:<版本>-cube` | CubeSandbox 模板 |区别在于 Cube 变体额外注入了 envd。Cube 直接把 OCI 镜像变成模板,并以 `GET :49983/health` 探活,这个端点只有 envd 提供;不带 envd 的镜像建模板必然以 `connection refused` 失败。E2B 不需要这个变体,因为它的构建流程会自行注入 envd;Docker 后端则完全不需要 envd。详见 [Cube 自带镜像接入](https://cubesandbox.com/zh/guide/tutorials/bring-your-own-image.html)。diff --git a/docs/sandbox-docker-backend.md b/docs/sandbox-docker-backend.mdnew file mode 100644index 000000000..7c725727f--- /dev/null+++ b/docs/sandbox-docker-backend.md@@ -0,0 +1,161 @@+# Docker 沙箱后端++面向部署方与要改这块代码的人。本文说明 docker 后端现在是什么形态、怎么配、边界在哪,+以及为什么是这个设计。协议层的整体立场见 [沙箱协议接入说明](./sandbox-protocol.md),+CubeSandbox / E2B 的集群与模板见 [沙箱集群与标准模板](./sandbox-cluster.md)。++## 结论先说++- docker 后端已经是**会话级后端**:一个会话一个长驻容器,脚本、`shell_exec`、附件暂存、+ 产物收集都落在同一个容器里,与 E2B/Cube 在应用层的行为一致。+- 实现方式是 `RemoteSandboxClient` 适配器(`internal/sandbox/docker_remote_client.go`),+ 直接打 Docker Engine API。session→sandbox 绑定、生命周期锁、能力矩阵一行没改——+ 这正是当初把 provider 抽象成 `RemoteSandboxClient` 的收益。+- 它适合单机 / 私有化部署。跨主机调度、内核级隔离、内存态快照仍然要用 E2B 协议后端,+ 原因见「边界」一节。+- Docker 官方的 Docker Sandboxes(`sbx`)不能当后端:那是开发者本机 CLI,要 Docker 账号登录、+ 工作区是宿主机目录直挂、没有多租户服务端 API。++## 之前为什么不行++旧实现每次执行都是 `docker run --rm` 加一个只读 bind mount,和 E2B 不是「能力少一点」,+而是模型不同。具体是这几条(都在改造中修掉了):++| 旧行为 | 后果 |+| --- | --- |+| 执行完即销毁容器 | 没有会话状态,`shell_exec`、附件暂存、产物收集在能力矩阵里根本不注册 |+| 超时 `kill` 的是 `docker run` 客户端进程 | 容器继续跑到自己结束;WeKnora 已经给用户返回超时了。实测见 [PoC](./poc/docker-sandbox) |+| `/workspace` 只读挂载 | 脚本写不了 `/workspace/output`,而 skills 框架恰恰把 `WEKNORA_SKILL_OUTPUT_DIR` 指到那里 |+| bind mount 由宿主机 daemon 解释 | WeKnora 自己跑在容器里时挂进去的是宿主机上的同名目录,通常不存在 |+| 走 docker CLI 而不是 API | 依赖宿主机装 CLI,错误只能靠字符串匹配,拿不到容器 ID 做对账与回收 |+| 配置面只有一个 `image` | CPU、内存、网络、TTL 都没法按空间配置 |++## 现在的形态++一个沙箱就是一个容器。标准镜像以 `USER user` 结尾,创建时覆盖为 uid 0,这样入口才能在 `/var/lib` 写下活跃标记;脚本仍以 `user` 执行。PID 1 是 `sleep infinity`,所有工作都通过 exec 进去做。++这层 wrapper 是通过 `Entrypoint` 下发并把 `Cmd` 显式清空的:daemon 会把镜像自带的+ENTRYPOINT 拼到 Cmd 前面,所以只设 Cmd 时,任何声明了 ENTRYPOINT 的镜像(本文件的+`cube` target 就有)都会顶掉 PID 1,活跃标记不会生成、exec 也会打到别的东西上。++| 契约方法 | Docker 实现 |+| --- | --- |+| `Health` | `GET /_ping` |+| `Create` | `POST /containers/create` + `/start`,metadata 落成 labels,镜像缺失时先 pull |+| `Connect` | `GET /containers/{id}/json`;容器被停掉时重新 `start`,被 pause 时 `unpause` |+| `Get` / `List` | `GET /containers/json?filters=label=…`,服务端按 label 过滤 |+| `Delete` | `DELETE /containers/{id}?force=1&v=1` |+| `Exec` | `POST /containers/{id}/exec` → `/exec/{id}/start`(hijack)→ `/exec/{id}/json` |+| `WriteFile` / `ReadFile` / `Stat` | `PUT` / `GET` / `HEAD /containers/{id}/archive` |+| `MakeDir` / `Remove` / `ListDir` | 没有原生接口,用 exec 的 `mkdir -p` / `rm -rf` / `find -printf` |++几个不显然但要紧的决定:++**超时由容器内的 `timeout(1)` 执行。** 取消 HTTP 请求不会终止容器里的进程([PoC](./poc/docker-sandbox)+里专门复现了这条),所以每次 exec 都包一层+`sh -c 'touch <marker>; exec timeout -s KILL <n> "$@"' weknora-exec <cmd> <args...>`。+命令通过位置参数传进去,不做任何字符串拼接,脚本里的引号和换行不会改变实际执行的东西。+退出码 137/124 被翻译成 `Killed=true`。++**空闲回收是 WeKnora 自己的事。** daemon 没有任何 TTL 概念。上面那层 wrapper 顺手 `touch`+一个活跃标记文件,清扫时用一次 `HEAD /archive` 读它的 mtime 就知道容器多久没干活了——+不需要额外往容器里 exec,也不需要 Redis 记账。清扫在 `Create`/`Connect` 时触发,+按 daemon 端点限流(默认最快一分钟一次),在后台跑。删掉一个空闲容器不需要跟绑定存储协调:+生命周期本来就把「provider 上已经没有的沙箱」当作可重新绑定,这跟 E2B 沙箱被自己的 TTL+回收后的路径完全一样。每个容器把创建时的 TTL 记在 label 上,所以 A 配置触发的清扫不会拿+自己的 TTL 去衡量 B 配置的容器。++标记文件必须对沙箱账号可写(只跑脚本的会话也要能刷新它),因此它的 mtime 是容器可影响的:+落在未来的时间戳一律不采信,退回按容器启动时间判断,否则一次 `touch -d 2099-01-01`+就能让容器永久免于回收。往前改只会让自己更早被回收,不构成问题。此外清扫在真正删除前+会再读一次标记:列举加逐个 stat 在繁忙 daemon 上不是瞬时的,期间会话可能已被恢复。++残留风险:容器内以 root 跑的东西(`shell_exec` 默认就是 root)可以起一个后台循环持续+`touch` 标记,从而把自己维持成「一直活跃」。这与「容器内 root 能让自己一直运行」是同一+信任边界,需要硬上限时应由部署方在 daemon 侧限制。++**exec 默认以 root 运行,脚本以 `user`(uid 1000) 运行。** 与 envd 后端的口径一致:+`RemoteExecRequest.User` 为空表示 root,脚本执行路径显式传 `DefaultSandboxExecUser`。+容器 `CapDrop: ALL` 之后额外补回 CHOWN/DAC_OVERRIDE/FOWNER/FSETID/SETGID/SETUID/KILL,+这是 root 装包和修属主需要的最小集合;Docker 默认给的 NET_RAW、MKNOD、SYS_CHROOT 等一律不给。++**镜像即模板。** `ListTemplates` 列出 daemon 上带 `com.weknora.sandbox.template=true` 标签的、+或名字就是标准镜像的镜像;`EnsureStandardTemplate` 在后台拉取,拉取期间模板状态显示为+`building`,与其它后端的模板构建流程对齐。++## 配置++在「设置 → 沙箱后端」中新建配置并选择 Docker:++| 字段 | 说明 |+| --- | --- |+| 镜像 | 必填。会话容器都从它创建,等价于其它后端的 template ID |+| Docker 守护进程地址 | 留空跟随本机 `docker` CLI(`DOCKER_HOST` 或当前 `docker context`),因此 Colima / Docker Desktop 不必手填 socket。远程填 `tcp://host:2376`,**必须**同时填 TLS 证书目录;私网地址要打开「允许访问私网集群地址」 |+| TLS 证书目录 | 远程 daemon 必填。WeKnora 主机上包含 `ca.pem`/`cert.pem`/`key.pem` 的目录,证书不入库 |+| 空闲回收 | 容器多久没执行任何命令就回收。留空 1800 秒 |+| CPU / 内存 / 进程数上限 | 单个沙箱的资源上限。留空 2 核 / 2048 MB / 512 进程 |+| 网络模式 | 只接受 `bridge`(默认)与 `none`(完全禁止出网)。`host`、`container:` 以及自定义网络名一律拒绝:常见部署通过挂载的 `docker.sock` 连 daemon,填上部署自身的 compose 网络就会让沙箱与 Postgres / Redis 同网 |++`tcp://` daemon 的连接与其它后端的租户端点同一口径:保存时校验地址,实际拨号时再按+「允许访问私网地址」开关过一遍 `SafeDialControl`,这样保存校验解析到公网、连接时被+重解析到 169.254.169.254 的情况也拦得住。unix socket 不经过这一层。++镜像要求:uid 1000 的 `user` 账号、`/workspace/{input,output}` 归该账号所有、+GNU `find`(`-printf`)与 coreutils `timeout`。`docker/Dockerfile.sandbox` 产出的标准镜像满足这些,+Debian 系基础镜像天然带 find 和 timeout。++部署形态:++| 形态 | 适用 | 关键约束 |+| --- | --- | --- |+| 本机 socket | 单机、私有化、开发 | app 与 daemon 同机;`docker.sock` 等于宿主机 root,只能暴露给 app 进程 |+| 远程 daemon(mTLS) | 沙箱负载与应用分离 | 必须配 TLS 证书;daemon 端口不得暴露到公网 |+| 每租户独立 daemon | 有强隔离诉求但没有 KVM | 由部署方分配,不同配置指向不同 host |++WeKnora 自己跑在容器里时,要把 **实际的** docker socket 挂进 app 容器(并接受它等同宿主机 root 的事实),+或者改用远程 daemon。Linux 上通常是 `/var/run/docker.sock`;macOS 上 Colima / Docker Desktop / OrbStack+各自有 `$HOME` 下的 socket,以 `docker context show` 为准。++## 边界++这些是 Docker 给不了的,写在这里以免被当成 bug:++- **跨主机调度**:一个配置就是一个 daemon,也就是一台机器。要多机就得自己选机、分发镜像、+ 在绑定里记住会话落在哪台机器上——那就是在写一个控制面,这条边界是刻意保留的。+- **内核级隔离**:容器共享宿主机内核。要更强只能叠 gVisor / Kata(配置里的 runtime 字段)。+- **内存态快照**:`docker commit` 只保存文件系统。CRIU(`docker checkpoint`)是 experimental,+ 默认 daemon 直接拒绝。E2B 的 pause/snapshot 会保存内存,Docker 不会。+- **域名级出网策略**:Docker 只有 L3/L4。`RemoteNetworkPolicy` 里的域名 allow/deny 在这个后端+ 只能表达成「全开」或「全关」,要按域名放行得在部署侧加 egress proxy。+- **卷挂载**:`SupportsVolumes` 目前是 false,租户级共享卷还没有映射到 Docker named volume。++## 快照++「空间级管理沙箱装 skill → commit 成快照 → 会话从快照起容器 → 增量出下一版」这套流程在 Docker 上+是原生形态(容器 → 镜像),[PoC](./poc/docker-sandbox) 已经验证:commit 一个 140 MB 镜像约+0.5–1.0 秒,从快照冷启一个容器约 0.2 秒,v1→v2 增量正常。两个要注意的约束:镜像层上限 127,+长期增量要定期压平;快照是本机资产,多机部署必须推到 registry。这部分按计划在单独分支实现。++## 测试++单元测试用一个内存版 Engine API 驱动适配器,不需要 daemon:++```bash+go test ./internal/sandbox -run 'TestDocker' -count=1+```++一致性测试打真实 daemon,覆盖会话状态保持、包安装跨执行存活、`shell_exec` 复用同一沙箱、+附件暂存与产物收集、超时确实终止进程、容器被外部停掉后恢复:++```bash+docker build -f docker/Dockerfile.sandbox --target sandbox -t wechatopenai/weknora-sandbox:dev .+DOCKER_INTEGRATION_IMAGE=wechatopenai/weknora-sandbox:dev \+go test -tags=docker_integration ./internal/sandbox \+ -run '^TestDocker.*Integration' -count=1 -v -timeout=15m+```++它和 E2B 的一致性测试断言的是同一批语义,这是刻意重复:一个后端只过其中一个,+就说明两者在应用层还不能互换。++[docs/poc/docker-sandbox](./poc/docker-sandbox) 是当初的可行性验证,保留下来作为+「Docker 能做什么、不能做什么」的可复现证据,它不参与主模块构建。diff --git a/docs/sandbox-protocol.md b/docs/sandbox-protocol.mdindex 8958e0225..23a790831 100644--- a/docs/sandbox-protocol.md+++ b/docs/sandbox-protocol.md@@ -4,9 +4,9 @@## 结论-- WeKnora 只维护一套远端沙箱协议客户端:E2B 协议(控制面 REST + 数据面 envd)。-- 具体的隔离能力由社区实现提供,WeKnora 不自研沙箱运行时,也不自研“Docker 版控制面”。容器隔离、MicroVM 隔离、托管服务都有现成的 E2B 兼容实现,见下面的选型表。-- 内置的 `docker` 与 `local` 后端是一次性(每次执行新建、执行完销毁)的本机后端,只适合开发调试。它们不参与会话级沙箱的能力集,也不会再扩展;生产环境请选 E2B 协议后端。+- 跨主机、需要内核级隔离的部署走 E2B 协议(控制面 REST + 数据面 envd):WeKnora 只维护一套这样的客户端,具体隔离能力由社区实现提供,见下面的选型表。+- 单机 / 私有化部署可以直接用 `docker` 后端:它现在也是会话级后端(一个会话一个长驻容器),在应用层与 E2B 行为一致,代价是空闲回收、执行超时这些控制面职责由 WeKnora 承担。详见 [Docker 沙箱后端](./sandbox-docker-backend.md)。+- `local` 后端在 WeKnora 主机上直接跑脚本,没有任何隔离,只适合可信的开发空间。## 当前的后端形态@@ -14,10 +14,10 @@| --- | --- | --- | --- | --- || `e2b` | E2B 协议 | 持久(一个会话一个沙箱) | 支持 | 生产主路径,可指向任意 E2B 兼容控制面 || `cube` | E2B 兼容(走 Cube 官方 Go SDK) | 持久 | 支持 | CubeSandbox 专用适配器,见“为什么还留着 cube 适配器” |-| `docker` | 无(本机 `docker run --rm`) | 无,每次执行都是新容器 | 不支持 | 本机开发调试 |+| `docker` | 无(Docker Engine API) | 持久(一个会话一个容器) | 支持 | 单机 / 私有化部署,见 [Docker 沙箱后端](./sandbox-docker-backend.md) || `local` | 无(本机进程) | 无 | 不支持 | 本机开发调试,隔离性最弱 |-`docker` 与 `local` 的“一次性”不是遗漏而是它们的边界:把会话级持久沙箱做在单机 Docker 上,等于自己实现一遍控制面(生命周期、空闲回收、跨副本绑定、孤儿清理、多租户隔离),而这些正是 E2B 兼容实现已经提供的东西。因此这两个后端保持现状,能力矩阵在 `internal/sandbox/capabilities.go` 中显式表达,agent 侧据此决定是否注册 shell/文件类工具。+`docker` 与 E2B 协议后端的分界不在能力而在规模:一个 docker 配置就是一台 daemon,跨主机调度、内核级隔离、内存态快照都不在它的能力范围内,那些正是 E2B 兼容实现提供的东西。`local` 依然不参与会话级能力集。能力矩阵在 `internal/sandbox/capabilities.go` 中显式表达,agent 侧据此决定是否注册 shell/文件类工具。## 可直接使用的开源实现diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.tsindex a51182c81..47fb2eb74 100644--- a/frontend/src/api/system/index.ts+++ b/frontend/src/api/system/index.ts@@ -757,7 +757,21 @@ export interface SandboxConfig {volume_mount?: SandboxVolumeMountConfigcube?: SandboxCubeConfige2b?: SandboxE2BConfig- docker?: { image?: string }+ docker?: SandboxDockerConfig+}++/** Docker backend: one daemon, one long-lived container per session. */+export interface SandboxDockerConfig {+ image?: string+ host?: string+ tls_cert_path?: string+ cpu_limit?: number+ memory_limit_mb?: number+ pids_limit?: number+ network_mode?: string+ runtime?: string+ idle_ttl_seconds?: number+ http_timeout_sec?: number}/** `ok: null` means the probe was not executed in this run. */diff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vueindex 241107f97..fede81828 100644--- a/frontend/src/components/SandboxConfigEditorDrawer.vue+++ b/frontend/src/components/SandboxConfigEditorDrawer.vue@@ -184,6 +184,15 @@<t-input v-model="docker.image" placeholder="wechatopenai/weknora-sandbox:latest"@input="onFieldInput('image')" /></t-form-item>+ <t-form-item :label="$t('settings.sandbox.dockerHost')" :help="$t('settings.sandbox.dockerHostHelp')">+ <t-input v-model="docker.host" placeholder="unix:///var/run/docker.sock"+ @input="onFieldInput('host')" />+ </t-form-item>+ <t-form-item :label="$t('settings.sandbox.dockerTlsCertPath')"+ :help="$t('settings.sandbox.dockerTlsCertPathHelp')">+ <t-input v-model="docker.tls_cert_path" placeholder="/etc/weknora/docker-certs"+ @input="onFieldInput('tls_cert_path')" />+ </t-form-item></template><t-alert v-else theme="warning" class="compact-alert" :message="$t('settings.sandbox.localRuntimeWarning')" /></section>@@ -293,6 +302,36 @@</t-form-item><p class="section-help section-help--field">{{ $t('settings.sandbox.sandboxTtlHelp') }}</p></template>+ <!--+ Docker has no provider-side timeout at all: an abandoned container+ keeps its memory and CPU share on the daemon host until WeKnora+ reclaims it, so the idle TTL and the resource caps are the only+ things bounding what one workspace can hold.+ -->+ <template v-if="backend === 'docker'">+ <t-form-item :label="$t('settings.sandbox.dockerIdleTtl')">+ <t-input-number v-model="docker.idle_ttl_seconds" :min="0" theme="column" placeholder="1800" />+ </t-form-item>+ <p class="section-help section-help--field">{{ $t('settings.sandbox.dockerIdleTtlHelp') }}</p>+ <t-form-item :label="$t('settings.sandbox.dockerCpuLimit')">+ <t-input-number v-model="docker.cpu_limit" :min="0" :step="0.5" theme="column" placeholder="2" />+ </t-form-item>+ <t-form-item :label="$t('settings.sandbox.dockerMemoryLimit')">+ <t-input-number v-model="docker.memory_limit_mb" :min="0" theme="column" placeholder="2048" />+ </t-form-item>+ <t-form-item :label="$t('settings.sandbox.dockerPidsLimit')">+ <t-input-number v-model="docker.pids_limit" :min="0" theme="column" placeholder="512" />+ </t-form-item>+ <p class="section-help section-help--field">{{ $t('settings.sandbox.dockerResourceHelp') }}</p>+ <t-form-item :label="$t('settings.sandbox.dockerNetworkMode')">+ <t-select v-model="docker.network_mode" :placeholder="$t('settings.sandbox.dockerNetworkBridge')"+ clearable>+ <t-option value="bridge" :label="$t('settings.sandbox.dockerNetworkBridge')" />+ <t-option value="none" :label="$t('settings.sandbox.dockerNetworkNone')" />+ </t-select>+ </t-form-item>+ <p class="section-help section-help--field">{{ $t('settings.sandbox.dockerNetworkModeHelp') }}</p>+ </template><t-form-item :label="$t('settings.sandbox.defaultTimeout')"><t-input-number v-model="defaultTimeoutSec" :min="0" theme="column" placeholder="60" /></t-form-item>@@ -407,6 +446,7 @@ import {type SandboxConflict,type SandboxCubeConfig,type SandboxE2BConfig,+ type SandboxDockerConfig,type SandboxTemplate,isNamedSandboxBackend,NAMED_SANDBOX_BACKEND_TYPES,@@ -455,7 +495,7 @@ const defaultTimeoutSec = ref<number | undefined>(undefined)const allowPrivateEndpoints = ref(false)const cube = reactive<SandboxCubeConfig>({})const e2b = reactive<SandboxE2BConfig>({})-const docker = reactive<{ image?: string }>({})+const docker = reactive<SandboxDockerConfig>({})// Tracks which secrets the tenant already has stored, so an empty input can// mean "keep the saved key" instead of "no key configured".const storedSecrets = reactive({ cube: false, e2b: false })@@ -470,6 +510,7 @@ let templatePollTimer: ReturnType<typeof setTimeout> | undefined// Remote backends additionally expose a template catalog and control-plane// settings. All four backends still share the same save/check API.const isRemoteBackend = computed(() => backend.value === 'cube' || backend.value === 'e2b')+const hasImageCatalog = computed(() => isRemoteBackend.value || backend.value === 'docker')const currentTemplateId = computed(() => (backend.value === 'cube' ? cube.template_id : backend.value === 'e2b' ? e2b.template_id : '')?.trim() || '')@@ -735,7 +776,7 @@ function scheduleTemplatePolling() {}async function loadTemplates(ensureStandard: boolean, silent = false): Promise<boolean> {- if (!isRemoteBackend.value) return true+ if (!hasImageCatalog.value) return trueif (!connectionReady()) return falseif (!silent) templatesLoading.value = truetemplatesError.value = ''@@ -817,6 +858,11 @@ async function handlePrimaryAction() {await loadTemplates(true)return}+ // Docker's template is the image typed on this step. Kick a background+ // pull so the first session does not block on a cold registry fetch.+ if (backend.value === 'docker') {+ void loadTemplates(true)+ }wizardStep.value += 1return}diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 4cc144409..7aa6e511d 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -1081,7 +1081,7 @@ export default {backendDescriptions: {cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',e2b: 'Managed MicroVM service or an E2B-compatible deployment',- docker: 'Run every script in a short-lived container on this WeKnora host',+ docker: 'Keep a long-lived container per session on this WeKnora host; scripts and files stay in that container',local: 'Run scripts directly in the WeKnora server process environment',},addConfig: 'Add sandbox backend',@@ -1132,7 +1132,7 @@ export default {namedBackendHint: 'Workspace configuration is the only runtime source. Agents without one cannot execute skill scripts.',weknoraTemplateTitle: 'WeKnora standard template',weknoraDockerImage: 'WeKnora standard image',- weknoraDockerImageHint: 'Each execution starts an isolated, short-lived container from this image. No session sandbox is retained.',+ weknoraDockerImageHint: 'Each session gets its own long-lived container. Scripts, shell commands and files all share it until the session ends or the idle timeout reclaims it.',localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',@@ -1204,6 +1204,20 @@ export default {sandboxTtl: 'Sandbox TTL (s)',sandboxTtlHelp: 'How long an idle sandbox survives before the provider reclaims it. Too short and a resumed session has to rebuild it; too long and idle instances keep billing. Empty means the backend default.',dockerImage: 'Docker image',+ dockerHost: 'Docker daemon endpoint',+ dockerHostHelp: 'Empty follows the local docker CLI (DOCKER_HOST or the current docker context), so you do not have to type /var/run/docker.sock. For a remote daemon use tcp://host:2376, fill in the TLS certificate directory, and turn on "allow private endpoints" for RFC1918 addresses.',+ dockerTlsCertPath: 'TLS certificate directory',+ dockerTlsCertPathHelp: 'Directory on the WeKnora host holding ca.pem, cert.pem and key.pem. Required for a remote daemon; certificates are mounted by the deployment, never stored here.',+ dockerIdleTtl: 'Idle reclaim (seconds)',+ dockerIdleTtlHelp: 'The Docker daemon has no idle timeout of its own. A container that runs no command for this long is reclaimed by WeKnora and rebuilt when the session continues. Empty means 1800 seconds.',+ dockerCpuLimit: 'CPU cores',+ dockerMemoryLimit: 'Memory limit (MB)',+ dockerPidsLimit: 'Process limit',+ dockerResourceHelp: 'Caps for one sandbox container. Empty means 2 cores / 2048 MB / 512 processes.',+ dockerNetworkMode: 'Network mode',+ dockerNetworkModeHelp: 'Defaults to bridge, which skills need to install packages. Choose none for no egress at all. Docker filters by network only; per-domain rules are not possible here.',+ dockerNetworkBridge: 'bridge (egress allowed)',+ dockerNetworkNone: 'none (no egress)',defaultTimeout: 'Execution timeout (s)',defaultTimeoutHelp: 'Longest a single skill script may run before it is killed. Empty means 60 seconds.',envVars: 'Environment variables',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex c44ca1b57..987a141d2 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -4913,7 +4913,7 @@ export default {backendDescriptions: {cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',e2b: 'Managed MicroVM service or an E2B-compatible deployment',- docker: 'Run every script in a short-lived container on this WeKnora host',+ docker: '이 WeKnora 호스트의 Docker에서 세션마다 장수명 컨테이너를 유지합니다. 스크립트와 파일이 같은 컨테이너에 남습니다',local: 'Run scripts directly in the WeKnora server process environment',},addConfig: 'Add sandbox backend',@@ -4964,7 +4964,7 @@ export default {namedBackendHint: 'Workspace configuration is the only runtime source. Agents without one cannot execute skill scripts.',weknoraTemplateTitle: 'WeKnora standard template',weknoraDockerImage: 'WeKnora standard image',- weknoraDockerImageHint: 'Each execution starts an isolated, short-lived container from this image. No session sandbox is retained.',+ weknoraDockerImageHint: 'Each session gets its own long-lived container. Scripts, shell commands and files all share it until the session ends or the idle timeout reclaims it.',localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',@@ -5036,6 +5036,20 @@ export default {sandboxTtl: 'Sandbox TTL (s)',sandboxTtlHelp: '유휴 샌드박스가 회수되기까지의 시간입니다. 너무 짧으면 세션을 이어갈 때 다시 만들어야 하고, 너무 길면 유휴 인스턴스에 계속 요금이 발생합니다. 비워 두면 백엔드 기본값을 사용합니다.',dockerImage: 'Docker image',+ dockerHost: 'Docker daemon endpoint',+ dockerHostHelp: 'Empty follows the local docker CLI (DOCKER_HOST or the current docker context), so you do not have to type /var/run/docker.sock. For a remote daemon use tcp://host:2376, fill in the TLS certificate directory, and turn on "allow private endpoints" for RFC1918 addresses.',+ dockerTlsCertPath: 'TLS certificate directory',+ dockerTlsCertPathHelp: 'Directory on the WeKnora host holding ca.pem, cert.pem and key.pem. Required for a remote daemon; certificates are mounted by the deployment, never stored here.',+ dockerIdleTtl: 'Idle reclaim (seconds)',+ dockerIdleTtlHelp: 'The Docker daemon has no idle timeout of its own. A container that runs no command for this long is reclaimed by WeKnora and rebuilt when the session continues. Empty means 1800 seconds.',+ dockerCpuLimit: 'CPU cores',+ dockerMemoryLimit: 'Memory limit (MB)',+ dockerPidsLimit: 'Process limit',+ dockerResourceHelp: 'Caps for one sandbox container. Empty means 2 cores / 2048 MB / 512 processes.',+ dockerNetworkMode: 'Network mode',+ dockerNetworkModeHelp: 'Defaults to bridge, which skills need to install packages. Choose none for no egress at all. Docker filters by network only; per-domain rules are not possible here.',+ dockerNetworkBridge: 'bridge (egress allowed)',+ dockerNetworkNone: 'none (no egress)',defaultTimeout: 'Execution timeout (s)',defaultTimeoutHelp: '스킬 스크립트 한 번이 실행될 수 있는 최대 시간이며, 초과하면 강제 종료됩니다. 비워 두면 60초입니다.',envVars: 'Environment variables',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 758bddd1d..eb1a6e73f 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -4913,7 +4913,7 @@ export default {backendDescriptions: {cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',e2b: 'Managed MicroVM service or an E2B-compatible deployment',- docker: 'Run every script in a short-lived container on this WeKnora host',+ docker: 'Держит долгоживущий контейнер на каждую сессию на этом хосте WeKnora; скрипты и файлы остаются в том же контейнере',local: 'Run scripts directly in the WeKnora server process environment',},addConfig: 'Add sandbox backend',@@ -4964,7 +4964,7 @@ export default {namedBackendHint: 'Workspace configuration is the only runtime source. Agents without one cannot execute skill scripts.',weknoraTemplateTitle: 'WeKnora standard template',weknoraDockerImage: 'WeKnora standard image',- weknoraDockerImageHint: 'Each execution starts an isolated, short-lived container from this image. No session sandbox is retained.',+ weknoraDockerImageHint: 'Each session gets its own long-lived container. Scripts, shell commands and files all share it until the session ends or the idle timeout reclaims it.',localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',@@ -5036,6 +5036,20 @@ export default {sandboxTtl: 'Sandbox TTL (s)',sandboxTtlHelp: 'Сколько простаивающая песочница живёт до освобождения провайдером. Слишком мало — при продолжении сессии её придётся создавать заново, слишком много — простаивающие экземпляры продолжают тарифицироваться. Пусто — значение бэкенда по умолчанию.',dockerImage: 'Docker image',+ dockerHost: 'Docker daemon endpoint',+ dockerHostHelp: 'Empty follows the local docker CLI (DOCKER_HOST or the current docker context), so you do not have to type /var/run/docker.sock. For a remote daemon use tcp://host:2376, fill in the TLS certificate directory, and turn on "allow private endpoints" for RFC1918 addresses.',+ dockerTlsCertPath: 'TLS certificate directory',+ dockerTlsCertPathHelp: 'Directory on the WeKnora host holding ca.pem, cert.pem and key.pem. Required for a remote daemon; certificates are mounted by the deployment, never stored here.',+ dockerIdleTtl: 'Idle reclaim (seconds)',+ dockerIdleTtlHelp: 'The Docker daemon has no idle timeout of its own. A container that runs no command for this long is reclaimed by WeKnora and rebuilt when the session continues. Empty means 1800 seconds.',+ dockerCpuLimit: 'CPU cores',+ dockerMemoryLimit: 'Memory limit (MB)',+ dockerPidsLimit: 'Process limit',+ dockerResourceHelp: 'Caps for one sandbox container. Empty means 2 cores / 2048 MB / 512 processes.',+ dockerNetworkMode: 'Network mode',+ dockerNetworkModeHelp: 'Defaults to bridge, which skills need to install packages. Choose none for no egress at all. Docker filters by network only; per-domain rules are not possible here.',+ dockerNetworkBridge: 'bridge (egress allowed)',+ dockerNetworkNone: 'none (no egress)',defaultTimeout: 'Execution timeout (s)',defaultTimeoutHelp: 'Максимальное время одного запуска скрипта навыка; по истечении он прерывается. Пусто — 60 секунд.',envVars: 'Environment variables',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 71ace7aaf..1fc5ca194 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -4915,7 +4915,7 @@ export default {backendDescriptions: {cube: '适合私有化或内网部署的自建 MicroVM 集群',e2b: 'E2B 托管服务或兼容 E2B 的集群',- docker: '每次在当前 WeKnora 主机启动一个短生命周期容器执行脚本',+ docker: '在本机 Docker 上为每个会话保留一个长驻容器,脚本和文件都落在同一容器里',local: '直接在 WeKnora 服务进程所在环境执行脚本',},addConfig: '添加沙箱后端',@@ -4966,7 +4966,7 @@ export default {namedBackendHint: '空间配置是唯一运行时来源;智能体没有选择配置时不会执行技能脚本。',weknoraTemplateTitle: 'WeKnora 标准模板',weknoraDockerImage: 'WeKnora 标准镜像',- weknoraDockerImageHint: '每次执行都会基于该镜像创建一个隔离的短生命周期容器,不保留会话沙箱。',+ weknoraDockerImageHint: '每次会话独占一个长驻容器,脚本、shell 命令与文件都在同一个容器内,会话结束或空闲超时后回收。',localRuntimeWarning: '本地进程会直接在 WeKnora 服务器上执行技能脚本,不具备容器或 MicroVM 隔离。仅建议在可信的开发空间使用。',weknoraTemplateOverview: 'WeKnora 负责提供标准运行环境。连接集群后会自动发现模板,缺少标准模板时自动创建。',weknoraTemplateDescription: '包含 WeKnora 技能所需的 Python、Node.js、CLI 工具、工作目录和非 root 执行用户。',@@ -5038,6 +5038,20 @@ export default {sandboxTtl: '沙箱 TTL(秒)',sandboxTtlHelp: '沙箱空闲多久后被远端回收。设得太短,会话继续时要重建沙箱;设得太长,闲置实例会一直计费。留空按后端默认值。',dockerImage: 'Docker 镜像',+ dockerHost: 'Docker 守护进程地址',+ dockerHostHelp: '留空跟随本机 docker CLI(DOCKER_HOST 或当前 docker context),不必手填 /var/run/docker.sock。远程守护进程填 tcp://host:2376,必须同时填写 TLS 证书目录,私网地址还要开启「允许访问私网地址」。',+ dockerTlsCertPath: 'TLS 证书目录',+ dockerTlsCertPathHelp: 'WeKnora 所在主机上包含 ca.pem、cert.pem、key.pem 的目录。远程守护进程必填,证书不入库,由部署方挂载。',+ dockerIdleTtl: '空闲回收(秒)',+ dockerIdleTtlHelp: 'Docker 守护进程本身没有空闲超时。容器多久没有执行任何命令就会被 WeKnora 回收,会话继续时重建。留空按 1800 秒。',+ dockerCpuLimit: 'CPU 核数上限',+ dockerMemoryLimit: '内存上限(MB)',+ dockerPidsLimit: '进程数上限',+ dockerResourceHelp: '单个沙箱容器的资源上限。留空按 2 核 / 2048 MB / 512 进程。',+ dockerNetworkMode: '网络模式',+ dockerNetworkModeHelp: '默认 bridge,技能安装依赖需要出网。选择 none 表示完全禁止出网。Docker 只能按网络隔离,无法按域名放行。',+ dockerNetworkBridge: 'bridge(允许出网)',+ dockerNetworkNone: 'none(禁止出网)',defaultTimeout: '执行超时(秒)',defaultTimeoutHelp: '单次技能脚本允许运行的最长时间,超时会被强制终止。留空按 60 秒。',envVars: '环境变量',diff --git a/go.mod b/go.modindex 027edf539..af63f9d73 100644--- a/go.mod+++ b/go.mod@@ -100,6 +100,7 @@ require (git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 // indirectgithub.com/JohannesKaufmann/dom v0.2.0 // indirectgithub.com/KyleBanks/depth v1.2.1 // indirect+ github.com/Microsoft/go-winio v0.6.2 // indirectgithub.com/andybalholm/brotli v1.2.0 // indirectgithub.com/andybalholm/cascadia v1.3.3 // indirectgithub.com/apache/arrow-go/v18 v18.5.1 // indirect@@ -137,11 +138,15 @@ require (github.com/cockroachdb/logtags v0.0.0-20211118104740-dabe8e521a4f // indirectgithub.com/cockroachdb/redact v1.1.3 // indirectgithub.com/containerd/cgroups/v3 v3.0.3 // indirect+ github.com/containerd/errdefs v1.0.0 // indirect+ github.com/containerd/errdefs/pkg v0.3.0 // indirectgithub.com/coreos/go-semver v0.3.0 // indirectgithub.com/coreos/go-systemd/v22 v22.3.2 // indirectgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirectgithub.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect+ github.com/distribution/reference v0.6.0 // indirectgithub.com/dlclark/regexp2 v1.11.5 // indirect+ github.com/docker/go-connections v0.7.0 // indirectgithub.com/docker/go-units v0.5.0 // indirectgithub.com/duckdb/duckdb-go-bindings v0.10502.0 // indirectgithub.com/duckdb/duckdb-go-bindings/lib/darwin-amd64 v0.10502.0 // indirect@@ -243,11 +248,16 @@ require (github.com/minio/md5-simd v1.1.2 // indirectgithub.com/mitchellh/mapstructure v1.5.0 // indirectgithub.com/mmcdole/goxpp v1.1.1-0.20240225020742-a0c311522b23 // indirect+ github.com/moby/docker-image-spec v1.3.1 // indirect+ github.com/moby/moby/api v1.55.0 // indirect+ github.com/moby/moby/client v0.5.1 // indirectgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirectgithub.com/modern-go/reflect2 v1.0.2 // indirectgithub.com/mozillazg/go-httpheader v0.2.1 // indirectgithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirectgithub.com/oklog/ulid/v2 v2.1.1 // indirect+ github.com/opencontainers/go-digest v1.0.0 // indirect+ github.com/opencontainers/image-spec v1.1.1 // indirectgithub.com/opencontainers/runtime-spec v1.0.2 // indirectgithub.com/parquet-go/bitpack v1.0.0 // indirectgithub.com/parquet-go/jsonlite v1.0.0 // indirectdiff --git a/go.sum b/go.sumindex 76771c861..0eeb7bc83 100644--- a/go.sum+++ b/go.sum@@ -2317,6 +2317,10 @@ github.com/mmcdole/goxpp v1.1.1-0.20240225020742-a0c311522b23 h1:Zr92CAlFhy2gL+Vgithub.com/mmcdole/goxpp v1.1.1-0.20240225020742-a0c311522b23/go.mod h1:v+25+lT2ViuQ7mVxcncQ8ch1URund48oH+jhjiwEgS8=github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=+github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc=+github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=+github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw=+github.com/moby/moby/client v0.5.1/go.mod h1:odLstlZ6uSnfvAgVxMpvgmb8SUdd+siH2T0GBuxVAlM=github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=diff --git a/internal/agent/tools/definitions.go b/internal/agent/tools/definitions.goindex e964fbf87..b0a3659c8 100644--- a/internal/agent/tools/definitions.go+++ b/internal/agent/tools/definitions.go@@ -31,10 +31,10 @@ const (ToolListSandboxFiles = "list_sandbox_files"ToolReadSandboxFile = "read_sandbox_file"// ToolShellExec lets the LLM execute ad-hoc shell commands inside the- // current session's Cube sandbox (dependency installs, environment- // probing). Only registered when the sandbox backend is Cube — Docker- // and Local backends do not expose this tool to preserve their- // existing stateless security model.+ // current session's sandbox (dependency installs, environment probing).+ // Registered only when the resolved backend advertises the session shell+ // capability — every session-scoped backend does (Cube, E2B, Docker); the+ // Local backend does not, so ad-hoc commands never reach the host.ToolShellExec = "shell_exec"// Wiki-related tools (only available when wiki KBs are in scope)ToolWikiReadPage = "wiki_read_page"diff --git a/internal/application/service/session.go b/internal/application/service/session.goindex f0c6d5abf..40a4aa228 100644--- a/internal/application/service/session.go+++ b/internal/application/service/session.go@@ -656,10 +656,10 @@ func (s *sessionService) DeleteAllSessions(ctx context.Context) error {// destroyBoundSandbox tears down the sandbox MicroVM bound to sessionID, if// the configured sandbox backend supports session-scoped instances.//-// Only SessionBoundManager (the CubeSandbox backend) implements the-// DestroySession method. For Docker/Local/Disabled backends the type assertion-// fails and the call is a no-op — those backends are stateless per Execute-// and hold no resources keyed on session ID.+// Only SessionBoundManager implements the DestroySession method, which every+// session-scoped backend resolves to (Cube, E2B, Docker). For Local/Disabled+// the type assertion fails and the call is a no-op — those backends are+// stateless per Execute and hold no resources keyed on session ID.//// Errors are logged but never propagated: sandbox teardown must not block// session deletion. Call this while the session row is still live so thediff --git a/internal/application/service/session_attachment_staging.go b/internal/application/service/session_attachment_staging.goindex ecc4cbaf9..205fd8f45 100644--- a/internal/application/service/session_attachment_staging.go+++ b/internal/application/service/session_attachment_staging.go@@ -60,7 +60,7 @@ type sessionAttachmentStager interface {//// Callers must gate staging on this rather than on the process-wide manager: a// different workspace configs expose different capabilities. Remote backends-// need attachment staging; stateless Docker/Local backends do not advertise a+// need attachment staging; the stateless Local backend does not advertise a// session filesystem at all.func (s *agentService) sessionSandboxInputStore(ctx context.Context,diff --git a/internal/application/service/tenant_sandbox_config.go b/internal/application/service/tenant_sandbox_config.goindex 516370f2f..f6e9b5ec6 100644--- a/internal/application/service/tenant_sandbox_config.go+++ b/internal/application/service/tenant_sandbox_config.go@@ -410,9 +410,19 @@ func (s *TenantSandboxConfigService) QueryTemplates(if strings.TrimSpace(merged.E2B.TemplateID) == "" {merged.E2B.TemplateID = "__catalog__"}+ case string(sandbox.SandboxTypeDocker):+ // Docker's template is an image, and the catalog step is where the+ // admin picks one. The standard image stands in until they do, so the+ // effective-config validation below has something to accept.+ if merged.Docker == nil {+ merged.Docker = &types.DockerSandboxConfig{}+ }+ if strings.TrimSpace(merged.Docker.Image) == "" {+ merged.Docker.Image = sandbox.DefaultDockerImage+ }default:return nil, apperrors.NewBadRequestError(- "sandbox template catalog only supports cube and e2b backends")+ "sandbox template catalog only supports cube, e2b and docker backends")}for _, endpoint := range sandboxConfigEndpoints(merged) {@@ -707,7 +717,7 @@ func (s *TenantSandboxConfigService) clientFor(return nil, err}switch effective.Type {- case sandbox.SandboxTypeCube, sandbox.SandboxTypeE2B:+ case sandbox.SandboxTypeCube, sandbox.SandboxTypeE2B, sandbox.SandboxTypeDocker:return s.newClient(effective)default:return nil, nildiff --git a/internal/handler/sandbox_check.go b/internal/handler/sandbox_check.goindex 7a06406f4..8f5936ed0 100644--- a/internal/handler/sandbox_check.go+++ b/internal/handler/sandbox_check.go@@ -144,7 +144,7 @@ func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {}result := &SandboxCheckResponse{OK: true, Provider: string(effective.Type)}- if effective.Type == sandbox.SandboxTypeDocker || effective.Type == sandbox.SandboxTypeLocal {+ if effective.Type == sandbox.SandboxTypeLocal {h.runStatelessSandboxCheck(ctx, effective, req.Deep, result)c.JSON(http.StatusOK, gin.H{"success": true, "data": result})return@@ -256,13 +256,6 @@ func (h *SystemHandler) runStatelessSandboxCheck(return}defer func() { _ = os.RemoveAll(dir) }()- // Docker executes as a non-root user that differs from the WeKnora process- // owner. The isolated bind-mount directory and probe must be traversable and- // readable by that user.- if err := os.Chmod(dir, 0o755); err != nil {- result.add("sandbox_exec", false, err.Error(), 0)- return- }path := filepath.Join(dir, "check.sh")const script = "#!/bin/sh\nprintf 'weknora-ok\\n'\n"if err := os.WriteFile(path, []byte(script), 0o644); err != nil {@@ -290,27 +283,18 @@ func (h *SystemHandler) runStatelessSandboxCheck(result.add("sandbox_exec", false, "沙箱没有返回执行结果", latency)return}- message := describeProbeMismatch(+ result.add("sandbox_exec", false, describeProbeMismatch(execResult.ExitCode, execResult.Killed,execResult.Stdout, execResult.Stderr, execResult.Error,- )- if cfg.Type == sandbox.SandboxTypeDocker && probeScriptWasInvisible(execResult.Stderr) {- message += ";容器没有看到挂载进去的脚本,请确认 Docker 运行时共享了目录 " + dir +- "(Docker Desktop / colima 需要在文件共享设置里包含该路径)"- }- result.add("sandbox_exec", false, message, latency)+ ), latency)return}result.add("sandbox_exec", true, "", latency)}-// createProbeStagingDir makes the directory the probe script is bind-mounted-// from. The OS temp dir looks like the obvious home for it but is the wrong-// choice for Docker: on macOS runtimes $TMPDIR lives under /var/folders, which-// the Docker VM does not share, so the mount arrives empty and the probe fails-// where real skill runs — staged under the process working directory, next to-// skills/ — succeed. Stage where the real scripts live and fall back to the temp-// dir only when the working directory is not writable.+// createProbeStagingDir makes the directory the local probe script is written+// to. It stays next to the real skill scripts under the process working+// directory and only falls back to the temp dir when that is not writable.func createProbeStagingDir() (string, error) {if wd, err := os.Getwd(); err == nil {if dir, err := os.MkdirTemp(wd, ".weknora-sandbox-check-*"); err == nil {@@ -320,17 +304,6 @@ func createProbeStagingDir() (string, error) {return os.MkdirTemp("", "weknora-sandbox-check-*")}-// probeScriptWasInvisible reports whether the interpreter could not find the-// script at all, which for Docker means the bind mount never carried it into-// the container rather than anything being wrong with the image.-func probeScriptWasInvisible(stderr string) bool {- lowered := strings.ToLower(stderr)- return strings.Contains(lowered, "check.sh") &&- (strings.Contains(lowered, "no such file") ||- strings.Contains(lowered, "not found") ||- strings.Contains(lowered, "cannot open"))-}-// describeProbeMismatch reports why the probe script did not print its marker.// "命令输出与预期不符" on its own hides the exit code and the stderr line that// normally name the actual problem — a missing interpreter, an image entrypoint@@ -587,6 +560,33 @@ func shellSingleQuote(s string) string {return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"}+func dockerUnavailableCheckReason(err *sandbox.RemoteError) string {+ host := dockerHostFromUnavailableMessage(err.Message)+ if host == "" {+ detail := firstProbeLine(err.Message)+ if detail == "" {+ return "无法连接 Docker 守护进程"+ }+ return "无法连接 Docker 守护进程:" + detail+ }+ return "无法连接 Docker 守护进程 " + host ++ "。留空地址时跟随本机 docker CLI(DOCKER_HOST 或当前 docker context)。" ++ "Colima 一般是 unix://$HOME/.colima/default/docker.sock;" ++ "WeKnora 跑在容器里时需要把该 socket 挂进 app。"+}++func dockerHostFromUnavailableMessage(message string) string {+ const prefix = "Cannot connect to the Docker daemon at "+ rest, ok := strings.CutPrefix(message, prefix)+ if !ok {+ return ""+ }+ if end := strings.IndexAny(rest, " \t"); end > 0 {+ rest = rest[:end]+ }+ return strings.TrimSuffix(strings.TrimSpace(rest), ".")+}+// sandboxCheckReason turns a provider error into a readable cause using the// adapter's normalized RemoteError.Kind, so the UI never shows raw SDK text.func sandboxCheckReason(err error) string {@@ -605,6 +605,9 @@ func sandboxCheckReason(err error) string {case sandbox.RemoteErrorKindTimeout:return "请求超时:端点不可达或响应过慢"case sandbox.RemoteErrorKindUnavailable:+ if remoteErr.Provider == sandbox.SandboxTypeDocker {+ return dockerUnavailableCheckReason(remoteErr)+ }return "服务不可用:端点拒绝连接"case sandbox.RemoteErrorKindCapacity:return "配额不足或触发限流"diff --git a/internal/handler/sandbox_check_test.go b/internal/handler/sandbox_check_test.goindex e61fb9198..1e0d3039b 100644--- a/internal/handler/sandbox_check_test.go+++ b/internal/handler/sandbox_check_test.go@@ -22,6 +22,16 @@ func TestSandboxConnectionCheckConfigAllowsTemplateDiscoveryAfterConnection(t *trequire.Empty(t, incoming.E2B.TemplateID, "the submitted form must not be mutated")}+func TestSandboxCheckReasonDockerUnavailableIncludesHost(t *testing.T) {+ msg := sandboxCheckReason(&sandbox.RemoteError{+ Kind: sandbox.RemoteErrorKindUnavailable,+ Provider: sandbox.SandboxTypeDocker,+ Message: "Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?",+ })+ require.Contains(t, msg, "unix:///var/run/docker.sock")+ require.Contains(t, msg, "docker context")+}+func TestRunStatelessSandboxCheckLocal(t *testing.T) {cfg := sandbox.DefaultConfig()cfg.Type = sandbox.SandboxTypeLocaldiff --git a/internal/sandbox/capabilities.go b/internal/sandbox/capabilities.goindex 95fbdf656..fc148c906 100644--- a/internal/sandbox/capabilities.go+++ b/internal/sandbox/capabilities.go@@ -23,8 +23,9 @@ import ()// SessionShellExecutor executes ad-hoc shell commands inside a session--// scoped remote sandbox. Local/Docker backends do not implement it; a-// SessionBoundManager only surfaces it while the remote backend is active.+// scoped remote sandbox. Local backends do not implement it; a+// SessionBoundManager only surfaces it while the remote backend is active+// (Cube, E2B, or Docker).type SessionShellExecutor interface {ExecShellCommand(ctx context.Context,diff --git a/internal/sandbox/config_identity.go b/internal/sandbox/config_identity.goindex 98fe2fb0a..16ff8e70a 100644--- a/internal/sandbox/config_identity.go+++ b/internal/sandbox/config_identity.go@@ -71,6 +71,15 @@ func IdentityOf(tenantCfg *types.TenantSandboxConfig) SandboxIdentity {identity.SandboxDomain = e2bCfg.SandboxDomainidentity.ProxyURL = e2bCfg.ProxyURL}+ case SandboxTypeDocker:+ // The daemon endpoint is both planes at once: containers are created,+ // exec'd and deleted over the same socket, so re-pointing it strands+ // every sandbox this config owns. The image is not part of the+ // identity — changing it only affects sandboxes created afterwards.+ if docker := tenantCfg.Docker; docker != nil {+ identity.APIURL = docker.Host+ identity.APIKey = docker.TLSCertPath+ }}return identity}diff --git a/internal/sandbox/docker.go b/internal/sandbox/docker.godeleted file mode 100644index 9f34b6773..000000000--- a/internal/sandbox/docker.go+++ /dev/null@@ -1,222 +0,0 @@-package sandbox--import (- "bytes"- "context"- "fmt"- "os/exec"- "path/filepath"- "strings"- "time"-)--// DockerSandbox implements the Sandbox interface using Docker containers-type DockerSandbox struct {- config *Config-}--// NewDockerSandbox creates a new Docker-based sandbox-func NewDockerSandbox(config *Config) *DockerSandbox {- if config == nil {- config = DefaultConfig()- }- if config.DockerImage == "" {- config.DockerImage = DefaultDockerImage- }- return &DockerSandbox{- config: config,- }-}--// Type returns the sandbox type-func (s *DockerSandbox) Type() SandboxType {- return SandboxTypeDocker-}--// IsAvailable checks if Docker is available-func (s *DockerSandbox) IsAvailable(ctx context.Context) bool {- cmd := exec.CommandContext(ctx, "docker", "version")- if err := cmd.Run(); err != nil {- return false- }- return true-}--// Execute runs a script in a Docker container-func (s *DockerSandbox) Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error) {- if config == nil {- return nil, ErrInvalidScript- }-- // Set default timeout- timeout := config.Timeout- if timeout == 0 {- timeout = s.config.DefaultTimeout- }- if timeout == 0 {- timeout = DefaultTimeout- }-- // Create context with timeout- execCtx, cancel := context.WithTimeout(ctx, timeout)- defer cancel()- // Managers are resolved from workspace configuration on demand, so an- // asynchronous pre-pull would race the first execution and start duplicate- // pulls on every resolve. Make image readiness part of the execution result.- if err := s.EnsureImage(execCtx); err != nil {- return nil, err- }-- // Build docker run command- args := s.buildDockerArgs(config)-- startTime := time.Now()- cmd := exec.CommandContext(execCtx, "docker", args...)-- var stdout, stderr bytes.Buffer- cmd.Stdout = &stdout- cmd.Stderr = &stderr-- if config.Stdin != "" {- cmd.Stdin = strings.NewReader(config.Stdin)- }-- err := cmd.Run()- duration := time.Since(startTime)-- result := &ExecuteResult{- Stdout: stdout.String(),- Stderr: stderr.String(),- Duration: duration,- }-- if err != nil {- if execCtx.Err() == context.DeadlineExceeded {- result.Killed = true- result.Error = ErrTimeout.Error()- result.ExitCode = -1- } else if exitErr, ok := err.(*exec.ExitError); ok {- result.ExitCode = exitErr.ExitCode()- } else {- result.Error = err.Error()- result.ExitCode = -1- }- }-- return result, nil-}--// buildDockerArgs constructs the docker run command arguments-func (s *DockerSandbox) buildDockerArgs(config *ExecuteConfig) []string {- args := []string{"run", "--rm"}-- // Security: run as non-root user- args = append(args, "--user", "1000:1000")-- // Security: drop all capabilities- args = append(args, "--cap-drop", "ALL")-- // Security: read-only root filesystem (optional)- if config.ReadOnlyRootfs {- args = append(args, "--read-only")- // Add writable tmp directory- args = append(args, "--tmpfs", "/tmp:rw,noexec,nosuid,size=64m")- }-- // Resource limits- memLimit := config.MemoryLimit- if memLimit == 0 {- memLimit = s.config.MaxMemory- }- if memLimit > 0 {- args = append(args, "--memory", fmt.Sprintf("%d", memLimit))- args = append(args, "--memory-swap", fmt.Sprintf("%d", memLimit)) // Disable swap- }-- cpuLimit := config.CPULimit- if cpuLimit == 0 {- cpuLimit = s.config.MaxCPU- }- if cpuLimit > 0 {- args = append(args, "--cpus", fmt.Sprintf("%.2f", cpuLimit))- }-- // Network isolation- if !config.AllowNetwork {- args = append(args, "--network", "none")- }-- // Security: disable privileged mode and limit PIDs- args = append(args, "--pids-limit", "100")- args = append(args, "--security-opt", "no-new-privileges")-- // Mount the script and working directory as read-only- scriptDir := filepath.Dir(config.Script)- args = append(args, "-v", fmt.Sprintf("%s:/workspace:ro", scriptDir))-- // Working directory- args = append(args, "-w", "/workspace")-- // Environment variables- for key, value := range config.Env {- args = append(args, "-e", fmt.Sprintf("%s=%s", key, value))- }-- // Image- args = append(args, s.config.DockerImage)-- // Script execution command- scriptName := filepath.Base(config.Script)- interpreter := getInterpreter(scriptName)-- args = append(args, interpreter, scriptName)- args = append(args, config.Args...)-- return args-}--// getInterpreter returns the appropriate interpreter for a script-func getInterpreter(scriptName string) string {- ext := strings.ToLower(filepath.Ext(scriptName))- switch ext {- case ".py":- return "python3"- case ".sh", ".bash":- return "bash"- case ".js":- return "node"- case ".rb":- return "ruby"- case ".pl":- return "perl"- default:- return "sh"- }-}--// ImageExists checks if the configured Docker image exists locally-func (s *DockerSandbox) ImageExists(ctx context.Context) bool {- cmd := exec.CommandContext(ctx, "docker", "image", "inspect", s.config.DockerImage)- return cmd.Run() == nil-}--// EnsureImage pulls the Docker image if it doesn't exist locally.-func (s *DockerSandbox) EnsureImage(ctx context.Context) error {- if s.ImageExists(ctx) {- return nil- }- cmd := exec.CommandContext(ctx, "docker", "pull", s.config.DockerImage)- var stderr bytes.Buffer- cmd.Stderr = &stderr- if err := cmd.Run(); err != nil {- return fmt.Errorf("failed to pull image %s: %w (%s)", s.config.DockerImage, err, stderr.String())- }- return nil-}--// Cleanup removes any lingering resources-func (s *DockerSandbox) Cleanup(ctx context.Context) error {- // Docker --rm flag should handle container cleanup- // This is here for any additional cleanup if needed- return nil-}diff --git a/internal/sandbox/docker_engine.go b/internal/sandbox/docker_engine.gonew file mode 100644index 000000000..9609ee25b--- /dev/null+++ b/internal/sandbox/docker_engine.go@@ -0,0 +1,459 @@+// Docker Engine plumbing for the docker backend.+//+// This file owns everything between WeKnora and the Docker Engine API that is+// not sandbox semantics: the narrow interface the adapter talks to (so unit+// tests need no daemon), how a daemon connection is built and shared, and how+// Engine errors are classified into the provider-neutral RemoteErrorKind.+//+// Connections are pooled per daemon endpoint. Managers are rebuilt on every+// request (see tenant_resolver.go), and each moby client owns an HTTP+// transport, so constructing one per request would leak a connection pool per+// request.++package sandbox++import (+ "context"+ "errors"+ "fmt"+ "net"+ "path/filepath"+ "strings"+ "sync"+ "time"++ cerrdefs "github.com/containerd/errdefs"+ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/client"+)++// dockerEngineAPI is the slice of the Docker Engine API the sandbox adapter+// uses. It exists so tests can drive the adapter without a daemon; the real+// implementation is *client.Client, which satisfies it as-is.+type dockerEngineAPI interface {+ Ping(ctx context.Context, options client.PingOptions) (client.PingResult, error)++ ContainerCreate(ctx context.Context, options client.ContainerCreateOptions) (client.ContainerCreateResult, error)+ ContainerStart(+ ctx context.Context, containerID string, options client.ContainerStartOptions,+ ) (client.ContainerStartResult, error)+ ContainerUnpause(+ ctx context.Context, containerID string, options client.ContainerUnpauseOptions,+ ) (client.ContainerUnpauseResult, error)+ ContainerInspect(+ ctx context.Context, containerID string, options client.ContainerInspectOptions,+ ) (client.ContainerInspectResult, error)+ ContainerList(ctx context.Context, options client.ContainerListOptions) (client.ContainerListResult, error)+ ContainerRemove(+ ctx context.Context, containerID string, options client.ContainerRemoveOptions,+ ) (client.ContainerRemoveResult, error)++ ExecCreate(+ ctx context.Context, containerID string, options client.ExecCreateOptions,+ ) (client.ExecCreateResult, error)+ ExecAttach(ctx context.Context, execID string, options client.ExecAttachOptions) (client.ExecAttachResult, error)+ ExecInspect(ctx context.Context, execID string, options client.ExecInspectOptions) (client.ExecInspectResult, error)++ CopyToContainer(+ ctx context.Context, containerID string, options client.CopyToContainerOptions,+ ) (client.CopyToContainerResult, error)+ CopyFromContainer(+ ctx context.Context, containerID string, options client.CopyFromContainerOptions,+ ) (client.CopyFromContainerResult, error)+ ContainerStatPath(+ ctx context.Context, containerID string, options client.ContainerStatPathOptions,+ ) (client.ContainerStatPathResult, error)++ ImageInspect(+ ctx context.Context, imageID string, opts ...client.ImageInspectOption,+ ) (client.ImageInspectResult, error)+ ImagePull(ctx context.Context, refStr string, options client.ImagePullOptions) (client.ImagePullResponse, error)+ ImageList(ctx context.Context, options client.ImageListOptions) (client.ImageListResult, error)+}++var _ dockerEngineAPI = (*client.Client)(nil)++// DefaultDockerHost is the last-resort daemon endpoint when the config, the+// DOCKER_HOST environment variable, and the current docker CLI context are+// all empty. Linux installs typically expose this socket; macOS tools such+// as Colima do not.+const DefaultDockerHost = "unix:///var/run/docker.sock"++// DefaultDockerHTTPTimeout bounds a single short Engine API call (ping, create,+// inspect, list, delete, exec create/inspect). Streaming calls — image pull,+// exec hijack, archive copy — use the caller's context instead, because+// http.Client.Timeout would kill them mid-body.+const DefaultDockerHTTPTimeout = 30 * time.Second++// DefaultDockerIdleTTL is how long a session container may go without an exec+// before the idle sweep reclaims it. The daemon has no TTL of its own, so this+// is the only thing standing between an abandoned session and a container that+// lives until the host runs out of memory.+const DefaultDockerIdleTTL = 30 * time.Minute++// DefaultDockerMemoryLimit / DefaultDockerCPULimit / DefaultDockerPidsLimit are+// the per-sandbox resource ceilings applied when a config names none. They are+// deliberately larger than the stateless backend's old 256MB/1CPU: a session+// container hosts a whole turn's work (package installs, data processing),+// not one short script.+const (+ DefaultDockerMemoryLimit int64 = 2 * 1024 * 1024 * 1024+ DefaultDockerCPULimit = 2.0+ DefaultDockerPidsLimit int64 = 512+)++// dockerSandboxCapabilities are granted back after CapDrop=ALL.+//+// Everything Docker grants by default that a sandbox does not need is left+// dropped (NET_RAW, NET_BIND_SERVICE, MKNOD, SYS_CHROOT, AUDIT_WRITE,+// SETPCAP, SETFCAP). What remains is what a root-run package installer needs:+// CHOWN/DAC_OVERRIDE/FOWNER/FSETID for writing into image-owned directories+// and fixing up ownership, SETUID/SETGID because apt and pip drop privileges+// while unpacking, KILL so a supervisor can stop its own children.+var dockerSandboxCapabilities = []string{+ "CHOWN", "DAC_OVERRIDE", "FOWNER", "FSETID", "SETGID", "SETUID", "KILL",+}++// dockerEngineClientPool hands out one shared client per daemon endpoint.+type dockerEngineClientPool struct {+ mu sync.Mutex+ clients map[string]*client.Client+}++// sharedDockerEngineClients is process-wide on purpose: two tenant configs+// pointing at the same daemon should share one connection pool, and the check+// endpoint builds throwaway configs that must not each open their own.+var sharedDockerEngineClients = &dockerEngineClientPool{+ clients: make(map[string]*client.Client),+}++// dockerEndpoint is the identity of a daemon connection. Two configs with+// equal endpoints may share a client.+type dockerEndpoint struct {+ Host string++ // TLSCertPath is a directory holding ca.pem / cert.pem / key.pem, the+ // layout Docker's own DOCKER_CERT_PATH uses. Empty means plain HTTP,+ // which is only acceptable for a local unix socket.+ TLSCertPath string++ // AllowPrivate mirrors the config's outbound policy. It is part of the+ // endpoint identity because it changes the dialer this client installs:+ // sharing a pooled client between a permissive and a restrictive config+ // would hand the restrictive one a connection it is not allowed to make.+ AllowPrivate bool++ Timeout time.Duration+}++func (e dockerEndpoint) key() string {+ // Timeout is applied per RPC, not on the HTTP client, so two configs+ // that differ only in HTTP timeout still share one connection pool.+ return fmt.Sprintf("%s|%s|%t", e.Host, e.TLSCertPath, e.AllowPrivate)+}++// get returns the shared client for endpoint, building it on first use.+func (p *dockerEngineClientPool) get(endpoint dockerEndpoint) (*client.Client, error) {+ key := endpoint.key()+ p.mu.Lock()+ defer p.mu.Unlock()+ if existing, ok := p.clients[key]; ok {+ return existing, nil+ }+ built, err := newDockerEngineClient(endpoint)+ if err != nil {+ return nil, err+ }+ p.clients[key] = built+ return built, nil+}++// newDockerEngineClient builds a moby client for one endpoint.+//+// API version negotiation is deliberately not performed here: it costs a+// round-trip against a daemon that may be down, and it would happen inside+// whatever request first touches the pool. The client's default version is+// negotiated lazily by the moby client itself on the first call.+func newDockerEngineClient(endpoint dockerEndpoint) (*client.Client, error) {+ host := strings.TrimSpace(endpoint.Host)+ if host == "" {+ host = DetectLocalDockerHost()+ }++ // Do not set http.Client.Timeout. It covers the entire response body,+ // so a cold image pull or a file copy longer than the RPC budget is+ // killed mid-stream. Short calls are bounded by withDockerRPCTimeout;+ // pulls, exec hijacks and archive streams honour the caller's context.+ opts := []client.Opt{+ client.WithHost(host),+ }+ if endpoint.TLSCertPath != "" {+ // Certificates stay on the application host rather than in the+ // workspace config: they are deployment infrastructure, and keeping+ // them out of the database keeps them out of backups and API+ // responses. The daemon certificate is always verified — a remote+ // daemon accepts container creation, so an unauthenticated peer on+ // that socket is a root shell on the sandbox host.+ certPath := endpoint.TLSCertPath+ opts = append(opts, client.WithTLSClientConfig(+ filepath.Join(certPath, "ca.pem"),+ filepath.Join(certPath, "cert.pem"),+ filepath.Join(certPath, "key.pem"),+ ))+ }++ // A TCP daemon address is a tenant-supplied endpoint like any other, so it+ // gets the same dial-time guard every other backend gets: saving the config+ // validates the address it was given, but a hostname can resolve to a public+ // address then and to 169.254.169.254 when the connection is actually made.+ // Reaching a private daemon stays possible through the config's own+ // "allow private endpoints" switch. Must come after WithHost, which+ // installs its own dialer.+ if dockerHostNeedsDialGuard(host) {+ opts = append(opts, client.WithDialContext((&net.Dialer{+ Timeout: 10 * time.Second,+ KeepAlive: 30 * time.Second,+ Control: SafeDialControlForPolicy(OutboundURLPolicy{AllowPrivate: endpoint.AllowPrivate}),+ }).DialContext))+ }++ built, err := client.New(opts...)+ if err != nil {+ return nil, fmt.Errorf("sandbox: build docker client for %s: %w", host, err)+ }+ return built, nil+}++// dockerHostNeedsDialGuard reports whether host is a network endpoint whose+// dials must pass the outbound policy. Unix sockets are local to the WeKnora+// process and carry no address to check.+func dockerHostNeedsDialGuard(host string) bool {+ scheme, _, found := strings.Cut(strings.TrimSpace(host), "://")+ if !found {+ return false+ }+ switch strings.ToLower(scheme) {+ case "tcp", "http", "https":+ return true+ default:+ return false+ }+}++// ValidateDockerHost checks a daemon endpoint before it is stored or dialled.+//+// A TCP endpoint gets the same outbound treatment as any other workspace-+// supplied URL: a daemon socket accepts container creation, so an admin who+// can point it anywhere can make WeKnora talk to an arbitrary internal+// service. Unix sockets are local by definition and only have to be absolute.+func ValidateDockerHost(host string, allowPrivate bool) error {+ trimmed := strings.TrimSpace(host)+ if trimmed == "" {+ return nil+ }+ scheme, address, found := strings.Cut(trimmed, "://")+ if !found {+ return fmt.Errorf(+ "sandbox: docker host %q must include a scheme (unix:// or tcp://)", host)+ }+ switch strings.ToLower(scheme) {+ case "unix":+ if !strings.HasPrefix(address, "/") {+ return fmt.Errorf("sandbox: docker unix socket path %q must be absolute", address)+ }+ return nil+ case "tcp", "http", "https":+ // The guard speaks HTTP; the daemon's TCP endpoint is an HTTP+ // endpoint, so the check is the same one every other backend gets.+ return ValidateOutboundURLWithPolicy(+ "http://"+address, OutboundURLPolicy{AllowPrivate: allowPrivate},+ )+ default:+ return fmt.Errorf("sandbox: unsupported docker host scheme %q", scheme)+ }+}++// ValidateDockerRemoteTLS requires client certificates for a TCP daemon.+// A remote Engine API that accepts container creation is a root shell on+// that host; plaintext tcp://2375 is not an acceptable way to reach it.+// Unix sockets are local to the WeKnora process and do not use TLS.+func ValidateDockerRemoteTLS(host, tlsCertPath string) error {+ trimmed := strings.TrimSpace(host)+ if trimmed == "" {+ return nil+ }+ scheme, _, found := strings.Cut(trimmed, "://")+ if !found {+ return nil+ }+ switch strings.ToLower(scheme) {+ case "tcp", "http", "https":+ if strings.TrimSpace(tlsCertPath) == "" {+ return fmt.Errorf(+ "sandbox: remote docker host %q requires a TLS certificate directory", host)+ }+ }+ return nil+}++// ValidateDockerNetworkMode allows only bridge (egress) and none (no egress).+//+// host and container: modes share another namespace outright, which would put+// sandbox code on the WeKnora host's or a sibling container's network. A+// user-defined network name is refused for the weaker but equally real version+// of the same problem: the usual deployment reaches its daemon through the+// mounted docker.sock, so naming the deployment's own compose network would+// place a sandbox on the same L3 network as Postgres and Redis. Only the+// operator can judge what a given named network exposes, and this value is set+// per workspace config, so it is not theirs to choose.+func ValidateDockerNetworkMode(mode string) error {+ trimmed := strings.TrimSpace(mode)+ if trimmed == "" {+ return nil+ }+ switch strings.ToLower(trimmed) {+ case "bridge", "none":+ return nil+ }+ return fmt.Errorf(+ "sandbox: docker network mode %q is not allowed; use \"bridge\" or \"none\"",+ mode)+}++// dockerErrorKind classifies an Engine API error. The moby client tags its+// errors with containerd's errdefs, which is a far more reliable signal than+// the message text.+func dockerErrorKind(op string, err error) RemoteErrorKind {+ switch {+ case err == nil:+ return ""+ case errors.Is(err, context.DeadlineExceeded), cerrdefs.IsDeadlineExceeded(err):+ return RemoteErrorKindTimeout+ case cerrdefs.IsNotFound(err):+ // A missing image on create is a bad template, not a vanished sandbox:+ // classifying it as NotFound would tell the lifecycle it may rebind.+ if op == "Create" {+ return RemoteErrorKindInvalidRequest+ }+ return RemoteErrorKindNotFound+ case cerrdefs.IsUnauthorized(err), cerrdefs.IsPermissionDenied(err):+ return RemoteErrorKindAuthentication+ case cerrdefs.IsInvalidArgument(err):+ return RemoteErrorKindInvalidRequest+ case cerrdefs.IsNotImplemented(err):+ return RemoteErrorKindUnsupported+ case cerrdefs.IsConflict(err), cerrdefs.IsAlreadyExists(err):+ return RemoteErrorKindConflict+ case cerrdefs.IsResourceExhausted(err):+ return RemoteErrorKindCapacity+ case cerrdefs.IsUnavailable(err), client.IsErrConnectionFailed(err):+ return RemoteErrorKindUnavailable+ default:+ return RemoteErrorKindInternal+ }+}++// dockerError wraps an Engine API error as a RemoteError.+func dockerError(op string, err error) error {+ if err == nil {+ return nil+ }+ var existing *RemoteError+ if errors.As(err, &existing) {+ return err+ }+ return &RemoteError{+ Kind: dockerErrorKind(op, err),+ Provider: SandboxTypeDocker,+ Op: op,+ Message: err.Error(),+ Cause: err,+ }+}++// dockerInvalidRequest reports a caller-side mistake that never reached the+// daemon (an unusable path, an unsupported request shape).+func dockerInvalidRequest(op, message string) error {+ return &RemoteError{+ Kind: RemoteErrorKindInvalidRequest,+ Provider: SandboxTypeDocker,+ Op: op,+ Message: message,+ }+}++// awaitImagePull waits for a pull to finish. The daemon only performs the+// transfer while its progress stream is being consumed, so a caller that+// closes the body early aborts the pull.+func awaitImagePull(ctx context.Context, body client.ImagePullResponse) error {+ if body == nil {+ return nil+ }+ defer func() { _ = body.Close() }()+ return body.Wait(ctx)+}++// dockerStateOf normalizes a container state string. "exited" is deliberately+// NOT terminal: a stopped container keeps its filesystem and Connect restarts+// it, which is the closest Docker gets to E2B's pause + auto-resume.+func dockerStateOf(status container.ContainerState) RemoteSandboxState {+ switch strings.ToLower(strings.TrimSpace(string(status))) {+ case "running":+ return RemoteStateRunning+ case "paused", "exited", "created":+ return RemoteStatePaused+ case "restarting", "removing":+ return RemoteStateTransitioning+ case "dead":+ return RemoteStateTerminal+ case "":+ return RemoteStateUnknown+ default:+ return RemoteStateUnknown+ }+}++// dockerContainerLabels projects sandbox metadata onto container labels and+// stamps the ownership marker every sweep relies on.+func dockerContainerLabels(metadata map[string]string) map[string]string {+ labels := make(map[string]string, len(metadata)+1)+ for key, value := range metadata {+ labels[key] = value+ }+ labels[dockerManagedLabel] = "true"+ return labels+}++// dockerSandboxMetadata is the inverse of dockerContainerLabels: it strips the+// ownership marker so callers see exactly the metadata they supplied.+func dockerSandboxMetadata(labels map[string]string) map[string]string {+ if labels == nil {+ return nil+ }+ metadata := make(map[string]string, len(labels))+ for key, value := range labels {+ if key == dockerManagedLabel {+ continue+ }+ metadata[key] = value+ }+ return metadata+}++// dockerManagedLabel marks every container this backend creates. Sweeps filter+// on it so a WeKnora deployment sharing a daemon with other workloads can+// never delete a container it does not own.+const dockerManagedLabel = "com.weknora.sandbox.managed"++// dockerContainerStartedAt parses the daemon's RFC3339Nano timestamps, which+// are the zero value string "0001-01-01T00:00:00Z" when unset.+func dockerContainerStartedAt(state *container.State) time.Time {+ if state == nil {+ return time.Time{}+ }+ parsed, err := time.Parse(time.RFC3339Nano, state.StartedAt)+ if err != nil {+ return time.Time{}+ }+ return parsed.UTC()+}diff --git a/internal/sandbox/docker_host.go b/internal/sandbox/docker_host.gonew file mode 100644index 000000000..74c69ed63--- /dev/null+++ b/internal/sandbox/docker_host.go@@ -0,0 +1,100 @@+package sandbox++import (+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+)++// DetectLocalDockerHost returns the daemon endpoint the Docker CLI would use+// on this machine when the workspace config leaves the host blank: DOCKER_HOST+// first, then the current docker context, then DefaultDockerHost.+//+// /var/run/docker.sock is the Linux default and is often absent on macOS+// (Colima, Docker Desktop, OrbStack each expose a socket under $HOME). An+// operator who can run `docker ps` should not have to copy that path into+// the settings form.+func DetectLocalDockerHost() string {+ if host := strings.TrimSpace(os.Getenv("DOCKER_HOST")); host != "" {+ return host+ }+ if host := dockerCLIContextHost(); host != "" {+ return host+ }+ return DefaultDockerHost+}++func dockerCLIContextHost() string {+ configDir := strings.TrimSpace(os.Getenv("DOCKER_CONFIG"))+ if configDir == "" {+ home, err := os.UserHomeDir()+ if err != nil || home == "" {+ return ""+ }+ configDir = filepath.Join(home, ".docker")+ }++ name := strings.TrimSpace(os.Getenv("DOCKER_CONTEXT"))+ if name == "" {+ name = dockerCurrentContextName(configDir)+ }+ if name == "" || name == "default" {+ return ""+ }++ entries, err := os.ReadDir(filepath.Join(configDir, "contexts", "meta"))+ if err != nil {+ return ""+ }+ for _, entry := range entries {+ if !entry.IsDir() {+ continue+ }+ host := dockerContextHost(+ filepath.Join(configDir, "contexts", "meta", entry.Name(), "meta.json"),+ name,+ )+ if host != "" {+ return host+ }+ }+ return ""+}++func dockerCurrentContextName(configDir string) string {+ body, err := os.ReadFile(filepath.Join(configDir, "config.json"))+ if err != nil {+ return ""+ }+ var parsed struct {+ CurrentContext string `json:"currentContext"`+ }+ if err := json.Unmarshal(body, &parsed); err != nil {+ return ""+ }+ return strings.TrimSpace(parsed.CurrentContext)+}++func dockerContextHost(metaPath, wantName string) string {+ body, err := os.ReadFile(metaPath)+ if err != nil {+ return ""+ }+ var parsed struct {+ Name string `json:"Name"`+ Endpoints map[string]struct {+ Host string `json:"Host"`+ } `json:"Endpoints"`+ }+ if err := json.Unmarshal(body, &parsed); err != nil {+ return ""+ }+ if parsed.Name != wantName {+ return ""+ }+ if parsed.Endpoints == nil {+ return ""+ }+ return strings.TrimSpace(parsed.Endpoints["docker"].Host)+}diff --git a/internal/sandbox/docker_host_test.go b/internal/sandbox/docker_host_test.gonew file mode 100644index 000000000..5eb9218bd--- /dev/null+++ b/internal/sandbox/docker_host_test.go@@ -0,0 +1,47 @@+package sandbox++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestDetectLocalDockerHostPrefersEnv(t *testing.T) {+ t.Setenv("DOCKER_HOST", "unix:///tmp/from-env.sock")+ t.Setenv("DOCKER_CONTEXT", "colima")+ require.Equal(t, "unix:///tmp/from-env.sock", DetectLocalDockerHost())+}++func TestDetectLocalDockerHostUsesCurrentContext(t *testing.T) {+ t.Setenv("DOCKER_HOST", "")+ t.Setenv("DOCKER_CONTEXT", "")+ dir := t.TempDir()+ t.Setenv("DOCKER_CONFIG", dir)++ require.NoError(t, os.MkdirAll(filepath.Join(dir, "contexts", "meta", "abc"), 0o755))+ require.NoError(t, os.WriteFile(filepath.Join(dir, "config.json"), []byte(+ `{"currentContext":"colima"}`,+ ), 0o644))+ meta, err := json.Marshal(map[string]any{+ "Name": "colima",+ "Endpoints": map[string]any{+ "docker": map[string]any{"Host": "unix:///tmp/colima.sock"},+ },+ })+ require.NoError(t, err)+ require.NoError(t, os.WriteFile(+ filepath.Join(dir, "contexts", "meta", "abc", "meta.json"), meta, 0o644,+ ))++ require.Equal(t, "unix:///tmp/colima.sock", DetectLocalDockerHost())+}++func TestDetectLocalDockerHostFallsBackToDefault(t *testing.T) {+ t.Setenv("DOCKER_HOST", "")+ t.Setenv("DOCKER_CONTEXT", "")+ t.Setenv("DOCKER_CONFIG", t.TempDir())+ require.Equal(t, DefaultDockerHost, DetectLocalDockerHost())+}diff --git a/internal/sandbox/docker_idle_sweeper.go b/internal/sandbox/docker_idle_sweeper.gonew file mode 100644index 000000000..10b4bbf7e--- /dev/null+++ b/internal/sandbox/docker_idle_sweeper.go@@ -0,0 +1,203 @@+// Idle reclamation for the docker backend.+//+// Every other backend gets this for free. Cube and E2B are told an idle+// timeout at creation and the provider pauses or kills the sandbox when it+// elapses, which is why SessionBoundManager never reaps anything itself. The+// Docker daemon has no such concept: a container runs until something stops+// it. Without a sweep, one abandoned session pins its memory and CPU share on+// the host forever.+//+// The sweep needs to know when a sandbox was last used, and Docker exposes no+// exec timestamps. Labels cannot help either — they are immutable after+// create. So each exec touches an activity marker file inside the container+// (folded into the exec wrapper, costing no extra round-trip), and the sweep+// reads its mtime with a single HEAD /archive call per container.+//+// Deleting an idle container needs no coordination with the binding store: the+// lifecycle already treats a sandbox the provider no longer has as replaceable+// (see CanReplaceRemoteBinding), which is exactly how an E2B sandbox reaped by+// its own TTL is handled.++package sandbox++import (+ "context"+ "log"+ "strconv"+ "sync"+ "time"++ "github.com/moby/moby/client"+)++// dockerIdleTTLLabel records the TTL each container was created with, so a+// sweep triggered by one workspace config never applies its own TTL to a+// container belonging to another.+const dockerIdleTTLLabel = "com.weknora.sandbox.idle-ttl-seconds"++// dockerSweepMinInterval bounds how often one daemon is swept, no matter how+// many requests trigger it. Sweeping is a list plus one stat per container;+// cheap, but not free enough to run on every execution.+const dockerSweepMinInterval = time.Minute++// dockerSweepBudget bounds one sweep so a wedged daemon cannot leave a+// goroutine hanging around forever.+const dockerSweepBudget = 2 * time.Minute++// dockerSweepThrottle records the last sweep per daemon endpoint. It is+// process-wide because the adapter is rebuilt per request; per-instance state+// would throttle nothing.+var dockerSweepThrottle = struct {+ mu sync.Mutex+ last map[string]time.Time+}{last: make(map[string]time.Time)}++// dockerIdleSweeper reclaims containers that have not executed anything for+// longer than their TTL.+type dockerIdleSweeper struct {+ client *DockerRemoteClient+ ttl time.Duration++ // now is injected by tests.+ now func() time.Time+}++func newDockerIdleSweeper(cli *DockerRemoteClient, ttl time.Duration) *dockerIdleSweeper {+ return &dockerIdleSweeper{client: cli, ttl: ttl, now: time.Now}+}++// trigger runs a sweep in the background unless one ran recently. It detaches+// from the caller's context so finishing the request does not abort the sweep,+// and it never reports failures upward: reclaiming storage must not turn a+// working execution into an error.+func (s *dockerIdleSweeper) trigger(ctx context.Context) {+ if s == nil || s.client == nil {+ return+ }+ if !s.claimSweep() {+ return+ }+ go func() {+ sweepCtx, cancel := context.WithTimeout(+ context.WithoutCancel(ctx), dockerSweepBudget,+ )+ defer cancel()+ if reclaimed, err := s.sweep(sweepCtx); err != nil {+ log.Printf("[sandbox] docker idle sweep failed: %v", err)+ } else if reclaimed > 0 {+ log.Printf("[sandbox] docker idle sweep reclaimed %d container(s)", reclaimed)+ }+ }()+}++// claimSweep reports whether this caller won the right to sweep now.+func (s *dockerIdleSweeper) claimSweep() bool {+ key := s.client.settings.Endpoint.key()+ now := s.now()+ dockerSweepThrottle.mu.Lock()+ defer dockerSweepThrottle.mu.Unlock()+ if last, ok := dockerSweepThrottle.last[key]; ok &&+ now.Sub(last) < dockerSweepMinInterval {+ return false+ }+ dockerSweepThrottle.last[key] = now+ return true+}++// sweep deletes every managed container idle beyond its own TTL and reports+// how many went away.+func (s *dockerIdleSweeper) sweep(ctx context.Context) (int, error) {+ summaries, err := s.client.List(ctx, RemoteListFilter{})+ if err != nil {+ return 0, err+ }+ reclaimed := 0+ for _, summary := range summaries {+ select {+ case <-ctx.Done():+ return reclaimed, ctx.Err()+ default:+ }+ if !s.isIdle(ctx, summary) {+ continue+ }+ // Re-check immediately before deleting. Listing every container and+ // stat'ing each one takes long enough on a busy daemon that a session+ // can be resumed in between, and deleting it then destroys a sandbox+ // the user is actively working in.+ if !s.isIdle(ctx, summary) {+ continue+ }+ if err := s.client.Delete(ctx, summary.ID); err != nil {+ // One undeletable container must not stop the sweep; the next+ // pass will try again.+ log.Printf("[sandbox] docker idle sweep: delete %s: %v", summary.ID, err)+ continue+ }+ reclaimed+++ }+ return reclaimed, nil+}++// isIdle decides whether one container has gone unused for longer than the+// TTL it was created with.+func (s *dockerIdleSweeper) isIdle(ctx context.Context, summary RemoteSandboxSummary) bool {+ ttl := s.ttlFor(summary)+ if ttl <= 0 {+ return false+ }+ lastUsed := s.lastActivity(ctx, summary)+ if lastUsed.IsZero() {+ // Neither a marker nor a creation timestamp: treating that as idle+ // would risk deleting a sandbox that is merely unreadable right now.+ return false+ }+ return s.now().UTC().Sub(lastUsed) > ttl+}++// ttlFor prefers the TTL stamped on the container at creation over this+// client's own configuration.+func (s *dockerIdleSweeper) ttlFor(summary RemoteSandboxSummary) time.Duration {+ if raw, ok := summary.Metadata[dockerIdleTTLLabel]; ok {+ if seconds, err := strconv.Atoi(raw); err == nil {+ return time.Duration(seconds) * time.Second+ }+ }+ return s.ttl+}++// lastActivity returns when the container last ran a command, falling back to+// when it started for a sandbox that has not executed anything yet.+//+// The marker lives inside the container and has to be writable by the+// unprivileged sandbox account, so its mtime is attacker-influenced: a script+// can `touch -d` it. A timestamp in the future is the one form of that which+// would disable reclamation permanently, so it is refused outright and the+// container falls back to its start time. Backdating only makes a sandbox look+// idle sooner, which costs the container that did it and nothing else.+func (s *dockerIdleSweeper) lastActivity(+ ctx context.Context,+ summary RemoteSandboxSummary,+) time.Time {+ stat, err := s.client.api.ContainerStatPath(ctx, summary.ID,+ client.ContainerStatPathOptions{Path: dockerActivityMarker})+ if err == nil && !stat.Stat.Mtime.IsZero() {+ marker := stat.Stat.Mtime.UTC()+ if marker.After(s.now().UTC().Add(dockerActivityClockSkew)) {+ log.Printf(+ "[sandbox] docker idle sweep: container %s reports activity at %s, "++ "which is in the future; falling back to its start time",+ summary.ID, marker.Format(time.RFC3339),+ )+ } else {+ return marker+ }+ }+ return summary.StartedAt.UTC()+}++// dockerActivityClockSkew is how far ahead of WeKnora the daemon's clock may+// run before a marker is treated as forged. The marker is stamped by the+// daemon host while the comparison happens here, and the two are not+// necessarily the same machine.+const dockerActivityClockSkew = 2 * time.Minutediff --git a/internal/sandbox/docker_idle_sweeper_test.go b/internal/sandbox/docker_idle_sweeper_test.gonew file mode 100644index 000000000..723bcd82b--- /dev/null+++ b/internal/sandbox/docker_idle_sweeper_test.go@@ -0,0 +1,206 @@+package sandbox++import (+ "context"+ "testing"+ "time"++ "github.com/moby/moby/api/types/container"+ "github.com/stretchr/testify/require"+)++// newSweeperFixture wires a sweeper over a fake daemon holding the given+// containers, with the activity marker of each one set from markers.+func newSweeperFixture(+ t *testing.T,+ ttl time.Duration,+ now time.Time,+ containers []container.Summary,+) (*dockerIdleSweeper, *fakeDockerEngine) {+ t.Helper()+ engine := newFakeDockerEngine()+ engine.list = containers+ docker := newTestDockerClient(t, engine)+ sweeper := newDockerIdleSweeper(docker, ttl)+ sweeper.now = func() time.Time { return now }+ return sweeper, engine+}++func TestDockerIdleSweeperReclaimsOnlyIdleContainers(t *testing.T) {+ now := time.Now().UTC()+ sweeper, engine := newSweeperFixture(t, 30*time.Minute, now, []container.Summary{+ {+ ID: "busy", State: "running", Created: now.Add(-4 * time.Hour).Unix(),+ Labels: map[string]string{dockerManagedLabel: "true"},+ },+ {+ ID: "idle", State: "running", Created: now.Add(-4 * time.Hour).Unix(),+ Labels: map[string]string{dockerManagedLabel: "true"},+ },+ })+ // The marker is what every exec touches; its mtime is the only record of+ // when a sandbox was last used.+ engine.statResult[dockerActivityMarker] = container.PathStat{Mtime: now.Add(-2 * time.Minute)}++ reclaimed, err := sweeper.sweep(context.Background())+ require.NoError(t, err)+ require.Zero(t, reclaimed, "a recently used sandbox must survive")+ require.Empty(t, engine.removed)++ engine.statResult[dockerActivityMarker] = container.PathStat{Mtime: now.Add(-90 * time.Minute)}+ reclaimed, err = sweeper.sweep(context.Background())+ require.NoError(t, err)+ require.Equal(t, 2, reclaimed)+ require.ElementsMatch(t, []string{"busy", "idle"}, engine.removed)+}++// A sandbox that has never executed anything has no marker, so its creation+// time decides. Without this a freshly created container would look infinitely+// idle and be deleted out from under the session that just created it.+func TestDockerIdleSweeperFallsBackToCreationTime(t *testing.T) {+ now := time.Now().UTC()+ sweeper, engine := newSweeperFixture(t, 30*time.Minute, now, []container.Summary{+ {+ ID: "fresh", State: "running", Created: now.Add(-time.Minute).Unix(),+ Labels: map[string]string{dockerManagedLabel: "true"},+ },+ })++ reclaimed, err := sweeper.sweep(context.Background())+ require.NoError(t, err)+ require.Zero(t, reclaimed)+ require.Empty(t, engine.removed)+}++// The marker has to be writable by the unprivileged sandbox account, so a+// script can backdate or postdate it. Postdating is the dangerous direction: a+// single `touch -d 2099-01-01` would otherwise exempt the container from+// reclamation forever.+func TestDockerIdleSweeperRejectsFutureActivityMarker(t *testing.T) {+ now := time.Now().UTC()+ sweeper, engine := newSweeperFixture(t, 30*time.Minute, now, []container.Summary{+ {+ ID: "forged", State: "running", Created: now.Add(-4 * time.Hour).Unix(),+ Labels: map[string]string{dockerManagedLabel: "true"},+ },+ })+ engine.statResult[dockerActivityMarker] = container.PathStat{+ Mtime: now.Add(100 * 365 * 24 * time.Hour),+ }++ reclaimed, err := sweeper.sweep(context.Background())+ require.NoError(t, err)+ require.Equal(t, 1, reclaimed,+ "a forged future marker must fall back to the container's start time")+ require.Equal(t, []string{"forged"}, engine.removed)+}++// A daemon on another host may run slightly ahead of WeKnora. That must not be+// mistaken for tampering, or every sandbox on that daemon would be judged by+// its start time alone and reclaimed mid-session.+func TestDockerIdleSweeperToleratesSmallClockSkew(t *testing.T) {+ now := time.Now().UTC()+ sweeper, engine := newSweeperFixture(t, 30*time.Minute, now, []container.Summary{+ {+ ID: "skewed", State: "running", Created: now.Add(-4 * time.Hour).Unix(),+ Labels: map[string]string{dockerManagedLabel: "true"},+ },+ })+ engine.statResult[dockerActivityMarker] = container.PathStat{+ Mtime: now.Add(dockerActivityClockSkew / 2),+ }++ reclaimed, err := sweeper.sweep(context.Background())+ require.NoError(t, err)+ require.Zero(t, reclaimed)+ require.Empty(t, engine.removed)+}++// Listing plus one stat per container is slow enough on a busy daemon that a+// session can be resumed in between. Deleting then would destroy a sandbox the+// user is working in, so the decision is re-taken right before the delete.+func TestDockerIdleSweeperRechecksActivityBeforeDeleting(t *testing.T) {+ now := time.Now().UTC()+ sweeper, engine := newSweeperFixture(t, 30*time.Minute, now, []container.Summary{+ {+ ID: "resumed", State: "running", Created: now.Add(-4 * time.Hour).Unix(),+ Labels: map[string]string{dockerManagedLabel: "true"},+ },+ })+ calls := 0+ engine.statHook = func(path string) (container.PathStat, bool) {+ if path != dockerActivityMarker {+ return container.PathStat{}, false+ }+ calls+++ if calls == 1 {+ return container.PathStat{Mtime: now.Add(-2 * time.Hour)}, true+ }+ return container.PathStat{Mtime: now.Add(-time.Second)}, true+ }++ reclaimed, err := sweeper.sweep(context.Background())+ require.NoError(t, err)+ require.Zero(t, reclaimed)+ require.Empty(t, engine.removed, "a sandbox used since the listing must survive")+ require.Equal(t, 2, calls)+}++// Each container carries the TTL it was created with, so a sweep triggered by+// one workspace config cannot apply its own TTL to another config's sandboxes.+func TestDockerIdleSweeperHonoursPerContainerTTL(t *testing.T) {+ now := time.Now().UTC()+ sweeper, engine := newSweeperFixture(t, time.Minute, now, []container.Summary{+ {+ ID: "long-ttl", State: "running", Created: now.Add(-2 * time.Hour).Unix(),+ Labels: map[string]string{+ dockerManagedLabel: "true",+ dockerIdleTTLLabel: "86400",+ },+ },+ })+ engine.statResult[dockerActivityMarker] = container.PathStat{Mtime: now.Add(-2 * time.Hour)}++ reclaimed, err := sweeper.sweep(context.Background())+ require.NoError(t, err)+ require.Zero(t, reclaimed)+ require.Empty(t, engine.removed)+}++// The sweep runs off the back of ordinary requests, so it must not turn into a+// list-plus-stat storm when a workspace is busy.+func TestDockerIdleSweeperThrottlesPerDaemon(t *testing.T) {+ now := time.Now().UTC()+ sweeper, _ := newSweeperFixture(t, time.Minute, now, nil)+ dockerSweepThrottle.mu.Lock()+ delete(dockerSweepThrottle.last, sweeper.client.settings.Endpoint.key())+ dockerSweepThrottle.mu.Unlock()++ require.True(t, sweeper.claimSweep(), "the first caller sweeps")+ require.False(t, sweeper.claimSweep(), "a second caller in the same minute does not")++ sweeper.now = func() time.Time { return now.Add(2 * dockerSweepMinInterval) }+ require.True(t, sweeper.claimSweep(), "the throttle expires")+}++// A container the daemon refuses to delete must not abort the pass: the rest+// of the idle set still has to be reclaimed.+func TestDockerIdleSweeperContinuesAfterDeleteFailure(t *testing.T) {+ now := time.Now().UTC()+ sweeper, engine := newSweeperFixture(t, time.Minute, now, []container.Summary{+ {+ ID: "wedged", State: "running", Created: now.Add(-2 * time.Hour).Unix(),+ Labels: map[string]string{dockerManagedLabel: "true"},+ },+ {+ ID: "reclaimable", State: "running", Created: now.Add(-2 * time.Hour).Unix(),+ Labels: map[string]string{dockerManagedLabel: "true"},+ },+ })+ engine.removeErr = context.DeadlineExceeded++ reclaimed, err := sweeper.sweep(context.Background())+ require.NoError(t, err)+ require.Zero(t, reclaimed)+ require.Len(t, engine.removed, 2, "every candidate is attempted")+}diff --git a/internal/sandbox/docker_integration_test.go b/internal/sandbox/docker_integration_test.gonew file mode 100644index 000000000..2d6f5922b--- /dev/null+++ b/internal/sandbox/docker_integration_test.go@@ -0,0 +1,448 @@+//go:build docker_integration++// Conformance test for the Docker backend against a real daemon.+//+// It drives the same public surface as the E2B-protocol conformance suite+// (session-scoped script execution, shell commands, attachment staging,+// artifact listing, timeouts, teardown), because the point of the docker+// backend is to be indistinguishable from a remote one at that level. Anything+// asserted here that the E2B suite also asserts is deliberate duplication: a+// backend that passes one and fails the other is not interchangeable.+//+// Run with a reachable daemon and the standard sandbox image:+//+// docker build -f docker/Dockerfile.sandbox -t wechatopenai/weknora-sandbox:dev .+// DOCKER_INTEGRATION_IMAGE=wechatopenai/weknora-sandbox:dev \+// go test -tags=docker_integration ./internal/sandbox \+// -run '^TestDocker.*Integration' -count=1 -v -timeout=15m+package sandbox++import (+ "bytes"+ "context"+ "fmt"+ "os"+ "path"+ "strings"+ "testing"+ "time"++ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/client"++ "github.com/Tencent/WeKnora/internal/types"+)++const dockerIntegrationTenantID = 1++func dockerIntegrationConfig(t *testing.T) *Config {+ t.Helper()+ image := strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_IMAGE"))+ if image == "" {+ t.Skip("DOCKER_INTEGRATION_IMAGE is required for the docker conformance suite")+ }+ cfg := DefaultConfig()+ cfg.Type = SandboxTypeDocker+ cfg.FallbackEnabled = false+ cfg.DockerImage = image+ cfg.DockerHost = strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_HOST"))+ cfg.DefaultTimeout = 2 * time.Minute+ applyDockerRuntimeDefaults(cfg)+ return cfg+}++func newDockerIntegrationManager(t *testing.T, cfg *Config) *SessionBoundManager {+ t.Helper()+ client, err := NewDockerRemoteClient(cfg)+ if err != nil {+ t.Fatalf("build docker client: %v", err)+ }+ probeCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()+ if err := client.Health(probeCtx); err != nil {+ t.Skipf("docker daemon unreachable: %v", err)+ }+ manager, err := NewSessionBoundManager(SessionBoundManagerConfig{+ Config: cfg,+ Client: client,+ Store: NewMemorySessionSandboxBindingStore(),+ Checker: PermissiveSessionExistenceChecker{},+ ConfigID: "docker-conformance",+ SkipHealthProbe: true,+ })+ if err != nil {+ t.Fatalf("NewSessionBoundManager: %v", err)+ }+ return manager+}++func TestDockerBackendConformanceIntegration(t *testing.T) {+ cfg := dockerIntegrationConfig(t)+ manager := newDockerIntegrationManager(t, cfg)++ ctx, cancel := context.WithTimeout(+ types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),+ 12*time.Minute,+ )+ defer cancel()++ sessionID := fmt.Sprintf("docker-conformance-%d", time.Now().UnixNano())+ t.Cleanup(func() {+ cleanupCtx, cleanupCancel := context.WithTimeout(+ types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),+ 2*time.Minute,+ )+ defer cleanupCancel()+ if err := manager.DestroySession(cleanupCtx, sessionID); err != nil {+ t.Errorf("DestroySession: %v", err)+ }+ })++ counterPath := path.Join(SessionOutputRoot, "counter.txt")+ t.Run("SessionScopedStatePersistsAcrossExecutions", func(t *testing.T) {+ first := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(`+with open(%q, 'w') as handle:+ handle.write('1')+print('wrote counter')+`, counterPath))+ if !first.IsSuccess() {+ t.Fatalf("first execution failed: %#v", first)+ }+ second := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(`+with open(%q) as handle:+ print('counter=' + handle.read())+`, counterPath))+ if !second.IsSuccess() || !strings.Contains(second.Stdout, "counter=1") {+ t.Fatalf("session state did not persist: %#v", second)+ }+ })++ t.Run("InstalledPackagesSurviveBetweenExecutions", func(t *testing.T) {+ install := runDockerScript(t, ctx, manager, sessionID, `+import subprocess+print(subprocess.run(+ ['pip', 'install', '--quiet', '--no-cache-dir', '--user', 'cowsay==6.1'],+ capture_output=True, text=True).returncode)+`)+ if !install.IsSuccess() {+ t.Fatalf("package install failed: %#v", install)+ }+ use := runDockerScript(t, ctx, manager, sessionID, `+import cowsay+print('cowsay-ok')+`)+ if !use.IsSuccess() || !strings.Contains(use.Stdout, "cowsay-ok") {+ t.Fatalf("installed package did not survive: %#v", use)+ }+ })++ t.Run("ShellExecSharesTheSessionSandbox", func(t *testing.T) {+ executor := manager.SessionShellExecutor()+ if executor == nil {+ t.Fatal("session shell executor is unavailable on a healthy docker backend")+ }+ result, err := executor.ExecShellCommand(+ ctx, sessionID, "cat "+counterPath, SessionWorkspaceRoot, time.Minute, nil,+ )+ if err != nil {+ t.Fatalf("ExecShellCommand: %v", err)+ }+ if !result.IsSuccess() || !strings.Contains(result.Stdout, "1") {+ t.Fatalf("shell command did not observe the session sandbox: %#v", result)+ }+ })++ t.Run("AttachmentStagingAndArtifactCollection", func(t *testing.T) {+ files := manager.SessionFileStore()+ if files == nil {+ t.Fatal("session file store is unavailable on a healthy docker backend")+ }+ inputPath := path.Join(SessionInputRoot, "attachment.txt")+ payload := []byte("attachment payload\n")+ if err := files.WriteSessionInputFile(ctx, sessionID, inputPath, payload); err != nil {+ t.Fatalf("WriteSessionInputFile: %v", err)+ }+ content, err := files.ReadSessionFile(ctx, sessionID, inputPath)+ if err != nil {+ t.Fatalf("ReadSessionFile: %v", err)+ }+ if !bytes.Equal(content, payload) {+ t.Fatalf("staged attachment mismatch: got=%q want=%q", content, payload)+ }++ result := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(`+import os+target = os.path.join(os.environ['%s'], 'report.txt')+with open(target, 'w') as handle:+ handle.write('artifact body')+print('artifact written')+`, skillOutputEnvVar))+ if !result.IsSuccess() {+ t.Fatalf("artifact-producing execution failed: %#v", result)+ }++ entries, err := files.ListSessionFiles(ctx, sessionID, SessionOutputRoot)+ if err != nil {+ t.Fatalf("ListSessionFiles: %v", err)+ }+ found := false+ for _, entry := range entries {+ if entry.Name == "report.txt" {+ found = true+ }+ }+ if !found {+ t.Fatalf("artifact directory did not contain report.txt: %#v", entries)+ }+ if err := files.RemoveSessionInputPath(ctx, sessionID, inputPath); err != nil {+ t.Fatalf("RemoveSessionInputPath: %v", err)+ }+ })++ t.Run("TimeoutIsReportedAsKilled", func(t *testing.T) {+ result := runDockerScriptWithTimeout(t, ctx, manager, sessionID, `+import time+time.sleep(60)+`, 5*time.Second)+ if !result.Killed {+ t.Fatalf("expected a killed result for an over-running script: %#v", result)+ }+ })++ // The daemon does not stop a process when the client goes away, so the+ // only proof that a timeout means anything is that nothing is left running.+ t.Run("TimeoutActuallyStopsTheProcess", func(t *testing.T) {+ executor := manager.SessionShellExecutor()+ _, err := executor.ExecShellCommand(+ ctx, sessionID, "sleep 120", SessionWorkspaceRoot, 3*time.Second, nil,+ )+ if err != nil {+ t.Fatalf("ExecShellCommand: %v", err)+ }+ time.Sleep(2 * time.Second)+ // Count processes whose command line is exactly "sleep 120", which the+ // probe's own shell cannot match.+ const probe = `n=0; for p in /proc/[0-9]*; do ` ++ `cmd=$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null); ` ++ `case "$cmd" in "sleep 120 ") n=$((n+1));; esac; done; echo "$n"`+ survivors, err := executor.ExecShellCommand(+ ctx, sessionID, probe, SessionWorkspaceRoot, 30*time.Second, nil,+ )+ if err != nil {+ t.Fatalf("survivor probe: %v", err)+ }+ if got := strings.TrimSpace(survivors.Stdout); got != "0" {+ t.Fatalf("timeout left %s 'sleep 120' process(es) running: %#v", got, survivors)+ }+ })+}++// The idle sweeper reclaims a container by the mtime of its activity marker,+// and skill scripts run as the unprivileged sandbox user. A session that only+// ever runs scripts must still count as active, or it gets deleted underneath+// the user who is actively using it.+func TestDockerBackendScriptExecutionRefreshesActivityMarkerIntegration(t *testing.T) {+ cfg := dockerIntegrationConfig(t)+ manager := newDockerIntegrationManager(t, cfg)++ ctx, cancel := context.WithTimeout(+ types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),+ 5*time.Minute,+ )+ defer cancel()++ sessionID := fmt.Sprintf("docker-activity-%d", time.Now().UnixNano())+ t.Cleanup(func() {+ cleanupCtx, cleanupCancel := context.WithTimeout(+ types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),+ time.Minute,+ )+ defer cleanupCancel()+ _ = manager.DestroySession(cleanupCtx, sessionID)+ })++ first := runDockerScript(t, ctx, manager, sessionID, `print('one')`)+ if !first.IsSuccess() {+ t.Fatalf("first execution failed: %#v", first)+ }+ client, err := NewDockerRemoteClient(cfg)+ if err != nil {+ t.Fatalf("build docker client: %v", err)+ }+ summaries, err := client.List(ctx, RemoteListFilter{+ Metadata: map[string]string{remoteMetadataSessionID: sessionID},+ })+ if err != nil || len(summaries) != 1 {+ t.Fatalf("expected exactly one container: %v %#v", err, summaries)+ }+ handle, err := client.Connect(ctx, summaries[0].ID)+ if err != nil {+ t.Fatalf("Connect: %v", err)+ }+ // The container entrypoint makes the marker world-writable on purpose.+ // Leaving it to whatever umask the daemon happens to run with would work+ // on a host with umask 000 and silently stop tracking script executions on+ // a host with umask 022.+ if mode := dockerActivityMarkerStat(t, ctx, summaries[0].ID).Mode.Perm(); mode != 0o666 {+ t.Fatalf("activity marker is %v, want 0666 so both root and %s can refresh it",+ mode, DefaultSandboxExecUser)+ }+ before := dockerActivityMarkerMTime(t, ctx, summaries[0].ID)++ // Exec directly as the unprivileged account, with no root-run step in+ // between: WeKnora happens to prepare the artifact directory as root+ // before each script today, and leaning on that would let the marker+ // silently stop tracking the account that actually runs user code.+ // The marker has one-second resolution on most filesystems.+ time.Sleep(2 * time.Second)+ result, err := client.Exec(ctx, handle, RemoteExecRequest{+ Command: "echo",+ Args: []string{"as-sandbox-user"},+ User: DefaultSandboxExecUser,+ Timeout: 30 * time.Second,+ })+ if err != nil || result.ExitCode != 0 {+ t.Fatalf("exec as %s failed: %v %#v", DefaultSandboxExecUser, err, result)+ }+ after := dockerActivityMarkerMTime(t, ctx, summaries[0].ID)++ if !after.After(before) {+ t.Fatalf("an exec as %s did not refresh the activity marker: before=%s after=%s",+ DefaultSandboxExecUser, before, after)+ }+}++func dockerActivityMarkerMTime(t *testing.T, ctx context.Context, containerID string) time.Time {+ t.Helper()+ return dockerActivityMarkerStat(t, ctx, containerID).Mtime+}++func dockerActivityMarkerStat(+ t *testing.T, ctx context.Context, containerID string,+) container.PathStat {+ t.Helper()+ api, err := sharedDockerEngineClients.get(dockerEndpoint{+ Host: strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_HOST")),+ Timeout: DefaultDockerHTTPTimeout,+ })+ if err != nil {+ t.Fatalf("docker client: %v", err)+ }+ stat, err := api.ContainerStatPath(ctx, containerID,+ client.ContainerStatPathOptions{Path: dockerActivityMarker})+ if err != nil {+ t.Fatalf("stat activity marker: %v", err)+ }+ return stat.Stat+}++// A session must survive the container being stopped underneath it: the+// filesystem is intact, so Connect restarts it rather than losing the state.+func TestDockerBackendResumesStoppedContainerIntegration(t *testing.T) {+ cfg := dockerIntegrationConfig(t)+ manager := newDockerIntegrationManager(t, cfg)++ ctx, cancel := context.WithTimeout(+ types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),+ 5*time.Minute,+ )+ defer cancel()++ sessionID := fmt.Sprintf("docker-resume-%d", time.Now().UnixNano())+ t.Cleanup(func() {+ cleanupCtx, cleanupCancel := context.WithTimeout(+ types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID),+ time.Minute,+ )+ defer cleanupCancel()+ _ = manager.DestroySession(cleanupCtx, sessionID)+ })++ marker := path.Join(SessionOutputRoot, "resume.txt")+ first := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(`+with open(%q, 'w') as handle:+ handle.write('before-stop')+print('ok')+`, marker))+ if !first.IsSuccess() {+ t.Fatalf("seed execution failed: %#v", first)+ }++ client, err := NewDockerRemoteClient(cfg)+ if err != nil {+ t.Fatalf("build docker client: %v", err)+ }+ summaries, err := client.List(ctx, RemoteListFilter{+ Metadata: map[string]string{remoteMetadataSessionID: sessionID},+ })+ if err != nil || len(summaries) != 1 {+ t.Fatalf("expected exactly one container for the session: %v %#v", err, summaries)+ }++ // Stop it the way a host reboot or an operator would.+ stopCtx, stopCancel := context.WithTimeout(ctx, time.Minute)+ defer stopCancel()+ if err := stopDockerContainerForTest(stopCtx, summaries[0].ID); err != nil {+ t.Fatalf("stop container: %v", err)+ }++ second := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(`+with open(%q) as handle:+ print('restored=' + handle.read())+`, marker))+ if !second.IsSuccess() || !strings.Contains(second.Stdout, "restored=before-stop") {+ t.Fatalf("session did not resume with its filesystem: %#v", second)+ }+}++// stopDockerContainerForTest stops a container behind the adapter's back, the+// way a host reboot or an operator with a shell would.+func stopDockerContainerForTest(ctx context.Context, id string) error {+ api, err := sharedDockerEngineClients.get(dockerEndpoint{+ Host: strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_HOST")),+ Timeout: DefaultDockerHTTPTimeout,+ })+ if err != nil {+ return err+ }+ grace := 5+ _, err = api.ContainerStop(ctx, id, client.ContainerStopOptions{Timeout: &grace})+ return err+}++func runDockerScript(+ t *testing.T,+ ctx context.Context,+ manager *SessionBoundManager,+ sessionID, source string,+) *ExecuteResult {+ t.Helper()+ return runDockerScriptWithTimeout(t, ctx, manager, sessionID, source, 3*time.Minute)+}++func runDockerScriptWithTimeout(+ t *testing.T,+ ctx context.Context,+ manager *SessionBoundManager,+ sessionID, source string,+ timeout time.Duration,+) *ExecuteResult {+ t.Helper()+ result, err := manager.Execute(ctx, &ExecuteConfig{+ Script: "conformance.py",+ ScriptContent: source,+ SessionID: sessionID,+ Timeout: timeout,+ SkipValidation: true,+ Env: map[string]string{skillOutputEnvVar: SessionOutputRoot},+ })+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ if result == nil {+ t.Fatal("Execute returned no result")+ }+ t.Logf("execute exit=%d killed=%v stdout=%q stderr=%q err=%q",+ result.ExitCode, result.Killed, result.Stdout, result.Stderr, result.Error)+ return result+}diff --git a/internal/sandbox/docker_remote_client.go b/internal/sandbox/docker_remote_client.gonew file mode 100644index 000000000..22e51a56f--- /dev/null+++ b/internal/sandbox/docker_remote_client.go@@ -0,0 +1,1089 @@+// Docker backend as a session-persistent RemoteSandboxClient.+//+// One sandbox is one long-lived container: PID 1 sleeps, and every script,+// shell command and file operation runs against that container until the+// session ends or the idle sweep reclaims it. That is what makes the docker+// backend behave like the E2B one — same session state, same shell_exec, same+// attachment staging — instead of the previous one-shot `docker run --rm`,+// which could not keep anything between two executions.+//+// The mapping onto the Engine API:+//+// Create → POST /containers/create + /start, metadata as labels+// Connect → GET /containers/{id}/json, restarting a stopped container+// Get/List → GET /containers/json?filters=label=…+// Delete → DELETE /containers/{id}?force=1+// Exec → POST /containers/{id}/exec → /exec/{id}/start (hijack)+// Files → PUT/GET/HEAD /containers/{id}/archive+//+// Three operations have no Engine API and are implemented as exec:+// MakeDir, Remove and ListDir. ListDir uses `find -printf`, which needs GNU+// findutils in the image; the standard WeKnora sandbox image provides it.+//+// Two Docker facts shape the rest of this file:+//+// - Cancelling an exec client-side does NOT stop the process inside the+// container. Every exec is therefore wrapped in the container's own+// timeout(1), which is the only thing that actually kills a runaway script.+// - The daemon has no idle timeout. Each exec refreshes an activity marker+// file (for free, inside the same wrapper) that dockerIdleSweeper reads to+// decide what to reclaim.++package sandbox++import (+ "archive/tar"+ "bytes"+ "context"+ "errors"+ "fmt"+ "io"+ "path"+ "strconv"+ "strings"+ "time"++ "github.com/moby/moby/api/pkg/stdcopy"+ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/client"+)++// dockerActivityMarker is touched by every exec and read by the idle sweeper.+// It lives outside /workspace so a script cannot mistake it for its own data,+// and outside /tmp so a tmpfs mount cannot hide it.+const dockerActivityMarker = "/var/lib/weknora-sandbox-activity"++// dockerSandboxEntrypoint keeps the container alive without running anything —+// the container is a place to exec into, not a service — and prepares the+// activity marker on the way.+//+// The marker has to be writable by every account that can exec, because+// scripts run as the unprivileged sandbox user while shell commands and+// filesystem helpers run as root. Creating it here, in the container's own+// entrypoint, is the only way to get that without spending an extra API round+// trip per sandbox: whoever PID 1 runs as owns the file, and the chmod that+// follows lets the other account refresh it. Without this the idle sweeper+// would see a session that only ever ran scripts as untouched, and reclaim it+// out from under the user.+var dockerSandboxEntrypoint = []string{+ "/bin/sh", "-c",+ "touch " + dockerActivityMarker + " 2>/dev/null; " ++ "chmod 666 " + dockerActivityMarker + " 2>/dev/null; " ++ "exec sleep infinity",+}++// DockerRemoteClient implements RemoteSandboxClient on top of one Docker+// daemon. It is safe for concurrent use: the moby client is, and this type+// holds no mutable state.+type DockerRemoteClient struct {+ api dockerEngineAPI+ settings dockerRuntimeSettings++ // sweeper reclaims idle containers. Nil disables idle reclamation, which+ // is only appropriate for the connectivity-check client.+ sweeper *dockerIdleSweeper+}++// dockerRuntimeSettings is the per-config slice of Config the adapter reads.+type dockerRuntimeSettings struct {+ Image string+ CPULimit float64+ MemoryBytes int64+ PidsLimit int64+ NetworkMode string+ Runtime string+ IdleTTL time.Duration+ HTTPTimeout time.Duration+ Endpoint dockerEndpoint+}++// NewDockerRemoteClient builds the adapter for one workspace config, reusing+// the shared connection to that daemon.+func NewDockerRemoteClient(cfg *Config) (*DockerRemoteClient, error) {+ settings, err := dockerSettingsFromConfig(cfg)+ if err != nil {+ return nil, err+ }+ api, err := sharedDockerEngineClients.get(settings.Endpoint)+ if err != nil {+ return nil, err+ }+ return newDockerRemoteClientWithAPI(withDockerRPCTimeout(api, settings.HTTPTimeout), settings), nil+}++// NewDockerRemoteClientForCheck builds a client for the connectivity check.+//+// It differs from the resolved client in one way: no idle sweeping. A probe+// runs against a config an admin is still editing, and a half-finished config+// must never delete containers a working config owns.+func NewDockerRemoteClientForCheck(cfg *Config) (*DockerRemoteClient, error) {+ settings, err := dockerSettingsFromConfig(cfg)+ if err != nil {+ return nil, err+ }+ api, err := sharedDockerEngineClients.get(settings.Endpoint)+ if err != nil {+ return nil, err+ }+ settings.IdleTTL = 0+ return newDockerRemoteClientWithAPI(withDockerRPCTimeout(api, settings.HTTPTimeout), settings), nil+}++// newDockerRemoteClientWithAPI is the seam unit tests use: it takes any+// dockerEngineAPI, including an in-memory fake.+func newDockerRemoteClientWithAPI(+ api dockerEngineAPI,+ settings dockerRuntimeSettings,+) *DockerRemoteClient {+ adapter := &DockerRemoteClient{api: api, settings: settings}+ if settings.IdleTTL > 0 {+ adapter.sweeper = newDockerIdleSweeper(adapter, settings.IdleTTL)+ }+ return adapter+}++// dockerSettingsFromConfig projects Config, applying the built-in defaults for+// every value the workspace config leaves unset.+func dockerSettingsFromConfig(cfg *Config) (dockerRuntimeSettings, error) {+ if cfg == nil {+ return dockerRuntimeSettings{}, errors.New("sandbox: docker client requires a config")+ }+ image := strings.TrimSpace(cfg.DockerImage)+ if image == "" {+ return dockerRuntimeSettings{}, errors.New("sandbox: docker backend requires an image")+ }+ settings := dockerRuntimeSettings{+ Image: image,+ CPULimit: cfg.DockerCPULimit,+ MemoryBytes: cfg.DockerMemoryBytes,+ PidsLimit: cfg.DockerPidsLimit,+ NetworkMode: strings.TrimSpace(cfg.DockerNetworkMode),+ Runtime: strings.TrimSpace(cfg.DockerRuntime),+ IdleTTL: cfg.DockerIdleTTL,+ HTTPTimeout: cfg.DockerHTTPTimeout,+ Endpoint: dockerEndpoint{+ Host: strings.TrimSpace(cfg.DockerHost),+ TLSCertPath: strings.TrimSpace(cfg.DockerTLSCertPath),+ AllowPrivate: cfg.AllowPrivateEndpoints,+ Timeout: cfg.DockerHTTPTimeout,+ },+ }+ if settings.CPULimit <= 0 {+ settings.CPULimit = DefaultDockerCPULimit+ }+ if settings.MemoryBytes <= 0 {+ settings.MemoryBytes = DefaultDockerMemoryLimit+ }+ if settings.PidsLimit <= 0 {+ settings.PidsLimit = DefaultDockerPidsLimit+ }+ if settings.IdleTTL <= 0 {+ settings.IdleTTL = DefaultDockerIdleTTL+ }+ if settings.HTTPTimeout <= 0 {+ settings.HTTPTimeout = DefaultDockerHTTPTimeout+ settings.Endpoint.Timeout = DefaultDockerHTTPTimeout+ }+ if err := ValidateDockerNetworkMode(settings.NetworkMode); err != nil {+ return dockerRuntimeSettings{}, err+ }+ if err := ValidateDockerRemoteTLS(settings.Endpoint.Host, settings.Endpoint.TLSCertPath); err != nil {+ return dockerRuntimeSettings{}, err+ }+ return settings, nil+}++// dockerSandboxHandle is the opaque reference the manager holds.+type dockerSandboxHandle struct {+ id string+ metadata map[string]string+}++func (h *dockerSandboxHandle) ID() string { return h.id }+func (h *dockerSandboxHandle) Provider() RemoteProvider { return SandboxTypeDocker }+func (h *dockerSandboxHandle) Metadata() map[string]string { return h.metadata }++// Provider identifies this backend.+func (c *DockerRemoteClient) Provider() RemoteProvider { return SandboxTypeDocker }++// Capabilities reports what this backend can do.+//+// SupportsTimeoutRefresh is false because the daemon has no timeout to+// refresh: idle reclamation is WeKnora's own sweep, not a provider feature.+// SupportsVolumes is false until the volume-mount surface is mapped onto+// Docker named volumes; advertising it early would let a workspace configure+// a mount that silently never appears.+func (c *DockerRemoteClient) Capabilities() RemoteSandboxCapabilities {+ return RemoteSandboxCapabilities{+ SupportsReconnect: true,+ SupportsMetadata: true,+ SupportsListSandboxes: true,+ SupportsPauseResume: true,+ SupportsTimeoutRefresh: false,+ SupportsFilesystemEnumeration: true,+ SupportsVolumes: false,+ }+}++// Health pings the daemon.+func (c *DockerRemoteClient) Health(ctx context.Context) error {+ if _, err := c.api.Ping(ctx, client.PingOptions{}); err != nil {+ return dockerError("Health", err)+ }+ return nil+}++// Create starts a new container for one sandbox.+func (c *DockerRemoteClient) Create(+ ctx context.Context,+ req RemoteCreateRequest,+) (RemoteSandboxHandle, error) {+ if len(req.VolumeMounts) > 0 {+ return nil, &RemoteError{+ Kind: RemoteErrorKindUnsupported,+ Provider: SandboxTypeDocker,+ Op: "Create",+ Message: "docker backend does not mount volumes yet",+ }+ }+ image := strings.TrimSpace(req.TemplateID)+ if image == "" {+ image = c.settings.Image+ }+ if err := c.ensureImage(ctx, image); err != nil {+ return nil, err+ }++ labels := dockerContainerLabels(req.Metadata)+ labels[dockerIdleTTLLabel] = strconv.Itoa(int(c.effectiveIdleTTL(req.Timeout).Seconds()))+ created, err := c.api.ContainerCreate(ctx, client.ContainerCreateOptions{+ Image: image,+ Config: &container.Config{+ // The standard image ends with USER user. The entrypoint has to+ // create and chmod the activity marker under /var/lib, which only+ // root can do; exec still names DefaultSandboxExecUser per call.+ User: dockerSandboxPID1User,+ // Entrypoint rather than Cmd, with Cmd explicitly emptied: the+ // daemon prepends the image's own ENTRYPOINT to Cmd, so an image+ // that declares one (the cube target of docker/Dockerfile.sandbox+ // does, and so do most custom images) would take over PID 1. The+ // activity marker would then never exist and every exec would run+ // against whatever that entrypoint started instead.+ Entrypoint: dockerSandboxEntrypoint,+ Cmd: []string{},+ WorkingDir: SessionWorkspaceRoot,+ Labels: labels,+ Env: dockerEnvSlice(req.EnvVars),+ },+ HostConfig: c.hostConfig(req.Network),+ })+ if err != nil {+ return nil, dockerError("Create", err)+ }+ if _, err := c.api.ContainerStart(ctx, created.ID, client.ContainerStartOptions{}); err != nil {+ // A container that cannot start is useless and would otherwise linger+ // as an unbound leftover the sweep only reclaims much later.+ c.removeQuietly(ctx, created.ID)+ return nil, dockerError("Create", err)+ }+ c.sweepInBackground(ctx)+ return &dockerSandboxHandle{id: created.ID, metadata: dockerSandboxMetadata(labels)}, nil+}++// effectiveIdleTTL resolves how long this sandbox may sit unused.+//+// The caller's timeout policy is honoured because it is what the session+// layer already expresses per provider; the configured value is the fallback.+// The action (pause vs kill) is not: Docker's pause keeps the container's+// memory resident on the host, so pausing an abandoned sandbox would reclaim+// nothing. Idle containers are always deleted, which matches what the+// lifecycle does with a sandbox its provider reaped.+func (c *DockerRemoteClient) effectiveIdleTTL(policy RemoteTimeoutPolicy) time.Duration {+ if policy.Mode == RemoteTimeoutExplicit && policy.Value > 0 {+ return policy.Value+ }+ return c.settings.IdleTTL+}++// hostConfig builds the isolation and resource envelope for a new container.+func (c *DockerRemoteClient) hostConfig(policy RemoteNetworkPolicy) *container.HostConfig {+ pids := c.settings.PidsLimit+ hostConfig := &container.HostConfig{+ Resources: container.Resources{+ Memory: c.settings.MemoryBytes,+ // Equal memory and memory+swap disables swap, so a runaway+ // allocation is killed instead of thrashing the host's disk.+ MemorySwap: c.settings.MemoryBytes,+ NanoCPUs: int64(c.settings.CPULimit * 1e9),+ PidsLimit: &pids,+ },+ CapDrop: []string{"ALL"},+ CapAdd: dockerSandboxCapabilities,+ SecurityOpt: []string{"no-new-privileges"},+ Runtime: c.settings.Runtime,+ NetworkMode: container.NetworkMode(c.networkMode(policy)),+ }+ return hostConfig+}++// networkMode resolves the effective Docker network for a sandbox.+//+// Docker filters at L3/L4 only, so the domain-level allow/deny lists in+// RemoteNetworkPolicy cannot be honoured here; the one thing that maps+// cleanly is "no egress at all", which AllowInternetAccess=false expresses.+// Domain rules are silently not applied — the config surface refuses them+// before they get this far (see RequireCompleteConfig).+func (c *DockerRemoteClient) networkMode(policy RemoteNetworkPolicy) string {+ if policy.AllowInternetAccess != nil && !*policy.AllowInternetAccess {+ return "none"+ }+ if c.settings.NetworkMode != "" {+ return c.settings.NetworkMode+ }+ return "bridge"+}++// Connect re-attaches to an existing container, resuming it when the daemon+// or the host stopped it. This is the docker equivalent of E2B's auto-resume:+// a stopped container keeps its filesystem, so the session continues where it+// left off instead of losing everything it installed.+func (c *DockerRemoteClient) Connect(+ ctx context.Context,+ sandboxID string,+) (RemoteSandboxHandle, error) {+ inspected, err := c.api.ContainerInspect(ctx, sandboxID, client.ContainerInspectOptions{})+ if err != nil {+ return nil, dockerError("Connect", err)+ }+ state := inspected.Container.State+ if state == nil {+ return nil, dockerError("Connect", errors.New("daemon returned no container state"))+ }+ switch dockerStateOf(state.Status) {+ case RemoteStateTerminal:+ return nil, &RemoteError{+ Kind: RemoteErrorKindTerminal,+ Provider: SandboxTypeDocker,+ Op: "Connect",+ Message: "container is dead",+ }+ case RemoteStatePaused:+ if err := c.resume(ctx, inspected.Container.ID, string(state.Status)); err != nil {+ return nil, err+ }+ }+ c.sweepInBackground(ctx)++ var labels map[string]string+ if inspected.Container.Config != nil {+ labels = inspected.Container.Config.Labels+ }+ return &dockerSandboxHandle{+ id: inspected.Container.ID,+ metadata: dockerSandboxMetadata(labels),+ }, nil+}++// resume brings a paused or stopped container back to running.+func (c *DockerRemoteClient) resume(ctx context.Context, id, status string) error {+ if strings.EqualFold(status, "paused") {+ if _, err := c.api.ContainerUnpause(ctx, id, client.ContainerUnpauseOptions{}); err != nil {+ return dockerError("Connect", err)+ }+ return nil+ }+ if _, err := c.api.ContainerStart(ctx, id, client.ContainerStartOptions{}); err != nil {+ return dockerError("Connect", err)+ }+ return nil+}++// Get returns one sandbox summary.+func (c *DockerRemoteClient) Get(+ ctx context.Context,+ sandboxID string,+) (*RemoteSandboxSummary, error) {+ inspected, err := c.api.ContainerInspect(ctx, sandboxID, client.ContainerInspectOptions{})+ if err != nil {+ return nil, dockerError("Get", err)+ }+ summary := &RemoteSandboxSummary{+ ID: inspected.Container.ID,+ StartedAt: dockerContainerStartedAt(inspected.Container.State),+ }+ if inspected.Container.Config != nil {+ summary.TemplateID = inspected.Container.Config.Image+ summary.Metadata = dockerSandboxMetadata(inspected.Container.Config.Labels)+ }+ if inspected.Container.State != nil {+ summary.RawState = string(inspected.Container.State.Status)+ summary.State = dockerStateOf(inspected.Container.State.Status)+ if finished, err := time.Parse(+ time.RFC3339Nano, inspected.Container.State.FinishedAt,+ ); err == nil && finished.Year() > 1 {+ summary.EndAt = finished.UTC()+ }+ }+ return summary, nil+}++// List enumerates the containers this backend owns, filtered server-side by+// the metadata labels the caller asked for.+func (c *DockerRemoteClient) List(+ ctx context.Context,+ filter RemoteListFilter,+) ([]RemoteSandboxSummary, error) {+ filters := client.Filters{}.Add("label", dockerManagedLabel+"=true")+ for key, value := range filter.Metadata {+ filters = filters.Add("label", key+"="+value)+ }+ listed, err := c.api.ContainerList(ctx, client.ContainerListOptions{+ All: true,+ Filters: filters,+ })+ if err != nil {+ return nil, dockerError("List", err)+ }++ wanted := make(map[RemoteSandboxState]struct{}, len(filter.States))+ for _, state := range filter.States {+ wanted[state] = struct{}{}+ }+ summaries := make([]RemoteSandboxSummary, 0, len(listed.Items))+ for _, item := range listed.Items {+ state := dockerStateOf(item.State)+ if len(wanted) > 0 {+ if _, ok := wanted[state]; !ok {+ continue+ }+ }+ summaries = append(summaries, RemoteSandboxSummary{+ ID: item.ID,+ TemplateID: item.Image,+ State: state,+ RawState: string(item.State),+ Metadata: dockerSandboxMetadata(item.Labels),+ StartedAt: time.Unix(item.Created, 0).UTC(),+ })+ }+ return summaries, nil+}++// Delete removes a container and its anonymous volumes.+func (c *DockerRemoteClient) Delete(ctx context.Context, sandboxID string) error {+ _, err := c.api.ContainerRemove(ctx, sandboxID, client.ContainerRemoveOptions{+ Force: true,+ RemoveVolumes: true,+ })+ if err != nil {+ return dockerError("Delete", err)+ }+ return nil+}++// removeQuietly deletes a container on a cleanup path where the caller+// already has a more interesting error to report.+func (c *DockerRemoteClient) removeQuietly(ctx context.Context, id string) {+ cleanupCtx, cancel := context.WithTimeout(+ context.WithoutCancel(ctx), remoteCleanupTimeout,+ )+ defer cancel()+ _, _ = c.api.ContainerRemove(cleanupCtx, id, client.ContainerRemoveOptions{+ Force: true, RemoveVolumes: true,+ })+}++// Exec runs one command inside the sandbox.+//+// The command is wrapped so that the container, not the client, enforces the+// timeout: cancelling the HTTP request leaves the process running (verified in+// docs/poc/docker-sandbox), which would let a runaway script keep burning the+// host's CPU long after WeKnora reported a timeout to the user.+func (c *DockerRemoteClient) Exec(+ ctx context.Context,+ handle RemoteSandboxHandle,+ req RemoteExecRequest,+) (*RemoteExecResult, error) {+ id, err := dockerHandleID("Exec", handle)+ if err != nil {+ return nil, err+ }+ if req.Shell && len(req.Args) > 0 {+ return nil, dockerInvalidRequest("Exec", "shell requests must not carry args")+ }+ if strings.TrimSpace(req.Command) == "" {+ return nil, dockerInvalidRequest("Exec", "command is required")+ }++ timeout := req.Timeout+ if timeout <= 0 {+ timeout = DefaultTimeout+ }+ // The client deadline is deliberately looser than the in-container one so+ // the wrapper gets to report the kill itself, which is what turns a+ // timeout into Killed=true rather than a transport error.+ execCtx, cancel := context.WithTimeout(ctx, timeout+dockerExecGrace)+ defer cancel()++ created, err := c.api.ExecCreate(execCtx, id, client.ExecCreateOptions{+ Cmd: dockerExecCommand(req, timeout),+ User: dockerExecUser(req.User),+ WorkingDir: req.WorkDir,+ Env: dockerEnvSlice(req.Env),+ AttachStdin: req.Stdin != "",+ AttachStdout: true,+ AttachStderr: true,+ })+ if err != nil {+ return nil, dockerError("Exec", err)+ }++ start := time.Now()+ stdout, stderr, err := c.streamExec(execCtx, created.ID, req.Stdin)+ if err != nil {+ return nil, err+ }+ inspected, err := c.api.ExecInspect(execCtx, created.ID, client.ExecInspectOptions{})+ if err != nil {+ return nil, dockerError("Exec", err)+ }++ result := &RemoteExecResult{+ Stdout: stdout,+ Stderr: stderr,+ ExitCode: inspected.ExitCode,+ Duration: time.Since(start),+ }+ if dockerExecWasKilled(inspected.ExitCode) {+ result.Killed = true+ }+ return result, nil+}++// dockerExecGrace is the slack between the in-container timeout and the+// client-side deadline. It covers the round-trip and the wrapper's own+// teardown so a script killed at the deadline is still reported as Killed+// instead of surfacing as a transport timeout.+const dockerExecGrace = 10 * time.Second++// streamExec starts the exec, writes stdin, and demultiplexes the output.+func (c *DockerRemoteClient) streamExec(+ ctx context.Context,+ execID string,+ stdin string,+) (string, string, error) {+ attached, err := c.api.ExecAttach(ctx, execID, client.ExecAttachOptions{})+ if err != nil {+ return "", "", dockerError("Exec", err)+ }+ defer attached.Close()++ if stdin != "" {+ if _, err := attached.Conn.Write([]byte(stdin)); err != nil {+ return "", "", dockerError("Exec", fmt.Errorf("write stdin: %w", err))+ }+ }+ // Always half-close: a command reading stdin (cat, python -) hangs+ // forever on an open write side, even when nothing was sent.+ if closer, ok := attached.Conn.(interface{ CloseWrite() error }); ok {+ _ = closer.CloseWrite()+ }++ var stdout, stderr bytes.Buffer+ done := make(chan error, 1)+ go func() {+ _, copyErr := stdcopy.StdCopy(&stdout, &stderr, attached.Reader)+ done <- copyErr+ }()++ select {+ case copyErr := <-done:+ if copyErr != nil && !errors.Is(copyErr, io.EOF) {+ return stdout.String(), stderr.String(), dockerError("Exec", copyErr)+ }+ return stdout.String(), stderr.String(), nil+ case <-ctx.Done():+ return stdout.String(), stderr.String(), dockerError("Exec", ctx.Err())+ }+}++// dockerExecCommand builds the argv actually handed to the daemon.+//+// The wrapper does two things no Engine API call can: it refreshes the+// activity marker the idle sweep reads, and it enforces the timeout inside+// the container. Positional arguments ("$@" / "$1") carry the caller's+// command through the shell without any quoting, so a script containing+// quotes or newlines cannot change what runs.+func dockerExecCommand(req RemoteExecRequest, timeout time.Duration) []string {+ seconds := strconv.Itoa(int(timeout.Round(time.Second).Seconds()))+ if seconds == "0" {+ seconds = "1"+ }+ touch := "touch " + dockerActivityMarker + " 2>/dev/null || true; "+ if req.Shell {+ return []string{+ "/bin/sh", "-c",+ touch + `exec timeout -s KILL ` + seconds + ` /bin/sh -c "$1"`,+ "weknora-exec", req.Command,+ }+ }+ argv := []string{+ "/bin/sh", "-c",+ touch + `exec timeout -s KILL ` + seconds + ` "$@"`,+ "weknora-exec", req.Command,+ }+ return append(argv, req.Args...)+}++// dockerExecUser resolves which account a command runs as. An empty user means+// root here, matching the envd-backed backends where an unspecified user is+// the daemon's own root context; callers that need the unprivileged account+// name it explicitly (see DefaultSandboxExecUser).+func dockerExecUser(user string) string {+ if strings.TrimSpace(user) == "" {+ return "root"+ }+ return user+}++// dockerExecWasKilled reports whether an exit code means the wrapper killed+// the process. 137 is SIGKILL (timeout -s KILL), 124 is timeout(1) reporting+// that it had to intervene.+func dockerExecWasKilled(exitCode int) bool {+ return exitCode == 137 || exitCode == 124+}++// WriteFile uploads one file through the archive endpoint.+func (c *DockerRemoteClient) WriteFile(+ ctx context.Context,+ handle RemoteSandboxHandle,+ filePath string,+ content []byte,+) error {+ id, err := dockerHandleID("WriteFile", handle)+ if err != nil {+ return err+ }+ clean, err := dockerCleanPath("WriteFile", filePath)+ if err != nil {+ return err+ }+ if err := c.makeDir(ctx, id, path.Dir(clean), "WriteFile"); err != nil {+ return err+ }++ var archive bytes.Buffer+ writer := tar.NewWriter(&archive)+ header := &tar.Header{+ Name: path.Base(clean),+ Mode: 0o644,+ Size: int64(len(content)),+ ModTime: time.Now(),+ // Files land owned by the sandbox account so scripts can read (and+ // replace) their own inputs; the archive endpoint applies these ids+ // verbatim when CopyUIDGID is set.+ Uid: dockerSandboxUID,+ Gid: dockerSandboxGID,+ }+ if err := writer.WriteHeader(header); err != nil {+ return dockerError("WriteFile", err)+ }+ if _, err := writer.Write(content); err != nil {+ return dockerError("WriteFile", err)+ }+ if err := writer.Close(); err != nil {+ return dockerError("WriteFile", err)+ }++ _, err = c.api.CopyToContainer(ctx, id, client.CopyToContainerOptions{+ DestinationPath: path.Dir(clean),+ Content: &archive,+ CopyUIDGID: true,+ })+ if err != nil {+ return dockerError("WriteFile", err)+ }+ return nil+}++// dockerSandboxUID / dockerSandboxGID are the ids of DefaultSandboxExecUser.+// The template contract fixes them at 1000, the same convention E2B templates+// use, so uploaded files can be owned correctly without an extra lookup.+const (+ dockerSandboxUID = 1000+ dockerSandboxGID = 1000++ // dockerSandboxPID1User overrides the image USER so the entrypoint can+ // create the world-writable activity marker. Numeric 0 does not depend+ // on a root account existing by name in a custom image.+ dockerSandboxPID1User = "0"+)++// ReadFile downloads one file through the archive endpoint.+func (c *DockerRemoteClient) ReadFile(+ ctx context.Context,+ handle RemoteSandboxHandle,+ filePath string,+) ([]byte, error) {+ id, err := dockerHandleID("ReadFile", handle)+ if err != nil {+ return nil, err+ }+ clean, err := dockerCleanPath("ReadFile", filePath)+ if err != nil {+ return nil, err+ }+ response, err := c.api.CopyFromContainer(ctx, id, client.CopyFromContainerOptions{+ SourcePath: clean,+ })+ if err != nil {+ return nil, dockerError("ReadFile", err)+ }+ defer func() { _ = response.Content.Close() }()++ reader := tar.NewReader(response.Content)+ for {+ header, err := reader.Next()+ if errors.Is(err, io.EOF) {+ return nil, &RemoteError{+ Kind: RemoteErrorKindNotFound,+ Provider: SandboxTypeDocker,+ Op: "ReadFile",+ Message: "archive contained no regular file for " + clean,+ }+ }+ if err != nil {+ return nil, dockerError("ReadFile", err)+ }+ switch header.Typeflag {+ case tar.TypeDir:+ return nil, dockerInvalidRequest("ReadFile", clean+" is a directory")+ case tar.TypeReg:+ content, err := io.ReadAll(reader)+ if err != nil {+ return nil, dockerError("ReadFile", err)+ }+ return content, nil+ default:+ continue+ }+ }+}++// Stat returns metadata for one path.+func (c *DockerRemoteClient) Stat(+ ctx context.Context,+ handle RemoteSandboxHandle,+ filePath string,+) (*RemoteStatEntry, error) {+ id, err := dockerHandleID("Stat", handle)+ if err != nil {+ return nil, err+ }+ clean, err := dockerCleanPath("Stat", filePath)+ if err != nil {+ return nil, err+ }+ stat, err := c.api.ContainerStatPath(ctx, id, client.ContainerStatPathOptions{Path: clean})+ if err != nil {+ return nil, dockerError("Stat", err)+ }+ entry := &RemoteStatEntry{+ Path: clean,+ Type: RemoteEntryFile,+ Size: stat.Stat.Size,+ ModTime: stat.Stat.Mtime,+ }+ if stat.Stat.Mode.IsDir() {+ entry.Type = RemoteEntryDir+ } else if !stat.Stat.Mode.IsRegular() {+ entry.Type = RemoteEntryOther+ }+ return entry, nil+}++// MakeDir creates a directory (and its parents) inside the sandbox.+func (c *DockerRemoteClient) MakeDir(+ ctx context.Context,+ handle RemoteSandboxHandle,+ dirPath string,+) error {+ id, err := dockerHandleID("MakeDir", handle)+ if err != nil {+ return err+ }+ clean, err := dockerCleanPath("MakeDir", dirPath)+ if err != nil {+ return err+ }+ return c.makeDir(ctx, id, clean, "MakeDir")+}++func (c *DockerRemoteClient) makeDir(ctx context.Context, id, dir, op string) error {+ result, err := c.Exec(ctx, &dockerSandboxHandle{id: id}, RemoteExecRequest{+ Command: "mkdir",+ Args: []string{"-p", dir},+ User: DefaultSandboxExecUser,+ Timeout: dockerFilesystemOpTimeout,+ })+ if err != nil {+ return dockerError(op, err)+ }+ if result.ExitCode != 0 {+ return &RemoteError{+ Kind: RemoteErrorKindInvalidRequest,+ Provider: SandboxTypeDocker,+ Op: op,+ Message: fmt.Sprintf("mkdir -p %s: %s", dir, firstNonEmptyLine(result.Stderr)),+ }+ }+ return nil+}++// Remove deletes a path recursively.+func (c *DockerRemoteClient) Remove(+ ctx context.Context,+ handle RemoteSandboxHandle,+ targetPath string,+) error {+ id, err := dockerHandleID("Remove", handle)+ if err != nil {+ return err+ }+ clean, err := dockerCleanPath("Remove", targetPath)+ if err != nil {+ return err+ }+ if clean == "/" {+ return dockerInvalidRequest("Remove", "refusing to remove the container root")+ }+ result, err := c.Exec(ctx, &dockerSandboxHandle{id: id}, RemoteExecRequest{+ Command: "rm",+ Args: []string{"-rf", clean},+ User: DefaultSandboxExecUser,+ Timeout: dockerFilesystemOpTimeout,+ })+ if err != nil {+ return dockerError("Remove", err)+ }+ if result.ExitCode != 0 {+ return &RemoteError{+ Kind: RemoteErrorKindInvalidRequest,+ Provider: SandboxTypeDocker,+ Op: "Remove",+ Message: fmt.Sprintf("rm -rf %s: %s", clean, firstNonEmptyLine(result.Stderr)),+ }+ }+ return nil+}++// ListDir lists one directory level.+//+// find(1) is used rather than ls because a single -printf format yields the+// type, size, mtime and path the caller needs, with a tab separator that+// cannot appear in find's own output fields.+func (c *DockerRemoteClient) ListDir(+ ctx context.Context,+ handle RemoteSandboxHandle,+ dirPath string,+) ([]RemoteDirEntry, error) {+ id, err := dockerHandleID("ListDir", handle)+ if err != nil {+ return nil, err+ }+ clean, err := dockerCleanPath("ListDir", dirPath)+ if err != nil {+ return nil, err+ }+ result, err := c.Exec(ctx, &dockerSandboxHandle{id: id}, RemoteExecRequest{+ Command: "find",+ Args: []string{+ clean, "-mindepth", "1", "-maxdepth", "1",+ "-printf", `%y\t%s\t%T@\t%p\n`,+ },+ User: DefaultSandboxExecUser,+ Timeout: dockerFilesystemOpTimeout,+ })+ if err != nil {+ return nil, dockerError("ListDir", err)+ }+ if result.ExitCode != 0 {+ if strings.Contains(result.Stderr, "No such file or directory") {+ return nil, &RemoteError{+ Kind: RemoteErrorKindNotFound,+ Provider: SandboxTypeDocker,+ Op: "ListDir",+ Message: clean + " does not exist",+ }+ }+ return nil, &RemoteError{+ Kind: RemoteErrorKindInternal,+ Provider: SandboxTypeDocker,+ Op: "ListDir",+ Message: fmt.Sprintf("find %s: %s", clean, firstNonEmptyLine(result.Stderr)),+ }+ }+ return parseDockerFindOutput(result.Stdout), nil+}++// dockerFilesystemOpTimeout bounds the exec-backed filesystem helpers. They+// are all single syscalls in practice; a longer budget would only delay the+// report of a wedged container.+const dockerFilesystemOpTimeout = 30 * time.Second++// parseDockerFindOutput turns `find -printf '%y\t%s\t%T@\t%p\n'` lines into+// directory entries, skipping anything malformed rather than failing the+// whole listing: one unreadable entry must not hide the rest of a directory.+func parseDockerFindOutput(output string) []RemoteDirEntry {+ var entries []RemoteDirEntry+ for _, line := range strings.Split(output, "\n") {+ fields := strings.SplitN(strings.TrimRight(line, "\r"), "\t", 4)+ if len(fields) != 4 {+ continue+ }+ entry := RemoteDirEntry{+ Path: fields[3],+ Name: path.Base(fields[3]),+ Type: dockerEntryType(fields[0]),+ }+ if size, err := strconv.ParseInt(fields[1], 10, 64); err == nil {+ entry.Size = size+ }+ if seconds, err := strconv.ParseFloat(fields[2], 64); err == nil {+ entry.ModTime = time.Unix(+ int64(seconds), int64((seconds-float64(int64(seconds)))*1e9),+ ).UTC()+ }+ entries = append(entries, entry)+ }+ return entries+}++func dockerEntryType(findType string) RemoteDirEntryType {+ switch findType {+ case "f":+ return RemoteEntryFile+ case "d":+ return RemoteEntryDir+ default:+ return RemoteEntryOther+ }+}++// ensureImage pulls the template image when the daemon does not have it.+//+// The pull is bounded by dockerImagePullBudget, not by the caller's deadline:+// a cold pull of the sandbox image takes minutes, and the settings wizard+// starts that pull in the background so a later Create usually just inspects.+func (c *DockerRemoteClient) ensureImage(ctx context.Context, image string) error {+ if _, err := c.api.ImageInspect(ctx, image); err == nil {+ return nil+ }+ pullCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dockerImagePullBudget)+ defer cancel()+ body, err := c.api.ImagePull(pullCtx, image, client.ImagePullOptions{})+ if err != nil {+ return dockerError("Create", fmt.Errorf("pull image %s: %w", image, err))+ }+ if err := awaitImagePull(pullCtx, body); err != nil {+ return dockerError("Create", fmt.Errorf("pull image %s: %w", image, err))+ }+ return nil+}++// sweepInBackground triggers a rate-limited idle sweep without adding latency+// to the request that happened to trigger it.+func (c *DockerRemoteClient) sweepInBackground(ctx context.Context) {+ if c.sweeper == nil {+ return+ }+ c.sweeper.trigger(ctx)+}++// dockerHandleID validates a handle belongs to this backend.+func dockerHandleID(op string, handle RemoteSandboxHandle) (string, error) {+ if handle == nil {+ return "", dockerInvalidRequest(op, "sandbox handle is required")+ }+ if handle.Provider() != SandboxTypeDocker {+ return "", dockerInvalidRequest(op, "handle belongs to provider "+string(handle.Provider()))+ }+ id := strings.TrimSpace(handle.ID())+ if id == "" {+ return "", dockerInvalidRequest(op, "sandbox handle has no ID")+ }+ return id, nil+}++// dockerCleanPath normalizes an absolute in-sandbox path. Relative paths are+// refused: they would resolve against the container's working directory,+// which differs between exec-backed and archive-backed operations.+func dockerCleanPath(op, raw string) (string, error) {+ trimmed := strings.TrimSpace(raw)+ if trimmed == "" {+ return "", dockerInvalidRequest(op, "path is required")+ }+ if !strings.HasPrefix(trimmed, "/") {+ return "", dockerInvalidRequest(op, "path must be absolute: "+raw)+ }+ clean := path.Clean(trimmed)+ if reserved := dockerReservedPath(clean); reserved != "" {+ return "", dockerInvalidRequest(op, "path is not addressable: "+reserved)+ }+ return clean, nil+}++// dockerReservedPathPrefixes are refused for every file operation.+//+// Unlike the envd-backed backends, the archive endpoints (WriteFile, ReadFile,+// Stat) are served by the daemon itself and therefore ignore the exec user+// entirely: they read and write as root no matter what a caller asks for. The+// callers in this repository only ever address /workspace, so this is defence+// in depth rather than a live hole — but it is what keeps a future caller from+// turning a file read into a way to lift PID 1's environment out of /proc, or+// a file write into a way to backdate the sweeper's own bookkeeping.+var dockerReservedPathPrefixes = []string{+ "/proc",+ "/sys",+ "/dev",+ dockerActivityMarker,+}++// dockerReservedPath returns the prefix clean is refused for, or "" when the+// path is addressable. clean must already be path.Clean'd.+func dockerReservedPath(clean string) string {+ for _, prefix := range dockerReservedPathPrefixes {+ if clean == prefix || strings.HasPrefix(clean, prefix+"/") {+ return prefix+ }+ }+ return ""+}++// dockerEnvSlice converts an env map into Docker's KEY=VALUE form.+func dockerEnvSlice(env map[string]string) []string {+ if len(env) == 0 {+ return nil+ }+ pairs := make([]string, 0, len(env))+ for key, value := range env {+ pairs = append(pairs, key+"="+value)+ }+ return pairs+}++// firstNonEmptyLine trims a command's stderr down to something a user-facing+// error can carry.+func firstNonEmptyLine(output string) string {+ for _, line := range strings.Split(output, "\n") {+ if trimmed := strings.TrimSpace(line); trimmed != "" {+ if len(trimmed) > 200 {+ return trimmed[:200] + "…"+ }+ return trimmed+ }+ }+ return ""+}++var _ RemoteSandboxClient = (*DockerRemoteClient)(nil)diff --git a/internal/sandbox/docker_remote_client_test.go b/internal/sandbox/docker_remote_client_test.gonew file mode 100644index 000000000..de301326e--- /dev/null+++ b/internal/sandbox/docker_remote_client_test.go@@ -0,0 +1,826 @@+package sandbox++import (+ "archive/tar"+ "bufio"+ "bytes"+ "context"+ "encoding/binary"+ "errors"+ "io"+ "iter"+ "net"+ "os"+ "strings"+ "testing"+ "time"++ cerrdefs "github.com/containerd/errdefs"+ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/api/types/image"+ "github.com/moby/moby/api/types/jsonstream"+ "github.com/moby/moby/client"+ "github.com/stretchr/testify/require"+)++// --- fake Engine API ---------------------------------------------------------++// fakeDockerEngine is an in-memory Docker daemon: enough of the Engine API to+// drive the adapter's logic without a host that can run containers.+type fakeDockerEngine struct {+ pingErr error++ created []client.ContainerCreateOptions+ createErr error+ createdID string+ started []string+ startErr error+ unpaused []string+ removed []string+ removeErr error+ inspect map[string]container.InspectResponse+ inspectErr error+ list []container.Summary+ listFilters []client.Filters+ listErr error++ execOptions []client.ExecCreateOptions+ execStdout string+ execStderr string+ execExit int+ execErr error+ execStdin bytes.Buffer++ statResult map[string]container.PathStat+ // statHook lets a test answer differently per call, which is how the+ // sweeper's re-check before deletion is exercised.+ statHook func(path string) (container.PathStat, bool)+ statErr error+ copiedTo []client.CopyToContainerOptions+ copyFrom []byte+ copyErr error++ images []image.Summary+ imagePresent map[string]bool+ pulled []string+}++func newFakeDockerEngine() *fakeDockerEngine {+ return &fakeDockerEngine{+ createdID: "container-1",+ inspect: make(map[string]container.InspectResponse),+ statResult: make(map[string]container.PathStat),+ imagePresent: make(map[string]bool),+ }+}++func (f *fakeDockerEngine) Ping(context.Context, client.PingOptions) (client.PingResult, error) {+ return client.PingResult{APIVersion: "1.55"}, f.pingErr+}++func (f *fakeDockerEngine) ContainerCreate(+ _ context.Context, options client.ContainerCreateOptions,+) (client.ContainerCreateResult, error) {+ f.created = append(f.created, options)+ if f.createErr != nil {+ return client.ContainerCreateResult{}, f.createErr+ }+ return client.ContainerCreateResult{ID: f.createdID}, nil+}++func (f *fakeDockerEngine) ContainerStart(+ _ context.Context, id string, _ client.ContainerStartOptions,+) (client.ContainerStartResult, error) {+ f.started = append(f.started, id)+ return client.ContainerStartResult{}, f.startErr+}++func (f *fakeDockerEngine) ContainerUnpause(+ _ context.Context, id string, _ client.ContainerUnpauseOptions,+) (client.ContainerUnpauseResult, error) {+ f.unpaused = append(f.unpaused, id)+ return client.ContainerUnpauseResult{}, nil+}++func (f *fakeDockerEngine) ContainerInspect(+ _ context.Context, id string, _ client.ContainerInspectOptions,+) (client.ContainerInspectResult, error) {+ if f.inspectErr != nil {+ return client.ContainerInspectResult{}, f.inspectErr+ }+ found, ok := f.inspect[id]+ if !ok {+ return client.ContainerInspectResult{}, cerrdefs.ErrNotFound.WithMessage("no such container")+ }+ return client.ContainerInspectResult{Container: found}, nil+}++func (f *fakeDockerEngine) ContainerList(+ _ context.Context, options client.ContainerListOptions,+) (client.ContainerListResult, error) {+ f.listFilters = append(f.listFilters, options.Filters)+ if f.listErr != nil {+ return client.ContainerListResult{}, f.listErr+ }+ return client.ContainerListResult{Items: f.list}, nil+}++func (f *fakeDockerEngine) ContainerRemove(+ _ context.Context, id string, _ client.ContainerRemoveOptions,+) (client.ContainerRemoveResult, error) {+ f.removed = append(f.removed, id)+ return client.ContainerRemoveResult{}, f.removeErr+}++func (f *fakeDockerEngine) ExecCreate(+ _ context.Context, _ string, options client.ExecCreateOptions,+) (client.ExecCreateResult, error) {+ f.execOptions = append(f.execOptions, options)+ if f.execErr != nil {+ return client.ExecCreateResult{}, f.execErr+ }+ return client.ExecCreateResult{ID: "exec-1"}, nil+}++func (f *fakeDockerEngine) ExecAttach(+ _ context.Context, _ string, _ client.ExecAttachOptions,+) (client.ExecAttachResult, error) {+ var framed bytes.Buffer+ writeStdcopyFrame(&framed, 1, f.execStdout)+ writeStdcopyFrame(&framed, 2, f.execStderr)+ return client.ExecAttachResult{HijackedResponse: client.HijackedResponse{+ Conn: &fakeHijackedConn{stdin: &f.execStdin},+ Reader: bufio.NewReader(&framed),+ }}, nil+}++func (f *fakeDockerEngine) ExecInspect(+ _ context.Context, _ string, _ client.ExecInspectOptions,+) (client.ExecInspectResult, error) {+ return client.ExecInspectResult{ExitCode: f.execExit}, nil+}++func (f *fakeDockerEngine) CopyToContainer(+ _ context.Context, _ string, options client.CopyToContainerOptions,+) (client.CopyToContainerResult, error) {+ if f.copyErr != nil {+ return client.CopyToContainerResult{}, f.copyErr+ }+ content, _ := io.ReadAll(options.Content)+ options.Content = bytes.NewReader(content)+ f.copiedTo = append(f.copiedTo, options)+ f.copyFrom = content+ return client.CopyToContainerResult{}, nil+}++func (f *fakeDockerEngine) CopyFromContainer(+ _ context.Context, _ string, _ client.CopyFromContainerOptions,+) (client.CopyFromContainerResult, error) {+ if f.copyErr != nil {+ return client.CopyFromContainerResult{}, f.copyErr+ }+ return client.CopyFromContainerResult{+ Content: io.NopCloser(bytes.NewReader(f.copyFrom)),+ }, nil+}++func (f *fakeDockerEngine) ContainerStatPath(+ _ context.Context, _ string, options client.ContainerStatPathOptions,+) (client.ContainerStatPathResult, error) {+ if f.statErr != nil {+ return client.ContainerStatPathResult{}, f.statErr+ }+ if f.statHook != nil {+ if stat, ok := f.statHook(options.Path); ok {+ return client.ContainerStatPathResult{Stat: stat}, nil+ }+ }+ stat, ok := f.statResult[options.Path]+ if !ok {+ return client.ContainerStatPathResult{}, cerrdefs.ErrNotFound.WithMessage("no such path")+ }+ return client.ContainerStatPathResult{Stat: stat}, nil+}++func (f *fakeDockerEngine) ImageInspect(+ _ context.Context, imageID string, _ ...client.ImageInspectOption,+) (client.ImageInspectResult, error) {+ if f.imagePresent[imageID] {+ return client.ImageInspectResult{}, nil+ }+ return client.ImageInspectResult{}, cerrdefs.ErrNotFound.WithMessage("no such image")+}++func (f *fakeDockerEngine) ImagePull(+ _ context.Context, ref string, _ client.ImagePullOptions,+) (client.ImagePullResponse, error) {+ f.pulled = append(f.pulled, ref)+ f.imagePresent[ref] = true+ return fakePullResponse{ReadCloser: io.NopCloser(strings.NewReader(`{"status":"Downloaded"}`))}, nil+}++func (f *fakeDockerEngine) ImageList(+ _ context.Context, _ client.ImageListOptions,+) (client.ImageListResult, error) {+ return client.ImageListResult{Items: f.images}, nil+}++// fakePullResponse satisfies the pull-response contract without a registry.+type fakePullResponse struct{ io.ReadCloser }++func (fakePullResponse) JSONMessages(context.Context) iter.Seq2[jsonstream.Message, error] {+ return func(func(jsonstream.Message, error) bool) {}+}+func (fakePullResponse) Wait(context.Context) error { return nil }++// writeStdcopyFrame appends one multiplexed frame in the format the daemon+// uses for non-TTY exec streams.+func writeStdcopyFrame(buf *bytes.Buffer, stream byte, payload string) {+ if payload == "" {+ return+ }+ header := make([]byte, 8)+ header[0] = stream+ binary.BigEndian.PutUint32(header[4:], uint32(len(payload)))+ buf.Write(header)+ buf.WriteString(payload)+}++// fakeHijackedConn stands in for the hijacked TCP connection. Only the write+// half matters: the adapter writes stdin and half-closes.+type fakeHijackedConn struct {+ stdin *bytes.Buffer+ closed bool+}++func (c *fakeHijackedConn) Read([]byte) (int, error) { return 0, io.EOF }+func (c *fakeHijackedConn) Write(p []byte) (int, error) { return c.stdin.Write(p) }+func (c *fakeHijackedConn) Close() error { c.closed = true; return nil }+func (c *fakeHijackedConn) CloseWrite() error { return nil }+func (c *fakeHijackedConn) LocalAddr() net.Addr { return nil }+func (c *fakeHijackedConn) RemoteAddr() net.Addr { return nil }+func (c *fakeHijackedConn) SetDeadline(time.Time) error { return nil }+func (c *fakeHijackedConn) SetReadDeadline(time.Time) error { return nil }+func (c *fakeHijackedConn) SetWriteDeadline(time.Time) error { return nil }++func newTestDockerClient(t *testing.T, engine *fakeDockerEngine) *DockerRemoteClient {+ t.Helper()+ settings, err := dockerSettingsFromConfig(&Config{+ Type: SandboxTypeDocker,+ DockerImage: "weknora/sandbox:test",+ })+ require.NoError(t, err)+ // Idle sweeping is disabled: it would race the assertions with a+ // background goroutine deleting the very containers under test.+ settings.IdleTTL = 0+ return newDockerRemoteClientWithAPI(engine, settings)+}++func testHandle(id string) RemoteSandboxHandle {+ return &dockerSandboxHandle{id: id}+}++// --- tests -------------------------------------------------------------------++func TestDockerClientCreateAppliesIsolationAndMetadata(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.imagePresent["weknora/sandbox:test"] = true+ docker := newTestDockerClient(t, engine)++ handle, err := docker.Create(context.Background(), RemoteCreateRequest{+ TemplateID: "weknora/sandbox:test",+ Metadata: map[string]string{remoteMetadataSessionID: "sess-1"},+ EnvVars: map[string]string{"FOO": "bar"},+ Timeout: RemoteTimeoutPolicy{Mode: RemoteTimeoutExplicit, Value: 15 * time.Minute},+ })+ require.NoError(t, err)+ require.Equal(t, "container-1", handle.ID())+ require.Equal(t, SandboxTypeDocker, handle.Provider())+ require.Equal(t, "sess-1", handle.Metadata()[remoteMetadataSessionID])+ require.NotContains(t, handle.Metadata(), dockerManagedLabel,+ "the ownership marker is our bookkeeping, not caller metadata")++ require.Len(t, engine.created, 1)+ created := engine.created[0]+ // PID 1 both keeps the container alive and prepares the activity marker so+ // that root and the unprivileged sandbox user can each refresh it; the+ // idle sweeper reads nothing else.+ require.Equal(t, dockerSandboxPID1User, created.Config.User,+ "PID 1 must be root so the entrypoint can chmod the activity marker")+ require.Equal(t, "/bin/sh", created.Config.Entrypoint[0])+ require.Contains(t, created.Config.Entrypoint[2], "touch "+dockerActivityMarker)+ require.Contains(t, created.Config.Entrypoint[2], "chmod 666 "+dockerActivityMarker)+ require.Contains(t, created.Config.Entrypoint[2], "exec sleep infinity")+ require.NotNil(t, created.Config.Cmd,+ "an empty (not nil) Cmd is what resets the image's own CMD on the wire")+ require.Empty(t, created.Config.Cmd)+ require.Equal(t, SessionWorkspaceRoot, created.Config.WorkingDir)+ require.Equal(t, []string{"FOO=bar"}, created.Config.Env)+ require.Equal(t, "true", created.Config.Labels[dockerManagedLabel])+ require.Equal(t, "sess-1", created.Config.Labels[remoteMetadataSessionID])+ require.Equal(t, "900", created.Config.Labels[dockerIdleTTLLabel],+ "the sweep must reclaim with the TTL the sandbox was created with")++ host := created.HostConfig+ require.Equal(t, []string{"ALL"}, host.CapDrop)+ require.Equal(t, dockerSandboxCapabilities, host.CapAdd)+ require.Contains(t, host.SecurityOpt, "no-new-privileges")+ require.Equal(t, DefaultDockerMemoryLimit, host.Memory)+ require.Equal(t, host.Memory, host.MemorySwap, "swap must not soften the memory cap")+ require.Equal(t, int64(DefaultDockerCPULimit*1e9), host.NanoCPUs)+ require.Equal(t, DefaultDockerPidsLimit, *host.PidsLimit)+ require.Equal(t, container.NetworkMode("bridge"), host.NetworkMode)+ require.Equal(t, []string{"container-1"}, engine.started)+}++func TestDockerClientCreatePullsMissingImage(t *testing.T) {+ engine := newFakeDockerEngine()+ docker := newTestDockerClient(t, engine)++ _, err := docker.Create(context.Background(), RemoteCreateRequest{+ TemplateID: "weknora/sandbox:test",+ })+ require.NoError(t, err)+ require.Equal(t, []string{"weknora/sandbox:test"}, engine.pulled)+}++// A container that cannot start is a leak waiting to happen: nothing binds it,+// so only the much later idle sweep would notice.+func TestDockerClientCreateRemovesContainerThatCannotStart(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.imagePresent["weknora/sandbox:test"] = true+ engine.startErr = errors.New("no space left on device")+ docker := newTestDockerClient(t, engine)++ _, err := docker.Create(context.Background(), RemoteCreateRequest{+ TemplateID: "weknora/sandbox:test",+ })+ require.Error(t, err)+ require.Equal(t, []string{"container-1"}, engine.removed)+}++func TestDockerClientCreateRefusesVolumeMounts(t *testing.T) {+ docker := newTestDockerClient(t, newFakeDockerEngine())+ _, err := docker.Create(context.Background(), RemoteCreateRequest{+ TemplateID: "weknora/sandbox:test",+ VolumeMounts: []RemoteVolumeMount{{Name: "skills", Path: "/skills"}},+ })+ require.Error(t, err)+ require.Equal(t, RemoteErrorKindUnsupported, remoteKind(err))+}++func TestDockerClientCreateNoEgressUsesNoneNetwork(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.imagePresent["weknora/sandbox:test"] = true+ docker := newTestDockerClient(t, engine)++ denied := false+ _, err := docker.Create(context.Background(), RemoteCreateRequest{+ TemplateID: "weknora/sandbox:test",+ Network: RemoteNetworkPolicy{AllowInternetAccess: &denied},+ })+ require.NoError(t, err)+ require.Equal(t, container.NetworkMode("none"), engine.created[0].HostConfig.NetworkMode)+}++// Connect is where a session survives a daemon restart: the container's+// filesystem is intact, so it is restarted rather than replaced.+func TestDockerClientConnectRestartsStoppedContainer(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.inspect["container-1"] = container.InspectResponse{+ ID: "container-1",+ State: &container.State{Status: "exited"},+ Config: &container.Config{Labels: map[string]string{+ dockerManagedLabel: "true",+ remoteMetadataSessionID: "sess-1",+ }},+ }+ docker := newTestDockerClient(t, engine)++ handle, err := docker.Connect(context.Background(), "container-1")+ require.NoError(t, err)+ require.Equal(t, "container-1", handle.ID())+ require.Equal(t, []string{"container-1"}, engine.started)+ require.Equal(t, "sess-1", handle.Metadata()[remoteMetadataSessionID])+}++func TestDockerClientConnectUnpausesPausedContainer(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.inspect["container-1"] = container.InspectResponse{+ ID: "container-1",+ State: &container.State{Status: "paused"},+ Config: &container.Config{},+ }+ docker := newTestDockerClient(t, engine)++ _, err := docker.Connect(context.Background(), "container-1")+ require.NoError(t, err)+ require.Equal(t, []string{"container-1"}, engine.unpaused)+ require.Empty(t, engine.started)+}++// A missing container must classify as NotFound so the lifecycle rebinds the+// session instead of failing every execution forever.+func TestDockerClientConnectMissingContainerIsReplaceable(t *testing.T) {+ docker := newTestDockerClient(t, newFakeDockerEngine())+ _, err := docker.Connect(context.Background(), "container-gone")+ require.Error(t, err)+ require.True(t, CanReplaceRemoteBinding(err))+}++func TestDockerClientGetNormalizesState(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.inspect["container-1"] = container.InspectResponse{+ ID: "container-1",+ State: &container.State{+ Status: "running",+ StartedAt: "2026-08-12T10:00:00.000000000Z",+ },+ Config: &container.Config{+ Image: "weknora/sandbox:test",+ Labels: map[string]string{remoteMetadataSessionID: "sess-1"},+ },+ }+ docker := newTestDockerClient(t, engine)++ summary, err := docker.Get(context.Background(), "container-1")+ require.NoError(t, err)+ require.Equal(t, RemoteStateRunning, summary.State)+ require.Equal(t, "running", summary.RawState)+ require.Equal(t, "weknora/sandbox:test", summary.TemplateID)+ require.Equal(t, 2026, summary.StartedAt.Year())+}++// "exited" must not be terminal: the filesystem is intact and Connect restarts+// it. Treating it as terminal would throw away a session's installed packages.+func TestDockerStateOfKeepsStoppedContainersResumable(t *testing.T) {+ require.Equal(t, RemoteStatePaused, dockerStateOf("exited"))+ require.Equal(t, RemoteStatePaused, dockerStateOf("paused"))+ require.Equal(t, RemoteStateRunning, dockerStateOf("running"))+ require.Equal(t, RemoteStateTerminal, dockerStateOf("dead"))+ require.Equal(t, RemoteStateTransitioning, dockerStateOf("restarting"))+}++func TestDockerClientListFiltersByOwnershipAndMetadata(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.list = []container.Summary{+ {+ ID: "a", State: "running", Image: "img", Created: 1700000000,+ Labels: map[string]string{dockerManagedLabel: "true", remoteMetadataSessionID: "s1"},+ },+ {+ ID: "b", State: "exited", Image: "img", Created: 1700000000,+ Labels: map[string]string{dockerManagedLabel: "true"},+ },+ }+ docker := newTestDockerClient(t, engine)++ all, err := docker.List(context.Background(), RemoteListFilter{+ Metadata: map[string]string{remoteMetadataSessionID: "s1"},+ })+ require.NoError(t, err)+ require.Len(t, all, 2, "the daemon does the metadata filtering; the fake does not")+ require.Len(t, engine.listFilters, 1)+ require.Contains(t, engine.listFilters[0]["label"], dockerManagedLabel+"=true")+ require.Contains(t, engine.listFilters[0]["label"], remoteMetadataSessionID+"=s1")++ running, err := docker.List(context.Background(), RemoteListFilter{+ States: []RemoteSandboxState{RemoteStateRunning},+ })+ require.NoError(t, err)+ require.Len(t, running, 1)+ require.Equal(t, "a", running[0].ID)+}++// The wrapper is the whole timeout story for this backend: cancelling the HTTP+// request does not stop the process, so the container must kill it.+func TestDockerClientExecWrapsCommandWithTimeoutAndActivityMarker(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.execStdout = "hello\n"+ docker := newTestDockerClient(t, engine)++ result, err := docker.Exec(context.Background(), testHandle("container-1"), RemoteExecRequest{+ Command: "python3",+ Args: []string{"/workspace/script.py", "--flag"},+ Timeout: 45 * time.Second,+ User: DefaultSandboxExecUser,+ WorkDir: SessionWorkspaceRoot,+ Env: map[string]string{"K": "V"},+ })+ require.NoError(t, err)+ require.Equal(t, "hello\n", result.Stdout)++ require.Len(t, engine.execOptions, 1)+ opts := engine.execOptions[0]+ require.Equal(t, DefaultSandboxExecUser, opts.User)+ require.Equal(t, SessionWorkspaceRoot, opts.WorkingDir)+ require.Equal(t, []string{"K=V"}, opts.Env)+ require.Equal(t, "/bin/sh", opts.Cmd[0])+ require.Contains(t, opts.Cmd[2], dockerActivityMarker)+ require.Contains(t, opts.Cmd[2], "timeout -s KILL 45")+ require.Equal(t, []string{"weknora-exec", "python3", "/workspace/script.py", "--flag"},+ opts.Cmd[3:], "the command must reach the shell as positional args, never interpolated")+}++// A script containing shell metacharacters must not be re-interpreted by the+// wrapper that enforces the timeout.+func TestDockerClientExecShellPassesCommandAsPositionalArgument(t *testing.T) {+ engine := newFakeDockerEngine()+ docker := newTestDockerClient(t, engine)++ _, err := docker.Exec(context.Background(), testHandle("container-1"), RemoteExecRequest{+ Command: `echo "a b"; rm -rf /nope`,+ Shell: true,+ Timeout: 10 * time.Second,+ })+ require.NoError(t, err)+ opts := engine.execOptions[0]+ require.Equal(t, []string{"weknora-exec", `echo "a b"; rm -rf /nope`}, opts.Cmd[3:])+ require.Equal(t, "root", opts.User, "an unspecified user means root, matching envd backends")+}++func TestDockerClientExecRejectsShellWithArgs(t *testing.T) {+ docker := newTestDockerClient(t, newFakeDockerEngine())+ _, err := docker.Exec(context.Background(), testHandle("c"), RemoteExecRequest{+ Command: "echo", Shell: true, Args: []string{"hi"},+ })+ require.Error(t, err)+ require.True(t, IsRemoteInvalidRequest(err))+}++func TestDockerClientExecSeparatesStreamsAndReportsKill(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.execStdout = "out"+ engine.execStderr = "err"+ engine.execExit = 137+ docker := newTestDockerClient(t, engine)++ result, err := docker.Exec(context.Background(), testHandle("c"), RemoteExecRequest{+ Command: "sleep", Args: []string{"30"}, Timeout: time.Second,+ })+ require.NoError(t, err)+ require.Equal(t, "out", result.Stdout)+ require.Equal(t, "err", result.Stderr)+ require.True(t, result.Killed, "SIGKILL from the timeout wrapper is a timeout, not a crash")+}++func TestDockerClientExecWritesStdin(t *testing.T) {+ engine := newFakeDockerEngine()+ docker := newTestDockerClient(t, engine)++ _, err := docker.Exec(context.Background(), testHandle("c"), RemoteExecRequest{+ Command: "cat", Stdin: "payload\n", Timeout: time.Second,+ })+ require.NoError(t, err)+ require.Equal(t, "payload\n", engine.execStdin.String())+ require.True(t, engine.execOptions[0].AttachStdin)+}++func TestDockerClientWriteFileUploadsArchiveOwnedBySandboxUser(t *testing.T) {+ engine := newFakeDockerEngine()+ docker := newTestDockerClient(t, engine)++ err := docker.WriteFile(context.Background(), testHandle("c"),+ "/workspace/input/note.txt", []byte("hello"))+ require.NoError(t, err)++ require.Len(t, engine.copiedTo, 1)+ require.Equal(t, "/workspace/input", engine.copiedTo[0].DestinationPath)+ require.True(t, engine.copiedTo[0].CopyUIDGID)+ require.Contains(t, engine.execOptions[0].Cmd, "mkdir",+ "the parent directory has no archive-API equivalent and must be exec'd")+ require.Equal(t, DefaultSandboxExecUser, engine.execOptions[0].User,+ "mkdir as root would leave nested dirs unwritable by skill scripts")++ content, err := docker.ReadFile(context.Background(), testHandle("c"),+ "/workspace/input/note.txt")+ require.NoError(t, err)+ require.Equal(t, []byte("hello"), content)+}++func TestDockerClientReadFileRejectsDirectoryArchive(t *testing.T) {+ engine := newFakeDockerEngine()+ var archive bytes.Buffer+ writer := tar.NewWriter(&archive)+ require.NoError(t, writer.WriteHeader(&tar.Header{+ Name: "output", Typeflag: tar.TypeDir, Mode: 0o755,+ }))+ require.NoError(t, writer.WriteHeader(&tar.Header{+ Name: "output/nested.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3,+ }))+ _, err := writer.Write([]byte("hi\n"))+ require.NoError(t, err)+ require.NoError(t, writer.Close())+ engine.copyFrom = archive.Bytes()++ _, err = newTestDockerClient(t, engine).ReadFile(+ context.Background(), testHandle("c"), "/workspace/output")+ require.True(t, IsRemoteInvalidRequest(err),+ "a directory archive must not return the first nested file")+}++func TestDockerClientPathsMustBeAbsolute(t *testing.T) {+ docker := newTestDockerClient(t, newFakeDockerEngine())+ err := docker.WriteFile(context.Background(), testHandle("c"), "relative.txt", []byte("x"))+ require.True(t, IsRemoteInvalidRequest(err))++ _, statErr := docker.Stat(context.Background(), testHandle("c"), "")+ require.True(t, IsRemoteInvalidRequest(statErr))+}++func TestDockerClientRemoveRefusesContainerRoot(t *testing.T) {+ docker := newTestDockerClient(t, newFakeDockerEngine())+ err := docker.Remove(context.Background(), testHandle("c"), "/")+ require.True(t, IsRemoteInvalidRequest(err))+}++func TestDockerClientListDirParsesFindOutput(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.execStdout = "d\t4096\t1786565482.1779913070\t/workspace/output/nested\n" ++ "f\t12\t1786565482.0000000000\t/workspace/output/report.txt\n"+ docker := newTestDockerClient(t, engine)++ entries, err := docker.ListDir(context.Background(), testHandle("c"), "/workspace/output")+ require.NoError(t, err)+ require.Len(t, entries, 2)+ require.Equal(t, RemoteEntryDir, entries[0].Type)+ require.Equal(t, "nested", entries[0].Name)+ require.Equal(t, RemoteEntryFile, entries[1].Type)+ require.Equal(t, int64(12), entries[1].Size)+ require.Equal(t, 2026, entries[1].ModTime.Year())+}++func TestDockerClientListDirMissingDirectoryIsNotFound(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.execExit = 1+ engine.execStderr = "find: '/workspace/nope': No such file or directory"+ docker := newTestDockerClient(t, engine)++ _, err := docker.ListDir(context.Background(), testHandle("c"), "/workspace/nope")+ require.True(t, IsRemoteNotFound(err))+}++func TestDockerClientStatMapsEntryType(t *testing.T) {+ engine := newFakeDockerEngine()+ engine.statResult["/workspace/output"] = container.PathStat{+ Size: 4096, Mode: os.ModeDir | 0o755, Mtime: time.Now(),+ }+ docker := newTestDockerClient(t, engine)++ entry, err := docker.Stat(context.Background(), testHandle("c"), "/workspace/output")+ require.NoError(t, err)+ require.Equal(t, RemoteEntryDir, entry.Type)++ _, err = docker.Stat(context.Background(), testHandle("c"), "/workspace/missing")+ require.True(t, IsRemoteNotFound(err))+}++func TestDockerClientCapabilities(t *testing.T) {+ caps := newTestDockerClient(t, newFakeDockerEngine()).Capabilities()+ require.True(t, caps.SupportsReconnect)+ require.True(t, caps.SupportsMetadata)+ require.True(t, caps.SupportsListSandboxes)+ require.True(t, caps.SupportsFilesystemEnumeration)+ require.False(t, caps.SupportsTimeoutRefresh,+ "the daemon has no TTL to refresh; reclamation is WeKnora's own sweep")+ require.False(t, caps.SupportsVolumes)+}++func TestDockerErrorKindClassification(t *testing.T) {+ require.Equal(t, RemoteErrorKindNotFound,+ dockerErrorKind("Get", cerrdefs.ErrNotFound.WithMessage("nope")))+ require.Equal(t, RemoteErrorKindInvalidRequest,+ dockerErrorKind("Create", cerrdefs.ErrNotFound.WithMessage("no such image")),+ "a missing image is a bad template, not a vanished sandbox")+ require.Equal(t, RemoteErrorKindConflict,+ dockerErrorKind("Exec", cerrdefs.ErrConflict.WithMessage("not running")))+ require.Equal(t, RemoteErrorKindAuthentication,+ dockerErrorKind("List", cerrdefs.ErrPermissionDenied.WithMessage("denied")))+ require.Equal(t, RemoteErrorKindTimeout,+ dockerErrorKind("Exec", context.DeadlineExceeded))+ require.Equal(t, RemoteErrorKindInternal,+ dockerErrorKind("Exec", errors.New("boom")))+}++func TestValidateDockerHost(t *testing.T) {+ require.NoError(t, ValidateDockerHost("", false))+ require.NoError(t, ValidateDockerHost("unix:///var/run/docker.sock", false))+ require.Error(t, ValidateDockerHost("unix://relative.sock", false))+ require.Error(t, ValidateDockerHost("/var/run/docker.sock", false),+ "a bare path hides whether the endpoint is local or remote")+ require.Error(t, ValidateDockerHost("ssh://host", false))+ require.Error(t, ValidateDockerHost("tcp://10.0.0.5:2376", false),+ "a private daemon address needs the explicit private-endpoint opt-in")+ require.NoError(t, ValidateDockerHost("tcp://10.0.0.5:2376", true))+}++func TestValidateDockerRemoteTLS(t *testing.T) {+ require.NoError(t, ValidateDockerRemoteTLS("", ""))+ require.NoError(t, ValidateDockerRemoteTLS("unix:///var/run/docker.sock", ""))+ require.Error(t, ValidateDockerRemoteTLS("tcp://10.0.0.5:2376", ""),+ "a remote daemon without TLS is a plaintext root socket")+ require.NoError(t, ValidateDockerRemoteTLS("tcp://10.0.0.5:2376", "/etc/weknora/docker-certs"))+}++// The archive endpoints are served by the daemon and ignore the exec user, so+// they read and write as root. Pseudo-filesystems and the sweeper's own marker+// must not be addressable through them.+func TestDockerCleanPathRefusesReservedPaths(t *testing.T) {+ engine := newFakeDockerEngine()+ docker := newTestDockerClient(t, engine)+ ctx := context.Background()++ for _, target := range []string{+ "/proc/1/environ",+ "/proc",+ "/sys/kernel",+ "/dev/mem",+ dockerActivityMarker,+ // path.Clean must run before the check, or traversal walks around it.+ "/workspace/../proc/1/environ",+ } {+ _, err := docker.ReadFile(ctx, testHandle("c"), target)+ require.Error(t, err, target)+ require.Equal(t, RemoteErrorKindInvalidRequest, remoteKind(err), target)++ err = docker.WriteFile(ctx, testHandle("c"), target, []byte("x"))+ require.Error(t, err, target)+ }++ require.Empty(t, engine.copiedTo, "a refused path must never reach the daemon")+}++func TestDockerHostNeedsDialGuard(t *testing.T) {+ require.True(t, dockerHostNeedsDialGuard("tcp://10.0.0.5:2376"))+ require.True(t, dockerHostNeedsDialGuard("https://daemon.example:2376"))+ require.False(t, dockerHostNeedsDialGuard("unix:///var/run/docker.sock"),+ "a unix socket carries no address the outbound policy could check")+ require.False(t, dockerHostNeedsDialGuard(""))+}++// Two configs pointing at the same daemon with different outbound policies must+// not share a pooled client: the client carries the dialer, so the stricter+// config would inherit connections it is not allowed to make.+func TestDockerEndpointKeySeparatesOutboundPolicy(t *testing.T) {+ permissive := dockerEndpoint{Host: "tcp://10.0.0.5:2376", AllowPrivate: true}+ restrictive := dockerEndpoint{Host: "tcp://10.0.0.5:2376"}+ require.NotEqual(t, permissive.key(), restrictive.key())+}++func TestDockerSettingsCarryOutboundPolicy(t *testing.T) {+ settings, err := dockerSettingsFromConfig(&Config{+ Type: SandboxTypeDocker,+ DockerImage: "weknora/sandbox:test",+ AllowPrivateEndpoints: true,+ })+ require.NoError(t, err)+ require.True(t, settings.Endpoint.AllowPrivate)+}++func TestValidateDockerNetworkMode(t *testing.T) {+ require.NoError(t, ValidateDockerNetworkMode(""))+ require.NoError(t, ValidateDockerNetworkMode("bridge"))+ require.NoError(t, ValidateDockerNetworkMode("none"))+ require.Error(t, ValidateDockerNetworkMode("host"))+ require.Error(t, ValidateDockerNetworkMode("container:abc"))+ require.Error(t, ValidateDockerNetworkMode("ns:/var/run/netns/foo"))+ // A named network is usually the deployment's own compose network, which+ // would put the sandbox alongside Postgres and Redis.+ require.Error(t, ValidateDockerNetworkMode("weknora_default"))+ require.Error(t, ValidateDockerNetworkMode("weknora-sandbox"))+}++func TestDockerSettingsRejectHostNetworkAndPlaintextTCP(t *testing.T) {+ _, err := dockerSettingsFromConfig(&Config{+ Type: SandboxTypeDocker,+ DockerImage: "weknora/sandbox:test",+ DockerNetworkMode: "host",+ })+ require.Error(t, err)++ _, err = dockerSettingsFromConfig(&Config{+ Type: SandboxTypeDocker,+ DockerImage: "weknora/sandbox:test",+ DockerHost: "tcp://10.0.0.5:2376",+ })+ require.Error(t, err)+}++func TestDockerSettingsRequireImage(t *testing.T) {+ _, err := dockerSettingsFromConfig(&Config{Type: SandboxTypeDocker})+ require.Error(t, err)+}++func TestDockerSessionCreateRequestDeletesIdleSandboxes(t *testing.T) {+ cfg := DefaultConfig()+ cfg.Type = SandboxTypeDocker+ cfg.DockerImage = "weknora/sandbox:test"+ applyDockerRuntimeDefaults(cfg)++ request, err := buildSessionCreateRequest(SandboxTypeDocker, cfg)+ require.NoError(t, err)+ require.Equal(t, "weknora/sandbox:test", request.TemplateID)+ require.Equal(t, DefaultDockerIdleTTL, request.Timeout.Value)+ require.Equal(t, RemoteOnTimeoutKill, request.Timeout.Action,+ "pausing a container keeps its memory on the host, so it reclaims nothing")+}diff --git a/internal/sandbox/docker_rpc_timeout.go b/internal/sandbox/docker_rpc_timeout.gonew file mode 100644index 000000000..545663266--- /dev/null+++ b/internal/sandbox/docker_rpc_timeout.go@@ -0,0 +1,150 @@+package sandbox++import (+ "context"+ "time"++ "github.com/moby/moby/client"+)++// withDockerRPCTimeout bounds short Engine API calls. Streaming methods are+// left on the caller's context: http.Client.Timeout (and a blanket RPC+// deadline) would abort a pull or hijacked exec after the budget, which is+// exactly how the previous 30s client timeout broke cold image pulls.+func withDockerRPCTimeout(inner dockerEngineAPI, timeout time.Duration) dockerEngineAPI {+ if inner == nil || timeout <= 0 {+ return inner+ }+ return &dockerRPCTimeoutAPI{inner: inner, timeout: timeout}+}++type dockerRPCTimeoutAPI struct {+ inner dockerEngineAPI+ timeout time.Duration+}++func (a *dockerRPCTimeoutAPI) rpcCtx(ctx context.Context) (context.Context, context.CancelFunc) {+ return context.WithTimeout(ctx, a.timeout)+}++func (a *dockerRPCTimeoutAPI) Ping(+ ctx context.Context, options client.PingOptions,+) (client.PingResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.Ping(rpcCtx, options)+}++func (a *dockerRPCTimeoutAPI) ContainerCreate(+ ctx context.Context, options client.ContainerCreateOptions,+) (client.ContainerCreateResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.ContainerCreate(rpcCtx, options)+}++func (a *dockerRPCTimeoutAPI) ContainerStart(+ ctx context.Context, containerID string, options client.ContainerStartOptions,+) (client.ContainerStartResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.ContainerStart(rpcCtx, containerID, options)+}++func (a *dockerRPCTimeoutAPI) ContainerUnpause(+ ctx context.Context, containerID string, options client.ContainerUnpauseOptions,+) (client.ContainerUnpauseResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.ContainerUnpause(rpcCtx, containerID, options)+}++func (a *dockerRPCTimeoutAPI) ContainerInspect(+ ctx context.Context, containerID string, options client.ContainerInspectOptions,+) (client.ContainerInspectResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.ContainerInspect(rpcCtx, containerID, options)+}++func (a *dockerRPCTimeoutAPI) ContainerList(+ ctx context.Context, options client.ContainerListOptions,+) (client.ContainerListResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.ContainerList(rpcCtx, options)+}++func (a *dockerRPCTimeoutAPI) ContainerRemove(+ ctx context.Context, containerID string, options client.ContainerRemoveOptions,+) (client.ContainerRemoveResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.ContainerRemove(rpcCtx, containerID, options)+}++func (a *dockerRPCTimeoutAPI) ExecCreate(+ ctx context.Context, containerID string, options client.ExecCreateOptions,+) (client.ExecCreateResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.ExecCreate(rpcCtx, containerID, options)+}++func (a *dockerRPCTimeoutAPI) ExecAttach(+ ctx context.Context, execID string, options client.ExecAttachOptions,+) (client.ExecAttachResult, error) {+ return a.inner.ExecAttach(ctx, execID, options)+}++func (a *dockerRPCTimeoutAPI) ExecInspect(+ ctx context.Context, execID string, options client.ExecInspectOptions,+) (client.ExecInspectResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.ExecInspect(rpcCtx, execID, options)+}++func (a *dockerRPCTimeoutAPI) CopyToContainer(+ ctx context.Context, containerID string, options client.CopyToContainerOptions,+) (client.CopyToContainerResult, error) {+ return a.inner.CopyToContainer(ctx, containerID, options)+}++func (a *dockerRPCTimeoutAPI) CopyFromContainer(+ ctx context.Context, containerID string, options client.CopyFromContainerOptions,+) (client.CopyFromContainerResult, error) {+ return a.inner.CopyFromContainer(ctx, containerID, options)+}++func (a *dockerRPCTimeoutAPI) ContainerStatPath(+ ctx context.Context, containerID string, options client.ContainerStatPathOptions,+) (client.ContainerStatPathResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.ContainerStatPath(rpcCtx, containerID, options)+}++func (a *dockerRPCTimeoutAPI) ImageInspect(+ ctx context.Context, imageID string, opts ...client.ImageInspectOption,+) (client.ImageInspectResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.ImageInspect(rpcCtx, imageID, opts...)+}++func (a *dockerRPCTimeoutAPI) ImagePull(+ ctx context.Context, refStr string, options client.ImagePullOptions,+) (client.ImagePullResponse, error) {+ return a.inner.ImagePull(ctx, refStr, options)+}++func (a *dockerRPCTimeoutAPI) ImageList(+ ctx context.Context, options client.ImageListOptions,+) (client.ImageListResult, error) {+ rpcCtx, cancel := a.rpcCtx(ctx)+ defer cancel()+ return a.inner.ImageList(rpcCtx, options)+}++var _ dockerEngineAPI = (*dockerRPCTimeoutAPI)(nil)diff --git a/internal/sandbox/docker_template_catalog.go b/internal/sandbox/docker_template_catalog.gonew file mode 100644index 000000000..b6d963277--- /dev/null+++ b/internal/sandbox/docker_template_catalog.go@@ -0,0 +1,185 @@+// Images as templates for the docker backend.+//+// The settings wizard asks every backend the same two questions — which+// templates exist, and please make sure the standard one does. For Docker the+// answer is images on the daemon: an image is a pre-baked filesystem a sandbox+// starts from, which is exactly what a Cube or E2B template is.+//+// Two differences from the MicroVM backends shape this file:+//+// - A daemon holds every image its host ever pulled, most of which have+// nothing to do with sandboxes. Listing all of them would bury the one the+// admin needs, so the catalog only reports images that are recognisably+// sandbox templates.+// - Making the standard template exist means pulling, which can take minutes+// on a cold host. The pull therefore runs in the background and the+// template reports "building" until it lands, mirroring how the other+// backends report an in-flight template build.++package sandbox++import (+ "context"+ "fmt"+ "strings"+ "sync"+ "time"++ "github.com/moby/moby/client"+)++// dockerTemplateLabel marks an image as a WeKnora sandbox template. Images+// built by an operator can opt into the catalog by carrying it.+const dockerTemplateLabel = "com.weknora.sandbox.template"++// dockerImagePulls tracks background pulls per daemon endpoint and image, so a+// second refresh reports the in-flight pull instead of starting another one.+var dockerImagePulls = struct {+ mu sync.Mutex+ state map[string]*dockerPullState+}{state: make(map[string]*dockerPullState)}++type dockerPullState struct {+ started time.Time+ done bool+ err error+}++// ListTemplates reports the sandbox images available on this daemon.+func (c *DockerRemoteClient) ListTemplates(ctx context.Context) ([]RemoteTemplate, error) {+ listed, err := c.api.ImageList(ctx, client.ImageListOptions{})+ if err != nil {+ return nil, dockerError("ListTemplates", err)+ }++ templates := make([]RemoteTemplate, 0, len(listed.Items))+ configured := strings.TrimSpace(c.settings.Image)+ configuredPresent := false+ for _, image := range listed.Items {+ for _, tag := range image.RepoTags {+ if tag == "" || tag == "<none>:<none>" {+ continue+ }+ standard := isStandardTemplateImage(tag)+ if !standard && image.Labels[dockerTemplateLabel] != "true" && tag != configured {+ continue+ }+ if tag == configured {+ configuredPresent = true+ }+ templates = append(templates, RemoteTemplate{+ ID: tag,+ Name: tag,+ Status: "ready",+ Image: tag,+ Version: image.ID,+ Standard: standard,+ CreatedAt: time.Unix(image.Created, 0).UTC().Format(time.RFC3339),+ })+ }+ }++ // A configured image the daemon has not pulled yet is still the template+ // this config will use. Hiding it would tell the admin their own choice+ // does not exist, when all that is missing is a pull.+ if configured != "" && !configuredPresent {+ templates = append(templates, c.pendingTemplate(configured))+ }+ return templates, nil+}++// pendingTemplate describes an image that is not on the daemon yet, reporting+// any background pull's outcome.+func (c *DockerRemoteClient) pendingTemplate(image string) RemoteTemplate {+ template := RemoteTemplate{+ ID: image,+ Name: image,+ Image: image,+ Status: "missing",+ Standard: isStandardTemplateImage(image),+ }+ dockerImagePulls.mu.Lock()+ state, ok := dockerImagePulls.state[c.pullKey(image)]+ dockerImagePulls.mu.Unlock()+ switch {+ case !ok:+ return template+ case !state.done:+ template.Status = "building"+ case state.err != nil:+ template.Status = "failed"+ template.Error = state.err.Error()+ }+ return template+}++// EnsureStandardTemplate makes the configured image available on the daemon,+// pulling it in the background when it is missing.+func (c *DockerRemoteClient) EnsureStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {+ image := strings.TrimSpace(c.settings.Image)+ if image == "" {+ image = DefaultDockerImage+ }+ if _, err := c.api.ImageInspect(ctx, image); err == nil {+ return &RemoteTemplate{+ ID: image,+ Name: image,+ Image: image,+ Status: "ready",+ Standard: isStandardTemplateImage(image),+ }, nil+ }++ key := c.pullKey(image)+ dockerImagePulls.mu.Lock()+ state, running := dockerImagePulls.state[key]+ if running && !state.done {+ dockerImagePulls.mu.Unlock()+ pending := c.pendingTemplate(image)+ return &pending, nil+ }+ dockerImagePulls.state[key] = &dockerPullState{started: time.Now()}+ dockerImagePulls.mu.Unlock()++ // Detached from the request: a cold pull outlives the HTTP call that+ // asked for it, and cancelling mid-pull would leave a partial download+ // that the next refresh restarts from scratch.+ go c.pullInBackground(context.WithoutCancel(ctx), key, image)++ pending := c.pendingTemplate(image)+ return &pending, nil+}++func (c *DockerRemoteClient) pullInBackground(ctx context.Context, key, image string) {+ pullCtx, cancel := context.WithTimeout(ctx, dockerImagePullBudget)+ defer cancel()++ err := func() error {+ body, err := c.api.ImagePull(pullCtx, image, client.ImagePullOptions{})+ if err != nil {+ return err+ }+ return awaitImagePull(pullCtx, body)+ }()++ dockerImagePulls.mu.Lock()+ defer dockerImagePulls.mu.Unlock()+ if err != nil {+ dockerImagePulls.state[key] = &dockerPullState{done: true, err: err}+ return+ }+ // A finished pull leaves no state behind: the image is now visible to+ // ImageInspect, which is a better source of truth than our bookkeeping.+ delete(dockerImagePulls.state, key)+}++// dockerImagePullBudget bounds a background pull. Sandbox images are large but+// not unbounded; a pull still running after this either hit a stalled registry+// or a network the daemon cannot reach.+const dockerImagePullBudget = 30 * time.Minute++func (c *DockerRemoteClient) pullKey(image string) string {+ return fmt.Sprintf("%s|%s", c.settings.Endpoint.key(), image)+}++var _ RemoteTemplateCatalog = (*DockerRemoteClient)(nil)diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.goindex dfe417a36..861ca8b64 100644--- a/internal/sandbox/manager.go+++ b/internal/sandbox/manager.go@@ -47,26 +47,11 @@ func (m *DefaultManager) initializeSandbox(ctx context.Context) error {m.sandbox = &disabledSandbox{}return nil- case SandboxTypeDocker:- dockerSandbox := NewDockerSandbox(m.config)- if dockerSandbox.IsAvailable(ctx) {- m.sandbox = dockerSandbox- return nil- }-- // Fallback to local if enabled- if m.config.FallbackEnabled {- m.sandbox = NewLocalSandbox(m.config)- return nil- }-- return fmt.Errorf("docker is not available and fallback is disabled")-case SandboxTypeLocal:m.sandbox = NewLocalSandbox(m.config)return nil- case SandboxTypeCube, SandboxTypeE2B:+ case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker:// Session-scoped remote backends are only reachable through// SessionBoundManager, which owns the authoritative binding.// DefaultManager exposes stateless semantics that cannot preserve@@ -240,9 +225,9 @@ func (s *disabledSandbox) IsAvailable(ctx context.Context) bool {// NewManagerFromType creates a sandbox manager with the specified type.// dockerImage is optional; if empty, the default image is used.//-// Session-scoped remote backends (Cube, E2B) route to SessionBoundManager,-// which keeps one persistent MicroVM per SessionID; stateless backends-// (Docker, Local, Disabled) route to DefaultManager. Both satisfy Manager.+// Session-scoped backends (Cube, E2B, Docker) route to SessionBoundManager,+// which keeps one persistent sandbox per SessionID; the stateless ones (Local,+// Disabled) route to DefaultManager. Both satisfy Manager.func NewManagerFromType(sandboxType string, fallbackEnabled bool, dockerImage string) (Manager, error) {var sType SandboxTypeswitch sandboxType {@@ -267,31 +252,32 @@ func NewManagerFromType(sandboxType string, fallbackEnabled bool, dockerImage stconfig.DockerImage = dockerImage}+ var client RemoteSandboxClient+ var err errorswitch sType {case SandboxTypeCube:- client, err := NewCubeRemoteClient(config)- if err != nil {+ if client, err = NewCubeRemoteClient(config); err != nil {return nil, fmt.Errorf("sandbox: build Cube client: %w", err)}- return NewSessionBoundManager(SessionBoundManagerConfig{- Config: config,- Client: client,- Store: NewMemorySessionSandboxBindingStore(),- Checker: PermissiveSessionExistenceChecker{},- })case SandboxTypeE2B:- client, err := NewE2BRemoteClient(config)- if err != nil {+ if client, err = NewE2BRemoteClient(config); err != nil {return nil, fmt.Errorf("sandbox: build E2B client: %w", err)}- return NewSessionBoundManager(SessionBoundManagerConfig{- Config: config,- Client: client,- Store: NewMemorySessionSandboxBindingStore(),- Checker: PermissiveSessionExistenceChecker{},- })+ case SandboxTypeDocker:+ applyDockerRuntimeDefaults(config)+ if client, err = NewDockerRemoteClient(config); err != nil {+ return nil, fmt.Errorf("sandbox: build Docker client: %w", err)+ }+ }+ if client == nil {+ return NewManager(config)}- return NewManager(config)+ return NewSessionBoundManager(SessionBoundManagerConfig{+ Config: config,+ Client: client,+ Store: NewMemorySessionSandboxBindingStore(),+ Checker: PermissiveSessionExistenceChecker{},+ })}// NewDisabledManager creates a manager that rejects all execution requestsdiff --git a/internal/sandbox/remote_sandbox.go b/internal/sandbox/remote_sandbox.goindex a3dc1faf8..1c9a9598b 100644--- a/internal/sandbox/remote_sandbox.go+++ b/internal/sandbox/remote_sandbox.go@@ -9,7 +9,7 @@// - Ephemeral: one call to Execute allocates a sandbox, uploads the script,// runs it, then deletes the sandbox regardless of success. This gives// stateless-per-call semantics for callers without a SessionID, matching-// the Docker/Local backends.+// the Local backend.// - Persistent (session-bound): SessionBoundManager resolves the session's// RemoteSandboxHandle through the lifecycle coordinator and hands it to// RemoteSandbox.ExecuteOnHandle. The handle stays owned by the manager;@@ -23,6 +23,7 @@ import ("os""path""path/filepath"+ "strings""time")@@ -206,6 +207,26 @@ func remoteExecuteResult(result *RemoteExecResult, err error, duration time.Dura}}+// getInterpreter picks the interpreter for a script from its extension. The+// remote backends upload the script and then exec this interpreter against+// the uploaded path, so the choice must not depend on anything host-side.+func getInterpreter(scriptName string) string {+ switch strings.ToLower(filepath.Ext(scriptName)) {+ case ".py":+ return "python3"+ case ".sh", ".bash":+ return "bash"+ case ".js":+ return "node"+ case ".rb":+ return "ruby"+ case ".pl":+ return "perl"+ default:+ return "sh"+ }+}+// readScriptContent resolves the script bytes to upload into the sandbox.// It prefers cfg.ScriptContent (populated by the security validator) and// falls back to reading cfg.Script from local disk.diff --git a/internal/sandbox/runtime_defaults.go b/internal/sandbox/runtime_defaults.goindex 458ec782a..a5ae97b83 100644--- a/internal/sandbox/runtime_defaults.go+++ b/internal/sandbox/runtime_defaults.go@@ -14,6 +14,34 @@ func applyCubeRuntimeDefaults(cfg *Config) {}}+func applyDockerRuntimeDefaults(cfg *Config) {+ if cfg == nil {+ return+ }+ // The image is deliberately not defaulted here: it is this backend's+ // template, and a config that fails to name one must be reported as+ // incomplete rather than silently pointed at whatever image the release+ // happens to ship.+ if cfg.DockerHost == "" {+ cfg.DockerHost = DetectLocalDockerHost()+ }+ if cfg.DockerCPULimit <= 0 {+ cfg.DockerCPULimit = DefaultDockerCPULimit+ }+ if cfg.DockerMemoryBytes <= 0 {+ cfg.DockerMemoryBytes = DefaultDockerMemoryLimit+ }+ if cfg.DockerPidsLimit <= 0 {+ cfg.DockerPidsLimit = DefaultDockerPidsLimit+ }+ if cfg.DockerIdleTTL <= 0 {+ cfg.DockerIdleTTL = DefaultDockerIdleTTL+ }+ if cfg.DockerHTTPTimeout <= 0 {+ cfg.DockerHTTPTimeout = DefaultDockerHTTPTimeout+ }+}+func applyE2BRuntimeDefaults(cfg *Config) {if cfg == nil {returndiff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.goindex c0aa608b4..75e435fa1 100644--- a/internal/sandbox/sandbox.go+++ b/internal/sandbox/sandbox.go@@ -12,15 +12,17 @@ import (type SandboxType stringconst (- // SandboxTypeDocker uses Docker containers for isolation+ // SandboxTypeDocker runs each session in its own long-lived Docker+ // container, driven through the Docker Engine API. Like the MicroVM+ // backends it keeps session state between executions; unlike them it+ // shares the host kernel and lives on a single daemon.SandboxTypeDocker SandboxType = "docker"// SandboxTypeLocal uses local process with restrictionsSandboxTypeLocal SandboxType = "local"// SandboxTypeCube uses Tencent CubeSandbox (E2B-compatible) MicroVM for isolation.- // Unlike Docker/Local backends which are stateless per execution, Cube supports- // session-scoped persistent sandboxes: multiple executions bound to the same- // SessionID share the same MicroVM instance and preserve installed packages,- // created files, running services, etc.+ // Like Docker and E2B it keeps session-scoped persistent sandboxes: multiple+ // executions bound to the same SessionID share one instance and preserve+ // installed packages, created files, running services, etc.SandboxTypeCube SandboxType = "cube"// SandboxTypeE2B uses E2B's hosted MicroVM sandbox service.SandboxTypeE2B SandboxType = "e2b"@@ -29,8 +31,8 @@ const ()// IsNamedSandboxBackendType reports whether raw can be stored as a user-facing-// named sandbox backend. Remote backends are session-persistent; docker/local-// are stateless, but all four share the same workspace configuration surface.+// named sandbox backend. Cube, E2B and Docker are session-persistent; local+// is stateless. All four share the same workspace configuration surface.func IsNamedSandboxBackendType(raw string) bool {switch SandboxType(raw) {case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker, SandboxTypeLocal:@@ -173,9 +175,9 @@ type ExecuteConfig struct {ScriptContent string// SessionID scopes the execution to a per-session persistent sandbox.- // Currently only honoured by remote backends; Docker/Local backends ignore it.- // When empty, Cube falls back to an ephemeral (one-shot) sandbox that is- // created and torn down inside the single Execute call.+ // Honoured by every session-scoped backend (Cube, E2B, Docker); the Local+ // backend ignores it. When empty, those backends fall back to an ephemeral+ // (one-shot) sandbox created and torn down inside the single Execute call.SessionID string}@@ -220,9 +222,44 @@ type Config struct {// connection. Link-local addresses are blocked regardless.AllowPrivateEndpoints bool- // DockerImage is the Docker image to use (Docker sandbox only)+ // DockerImage is the image every sandbox container is created from. It+ // plays the same role as a Cube/E2B template ID.DockerImage string+ // DockerHost is the daemon endpoint, in DOCKER_HOST form+ // ("unix:///var/run/docker.sock", "tcp://10.0.0.5:2376"). Empty uses+ // DefaultDockerHost.+ DockerHost string++ // DockerTLSCertPath is a directory on the WeKnora host holding+ // ca.pem / cert.pem / key.pem. Required for a TCP daemon; unix sockets+ // do not use TLS.+ DockerTLSCertPath string++ // DockerCPULimit / DockerMemoryBytes / DockerPidsLimit cap one sandbox+ // container. Zero uses the built-in defaults.+ DockerCPULimit float64+ DockerMemoryBytes int64+ DockerPidsLimit int64++ // DockerNetworkMode is the Docker network every sandbox joins: "bridge" or+ // "none". host, container: and named networks are rejected (see+ // ValidateDockerNetworkMode). Empty means "bridge"; skills that install+ // packages need egress, so a sandbox is not isolated from the network by+ // default.+ DockerNetworkMode string++ // DockerRuntime selects an alternative OCI runtime, e.g. "runsc" for+ // gVisor. Empty uses the daemon's default runtime.+ DockerRuntime string++ // DockerIdleTTL is how long a container may go without executing anything+ // before the idle sweep reclaims it. Zero uses DefaultDockerIdleTTL.+ DockerIdleTTL time.Duration++ // DockerHTTPTimeout bounds each Engine API call. Zero uses the default.+ DockerHTTPTimeout time.Duration+// AllowedCommands is the default list of allowed commandsAllowedCommands []stringdiff --git a/internal/sandbox/session_binding.go b/internal/sandbox/session_binding.goindex c5c9beb14..53c344bfe 100644--- a/internal/sandbox/session_binding.go+++ b/internal/sandbox/session_binding.go@@ -270,5 +270,10 @@ func validateBindingMatch(}func isRemoteProvider(provider RemoteProvider) bool {- return provider == SandboxTypeCube || provider == SandboxTypeE2B+ switch provider {+ case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker:+ return true+ default:+ return false+ }}diff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.goindex 4d5ea1c4d..1e57032d4 100644--- a/internal/sandbox/session_manager.go+++ b/internal/sandbox/session_manager.go@@ -23,10 +23,8 @@// Every session-scoped capability (shell exec, file staging, session// filesystem inspection) then refuses to run on the host: those calls// require a real remote provider.-// - Sandboxes are never reaped from inside WeKnora. Idle-timeout / pause /-// kill is the provider's responsibility (Cube's on_timeout + Cube's-// sweeper; E2B's built-in TTL). Multi-instance deployments must not race-// on this decision.+// - Cube and E2B reap idle sandboxes themselves. Docker has no provider TTL,+// so that backend runs its own idle sweep against activity-marker mtimes.package sandboximport (@@ -162,6 +160,8 @@ func NewSessionBoundManager(deps SessionBoundManagerConfig) (*SessionBoundManageapplyCubeRuntimeDefaults(cfg)case SandboxTypeE2B:applyE2BRuntimeDefaults(cfg)+ case SandboxTypeDocker:+ applyDockerRuntimeDefaults(cfg)}// Build the provider-specific neutral create request using the@@ -818,6 +818,26 @@ func buildSessionCreateRequest(provider RemoteProvider, cfg *Config) (RemoteCrea},}, nil+ case SandboxTypeDocker:+ ttl := cfg.DockerIdleTTL+ if ttl <= 0 {+ ttl = DefaultDockerIdleTTL+ }+ return RemoteCreateRequest{+ TemplateID: cfg.DockerImage,+ EnvVars: envVars,+ Timeout: RemoteTimeoutPolicy{+ Mode: RemoteTimeoutExplicit,+ Value: ttl,+ // Docker's pause keeps the container's memory resident on the+ // host, so pausing an abandoned sandbox would reclaim nothing.+ // Idle containers are deleted; the lifecycle rebinds the+ // session exactly as it does for a provider-reaped sandbox.+ Action: RemoteOnTimeoutKill,+ AutoResume: false,+ },+ }, nil+default:return RemoteCreateRequest{}, fmt.Errorf("sandbox: unsupported remote provider %q for session create request",@@ -842,6 +862,11 @@ func effectiveHTTPTimeout(provider RemoteProvider, cfg *Config) time.Duration {return cfg.E2BHTTPTimeout}return DefaultE2BHTTPTimeout+ case SandboxTypeDocker:+ if cfg.DockerHTTPTimeout > 0 {+ return cfg.DockerHTTPTimeout+ }+ return DefaultDockerHTTPTimeoutdefault:return DefaultCubeHTTPTimeout}diff --git a/internal/sandbox/tenant_config.go b/internal/sandbox/tenant_config.goindex e1d1ac710..ca4f4f8bb 100644--- a/internal/sandbox/tenant_config.go+++ b/internal/sandbox/tenant_config.go@@ -92,6 +92,30 @@ func ResolveEffectiveConfig(if docker := tenantCfg.Docker; docker != nil {overrideString(&effective.DockerImage, docker.Image)+ if err := ValidateDockerHost(docker.Host, effective.AllowPrivateEndpoints); err != nil {+ return nil, err+ }+ if err := ValidateDockerRemoteTLS(docker.Host, docker.TLSCertPath); err != nil {+ return nil, err+ }+ if err := ValidateDockerNetworkMode(docker.NetworkMode); err != nil {+ return nil, err+ }+ overrideString(&effective.DockerHost, docker.Host)+ overrideString(&effective.DockerTLSCertPath, docker.TLSCertPath)+ overrideString(&effective.DockerNetworkMode, docker.NetworkMode)+ overrideString(&effective.DockerRuntime, docker.Runtime)+ if docker.CPULimit > 0 {+ effective.DockerCPULimit = docker.CPULimit+ }+ if docker.MemoryLimitMB > 0 {+ effective.DockerMemoryBytes = int64(docker.MemoryLimitMB) * 1024 * 1024+ }+ if docker.PidsLimit > 0 {+ effective.DockerPidsLimit = int64(docker.PidsLimit)+ }+ overrideSeconds(&effective.DockerIdleTTL, docker.IdleTTLSeconds)+ overrideSeconds(&effective.DockerHTTPTimeout, docker.HTTPTimeoutSec)}switch effective.Type {@@ -99,6 +123,8 @@ func ResolveEffectiveConfig(applyCubeRuntimeDefaults(&effective)case SandboxTypeE2B:applyE2BRuntimeDefaults(&effective)+ case SandboxTypeDocker:+ applyDockerRuntimeDefaults(&effective)}// Deliberately after the runtime defaults: TTLs and HTTP timeouts have// built-in fallbacks, endpoints and credentials do not.@@ -115,6 +141,15 @@ func ResolveEffectiveConfig(// "inherits nothing" would still have an exception to explain.func clearProviderFields(cfg *Config) {cfg.DockerImage = ""+ cfg.DockerHost = ""+ cfg.DockerTLSCertPath = ""+ cfg.DockerNetworkMode = ""+ cfg.DockerRuntime = ""+ cfg.DockerCPULimit = 0+ cfg.DockerMemoryBytes = 0+ cfg.DockerPidsLimit = 0+ cfg.DockerIdleTTL = 0+ cfg.DockerHTTPTimeout = 0cfg.CubeAPIURL = ""cfg.CubeProxyURL = ""cfg.CubeSandboxDomain = ""@@ -167,6 +202,10 @@ func EffectiveTemplateID(cfg *Config) string {return cfg.CubeTemplatecase SandboxTypeE2B:return cfg.E2BTemplate+ case SandboxTypeDocker:+ // The image is what a template ID is for the MicroVM backends: the+ // pre-baked filesystem a sandbox starts from.+ return cfg.DockerImagedefault:return ""}diff --git a/internal/sandbox/tenant_config_test.go b/internal/sandbox/tenant_config_test.goindex 630fb3326..ed7890c9e 100644--- a/internal/sandbox/tenant_config_test.go+++ b/internal/sandbox/tenant_config_test.go@@ -184,6 +184,45 @@ func TestResolveEffectiveConfigRejectsUnsafeCubeProxyURL(t *testing.T) {require.ErrorIs(t, err, ErrUnsafeOutboundURL)}+func TestResolveEffectiveConfigRejectsDockerHostNetwork(t *testing.T) {+ _, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{+ SandboxType: "docker",+ Docker: &types.DockerSandboxConfig{+ Image: "weknora:test",+ NetworkMode: "host",+ },+ }, DefaultConfig())+ require.Error(t, err)+}++// A blank host must come out of config resolution already pointing at the+// daemon the Docker CLI would use, because that resolved value is what the+// connectivity check dials. Leaving it empty here is what made the check fail+// on a Colima or Docker Desktop host, where /var/run/docker.sock is absent.+func TestResolveEffectiveConfigDetectsLocalDockerHostWhenBlank(t *testing.T) {+ t.Setenv("DOCKER_HOST", "unix:///tmp/from-env.sock")++ effective, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{+ SandboxType: "docker",+ Docker: &types.DockerSandboxConfig{Image: "weknora:test"},+ }, DefaultConfig())++ require.NoError(t, err)+ require.Equal(t, "unix:///tmp/from-env.sock", effective.DockerHost)+}++func TestResolveEffectiveConfigRejectsPlaintextDockerTCP(t *testing.T) {+ _, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{+ SandboxType: "docker",+ AllowPrivateEndpoints: true,+ Docker: &types.DockerSandboxConfig{+ Image: "weknora:test",+ Host: "tcp://10.0.0.5:2376",+ },+ }, DefaultConfig())+ require.Error(t, err)+}+func TestEffectiveTemplateIDPerProvider(t *testing.T) {require.Equal(t, "e2b-tpl", EffectiveTemplateID(&Config{Type: SandboxTypeE2B, E2BTemplate: "e2b-tpl", CubeTemplate: "cube-tpl",diff --git a/internal/sandbox/tenant_resolver.go b/internal/sandbox/tenant_resolver.goindex 69d2ed8ce..f4e4f55ed 100644--- a/internal/sandbox/tenant_resolver.go+++ b/internal/sandbox/tenant_resolver.go@@ -179,7 +179,7 @@ func (r *tenantSandboxResolver) Resolve(switch effective.Type {case SandboxTypeDisabled:return NewDisabledManager(), nil- case SandboxTypeCube, SandboxTypeE2B:+ case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker:client, err := r.buildClient(effective)if err != nil {return nil, err@@ -192,11 +192,10 @@ func (r *tenantSandboxResolver) Resolve(SkipHealthProbe: true,ConfigID: configID,})- case SandboxTypeDocker, SandboxTypeLocal:- // Stateless backends still come from the selected workspace row. Docker- // fallback is deliberately disabled: silently running a configured- // container workload on the application host would cross an isolation- // boundary.+ case SandboxTypeLocal:+ // The local backend runs scripts on the application host, so falling+ // back to it silently is never right: a workspace that selected it did+ // so knowingly, and one that selected something else must fail loudly.effective.FallbackEnabled = falsereturn NewManager(effective)default:@@ -221,6 +220,12 @@ func (r *tenantSandboxResolver) buildClient(cfg *Config) (RemoteSandboxClient, ereturn NewE2BRemoteClientWithPool(cfg, r.privateGatewayTransports)}return NewE2BRemoteClientWithPool(cfg, r.gatewayTransports)+ case SandboxTypeDocker:+ // The docker client keeps its own pooled connection per daemon+ // endpoint rather than using the transports above: the Engine API is+ // reached over a unix socket as often as over TCP. It installs the+ // same guarded dialer for TCP endpoints (see newDockerEngineClient).+ return NewDockerRemoteClient(cfg)default:return nil, fmt.Errorf("sandbox: provider %q has no remote client", cfg.Type)}@@ -248,6 +253,8 @@ func NewRemoteClientForCheck(cfg *Config) (RemoteSandboxClient, error) {// routing the resolved manager will use.return NewE2BRemoteClientWithPool(cfg, NewSandboxGatewayTransportPoolWithPolicy(nil,OutboundURLPolicy{AllowPrivate: cfg.AllowPrivateEndpoints}))+ case SandboxTypeDocker:+ return NewDockerRemoteClientForCheck(cfg)default:return nil, fmt.Errorf("sandbox: provider %q cannot be probed", cfg.Type)}diff --git a/internal/sandbox/tenant_resolver_test.go b/internal/sandbox/tenant_resolver_test.goindex fce84ecdb..8b17aab5b 100644--- a/internal/sandbox/tenant_resolver_test.go+++ b/internal/sandbox/tenant_resolver_test.go@@ -101,6 +101,51 @@ func TestResolveBuildsRemoteManagerWithoutHealthProbe(t *testing.T) {require.Equal(t, SandboxTypeE2B, mgr.GetType())}+// Docker is a session-scoped backend like the MicroVM ones: it must resolve to+// a SessionBoundManager that advertises shell_exec and the session file store,+// not to the stateless DefaultManager it used to get.+func TestResolveBuildsSessionBoundManagerForDocker(t *testing.T) {+ resolver, fallback := newTestResolver(t, &stubTenantConfigLoader{+ result: ResolvedTenantSandboxConfig{+ Config: &types.TenantSandboxConfig{+ SandboxType: "docker",+ Docker: &types.DockerSandboxConfig{+ Image: "wechatopenai/weknora-sandbox:test",+ },+ },+ Found: true,+ },+ })++ mgr, err := resolver.Resolve(context.Background(), 42, "cfg-docker")++ require.NoError(t, err)+ require.NotSame(t, fallback, mgr)+ require.Equal(t, SandboxTypeDocker, mgr.GetType())++ capabilities, ok := mgr.(SessionCapabilityProvider)+ require.True(t, ok, "docker must expose session-scoped capabilities")+ require.NotNil(t, capabilities.SessionShellExecutor())+ require.NotNil(t, capabilities.SessionFileStore())+}++// The image is this backend's template. Without it there is nothing to create a+// sandbox from, so the config must be refused up front rather than at the first+// execution.+func TestResolveRefusesDockerConfigWithoutImage(t *testing.T) {+ resolver, _ := newTestResolver(t, &stubTenantConfigLoader{+ result: ResolvedTenantSandboxConfig{+ Config: &types.TenantSandboxConfig{SandboxType: "docker"},+ Found: true,+ },+ })++ mgr, err := resolver.Resolve(context.Background(), 42, "cfg-docker")++ require.Nil(t, mgr)+ require.ErrorIs(t, err, ErrSandboxConfigIncomplete)+}+func TestResolveBuildsLocalManagerFromWorkspaceConfig(t *testing.T) {resolver, fallback := newTestResolver(t, &stubTenantConfigLoader{result: ResolvedTenantSandboxConfig{diff --git a/internal/types/tenant.go b/internal/types/tenant.goindex cb17e9d9d..a312bacf1 100644--- a/internal/types/tenant.go+++ b/internal/types/tenant.go@@ -706,8 +706,54 @@ type E2BSandboxConfig struct {E2BSandboxTTLSeconds int `json:"e2b_sandbox_ttl_seconds,omitempty"`}+// DockerSandboxConfig addresses one Docker daemon. Image is required and plays+// the role a template ID plays for the MicroVM backends: every session+// container is created from it.+//+// The daemon endpoint is deliberately the only connection field, and TLS+// material is referenced by path rather than stored here. Client certificates+// are deployment infrastructure mounted onto the WeKnora host; keeping them+// out of the database keeps them out of backups, exports and API responses.type DockerSandboxConfig struct {Image string `json:"image,omitempty"`++ // Host is the daemon endpoint in DOCKER_HOST form. Empty means the local+ // unix socket.+ Host string `json:"host,omitempty"`++ // TLSCertPath is a directory on the WeKnora host containing ca.pem,+ // cert.pem and key.pem. Required when Host is a TCP endpoint.+ TLSCertPath string `json:"tls_cert_path,omitempty"`++ // CPULimit is the number of CPU cores one sandbox may use. 0 uses the+ // built-in default.+ CPULimit float64 `json:"cpu_limit,omitempty"`++ // MemoryLimitMB caps one sandbox's memory. 0 uses the built-in default.+ MemoryLimitMB int `json:"memory_limit_mb,omitempty"`++ // PidsLimit caps how many processes one sandbox may run. 0 uses the+ // built-in default.+ PidsLimit int `json:"pids_limit,omitempty"`++ // NetworkMode is the Docker network sandboxes join: "bridge" (default) or+ // "none" for no egress. Nothing else is accepted — host and container:+ // modes share another namespace outright, and a named network is usually+ // the deployment's own compose network, which would put the sandbox next+ // to Postgres and Redis.+ NetworkMode string `json:"network_mode,omitempty"`++ // Runtime selects an alternative OCI runtime such as "runsc" (gVisor).+ // Empty uses the daemon default.+ Runtime string `json:"runtime,omitempty"`++ // IdleTTLSeconds is how long a session container may go unused before it+ // is reclaimed. The daemon has no idle timeout of its own, so this is what+ // stops an abandoned session from pinning host memory indefinitely.+ IdleTTLSeconds int `json:"idle_ttl_seconds,omitempty"`++ // HTTPTimeoutSec bounds each Engine API call. 0 uses the built-in default.+ HTTPTimeoutSec int `json:"http_timeout_sec,omitempty"`}// VolumeMountConfig configures a shared volume mount into every sandboxdiff --git a/scripts/git-hooks/common.sh b/scripts/git-hooks/common.shindex 8db8a60ed..e63704896 100755--- a/scripts/git-hooks/common.sh+++ b/scripts/git-hooks/common.sh@@ -133,11 +133,16 @@ check_gofmt_files() {collect_go_packages_from_files() {local -a files=("$@")- local f dir pkg+ local f dir pkg module root_modulelocal -a pkgs=()+ # Nested modules (docs/poc, cli, client) are not testable from the root+ # module, so only keep packages that belong to it.+ root_module="$(cd "$ROOT" && go list -m 2>/dev/null || true)"for f in "${files[@]}"; do[[ "$f" == *.go ]] || continuedir="$(dirname "$f")"+ module="$(cd "$ROOT/$dir" && go list -m 2>/dev/null)" || continue+ [[ "$module" == "$root_module" ]] || continuepkg="$(cd "$ROOT/$dir" && go list . 2>/dev/null)" || continuepkgs+=("$pkg")donediff --git a/website-docs/01-getting-started/01-introduction.md b/website-docs/01-getting-started/01-introduction.mdindex ff7a7c67d..d8ee8ae1d 100644--- a/website-docs/01-getting-started/01-introduction.md+++ b/website-docs/01-getting-started/01-introduction.md@@ -123,7 +123,7 @@ flowchart TB| docreader | Python / gRPC | `docreader/` | 50051(仅容器网络内) | 文档解析、OCR、网页抓取、图片提取 || postgres | ParadeDB(PostgreSQL 17 + BM25/向量扩展) | 镜像 `paradedb/paradedb` | 5432 | 主数据库 + 默认混合检索引擎(`RETRIEVE_DRIVER=postgres`) || redis | Redis 7 | — | 6379 | 流管理(SSE 恢复)、Asynq 任务队列 |-| sandbox | Python 3.11 + Node 20 | `docker/Dockerfile.sandbox` | — | Agent Skills 脚本的一次性沙箱容器 |+| sandbox | Python 3.11 + Node 20 | `docker/Dockerfile.sandbox` | — | Agent Skills 的会话沙箱容器镜像 || 可选:qdrant / milvus / weaviate / doris | — | `docker-compose.yml` profiles | 6334 / 19530 / 9035 / 9030 | 替代或叠加的向量检索引擎(`RETRIEVE_DRIVER`) || 可选:opensearch | — | 仅 `docker-compose.dev.yml` | 9200 | 开发环境用;生产需自备集群 || 可选:elasticsearch / tencent_vectordb | — | 不随 compose 提供 | — | 代码支持,但需自行部署后用 `RETRIEVE_DRIVER` 接入 |diff --git a/website-docs/01-getting-started/02-installation.md b/website-docs/01-getting-started/02-installation.mdindex 64097c058..3f9d877de 100644--- a/website-docs/01-getting-started/02-installation.md+++ b/website-docs/01-getting-started/02-installation.md@@ -130,7 +130,7 @@ make dev-logs / dev-status / dev-stop / dev-restart| `docker/Dockerfile.app` | `wechatopenai/weknora-app` | 两阶段:`golang:1.26-bookworm` 编译(`make build-prod`,默认 `WITH_ANYDOC=1` 链接进程内 office 解析引擎,注入版本信息,预下载 DuckDB 扩展 `cmd/download/duckdb`)→ `debian:12.12-slim` 运行层(含 `migrate` 迁移工具、python3/node/uvx(供 stdio MCP 与 Skills 使用)、ffmpeg(ASR)、gosu 降权)。入口 `scripts/docker-entrypoint.sh`:修复挂载目录属主、把 `_builtin` 内置 Skills 合并回 `skills/preloaded`,再以 appuser 运行 `./WeKnora`。`EXPOSE 8080` || `docker/Dockerfile.docreader` | `wechatopenai/weknora-docreader` | Python 3.10 + uv 依赖锁定;生成 protobuf;运行层安装 LibreOffice、OpenJDK 17、antiword、Playwright(webkit)与 `grpc_health_probe`。轻量版不含 PaddleOCR。`EXPOSE 50051`。支持 `APT_MIRROR` 构建参数 || `docker/Dockerfile.odl-hybrid` | `weknora-odl-hybrid:local` | 安装 `opendataloader-pdf[hybrid]`(Docling),监听 5002,默认 `--no-ocr`;仅本地构建不发布 |-| `docker/Dockerfile.sandbox` | `wechatopenai/weknora-sandbox` | Python 3.11-slim + Node 20 + jq,非 root 用户 `sandbox`(UID 1000),供 Agent Skills 脚本在一次性容器中执行 |+| `docker/Dockerfile.sandbox` | `wechatopenai/weknora-sandbox` | Python 3.11-slim + Node 20 + jq,非 root 用户 `user`(UID 1000),Agent Skills 的会话沙箱镜像 || `frontend/Dockerfile` | `wechatopenai/weknora-ui` | 需先在宿主机执行 `./scripts/build_frontend_dist.sh` 产出 `dist/`;基底为按 digest 固定的 `nginx:1.30.3-alpine`(兼容 CentOS 7 旧内核) |从源码构建全部镜像: